Cotton code
212 lines · 14.4 KB · TypeScriptRaw
/** * TOKEN SCOPES, PROVEN AGAIN AT HEAD (coordinator, 24 Nov 2026; assets/design/shared/TOKEN-SCOPES.md "Proven on dev", * TOKEN-SCOPES-GO-LIVE.md). The 23 Nov proof's checks, as a script that runs again: on one invented +1555 account, * a phone (the device credential), a pasted owner token (as the coordinator's is minted), a pasted assistant (read, * write) and a real OAuth connector (register, authorize with the number and the code, the redemption), then: *   off: the switch is off, and a token is still the owner on /v1/admin, as before; *   on:  /v1/admin takes the admin token alone; a token reaches no device route but mint and revoke by a pasted *        token; nothing mints the owner scope or a token with no end; a connector mints nothing; a revoked assistant *        stays revoked; /mcp answers every token and the phone reads; the admin token still reaches its routes; *   back: off again, and the owner token is the owner again. * The switch takes the admin token, so this runs on a Worker whose admin token is given (--admin-token-file): a local * wrangler dev at head, or the dev Worker by the coordinator. Invented data only; nothing secret is printed. * *   pnpm -s exec tsx scripts/token-scopes-proof.ts --base <url> --code-file <path> --admin-token-file <path> */import { randomBytes } from "node:crypto";import { readFileSync } from "node:fs";import { homedir } from "node:os";import { signIn } from "./dev-seed/client.ts";import { devBase } from "./dev-server";const arg = (name: string, fallback?: string) => {  const i = process.argv.indexOf(`--${name}`);  return i > 0 ? process.argv[i + 1]! : fallback;};const DEV = arg("base", devBase())!;if (DEV !== devBase() && !/^http:\/\/127\.0\.0\.1:\d+$/.test(DEV)) throw new Error("--base is the dev Worker or a local wrangler dev");const CODE = readFileSync(arg("code-file", `${homedir()}/.cotton-credentials/cotton/dev-otp`)!, "utf8").replace(/\D/g, "");const ADMIN = readFileSync(arg("admin-token-file", `${homedir()}/.cotton-credentials/cloudflare/business-dev-admin-token`)!, "utf8").trim();const NUMBER = arg("number", `+1555${String(Math.floor(1_000_000 + Math.random() * 8_999_999))}`)!;if (!/^\+1555\d{7}$/.test(NUMBER)) throw new Error("--number is an invented +1555 number");const say = (line: string) => console.log(`[token-scopes] ${line}`);const b64url = (bytes: Uint8Array) => Buffer.from(bytes).toString("base64url");const hidden = (html: string): Record<string, string> => {  const out: Record<string, string> = {};  for (const m of html.matchAll(/<input type="hidden" name="([^"]+)" value="([^"]*)">/g)) out[m[1]!] = m[2]!.replace(/&quot;/g, '"').replace(/&#39;/g, "'").replace(/&lt;/g, "<").replace(/&gt;/g, ">").replace(/&amp;/g, "&");  return out;};/** An assistant connected as claude.ai connects one (the MCP walk's `connect`): its access token. */async function connectOAuth(number: string, code: string): Promise<string> {  const REDIRECT = "https://claude.ai/api/mcp/auth_callback";  const form = (path: string, body: Record<string, string>) => fetch(`${DEV}${path}`, { method: "POST", redirect: "manual", headers: { "content-type": "application/x-www-form-urlencoded" }, body: new URLSearchParams(body).toString() });  const reg = await fetch(`${DEV}/oauth/register`, { method: "POST", headers: { "content-type": "application/json" }, body: JSON.stringify({ client_name: "Invented connector", redirect_uris: [REDIRECT] }) });  if (reg.status !== 201) throw new Error(`register answered ${reg.status}`);  const clientId = ((await reg.json()) as { client_id: string }).client_id;  const verifier = b64url(randomBytes(40));  const challenge = b64url(new Uint8Array(await crypto.subtle.digest("SHA-256", new TextEncoder().encode(verifier))));  const query = new URLSearchParams({ client_id: clientId, redirect_uri: REDIRECT, response_type: "code", code_challenge: challenge, code_challenge_method: "S256", state: "proof", scope: "owner", resource: `${DEV}/mcp` });  const start = await fetch(`${DEV}/oauth/authorize?${query}`, { redirect: "manual" });  if (start.status !== 200) throw new Error(`authorize answered ${start.status}`);  const sent = await form("/oauth/authorize", { ...hidden(await start.text()), phone: number });  if (sent.status !== 200) throw new Error(`the number's step answered ${sent.status}`);  const proved = await form("/oauth/authorize", { ...hidden(await sent.text()), code });  const to = proved.headers.get("location");  const got = to ? new URL(to).searchParams.get("code") : null;  if (proved.status !== 302 || !got) throw new Error(`the code's step answered ${proved.status}`);  const res = await form("/oauth/token", { grant_type: "authorization_code", client_id: clientId, code: got, code_verifier: verifier, redirect_uri: REDIRECT, resource: `${DEV}/mcp` });  if (res.status !== 200) throw new Error(`the redemption answered ${res.status}`);  return ((await res.json()) as { access_token: string }).access_token;}type Answer = { status: number; body: Record<string, unknown> };async function call(base: string, method: string, path: string, bearer: string | null, body?: unknown): Promise<Answer> {  const res = await fetch(`${base}${path}`, { method, headers: { "content-type": "application/json", accept: "application/json, text/event-stream", ...(bearer ? { authorization: `Bearer ${bearer}` } : {}) }, body: body === undefined ? undefined : JSON.stringify(body) });  const text = await res.text();  const json = text.trimStart().startsWith("{") ? text : (text.split("\n").find((l) => l.startsWith("data:"))?.slice(5) ?? "");  let parsed: Record<string, unknown> = {};  try {    parsed = json ? JSON.parse(json) : {};  } catch {    parsed = { text: text.slice(0, 200) };  }  return { status: res.status, body: parsed };}let passed = 0;const failed: string[] = [];function check(ok: boolean, what: string, got?: Answer): void {  if (ok) passed++;  else failed.push(`${what}${got ? ` (${got.status} ${String(got.body.code ?? got.body.error ?? "")})` : ""}`);  say(`${ok ? "ok  " : "FAIL"} ${what}${!ok && got ? `: ${got.status} ${JSON.stringify(got.body).slice(0, 160)}` : ""}`);}async function main(): Promise<void> {  const s = await signIn(DEV, NUMBER, CODE);  const db = s.databaseId;  const B = `${DEV}/b/p-${db}`;  const phone = s.credential;  const act = (bearer: string, name: string, args: Record<string, unknown>) => call(B, "POST", "/v1/act", bearer, { act: name, args });  // The sign-in's own owner token is this script's to forget: revoked, so the gate names only the tokens below.  await act(phone, "revoke_token", { id: s.tokenId });  const minted = await act(phone, "mint_token", { name: "coordinator (invented)", scopes: ["owner"], allow: "all" });  const owner = String(minted.body.token);  const asst = await act(phone, "mint_token", { name: "assistant (invented)", scopes: ["read", "write"], expires_in_days: 30, allow: "all" });  const assistant = String(asst.body.token);  const assistantId = String((asst.body.made as { id?: string } | undefined)?.id);  const conn = await connectOAuth(NUMBER, CODE);  const mcp = (bearer: string, tool: string, args: Record<string, unknown> = {}) => call(DEV, "POST", "/mcp", bearer, { jsonrpc: "2.0", id: 1, method: "tools/call", params: { name: tool, arguments: args } });  const answers = (a: Answer) => a.status === 200 && !a.body.error && (a.body.result as { isError?: boolean } | undefined)?.isError !== true;  say(`an invented account (database ${db.slice(0, 8)}…): a phone, a pasted owner token, a pasted assistant, an OAuth connector`);  // Off.  const gate0 = await call(B, "GET", "/v1/admin/token-scopes", ADMIN);  check(gate0.status === 200 && gate0.body.on === null, "off by default", gate0);  const ownerAdmin = await call(B, "GET", "/v1/admin/row-counts", owner);  check(ownerAdmin.status === 200, "off: the pasted owner token is the owner on /v1/admin, as before", ownerAdmin);  for (const [name, token] of [["the connector", conn], ["the owner token", owner], ["the assistant", assistant]] as const) check(answers(await mcp(token, "list_tools")), `off: /mcp answers ${name}`);  // On, from now: the routes seen before the move do not count (`since`).  const since = new Date().toISOString();  const on = await call(B, "POST", "/v1/admin/token-scopes", ADMIN, { on: true, since });  check(on.status === 200 && !!on.body.on, "the admin token throws the switch", on);  check((await call(B, "GET", "/v1/admin/row-counts", ADMIN)).status === 200, "on: the admin token reaches /v1/admin");  const ADMIN_ROUTES: [string, string, unknown?][] = [    ["GET", "/v1/admin/row-counts"],    ["GET", "/v1/admin/export?limit=1"],    ["POST", "/v1/admin/reset", {}],    ["POST", "/v1/admin/erase", { set: "tables", tables: ["note"] }],    ["GET", "/v1/admin/business"],    ["POST", "/v1/admin/import", { rows: [] }],    ["GET", "/v1/admin/token-scopes"],    ["GET", "/v1/admin/memory-lock"],    ["GET", "/v1/admin/open-tables-lock"],    ["GET", "/v1/admin/order-shadow"],  ];  const DEVICE_ROUTES: [string, string, unknown?][] = [    ["GET", "/v1/sync?since=0&limit=1"],    ["GET", "/v1/held?tables=note"],    ["GET", "/v1/me"],    ["GET", "/v1/outbox"],    ["GET", "/v1/google/status"],    ["GET", "/v1/space"],    ["POST", "/v1/import/messages", {}],    ["DELETE", `/v1/media/${db}/proof?prefix=1`],  ];  for (const [name, token] of [["the connector", conn], ["the owner token", owner]] as const) {    for (const [method, path, body] of ADMIN_ROUTES) {      const r = await call(B, method, path, token, body);      check(r.status === 403, `on: ${name} is refused ${method} ${path.split("?")[0]}`, r);    }    for (const [method, path, body] of DEVICE_ROUTES) {      const r = await call(B, method, path, token, body);      check(r.status === 403 && r.body.code === "token_scopes", `on: ${name} is refused ${method} ${path.split("?")[0]} (token_scopes)`, r);    }    const created = await act(token, "create", { table: "todo", data: { title: "invented" } });    check(created.status === 403, `on: ${name} is refused /v1/act create`, created);  }  // Minting.  const connMint = await act(conn, "mint_token", { name: "x", scopes: ["read"], expires_in_days: 7 });  check(connMint.status === 403, "on: a connector mints nothing through /v1/act", connMint);  const connRun = await mcp(conn, "run_act", { act: "mint_token", args: { name: "x", scopes: ["read"], expires_in_days: 7 } });  check(!answers(connRun) || /refus|not|cannot|403/i.test(JSON.stringify(connRun.body)), "on: a connector mints nothing through run_act at /mcp", connRun);  const ownerScope = await act(owner, "mint_token", { name: "x", scopes: ["owner"], expires_in_days: 7 });  check(ownerScope.status >= 400, "on: the pasted token cannot mint the owner scope", ownerScope);  const noEnd = await act(owner, "mint_token", { name: "x", scopes: ["read"] });  check(noEnd.status >= 400, "on: the pasted token cannot mint a token with no end", noEnd);  const tooLong = await act(owner, "mint_token", { name: "x", scopes: ["read"], expires_in_days: 91 });  check(tooLong.status >= 400, "on: the pasted token cannot mint past 90 days", tooLong);  const lane = await act(owner, "mint_token", { name: "lane invented", scopes: ["read", "lane:invented"], expires_in_days: 7 });  check(lane.status === 200 && typeof lane.body.token === "string", "on: the pasted token mints a lane for 7 days (lane-start)", lane);  if (lane.status === 200) {    check(answers(await mcp(String(lane.body.token), "list_tools")), "on: the lane answers at /mcp");    const revoked = await act(owner, "revoke_token", { id: String((lane.body.made as { id?: string } | undefined)?.id) });    check(revoked.status === 200, "on: the pasted token revokes the lane (lane-stop)", revoked);    const after = await mcp(String(lane.body.token), "list_tools");    check(after.status === 401, "on: the revoked lane is answered 401", after);  }  // A revoked assistant stays revoked.  const revokeAsst = await act(phone, "revoke_token", { id: assistantId });  check(revokeAsst.status === 200, "the phone revokes the assistant", revokeAsst);  check((await mcp(assistant, "list_tools")).status === 401, "on: the revoked assistant is answered 401");  for (const [name, token] of [["the connector", conn], ["the owner token", owner]] as const) {    const back = await act(token, "update", { table: "mcp_token", id: assistantId, data: { revoked_at: null } });    check(back.status === 403, `on: ${name} cannot un-revoke it through /v1/act`, back);    const viaMcp = await mcp(token, "update_record", { table: "mcp_token", id: assistantId, data: { revoked_at: null } });    check(!answers(viaMcp), `on: ${name} cannot un-revoke it through MCP update_record`, viaMcp);    const device = await mcp(token, "delete_record", { table: "device", id: "any" });    check(!answers(device), `on: ${name} cannot delete a device row through MCP`, device);  }  check((await mcp(assistant, "list_tools")).status === 401, "on: the assistant is still 401 after");  // What keeps working.  for (const [name, token] of [["the connector", conn], ["the owner token", owner]] as const) {    const t0 = Date.now();    const brief = await mcp(token, "brief", { repoUrl: "https://git.example.test/invented/garden", machine: "invented-mac" });    check(answers(brief), `on: /mcp briefs ${name} (${Date.now() - t0} ms)`, brief);  }  check((await call(B, "GET", "/v1/sync?since=0&limit=1", phone)).status === 200, "on: the phone syncs");  check((await call(B, "GET", "/v1/me", phone)).status === 200, "on: the phone reads /v1/me");  const resetAdmin = await call(B, "POST", "/v1/admin/reset", ADMIN, {});  check(resetAdmin.status >= 400 && resetAdmin.status !== 403, "on: reset without confirm is refused even to the admin token (it needs confirm naming the database)", resetAdmin);  // Back.  const off = await call(B, "POST", "/v1/admin/token-scopes", ADMIN, { on: false });  check(off.status === 200 && off.body.on === null, "the admin token turns it off", off);  const ownerBack = await call(B, "GET", "/v1/admin/row-counts", owner);  check(ownerBack.status === 200, "off again: the owner token is the owner again", ownerBack);  await act(phone, "revoke_token", { id: String((minted.body.made as { id?: string } | undefined)?.id) });  say(`${failed.length ? "FAILED" : "TOKEN SCOPES proven"}: ${passed} of ${passed + failed.length} checks${failed.length ? `; failed: ${failed.join("; ")}` : ""}`);  if (failed.length) process.exit(1);}main().catch((error) => {  console.error(`[token-scopes] FAILED: ${error instanceof Error ? error.message : String(error)}`);  process.exit(1);});