import { env, runInDurableObject } from "cloudflare:test"; import { beforeAll, describe, expect, it } from "vitest"; import vector from "../../../crates/cotton-conformance/vectors/seal/row.json"; import { openRow, tableKey } from "../src/seal.ts"; import { ADMIN, answer, DATABASE_ID, http, personalObject, refusal, refusal as tool_, tool } from "./personal.ts"; import { holdsWord } from "./clear-word.ts"; /** * A synthetic sealed table beside the package's (no kit table is sealed yet): * the date and the bin stay clear, the body, mood and external id travel * sealed, the body by word tokens and the external id by an exact one. */ 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: "mood", type: "text", default: "calm" }, { key: "external_id", type: "text" }, { key: "trashed_at", type: "date" }, ], seal: { clear: ["written_at", "trashed_at"], blind: ["body"], blind_exact: ["external_id"] }, }; /** Words the guard looks for in every place the object keeps text: none may land anywhere. */ const SECRET_WORDS = ["zanzibar", "quokka-lantern", "ext-7731"]; function b64url(bytes: Uint8Array): string { return btoa(String.fromCharCode(...bytes)).replace(/\+/g, "-").replace(/\//g, "_").replace(/=+$/, ""); } /** A seal of the right shape (the object never opens it): a 64-byte padded body and a wrapped 32-byte key, as random bytes. */ function seal(v = 1): Record { return { sealed_enc: `s1:${b64url(crypto.getRandomValues(new Uint8Array(12 + 64 + 16)))}`, dek_enc: `d1:${b64url(crypto.getRandomValues(new Uint8Array(12 + 32 + 16)))}`, seal_v: v, }; } async function act(slug: string, credential: string, name: string, args: Record): Promise<{ status: number; body: Record }> { return http(slug, "POST", "/v1/act", { act: name, args }, { authorization: `Bearer ${credential}` }); } /** Every text the object keeps of rows, the change log and the act log, for the plaintext guard. */ async function kept(slug: string): Promise<{ rows: string; change: string; acts: string }> { return runInDurableObject(env.BUSINESS.get(env.BUSINESS.idFromName(slug)), (_instance, state) => { const all = (sql: string) => JSON.stringify(state.storage.sql.exec(sql).toArray()); return { rows: all("SELECT data FROM rows WHERE table_id = 'sealed_diary'"), change: all("SELECT before, after FROM change WHERE table_id = 'sealed_diary'"), acts: all("SELECT args, outcome FROM acts") }; }); } async function blindOf(slug: string, id: string): Promise { return runInDurableObject(env.BUSINESS.get(env.BUSINESS.idFromName(slug)), (_instance, state) => state.storage.sql .exec<{ tok: string }>("SELECT CAST(b.tok AS TEXT) AS tok FROM blind b JOIN blind_row r ON r.rid = b.rid WHERE r.table_id = 'sealed_diary' AND r.id = ? ORDER BY b.tok", id) .toArray() .map((r) => r.tok), ); } /** RULE (sealing plan §2.2, §4, §7): a sealed table's sealed columns reach the object only inside a device's blob, never in rows, change or acts in the clear. */ describe("sealed tables on the object", () => { const slug = "sealed-store"; let credential = ""; let owner = ""; beforeAll(async () => { ({ credential, owner } = await personalObject(slug, { windows: true })); }, 60_000); it("refuses a seal block that does not read, as the Rust definition does, plus what the object's SQL needs clear", async () => { const bad = async (patch: Record, says: string) => { const res = await http(slug, "POST", "/v1/admin/definitions/tables", { tables: [{ ...DIARY, ...patch }] }, ADMIN); expect(res.status, JSON.stringify(res.body)).toBe(400); expect(JSON.stringify(res.body)).toContain(says); }; await bad({ seal: { clear: ["written_at", "nope"] } }, 'seal.clear names \\"nope\\", which is no column'); await bad({ seal: { clear: ["written_at"], blind: ["written_at"] } }, "which is clear"); await bad({ seal: { clear: ["written_at"], hidden: [] } }, 'seal has no \\"hidden\\"'); await bad({ seal: { clear: ["written_at"], blind: ["body"], blind_bytes: { mood: 10 } } }, 'seal.blind_bytes names \\"mood\\"'); await bad({ seal: { clear: ["written_at"], blind: ["body"], blind_bytes: { body: 0 } } }, 'seal.blind_bytes names \\"body\\"'); await bad({ seal: { clear: ["written_at"], blind: ["body"], blind_bytes: [2048] } }, "seal.blind_bytes is an object"); await bad({ columns: [...DIARY.columns, { key: "seal_v", type: "number" }] }, "the sealer writes it"); await bad({ seal: { clear: ["trashed_at"] } }, 'date names \\"written_at\\", which is sealed'); await bad({ row_key: "external_id" }, 'row_key names \\"external_id\\", which is sealed'); await bad({ columns: [...DIARY.columns, { key: "shout", type: "text", computed: { formula: { op: "concat", of: ["body"] } } }] }, 'reads \\"body\\", which is sealed'); // An email's body is indexed to its first 2 KB (Q12): the cap is the device's, the object only reads its shape. const capped = await http(slug, "POST", "/v1/admin/definitions/tables", { tables: [{ ...DIARY, id: "sealed_capped", seal: { ...(DIARY.seal as object), blind_bytes: { body: 2048 } } }] }, ADMIN); expect(capped.status, JSON.stringify(capped.body)).toBe(200); // A row keyed by a clear column (Health's day readings, b59afc2bb) says nothing its row does not already say in the clear. const keyed = await http(slug, "POST", "/v1/admin/definitions/tables", { tables: [{ ...DIARY, id: "sealed_keyed", row_key: "written_at" }] }, ADMIN); expect(keyed.status, JSON.stringify(keyed.body)).toBe(200); expect((await http(slug, "POST", "/v1/admin/definitions/tables", { tables: [DIARY] }, ADMIN)).status).toBe(200); // A tool's automation that watches or sets a sealed column is refused: the object cannot read or write it. const watching = { id: "synthetic-diary", name: "Diary", tables: ["sealed_diary"], automations: [{ id: "a1", name: "x", when: { table: "sealed_diary", column: "mood", to: "any" }, then: [] }] }; const res = await http(slug, "POST", "/v1/admin/definitions/tools", { tools: [watching] }, ADMIN); expect(res.status).toBe(400); expect(JSON.stringify(res.body)).toContain("sealed_diary.mood, which is sealed"); }); // RULE (film-progress-clobber, 18 Nov 2026): a device's update naming clear columns alone changes those columns and leaves the rest of the sealed row, its blob included, as another writer left it. it("merges a device's update of clear columns over a sealed row, column by column", async () => { expect((await http(slug, "POST", "/v1/admin/definitions/tables", { tables: [DIARY] }, ADMIN)).status).toBe(200); const blob = seal(); const made = await act(slug, credential, "create", { table: "sealed_diary", data: { written_at: "2026-11-09", ...blob } }); expect(made.status, JSON.stringify(made.body)).toBe(200); const id = (made.body.changed as { id: string }[])[0]!.id; const other = await act(slug, credential, "update", { table: "sealed_diary", id, data: { written_at: "2026-11-10" } }); expect(other.status, JSON.stringify(other.body)).toBe(200); const saved = await act(slug, credential, "update", { table: "sealed_diary", id, data: { trashed_at: "2026-11-18" } }); expect(saved.status, JSON.stringify(saved.body)).toBe(200); const row = (saved.body.changed as { data: Record }[])[0]!.data; expect(row).toMatchObject({ written_at: "2026-11-10", trashed_at: "2026-11-18", ...blob }); }); it("refuses at definition time a group or a view's filter over a sealed column, and any edit of a seal, and lays a sort over one (the device sorts, R3) and another table's lookup or rollup over one", async () => { const tables = (laid: Record[]) => http(slug, "POST", "/v1/admin/definitions/tables", { tables: laid }, ADMIN); const refusedFor = async (res: { status: number; body: unknown }, says: string) => { expect(res.status, JSON.stringify(res.body)).toBe(400); expect(JSON.stringify(res.body)).toContain(says); }; await refusedFor(await tables([{ ...DIARY, group: { column: "mood", sections: [] } }]), 'group.column names \\"mood\\", which is sealed'); const tool = (view: Record) => http(slug, "POST", "/v1/admin/definitions/tools", { tools: [{ id: "synthetic-diary-views", name: "Diary", tables: ["sealed_diary"], views: [{ id: "v1", label: "V", visibility: "owner", is_default: true, ...view }] }] }, ADMIN); // A sort of a sealed column is the device's (R3, seal/default.json sorted_on_device): laid, and the object lists without it. expect((await tool({ read: { table: "sealed_diary" }, sort: { column: "mood", descending: false } })).status).toBe(200); expect((await tables([{ ...DIARY, sort: { column: "mood" } }])).status).toBe(200); expect((await tables([DIARY])).status).toBe(200); await refusedFor(await tool({ read: { table: "sealed_diary", where: { mood: "calm" } } }), "filters sealed_diary by mood"); expect((await tool({ read: { table: "sealed_diary", where: { trashed_at: null } }, sort: { column: "written_at", descending: true } })).status).toBe(200); // What a view narrows and orders by once its rows open on the phone is never the object's read: a sealed column stands there. expect((await tool({ read: { table: "sealed_diary" }, sort: { column: "written_at", descending: true }, opened: { where: { mood: "calm" }, tie: "mood" } })).status).toBe(200); expect(await refusal(slug, owner, "list_records", { table: "sealed_diary", view: "synthetic-diary-views/v1" })).toContain("narrowed on the owner's phone"); // Another table reading a sealed column: a lookup through its link, a rollup over the rows that link to it. const index = (computed: Record) => ({ format_version: 1, id: "diary_index", name: "Diary index", plural: "Diary indexes", title: "label", columns: [ { key: "label", type: "text" }, { key: "diary_id", type: "link", link_to: "sealed_diary" }, { key: "seen", type: "text", computed }, ], }); // R3 (15 Nov 2026): the device works such a column out on its copy, so it is laid; the object never reads the sealed column for it. expect((await tables([index({ lookup: { through: "diary_id", column: "body" } })])).status).toBe(200); expect((await tables([index({ rollup: { table: "sealed_diary", link: "index_id", op: "count_values", column: "mood" } })])).status).toBe(200); expect((await tables([index({ lookup: { through: "diary_id", column: "written_at" } })])).status).toBe(200); // No edit seals, unseals or reshapes a seal: it is the kit's to say. const unseal = await tool_(slug, owner, "update_definition", { table: "sealed_diary", seal: null }); expect(unseal).toContain("cannot be changed here"); expect(await tool_(slug, owner, "update_definition", { table: "note", seal: { clear: ["title"] } })).toContain("cannot be changed here"); }); it("refuses a device's sealed column in the clear, and keeps nothing of it in the act log", async () => { const res = await act(slug, credential, "create", { table: "sealed_diary", data: { written_at: "2026-11-11", body: "zanzibar at dawn" } }); expect(res.status).toBe(400); expect(res.body).toMatchObject({ code: "sealed_in_clear" }); expect(String(res.body.message)).toContain("body"); // A blob beside a clear sealed column is refused too: a sealed row never holds both. const both = await act(slug, credential, "create", { table: "sealed_diary", data: { written_at: "2026-11-11", mood: "quokka-lantern", ...seal() } }); expect(both.body).toMatchObject({ code: "sealed_in_clear" }); const logged = await kept(slug); for (const w of SECRET_WORDS) expect(holdsWord(logged.acts, w), w).toBe(false); expect(logged.acts).toContain("‹sealed›"); }); it("refuses a seal that is not whole or not in its format, by name", async () => { const half = { ...seal() }; delete half.dek_enc; expect((await act(slug, credential, "create", { table: "sealed_diary", data: { written_at: "2026-11-11", ...half } })).body).toMatchObject({ code: "seal_column_missing" }); expect((await act(slug, credential, "create", { table: "sealed_diary", data: { ...seal(), sealed_enc: "x1:abc" } })).body).toMatchObject({ code: "bad_seal" }); expect((await act(slug, credential, "create", { table: "sealed_diary", data: { ...seal(), seal_v: 0 } })).body).toMatchObject({ code: "bad_seal" }); expect((await act(slug, credential, "create", { table: "project", data: { name: "n", ...seal() } })).body).toMatchObject({ code: "unknown_field" }); expect((await act(slug, credential, "create", { table: "sealed_diary", data: { written_at: "2026-11-11", ...seal() }, blind: ["12", "x"] })).body).toMatchObject({ code: "bad_blind" }); expect((await act(slug, credential, "create", { table: "sealed_diary", data: { written_at: "2026-11-11" }, blind: ["12"] })).body).toMatchObject({ code: "bad_blind" }); }); let sealedId = ""; const tokens = ["-9223372036854775808", "9223372036854775807", "42", "-7"]; it("stores a device's sealed row opaque: clear columns and the blob, no default or required sealed column asked for, its tokens beside it", async () => { const made = await act(slug, credential, "create", { table: "sealed_diary", data: { written_at: "2026-11-10", ...seal() }, blind: [...tokens, "42"] }); expect(made.status, JSON.stringify(made.body)).toBe(200); const row = (made.body.changed as { id: string; data: Record }[])[0]!; sealedId = row.id; expect(Object.keys(row.data).sort()).toEqual(["dek_enc", "seal_v", "sealed_enc", "written_at"]); // Stored as integers, exact to the last digit: numeric order, the extremes kept, the repeat once. expect(await blindOf(slug, sealedId)).toEqual(["-9223372036854775808", "-7", "42", "9223372036854775807"]); // The phone pulls it as stored. const pulled = await http<{ rows: { table: string; id: string; data: Record }[] }>(slug, "GET", "/v1/sync?since=0&tables=sealed_diary", undefined, { authorization: `Bearer ${credential}` }); expect(pulled.body.rows.find((r) => r.id === sealedId)?.data).toEqual(row.data); // MCP reads it only in a window (src/window.ts): without one the read asks the owner's phone and answers window_needed, never the blob. const read = await tool(slug, owner, "get_record_by_table", { table: "sealed_diary", id: sealedId }); expect(read.isError).toBe(true); expect(read.structuredContent).toMatchObject({ code: "window_needed" }); expect(read.content[0]!.text).not.toContain("s1:"); }); it("lets a device re-seal and change clear columns, journals only ciphertext, and keeps the Worker from writing plaintext into a sealed row", async () => { const next = seal(2); const res = await act(slug, credential, "update", { table: "sealed_diary", id: sealedId, data: { ...next, trashed_at: "2026-11-11" }, blind: ["5"] }); expect(res.status, JSON.stringify(res.body)).toBe(200); expect(await blindOf(slug, sealedId)).toEqual(["5"]); // An update with no seal leaves the tokens as they are. expect((await act(slug, credential, "update", { table: "sealed_diary", id: sealedId, data: { trashed_at: null } })).status).toBe(200); expect(await blindOf(slug, sealedId)).toEqual(["5"]); const refused = await tool(slug, owner, "update_record", { table: "sealed_diary", id: sealedId, patch: { mood: "zanzibar" } }); expect(refused.isError).toBe(true); expect(refused.content[0]!.text).toContain("sealed"); const log = await answer<{ changes: { before: Record | null; after: Record | null }[] }>(slug, owner, "list_changes", { table: "sealed_diary", id: sealedId }); expect(log.changes.length).toBeGreaterThan(0); }); it("keeps a device's update made from an older version than the row holds only when it says nothing of the version, and refuses it when it does (STALE, 21 Nov 2026)", async () => { const versionOf = () => runInDurableObject(env.BUSINESS.get(env.BUSINESS.idFromName(slug)), (_i, state) => Number(state.storage.sql.exec<{ version: number }>("SELECT version FROM rows WHERE table_id = 'sealed_diary' AND id = ?", sealedId).one().version)); const read = await versionOf(); expect((await act(slug, credential, "update", { table: "sealed_diary", id: sealedId, data: { trashed_at: "2026-11-21" }, expect_version: read })).status).toBe(200); // Another writer's change landed since `read`: a write made from `read` is refused, and the row keeps the newer words. const stale = await act(slug, credential, "update", { table: "sealed_diary", id: sealedId, data: { trashed_at: null }, expect_version: read }); expect(stale.status).toBe(409); expect(stale.body).toMatchObject({ code: "version_moved" }); expect((await act(slug, credential, "update", { table: "sealed_diary", id: sealedId, data: { trashed_at: null }, expect_version: "3" })).body).toMatchObject({ code: "bad_args" }); expect((await act(slug, credential, "update", { table: "sealed_diary", id: sealedId, data: { trashed_at: null }, expect_version: await versionOf() })).status).toBe(200); }); it("keeps an open row written before the table was sealed, which a device then seals only at the version it read, taking the plaintext out of the row and the log", async () => { // Nothing writes one in the clear once the table is sealed: an assistant outside a window is refused (window_needed), a device's clear copy too. const outside = await tool(slug, owner, "create_record", { table: "sealed_diary", data: { written_at: "2026-11-09", body: "zanzibar quokka-lantern" } }); expect(outside.isError).toBe(true); expect(JSON.stringify(outside.content)).toContain("window"); expect((await act(slug, credential, "create", { table: "sealed_diary", data: { written_at: "2026-11-09", body: "zanzibar" } })).body).toMatchObject({ code: "sealed_in_clear" }); // So the open row is one the table held before it was sealed: written and edited while it was open, then the table marked sealed. const { seal: _seal, ...open } = DIARY; expect((await http(slug, "POST", "/v1/admin/definitions/tables", { tables: [open] }, ADMIN)).status).toBe(200); const made = await answer<{ record: { id: string } }>(slug, owner, "create_record", { table: "sealed_diary", data: { written_at: "2026-11-09", body: "zanzibar quokka-lantern", external_id: "ext-7731" } }); const id = made.record.id; await answer(slug, owner, "update_record", { table: "sealed_diary", id, patch: { body: "zanzibar again" } }); expect((await http(slug, "POST", "/v1/admin/definitions/tables", { tables: [DIARY] }, ADMIN)).status).toBe(200); let logged = await kept(slug); expect(logged.change, "an open row is journalled as it is held").toContain("zanzibar"); const version = await runInDurableObject(env.BUSINESS.get(env.BUSINESS.idFromName(slug)), (_i, state) => Number(state.storage.sql.exec<{ version: number }>("SELECT version FROM rows WHERE table_id = 'sealed_diary' AND id = ?", id).one().version)); // A stale version is refused: an edit landed since the device read the row. const stale = await act(slug, credential, "seal", { table: "sealed_diary", id, expect_version: version - 1, data: { written_at: "2026-11-09", ...seal() } }); expect(stale.status).toBe(409); expect(stale.body).toMatchObject({ code: "version_moved" }); // A seal carrying plaintext of a column no clear list of its table ever kept is refused like any device write. // (sealed_diary was open just now: a phone still holding that list is taken, never refused, SEALING-CONTRACT.md; // sealed_capped never was.) expect((await act(slug, credential, "create", { table: "sealed_capped", data: { body: "zanzibar", ...seal() } })).body).toMatchObject({ code: "sealed_in_clear" }); // A token cannot seal: only the owner's devices can. const byToken = await tool(slug, owner, "run_act", { act: "seal", args: { table: "sealed_diary", id, expect_version: version, data: seal() } }); expect(byToken.isError).toBe(true); const sealed = await act(slug, credential, "seal", { table: "sealed_diary", id, expect_version: version, data: { written_at: "2026-11-09", ...seal() }, blind: ["99"] }); expect(sealed.status, JSON.stringify(sealed.body)).toBe(200); expect(Object.keys((sealed.body.changed as { data: Record }[])[0]!.data).sort()).toEqual(["dek_enc", "seal_v", "sealed_enc", "written_at"]); logged = await kept(slug); for (const w of SECRET_WORDS) { expect(holdsWord(logged.rows, w), `rows.data holds ${w}`).toBe(false); expect(holdsWord(logged.change, w), `change holds ${w}`).toBe(false); } expect(await blindOf(slug, id)).toEqual(["99"]); }); it("seals many open rows in one act, each kept or refused on its own (SYNC STUCK: one round trip a row kept his phones from finishing a pass)", async () => { const { seal: _seal, ...open } = DIARY; expect((await http(slug, "POST", "/v1/admin/definitions/tables", { tables: [open] }, ADMIN)).status).toBe(200); const ids: string[] = []; for (let i = 0; i < 3; i++) ids.push((await answer<{ record: { id: string } }>(slug, owner, "create_record", { table: "sealed_diary", data: { written_at: "2026-11-10", body: `zanzibar ${i}` } })).record.id); expect((await http(slug, "POST", "/v1/admin/definitions/tables", { tables: [DIARY] }, ADMIN)).status).toBe(200); const versions = await runInDurableObject(env.BUSINESS.get(env.BUSINESS.idFromName(slug)), (_i, state) => ids.map((id) => Number(state.storage.sql.exec<{ version: number }>("SELECT version FROM rows WHERE table_id = 'sealed_diary' AND id = ?", id).one().version))); const rows = ids.map((id, i) => ({ table: "sealed_diary", id, expect_version: versions[i]! - (i === 1 ? 1 : 0), data: { written_at: "2026-11-10", ...seal() }, blind: ["7"] })); const many = await act(slug, credential, "seal_many", { rows }); expect(many.status, JSON.stringify(many.body)).toBe(200); expect(many.body.results).toEqual([ { table: "sealed_diary", id: ids[0], ok: true }, { table: "sealed_diary", id: ids[1], ok: false, status: 409, code: "version_moved" }, { table: "sealed_diary", id: ids[2], ok: true }, ]); // The one refused is sealed again at the version it holds now, as the device's next sweep does. const again = await act(slug, credential, "seal_many", { rows: [{ ...rows[1]!, expect_version: versions[1]! }] }); expect(again.body.results).toEqual([{ table: "sealed_diary", id: ids[1], ok: true }]); const logged = await kept(slug); for (let i = 0; i < 3; i++) expect(holdsWord(logged.rows, `zanzibar ${i}`), `row ${i}`).toBe(false); // The act log keeps such a batch as its count by table, never its rows. expect(logged.acts).toContain('{\\"rows\\":3,\\"tables\\":{\\"sealed_diary\\":3}}'); // Only the owner's own device, and at most 200 rows. expect((await tool(slug, owner, "run_act", { act: "seal_many", args: { rows } })).isError).toBe(true); expect((await act(slug, credential, "seal_many", { rows: [] })).body).toMatchObject({ code: "bad_args" }); expect((await act(slug, credential, "seal_many", { rows: Array.from({ length: 201 }, () => rows[0]) })).body).toMatchObject({ code: "bad_args" }); }); it("refuses where, summary and search over a sealed column, and searches only clear text", async () => { expect(await refusal(slug, owner, "list_records", { table: "sealed_diary", where: { mood: "calm" } })).toContain("sealed"); expect(await refusal(slug, owner, "list_records", { table: "vault_key", where: { wrapped_vmk: { present: true } } })).toContain("never read"); expect(await refusal(slug, owner, "summarize_records", { table: "sealed_diary", measures: [{ op: "count" }], group_by: "mood" })).toContain("sealed"); const counted = await answer<{ groups: { count: number }[] }>(slug, owner, "summarize_records", { table: "sealed_diary", measures: [{ op: "count" }], where: { written_at: { present: true } } }); expect(counted.groups[0]!.count).toBeGreaterThan(0); }); it("answers GET /v1/blind with ids holding every token, newest first, to the owner's devices only", async () => { const other = await act(slug, credential, "create", { table: "sealed_diary", data: { written_at: "2026-11-12", ...seal() }, blind: ["5", "6"] }); const otherId = (other.body.changed as { id: string }[])[0]!.id; const ask = (q: string, auth = `Bearer ${credential}`) => http<{ table: string; ids: string[] }>(slug, "GET", `/v1/blind?${q}`, undefined, { authorization: auth }); expect((await ask("table=sealed_diary&tok=5")).body).toEqual({ table: "sealed_diary", ids: [otherId, sealedId] }); expect((await ask("table=sealed_diary&tok=5,6")).body.ids).toEqual([otherId]); expect((await ask("table=sealed_diary&tok=12345")).body.ids).toEqual([]); expect((await ask("table=sealed_diary&tok=9223372036854775808")).status).toBe(400); expect((await ask("table=project&tok=5")).status).toBe(400); expect((await ask("table=sealed_diary&tok=5", `Bearer ${owner}`)).status).toBe(403); // A row deleted takes its tokens with it. expect((await act(slug, credential, "delete", { table: "sealed_diary", id: otherId })).status).toBe(200); expect(await blindOf(slug, otherId)).toEqual([]); expect((await ask("table=sealed_diary&tok=5")).body.ids).toEqual([sealedId]); }); it("keeps seal_key as the plan shapes it: one data key, versions only forward, written by the owner's devices alone, never deleted", async () => { const dk = { dk_enc: `v2:${b64url(crypto.getRandomValues(new Uint8Array(60)))}`, vmk_version: 1, created_at: "2026-11-11T10:00:00.000Z" }; const made = await act(slug, credential, "create", { table: "seal_key", id: "dk", data: dk }); expect(made.status, JSON.stringify(made.body)).toBe(200); // A second first device racing the first ends with one data key. expect((await act(slug, credential, "create", { table: "seal_key", id: "dk", data: { ...dk, dk_enc: "v2:other" } })).body).toMatchObject({ code: "duplicate_id" }); expect((await act(slug, credential, "create", { table: "seal_key", data: dk })).body).toMatchObject({ code: "bad_seal_key" }); expect((await act(slug, credential, "update", { table: "seal_key", id: "dk", data: { vmk_version: 0 } })).body).toMatchObject({ code: "bad_seal_key" }); // A vault key rotation re-wraps it forward, never back. expect((await act(slug, credential, "update", { table: "seal_key", id: "dk", data: { dk_enc: "v2:rewrapped", vmk_version: 2 } })).status).toBe(200); expect((await act(slug, credential, "update", { table: "seal_key", id: "dk", data: { dk_enc: "v2:older", vmk_version: 1 } })).body).toMatchObject({ code: "seal_version_back" }); // A sealed table's version: made by the first advance (2), then only forward. expect((await act(slug, credential, "create", { table: "seal_key", id: "v:sealed_diary", data: { v: 1 } })).body).toMatchObject({ code: "seal_version_back" }); expect((await act(slug, credential, "create", { table: "seal_key", id: "v:sealed_diary", data: { v: 2 } })).status).toBe(200); expect((await act(slug, credential, "update", { table: "seal_key", id: "v:sealed_diary", data: { v: 2 } })).body).toMatchObject({ code: "seal_version_back" }); expect((await act(slug, credential, "update", { table: "seal_key", id: "v:sealed_diary", data: { v: 3 } })).status).toBe(200); expect((await act(slug, credential, "create", { table: "seal_key", id: "v:project", data: { v: 2 } })).body).toMatchObject({ code: "bad_seal_key" }); expect((await act(slug, credential, "create", { table: "seal_key", id: "v:sealed_diary", data: { v: 4, dk_enc: "x" } })).body).toMatchObject({ code: "bad_seal_key" }); expect((await act(slug, credential, "create", { table: "seal_key", id: "key", data: { v: 2 } })).body).toMatchObject({ code: "bad_seal_key" }); // Deleting the data key would let a later device mint another and lose every sealed row: no seal key is deleted. expect((await act(slug, credential, "delete", { table: "seal_key", id: "dk" })).body).toMatchObject({ code: "no_delete" }); // An assistant's token writes none. const byToken = await tool(slug, owner, "run_act", { act: "update", args: { table: "seal_key", id: "v:sealed_diary", data: { v: 9 } } }); expect(byToken.isError).toBe(true); // Refused at the one gate for every key (ADMIN KEYS 1b: seal_key holds who may do what). expect(byToken.content[0]!.text).toMatch(/owner's own devices|holds who may do what/); // A device pulls both rows as written; MCP never answers the wrap. const pulled = await http<{ rows: { table: string; id: string; data: Record }[] }>(slug, "GET", "/v1/sync?since=0&tables=seal_key", undefined, { authorization: `Bearer ${credential}` }); const rows = Object.fromEntries(pulled.body.rows.filter((r) => r.table === "seal_key").map((r) => [r.id, r.data])); expect(rows).toMatchObject({ dk: { dk_enc: "v2:rewrapped", vmk_version: 2 }, "v:sealed_diary": { v: 3 } }); const read = JSON.stringify(await tool(slug, owner, "list_records", { table: "seal_key" })); expect(read).not.toContain("v2:rewrapped"); }); it("restores a sealed row with its blind tokens, as a sealed write keeps them, and never a seal key", async () => { const row = { table: "sealed_diary", id: "restored-1", data: { written_at: "2026-11-08", ...seal() }, blind: ["11", "-3"], updated_at: "2026-11-08T10:00:00.000Z" }; const res = await act(slug, credential, "restore", { rows: [row] }); expect(res.status, JSON.stringify(res.body)).toBe(200); expect(res.body).toMatchObject({ restored: [{ table: "sealed_diary", id: "restored-1", landed: "made" }] }); expect(await blindOf(slug, "restored-1")).toEqual(["-3", "11"]); // The phone's newer copy writes it again, with its tokens. const again = await act(slug, credential, "restore", { rows: [{ ...row, data: { written_at: "2026-11-08", ...seal() }, blind: ["12"], updated_at: "2026-11-09T10:00:00.000Z" }] }); expect(again.body).toMatchObject({ restored: [{ landed: "written" }] }); expect(await blindOf(slug, "restored-1")).toEqual(["12"]); expect((await act(slug, credential, "restore", { rows: [{ table: "sealed_diary", id: "restored-2", data: { written_at: "2026-11-08" }, blind: ["1"] }] })).body).toMatchObject({ code: "bad_blind" }); expect((await act(slug, credential, "restore", { rows: [{ table: "sealed_capped", id: "restored-3", data: { written_at: "2026-11-08", body: "zanzibar" } }] })).body).toMatchObject({ code: "sealed_in_clear" }); expect((await act(slug, credential, "restore", { rows: [{ table: "seal_key", id: "v:sealed_diary", data: { v: 7 } }] })).body).toMatchObject({ code: "not_restored" }); }); it("lands the Mac importer's planned rows whole in one call, sealed with their tokens, and none of them when one is refused", async () => { const one = (id: string, extra: Record = {}) => ({ table: "sealed_diary", id, data: { written_at: "2026-11-10", ...seal() }, blind: ["21", "-4"], created_at: "2026-11-10T08:00:00.000Z", updated_at: "2026-11-10T08:00:00.000Z", ...extra }); const res = await act(slug, credential, "import_rows", { rows: [one("imported-1"), one("imported-2")] }); expect(res.status, JSON.stringify(res.body)).toBe(200); expect(res.body).toMatchObject({ made: { sealed_diary: 2 }, changed: {} }); expect(await blindOf(slug, "imported-1")).toEqual(["-4", "21"]); // The same row again with a new seal is a patch; a retract deletes. const again = await act(slug, credential, "import_rows", { rows: [one("imported-1", { blind: ["22"], updated_at: "2026-11-10T09:00:00.000Z" }), { table: "sealed_diary", id: "imported-2", retract: true }] }); expect(again.body).toMatchObject({ made: {}, changed: { sealed_diary: 2 } }); expect(await blindOf(slug, "imported-1")).toEqual(["22"]); expect(await blindOf(slug, "imported-2")).toEqual([]); // One refused row refuses the call: the row before it is not kept. const refused = await act(slug, credential, "import_rows", { rows: [one("imported-3"), { table: "sealed_capped", id: "imported-4", data: { written_at: "2026-11-10", body: "zanzibar" } }] }); expect(refused.body).toMatchObject({ code: "sealed_in_clear" }); const held = await runInDurableObject(env.BUSINESS.get(env.BUSINESS.idFromName(slug)), (_i, state) => state.storage.sql.exec("SELECT id FROM rows WHERE id IN ('imported-3','imported-4')").toArray()); expect(held).toEqual([]); expect((await act(slug, credential, "import_rows", { rows: [{ table: "sealed_diary", id: "imported-5", data: { written_at: "2026-11-10" }, blind: ["1"] }] })).body).toMatchObject({ code: "bad_blind" }); expect((await act(slug, credential, "import_rows", { rows: [{ table: "seal_key", id: "v:sealed_diary", data: { v: 9 } }] })).body).toMatchObject({ code: "not_imported" }); expect((await act(slug, credential, "import_rows", { rows: Array.from({ length: 501 }, (_, i) => one(`many-${i}`)) })).body).toMatchObject({ code: "too_many" }); // LIVE CPU 4: a call lands at most BLIND_PER_CALL tokens across its rows, so a client splits a long catch-up; one // row alone may carry its whole list (a long mail is one row), every token kept. const toks = (n: number, from: number) => Array.from({ length: n }, (_, k) => String(from + k)); const over = await act(slug, credential, "import_rows", { rows: Array.from({ length: 21 }, (_, i) => one(`tok-over-${i}`, { blind: toks(100, i * 1000) })) }); expect(over.status).toBe(413); expect(over.body).toMatchObject({ code: "too_large" }); expect(await blindOf(slug, "tok-over-0")).toEqual([]); expect((await act(slug, credential, "import_rows", { rows: Array.from({ length: 20 }, (_, i) => one(`tok-fits-${i}`, { blind: toks(100, i * 1000) })) })).status).toBe(200); expect((await blindOf(slug, "tok-fits-19")).length).toBe(100); expect((await act(slug, credential, "import_rows", { rows: [one("tok-alone", { blind: toks(5000, 1) })] })).status).toBe(200); expect((await blindOf(slug, "tok-alone")).length).toBe(5000); expect((await act(slug, credential, "restore", { rows: Array.from({ length: 3 }, (_, i) => ({ table: "sealed_diary", id: `tok-restore-${i}`, data: { written_at: "2026-11-10", ...seal() }, blind: toks(1000, i * 10000) })) })).body).toMatchObject({ code: "too_large" }); // A big batch is logged as its count by table, whole JSON however many // rows it held (whole rows outgrew the log's 4000 characters and read as // plaintext left behind to seal-check, found walking the dev Worker). expect((await act(slug, credential, "import_rows", { rows: Array.from({ length: 200 }, (_, i) => one(`batch-${i}`)) })).status).toBe(200); const logged = await runInDurableObject(env.BUSINESS.get(env.BUSINESS.idFromName(slug)), (_i, state) => state.storage.sql.exec<{ args: string }>("SELECT args FROM acts WHERE act = 'import_rows'").toArray(), ); const said = logged.map((a) => JSON.parse(a.args) as Record); expect(said).toContainEqual({ rows: 200, tables: { sealed_diary: 200 } }); expect(said.every((a) => !Array.isArray(a.rows))).toBe(true); }); it("never lets a sealed column's plaintext reach rows.data, change or acts (the guard)", async () => { const logged = await kept(slug); for (const w of SECRET_WORDS) { expect(holdsWord(logged.rows, w), w).toBe(false); expect(holdsWord(logged.change, w), w).toBe(false); expect(holdsWord(logged.acts, w), w).toBe(false); } }); }); /** RULE (sealing plan §2.2; seal-core's row vector): a row the Rust core sealed goes up through the act path, comes back as stored, and opens to the row it sealed; nothing of its plaintext stays on the object. */ describe("the core's sealed row through the object", () => { const slug = "sealed-vector"; // The vector's own table, laid in this synthetic object only: its spec and its columns, plain text so the object checks no link. // The kit's tools hold views over messages: what they sort and filter by stays clear (a view over a sealed column is refused), beside the vector's own clear columns. const messageOf = (viewed: string[]) => { const columns = [...new Set(["sent_at", "thread_id", "reply_to_id", "channel", "trashed_at", "body", "preview", "external_id", "sender_handle", "reactions", ...viewed])]; return { format_version: 1, id: vector.table, name: "Message", plural: "Messages", date: "sent_at", columns: columns.map((key) => ({ key, type: key.endsWith("_at") ? "date" : "text" })), seal: { ...vector.spec, clear: [...new Set([...vector.spec.clear, ...viewed])] }, }; }; const viewedColumns = async (credential: string): Promise => { const served = await http<{ tools: { views?: { read?: { table?: string; where?: Record }; sort?: { column?: string; tie?: string } }[] }[] }>(slug, "GET", "/v1/definitions", undefined, { authorization: `Bearer ${credential}` }); const out = new Set(); for (const tool of served.body.tools ?? []) { for (const v of tool.views ?? []) { if (v.read?.table !== vector.table) continue; for (const key of [v.sort?.column, v.sort?.tie, ...Object.keys(v.read.where ?? {})]) if (key) out.add(key); } } return [...out]; }; it("stores it opaque and hands it back to open whole", async () => { expect(vector.database_id).toBe(DATABASE_ID); const { credential } = await personalObject(slug, { windows: true }); const MESSAGE = messageOf(await viewedColumns(credential)); const laid = await http(slug, "POST", "/v1/admin/definitions/tables", { tables: [MESSAGE] }, ADMIN); expect(laid.status, JSON.stringify(laid.body)).toBe(200); const { id: _frame, ...data } = vector.stored; const made = await act(slug, credential, "create", { table: vector.table, id: vector.id, data }); expect(made.status, JSON.stringify(made.body)).toBe(200); const pulled = await http<{ rows: { table: string; id: string; data: Record }[] }>(slug, "GET", `/v1/sync?since=0&tables=${vector.table}`, undefined, { authorization: `Bearer ${credential}` }); const held = pulled.body.rows.find((r) => r.table === vector.table && r.id === vector.id)!; expect(held.data).toEqual(data); const tk = await tableKey(Uint8Array.from(vector.dk_hex.match(/../g)!.map((b) => parseInt(b, 16))), vector.database_id, vector.table, vector.seal_v); const { id: _id, ...sealedRow } = vector.row; expect(await openRow(tk, vector.database_id, vector.table, vector.id, held.data)).toEqual(sealedRow); const everything = await runInDurableObject(env.BUSINESS.get(env.BUSINESS.idFromName(slug)), (_instance, state) => JSON.stringify([state.storage.sql.exec("SELECT data FROM rows").toArray(), state.storage.sql.exec("SELECT before, after FROM change").toArray(), state.storage.sql.exec("SELECT args FROM acts").toArray()]), ); for (const w of ["Zanzibar", "wamid.", "+919876543210", "jetty"]) expect(holdsWord(everything, w), w).toBe(false); }); }); /** RULE (e2e rulings R2, 15 Nov 2026): what an assistant writes into a sealed table with no window open is sealed as it arrives, to the person's arrival key their phone handed the object; the object keeps no word of it in rows, change or acts, cannot read it back, and asks for a window when no arrival key is held. */ describe("sealed at arrival on the object", () => { const slug = "sealed-arrival"; let credential = ""; let owner = ""; const ARRIVAL_PUB = "A2gjfILDYh1lR_xtL79_FatTc-5b6r-VseMAgcIP1gI"; beforeAll(async () => { ({ credential, owner } = await personalObject(slug, { windows: true })); expect((await http(slug, "POST", "/v1/admin/definitions/tables", { tables: [DIARY] }, ADMIN)).status).toBe(200); }, 60_000); it("asks for a window until a phone hands over the arrival key, then seals what arrives to it", async () => { const write = { table: "sealed_diary", data: { written_at: "2026-11-15", body: "zanzibar under the quokka-lantern", external_id: "ext-7731" } }; expect(await refusal(slug, owner, "create_record", write)).toContain("are sealed"); // Only the owner's phone hands it over, once, and only a 32-byte key. expect((await act(slug, credential, "create", { table: "seal_key", id: "arrival", data: { pub: "not-a-key" } })).body).toMatchObject({ code: "bad_seal_key" }); expect((await act(slug, credential, "create", { table: "seal_key", id: "arrival", data: { pub: ARRIVAL_PUB } })).status).toBe(200); const other = "B2gjfILDYh1lR_xtL79_FatTc-5b6r-VseMAgcIP1gI"; expect((await act(slug, credential, "update", { table: "seal_key", id: "arrival", data: { pub: other } })).body).toMatchObject({ code: "arrival_key_held" }); const made = await answer<{ record: { id: string; data: Record; sealed: string }; sealed_at_arrival: string }>(slug, owner, "create_record", write); expect(made.record).toMatchObject({ data: { written_at: "2026-11-15" }, sealed: "sealed_at_arrival" }); expect(made.record.data.body, "the answer does not read it back").toBeUndefined(); expect(made.sealed_at_arrival).toContain("Only their devices open it"); const row = await runInDurableObject(env.BUSINESS.get(env.BUSINESS.idFromName(slug)), (_instance, state) => JSON.parse(state.storage.sql.exec<{ data: string }>("SELECT data FROM rows WHERE table_id = 'sealed_diary' AND id = ?", made.record.id).one().data) as Record, ); expect(row).toMatchObject({ written_at: "2026-11-15", seal_v: 0 }); expect(String(row.dek_enc)).toMatch(/^a1:/); expect(String(row.sealed_enc)).toMatch(/^s1:/); const everything = await kept(slug); for (const word of SECRET_WORDS) for (const [where, text] of Object.entries(everything)) expect(text.includes(word), `${word} in ${where}`).toBe(false); // Reading it back is the window's: the object cannot open what it sealed. expect(await refusal(slug, owner, "get_record_by_table", { table: "sealed_diary", id: made.record.id })).toContain("are sealed"); }); });