Skip to content

Every analytics tool wants a subscription. And your data. I built Twiligent instead. YouTube stats. Instagram stats. One dashboard. Runs locally on your machine.

feat(mcp): sign confirmation tokens for irreversible tools

spacesdrive8a4b84414321
diff --git a/backend/lib/mcp/confirmation.ts b/backend/lib/mcp/confirmation.ts
new file mode 100644
index 0000000..1251fe0
--- /dev/null
+++ b/backend/lib/mcp/confirmation.ts
@@ -0,0 +1,64 @@
+import { toBase64Url } from './accessToken.ts';
+
+// an irreversible tool runs only when the second call carries a token from the first: signed, bound to the person,
+// the tool and the exact arguments, and short-lived, so text a model reads in a comment cannot approve an action
+export const CONFIRMATION_TTL_MS = 5 * 60 * 1000;
+
+export interface ConfirmationSubject {
+ userId: string;
+ tool: string;
+ args: Record<string, unknown>;
+}
+
+// the same arguments in any key order give the same text; the token field itself is left out
+export function canonicalArgs(args: Record<string, unknown>): string {
+ const sort = (value: unknown): unknown => {
+ if (Array.isArray(value)) return value.map(sort);
+ if (typeof value !== 'object' || value === null) return value;
+ return Object.fromEntries(Object.keys(value).sort().map(key => [key, sort((value as Record<string, unknown>)[key])]));
+ };
+ const { confirmationToken: _token, ...rest } = args;
+ return JSON.stringify(sort(rest));
+}
+
+async function signingKey(secret: string, usage: 'sign' | 'verify'): Promise<CryptoKey> {
+ const material = await crypto.subtle.importKey('raw', new TextEncoder().encode(secret), 'HKDF', false, ['deriveKey']);
+ // derived for this one purpose, so the same Worker secret can also encrypt stored tokens without the keys overlapping
+ return crypto.subtle.deriveKey(
+ { name: 'HKDF', hash: 'SHA-256', salt: new Uint8Array(0), info: new TextEncoder().encode('twiligent mcp confirmation') },
+ material,
+ { name: 'HMAC', hash: 'SHA-256' },
+ false,
+ [usage],
+ );
+}
+
+function payloadOf(subject: ConfirmationSubject, expiresAt: number): string {
+ return `${subject.userId}\n${subject.tool}\n${canonicalArgs(subject.args)}\n${expiresAt}`;
+}
+
+export async function createConfirmation(subject: ConfirmationSubject, secret: string, now = Date.now()): Promise<string> {
+ const expiresAt = now + CONFIRMATION_TTL_MS;
+ const signature = await crypto.subtle.sign('HMAC', await signingKey(secret, 'sign'), new TextEncoder().encode(payloadOf(subject, expiresAt)));
+ return `${expiresAt}.${toBase64Url(new Uint8Array(signature))}`;
+}
+
+function fromBase64Url(text: string): Uint8Array<ArrayBuffer> | null {
+ try {
+ return Uint8Array.from(atob(text.replace(/-/g, '+').replace(/_/g, '/')), char => char.charCodeAt(0));
+ } catch {
+ // a tampered token is not valid base64
+ return null;
+ }
+}
+
+// subtle.verify compares in constant time; a token for other arguments, another tool or another person fails here
+export async function verifyConfirmation(token: unknown, subject: ConfirmationSubject, secret: string, now = Date.now()): Promise<boolean> {
+ if (typeof token !== 'string') return false;
+ const [expires, signature, extra] = token.split('.');
+ const expiresAt = Number(expires);
+ if (extra !== undefined || !signature || !Number.isInteger(expiresAt) || expiresAt < now || expiresAt > now + CONFIRMATION_TTL_MS) return false;
+ const bytes = fromBase64Url(signature);
+ if (!bytes) return false;
+ return crypto.subtle.verify('HMAC', await signingKey(secret, 'verify'), bytes, new TextEncoder().encode(payloadOf(subject, expiresAt)));
+}
diff --git a/backend/tests/lib/mcp/confirmation.test.ts b/backend/tests/lib/mcp/confirmation.test.ts
new file mode 100644
index 0000000..876585c
--- /dev/null
+++ b/backend/tests/lib/mcp/confirmation.test.ts
@@ -0,0 +1,35 @@
+import { test } from 'node:test';
+import assert from 'node:assert/strict';
+import { CONFIRMATION_TTL_MS, canonicalArgs, createConfirmation, verifyConfirmation } from '../../../lib/mcp/confirmation.ts';
+
+const SECRET = 'test-secret-with-enough-length-0123456789';
+const NOW = 1_760_000_000_000;
+const SUBJECT = { userId: 'user-1', tool: 'cancel_scheduled_post', args: { postId: 'p1', reason: 'moved' } };
+
+test('a token confirms the same person, tool and arguments, in any key order', async () => {
+ const token = await createConfirmation(SUBJECT, SECRET, NOW);
+ const reordered = { ...SUBJECT, args: { reason: 'moved', postId: 'p1', confirmationToken: token } };
+ assert.equal(await verifyConfirmation(token, reordered, SECRET, NOW + 1000), true);
+});
+
+test('a token does not confirm other arguments, another tool, another person or another secret', async () => {
+ const token = await createConfirmation(SUBJECT, SECRET, NOW);
+ assert.equal(await verifyConfirmation(token, { ...SUBJECT, args: { postId: 'p2', reason: 'moved' } }, SECRET, NOW), false);
+ assert.equal(await verifyConfirmation(token, { ...SUBJECT, tool: 'delete_media' }, SECRET, NOW), false);
+ assert.equal(await verifyConfirmation(token, { ...SUBJECT, userId: 'user-2' }, SECRET, NOW), false);
+ assert.equal(await verifyConfirmation(token, SUBJECT, 'another-secret-with-enough-length-000000', NOW), false);
+});
+
+test('a token stops working after five minutes, and a tampered or missing one never works', async () => {
+ const token = await createConfirmation(SUBJECT, SECRET, NOW);
+ assert.equal(await verifyConfirmation(token, SUBJECT, SECRET, NOW + CONFIRMATION_TTL_MS + 1), false);
+ const [expires, signature] = token.split('.');
+ assert.equal(await verifyConfirmation(`${Number(expires) + 60_000}.${signature}`, SUBJECT, SECRET, NOW), false);
+ for (const bad of [undefined, '', 'nonsense', `${expires}.***`, `${token}.extra`]) {
+ assert.equal(await verifyConfirmation(bad, SUBJECT, SECRET, NOW), false);
+ }
+});
+
+test('nested arguments are compared by value, not by key order', () => {
+ assert.equal(canonicalArgs({ b: { y: 1, x: [2, { d: 1, c: 0 }] }, a: 1 }), canonicalArgs({ a: 1, b: { x: [2, { c: 0, d: 1 }], y: 1 } }));
+});