Cotton code
640 lines · 45.5 KB · TypeScriptRaw
/** * Your Claude's standing grant on the Worker (src/agent.ts): * one card per member, granted standing; the keys wrapped to a * member key that only the connection's tokens carry; lanes inherit their * minter's member; OAuth refreshes carry it on; Remove ends it for every * token. Every key is made here or is seal-core's vector; every row is * synthetic. */import { env, runInDurableObject, SELF } from "cloudflare:test";import { beforeAll, describe, expect, it } from "vitest";import vector from "../../../crates/cotton-conformance/vectors/seal/agent_grant.json";import { agentStatement, policy, publicOf, verifyAgentGrant } from "../src/agent.ts";import type { Business } from "../src/business.ts";import { blindKey, bodyAad, bucket, dekAad, tableKey, textTokens } from "../src/seal.ts";import { tableFileRoot } from "../src/table_files.ts";import { fromBase64Url, toBase64Url } from "../src/vault.ts";import { openSecret, parseBundle, unlockStatement, unwrap } from "../src/window.ts";import { ADMIN, DATABASE_ID, http, mint, OWNER_PHONE, PERSONAL_TABLES, PERSONAL_TOOLS, publishPersonKey, tool, windowsOnly, type ToolResult } from "./personal.ts";const utf8 = new TextEncoder();const hex = (h: string): Uint8Array => Uint8Array.from(h.match(/../g)!.map((b) => parseInt(b, 16)));const PERSON_SEED = new Uint8Array(32).fill(7);const X25519_PKCS8 = hex("302e020100300506032b656e04220420");const ED25519_PKCS8 = hex("302e020100300506032b657004220420");const DIARY = {  format_version: 1,  id: "sealed_diary",  name: "Sealed diary",  plural: "Sealed diaries",  title: "body",  date: "written_at",  columns: [    { key: "written_at", type: "date" },    { key: "body", type: "longtext", required: true },    { key: "trashed_at", type: "date" },  ],  seal: { clear: ["written_at", "trashed_at"], blind: ["body"] },};// ── the phone's half, mirrored from seal-core (seal::agent, grant.rs, wrap.rs, row.rs) ──async function okp(prefix: Uint8Array, secret: Uint8Array, name: "X25519" | "Ed25519", uses: string[]): Promise<{ key: CryptoKey; pub: Uint8Array }> {  const pkcs8 = new Uint8Array(48);  pkcs8.set(prefix);  pkcs8.set(secret, 16);  const key = await crypto.subtle.importKey("pkcs8", pkcs8, { name }, true, uses as Parameters<typeof crypto.subtle.importKey>[4]);  const jwk = (await crypto.subtle.exportKey("jwk", key)) as JsonWebKey;  return { key, pub: fromBase64Url(jwk.x!) };}async function wrapWith(ephemeral: Uint8Array, nonce: Uint8Array, recipientPub: Uint8Array, plain: Uint8Array): Promise<string> {  const eph = await okp(X25519_PKCS8, ephemeral, "X25519", ["deriveBits"]);  const peer = await crypto.subtle.importKey("raw", recipientPub, { name: "X25519" }, false, []);  const shared = new Uint8Array(await crypto.subtle.deriveBits({ name: "X25519", public: peer } as unknown as SubtleCryptoDeriveKeyAlgorithm, eph.key, 256));  const salt = new Uint8Array(64);  salt.set(eph.pub);  salt.set(recipientPub, 32);  const ikm = await crypto.subtle.importKey("raw", shared, "HKDF", false, ["deriveBits"]);  const k = await crypto.subtle.importKey("raw", await crypto.subtle.deriveBits({ name: "HKDF", hash: "SHA-256", salt, info: utf8.encode("cotton-vault-wrap-v1") }, ikm, 256), "AES-GCM", false, ["encrypt"]);  const body = new Uint8Array(await crypto.subtle.encrypt({ name: "AES-GCM", iv: nonce, additionalData: recipientPub }, k, plain));  const out = new Uint8Array(32 + 12 + body.length);  out.set(eph.pub);  out.set(nonce, 32);  out.set(body, 44);  return `w1:${toBase64Url(out)}`;}function canonical(v: unknown): string {  if (v && typeof v === "object" && !Array.isArray(v)) {    const o = v as Record<string, unknown>;    return `{${Object.keys(o).sort().map((k) => `${JSON.stringify(k)}:${canonical(o[k])}`).join(",")}}`;  }  return JSON.stringify(v);}/** The keys of `tables` (every version up to each one's), as the bundle names them for a member. */async function bundleOf(dk: Uint8Array, memberId: string, tables: [string, number][]): Promise<string> {  const keys: Record<string, Record<string, string>> = {};  const blind: Record<string, string> = {};  for (const [t, v] of tables) {    keys[t] = {};    for (let n = 1; n <= v; n++) keys[t]![String(n)] = toBase64Url(await tableKey(dk, DATABASE_ID, t, n));    blind[t] = toBase64Url(await blindKey(dk, DATABASE_ID, t));  }  // grant.rs: a bundle naming message carries the message table's files root (a kept chat picture opens with it).  const files = keys.message ? { files: { message: toBase64Url(await tableFileRoot(dk, DATABASE_ID, "message")) } } : {};  return canonical({ request_id: memberId, token_id: memberId, keys, blind, ...files });}/** `seal::agent::build_agent_grant`: wrapped to the member key, the policy signed. */async function agentGrant(o: { dk: Uint8Array; memberId: string; memberPub: string; tables: [string, number][]; withheld?: string[]; seed?: Uint8Array; ephemeral?: Uint8Array; nonce?: Uint8Array }): Promise<{ tables: string[]; withheld: string[]; wrapped: string; signer: string; sig: string }> {  const withheld = policy(o.withheld ?? []);  const wrapped = await wrapWith(o.ephemeral ?? crypto.getRandomValues(new Uint8Array(32)), o.nonce ?? crypto.getRandomValues(new Uint8Array(12)), fromBase64Url(o.memberPub), utf8.encode(await bundleOf(o.dk, o.memberId, o.tables)));  const person = await okp(ED25519_PKCS8, o.seed ?? PERSON_SEED, "Ed25519", ["sign"]);  const statement = await agentStatement(DATABASE_ID, o.memberId, o.memberPub, withheld, wrapped);  const sig = toBase64Url(new Uint8Array(await crypto.subtle.sign({ name: "Ed25519" }, person.key, utf8.encode(statement))));  return { tables: o.tables.map(([t]) => t).sort(), withheld, wrapped, signer: toBase64Url(person.pub).slice(0, 8), sig };}async function gcm(key: Uint8Array, plain: Uint8Array, aad: string): Promise<string> {  const nonce = crypto.getRandomValues(new Uint8Array(12));  const k = await crypto.subtle.importKey("raw", key, "AES-GCM", false, ["encrypt"]);  const body = new Uint8Array(await crypto.subtle.encrypt({ name: "AES-GCM", iv: nonce, additionalData: utf8.encode(aad) }, k, plain));  const out = new Uint8Array(12 + body.length);  out.set(nonce);  out.set(body, 12);  return toBase64Url(out);}async function sealRow(dk: Uint8Array, id: string, v: number, sealed: Record<string, unknown>, table = DIARY.id): Promise<Record<string, unknown>> {  const text = canonical(sealed);  const padded = text + " ".repeat(bucket(utf8.encode(text).length) - utf8.encode(text).length);  const dek = crypto.getRandomValues(new Uint8Array(32));  return {    sealed_enc: `s1:${await gcm(dek, utf8.encode(padded), bodyAad(DATABASE_ID, table, id))}`,    dek_enc: `d1:${await gcm(await tableKey(dk, DATABASE_ID, table, v), dek, dekAad(DATABASE_ID, table, id, v))}`,    seal_v: v,  };}// ── the object ─────────────────────────────────────────────────────────const stub = (slug: string) => env.BUSINESS.get(env.BUSINESS.idFromName(slug));async function act(slug: string, credential: string, name: string, args: Record<string, unknown>): Promise<{ status: number; body: Record<string, unknown> }> {  return http(slug, "POST", "/v1/act", { act: name, args }, { authorization: `Bearer ${credential}` });}async function object(slug: string, o: { tables?: Record<string, unknown>[]; grant?: boolean } = {}): Promise<{ credential: string; owner: string }> {  expect((await http(slug, "PUT", "/v1/admin/business", { name: "Personal", kind: "personal", owner_phone: OWNER_PHONE, database_id: DATABASE_ID, timezone: "Asia/Kolkata" }, ADMIN)).status).toBe(200);  const defs = await http(slug, "PUT", "/v1/admin/definitions", { tools: PERSONAL_TOOLS, tables: [...PERSONAL_TABLES, ...(o.tables ?? [DIARY])], flavour: { flavour: "personal" } }, ADMIN);  expect(defs.status, JSON.stringify(defs.body)).toBe(200);  const code = await http<{ challenge_id: string }>(slug, "POST", "/v1/code", { phone: OWNER_PHONE, device_id: "phone" });  const signed = await http<{ credential: string }>(slug, "POST", "/v1/sign-in", { challenge_id: code.body.challenge_id, code: "123456", device_id: "phone" });  expect(signed.status, JSON.stringify(signed.body)).toBe(200);  await publishPersonKey(slug, signed.body.credential, vector.person_public_key);  // The standing grant answers on this object as on the dev Worker.  // The grant is on Worker-wide (wrangler.jsonc); `grant: false` keeps this object on timed windows until grantOn.  if (o.grant === false) await windowsOnly(slug);  else await grantOn(slug);  return { credential: signed.body.credential, owner: await mint(slug, signed.body.credential, "coordinator (mac-c)", ["owner"]) };}/** The standing grant answers on this object as on the dev Worker (and, since 21 Nov, the live one). */async function grantOn(slug: string): Promise<void> {  await runInDurableObject(stub(slug), (instance: Business) => (instance as unknown as { store: { setMeta(k: string, v: string): void } }).store.setMeta("agent_grant", "on"));}async function rowOf(slug: string, table: string, id: string): Promise<Record<string, unknown>> {  return runInDurableObject(stub(slug), (_i, state) => JSON.parse(state.storage.sql.exec<{ data: string }>("SELECT data FROM rows WHERE table_id = ? AND id = ?", table, id).one().data) as Record<string, unknown>);}async function count(slug: string, sql: string, ...args: unknown[]): Promise<number> {  return runInDurableObject(stub(slug), (_i, state) => Number(state.storage.sql.exec<{ n: number }>(sql, ...args).one().n));}async function everything(slug: string): Promise<string> {  return runInDurableObject(stub(slug), (_i, state) => {    const tables = state.storage.sql.exec<{ name: string }>("SELECT name FROM sqlite_master WHERE type = 'table'").toArray().map((t) => t.name).filter((t) => !t.startsWith("_cf_") && !t.startsWith("sqlite_"));    return JSON.stringify(tables.map((t) => state.storage.sql.exec(`SELECT * FROM "${t}"`).toArray()));  });}function parsed(r: ToolResult): Record<string, unknown> {  expect(r.isError, r.content[0]?.text).toBe(false);  return JSON.parse(r.content[0]!.text) as Record<string, unknown>;}function code(r: ToolResult): unknown {  expect(r.isError, r.content[0]?.text).toBe(true);  return r.structuredContent?.code;}async function sha256(text: string): Promise<string> {  return [...new Uint8Array(await crypto.subtle.digest("SHA-256", utf8.encode(text)))].map((b) => b.toString(16).padStart(2, "0")).join("");}// ── tests ──────────────────────────────────────────────────────────────/** RULE (seal-core seal::agent vector): the statement and the signature are seal-core's to the byte. */describe("the agent grant against seal-core's vector", () => {  it("builds the vector's statement, verifies its signature, and opens its wrap with the member secret", async () => {    expect(policy(["money_entry"])).toEqual(vector.withheld);    expect(await agentStatement(vector.database_id, vector.member_id, vector.member_pub, vector.withheld, vector.wrapped)).toBe(vector.statement);    const g = { withheld: vector.withheld, wrapped: vector.wrapped, signer: vector.signer, sig: vector.sig };    expect(await verifyAgentGrant(vector.person_public_key, vector.database_id, vector.member_id, vector.member_pub, g)).toBe(true);    // Another member key, a wider policy, or another member: not what the person signed.    expect(await verifyAgentGrant(vector.person_public_key, vector.database_id, vector.member_id, toBase64Url(await publicOf(new Uint8Array(32).fill(11))), g)).toBe(false);    expect(await verifyAgentGrant(vector.person_public_key, vector.database_id, vector.member_id, vector.member_pub, { ...g, withheld: policy([]) })).toBe(false);    expect(await verifyAgentGrant(vector.person_public_key, vector.database_id, "mem-2", vector.member_pub, g)).toBe(false);    expect(toBase64Url(await publicOf(hex(vector.member_secret_hex)))).toBe(vector.member_pub);    const plain = await unwrap(hex(vector.member_secret_hex), fromBase64Url(vector.member_pub), vector.wrapped);    expect(new TextDecoder().decode(plain!)).toBe(vector.bundle);    // The wrap is the phone's to the byte: rebuilt from the vector's fixed keys.    const rebuilt = await agentGrant({ dk: hex(vector.dk_hex), memberId: vector.member_id, memberPub: vector.member_pub, tables: vector.tables.map((t) => [t.table, t.seal_v] as [string, number]), withheld: ["money_entry"], ephemeral: hex(vector.ephemeral_hex), nonce: hex(vector.nonce_hex) });    expect(rebuilt.wrapped).toBe(vector.wrapped);    expect(rebuilt.sig).toBe(vector.sig);  });});/** RULE (owner, 20 Nov 2026): connecting Claude is the grant. One card per connection, then no timer and no card per token; Remove ends it for every token. */describe("Your Claude's standing grant on the object", () => {  const slug = "agent-grant";  const dk = crypto.getRandomValues(new Uint8Array(32));  let credential = "";  let owner = "";  let lane = "";  let entry = "";  let requestId = "";  let memberId = "";  let memberPub = "";  let grantId = "";  beforeAll(async () => {    ({ credential, owner } = await object(slug));    entry = crypto.randomUUID();    const sealed = { body: "Zanzibar spice market at dawn" };    const made = await act(slug, credential, "create", { table: DIARY.id, id: entry, data: { written_at: "2026-11-01", ...(await sealRow(dk, entry, 1, sealed)) }, blind: [...new Set(await textTokens(await blindKey(dk, DATABASE_ID, DIARY.id), "body", sealed.body))] });    expect(made.status, JSON.stringify(made.body)).toBe(200);  }, 120_000);  it("files ONE card for a connection with no grant, naming every sealed table but saved secrets, with no window key kept", async () => {    const first = await tool(slug, owner, "get_record_by_table", { table: DIARY.id, id: entry });    expect(code(first)).toBe("window_needed");    requestId = String(first.structuredContent!.request_id);    const request = await rowOf(slug, "unlock_request", requestId);    expect(request).toMatchObject({ account: true, state: "waiting", minutes: 0, client: "coordinator (mac-c)" });    memberId = String(request.member_id);    memberPub = String(request.member_pub);    expect(request.worker_pub).toBe(memberPub);    const tables = request.tables as string[];    expect(tables).toContain(DIARY.id);    for (const never of ["secret", "passkey", "code_credential"]) expect(tables).not.toContain(never);    // No one-use key: the phone wraps to the member key, whose private half only the token carries.    expect(await count(slug, "SELECT COUNT(*) AS n FROM window_request_key")).toBe(0);    expect(await count(slug, "SELECT COUNT(*) AS n FROM agent_carrier WHERE member_id = ?", memberId)).toBe(1);    // Asking again answers the same card.    expect((await tool(slug, owner, "list_records", { table: DIARY.id })).structuredContent!.request_id).toBe(requestId);  });  it("a lane minted by that token is the same connection: one card covers it", async () => {    // A key's lane mint names no allow (it carries the minting key's: ADMIN KEYS 1b), so the helper's "all" is left out.    lane = await mint(slug, owner, "lane widgets", ["read", "lane:widgets"], 7, undefined, null);    expect(await count(slug, "SELECT COUNT(*) AS n FROM agent_carrier WHERE member_id = ?", memberId)).toBe(2);    expect((await tool(slug, lane, "get_record_by_table", { table: DIARY.id, id: entry })).structuredContent!.request_id).toBe(requestId);  });  it("refuses a signature over another member key, a token's own allow, and a grant naming saved secrets", async () => {    const swapped = await agentGrant({ dk, memberId, memberPub: toBase64Url(await publicOf(crypto.getRandomValues(new Uint8Array(32)))), tables: [[DIARY.id, 1]] });    expect((await act(slug, credential, "assistant_allow", { request_id: requestId, ...swapped })).body.code).toBe("bad_signature");    const real = await agentGrant({ dk, memberId, memberPub, tables: [[DIARY.id, 1]] });    // A grant is an access act: refused to every key at the one gate (ADMIN KEYS 1b).    expect((await act(slug, owner, "assistant_allow", { request_id: requestId, ...real })).body.code).toBe("access_act");    const secrets = await act(slug, credential, "assistant_allow", { request_id: requestId, ...real, tables: ["secret"] });    expect(secrets.status).toBe(400);    expect((await rowOf(slug, "unlock_request", requestId)).state).toBe("waiting");  });  it("the person's Allow is the standing grant: the token and its lane read, logged, with no timer and nothing more asked", async () => {    const g = await agentGrant({ dk, memberId, memberPub, tables: [[DIARY.id, 1]] });    const res = await act(slug, credential, "assistant_allow", { request_id: requestId, ...g });    expect(res.status, JSON.stringify(res.body)).toBe(200);    grantId = String(res.body.grant);    expect(await rowOf(slug, "unlock_grant", grantId)).toMatchObject({ account: true, standing: true, member_id: memberId, ends_at: "9999-12-31T23:59:59.999Z", tables: [DIARY.id], withheld: ["code_credential", "passkey", "secret"] });    for (const token of [owner, lane]) {      const read = parsed(await tool(slug, token, "get_record_by_table", { table: DIARY.id, id: entry }));      expect(JSON.stringify(read)).toContain("Zanzibar spice market at dawn");    }    expect(await count(slug, "SELECT COUNT(*) AS n FROM rows WHERE table_id = 'assistant_read' AND json_extract(data, '$.grant_id') = ?", grantId)).toBe(2);    // A lane started after the grant reads at once.    const later = await mint(slug, owner, "lane later", ["read", "lane:later"], 7, undefined, null);    expect(JSON.stringify(parsed(await tool(slug, later, "get_record_by_table", { table: DIARY.id, id: entry })))).toContain("Zanzibar");    expect(await count(slug, "SELECT COUNT(*) AS n FROM rows WHERE table_id = 'unlock_request'")).toBe(1);  });  it("keeps nothing at rest that opens a granted table: no table key, and no carrier WINDOW_KEY alone opens", async () => {    const all = await everything(slug);    expect(all).not.toContain(toBase64Url(await tableKey(dk, DATABASE_ID, DIARY.id, 1)));    expect(all).not.toContain("Zanzibar");    const carriers = await runInDurableObject(stub(slug), (_i, state) => state.storage.sql.exec<{ token_hash: string; blob: string }>("SELECT token_hash, blob FROM agent_carrier WHERE member_id = ?", memberId).toArray());    const windowKey = fromBase64Url(String(env.WINDOW_KEY));    for (const c of carriers) expect(await openSecret(windowKey, `agent-carrier|${c.token_hash}|${memberId}`, c.blob)).toBeNull();    // With the token string it opens, to the member key's private half.    const ikm = await crypto.subtle.importKey("raw", utf8.encode(owner), "HKDF", false, ["deriveBits"]);    const hash = await sha256(owner);    const k = new Uint8Array(await crypto.subtle.deriveBits({ name: "HKDF", hash: "SHA-256", salt: windowKey, info: utf8.encode(`cotton-agent-carrier-v1|${hash}`) }, ikm, 256));    const mine = carriers.find((c) => c.token_hash === hash)!;    const secret = await openSecret(k, `agent-carrier|${hash}|${memberId}`, mine.blob);    expect(toBase64Url(await publicOf(secret!))).toBe(memberPub);    // The act log says a wrap was handed, never the wrap.    const acts = await runInDurableObject(stub(slug), (_i, state) => JSON.stringify(state.storage.sql.exec("SELECT args FROM acts WHERE act = 'assistant_allow'").toArray()));    expect(acts).toContain("‹wrap›");  });  it("a new table inside the policy is added by the phone unsigned; a withheld one is refused", async () => {    const add = await wrapWith(crypto.getRandomValues(new Uint8Array(32)), crypto.getRandomValues(new Uint8Array(12)), fromBase64Url(memberPub), utf8.encode(await bundleOf(dk, memberId, [["note", 1]])));    expect((await act(slug, credential, "assistant_add", { grant_id: grantId, tables: ["note"], wrapped: add })).status).toBe(200);    expect((await rowOf(slug, "unlock_grant", grantId)).tables).toEqual(["note", DIARY.id].sort());    expect((await act(slug, credential, "assistant_add", { grant_id: grantId, tables: ["secret"], wrapped: add })).body.code).toBe("withheld");    expect((await act(slug, owner, "assistant_add", { grant_id: grantId, tables: ["note"], wrapped: add })).body.code).toBe("access_act");  });  it("never gives Sites' list to an assistant: no card offers it, no key is added for it, and every tool answers as if it were not there", async () => {    // The kit holds the sealed table; the card filed for this connection named every sealed table but it.    expect(PERSONAL_TABLES.some((t) => t.id === "site")).toBe(true);    expect((await rowOf(slug, "unlock_request", requestId)).tables as string[]).not.toContain("site");    const add = await wrapWith(crypto.getRandomValues(new Uint8Array(32)), crypto.getRandomValues(new Uint8Array(12)), fromBase64Url(memberPub), utf8.encode(await bundleOf(dk, memberId, [["site", 1]])));    expect((await act(slug, credential, "assistant_add", { grant_id: grantId, tables: ["site"], wrapped: add })).body.code).toBe("closed");    expect((await rowOf(slug, "unlock_grant", grantId)).tables as string[]).not.toContain("site");    for (const access of ["on", "ask"]) expect((await act(slug, credential, "assistant_scope", { table: "site", access })).body.code).toBe("closed");    for (const [name, args] of [["list_records", { table: "site" }], ["get_record_by_table", { table: "site", id: crypto.randomUUID() }], ["summarize_records", { table: "site" }]] as const) {      expect(code(await tool(slug, owner, name, args)), name).toBe("no_tool_draws_this_table");    }    const asked = await tool(slug, owner, "request_unlock", { tables: ["site"], reason: "invented" });    expect(asked.isError).toBe(true);    expect(await count(slug, "SELECT COUNT(*) AS n FROM rows WHERE table_id = 'unlock_request' AND data LIKE '%\"site\"%'")).toBe(0);  });  it("off refuses by name with nothing asked; ask hands the table to the timed window; on reads again", async () => {    expect((await act(slug, credential, "assistant_scope", { table: DIARY.id, access: "off" })).status).toBe(200);    expect(code(await tool(slug, owner, "get_record_by_table", { table: DIARY.id, id: entry }))).toBe("assistant_off");    expect((await act(slug, credential, "assistant_scope", { table: DIARY.id, access: "ask" })).status).toBe(200);    const asked = await tool(slug, owner, "get_record_by_table", { table: DIARY.id, id: entry });    expect(code(asked)).toBe("window_needed");    expect(await rowOf(slug, "unlock_request", String(asked.structuredContent!.request_id))).toMatchObject({ minutes: 15, tables: [DIARY.id] });    expect((await rowOf(slug, "unlock_request", String(asked.structuredContent!.request_id))).account).toBeUndefined();    expect((await act(slug, credential, "assistant_scope", { table: DIARY.id, access: "on" })).status).toBe(200);    expect(JSON.stringify(parsed(await tool(slug, owner, "get_record_by_table", { table: DIARY.id, id: entry })))).toContain("Zanzibar");    expect((await act(slug, credential, "assistant_scope", { table: "secret", access: "on" })).body.code).toBe("never");  });  it("a connection the phone did not make, a token minted on the phone, is its own: one card of its own", async () => {    const pasted = await mint(slug, credential, "Claude Desktop", ["owner"]);    const first = await tool(slug, pasted, "get_record_by_table", { table: DIARY.id, id: entry });    expect(code(first)).toBe("window_needed");    const request = await rowOf(slug, "unlock_request", String(first.structuredContent!.request_id));    expect(request.account).toBe(true);    expect(request.member_id).not.toBe(memberId);  });  it("revoking a lane drops its carrier; the grant stands for the rest", async () => {    const id = await runInDurableObject(stub(slug), async (_i, state) => state.storage.sql.exec<{ id: string }>("SELECT id FROM rows WHERE table_id = 'mcp_token' AND json_extract(data, '$.token_hash') = ?", await sha256(lane)).one().id);    expect((await act(slug, credential, "revoke_token", { id })).status).toBe(200);    expect(await count(slug, "SELECT COUNT(*) AS n FROM agent_carrier WHERE token_hash = ?", await sha256(lane))).toBe(0);    expect(JSON.stringify(parsed(await tool(slug, owner, "get_record_by_table", { table: DIARY.id, id: entry })))).toContain("Zanzibar");  });  it("a table left off on the card is off: refused by name, nothing asked", async () => {    // A second connection whose card left the diary off.    const desk = await mint(slug, credential, "Claude Desktop (left off)", ["owner"]);    const asked = await tool(slug, desk, "get_record_by_table", { table: DIARY.id, id: entry });    expect(code(asked)).toBe("window_needed");    const request = await rowOf(slug, "unlock_request", String(asked.structuredContent!.request_id));    const g = await agentGrant({ dk, memberId: String(request.member_id), memberPub: String(request.member_pub), tables: [["note", 1]], withheld: [DIARY.id] });    expect((await act(slug, credential, "assistant_allow", { request_id: request.id ?? asked.structuredContent!.request_id, ...g })).status).toBe(200);    // The newest live grant's settings stand for every connection: the diary is off now for the first one too.    expect(code(await tool(slug, desk, "get_record_by_table", { table: DIARY.id, id: entry }))).toBe("assistant_off");    expect(code(await tool(slug, owner, "get_record_by_table", { table: DIARY.id, id: entry }))).toBe("assistant_off");  });  it("Remove ends the grant for every token and drops every wrap; the next read files the one card again", async () => {    const res = await act(slug, credential, "assistant_remove", {});    expect(res.body).toMatchObject({ ended: 2 });    expect(await rowOf(slug, "unlock_grant", grantId)).toMatchObject({ ended_by: "phone" });    expect(await count(slug, "SELECT COUNT(*) AS n FROM agent_wrap")).toBe(0);    const again = await tool(slug, owner, "get_record_by_table", { table: DIARY.id, id: entry });    expect(code(again)).toBe("window_needed");    expect((await rowOf(slug, "unlock_request", String(again.structuredContent!.request_id))).account).toBe(true);  });});// ── OAuth: the connector's refresh carries the member on; Connect Claude ──const OAUTH = "agent-oauth";const BASE = `https://example.test/b/${OAUTH}`;const REDIRECT = "https://claude.ai/api/mcp/auth_callback";async function post(url: string, body: Record<string, string>): Promise<Response> {  return SELF.fetch(url, { method: "POST", redirect: "manual", headers: { "content-type": "application/x-www-form-urlencoded" }, body: new URLSearchParams(body).toString() });}function fields(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;}async function connect(clientId: string, base = BASE, redirect = REDIRECT): Promise<{ access: string; refresh: string }> {  const v = toBase64Url(crypto.getRandomValues(new Uint8Array(40)));  const challenge = toBase64Url(new Uint8Array(await crypto.subtle.digest("SHA-256", utf8.encode(v))));  const q = new URLSearchParams({ client_id: clientId, redirect_uri: redirect, response_type: "code", code_challenge: challenge, code_challenge_method: "S256", state: "st", scope: "owner", resource: `${base}/mcp` });  const start = await SELF.fetch(`${base}/oauth/authorize?${q}`, { redirect: "manual" });  const sent = await post(`${base}/oauth/authorize`, { ...fields(await start.text()), phone: OWNER_PHONE });  const done = await post(`${base}/oauth/authorize`, { ...fields(await sent.text()), code: "123456" });  expect(done.status).toBe(302);  const code = new URL(done.headers.get("location")!).searchParams.get("code")!;  const res = await post(`${base}/oauth/token`, { grant_type: "authorization_code", client_id: clientId, code, code_verifier: v, redirect_uri: redirect, resource: `${base}/mcp` });  const body = (await res.json()) as { access_token: string; refresh_token: string };  return { access: body.access_token, refresh: body.refresh_token };}async function refreshed(clientId: string, refresh: string, base = BASE): Promise<{ access: string; refresh: string }> {  const res = await post(`${base}/oauth/token`, { grant_type: "refresh_token", client_id: clientId, refresh_token: refresh });  expect(res.status).toBe(200);  const body = (await res.json()) as { access_token: string; refresh_token: string };  return { access: body.access_token, refresh: body.refresh_token };}describe("the connector's member across OAuth refreshes, and Connect Claude", () => {  const dk = crypto.getRandomValues(new Uint8Array(32));  let credential = "";  let clientId = "";  let entry = "";  beforeAll(async () => {    ({ credential } = await object(OAUTH));    const reg = await SELF.fetch(`${BASE}/oauth/register`, { method: "POST", headers: { "content-type": "application/json" }, body: JSON.stringify({ client_name: "Claude", redirect_uris: [REDIRECT], grant_types: ["authorization_code", "refresh_token"], response_types: ["code"], token_endpoint_auth_method: "none" }) });    clientId = ((await reg.json()) as { client_id: string }).client_id;    entry = crypto.randomUUID();    const sealed = { body: "A quokka smiled at the ferry" };    expect((await act(OAUTH, credential, "create", { table: DIARY.id, id: entry, data: { written_at: "2026-11-02", ...(await sealRow(dk, entry, 1, sealed)) }, blind: [...new Set(await textTokens(await blindKey(dk, DATABASE_ID, DIARY.id), "body", sealed.body))] })).status).toBe(200);  }, 120_000);  it("a connection is a member from its first token; the card's grant stands across refreshes, with no copy of the member key kept", async () => {    let pair = await connect(clientId);    const first = await tool(OAUTH, pair.access, "get_record_by_table", { table: DIARY.id, id: entry });    expect(code(first)).toBe("window_needed");    const request = await rowOf(OAUTH, "unlock_request", String(first.structuredContent!.request_id));    expect(request).toMatchObject({ account: true, client: "Claude" });    const memberId = String(request.member_id);    const g = await agentGrant({ dk, memberId, memberPub: String(request.member_pub), tables: [[DIARY.id, 1]] });    expect((await act(OAUTH, credential, "assistant_allow", { request_id: request.id ?? first.structuredContent!.request_id, ...g })).status).toBe(200);    for (let i = 0; i < 3; i++) {      const before = pair;      pair = await refreshed(clientId, pair.refresh);      expect(JSON.stringify(parsed(await tool(OAUTH, pair.access, "get_record_by_table", { table: DIARY.id, id: entry })))).toContain("quokka");      // The spent refresh token's carrier is gone; the new pair carries the same member.      expect(await count(OAUTH, "SELECT COUNT(*) AS n FROM agent_carrier WHERE token_hash = ?", await sha256(before.refresh))).toBe(0);      expect(await count(OAUTH, "SELECT COUNT(*) AS n FROM agent_carrier WHERE token_hash = ? AND member_id = ?", await sha256(pair.refresh), memberId)).toBe(1);    }    expect(await count(OAUTH, "SELECT COUNT(*) AS n FROM rows WHERE table_id = 'unlock_request' AND json_extract(data, '$.account') = 1")).toBe(1);  });  it("Connect Claude in the app: the phone's own member, granted before connecting, is claimed by the next connection, which reads with no card", async () => {    const secret = crypto.getRandomValues(new Uint8Array(32));    const pub = toBase64Url(await publicOf(secret));    const memberId = crypto.randomUUID();    const g = await agentGrant({ dk, memberId, memberPub: pub, tables: [[DIARY.id, 1]] });    const made = await act(OAUTH, credential, "assistant_allow", { member_id: memberId, member_secret: toBase64Url(secret), name: "Claude", ...g });    expect(made.status, JSON.stringify(made.body)).toBe(200);    // A wrap claimed for tables it does not hold is refused while the object can still check it.    const wrong = await agentGrant({ dk, memberId: crypto.randomUUID(), memberPub: pub, tables: [[DIARY.id, 1]] });    expect((await act(OAUTH, credential, "assistant_allow", { member_id: crypto.randomUUID(), member_secret: toBase64Url(secret), ...wrong })).body.code).toBe("grant_does_not_open");    // AUDIT C 5: another client connecting in the window (its code going back to a host not Claude's) never claims it.    const phishRedirect = "https://phish.invented.example/callback";    const phishReg = await SELF.fetch(`${BASE}/oauth/register`, { method: "POST", headers: { "content-type": "application/json" }, body: JSON.stringify({ client_name: "Claude", redirect_uris: [phishRedirect], grant_types: ["authorization_code", "refresh_token"], response_types: ["code"], token_endpoint_auth_method: "none" }) });    expect(phishReg.status, await phishReg.clone().text()).toBe(201);    const phish = await connect(((await phishReg.json()) as { client_id: string }).client_id, BASE, phishRedirect);    expect(await count(OAUTH, "SELECT COUNT(*) AS n FROM agent_member WHERE id = ? AND pending IS NOT NULL", memberId)).toBe(1);    expect(code(await tool(OAUTH, phish.access, "get_record_by_table", { table: DIARY.id, id: entry }))).toBe("window_needed");    const pair = await connect(clientId);    expect(await count(OAUTH, "SELECT COUNT(*) AS n FROM agent_carrier WHERE member_id = ?", memberId)).toBe(2);    expect(await count(OAUTH, "SELECT COUNT(*) AS n FROM agent_member WHERE id = ? AND pending IS NULL", memberId)).toBe(1);    expect(JSON.stringify(parsed(await tool(OAUTH, pair.access, "get_record_by_table", { table: DIARY.id, id: entry })))).toContain("quokka");    // A copy no connection claims goes at its time: the alarm is set for it.    const lone = crypto.getRandomValues(new Uint8Array(32));    const loneId = crypto.randomUUID();    const lonely = await agentGrant({ dk, memberId: loneId, memberPub: toBase64Url(await publicOf(lone)), tables: [[DIARY.id, 1]] });    expect((await act(OAUTH, credential, "assistant_allow", { member_id: loneId, member_secret: toBase64Url(lone), ...lonely })).status).toBe(200);    const alarm = await runInDurableObject(stub(OAUTH), (_i, state) => state.storage.getAlarm());    expect(alarm! - Date.now()).toBeLessThanOrEqual(15 * 60_000);    // The act log never keeps the member key's private half.    const acts = await runInDurableObject(stub(OAUTH), (_i, state) => JSON.stringify(state.storage.sql.exec("SELECT args FROM acts WHERE act = 'assistant_allow'").toArray()));    expect(acts).not.toContain(toBase64Url(secret));    void parseBundle;  });});/** RULE: an object off the grant (its meta "off") answers with the windows exactly as before. */describe("an object kept off the grant", () => {  it("files today's timed request and refuses the assistant acts", async () => {    const slug = "agent-off";    expect((await http(slug, "PUT", "/v1/admin/business", { name: "Personal", kind: "personal", owner_phone: OWNER_PHONE, database_id: DATABASE_ID, timezone: "Asia/Kolkata" }, ADMIN)).status).toBe(200);    await windowsOnly(slug);    expect((await http(slug, "PUT", "/v1/admin/definitions", { tools: PERSONAL_TOOLS, tables: [...PERSONAL_TABLES, DIARY], flavour: { flavour: "personal" } }, ADMIN)).status).toBe(200);    const c = await http<{ challenge_id: string }>(slug, "POST", "/v1/code", { phone: OWNER_PHONE, device_id: "phone" });    const signed = await http<{ credential: string }>(slug, "POST", "/v1/sign-in", { challenge_id: c.body.challenge_id, code: "123456", device_id: "phone" });    const owner = await mint(slug, signed.body.credential, "Claude", ["owner"]);    const r = await tool(slug, owner, "list_records", { table: DIARY.id });    expect(code(r)).toBe("window_needed");    expect((await rowOf(slug, "unlock_request", String(r.structuredContent!.request_id))).account).toBeUndefined();    expect(await count(slug, "SELECT COUNT(*) AS n FROM agent_member")).toBe(0);    expect((await act(slug, signed.body.credential, "assistant_remove", {})).body.code).toBe("agent_grant_off");  });});// ── live, 21 Nov: the grant turned on over an account full of old windows ──const NOTEBOOK = { ...DIARY, id: "sealed_notebook", name: "Sealed notebook", plural: "Sealed notebooks" };const LETTERS = { ...DIARY, id: "sealed_letter", name: "Sealed letter", plural: "Sealed letters" };const LIVE = "agent-live";const LIVE_BASE = `https://example.test/b/${LIVE}`;/** An old timed window, as the phone allows one: the request's keys wrapped to its one-use key, the statement signed (seal-core seal::grant). */async function allowWindow(slug: string, credential: string, dk: Uint8Array, requestId: string, table: string, minutes: number): Promise<void> {  const request = await rowOf(slug, "unlock_request", requestId);  const bundle = canonical({ request_id: requestId, token_id: String(request.token_id), keys: { [table]: { "1": toBase64Url(await tableKey(dk, DATABASE_ID, table, 1)) } }, blind: { [table]: toBase64Url(await blindKey(dk, DATABASE_ID, table)) } });  const wrapped = await wrapWith(crypto.getRandomValues(new Uint8Array(32)), crypto.getRandomValues(new Uint8Array(12)), fromBase64Url(String(request.worker_pub)), utf8.encode(bundle));  const person = await okp(ED25519_PKCS8, PERSON_SEED, "Ed25519", ["sign"]);  const sig = toBase64Url(new Uint8Array(await crypto.subtle.sign({ name: "Ed25519" }, person.key, utf8.encode(await unlockStatement(DATABASE_ID, requestId, String(request.token_id), [table], minutes, wrapped)))));  const res = await act(slug, credential, "unlock_allow", { request_id: requestId, tables: [table], minutes, wrapped, signer: toBase64Url(person.pub).slice(0, 8), sig });  expect(res.status, JSON.stringify(res.body)).toBe(200);}/** The hour's request limit is the database's, not a test's: earlier requests are aged out of it. */async function ageRequests(slug: string): Promise<void> {  await runInDurableObject(stub(slug), (_i, state) => {    state.storage.sql.exec("UPDATE rows SET data = json_set(data, '$.requested_at', ?) WHERE table_id = 'unlock_request'", new Date(Date.now() - 2 * 3_600_000).toISOString());  });}const accountCards = (slug: string): Promise<number> => count(slug, "SELECT COUNT(*) AS n FROM rows WHERE table_id = 'unlock_request' AND json_extract(data, '$.account') = 1");/** * RULE (live, 21 Nov 2026): with the grant on, a connection made now files * the one card as it connects, and its first private read says it is that * card (`card: "account"`), never the old window's words, whatever old * windows and waiting requests the account holds. A connection made before * the grant is told its token has ended; its refresh makes it Your Claude * and files the card. Once allowed, every private table reads with nothing * more asked. */describe("the grant turned on over an account full of old windows", () => {  const dk = crypto.getRandomValues(new Uint8Array(32));  const tables = [DIARY, NOTEBOOK, LETTERS];  const entries = new Map<string, string>();  let credential = "";  let clientId = "";  let legacy = { access: "", refresh: "" };  beforeAll(async () => {    ({ credential } = await object(LIVE, { tables, grant: false }));    const reg = await SELF.fetch(`${LIVE_BASE}/oauth/register`, { method: "POST", headers: { "content-type": "application/json" }, body: JSON.stringify({ client_name: "Claude", redirect_uris: [REDIRECT], grant_types: ["authorization_code", "refresh_token"], response_types: ["code"], token_endpoint_auth_method: "none" }) });    clientId = ((await reg.json()) as { client_id: string }).client_id;    for (const t of tables) {      const id = crypto.randomUUID();      const sealed = { body: `Platypus number ${t.id}` };      const made = await act(LIVE, credential, "create", { table: t.id, id, data: { written_at: "2026-11-21", ...(await sealRow(dk, id, 1, sealed, t.id)) }, blind: [...new Set(await textTokens(await blindKey(dk, DATABASE_ID, t.id), "body", sealed.body))] });      expect(made.status, JSON.stringify(made.body)).toBe(200);      entries.set(t.id, id);    }    // Before the grant: a connector whose diary window the owner allowed for a day, pasted tokens with windows and waiting requests.    legacy = await connect(clientId, LIVE_BASE);    const asked = await tool(LIVE, legacy.access, "get_record_by_table", { table: DIARY.id, id: entries.get(DIARY.id)! });    expect(code(asked)).toBe("window_needed");    await allowWindow(LIVE, credential, dk, String(asked.structuredContent!.request_id), DIARY.id, 1440);    expect(JSON.stringify(parsed(await tool(LIVE, legacy.access, "get_record_by_table", { table: DIARY.id, id: entries.get(DIARY.id)! })))).toContain("Platypus");    for (let i = 0; i < 3; i++) {      await ageRequests(LIVE);      const old = await mint(LIVE, credential, `old assistant ${i}`, ["owner"]);      const r = await tool(LIVE, old, "list_records", { table: NOTEBOOK.id });      if (i === 0) await allowWindow(LIVE, credential, dk, String(r.structuredContent!.request_id), NOTEBOOK.id, 0);    }    expect(await count(LIVE, "SELECT COUNT(*) AS n FROM rows WHERE table_id = 'unlock_request' AND json_extract(data, '$.state') = 'waiting'")).toBe(2);    expect(await accountCards(LIVE)).toBe(0);    await ageRequests(LIVE);    await grantOn(LIVE);  }, 120_000);  async function readsAll(token: string): Promise<void> {    for (const t of tables) {      const read = parsed(await tool(LIVE, token, "get_record_by_table", { table: t.id, id: entries.get(t.id)! }));      expect(JSON.stringify(read)).toContain(`Platypus number ${t.id}`);      expect(read.window).toMatchObject({ table: t.id, standing: true });    }  }  async function allowCard(requestId: string): Promise<void> {    const request = await rowOf(LIVE, "unlock_request", requestId);    expect(request).toMatchObject({ account: true, state: "waiting", reason: "Let your Claude read your data", expires_at: "9999-12-31T23:59:59.999Z" });    const g = await agentGrant({ dk, memberId: String(request.member_id), memberPub: String(request.member_pub), tables: tables.map((t) => [t.id, 1] as [string, number]) });    const res = await act(LIVE, credential, "assistant_allow", { request_id: requestId, ...g });    expect(res.status, JSON.stringify(res.body)).toBe(200);  }  it("a connection made now files the card as it connects; its first private read says it is that card; once allowed, three tables read with no further card", async () => {    const pair = await connect(clientId, LIVE_BASE);    // The card stands on the phone before Claude reads anything.    expect(await accountCards(LIVE)).toBe(1);    const first = await tool(LIVE, pair.access, "get_record_by_table", { table: NOTEBOOK.id, id: entries.get(NOTEBOOK.id)! });    expect(code(first)).toBe("window_needed");    expect(first.structuredContent!.card).toBe("account");    const said = first.content[0]!.text;    expect(said).toContain("Let your Claude read your data");    expect(said).not.toContain("has not opened a window");    expect(said).not.toContain("how long to allow");    // request_unlock and brief say the same card.    const asked = parsed(await tool(LIVE, pair.access, "request_unlock", { reason: "read" }));    expect(asked).toMatchObject({ state: "waiting", card: "account", request_id: first.structuredContent!.request_id });    expect(await accountCards(LIVE)).toBe(1);    await allowCard(String(first.structuredContent!.request_id));    await readsAll(pair.access);    expect(await accountCards(LIVE)).toBe(1);  });  it("a connection made before the grant is told its token ended; its refresh makes it Your Claude with the card filed; once allowed, three tables read standing", async () => {    await ageRequests(LIVE);    const before = await accountCards(LIVE);    const call = await SELF.fetch(`${LIVE_BASE}/mcp`, { method: "POST", headers: { authorization: `Bearer ${legacy.access}`, "content-type": "application/json", accept: "application/json, text/event-stream" }, body: JSON.stringify({ jsonrpc: "2.0", id: 1, method: "tools/list" }) });    expect(call.status).toBe(401);    expect(call.headers.get("www-authenticate")).toContain('error="invalid_token"');    expect(await call.text()).toContain("disconnect Cotton, connect it again");    // Every client refreshes on invalid_token, as at any expiry.    const pair = await refreshed(clientId, legacy.refresh, LIVE_BASE);    expect(await accountCards(LIVE)).toBe(before + 1);    const first = await tool(LIVE, pair.access, "get_record_by_table", { table: LETTERS.id, id: entries.get(LETTERS.id)! });    expect(first.structuredContent!.card).toBe("account");    // Its old day window still reads the diary meanwhile: the connection is the same one.    expect(JSON.stringify(parsed(await tool(LIVE, pair.access, "get_record_by_table", { table: DIARY.id, id: entries.get(DIARY.id)! })))).toContain("Platypus");    await allowCard(String(first.structuredContent!.request_id));    await readsAll(pair.access);    // And across its next refresh, with nothing more asked.    const next = await refreshed(clientId, pair.refresh, LIVE_BASE);    await readsAll(next.access);    expect(await accountCards(LIVE)).toBe(before + 1);  });  it("a table the owner keeps asked each time says so, not the account card", async () => {    await ageRequests(LIVE);    expect((await act(LIVE, credential, "assistant_scope", { table: LETTERS.id, access: "ask" })).status).toBe(200);    const pair = await connect(clientId, LIVE_BASE);    await allowCard(String((await tool(LIVE, pair.access, "get_record_by_table", { table: DIARY.id, id: entries.get(DIARY.id)! })).structuredContent!.request_id));    const r = await tool(LIVE, pair.access, "get_record_by_table", { table: LETTERS.id, id: entries.get(LETTERS.id)! });    expect(code(r)).toBe("window_needed");    expect(r.structuredContent!.card).toBe("each_time");    expect(r.content[0]!.text).toContain("to be asked each time");  });});