/** * Your Claude: one standing grant to the person's own assistant, made once * (owner, 20 Nov 2026: "if I connect the MCP, why not * automatically give Claude the access?"). Beside the unlock window * (src/window.ts), which stays as it was for tables set to ask each time. * * MEMBERS. Every assistant connection is a member: an X25519 pair. Its public * half is kept clear (`agent_member.pub`); its private half S is kept only * inside the connection's tokens. For each token (access, refresh, lane) the * object keeps a CARRIER: AES-256-GCM of S under HKDF-SHA256(ikm = the token * string, salt = WINDOW_KEY, info = "cotton-agent-carrier-v1|" sha256(token)). * The object stores a token only as its sha256, so neither the database nor * WINDOW_KEY opens a carrier: S exists in memory only while a call that * presented the token is answered. * * - An OAuth connection is a member from the code's redemption; each refresh * opens S from the presented refresh token's carrier and carries it into * the new pair, so the grant stands across refreshes with nothing kept. * - A lane token minted by a token that carries S carries the same S: the * lane is the same member, granted from birth. * - A pasted token minted before this is a member from its first call. * - Connect Claude in an app: the phone makes the pair and the grant, and * hands S over sealed under WINDOW_KEY (`pending`) for at most * [PENDING_MS]; the next OAuth connection claims it and the copy is deleted. * The one moment S rests on the object, bounded and named. * * THE GRANT is an `unlock_grant` row with `account` true: standing, bound to * the member (connection_id `member:<id>`, so no connection's revoke ends it). * The phone wraps the tables' keys to the member's public half and signs the * policy with the person key (seal-core `seal::agent`): every sealed table * except `withheld` (saved secrets always among them). The wraps are kept as * they came (`agent_wrap`, ciphertext to the member key). More tables or * versions inside the policy come as unsigned additions; widening is signed. * `off` and `ask` narrow it on the object at once (no signature: narrowing * opens nothing); ask hands that table back to the timed window. * * THE CARD. A sealed read by a member with no grant files ONE request, * `account` true, naming every sealed table in scope; the phone's Allow * (assistant_allow) is the grant. A member that has a grant is never asked * again. The card stands until answered (no ten minutes: it opens nothing * by itself). Remove (assistant_remove) ends every account grant and deletes every * wrap; the phone moves those tables to fresh keys. * * NO FALLBACK TO CLEAR. No WINDOW_KEY: nothing here is made or opened, and a * read is answered by the window code's own refusal. */importtype { Engine, Outcome } from"./engine.ts";import { refuse, sha256Hex } from"./http.ts";importtype { StoredRow } from"./store.ts";import { askerOf } from"./tokens.ts";import { AGENT_CONTEXT, agentStatement, closed, CLOSED, NEVER, plain, policy } from"./agent_statement.ts";export { AGENT_CONTEXT, agentStatement, CLOSED, closed, NEVER, policy };import { fromBase64Url, toBase64Url } from"./vault.ts";import { GRANT_TABLE, openSecret, parseBundle, REQUEST_TABLE, REQUESTS_PER_HOUR, sealSecret, STANDING, STANDING_ENDS, unwrap, verifySig,typeTableKeys,typeWindowHost,} from"./window.ts";exportconst SCHEMA = `CREATE TABLE IF NOT EXISTS agent_member (id TEXT PRIMARY KEY, pub TEXT NOT NULL, name TEXT NOT NULL, made_by TEXT NOT NULL, created_at TEXT NOT NULL, pending TEXT, pending_until TEXT);CREATE TABLE IF NOT EXISTS agent_carrier (token_hash TEXT PRIMARY KEY, member_id TEXT NOT NULL, blob TEXT NOT NULL);CREATE INDEX IF NOT EXISTS agent_carrier_member ON agent_carrier (member_id);CREATE TABLE IF NOT EXISTS agent_wrap (id INTEGER PRIMARY KEY AUTOINCREMENT, grant_id TEXT NOT NULL, member_id TEXT NOT NULL, wrapped TEXT NOT NULL, added_at TEXT NOT NULL);CREATE INDEX IF NOT EXISTS agent_wrap_grant ON agent_wrap (grant_id);`;/** How long a member made by Connect Claude waits for its connection. */exportconst PENDING_MS = 15 * 60_000;/** The hosts Claude's apps (claude.ai, Claude Desktop) take an OAuth code back on: the only redirects that claim a waiting Connect Claude. */exportconst CLAUDE_REDIRECT_HOSTS: ReadonlySet<string> = newSet(["claude.ai", "claude.com"]);/** Whether an OAuth redirect lands on Claude's own host, over https. */exportfunction claudeRedirect(redirect: string | null): boolean {if (!redirect) returnfalse;try {const u = new URL(redirect);return u.protocol === "https:" && CLAUDE_REDIRECT_HOSTS.has(u.hostname.toLowerCase()); } catch {returnfalse; }}exporttypeAccess = "on" | "ask" | "off";const CARRIER_INFO = "cotton-agent-carrier-v1|";constX25519_PKCS8 = Uint8Array.from([0x30, 0x2e, 0x02, 0x01, 0x00, 0x30, 0x05, 0x06, 0x03, 0x2b, 0x65, 0x6e, 0x04, 0x22, 0x04, 0x20]);const utf8 = newTextEncoder();const iso = (ms: number): string => newDate(ms).toISOString();const memberConnection = (memberId: string): string => `member:${memberId}`;const pendingAad = (memberId: string): string => `agent-pending|${memberId}`;/** A presented token: the string, and its sha256 as the object keeps it. */exportinterfacePresented { token: string; hash: string;}/** A member's private half, opened for one call. */exportinterfaceOpened { memberId: string; secret: Uint8Array; pub: Uint8Array;}// ── keys ─────────────────────────────────────────────────────────────────/** The X25519 public half of a 32-byte private half. */exportasyncfunction publicOf(secret: Uint8Array): Promise<Uint8Array> {const pkcs8 = newUint8Array(X25519_PKCS8.length + 32); pkcs8.set(X25519_PKCS8); pkcs8.set(secret, X25519_PKCS8.length);const key = await crypto.subtle.importKey("pkcs8", pkcs8, { name: "X25519" }, true, ["deriveBits"]); pkcs8.fill(0);return fromBase64Url(((await crypto.subtle.exportKey("jwk", key)) asJsonWebKey).x!);}/** A fresh member pair. */exportasyncfunction mintMember(): Promise<{ secret: Uint8Array; pub: Uint8Array }> {const pair = (await crypto.subtle.generateKey({ name: "X25519" }, true, ["deriveBits"])) asCryptoKeyPair;const jwk = (await crypto.subtle.exportKey("jwk", pair.privateKey)) asJsonWebKey;return { secret: fromBase64Url(jwk.d!), pub: fromBase64Url(jwk.x!) };}asyncfunction carrierKey(windowKey: Uint8Array, presented: Presented): Promise<Uint8Array> {const ikm = await crypto.subtle.importKey("raw", utf8.encode(presented.token), "HKDF", false, ["deriveBits"]);returnnewUint8Array(await crypto.subtle.deriveBits({ name: "HKDF", hash: "SHA-256", salt: windowKey, info: utf8.encode(CARRIER_INFO + presented.hash) }, ikm, 256));}const carrierAad = (hash: string, memberId: string): string => `agent-carrier|${hash}|${memberId}`;/** S sealed for one token: opens only with that token's string (and WINDOW_KEY). */exportasyncfunction carry(windowKey: Uint8Array, presented: Presented, memberId: string, secret: Uint8Array): Promise<string> {const k = await carrierKey(windowKey, presented);try {returnawait sealSecret(k, carrierAad(presented.hash, memberId), secret); } finally { k.fill(0); }}// ── the policy and the statement (seal-core seal::agent) ─────────────────/** Does the person key sign this policy and wrap for this member key? */exportasyncfunction verifyAgentGrant(publicKey: string, databaseId: string, memberId: string, memberPub: string, g: { withheld: readonly string[]; wrapped: string; signer: string; sig: string }): Promise<boolean> {if (publicKey.slice(0, 8) !== g.signer) returnfalse;let statement: string;try { statement = await agentStatement(databaseId, memberId, memberPub, g.withheld, g.wrapped); } catch {returnfalse; }return verifySig(publicKey, g.sig, statement);}// ── reading args ─────────────────────────────────────────────────────────function textArg(args: Record<string, unknown>, key: string, said: string): string {const v = args[key];returntypeof v === "string" && v ? v : refuse(400, "bad_args", said);}function tablesArg(args: Record<string, unknown>, key: string): string[] {const v = args[key];if (!Array.isArray(v) || v.some((t) => typeof t !== "string")) refuse(400, "bad_args", `${key} is a list of table ids`);return [...newSet((v as string[]).map((t) => plain("table", t)))].sort();}function list(row: StoredRow | null | undefined, key: string): string[] {const v = row?.data[key];returnArray.isArray(v) ? (v as string[]) : [];}// ── the object's side ────────────────────────────────────────────────────exporttypeMemberRow = { id: string; pub: string; name: string; made_by: string; created_at: string;};/** What assistant_allow checked before its transaction. */exportinterfacePreparedAgentAllow { request: StoredRow | null; grant: StoredRow | null; memberId: string; memberPub: string; withheld: string[]; tables: string[]; wrapped: string; wrappedSha256: string; signer: string; sig: string;/** Connect Claude: S sealed under WINDOW_KEY, waiting for its connection. */ pending: string | null; name: string;}exportclassAgents {// ── members and carriers ── member(host: Pick<WindowHost, "sql">, id: string): MemberRow | null {return host.sql.exec<MemberRow>("SELECT id, pub, name, made_by, created_at FROM agent_member WHERE id = ?", id).toArray()[0] ?? null; } members(host: Pick<WindowHost, "sql">): MemberRow[] {return host.sql.exec<MemberRow>("SELECT id, pub, name, made_by, created_at FROM agent_member ORDER BY created_at").toArray(); }/** The member a presented token carries, opened for this call, or null (no carrier, or it does not open). */async opened(host: Pick<WindowHost, "sql" | "key">, presented: Presented): Promise<Opened | null> {if (!host.key) returnnull;const row = host.sql.exec<{ member_id: string; blob: string }>("SELECT member_id, blob FROM agent_carrier WHERE token_hash = ?", presented.hash).toArray()[0];if (!row) returnnull;const member = this.member(host, row.member_id);if (!member) returnnull;const k = await carrierKey(host.key, presented);const secret = await openSecret(k, carrierAad(presented.hash, row.member_id), row.blob); k.fill(0);if (!secret || secret.length !== 32) returnnull;return { memberId: row.member_id, secret, pub: fromBase64Url(member.pub) }; }private insertCarrier(host: Pick<WindowHost, "sql">, hash: string, memberId: string, blob: string): void { host.sql.exec("INSERT OR REPLACE INTO agent_carrier (token_hash, member_id, blob) VALUES (?, ?, ?)", hash, memberId, blob); } dropCarrier(host: Pick<WindowHost, "sql">, hash: string): void { host.sql.exec("DELETE FROM agent_carrier WHERE token_hash = ?", hash); }private insertMember(host: Pick<WindowHost, "sql">, id: string, pub: Uint8Array, name: string, madeBy: string, nowMs: number, pending: string | null = null): void { host.sql.exec("INSERT INTO agent_member (id, pub, name, made_by, created_at, pending, pending_until) VALUES (?, ?, ?, ?, ?, ?, ?)", id, toBase64Url(pub), name || "Claude", madeBy, iso(nowMs), pending, pending ? iso(nowMs + PENDING_MS) : null); }/** A pasted token (no OAuth connection) with no member becomes one on its first call. An OAuth token minted before members becomes one at its next refresh, so its refresh token carries S too. */async ensurePasted(host: Pick<WindowHost, "sql" | "key" | "store">, presented: Presented, tokenId: string, nowMs: number): Promise<void> {if (!host.key) return;const token = host.store.get("mcp_token", tokenId);if (!token || (typeof token.data.connection_id === "string" && token.data.connection_id)) return;if (host.sql.exec("SELECT 1 FROM agent_carrier WHERE token_hash = ?", presented.hash).toArray().length) return;const pair = await mintMember();const id = crypto.randomUUID();const blob = await carry(host.key, presented, id, pair.secret); pair.secret.fill(0);if (host.sql.exec("SELECT 1 FROM agent_carrier WHERE token_hash = ?", presented.hash).toArray().length) return;this.insertMember(host, id, pair.pub, String(token.data.name ?? ""), "token", nowMs);this.insertCarrier(host, presented.hash, id, blob); }/** A token minted by a token that carries S (a lane by the coordinator's): the same member. Answers the sealed carrier to insert once the mint is written, or null. */async inherit(host: Pick<WindowHost, "sql" | "key">, minter: Presented, minted: Presented): Promise<{ hash: string; memberId: string; blob: string } | null> {const opened = awaitthis.opened(host, minter);if (!opened || !host.key) returnnull;const blob = await carry(host.key, minted, opened.memberId, opened.secret); opened.secret.fill(0);return { hash: minted.hash, memberId: opened.memberId, blob }; }/** Write what `inherit` or the OAuth hooks prepared. */ place(host: Pick<WindowHost, "sql">, carriers: readonly { hash: string; memberId: string; blob: string }[]): void {for (const c of carriers) this.insertCarrier(host, c.hash, c.memberId, c.blob); }/** * An OAuth code redeemed: a member for the new connection, carried by its * access and refresh tokens. A member Connect Claude left waiting (and not * past its time) is claimed: its S moves into the carriers and the waiting * copy is deleted. */async redeemed(host: Pick<WindowHost, "sql" | "key">, access: Presented, refresh: Presented, clientName: string, nowMs: number, redirect: string | null = null): Promise<(() => void) | null> {if (!host.key) returnnull;// AUDIT C 5: the grant the owner just signed goes only to Claude: a connection whose code went back to Claude's own// host. Any other client redeeming in the window (a phish on the real sign-in page) is a fresh member, with a card.const waiting = !claudeRedirect(redirect) ? undefined : host.sql.exec<{ id: string; pending: string }>("SELECT id, pending FROM agent_member WHERE pending IS NOT NULL AND pending_until > ? ORDER BY created_at LIMIT 1", iso(nowMs)).toArray()[0];let id: string;let secret: Uint8Array | null = null;let fresh: Uint8Array | null = null;if (waiting) { secret = await openSecret(host.key, pendingAad(waiting.id), waiting.pending); id = waiting.id; }if (!secret) {const pair = await mintMember(); secret = pair.secret; fresh = pair.pub; id = crypto.randomUUID(); }const a = await carry(host.key, access, id!, secret);const r = await carry(host.key, refresh, id!, secret); secret.fill(0);return () => {if (fresh) this.insertMember(host, id, fresh, clientName, "oauth", nowMs);else host.sql.exec("UPDATE agent_member SET pending = NULL, pending_until = NULL, name = ? WHERE id = ?", clientName || "Claude", id);this.insertCarrier(host, access.hash, id, a);this.insertCarrier(host, refresh.hash, id, r); }; }/** An OAuth refresh: S opened from the presented refresh token's carrier and carried into the new pair; null when that token carried none (a connection made before members: it becomes one now). */async refreshed(host: Pick<WindowHost, "sql" | "key">, presented: Presented, access: Presented, refresh: Presented, clientName: string, nowMs: number): Promise<(() => void) | null> {if (!host.key) returnnull;const opened = awaitthis.opened(host, presented);if (!opened) returnthis.redeemedFresh(host, access, refresh, clientName, nowMs);const a = await carry(host.key, access, opened.memberId, opened.secret);const r = await carry(host.key, refresh, opened.memberId, opened.secret); opened.secret.fill(0);return () => {this.insertCarrier(host, access.hash, opened.memberId, a);this.insertCarrier(host, refresh.hash, opened.memberId, r);this.dropCarrier(host, presented.hash); }; }/** A legacy connection's first refresh: a new member, never a waiting one (Connect Claude waits for a new connection). */privateasync redeemedFresh(host: Pick<WindowHost, "sql" | "key">, access: Presented, refresh: Presented, clientName: string, nowMs: number): Promise<(() => void) | null> {const key = host.key!;const pair = await mintMember();const id = crypto.randomUUID();const a = await carry(key, access, id, pair.secret);const r = await carry(key, refresh, id, pair.secret); pair.secret.fill(0);return () => {this.insertMember(host, id, pair.pub, clientName, "oauth", nowMs);this.insertCarrier(host, access.hash, id, a);this.insertCarrier(host, refresh.hash, id, r); }; }// ── grants ──/** The member's live account grant, or null. */ grantOf(store: WindowHost["store"], memberId: string): StoredRow | null {return store.list(GRANT_TABLE, { column: "member_id", equals: memberId }).find((g) => g.data.account === true && !g.data.ended_at) ?? null; }/** Is `table` off for this member: switched off, or withheld by its own signed policy? */ offFor(store: WindowHost["store"], memberId: string | null, table: string): boolean {if (this.access(store, table) === "off") returntrue;const mine = memberId ? this.grantOf(store, memberId) : null;return !!mine && !NEVER.includes(table) && list(mine, "withheld").includes(table) && !list(mine, "ask").includes(table); }/** Every live account grant, newest first: the newest says the person's settings. */ liveGrants(store: WindowHost["store"]): StoredRow[] {return [...store.scan(GRANT_TABLE)].filter((g) => g.data.account === true && !g.data.ended_at).sort((a, b) => String(b.data.granted_at).localeCompare(String(a.data.granted_at)) || b.id.localeCompare(a.id)); }/** How the person set a table: on, ask each time, or off (the newest live grant says; with none, on). NEVER tables ask each time (today's timed card); a table left off on the card is off. */ access(store: WindowHost["store"], table: string): Access {if (closed(table)) return"off";const g = this.liveGrants(store)[0];if (NEVER.includes(table) || list(g, "ask").includes(table)) return"ask";// Left off on the card (the signed policy withholds it) is off, as switched off since.if (list(g, "off").includes(table) || list(g, "withheld").includes(table)) return"off";return"on"; }/** * The keys this member's grant holds for `table`, or null: the grant live, * the table neither withheld nor narrowed away, and a wrap opening to it * with the member's private half. `cache` keeps the opened bundles for the * one call that presented the token; nothing outlives it. */async keys(host: WindowHost, opened: Opened, table: string, cache: Map<string, Map<string, { tk: Map<number, Uint8Array>; bk: Uint8Array; files?: Uint8Array }>>): Promise<TableKeys | null> {if (closed(table)) returnnull;const grant = this.grantOf(host.store, opened.memberId);if (!grant) returnnull;// The member's own signed policy, and the person's settings for every connection (the newest grant's).if (list(grant, "withheld").includes(table) || this.access(host.store, table) !== "on") returnnull;let held = cache.get(grant.id);if (!held) { held = newMap();const withheld = list(grant, "withheld");for (const w of host.sql.exec<{ wrapped: string }>("SELECT wrapped FROM agent_wrap WHERE grant_id = ? AND member_id = ? ORDER BY id", grant.id, opened.memberId).toArray()) {const plainText = await unwrap(opened.secret, opened.pub, w.wrapped);const bundle = plainText ? parseBundle(newTextDecoder().decode(plainText)) : null; plainText?.fill(0);if (!bundle || bundle.request_id !== opened.memberId || bundle.token_id !== opened.memberId) continue;if ([...bundle.keys.keys()].some((t) => withheld.includes(t))) continue;for (const [t, versions] of bundle.keys) {const bk = bundle.blind.get(t);if (!bk) continue;const into = held.get(t) ?? { tk: newMap<number, Uint8Array>(), bk };for (const [v, k] of versions) into.tk.set(v, k);// A message's kept chat pictures' root (grant.rs `files`), from a wrap made since 22 Nov 2026.const files = bundle.files.get(t);if (files) into.files = files; held.set(t, into); } } cache.set(grant.id, held); }const found = held.get(table);return found ? { table, grant_id: grant.id, standing: true, tk: found.tk, bk: found.bk, ...(found.files ? { files: found.files } : {}), ends_at: STANDING_ENDS } : null; }/** What `open()` says of the account grant: the tables it reads now. */ open(host: Pick<WindowHost, "store">, memberId: string): { tables: string[]; ends_at: string; standing: boolean }[] {const g = this.grantOf(host.store, memberId);if (!g) return [];const narrowed = newSet([...list(g, "withheld"), ...list(g, "off"), ...list(g, "ask"), ...NEVER, ...CLOSED]);return [{ tables: list(g, "tables").filter((t) => !narrowed.has(t)), ends_at: STANDING_ENDS, standing: true }]; }/** * A member with no grant asks: the one card, naming every sealed table in * scope (`sealed`, the database's sealed tables; NEVER left out). A waiting * card of this member is answered again. Null when this is not the card's * to answer: the member has a grant, or nothing asked is in scope (an ask * table, a NEVER table), and the timed window asks instead. */ request(host: WindowHost, opened: Pick<Opened, "memberId">, client: string, tokenId: string, asked: readonly string[], sealed: readonly string[], nowMs: number): StoredRow | null {const scope = sealed.filter((t) => !NEVER.includes(t) && !closed(t));if (!asked.some((t) => scope.includes(t))) returnnull;if (this.grantOf(host.store, opened.memberId)) returnnull;const now = iso(nowMs);const same = host.store.list(REQUEST_TABLE, { column: "member_id", equals: opened.memberId }).find((r) => r.data.account === true && r.data.state === "waiting" && String(r.data.expires_at) > now);if (same) return same;const lastHour = [...host.store.scan(REQUEST_TABLE)].filter((r) => String(r.data.requested_at) > iso(nowMs - 3_600_000)).length;if (lastHour >= REQUESTS_PER_HOUR) refuse(429, "too_many_requests", `this database took ${REQUESTS_PER_HOUR} unlock requests in the last hour: ask again later`);const member = this.member(host, opened.memberId)!;return host.write((engine, version, outcome) => engine.create( REQUEST_TABLE, { token_id: tokenId, connection_id: memberConnection(opened.memberId), token_name: member.name, client: client || member.name || "Claude", tables: [...scope].sort(), reason: "Let your Claude read your data", minutes: STANDING, worker_pub: member.pub, requested_at: now,// The one card stands until the owner answers it: it opens nothing by itself, and the owner may open an app hours later. expires_at: STANDING_ENDS, state: "waiting", account: true, member_id: opened.memberId, member_pub: member.pub, connected_at: member.created_at, ...askerOf(host.store, tokenId), }, version, outcome, ), ); }/** * `assistant_allow`'s checks, before its transaction. Three shapes, one * statement: `{request_id}` answers the card; `{grant_id}` re-signs a live * grant (widening it); `{member_id, member_secret}` is Connect Claude, the * phone's own pair, waiting for its connection. */async prepareAllow(host: WindowHost, args: Record<string, unknown>, nowMs: number): Promise<PreparedAgentAllow> {if (!host.key) refuse(503, "window_unavailable", "this Worker holds no WINDOW_KEY: no grant can be made, and nothing is answered in the clear");const withheld = policy(tablesArg(args, "withheld"));const tables = tablesArg(args, "tables").filter((t) => !withheld.includes(t));if (!tables.length) refuse(400, "bad_args", "a grant hands at least one table's keys");const wrapped = textArg(args, "wrapped", 'wrapped is the "w1:" wrap of the keys to the member key');if (!wrapped.startsWith("w1:")) refuse(400, "bad_args", 'wrapped is the "w1:" wrap of the keys to the member key');const signer = textArg(args, "signer", "signer is the person key's fingerprint");const sig = textArg(args, "sig", "sig is the Ed25519 signature, base64url");let request: StoredRow | null = null;let grant: StoredRow | null = null;let memberId: string;let memberPub: string;let pending: string | null = null;let name = "Claude";if (typeof args.request_id === "string" && args.request_id) { request = host.store.get(REQUEST_TABLE, args.request_id) ?? refuse(404, "no_such_request", `no unlock request ${args.request_id}`);if (request.data.account !== true) refuse(400, "not_account", `unlock request ${request.id} is a timed window's: answer it with unlock_allow`);if (request.data.state !== "waiting") refuse(409, "request_answered", `unlock request ${request.id} is ${String(request.data.state)} already`);if (String(request.data.expires_at) <= iso(nowMs)) refuse(410, "request_expired", `unlock request ${request.id} expired at ${String(request.data.expires_at)}: the assistant asks again`); memberId = String(request.data.member_id); memberPub = String(request.data.member_pub); name = String(request.data.client || "Claude"); } elseif (typeof args.grant_id === "string" && args.grant_id) { grant = host.store.get(GRANT_TABLE, args.grant_id) ?? refuse(404, "no_such_grant", `no grant ${args.grant_id}`);if (grant.data.account !== true || grant.data.ended_at) refuse(409, "grant_ended", `grant ${grant.id} is not a live grant to your Claude`); memberId = String(grant.data.member_id); memberPub = String(grant.data.member_pub); } else { memberId = textArg(args, "member_id", "request_id, grant_id, or member_id with member_secret"); plain("member", memberId);if (this.member(host, memberId)) refuse(409, "member_exists", `member ${memberId} is made already`);const secret = fromBase64Url(textArg(args, "member_secret", "member_secret is the member key's private half, base64url"));if (secret.length !== 32) refuse(400, "bad_args", "member_secret is 32 bytes"); memberPub = toBase64Url(await publicOf(secret));// The object has S here, so it checks the wrap opens to what is claimed.const plainText = await unwrap(secret, fromBase64Url(memberPub), wrapped);const bundle = plainText ? parseBundle(newTextDecoder().decode(plainText)) : null; plainText?.fill(0);if (!bundle || bundle.request_id !== memberId || [...bundle.keys.keys()].sort().join(",") !== tables.join(",")) refuse(400, "grant_does_not_open", "the wrap does not open to this member's keys for these tables"); pending = await sealSecret(host.key, pendingAad(memberId), secret); secret.fill(0); name = typeof args.name === "string" && args.name.trim() ? args.name.trim().slice(0, 60) : "Claude"; }const publicKey = host.personKey(signer) ?? refuse(409, "no_person_key", `this database holds no person key ${signer} to check the grant against`);if (!(await verifyAgentGrant(publicKey, host.databaseId, memberId, memberPub, { withheld, wrapped, signer, sig }))) refuse(403, "bad_signature", "the signature does not hold for this grant under the person key");return { request, grant, memberId, memberPub, withheld, tables, wrapped, wrappedSha256: await sha256Hex(wrapped), signer, sig, pending, name }; }/** `assistant_allow` in its transaction. */ applyAllow(host: WindowHost, engine: Engine, p: PreparedAgentAllow, nowMs: number, version: number, outcome: Outcome): { grant: string; member: string } {const now = iso(nowMs);if (p.grant) {const g = host.store.get(GRANT_TABLE, p.grant.id);if (!g || g.data.ended_at) refuse(409, "grant_ended", `grant ${p.grant.id} ended meanwhile`);const tables = [...newSet([...list(g, "tables"), ...p.tables])].sort();// Widening: the newly signed policy; what was set ask or off and is now granted is on again. engine.update(g, { withheld: p.withheld, tables, ask: list(g, "ask").filter((t) => !p.tables.includes(t)), off: list(g, "off").filter((t) => !p.tables.includes(t)), wrapped_sha256: p.wrappedSha256, signer: p.signer, sig: p.sig }, version, outcome); host.sql.exec("INSERT INTO agent_wrap (grant_id, member_id, wrapped, added_at) VALUES (?, ?, ?, ?)", g.id, p.memberId, p.wrapped, now);return { grant: g.id, member: p.memberId }; }if (p.pending) this.insertMember(host, p.memberId, fromBase64Url(p.memberPub), p.name, "phone", nowMs, p.pending);if (this.grantOf(host.store, p.memberId)) refuse(409, "request_answered", `your Claude's connection ${p.memberId} holds a grant already`);let requestId = `connect:${p.memberId}`;if (p.request) {const r = host.store.get(REQUEST_TABLE, p.request.id);if (!r || r.data.state !== "waiting") refuse(409, "request_answered", `unlock request ${p.request.id} was answered meanwhile`); engine.update(r, { state: "granted" }, version, outcome); requestId = r.id; }// Every account grant shares the person's settings: a new connection takes the ones that stand.const standing = this.liveGrants(host.store)[0];const made = engine.create( GRANT_TABLE, { request_id: requestId, token_id: p.memberId, connection_id: memberConnection(p.memberId), client: p.name, standing: true, tables: p.tables, minutes: STANDING, wrapped_sha256: p.wrappedSha256, signer: p.signer, sig: p.sig, granted_at: now, ends_at: STANDING_ENDS, account: true, member_id: p.memberId, member_pub: p.memberPub, withheld: p.withheld, ask: list(standing, "ask"), off: list(standing, "off"), }, version, outcome, ); outcome.made = made; host.sql.exec("INSERT INTO agent_wrap (grant_id, member_id, wrapped, added_at) VALUES (?, ?, ?, ?)", made.id, p.memberId, p.wrapped, now);return { grant: made.id, member: p.memberId }; }/** `assistant_add { grant_id, tables, wrapped }`: more keys inside the signed policy, unsigned (a wrap only the member key opens; a table the policy withholds is refused). */ add(host: WindowHost, engine: Engine, args: Record<string, unknown>, nowMs: number, version: number, outcome: Outcome): void {const grant = host.store.get(GRANT_TABLE, textArg(args, "grant_id", "grant_id is your Claude's grant")) ?? refuse(404, "no_such_grant", "no such grant");if (grant.data.account !== true || grant.data.ended_at) refuse(409, "grant_ended", `grant ${grant.id} is not a live grant to your Claude`);const tables = tablesArg(args, "tables");if (!tables.length) refuse(400, "bad_args", "an addition hands at least one table's keys");const withheld = list(grant, "withheld");const shut = tables.find(closed);if (shut) refuse(403, "closed", `${shut} is never given to an assistant`);const stray = tables.find((t) => withheld.includes(t) || NEVER.includes(t));if (stray) refuse(403, "withheld", `${stray} is withheld from your Claude: widening is signed (assistant_allow with grant_id)`);const wrapped = textArg(args, "wrapped", 'wrapped is the "w1:" wrap of the keys to the member key');if (!wrapped.startsWith("w1:")) refuse(400, "bad_args", 'wrapped is the "w1:" wrap of the keys to the member key'); host.sql.exec("INSERT INTO agent_wrap (grant_id, member_id, wrapped, added_at) VALUES (?, ?, ?, ?)", grant.id, String(grant.data.member_id), wrapped, iso(nowMs)); engine.update(grant, { tables: [...newSet([...list(grant, "tables"), ...tables])].sort() }, version, outcome); }/** `assistant_scope { table, access }`: off or ask narrows every live grant at once; on is refused while the signed policy withholds it. */ scope(host: WindowHost, engine: Engine, args: Record<string, unknown>, version: number, outcome: Outcome): { table: string; access: Access } {const table = plain("table", textArg(args, "table", "table is a sealed table's id"));const access = args.access;if (access !== "on" && access !== "ask" && access !== "off") refuse(400, "bad_args", "access is on, ask or off");if (closed(table) && access !== "off") refuse(403, "closed", `${table} is never given to an assistant`);if (NEVER.includes(table) && access === "on") refuse(403, "never", `${table} keeps saved secrets: no assistant reads it standing`);const grants = this.liveGrants(host.store);if (!grants.length) refuse(409, "no_grant", "your Claude holds no grant: connect it first");for (const g of grants) {if (access === "on" && list(g, "withheld").includes(table)) refuse(409, "needs_signature", `${table} was left out when you allowed your Claude: turning it on is signed on your phone (assistant_allow with grant_id)`);const ask = list(g, "ask").filter((t) => t !== table);const off = list(g, "off").filter((t) => t !== table);if (access === "ask") ask.push(table);if (access === "off") off.push(table); engine.update(g, { ask: ask.sort(), off: off.sort() }, version, outcome); }return { table, access }; }/** `assistant_remove {}`: every account grant ends (ended_by phone) and every wrap goes; the phone moves those tables to fresh keys. Members and their carriers stay: the next sealed read files the one card again. */ remove(host: WindowHost, engine: Engine, nowMs: number, version: number, outcome: Outcome): number {let ended = 0;for (const g ofthis.liveGrants(host.store)) { engine.update(g, { ended_at: iso(nowMs), ended_by: "phone" }, version, outcome); ended++; } host.sql.exec("DELETE FROM agent_wrap"); host.sql.exec("UPDATE agent_member SET pending = NULL, pending_until = NULL WHERE pending IS NOT NULL");return ended; }/** When a waiting Connect Claude copy is next due to go, in ms, or null: the alarm comes then. */ nextDue(host: Pick<WindowHost, "sql">): number | null {const at = host.sql.exec<{ at: string | null }>("SELECT MIN(pending_until) AS at FROM agent_member WHERE pending IS NOT NULL").one().at;return at ? Date.parse(at) : null; }/** The clean-up: wraps of ended grants, waiting members past their time (the member goes with its unused copy), carriers whose token is gone. */ sweep(host: Pick<WindowHost, "sql" | "store">, nowMs: number): void {for (const w of host.sql.exec<{ grant_id: string }>("SELECT DISTINCT grant_id FROM agent_wrap").toArray()) {const g = host.store.get(GRANT_TABLE, w.grant_id);if (!g || g.data.ended_at) host.sql.exec("DELETE FROM agent_wrap WHERE grant_id = ?", w.grant_id); } host.sql.exec("UPDATE agent_member SET pending = NULL, pending_until = NULL WHERE pending IS NOT NULL AND pending_until <= ?", iso(nowMs)); }}