/** * LOCK TABLES 1 (assets/design/shared/LOCK-TABLES.md): a sealed table whose clear list narrows. Rows sealed under the * old list still hold the newly sealed columns in the clear beside their seal. seal-check counts them (`clear_left`), * and the same migration that seals open rows (stage, read back, commit; the Mac's seal-migrate) reseals them whole: * the clear copies go from the row and its logged changes, and the owner opens every value as before. * * LOCK TABLES 2 (H1, the rule for every narrowing: assets/design/shared/SEALING-CONTRACT.md): a phone still holding the * wider list, offline across the narrowing, is never refused for it. A newly sealed column it says with a value is * stored and the row marked sealed wide for the reseal; one it says empty is dropped; the answer says its definitions * are old. (M1) The reseal's commit drops the clear copy of any key the device sealed, a column or not. * Synthetic rows only. */ import { env, runInDurableObject } from "cloudflare:test"; import { beforeAll, describe, expect, it } from "vitest"; import { openRow, tableKey } from "../src/seal.ts"; import { ADMIN, DATABASE_ID, http, personalObject, TODOS_OPEN } from "./personal.ts"; import { rowTokens, sealRow } from "./seal-device.ts"; const WIDE = { clear: ["seen_on", "tracks", "note"], blind: ["title"] }; const NARROW = { clear: ["seen_on"], blind: ["title"] }; const DEF = { format_version: 1, id: "narrowed_film", name: "Narrowed film", plural: "Narrowed films", title: "title", date: "seen_on", columns: [ { key: "seen_on", type: "date" }, { key: "title", type: "text" }, { key: "tracks", type: "longtext" }, { key: "note", type: "text" }, ], }; const TABLE = DEF.id; const DK = Uint8Array.from({ length: 32 }, (_, i) => (i * 11 + 5) & 0xff); const WORDS = ["saffron-subtitle", "marigold-note"]; const act = (slug: string, credential: string, name: string, args: Record) => http(slug, "POST", "/v1/act", { act: name, args }, { authorization: `Bearer ${credential}` }); const onObject = (slug: string, fn: (sql: SqlStorage) => T) => runInDurableObject(env.BUSINESS.get(env.BUSINESS.idFromName(slug)), (_i, state) => fn(state.storage.sql)); const held = (slug: string, id: string) => onObject(slug, (sql) => { const r = sql.exec<{ version: number; data: string }>("SELECT version, data FROM rows WHERE table_id = ? AND id = ?", TABLE, id).one(); return { version: Number(r.version), data: JSON.parse(r.data) as Record }; }); /** A row as the device seals it under `spec`: the clear columns beside a seal of the rest, and its tokens. */ async function sealedUnder(spec: { clear: string[]; blind: string[] }, id: string, row: Record): Promise<{ data: Record; blind: string[] }> { const clear: Record = {}; const inside: Record = {}; for (const [k, v] of Object.entries(row)) (spec.clear.includes(k) ? clear : inside)[k] = v; return { data: { ...clear, ...(await sealRow(DK, TABLE, id, 1, inside)) }, blind: await rowTokens(DK, TABLE, spec, row) }; } describe("a sealed table whose clear list narrows", () => { const slug = "seal-narrow"; let credential = ""; const id = crypto.randomUUID(); const row = { seen_on: "2026-11-20", title: "The Heron", tracks: `[{"language":"en","label":"${WORDS[0]}"}]`, note: WORDS[1] }; beforeAll(async () => { ({ credential } = await personalObject(slug, { open: TODOS_OPEN })); // Sealed with the wide list, as a build before this one sealed it: tracks and note left beside the seal. const wide = await http(slug, "POST", "/v1/admin/definitions/tables", { tables: [{ ...DEF, seal: WIDE }] }, ADMIN); expect(wide.status, JSON.stringify(wide.body)).toBe(200); const s = await sealedUnder(WIDE, id, row); const made = await act(slug, credential, "create", { table: TABLE, id, data: s.data, blind: s.blind }); expect(made.status, JSON.stringify(made.body)).toBe(200); // Then the list narrows (this build's definition). expect((await http(slug, "POST", "/v1/admin/definitions/tables", { tables: [{ ...DEF, seal: NARROW }] }, ADMIN)).status).toBe(200); }, 120_000); it("is counted by seal-check as sealed rows with columns left in the clear, never saying them", async () => { const check = await http<{ tables: Record[] }>(slug, "GET", "/v1/admin/seal-check", undefined, ADMIN); expect(check.status).toBe(200); expect(check.body.tables.find((t) => t.table === TABLE)).toMatchObject({ rows: 1, sealed: 1, open: 0, clear_left: 1 }); for (const w of WORDS) expect(JSON.stringify(check.body)).not.toContain(w); }); it("takes an old phone's edit sealed under the wider list: a value kept and marked, an empty one dropped, the answer says its definitions are old", async () => { // The phone saved this offline before the narrowing reached it, and sends its whole row sealed under the list it holds. const edited = { ...row, seen_on: "2026-11-21", tracks: `[{"language":"fr","label":"${WORDS[0]}"}]`, note: null }; const s = await sealedUnder(WIDE, id, edited); const answer = await act(slug, credential, "update", { table: TABLE, id, data: s.data, blind: s.blind }); expect(answer.status, JSON.stringify(answer.body)).toBe(200); expect(answer.body).toMatchObject({ definitions_stale: true }); const stored = await held(slug, id); expect(stored.data.tracks).toBe(edited.tracks); expect("note" in stored.data).toBe(false); const check = await http<{ tables: Record[] }>(slug, "GET", "/v1/admin/seal-check", undefined, ADMIN); expect(check.body.tables.find((t) => t.table === TABLE)).toMatchObject({ sealed: 1, clear_left: 1, wide: 1, was_clear: ["note", "tracks"] }); for (const w of WORDS) expect(JSON.stringify(check.body)).not.toContain(w); // The row opens to what the phone wrote; its note was empty. expect(await openRow(await tableKey(DK, DATABASE_ID, TABLE, 1), DATABASE_ID, TABLE, id, stored.data)).toMatchObject({ seen_on: edited.seen_on, title: row.title, tracks: edited.tracks }); row.seen_on = edited.seen_on; row.tracks = edited.tracks; delete (row as Partial).note; }); it("takes an old phone's edit whose newly sealed columns are all empty, holding nothing of them in the clear", async () => { const other = crypto.randomUUID(); const made = await sealedUnder(NARROW, other, { seen_on: "2026-11-22", title: "The Egret" }); expect((await act(slug, credential, "create", { table: TABLE, id: other, data: made.data, blind: made.blind })).status).toBe(200); const s = await sealedUnder(WIDE, other, { seen_on: "2026-11-23", title: "The Egret", tracks: null, note: "" }); const answer = await act(slug, credential, "update", { table: TABLE, id: other, data: s.data, blind: s.blind }); expect(answer.status, JSON.stringify(answer.body)).toBe(200); expect(answer.body).toMatchObject({ definitions_stale: true }); expect(Object.keys((await held(slug, other)).data).sort()).toEqual(["dek_enc", "seal_v", "sealed_enc", "seen_on"]); // A new row from the same phone, made offline, lands too. const fresh = crypto.randomUUID(); const f = await sealedUnder(WIDE, fresh, { seen_on: "2026-11-24", title: "The Crane", tracks: "", note: "kept-note" }); const madeOld = await act(slug, credential, "create", { table: TABLE, id: fresh, data: f.data, blind: f.blind }); expect(madeOld.status, JSON.stringify(madeOld.body)).toBe(200); expect((await held(slug, fresh)).data).toMatchObject({ note: "kept-note" }); expect("tracks" in (await held(slug, fresh)).data).toBe(false); // Through seal_many as well (the phone's sweep): the same rule. const sweep = await sealedUnder(WIDE, other, { seen_on: "2026-11-25", title: "The Egret", tracks: null, note: null }); const many = await act(slug, credential, "seal_many", { rows: [{ table: TABLE, id: other, expect_version: (await held(slug, other)).version, data: sweep.data, blind: sweep.blind }] }); expect(many.body).toMatchObject({ results: [{ ok: true }], definitions_stale: true }); // A column no list ever kept clear is still refused in the clear. const leaked = await act(slug, credential, "update", { table: TABLE, id: other, data: { ...sweep.data, title: "in the clear" } }); expect(leaked.body).toMatchObject({ code: "sealed_in_clear" }); // A phone that holds the narrow list is told nothing. const now = await sealedUnder(NARROW, other, { seen_on: "2026-11-26", title: "The Egret" }); const current = await act(slug, credential, "update", { table: TABLE, id: other, data: now.data, blind: now.blind }); expect(current.status).toBe(200); expect(current.body.definitions_stale).toBeUndefined(); // The two side rows go: the reseal below is the first row's. for (const gone of [other, fresh]) expect((await act(slug, credential, "delete", { table: TABLE, id: gone })).status).toBe(200); }); it("is resealed whole by the migration's stage and commit: nothing left clear, every value still opens", async () => { const before = await held(slug, id); // The device opens what is stored (the seal, and the clear columns beside it) and seals it again under the narrow list. const opened = await openRow(await tableKey(DK, DATABASE_ID, TABLE, 1), DATABASE_ID, TABLE, id, before.data); expect(opened).toMatchObject(row); const again = await sealedUnder(NARROW, id, opened); const staged = await act(slug, credential, "seal_stage", { table: TABLE, rows: [{ id, expect_version: before.version, data: again.data, blind: again.blind }] }); expect(staged.status, JSON.stringify(staged.body)).toBe(200); const twin = (staged.body.staged as { twin: string }[])[0]!.twin; const committed = await act(slug, credential, "seal_commit", { table: TABLE, twins: [twin] }); expect(committed.body).toMatchObject({ sealed: [id], left: [] }); const after = await held(slug, id); expect(Object.keys(after.data).sort()).toEqual(["dek_enc", "seal_v", "sealed_enc", "seen_on"]); expect(await openRow(await tableKey(DK, DATABASE_ID, TABLE, 1), DATABASE_ID, TABLE, id, after.data)).toMatchObject(row); // Gone from the row and from its logged changes; the act log's copies go with seal_purge. expect((await act(slug, credential, "seal_purge", { table: TABLE })).status).toBe(200); const kept = await onObject(slug, (sql) => JSON.stringify([sql.exec("SELECT data FROM rows WHERE table_id = ?", TABLE).toArray(), sql.exec("SELECT before, after FROM change WHERE table_id = ?", TABLE).toArray(), sql.exec("SELECT args FROM acts").toArray()])); for (const w of WORDS) expect(kept).not.toContain(w); // The deleted row's history too: the old phone's note was taken in the clear and logged before the row went. expect(kept).not.toContain("kept-note"); const check = await http<{ tables: Record[] }>(slug, "GET", "/v1/admin/seal-check", undefined, ADMIN); expect(check.body.tables.find((t) => t.table === TABLE)).toMatchObject({ sealed: 1, clear_left: 0, acts_plain: 0, wide: 0 }); }); it("drops the clear copy of a key that is no column once the reseal sealed it, so the row opens (M1)", async () => { // A key a definition has since dropped, held beside the seal (planted: no write today can put one there). await onObject(slug, (sql) => sql.exec("UPDATE rows SET data = json_set(data, '$.old_rating', 'four-stars') WHERE table_id = ? AND id = ?", TABLE, id)); let check = await http<{ tables: Record[] }>(slug, "GET", "/v1/admin/seal-check", undefined, ADMIN); expect(check.body.tables.find((t) => t.table === TABLE)).toMatchObject({ clear_left: 1, stray: 1 }); expect(JSON.stringify(check.body)).not.toContain("four-stars"); const before = await held(slug, id); const opened = await openRow(await tableKey(DK, DATABASE_ID, TABLE, 1), DATABASE_ID, TABLE, id, before.data); expect(opened).toMatchObject({ old_rating: "four-stars" }); // The device seals every key the list does not keep clear, as cotton-client seal::migrate does. const again = await sealedUnder(NARROW, id, opened); const staged = await act(slug, credential, "seal_stage", { table: TABLE, rows: [{ id, expect_version: before.version, data: again.data, blind: again.blind }] }); const twin = (staged.body.staged as { twin: string }[])[0]!.twin; expect((await act(slug, credential, "seal_commit", { table: TABLE, twins: [twin] })).body).toMatchObject({ sealed: [id] }); const after = await held(slug, id); expect(Object.keys(after.data).sort()).toEqual(["dek_enc", "seal_v", "sealed_enc", "seen_on"]); expect(await openRow(await tableKey(DK, DATABASE_ID, TABLE, 1), DATABASE_ID, TABLE, id, after.data)).toMatchObject({ old_rating: "four-stars" }); check = await http<{ tables: Record[] }>(slug, "GET", "/v1/admin/seal-check", undefined, ADMIN); expect(check.body.tables.find((t) => t.table === TABLE)).toMatchObject({ clear_left: 0, stray: 0 }); }); it("the kit's narrowed tables: Story's headings, film subtitles, meeting marks and part 4's fields are sealed", async () => { const defs = (await http<{ tables: { id: string; seal?: { clear: string[] } }[] }>(slug, "GET", "/v1/definitions", undefined, { authorization: `Bearer ${credential}` })).body.tables; const clearOf = (table: string) => defs.find((t) => t.id === table)?.seal?.clear ?? []; for (const k of ["setting", "place"]) expect(clearOf("story_draft_scene"), k).not.toContain(k); for (const table of ["film", "film_episode"]) for (const k of ["subtitles", "subtitle_note"]) expect(clearOf(table), `${table}.${k}`).not.toContain(k); expect(clearOf("meetings_meeting")).not.toContain("marks"); // What the server's own code reads stays clear (LOCK-TABLES.md names the route for each). expect(clearOf("film")).toEqual(expect.arrayContaining(["subtitle_work", "subtitle_given", "filled_from"])); expect(clearOf("meetings_meeting")).toEqual(expect.arrayContaining(["status", "status_why"])); // LOCK TABLES 2 part 4 (LOCK-TABLES.md ยง6): what the server never reads is sealed; what it reads stays clear. for (const k of ["ical_uid", "timezone"]) expect(clearOf("event"), `event.${k}`).not.toContain(k); expect(clearOf("event")).toEqual(expect.arrayContaining(["rrule", "exdates", "account", "gcal_id", "gcal_etag", "sync_state"])); for (const k of ["speakers", "languages", "call", "languages_chosen"]) expect(clearOf("meetings_meeting"), `meetings_meeting.${k}`).not.toContain(k); expect(clearOf("story_answer")).not.toContain("question"); expect(clearOf("assistant_ask")).not.toContain("client"); expect(clearOf("assistant_ask")).toEqual(expect.arrayContaining(["token_id", "state", "expires_at"])); expect(clearOf("outbox")).not.toContain("account"); expect(clearOf("outbox")).toContain("status"); for (const table of ["film", "film_episode"]) { for (const k of ["sha256", "oshash", "original_sha256", "minutes", "height", "bitrate"]) expect(clearOf(table), `${table}.${k}`).not.toContain(k); expect(clearOf(table)).toEqual(expect.arrayContaining(["file", "original", "subtitle_work", "needs_mac"])); } // Each move is on record, so an old phone's write of one in the clear is taken, never refused (SEALING-CONTRACT.md). const was = await onObject(slug, (sql) => sql.exec<{ t: string }>("SELECT table_id || '.' || col AS t FROM seal_was_clear").toArray().map((r) => r.t)); for (const k of ["event.ical_uid", "event.timezone", "meetings_meeting.speakers", "meetings_meeting.languages", "meetings_meeting.call", "meetings_meeting.languages_chosen", "story_answer.question", "assistant_ask.client", "outbox.account", "film.sha256", "film.oshash", "film_episode.minutes", "film_episode.original_sha256"]) expect(was).toContain(k); }); });