/** * TOKEN SCOPES (coordinator, 23 Nov 2026; plan assets/design/shared/TOKEN-SCOPES.md; findings 2, 3, 5, 8, 9 and 10 of * assets/design/shared/ROUTES-AUDIT.md). * * A Cotton MCP token (`ctn_…`) with the owner scope was the owner everywhere: on /v1/admin (requireAdmin let it in), on * every device route (caller() made it the owner), and in every act. Every OAuth connector holds one. This switch, * per account and off by default, keeps a token to what tokens are for: * * - /v1/admin/* takes the admin token alone. * - A token reaches no device route but `POST /v1/act` with `mint_token` or `revoke_token`, and only a token pasted * by hand (the coordinator's), never a connector's (one that carries an OAuth refresh row). * - A token mints only what is narrower than the owner: never the owner scope, always with an end (at most * MINT_DAYS days; a lane at most 7 as before). * - A token, at /mcp or /v1/act, never writes the tables that hold the account's keys and credentials (PROTECTED). * - reset is refused on the live Worker, and reset and erase take `confirm` naming the database's id. * * Off (no meta), everything is as it was. What every token reaches is noted either way (`token_route`), so the switch's * gate can say before it is thrown which token would lose a route it uses. *//** The meta the switch is held in: `{ on_at, by }`, absent when off. */exportconst META = "token_scopes";/** How long a token-minted token may live, at most. */exportconst MINT_DAYS = 90;/** How far back a token counts as in use (as memory_lock.ts). */exportconst IN_USE_DAYS = 14;/** What a token may still do on a device route: mint and revoke, by a token pasted by hand. */exportconst TOKEN_ACTS: ReadonlySet<string> = newSet(["mint_token", "revoke_token"]);/** * The tables a token never writes, token scopes on or off, at /v1/act and from any tool (create, update, delete, undo, * a restore of a version): who may do what is held in them (keys, credentials, devices, passkeys, the grants and asks * the phone answers). The owner's phones, the sign-in, OAuth and the admin write them (ADMIN KEYS 1b). */exportconst PROTECTED: ReadonlySet<string> = newSet(["mcp_token","oauth_client","oauth_code","oauth_refresh","device","vault_key","seal_key","person_key","passkey","code_credential","unlock_grant","unlock_request","assistant_ask","placement_proposal",]);/** * The acts that change who may do what: a person's role (another phone made owner), a key minted, an unlock or an * assistant's grant given, widened, narrowed or ended. Never a token's, token scopes on or off, at /v1/act or by * run_act (ADMIN KEYS 1b): the owner's own signed-in device does them. revoke_token stays open to a token: it only * ends access. */exportconst ACCESS_ACTS: ReadonlySet<string> = newSet(["set_role", "mint_token", "token_allow", "unlock_allow", "assistant_allow", "assistant_add", "assistant_scope", "assistant_remove", "unlock_decline", "unlock_end"]);const LANE_SCOPE = /^lane:[A-Za-z0-9_-]{1,60}$/;/** * ADMIN KEYS 1b, the coordinator's call (27 Nov): the ONE mint a key may make is a lane token. Why `mint_token` by a key * is refused, or null when it is a lane mint: the minting key holds the owner scope (a lane token, or any narrower key, * mints nothing, so a lane token never renews itself); the new token's scopes are exactly `read` and one * `lane:<name>`; it ends in 1 to 7 days; it names no `allow` (it carries the minting key's, never wider); and it asks * nothing else (its name and the machine it runs on alone). */exportfunction laneMintRefusal(minterScopes: readonly string[], args: Record<string, unknown>): string | null {const lane = "mint_token changes who may do what: the owner does it from their own device, never a key; a key mints only a lane token (scopes read and one lane:<name>, ending in at most 7 days)";if (!minterScopes.includes("owner")) return`${lane}, and only an owner-scope key mints one`;const extra = Object.keys(args).filter((k) => !["name", "scopes", "expires_in_days", "machine"].includes(k));if (extra.length) return`${lane}; it asks no ${extra.join(", ")} (a lane token carries what the minting key may do, never wider)`;const scopes = args.scopes;if (!Array.isArray(scopes) || scopes.length !== 2 || !scopes.includes("read") || !scopes.some((s) => typeof s === "string" && LANE_SCOPE.test(s))) return lane;const days = args.expires_in_days;if (typeof days !== "number" || !Number.isInteger(days) || days < 1 || days > 7) return`${lane}: expires_in_days is 1 to 7`;returnnull;}/** * ADMIN KEYS 4, the coordinator's call (27 Nov): the SECOND mint a key may make, the Macs' machines producer * (the machine-row install's --mint), exactly: scopes `read` and `write`; an allow list of PRODUCER_ALLOW and * nothing wider; named producer (`producer_of`) of some of PRODUCER_TABLES; 1 to 90 days; by an owner-scope key. It * cannot mint (it holds no owner scope), and its row names the key that minted it. * What the producer needs, named: it reads and writes `machine` (machine-row.sh: its Machines row) and `disk_claim` * (claims-sweep.sh: its Disk rows), reads `session` and `project` (claims-sweep.sh list_sessions, which names each * session's project: which claims' sessions ended), and * list_devices answers it because it reads `machine` (machine-row.sh: whether this Mac is a builder; key_allow mayReadIn). */exportconst PRODUCER_TABLES: readonly string[] = ["disk_claim", "machine"];exportconst PRODUCER_ALLOW = { read: ["disk_claim", "machine", "project", "session"], write: ["disk_claim", "machine"], outward: false, sealed: false, acts: [] as string[] };exportfunction producerMintRefusal(minterScopes: readonly string[], args: Record<string, unknown>): string | null {const shape = "a key mints a machines producer only as scopes read and write, allow exactly the producer's tables (read disk_claim, machine, project, session; write disk_claim, machine), producer_of some of disk_claim and machine, ending in at most 90 days";if (!minterScopes.includes("owner")) return`${shape}, and only an owner-scope key mints one`;const extra = Object.keys(args).filter((k) => !["name", "scopes", "expires_in_days", "machine", "allow", "producer_of"].includes(k));if (extra.length) return`${shape}; it asks no ${extra.join(", ")}`;const scopes = args.scopes;if (!Array.isArray(scopes) || scopes.length !== 2 || !scopes.includes("read") || !scopes.includes("write")) return shape;const days = args.expires_in_days;if (typeof days !== "number" || !Number.isInteger(days) || days < 1 || days > 90) return`${shape}: expires_in_days is 1 to 90`;constof = args.producer_of;if (!Array.isArray(of) || !of.length || newSet(of).size !== of.length || !of.every((t) => typeof t === "string" && PRODUCER_TABLES.includes(t))) return`${shape}: producer_of names disk_claim, machine or both`;const asked = args.allow asRecord<string, unknown> | null | undefined;const sorted = (v: unknown) => (Array.isArray(v) ? [...v].map(String).sort() : v);const exact = !!asked && typeof asked === "object" && !Array.isArray(asked) &&Object.keys(asked).every((k) => k in PRODUCER_ALLOW) && JSON.stringify(sorted(asked.read)) === JSON.stringify(PRODUCER_ALLOW.read) && JSON.stringify(sorted(asked.write)) === JSON.stringify(PRODUCER_ALLOW.write) && (asked.outward ?? false) === false && (asked.sealed ?? false) === false && (Array.isArray(asked.acts) ? asked.acts.length === 0 : asked.acts === undefined);return exact ? null : `${shape}: allow is exactly that, nothing wider`;}/** Why a key's mint is refused, or null for one of the two shapes it may make (a lane token, a machines producer). */exportfunction keyMintRefusal(minterScopes: readonly string[], args: Record<string, unknown>): string | null {if (args.producer_of !== undefined) return producerMintRefusal(minterScopes, args);return laneMintRefusal(minterScopes, args);}/** The acts that write a table named in `table`: a token never names a PROTECTED one. */exportconst TABLE_WRITE_ACTS: ReadonlySet<string> = newSet(["create", "update", "delete", "record_act"]);exportconst SCHEMA = `CREATE TABLE IF NOT EXISTS token_route (token_id TEXT NOT NULL, route TEXT NOT NULL, last_at TEXT NOT NULL, PRIMARY KEY (token_id, route));`;exportinterfaceSwitch { on_at: string; by: string;}exportfunction readSwitch(text: string | null): Switch | null {if (!text) returnnull;try {const v = JSON.parse(text) asSwitch;return v && typeof v.on_at === "string" ? v : null; } catch {returnnull; }}/** The route a token's call is noted under: an act by its name, any other path as it is, never an id or a query. */exportfunction routeOf(method: string, path: string, act?: string): string {if (act) return`act ${act}`;return`${method} ${path.replace(/\/[0-9a-f-]{16,}(?=\/|$)/gi, "/:id")}`;}/** Would this route still answer the token with the switch on? */exportfunction allowed(route: string, connector: boolean): boolean {if (route === "POST /mcp") returntrue;if (connector) returnfalse;return route.startsWith("act ") && TOKEN_ACTS.has(route.slice(4));}/** The refusal a token gets on a device or admin route with the switch on. */exportconst DEVICE_REFUSAL = "a Cotton MCP token speaks at /mcp: this route is for the owner's phones and the admin";/** A token's mint, checked with the switch on: what is wrong with it, or null. */exportfunction mintRefusal(scopes: readonly string[], days: number | null): string | null {if (scopes.includes("owner")) return"a token cannot mint the owner scope: mint read, write or a lane";if (days === null) return`a token mints a token with an end: expires_in_days, at most ${MINT_DAYS}`;if (days > MINT_DAYS) return`a token mints a token of at most ${MINT_DAYS} days`;returnnull;}exportinterfaceTokenSeen { id: string; name: string; scopes: string[]; last_used_at: string | null; created_at: string | null; expires_at: string | null; revoked_at: string | null; connector: boolean;}/** Is this token live and in use: unrevoked, unexpired, used (or made) in the last IN_USE_DAYS days? */exportfunction inUse(t: TokenSeen, nowMs: number): boolean {if (t.revoked_at) returnfalse;if (t.expires_at && Date.parse(t.expires_at) <= nowMs) returnfalse;const at = t.last_used_at ?? t.created_at;return !!at && Date.parse(at) >= nowMs - IN_USE_DAYS * 86_400_000;}exportinterfaceHolder { token_id: string; name: string; scopes: string[]; connector: boolean; last_used_at: string | null;/** Every route it was seen on since the object began noting, with when last. */ routes: { route: string; last_at: string; kept: boolean }[]; verdict: "fine" | "excused" | "would_lose"; says: string;}/** The gate's verdict on one token in use: fine when every route it uses stays open to it. */exportfunction holderOf(t: TokenSeen, routes: { route: string; last_at: string }[], excuse: ReadonlySet<string>): Holder {const marked = routes.map((r) => ({ ...r, kept: allowed(r.route, t.connector) })).sort((a, b) => a.route.localeCompare(b.route));const lost = marked.filter((r) => !r.kept);const verdict: Holder["verdict"] = !lost.length ? "fine" : excuse.has(t.id) ? "excused" : "would_lose";const says = verdict === "fine" ? t.connector ? "a connector: speaks at /mcp only" : "uses /mcp, and mints or revokes tokens at most" : `${verdict === "excused" ? "excused, but loses" : "would lose"} ${lost.map((r) => r.route).join(", ")}: ${t.connector ? "a connector keeps /mcp only" : "move it to the admin token, or a phone"}`;return { token_id: t.id, name: t.name, scopes: t.scopes, connector: t.connector, last_used_at: t.last_used_at, routes: marked, verdict, says };}