173 lines · 13.1 KB · TypeScriptRaw
/** * Token scopes (src/token_scopes.ts; plan assets/design/shared/TOKEN-SCOPES.md; ROUTES-AUDIT findings 2, 3, 5, 8, 9, * 10): a per-account switch, off by default, that keeps a Cotton MCP token to /mcp, and a hand-pasted one to minting and * revoking narrower tokens. Every account, token and row is invented. */import { describe, expect, it } from "vitest";import { ADMIN, DATABASE_ID, http, mint, OWNER_PHONE, personalObject, put, tool } from "./personal.ts";type Doc = Record<string, unknown>;const as = (token: string) => ({ authorization: `Bearer ${token}` });async function act(slug: string, token: string, name: string, args: Doc): Promise<{ status: number; body: Doc }> { return http<Doc>(slug, "POST", "/v1/act", { act: name, args }, as(token));}/** A connector's token: an owner token told apart by its refresh row, as src/oauth.ts writes one. */async function connector(slug: string, credential: string): Promise<string> { const minted = await http<{ token: string; made: { id: string } }>(slug, "POST", "/v1/act", { act: "mint_token", args: { name: "connector stand-in", scopes: ["owner"], allow: "all" } }, as(credential)); expect(minted.status, JSON.stringify(minted.body)).toBe(200); await put(slug, [{ table: "oauth_refresh", data: { client_id: "client-x", token: minted.body.made.id, scope: "owner", expires_at: "2099-01-01T00:00:00.000Z" } }]); return minted.body.token;}interface Gate { ready: boolean; on: Doc | null; holders: { token_id: string; name: string; connector: boolean; verdict: string; says: string; routes: { route: string; kept: boolean }[] }[];}/** RULE (coordinator, 23 Nov 2026; ROUTES-AUDIT 2, 3, 5, 8, 9, 10): off, nothing changes; the switch is the admin's, and refuses while a token in use would lose a route it uses; on, a token speaks at /mcp, mints and revokes narrower tokens only when pasted by hand, never writes the account's keys, and /v1/admin takes the admin token alone. */describe("token scopes", () => { it("changes nothing while off, and its gate names each token by the routes it would lose", async () => { const slug = "token-scopes-gate"; const { credential, owner } = await personalObject(slug); const wire = await connector(slug, credential); // Off: the pasted owner token is the admin and the owner, as before. expect((await http(slug, "GET", "/v1/admin/row-counts", undefined, as(owner))).status).toBe(200); expect((await http(slug, "GET", "/v1/sync?since=0", undefined, as(owner))).status).toBe(200); // ADMIN KEYS 1b: the one mint a pasted owner key makes is a lane token, switch off or on. expect((await act(slug, owner, "mint_token", { name: "lane x", scopes: ["read", "lane:x"], expires_in_days: 7 })).status).toBe(200); expect((await http(slug, "GET", "/v1/sync?since=0", undefined, as(wire))).status).toBe(200); // The switch is the admin's alone. expect((await http(slug, "GET", "/v1/admin/token-scopes", undefined, as(owner))).status).toBe(403); const gate = await http<Gate>(slug, "GET", "/v1/admin/token-scopes", undefined, ADMIN); expect(gate.status, JSON.stringify(gate.body)).toBe(200); expect(gate.body.on).toBeNull(); const pasted = gate.body.holders.find((h) => h.name === "coordinator owner")!; expect(pasted.verdict).toBe("would_lose"); expect(pasted.routes.map((r) => [r.route, r.kept]), JSON.stringify(pasted.routes)).toEqual([["act mint_token", true], ["GET /v1/admin/row-counts", false], ["GET /v1/admin/token-scopes", false], ["GET /v1/sync", false]]); const wired = gate.body.holders.find((h) => h.connector)!; expect(wired.routes.map((r) => r.route)).toEqual(["GET /v1/sync"]); const refused = await http<Doc>(slug, "POST", "/v1/admin/token-scopes", { on: true }, ADMIN); expect(refused.status).toBe(409); expect(String(refused.body.message)).toMatch(/coordinator owner would lose GET \/v1\/admin\/row-counts, .*GET \/v1\/sync/); const on = await http<Gate>(slug, "POST", "/v1/admin/token-scopes", { on: true, excuse: [pasted.token_id, wired.token_id] }, ADMIN); expect(on.status, JSON.stringify(on.body)).toBe(200); expect(on.body.on).toMatchObject({ by: "admin" }); }, 180_000); it("on: a token speaks at /mcp, a pasted one revokes but mints nothing, and the admin's routes take the admin token", async () => { const slug = "token-scopes-on"; const { credential, owner } = await personalObject(slug); const wire = await connector(slug, credential); const gate = await http<Gate>(slug, "GET", "/v1/admin/token-scopes", undefined, ADMIN); const switched = await http(slug, "POST", "/v1/admin/token-scopes", { on: true, excuse: gate.body.holders.map((h) => h.token_id) }, ADMIN); expect(switched.status, JSON.stringify(switched.body)).toBe(200); // Finding 2: /v1/admin takes the admin token alone. for (const token of [owner, wire]) { expect((await http(slug, "GET", "/v1/admin/row-counts", undefined, as(token))).status).toBe(403); expect((await http(slug, "POST", "/v1/admin/reset", {}, as(token))).status).toBe(403); expect((await http(slug, "PUT", "/v1/admin/business", { owner_phone: "+919000000123" }, as(token))).status).toBe(403); } expect((await http(slug, "GET", "/v1/admin/row-counts", undefined, ADMIN)).status).toBe(200); // Findings 3, 5, 8, 9: no device route but mint and revoke, and those only for a token pasted by hand. for (const [method, path] of [["GET", "/v1/sync?since=0"], ["GET", "/v1/held"], ["GET", "/v1/me"], ["POST", "/v1/mail/send"], ["POST", "/v1/google/events"], ["DELETE", `/v1/media/${DATABASE_ID}/photos/x?prefix=1`]] as const) { const got = await http<Doc>(slug, method, path, method === "GET" || method === "DELETE" ? undefined : {}, as(owner)); expect([got.status, got.body.code], `${method} ${path}`).toEqual([403, "token_scopes"]); } expect((await act(slug, owner, "create", { table: "note", data: { title: "Invented" } })).body.code).toBe("token_scopes"); // ADMIN KEYS 1b: no key mints, pasted or a connector's; the owner's phone mints, and a pasted key revokes. expect((await act(slug, wire, "mint_token", { name: "x", scopes: ["read"], expires_in_days: 7 })).body.code).toBe("access_act"); // A connector mints nothing, a lane token least of all; a pasted owner key mints a lane token alone. expect((await act(slug, wire, "mint_token", { name: "lane w", scopes: ["read", "lane:w"], expires_in_days: 7 })).body.code).toBe("access_act"); expect((await act(slug, owner, "mint_token", { name: "y", scopes: ["read"], expires_in_days: 7 })).body.code).toBe("access_act"); const lane = await act(slug, owner, "mint_token", { name: "lane y", scopes: ["read", "lane:y"], expires_in_days: 7 }); expect(lane.status, JSON.stringify(lane.body)).toBe(200); expect((await act(slug, owner, "revoke_token", { id: (lane.body.made as { id: string }).id })).status).toBe(200); // At /mcp: tools answer as before; no key mints, and no token writes the keys' tables. expect((await tool(slug, wire, "storage_summary", {})).isError).toBe(false); for (const token of [wire, owner]) { const minted = await tool(slug, token, "run_act", { act: "mint_token", args: { name: "z", scopes: ["read"], expires_in_days: 7 } }); expect([minted.isError, minted.content[0]!.text]).toEqual([true, expect.stringMatching(/changes who may do what/)]); } const key = await tool(slug, owner, "run_act", { act: "delete", args: { table: "vault_key", id: "any" } }); // ADMIN KEYS 1b: refused before the scopes' own check, by the access rule (switch on or off). expect(key.content[0]!.text).toMatch(/vault_key holds who may do what/); // The owner's phones are untouched. expect((await http(slug, "GET", "/v1/sync?since=0", undefined, as(credential))).status).toBe(200); expect((await http(slug, "GET", "/v1/me", undefined, as(credential))).status).toBe(200); // Off again: as before. expect((await http(slug, "POST", "/v1/admin/token-scopes", { on: false }, ADMIN)).status).toBe(200); expect((await http(slug, "GET", "/v1/admin/row-counts", undefined, as(owner))).status).toBe(200); expect((await http(slug, "POST", "/v1/admin/token-scopes", { on: true, excuse: gate.body.holders.map((h) => h.token_id) }, ADMIN)).status).toBe(200); // Finding 10 and the wipes: an import plants no key; reset and erase name the database. const planted = await http<Doc>(slug, "POST", "/v1/admin/import", { rows: [{ table: "vault_key", data: { device: "d" } }] }, ADMIN); expect(planted.body.code).toBe("token_scopes"); expect((await http<Doc>(slug, "POST", "/v1/admin/reset", {}, ADMIN)).body.code).toBe("confirm_database"); expect((await http(slug, "POST", "/v1/admin/reset", { confirm: DATABASE_ID }, ADMIN)).status).toBe(200); }, 180_000); // RULE (coordinator, 24 Nov 2026; TOKEN-SCOPES-GO-LIVE.md): what Cotton Fetch, Films and the by-hand scripts ask // of /v1 they ask with the Mac's own device credential, which the switch leaves whole; and the gate, read since // the move, shows the token they held fine once it speaks only at /mcp. it("on: the Mac's device credential reaches every route Fetch and Films use, and the gate since the move shows their old token fine", async () => { const slug = "token-scopes-mac"; const { credential } = await personalObject(slug); // The importers' owner token, as Fetch held it: its routes before the move. const fetchToken = await mint(slug, credential, "invented-mac fetch", ["owner"]); expect((await http(slug, "GET", "/v1/fetch/pending?machine=invented-mac", undefined, as(fetchToken))).status).not.toBe(403); const before = await http<Gate>(slug, "GET", "/v1/admin/token-scopes", undefined, ADMIN); expect(before.body.holders.find((h) => h.name === "invented-mac fetch")!.verdict).toBe("would_lose"); await new Promise((done) => setTimeout(done, 5)); const moved = new Date().toISOString(); // After the move: the token at /mcp only. expect((await tool(slug, fetchToken, "storage_summary", {})).isError).toBe(false); const since = await http<Gate>(slug, "GET", `/v1/admin/token-scopes?since=${encodeURIComponent(moved)}`, undefined, ADMIN); const held = since.body.holders.find((h) => h.name === "invented-mac fetch")!; expect([held.verdict, held.routes.map((r) => r.route)], JSON.stringify(held)).toEqual(["fine", []]); expect((await http(slug, "GET", "/v1/admin/token-scopes?since=yesterday-ish", undefined, ADMIN)).status).toBe(400); const pasted = since.body.holders.filter((h) => h.verdict === "would_lose").map((h) => h.token_id); const on = await http(slug, "POST", "/v1/admin/token-scopes", { on: true, since: moved, excuse: pasted }, ADMIN); expect(on.status, JSON.stringify(on.body)).toBe(200); // The Mac signs in as a device of the owner's, as seal-device does. const code = await http<{ challenge_id: string }>(slug, "POST", "/v1/code", { phone: OWNER_PHONE, device_id: "invented-mac" }); const mac = (await http<{ credential: string }>(slug, "POST", "/v1/sign-in", { challenge_id: code.body.challenge_id, code: "123456", device_id: "invented-mac" })).body.credential; const routes: [string, string, Doc | undefined][] = [ ["GET", "/v1/definitions", undefined], ["GET", "/v1/fetch/pending?machine=invented-mac", undefined], ["GET", "/v1/fetch/again", undefined], ["GET", "/v1/films/pending", undefined], ["GET", "/v1/films/subtitles/asked", undefined], ["GET", "/v1/films/find?id=abcd", undefined], ["POST", "/v1/media/missing", { keys: [`${DATABASE_ID}/films/invented/video/seg00001.m4s`] }], ]; for (const [method, path, body] of routes) { const got = await http<Doc>(slug, method, path, body, as(mac)); expect([got.status, got.body.code], `${method} ${path}: ${JSON.stringify(got.body)}`).not.toContainEqual(403); // And the same route refused to the token, as the switch means. // (The definitions are served to any caller.) if (path !== "/v1/definitions") expect((await http<Doc>(slug, method, path, body, as(fetchToken))).body.code, `${method} ${path} by the token`).toBe("token_scopes"); } // The named acts the importers and the by-hand scripts send: never refused for being a device's. for (const [name, args] of [["fetch_claim", { fetch: "00000000-0000-4000-8000-00000000f001", machine: "invented-mac" }], ["fetch_again", { fetch: "00000000-0000-4000-8000-00000000f001" }], ["film_converted", { table: "film", id: "00000000-0000-4000-8000-00000000f002", file: "k" }], ["reshape_films", {}], ["drop_old_music", {}]] as const) { const got = await act(slug, mac, name, args); expect([got.status, got.body.code], `${name}: ${JSON.stringify(got.body)}`).not.toContainEqual("token_scopes"); expect(got.status, `${name}: ${JSON.stringify(got.body)}`).not.toBe(403); expect((await act(slug, fetchToken, name, args)).body.code, `${name} by the token`).toBe("token_scopes"); } // A sealed table's row in the clear is refused to the device by name: so the importers write it sealed (seal-files serve). const clear = await act(slug, mac, "create", { table: "book", data: { title: "Invented book" } }); expect(clear.body.code, JSON.stringify(clear.body)).toBe("sealed_in_clear"); }, 180_000);});