451 lines · 36.8 KB · TypeScriptRaw
/** * OPEN TABLES LOCK (owner via the coordinator, 24 Nov 2026; assets/design/shared/OPEN-TABLES.md §2, * src/open_tables_lock.ts). The memory lock widened to the session tables and projects, on one invented account: * off by default; gate 1 refusing a token with no grant and filing its card; the owner's Allow; on, gate 2 holding every * seal until the phone hands the tables' keys; the sweep; and then the same brief, list_sessions (with search and a * machine), get_session and log_session through the hook's token and a lane minted from it, with no word of any * session in the clear on the object. An ungranted token is answered window_needed. Every key and row is invented. */import { env, runInDurableObject } from "cloudflare:test";import { beforeAll, describe, expect, it } from "vitest";import vector from "../../../crates/cotton-conformance/vectors/seal/agent_grant.json";import { agentStatement, policy } from "../src/agent.ts";import { GRANTED, SEALS, TABLES } from "../src/open_tables_lock.ts";import type { Env } from "../src/env.ts";import { arrivalPub } from "./arrival_keys.ts";import { blindKey, bodyAad, bucket, dekAad, parseSeal, rowTokens, tableKey } from "../src/seal.ts";import { tableFileRoot } from "../src/table_files.ts";import { fromBase64Url, toBase64Url } from "../src/vault.ts";import { ADMIN, DATABASE_ID, http, mint, OWNER_PHONE, PERSONAL_TABLES, PERSONAL_TOOLS, publishPersonKey, put, tool, type ToolResult } from "./personal.ts";import { holdsWord } from "./clear-word.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");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 = "memory"): 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, };}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}` });}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>;}// ── the invented account ──────────────────────────────────────────────const PROJECTS = 13;const SESSIONS = 60;const TURNS = 10;const REPO = "https://git.example.test/invented/garden";const pad = (n: number) => String(n).padStart(12, "0");const uuid = (kind: number, i: number) => `00000000-0000-4000-8${kind}00-${pad(i)}`;const projectSlug = (p: number) => `invented-project-${p}`;/** Within the last days: the object keeps prompts 30 days (erase.ts keepPrompts), and these must stay. */const BASE = Math.floor(Date.now() / 60_000) * 60_000 - 3 * 86_400_000;const at = (i: number) => new Date(BASE + i * 60_000).toISOString();async function lockOf(slug: string, excuse?: string[]) { return http<{ lock: unknown; ready: boolean; state: string; readers: { token_id: string; name: string; verdict: string; says: string }[]; open_rows: Record<string, number>; sealed_rows: Record<string, number> }>(slug, "GET", `/v1/admin/open-tables-lock${excuse ? `?excuse=${excuse.join(",")}` : ""}`, undefined, ADMIN);}/** The phone's sweep over the locked tables: each open row sealed with the data key, its blind tokens beside it. */async function sweep(slug: string, credential: string, dk: Uint8Array, tables: readonly string[] = TABLES, most = Infinity): Promise<{ sealed: number; refused: Record<string, number> }> { const refused: Record<string, number> = {}; let sealed = 0; for (const table of tables) { const seal = SEALS[table]!; const raw = { ...PERSONAL_TABLES.find((t) => t.id === table)!, seal }; const spec = parseSeal(raw as Record<string, unknown>)!; const bk = await blindKey(dk, DATABASE_ID, table); const rows = (await runInDurableObject(stub(slug), (_i, state) => state.storage.sql.exec<{ id: string; version: number; data: string }>("SELECT id, version, data FROM rows WHERE table_id = ? AND deleted = 0 AND json_extract(data, '$.sealed_enc') IS NULL", table).toArray())).slice(0, most); for (const r of rows) { const d = JSON.parse(r.data) as Record<string, unknown>; const inside: Record<string, unknown> = {}; const clear: Record<string, unknown> = {}; for (const [k, v] of Object.entries(d)) (seal.clear.includes(k) ? clear : inside)[k] = v; const blind = await rowTokens(bk, raw as Record<string, unknown>, spec, d); const res = await act(slug, credential, "seal", { table, id: r.id, expect_version: r.version, data: { ...clear, ...(await sealRow(dk, r.id, 1, inside, table)) }, blind }); if (res.status === 200) sealed++; else refused[String(res.body.code)] = (refused[String(res.body.code)] ?? 0) + 1; } } return { sealed, refused };}const words = (s: number, t: number) => (s === 7 && t === 3 ? "the otters hold hands while they sleep, so they do not drift apart" : `invented turn ${t} of session ${s} about ${s % 2 ? "tulips" : "ferns"}`);describe("the open tables lock on an invented account", () => { const slug = "open-tables-lock"; const dk = crypto.getRandomValues(new Uint8Array(32)); let credential = ""; let hook = ""; let before: Record<string, string> = {}; const answers = async (token: string): Promise<Record<string, string>> => ({ brief: String(parsed(await tool(slug, token, "brief", { repoUrl: REPO, machine: "invented-mac" })).briefing), list: JSON.stringify(parsed(await tool(slug, token, "list_sessions", { limit: 50 }))), project: JSON.stringify(parsed(await tool(slug, token, "list_sessions", { project: projectSlug(2), limit: 50 }))), machine: JSON.stringify(parsed(await tool(slug, token, "list_sessions", { machine: "invented-mini", limit: 50 }))), search: JSON.stringify(parsed(await tool(slug, token, "list_sessions", { q: "otters hold", limit: 10 }))), get: JSON.stringify(parsed(await tool(slug, token, "get_session", { sessionId: uuid(2, 7) }))), projects: JSON.stringify(parsed(await tool(slug, token, "list_projects", {}))), // A project named by its slug outside the session tools (records/list.ts resolveProject). todos: JSON.stringify(parsed(await tool(slug, token, "list_todos", { project: projectSlug(2) }))), }); const secrets = async (): Promise<string> => JSON.stringify(parsed(await tool(slug, hook, "list_secrets", {}))); beforeAll(async () => { 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, flavour: { flavour: "personal" } }, ADMIN); expect(defs.status, JSON.stringify(defs.body)).toBe(200); for (const t of TABLES) expect(PERSONAL_TABLES.find((x) => x.id === t)!.seal, `${t} is open in the kit`).toBeUndefined(); 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" }); credential = signed.body.credential; await publishPersonKey(slug, credential, vector.person_public_key); // The phone hands its arrival key at sign-in: what the object seals its own writes to. const handed = await http(slug, "POST", "/v1/act", { act: "create", args: { table: "seal_key", id: "arrival", data: { pub: await arrivalPub() } } }, { authorization: `Bearer ${credential}` }); expect(handed.status, JSON.stringify(handed.body)).toBe(200); await runInDurableObject(stub(slug), (instance) => (instance as unknown as { store: { setMeta(k: string, v: string): void } }).store.setMeta("agent_grant", "on")); hook = await mint(slug, credential, "invented-mac hook", ["owner"]); const rows: Record<string, unknown>[] = []; for (let p = 0; p < PROJECTS; p++) rows.push({ verb: "put", table: "project", id: uuid(1, p), data: { slug: projectSlug(p), name: `Invented project ${p}`, repos: p === 0 ? [REPO] : [], status: "active" } }); for (let s = 0; s < SESSIONS; s++) { rows.push({ verb: "put", table: "session", id: uuid(2, s), data: { tool: "claude-code", external_id: `invented-session-${s}`, machine: s % 3 ? "invented-mac" : "invented-mini", project: uuid(1, s % PROJECTS), repo_url: REPO, branch: "main", cwd: "/invented/garden", title: `Invented session ${s}`, summary: `Invented summary ${s}`, started_at: at(s * 20), last_active_at: at(s * 20 + 10), turn_count: TURNS, prompt_count: TURNS, state: "done" } }); for (let t = 0; t < TURNS; t++) rows.push({ verb: "put", table: "prompt", id: uuid(3, s * 100 + t), data: { session: uuid(2, s), project: uuid(1, s % PROJECTS), seq: t, ts: at(s * 20 + t), role: t % 2 ? "assistant" : "user", text: words(s, t) } }); rows.push({ verb: "put", table: "session_task", id: uuid(4, s), data: { session: uuid(2, s), seq: 0, text: `Invented task of session ${s}`, state: s % 2 ? "done" : "open" } }); if (s % 10 === 0) rows.push({ verb: "put", table: "session_message", id: uuid(5, s), data: { to_kind: "session", to_session: uuid(2, s), from_kind: "owner", kind: "answer", status: "delivered", body: `Invented reply to session ${s}` } }); } // A to-do filed under a project: list_todos names its project by slug, and finds it by one. rows.push({ verb: "put", table: "todo", id: uuid(7, 1), data: { title: "Invented: repot the ferns", status: "open" } }); rows.push({ verb: "put", table: "project_link", id: uuid(7, 2), data: { project: uuid(1, 2), record_kind: "todo", record_id: uuid(7, 1) } }); for (let i = 0; i < rows.length; i += 200) await put(slug, rows.slice(i, i + 200)); // Two invented passwords as a phone saves them, and an API key saved over MCP (its value under the Worker's key). await put(slug, [ { verb: "put", table: "secret", id: uuid(6, 1), data: { name: "Invented Garden Club", kind: "login", site: "garden.example.test", username: "mira.invented", value_enc: "v2:invented-device-sealed-value", vmk_version: 1 } }, { verb: "put", table: "secret", id: uuid(6, 2), data: { name: "Invented Kiln Shop", kind: "login", site: "kiln.example.test", username: "mira.kiln", value_enc: "v2:invented-device-sealed-value-2", vmk_version: 1 } }, ]); expect(parsed(await tool(slug, hook, "create_secret", { name: "Invented weather key", kind: "api_key", service: "invented-weather", value: "invented-key-0000-1111" })).hint).toBeUndefined(); }, 600_000); it("is off by default: every tool answers as it always has, and devices read the tables open", async () => { const r = await lockOf(slug); expect(r.status, JSON.stringify(r.body)).toBe(200); expect(r.body).toMatchObject({ lock: null, state: "off" }); expect(r.body.open_rows).toMatchObject({ project: PROJECTS, session: SESSIONS, prompt: SESSIONS * TURNS }); before = await answers(hook); expect(before.search).toContain("otters hold hands"); expect(before.machine).toContain("invented-mini"); const served = await http<{ tables: { id: string; seal?: unknown }[] }>(slug, "GET", "/v1/definitions", undefined, { authorization: `Bearer ${credential}` }); for (const t of TABLES) expect(served.body.tables.find((x) => x.id === t)!.seal, t).toBeUndefined(); const listed = await secrets(); for (const w of ["Invented Garden Club", "garden.example.test", "mira.invented", "Invented weather key"]) expect(listed, w).toContain(w); // The passwords saved over MCP stay where they are until the lock is on. expect((await http(slug, "GET", "/v1/secret/rewrap", undefined, { authorization: `Bearer ${credential}` })).body).toEqual({ rows: [], unopened: 0, left: 0 }); }, 300_000); it("gate 1 refuses while the hook's token holds no grant and files its card; the owner's Allow makes it ready", async () => { const gate = await lockOf(slug); expect(gate.body.readers.find((r) => r.name === "invented-mac hook")).toMatchObject({ verdict: "needs_allow" }); const on = await http(slug, "POST", "/v1/admin/open-tables-lock", { on: true }, ADMIN); expect(on.status).toBe(409); expect(on.body.code).toBe("open_tables_lock_not_ready"); expect(String(on.body.message ?? on.body.error)).toContain("Its card is on the owner's phone to Allow"); const card = await runInDurableObject(stub(slug), (_i, state) => state.storage.sql.exec<{ id: string; data: string }>("SELECT id, data FROM rows WHERE table_id = 'unlock_request' AND json_extract(data, '$.state') = 'waiting'").one()); const d = JSON.parse(card.data) as Record<string, string>; const g = await agentGrant({ dk, memberId: d.member_id!, memberPub: d.member_pub!, tables: [["note", 1]] }); const allowed = await act(slug, credential, "assistant_allow", { request_id: card.id, ...g }); expect(allowed.status, JSON.stringify(allowed.body)).toBe(200); expect((await lockOf(slug)).body.readers.find((r) => r.name === "invented-mac hook")!.verdict).toBe("ready"); expect((await lockOf(slug)).body.ready).toBe(true); }, 120_000); it("on: devices read the tables sealed; the object keeps them open and refuses every seal until the keys are handed", async () => { const on = await http<{ state: string }>(slug, "POST", "/v1/admin/open-tables-lock", { on: true }, ADMIN); expect(on.status, JSON.stringify(on.body)).toBe(200); expect(on.body.state).toBe("handing"); const served = await http<{ tables: { id: string; seal?: { clear: string[] } }[] }>(slug, "GET", "/v1/definitions", undefined, { authorization: `Bearer ${credential}` }); for (const t of TABLES) expect(served.body.tables.find((x) => x.id === t)!.seal!.clear, t).toEqual(SEALS[t]!.clear); expect(await sweep(slug, credential, dk, ["session"], 5)).toEqual({ sealed: 0, refused: { grant_not_handed: 5 } }); expect(await answers(hook)).toEqual(before); // The admin reads which grant holds handing and which keys it lacks (HANDING STUCK, 25 Nov 2026). const read = await http<{ waiting: { grant_id: string; member_id: string; client: string; live_tokens: number; missing: string[] }[] }>(slug, "GET", "/v1/admin/open-tables-lock", undefined, ADMIN); expect(read.body.waiting).toHaveLength(1); expect(read.body.waiting[0]!.missing.sort()).toEqual([...GRANTED].sort()); expect(read.body.waiting[0]!.member_id).toMatch(/./); expect(read.body.waiting[0]!.live_tokens).toBe(1); // Gate 1 with the lock on: the hook's grant covers every table but holds no key yet, so it is not ready. const hookReader = (await lockOf(slug)).body.readers.find((r) => r.name === "invented-mac hook")!; expect(hookReader.verdict).toBe("needs_allow"); expect(hookReader.says).toContain("waits for the keys of"); }, 300_000); it("the phone hands the keys, the sweep seals every row, and every tool answers the same with no word in the clear", async () => { const grant = await runInDurableObject(stub(slug), (_i, state) => state.storage.sql.exec<{ id: string; data: string }>("SELECT id, data FROM rows WHERE table_id = 'unlock_grant' AND json_extract(data, '$.account') = 1").one()); const memberId = String((JSON.parse(grant.data) as Record<string, unknown>).member_id); const pub = String((JSON.parse(grant.data) as Record<string, unknown>).member_pub ?? "") || (await runInDurableObject(stub(slug), (_i, state) => state.storage.sql.exec<{ pub: string }>("SELECT pub FROM agent_member WHERE id = ?", memberId).one().pub)); // The phone hands every locked table but the passwords, which no grant ever carries. const add = await wrapWith(crypto.getRandomValues(new Uint8Array(32)), crypto.getRandomValues(new Uint8Array(12)), fromBase64Url(pub), utf8.encode(await bundleOf(dk, memberId, GRANTED.map((t) => [t, 1])))); expect((await act(slug, credential, "assistant_add", { grant_id: grant.id, tables: [...GRANTED], wrapped: add })).status).toBe(200); expect((await lockOf(slug)).body.state).toBe("sealing"); expect((await http<{ waiting: unknown[] }>(slug, "GET", "/v1/admin/open-tables-lock", undefined, ADMIN)).body.waiting).toEqual([]); expect((await lockOf(slug)).body.readers.find((r) => r.name === "invented-mac hook")!.verdict).toBe("ready"); expect((await http(slug, "POST", "/v1/admin/open-tables-lock", { on: false }, ADMIN)).body.code).toBe("open_tables_lock_sealing"); const swept = await sweep(slug, credential, dk); expect(swept.refused).toEqual({}); const left = await lockOf(slug); for (const t of TABLES) expect(left.body.open_rows[t], t).toBe(0); expect(left.body.state).toBe("sealed"); const all = await runInDurableObject(stub(slug), (_i, state) => JSON.stringify(state.storage.sql.exec(`SELECT data FROM rows WHERE table_id IN (${TABLES.map(() => "?").join(",")})`, ...TABLES).toArray())); for (const w of ["otters hold hands", "Invented session 7", "Invented summary", "invented-mini", "Invented project 2", "invented-project-2", "/invented/garden", "Invented task", "Invented reply", "Invented Garden Club", "garden.example.test", "mira.invented", "Invented weather key"]) expect(holdsWord(all, w), w).toBe(false); // The passwords list says what stays clear, and no name; the key saved over MCP is still found by its service. const listed = JSON.parse(await secrets()) as { secrets: Record<string, unknown>[] }; expect(listed.secrets).toHaveLength(3); for (const one of listed.secrets) for (const k of ["name", "site", "username", "hint"]) expect(one[k], k).toBeUndefined(); expect(listed.secrets.every((one) => one.isSet === true)).toBe(true); const found = parsed(await tool(slug, hook, "list_secrets", { q: "invented-weather" })) as { secrets: { service: string }[] }; expect(found.secrets.map((x) => x.service)).toEqual(["invented-weather"]); const lane = await mint(slug, hook, "lane invented", ["read", "lane:invented"], 7, undefined, null); for (const token of [hook, lane]) { const started = Date.now(); const now = await answers(token); console.log(`open tables lock: every answer over ${SESSIONS} sealed sessions in ${Date.now() - started} ms`); expect(now).toEqual(before); } }, 1_200_000); it("log_session writes sealed through the hook, and reads back the same", async () => { const logged = parsed(await tool(slug, hook, "log_session", { tool: "claude-code", externalId: "invented-session-7", machine: "invented-mac", lastActiveAt: at(5000), title: "Invented herons at dawn", prompts: [{ seq: TURNS, ts: at(5000), role: "user", text: "herons stand still to fish" }], tasks: [{ seq: 0, text: "Invented: watch the herons", state: "open" }] })); expect(logged).toMatchObject({ sessionId: uuid(2, 7), inserted: 1 }); const made = parsed(await tool(slug, hook, "log_session", { tool: "claude-code", externalId: "invented-new-session", machine: "invented-mac", repoUrl: REPO, lastActiveAt: at(5001), title: "Invented kingfishers", prompts: [{ seq: 0, ts: at(5001), role: "user", text: "kingfishers dive straight down" }] })); expect(made.inserted).toBe(1); const all = await runInDurableObject(stub(slug), (_i, state) => JSON.stringify(state.storage.sql.exec(`SELECT data FROM rows WHERE table_id IN (${TABLES.map(() => "?").join(",")})`, ...TABLES).toArray())); for (const w of ["herons", "kingfishers", "Invented: watch"]) expect(holdsWord(all, w), w).toBe(false); // A password saved over MCP once the passwords are sealed: its name and hint sealed on arrival. const saved = parsed(await tool(slug, hook, "create_secret", { name: "Invented heron feeder", kind: "api_key", service: "invented-heron", value: "invented-key-2222-3333" })); expect(saved.name).toBe("Invented heron feeder"); const stored = await runInDurableObject(stub(slug), (_i, state) => state.storage.sql.exec<{ data: string }>("SELECT data FROM rows WHERE table_id = 'secret' AND id = ?", String(saved.id)).one().data); for (const w of ["Invented heron feeder", "3333", "invented-key"]) expect(holdsWord(stored, w), w).toBe(false); expect(JSON.parse(stored)).toMatchObject({ kind: "api_key", service: "invented-heron" }); // S3: its value is sealed to the arrival key, which the object cannot open (a2:), never under VAULT_KEY (k1:). expect(String((JSON.parse(stored) as Record<string, unknown>).sealed)).toMatch(/^a2:s1:[A-Za-z0-9_-]+\|a1:[A-Za-z0-9_-]+$/); const got = parsed(await tool(slug, hook, "get_session", { sessionId: uuid(2, 7) })) as { title: string; prompts: { text: string }[]; tasks: { text: string }[] }; expect(got.title).toBe("Invented herons at dawn"); expect(got.prompts.at(-1)!.text).toBe("herons stand still to fish"); expect(got.tasks.map((t) => t.text)).toEqual(["Invented: watch the herons"]); const found = parsed(await tool(slug, hook, "list_sessions", { q: "kingfishers", limit: 5 })) as { sessions: { title: string; project: string }[] }; expect(found.sessions.map((s) => [s.title, s.project])).toEqual([["Invented kingfishers", projectSlug(0)]]); }, 300_000); it("the passwords saved over MCP move under the vault key: opened to the owner's device alone, then nothing under VAULT_KEY is left", async () => { const owner = { authorization: `Bearer ${credential}` }; // A token never reaches it: the front door admits tokens to /v1/act alone. expect((await http(slug, "GET", "/v1/secret/rewrap", undefined, { authorization: `Bearer ${hook}` })).status).toBe(403); const asked = await http<{ rows: { id: string; version: number; payload?: string; arrival?: string }[]; unopened: number; left: number }>(slug, "GET", "/v1/secret/rewrap", undefined, owner); expect(asked.status, JSON.stringify(asked.body)).toBe(200); // The one saved before the lock comes opened from VAULT_KEY; the one saved after comes sealed to the arrival key, // as stored, for the phone to open (cotton-core open_arrival_value; the Worker cannot). const payloads = asked.body.rows.filter((r) => r.payload).map((r) => (JSON.parse(r.payload!) as { key: string }).key); expect(payloads).toEqual(["invented-key-0000-1111"]); const arriving = asked.body.rows.filter((r) => r.arrival); expect(arriving).toHaveLength(1); expect(arriving[0]!.arrival).toMatch(/^a2:/); expect(JSON.stringify(asked.body)).not.toContain("2222-3333"); expect(asked.body).toMatchObject({ unopened: 0, left: 0 }); // The phone seals each under the vault key (invented here: the Worker never opens a v2 value) and hands it back. const rows = asked.body.rows.map((r, i) => ({ id: r.id, version: r.version, value_enc: `v2:invented-sealed-by-the-phone-${i}`, vmk_version: 1 })); // A row read before another change is left as it is. const stale = { ...rows[0]!, version: rows[0]!.version - 1 }; expect((await http(slug, "POST", "/v1/secret/rewrap", { rows: [stale] }, owner)).body).toEqual({ moved: 0, skipped: 1 }); expect((await http(slug, "POST", "/v1/secret/rewrap", { rows }, owner)).body).toEqual({ moved: 2, skipped: 0 }); expect((await http(slug, "GET", "/v1/secret/rewrap", undefined, owner)).body).toMatchObject({ rows: [], left: 0 }); const kept = await runInDurableObject(stub(slug), (_i, state) => ({ rows: state.storage.sql.exec<{ id: string; data: string }>("SELECT id, data FROM rows WHERE table_id = 'secret'").toArray(), changes: JSON.stringify(state.storage.sql.exec("SELECT before, after FROM change WHERE table_id = 'secret'").toArray()), })); for (const r of rows) { const data = JSON.parse(kept.rows.find((k) => k.id === r.id)!.data) as Record<string, unknown>; expect(data.value_enc).toBe(r.value_enc); expect(data.sealed ?? null).toBeNull(); } expect(kept.rows.every((k) => !k.data.includes("k1:")), "no password under VAULT_KEY").toBe(true); expect(kept.changes).not.toContain("k1:"); const listed = parsed(await tool(slug, hook, "list_secrets", {})) as { secrets: { isSet: boolean }[] }; expect(listed.secrets.every((x) => x.isSet)).toBe(true); }, 300_000); it("a token with no grant is answered window_needed, and no session is said", async () => { const stranger = await mint(slug, credential, "invented unknown machine", ["read"]); const r = await tool(slug, stranger, "list_sessions", { limit: 5 }); expect(r.isError).toBe(true); expect(JSON.stringify(r)).toContain("window_needed"); expect(JSON.stringify(r)).not.toContain("Invented session"); }, 120_000);});describe("a grant nothing reads through (HANDING STUCK, 25 Nov 2026)", () => { const slug = "open-tables-lock-dead-grant"; const dk = crypto.getRandomValues(new Uint8Array(32)); it("never holds handing: once its last token is revoked, gate 2 passes it by and sealing begins", async () => { 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); expect((await http(slug, "PUT", "/v1/admin/definitions", { tools: PERSONAL_TOOLS, tables: PERSONAL_TABLES, flavour: { flavour: "personal" } }, ADMIN)).status).toBe(200); const code = await http<{ challenge_id: string }>(slug, "POST", "/v1/code", { phone: OWNER_PHONE, device_id: "phone" }); const credential = (await http<{ credential: string }>(slug, "POST", "/v1/sign-in", { challenge_id: code.body.challenge_id, code: "123456", device_id: "phone" })).body.credential; await publishPersonKey(slug, credential, vector.person_public_key); expect((await http(slug, "POST", "/v1/act", { act: "create", args: { table: "seal_key", id: "arrival", data: { pub: await arrivalPub() } } }, { authorization: `Bearer ${credential}` })).status).toBe(200); await runInDurableObject(stub(slug), (instance) => (instance as unknown as { store: { setMeta(k: string, v: string): void } }).store.setMeta("agent_grant", "on")); await put(slug, [{ verb: "put", table: "session", id: uuid(2, 1), data: { tool: "claude-code", external_id: "invented-dead-1", machine: "invented-mac", repo_url: REPO, branch: "main", cwd: "/invented/garden", title: "Invented dead session", summary: "Invented", started_at: at(1), last_active_at: at(2), turn_count: 1, prompt_count: 1, state: "done" } }]); const lane = await mint(slug, credential, "invented stopped lane", ["owner"]); // Used once, as a lane uses its token: it becomes a member (its carrier) and a reader in use. await tool(slug, lane, "list_sessions", {}); // Its card, allowed: a live grant to the lane's member, holding no session table's key yet. expect((await http(slug, "POST", "/v1/admin/open-tables-lock", { on: true }, ADMIN)).status).toBe(409); const card = await runInDurableObject(stub(slug), (_i, state) => state.storage.sql.exec<{ id: string; data: string }>("SELECT id, data FROM rows WHERE table_id = 'unlock_request' AND json_extract(data, '$.state') = 'waiting'").one()); const d = JSON.parse(card.data) as Record<string, string>; expect((await act(slug, credential, "assistant_allow", { request_id: card.id, ...(await agentGrant({ dk, memberId: d.member_id!, memberPub: d.member_pub!, tables: [["note", 1]] })) })).status).toBe(200); const on = await http<{ state: string }>(slug, "POST", "/v1/admin/open-tables-lock", { on: true }, ADMIN); expect(on.status, JSON.stringify(on.body)).toBe(200); expect(on.body.state).toBe("handing"); const held = await http<{ state: string; waiting: { live_tokens: number }[] }>(slug, "GET", "/v1/admin/open-tables-lock", undefined, ADMIN); expect([held.body.state, held.body.waiting.length, held.body.waiting[0]?.live_tokens]).toEqual(["handing", 1, 1]); // The lane stops: its token revoked, the grant left live (only the phone ends a grant). Nothing reads through it now. const laneId = await runInDurableObject(stub(slug), (_i, state) => state.storage.sql.exec<{ id: string }>("SELECT id FROM rows WHERE table_id = 'mcp_token' AND json_extract(data, '$.name') = 'invented stopped lane'").one().id); expect((await act(slug, credential, "revoke_token", { id: laneId })).status).toBe(200); const after = await http<{ state: string; waiting: unknown[] }>(slug, "GET", "/v1/admin/open-tables-lock", undefined, ADMIN); expect(after.body.waiting).toEqual([]); expect(after.body.state).toBe("sealing"); // The grant itself still stands: revoking a token never ends it. const grants = await runInDurableObject(stub(slug), (_i, state) => state.storage.sql.exec<{ n: number }>("SELECT count(*) AS n FROM rows WHERE table_id = 'unlock_grant' AND json_extract(data, '$.account') = 1 AND json_extract(data, '$.ended_at') IS NULL").one().n); expect(grants).toBe(1); }, 300_000);});describe("a new personal database (coordinator, 25 Nov 2026)", () => { type Born = { env: Env; provision(a: { databaseId: string; slug: string; phone: string }): Promise<void>; store: { meta(k: string): string | null } }; const born = async (slug: string, atBirth: string | undefined) => { const metas = await runInDurableObject(stub(slug), async (instance) => { const o = instance as unknown as Born; o.env = { ...o.env, LOCKS_AT_BIRTH: atBirth }; await o.provision({ databaseId: DATABASE_ID, slug, phone: OWNER_PHONE }); return { memory: o.store.meta("memory_lock"), tables: o.store.meta("open_tables_lock"), secret: o.store.meta("secret_lock") }; }); // The directory's sign-up writes the slug before it provisions; made here directly, the front would answer a slug it // never heard of as nobody (AUDIT FIX B1, B-6). An admin call makes it known, as for any object the admin makes. expect((await lockOf(slug)).status).toBe(200); return metas; }; it("is born with memory and the session tables sealed when LOCKS_AT_BIRTH is on: both locks past handing, every table served sealed", async () => { const slug = "born-locked"; const metas = await born(slug, "on"); for (const m of [metas.memory, metas.tables]) expect(JSON.parse(m!)).toMatchObject({ by: "birth", sealing_at: expect.any(String) }); // Made in the object directly, so the directory learns the slug from the admin's first request (AUDIT FIX B1, B-6: // a slug it does not know reaches the nobody object). expect((await http(slug, "GET", "/v1/admin/open-tables-lock", undefined, ADMIN)).status).toBe(200); const code = await http<{ challenge_id: string }>(slug, "POST", "/v1/code", { phone: OWNER_PHONE, device_id: "phone" }); const credential = (await http<{ credential: string }>(slug, "POST", "/v1/sign-in", { challenge_id: code.body.challenge_id, code: "123456", device_id: "phone" })).body.credential; const served = await http<{ tables: { id: string; seal?: { clear: string[] } }[] }>(slug, "GET", "/v1/definitions", undefined, { authorization: `Bearer ${credential}` }); expect(served.status, JSON.stringify(served.body).slice(0, 400)).toBe(200); for (const t of [...TABLES, "memory"]) expect(served.body.tables.find((x) => x.id === t)?.seal, t).toBeTruthy(); // BORN LOCKED 2: the passwords too, from the first row (their own lock: no grant ever carries their key). expect(JSON.parse(metas.secret!)).toMatchObject({ by: "birth" }); expect((await http<{ state: string }>(slug, "GET", "/v1/admin/secret-lock", undefined, ADMIN)).body.state).toBe("sealed"); const lock = await lockOf(slug); expect(lock.body.state).toBe("sealed"); expect((await http<{ state: string }>(slug, "GET", "/v1/admin/memory-lock", undefined, ADMIN)).body.state).toBe("sealed"); // An open row of a locked table is refused from the first: the object holds no clear session. const open = await http(slug, "POST", "/v1/act", { act: "create", args: { table: "session", data: { tool: "claude-code", external_id: "invented-born-1", machine: "invented-mac" } } }, { authorization: `Bearer ${credential}` }); expect(open.status, JSON.stringify(open.body)).not.toBe(200); }, 300_000); it("is born open, as before, when LOCKS_AT_BIRTH is not on", async () => { expect(await born("born-open", undefined)).toEqual({ memory: null, tables: null, secret: null }); }, 120_000);});