/** * ASSISTANT KEYS THAT CARRY WHAT THEY MAY DO (NEXT-ADMIN-KEYS part 2, 27 Nov 2026). * * A Cotton MCP key (`mcp_token` row) may carry `allow`: the tables it may read, the tables it may write, and whether it * may act on the outside world. Nothing else is open to it: * * - At /mcp: the tools it is shown and may call (a write tool needs a table to write; an outward tool needs outward), * the tables every tool sees (the object's definitions, narrowed to the readable ones, as a CLOSED table is hidden), * every row read (`ctx.scan`, `ctx.where`, `ctx.get`) and every row written (`ctx.write`), every file read by a * row's key (a file of a kind a table owns is read only when that table is), and every act (`tokenAct`). * - At /v1/act: the acts whose tables it may write, by their names (ACT_TABLES); any other act is refused. * - No device route (sync, records, media, export, the admin door): a narrowed key speaks at /mcp and /v1/act alone, * as every key does with token scopes on. Its outward routes (mail sent from the owner's domain, a forward changed, * guests invited) are the owner's to allow on the phone unless the key carries `outward`. * * A key with no `allow` is as it was (the owner's keys made before this; they keep working unchanged until he narrows * them with `token_allow`). A NEW key carries DEFAULT_ALLOW unless its mint names a narrower or, from the owner's own * device, a wider one; a key never mints a key wider than itself, and an OAuth refresh carries its connection's allow. *//** * A mint's or token_allow's `allow: "all"`: a key as every key was before allows (its scopes alone, every device route * its scopes reach). Stored as no allow; only the owner's own device, the admin, or a key that is itself all gives it. */exportconst ALL = "all";/** A table list, or every table the account holds ("*"). */exporttypeTables = readonly string[] | "*";exportinterfaceAllow { read: Tables; write: Tables;/** Mail sent, a forward changed, guests invited, a message to someone outside: off unless named. */ outward: boolean;/** * Reads a sealed table its list does not name as far as the owner's phone grants it: a sealed table is opened only * with keys the phone hands the assistant (Your Claude's grant, on / ask / off per table, or a timed window), so the * phone already decides each one. Off, a sealed table is read only when the list names it (and the phone grants it). */ sealed: boolean;/** * Acts and tools that are not one table's write, each opened by name and off unless named (GRANTABLE_ACTS). Today: * `update_definition`, which an assistant uses to reshape a table's look (its slip, page, group, sort, instructions, * columns); a table's visibility stays the owner's device's (ADMIN KEYS 1b). */ acts: readonly string[];}/** What `allow.acts` may name. */exportconst GRANTABLE_ACTS: ReadonlySet<string> = newSet(["update_definition"]);/** * The narrowest useful set: what the assistant's own workflow reads and writes (brief, recall, remember, log_session, * list_projects), the sealed tables only as the owner's phone grants them, and nothing else of the person's apps: * no open table, no write beyond its memory and session logs, nothing outward. The owner widens it (`token_allow`). */exportconst DEFAULT_ALLOW: Allow = { read: ["memory", "project", "project_link", "prompt", "session", "session_message", "session_task"], write: ["memory", "prompt", "session", "session_message", "session_task"], outward: false, sealed: true, acts: [],};/** Tables no key ever reads or writes, whatever its list says: the account's keys and credentials (token_scopes.ts PROTECTED). */const NEVER: ReadonlySet<string> = newSet(["mcp_token", "oauth_client", "oauth_code", "oauth_refresh", "device", "vault_key", "seal_key", "person_key"]);const TABLE = /^[a-z_][a-z0-9_]{0,63}$/;function tables(v: unknown, what: string): Tables | string {if (v === "*") return"*";if (!Array.isArray(v)) return`${what} is a list of table ids, or "*"`;const out: string[] = [];for (const t of v) {if (typeof t !== "string" || !TABLE.test(t)) return`${what} names a table by its id: ${JSON.stringify(t)} is not one`;if (NEVER.has(t)) return`${t} holds the account's keys and credentials: no key reads or writes it`;if (!out.includes(t)) out.push(t); }return out.sort();}/** A mint's or token_allow's `allow`, checked: the allow, or the sentence refusing it. */exportfunction checkAllow(v: unknown): Allow | string {if (!v || typeof v !== "object" || Array.isArray(v)) return'allow is { read: [tables] | "*", write: [tables] | "*", outward: true | false, sealed: true | false, acts: [names] }';const o = v asRecord<string, unknown>;const extra = Object.keys(o).filter((k) => k !== "read" && k !== "write" && k !== "outward" && k !== "sealed" && k !== "acts");if (extra.length) return`allow holds read, write, outward, sealed and acts alone, not ${extra.join(", ")}`;const acts = o.acts ?? [];if (!Array.isArray(acts) || acts.some((a) => typeof a !== "string" || !GRANTABLE_ACTS.has(a))) return`allow.acts names acts a key may be given: ${[...GRANTABLE_ACTS].join(", ")}`;if (o.sealed !== undefined && typeof o.sealed !== "boolean") return"allow.sealed is true or false";const read = tables(o.read ?? [], "allow.read");if (typeof read === "string" && read !== "*") return read;const write = tables(o.write ?? [], "allow.write");if (typeof write === "string" && write !== "*") return write;if (o.outward !== undefined && typeof o.outward !== "boolean") return"allow.outward is true or false";return { read: read asTables, write: write asTables, outward: o.outward === true, sealed: o.sealed === true, acts: [...newSet(acts as string[])].sort() };}/** May this key run the grantable act or tool `name`? Null (no allow): its scopes alone decide. */exportfunction mayAct(a: Allow | null, name: string): boolean {return !a || a.acts.includes(name);}/** The allow a token row carries, or null for a key made before allows (as it was: its scopes alone). */exportfunction allowOf(data: Record<string, unknown>): Allow | null {if (data.allow === undefined || data.allow === null || data.allow === "") returnnull;let held: unknown = data.allow;if (typeof held === "string") {try { held = JSON.parse(held); } catch { held = null; } }const a = checkAllow(held);// A stored allow that no longer reads is the narrowest, never the widest.returntypeof a === "string" ? { read: [], write: [], outward: false, sealed: false, acts: [] } : a;}const has = (list: Tables, table: string): boolean => !NEVER.has(table) && (list === "*" || list.includes(table));/** An allow as the token row keeps it (the `allow` column, JSON text); null keeps none. */exportfunction stored(a: Allow | null): string | null {return a ? JSON.stringify(a) : null;}/** * May this key read `table`? A table it may write it may read; a sealed one (`isSealed`) also with `sealed`, the phone's * grant then deciding. Null (no allow) is the key's scopes alone. */exportfunction mayRead(a: Allow | null, table: string, isSealed = false): boolean {return !a || has(a.read, table) || has(a.write, table) || (a.sealed && isSealed && !NEVER.has(table));}exportfunction mayWrite(a: Allow | null, table: string): boolean {return !a || has(a.write, table);}/** Does it write anything at all? A key that writes nothing is shown no write tool. */exportfunction writesAny(a: Allow | null): boolean {return !a || a.write === "*" || a.write.length > 0;}/** Is `inner` within `outer`? A key mints only what it holds; null (a key before allows) holds everything. *//** A key with no list (null), as a list: everything a list can say. */exportconst EVERYTHING: Allow = { read: "*", write: "*", outward: true, sealed: true, acts: [...GRANTABLE_ACTS] };exportfunction within(inner: Allow, outer: Allow | null): boolean {if (!outer) returntrue;const sub = (i: Tables, o: Tables) => o === "*" || (i !== "*" && i.every((t) => o.includes(t)));return sub(inner.read, outer.read === "*" || outer.write === "*" ? "*" : [...outer.read, ...(outer.write asreadonly string[])]) && sub(inner.write, outer.write) && (!inner.outward || outer.outward) && (!inner.sealed || outer.sealed) && inner.acts.every((n) => outer.acts.includes(n));}/** * The table a file's kind (`<database>/<kind>/…`) belongs to, for a narrowed key's file read: the file is read only when * that table is. A kind not named here is read only by a key that reads every table. */exportconst FILE_KIND_TABLES: Readonly<Record<string, string>> = { photos: "photo", films: "film", documents: "document", mail: "email", messages: "message", people: "person", books: "book", music: "song", recordings: "recording", podcasts: "episode",};/** May this key read a file of `kind`? */exportfunction mayReadKind(a: Allow | null, kind: string | null, sealedTable: (table: string) => boolean = () => false): boolean {if (!a || a.read === "*") returntrue;const table = kind ? FILE_KIND_TABLES[kind] : undefined;return !!table && mayRead(a, table, sealedTable(table));}/** * Tools that read or change the whole database at once (the change log, the bin, undo, the size of every table, an * export, the devices): only a key that reads every table sees them, and the ones that change, writes every table. */exportconst WHOLE_DATABASE_TOOLS: Readonly<Record<string, "read" | "write">> = { list_changes: "read", list_bin: "read", storage_summary: "read", summarize_records: "read", list_devices: "read", export_open_bundle: "read", list_tools: "read", restore_from_bin: "write", empty_bin: "write", undo: "write", restore_version: "write", merge_people: "write",};/** * May this key read `table` inside the tool `tool`? As mayRead, with one named exception: list_devices answers a key that * reads `machine` (the account's machines and their state, the machines producer's builder question), though `device` * is never read by a key otherwise (NEVER). list_devices answers no key, hash or secret. */exportfunction mayReadIn(a: Allow | null, table: string, tool: string | null, isSealed = false): boolean {if (table === "device" && tool === "list_devices" && a && mayRead(a, "machine")) returntrue;return mayRead(a, table, isSealed);}/** Is `tool` (of catalogue scope `scope`) open to this key? Null: its scopes alone decide. */exportfunction toolOpen(a: Allow | null, tool: string, scope: string): boolean {if (!a) returntrue;if (tool.startsWith("dev_")) returnfalse;// A grantable tool opens by its name alone, never by a wide write list (`allow.acts`).if (GRANTABLE_ACTS.has(tool)) return mayAct(a, tool);// The one named exception (mayReadIn): list_devices opens to a key that reads `machine`.if (tool === "list_devices" && mayRead(a, "machine")) returntrue;const whole = WHOLE_DATABASE_TOOLS[tool];if (whole === "read" && a.read !== "*") returnfalse;if (whole === "write" && a.write !== "*") returnfalse;if ((scope === "write" || scope === "owner") && !writesAny(a)) returnfalse;returntrue;}/** The Store methods whose first argument is a table: a narrowed key's tools reach them only for a table it reads. */exportconst STORE_TABLE_FIRST: ReadonlySet<string> = newSet(["get", "any", "list", "scan", "select", "selectOrdered", "pageBack", "count", "liveCount", "countBy", "value", "blindIds", "blindCond", "setBlind", "owned"]);/** * ADMIN KEYS 4, THE ONE PLACE outward is decided, by what a thing does, never by its route: "outward" reaches a person * other than the owner (a message, a chat post, mail, a calendar guest, a share, an invite, a booking with a business) or * a server outside Cotton (a fetch of a url, a feed, a lookup, a download onto the owner's Mac); "inside" stays in this * database and the owner's own devices. Every MCP tool and every act is classed here (test/key-allow.test.ts holds the * lists to the catalogue and acts.ts); one whose reach depends on what it is asked names it in `outwardTool`/`outwardAct`. * A key without outward runs none of the outward ones. REST routes that reach outside are owner_asks.ts `outwardRoute`. */exporttypeReach = "outward" | "inside" | "by_args";exportconst TOOL_REACH: Readonly<Record<string, Reach>> = { agent_chat_post: "outward", agent_chat_react: "outward", put_document: "by_args", create_record: "by_args", update_record: "by_args", run_act: "by_args", agent_chat_read: "inside", agent_chat_state: "inside", agent_chats: "inside", brief: "inside", create_project: "inside", create_secret: "inside", create_todo: "inside", delete_record: "inside", dev_reveal_secret: "inside", empty_bin: "inside", end_unlock: "inside", export_open_bundle: "inside", get_media: "inside", get_record: "inside", get_record_by_table: "inside", get_session: "inside", link_to_project: "inside", list_bin: "inside", list_changes: "inside", list_devices: "inside", list_projects: "inside", list_records: "inside", list_secrets: "inside", list_sessions: "inside", list_todos: "inside", list_tools: "inside", log_session: "inside", memory_archive: "inside", memory_update: "inside", merge_people: "inside", recall: "inside", recording_read: "inside", recording_summary_write: "inside", recordings_to_summarise: "inside", remember: "inside", request_unlock: "inside", restore_from_bin: "inside", restore_version: "inside", search_records: "inside", storage_summary: "inside", story_copy: "inside", story_draft_changes: "inside", story_draft_mark: "inside", story_draft_read: "inside", story_draft_restore: "inside", story_fdx_write: "inside", story_fountain_read: "inside", story_fountain_write: "inside", story_line_remove: "inside", story_line_write: "inside", story_merge: "inside", story_move_old: "inside", story_picture_add: "inside", story_rename: "inside", story_scene_merge: "inside", story_scene_move: "inside", story_scene_split: "inside", story_scene_write: "inside", summarize_records: "inside", undo: "inside", update_definition: "inside", update_project: "inside", update_todo: "inside",};exportconst ACT_REACH: Readonly<Record<string, Reach>> = { message: "outward", book: "outward", order: "outward", cancel: "outward", subscribe_podcast: "outward", refresh_podcast: "outward", import_opml: "outward", find_book: "outward", find_film: "outward", find_lyrics: "outward", fetch_cover: "outward", fetch_add: "outward", fetch_retry: "outward", fetch_again: "outward", create: "by_args", update: "by_args", record_act: "by_args", definition: "inside", profile: "inside", delete: "inside", seal: "inside", seal_many: "inside", seal_stage: "inside", seal_commit: "inside", seal_purge: "inside", unlock_allow: "inside", assistant_allow: "inside", assistant_add: "inside", assistant_scope: "inside", assistant_remove: "inside", unlock_decline: "inside", unlock_end: "inside", restore: "inside", import_rows: "inside", set_role: "inside", mint_token: "inside", token_allow: "inside", revoke_token: "inside", make_todo_recurring: "inside", update_todo_recurrence: "inside", stop_todo_recurrence: "inside", read_statement: "inside", submit_statement_reading: "inside", book_statement: "inside", settle_expected: "inside", merge_people: "inside", unmerge_people: "inside", merge_accounts: "inside", match_external: "inside", start_book: "inside", finish_book: "inside", import_goodreads: "inside", export_opml: "inside", drop_old_music: "inside", reshape_films: "inside", film_converted: "inside", fetch_cancel: "inside", fetch_claim: "inside", fetch_stage: "inside", fetch_progress: "inside", fetch_landed: "inside", fetch_failed: "inside", meeting_claim: "inside", meeting_failed: "inside",};/** Tables whose rows, once written, reach outside: the outbox the Mac sends from, and the downloads it fetches. */exportconst OUTWARD_TABLES: ReadonlySet<string> = newSet(["outbox", "fetch"]);/** Does this tool call reach outside? An unknown tool counts as outward: unclassed is never assumed safe. */exportfunction outwardTool(tool: string, args: Record<string, unknown>): boolean {const reach = TOOL_REACH[tool] ?? "outward";if (reach !== "by_args") return reach === "outward";if (tool === "put_document") returntypeof args.url === "string" && args.url !== "";if (tool === "run_act") return outwardAct(typeof args.act === "string" ? args.act : "", (args.args asRecord<string, unknown>) ?? {});returntypeof args.table === "string" && OUTWARD_TABLES.has(args.table);}/** Does this act reach outside? An unknown act counts as outward. */exportfunction outwardAct(act: string, args: Record<string, unknown>): boolean {const reach = ACT_REACH[act] ?? "outward";if (reach !== "by_args") return reach === "outward";returntypeof args.table === "string" && OUTWARD_TABLES.has(args.table);}/** The refusal for an outward thing asked by a key without outward, or null. */exportfunction outwardRefusal(a: Allow | null, outward: boolean, what: string): string | null {return a && outward && !a.outward ? `${what} reaches someone or somewhere outside Cotton: this key does not act on the outside world (the owner allows outward on the phone)` : null;}/** * The tables an act writes, for a narrowed key at /v1/act or run_act: every one must be writable. An act not named here * is refused to a narrowed key (the owner's phone runs it, or a key with no allow). `create`, `update`, `delete` and * the seal acts name their table in `table`. */exportconst ACT_TABLES: Readonly<Record<string, readonly string[]>> = { make_todo_recurring: ["todo", "todo_recurrence"], update_todo_recurrence: ["todo", "todo_recurrence"], stop_todo_recurrence: ["todo", "todo_recurrence"], start_book: ["book"], finish_book: ["book"], find_book: ["book"], find_film: ["film"], fetch_add: ["fetch"], fetch_cancel: ["fetch"], fetch_retry: ["fetch"], fetch_again: ["fetch"], subscribe_podcast: ["podcast"], refresh_podcast: ["podcast", "episode"],};/** The acts that name their own table in `table` (the seal acts, restore and import are the owner's own devices', never a key's). */exportconst TABLE_ACTS: ReadonlySet<string> = newSet(["create", "update", "delete", "record_act"]);/** Why a narrowed key may not run `act` with `args`, or null when it may. */exportfunction actRefusal(a: Allow | null, act: string, args: Record<string, unknown>): string | null {if (!a) returnnull;const outward = outwardAct(act, args);const away = outwardRefusal(a, outward, act);if (away) return away;// mint_token and token_allow are refused to every key before this (ADMIN KEYS 1b, token_scopes ACCESS_ACTS); a key// revokes as the owner's tokens do.if (act === "mint_token" || act === "revoke_token" || act === "token_allow") returnnull;if (GRANTABLE_ACTS.has(act)) return mayAct(a, act) ? null : `${act} is not open to this key: the owner names it in the key's acts from the phone`;if (TABLE_ACTS.has(act)) {const table = typeof args.table === "string" ? args.table : "";return mayWrite(a, table) ? null : `this key does not write ${table || "that table"}`; }const named = ACT_TABLES[act];// `message` writes no table of the key's: with outward it runs (as before); every other unnamed act is the phone's.if (!named) return act === "message" ? null : `${act} is not open to this key: the owner runs it from the phone`;const shut = named.filter((t) => !mayWrite(a, t));return shut.length ? `${act} writes ${shut.join(", ")}: this key does not` : null;}