/** * LOCK TABLES 1, PROVEN ON A LOCAL DEV WORKER (assets/design/shared/LOCK-TABLES.md; test/seal-narrow.test.ts runs the * same in the pool). The kit narrows four sealed tables' clear lists (film and film_episode: subtitles, subtitle_note; * story_draft_scene: setting, place; meetings_meeting: marks). On one invented account: * 1. rows are planted sealed as a build before this one sealed them: the newly sealed columns beside the seal, in * the clear; seal-check counts them (clear_left), and a plain sync (what an older build does) serves them; * 2. the reseal the Mac's `seal-migrate --from-start` makes (cotton-client seal::migrate): each such row opened with * the data key, sealed again under the table's clear list now, staged, its twin read back and opened, committed, * and the act log purged; * 3. the server holds none of the planted words (export, seal-check clear_left 0, acts_plain 0); the phone opens * every row to what was planted; a plain sync still serves every row; a device's edit of a clear column is taken. * The phone and the Mac here are this script: its data key is made for the run and never leaves it. Invented data only; * refuses any server but a local wrangler dev or the dev Worker. * * pnpm -s exec tsx scripts/narrow-seal-proof.ts --base http://127.0.0.1: --number +1555XXXXXXX \ * --code-file --admin-token-file */ import { readFileSync } from "node:fs"; import { homedir } from "node:os"; import { blindKey, bodyAad, bucket, dekAad, parseSeal, rowTokens, tableKey } from "../src/seal.ts"; import { fromBase64Url, toBase64Url } from "../src/base64.ts"; import { signIn } from "./dev-seed/client.ts"; import { devBase } from "./dev-server"; const arg = (name: string, fallback?: string) => { const i = process.argv.indexOf(`--${name}`); return i > 0 ? process.argv[i + 1]! : fallback; }; const DEV = arg("base", devBase())!; if (DEV !== devBase() && !/^http:\/\/127\.0\.0\.1:\d+$/.test(DEV)) throw new Error("--base is the dev Worker or a local wrangler dev"); const NUMBER = arg("number"); if (!NUMBER || !/^\+1555\d{7}$/.test(NUMBER)) throw new Error("--number is an invented +1555 number"); const say = (line: string) => console.log(`[narrow-seal] ${new Date().toISOString().slice(11, 19)} ${line}`); const fail = (what: string): never => { throw new Error(what); }; const utf8 = new TextEncoder(); void fromBase64Url; void toBase64Url; /** What this build took out of each table's clear list: what an older build left beside the seal. */ const NARROWED: Record = { film: ["subtitles", "subtitle_note"], film_episode: ["subtitles", "subtitle_note"], story_draft_scene: ["setting", "place"], meetings_meeting: ["marks"], }; function canonical(v: unknown): string { if (v && typeof v === "object" && !Array.isArray(v)) { const o = v as Record; return `{${Object.keys(o).sort().map((k) => `${JSON.stringify(k)}:${canonical(o[k])}`).join(",")}}`; } return JSON.stringify(v); } async function gcm(key: Uint8Array, plain: Uint8Array, aad: string): Promise { 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 ungcm(key: Uint8Array, sealed: string, aad: string): Promise { const raw = fromBase64Url(sealed); const k = await crypto.subtle.importKey("raw", key, "AES-GCM", false, ["decrypt"]); return new Uint8Array(await crypto.subtle.decrypt({ name: "AES-GCM", iv: raw.subarray(0, 12), additionalData: utf8.encode(aad) }, k, raw.subarray(12))); } async function sealRow(dk: Uint8Array, db: string, table: string, id: string, inside: Record): Promise> { const text = canonical(inside); 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(db, table, id))}`, dek_enc: `d1:${await gcm(await tableKey(dk, db, table, 1), dek, dekAad(db, table, id, 1))}`, seal_v: 1, }; } /** A sealed row opened as the phone opens it: its data key's table key opens the row's key, which opens the body. */ async function openRow(dk: Uint8Array, db: string, table: string, id: string, data: Record): Promise> { const v = Number(data.seal_v); const dek = await ungcm(await tableKey(dk, db, table, v), String(data.dek_enc).slice(3), dekAad(db, table, id, v)); const body = JSON.parse(new TextDecoder().decode(await ungcm(dek, String(data.sealed_enc).slice(3), bodyAad(db, table, id))).trimEnd()) as Record; const clear = Object.fromEntries(Object.entries(data).filter(([k]) => !["sealed_enc", "dek_enc", "seal_v"].includes(k))); return { ...clear, ...body }; } // ── the local Worker ───────────────────────────────────────────────── async function call>(base: string, bearer: string, method: string, path: string, body?: unknown): Promise<{ status: number; body: T }> { for (let attempt = 0; ; attempt++) { try { const res = await fetch(`${base}${path}`, { method, headers: { "content-type": "application/json", authorization: `Bearer ${bearer}` }, body: body === undefined ? undefined : JSON.stringify(body) }); const text = await res.text(); if (res.status >= 500 && attempt < 4) throw new Error(`${res.status} ${text.slice(0, 200)}`); return { status: res.status, body: (text ? JSON.parse(text) : {}) as T }; } catch (error) { if (attempt >= 4) throw error; say(`retry ${method} ${path}: ${error instanceof Error ? error.message : String(error)}`); await new Promise((done) => setTimeout(done, 3_000 * (attempt + 1))); } } } type Row = { table: string; id: string; version: number; data: Record; deleted?: boolean }; async function main(): Promise { const code = readFileSync(arg("code-file", `${homedir()}/.cotton-credentials/cotton/dev-otp`)!, "utf8").replace(/\D/g, ""); const admin = readFileSync(arg("admin-token-file", `${homedir()}/.cotton-credentials/cloudflare/business-dev-admin-token`)!, "utf8").trim(); const s = await signIn(DEV, NUMBER!, code); const db = s.databaseId; const base = `${DEV}/b/p-${db}`; const phone = >(method: string, path: string, body?: unknown) => call(base, s.credential, method, path, body); const asAdmin = >(method: string, path: string, body?: unknown) => call(base, admin, method, path, body); const act = (name: string, args: Record) => phone("POST", "/v1/act", { act: name, args }); say(`signed in ${NUMBER} (database ${db.slice(0, 8)}…)`); const dk = crypto.getRandomValues(new Uint8Array(32)); const defs = (await phone<{ tables: Record[] }>("GET", "/v1/definitions")).body.tables; const defOf = (t: string) => defs.find((d) => d.id === t) ?? fail(`no definition of ${t}`); const clearNow = (t: string) => ((defOf(t).seal as { clear?: string[] } | undefined)?.clear ?? fail(`${t} has no seal block`)) as string[]; for (const [t, keys] of Object.entries(NARROWED)) for (const k of keys) if (clearNow(t).includes(k)) fail(`${t}.${k} is still clear in this build's definition`); // 1. Planted sealed as an older build sealed them: the narrowed columns beside the seal. const uuid = (kind: number, i: number) => `00000000-0000-4000-8${kind}00-${String(i).padStart(12, "0")}`; const planted: { table: string; id: string; data: Record }[] = []; const N = Number(arg("rows", "25")); for (let i = 0; i < N; i++) { planted.push({ table: "film", id: uuid(1, i), data: { title: `Invented heron film ${i}`, watched_on: "2026-11-20", subtitles: [{ language: "en", label: `saffron-subtitle-${i}` }], subtitle_note: `marigold-note-${i}` } }); planted.push({ table: "film_episode", id: uuid(2, i), data: { season: uuid(5, 0), number: i + 1, title: `Invented episode ${i}`, subtitles: [{ language: "fr", label: `cobalt-subtitle-${i}` }], subtitle_note: `juniper-note-${i}` } }); planted.push({ table: "story_draft_scene", id: uuid(3, i), data: { draft: uuid(6, 0), story: uuid(7, 0), scene: `Invented scene ${i}`, setting: "INT", place: `lantern-kitchen-${i}` } }); planted.push({ table: "meetings_meeting", id: `invented-take-${i}`, data: { take: `invented-take-${i}`, status: "done", marks: [{ at: 12, label: `pebble-mark-${i}` }] } }); } /** The words in the narrowed columns: what the server holds in the clear before, and must not after. */ const PLANTED = ["saffron-subtitle", "marigold-note", "cobalt-subtitle", "juniper-note", "lantern-kitchen", "pebble-mark"]; // Their parents, as this build seals them: the season the episodes belong to, the story and draft of the scenes. const parents = [ { table: "film_season", id: uuid(5, 0), data: { film: uuid(1, 0), number: 1, title: "Invented season" } }, { table: "story_story", id: uuid(7, 0), data: { title: "Invented story" } }, { table: "story_draft", id: uuid(6, 0), data: { story: uuid(7, 0), name: "Invented draft" } }, ]; const parentRows: Record[] = []; for (const p of parents) { const clear: Record = {}; const inside: Record = {}; for (const [k, v] of Object.entries(p.data)) (clearNow(p.table).includes(k) ? clear : inside)[k] = v; parentRows.push({ verb: "put", table: p.table, id: p.id, data: { ...clear, ...(await sealRow(dk, db, p.table, p.id, inside)) } }); } planted.sort((x, y) => Number(y.table === "film") - Number(x.table === "film")); const rows: Record[] = []; for (const p of planted) { if (p.table !== "film" && rows.length === N) rows.push(...parentRows); const oldClear = [...clearNow(p.table), ...NARROWED[p.table]!]; const clear: Record = {}; const inside: Record = {}; for (const [k, v] of Object.entries(p.data)) (oldClear.includes(k) ? clear : inside)[k] = v; rows.push({ verb: "put", table: p.table, id: p.id, data: { ...clear, ...(await sealRow(dk, db, p.table, p.id, inside)) } }); } // The object refuses a sealed column in the clear under this build's definitions (sealed_in_clear), so the older // build's state is made as it was made: its wider clear lists in place while the rows land, then this build's back. const define = async (tables: Record[], what: string) => { const r = await asAdmin("POST", "/v1/admin/definitions/tables", { tables }); if (r.status !== 200) fail(`${what}: ${r.status} ${JSON.stringify(r.body).slice(0, 300)}`); }; const current = Object.keys(NARROWED).map((t) => defOf(t)); await define(current.map((d) => ({ ...d, seal: { ...(d.seal as Record), clear: [...clearNow(String(d.id)), ...NARROWED[String(d.id)]!] } })), "the older build's definitions"); for (let i = 0; i < rows.length; i += 200) { const r = await asAdmin("POST", "/v1/admin/import", { rows: rows.slice(i, i + 200) }); if (r.status !== 200) fail(`import: ${r.status} ${JSON.stringify(r.body).slice(0, 300)}`); } await define(current, "this build's definitions back"); const back = (await phone<{ tables: Record[] }>("GET", "/v1/definitions")).body.tables; for (const d of current) if (canonical(back.find((x) => x.id === d.id)?.seal) !== canonical(d.seal)) fail(`${String(d.id)}: this build's seal block is not back`); type Check = { tables: { table: string; rows?: number; sealed?: number; open?: number; clear_left?: number; acts_plain?: number; twins?: number }[] }; const check = async () => (await asAdmin("GET", "/v1/admin/seal-check")).body.tables.filter((t) => t.table in NARROWED); const standing = (c: Check["tables"]) => c.map((t) => `${t.table} ${t.sealed}/${t.rows} sealed, ${t.clear_left} with columns left clear, ${t.acts_plain ?? 0} in the act log`).join("; "); const before = await check(); say(`before: ${standing(before)}`); if (before.some((t) => (t.clear_left ?? 0) < N)) fail("seal-check does not count the rows sealed under the wider lists"); const synced = async (): Promise => { const out: Row[] = []; let path = `/v1/sync?since=0&tables=${Object.keys(NARROWED).join(",")}&limit=5000`; for (;;) { const page = (await phone<{ rows: Row[]; next?: string }>("GET", path)).body; out.push(...page.rows.filter((x) => x.table in NARROWED && !x.deleted)); if (!page.next) return out; path = `/v1/sync?cursor=${encodeURIComponent(page.next)}`; } }; const servedBefore = await synced(); const clearHeld = JSON.stringify(servedBefore); say(`a plain sync (an older build's) serves ${servedBefore.length} rows; the server holds ${PLANTED.filter((w) => clearHeld.includes(w)).join(", ") || "none"} in the clear`); // 2. The reseal, as cotton-client seal::migrate makes it for a row sealed with columns left clear. let resealed = 0; for (const table of Object.keys(NARROWED)) { const raw = defOf(table); const spec = parseSeal(raw) ?? fail(`${table}: no seal`); const bk = await blindKey(dk, db, table); const mine = servedBefore.filter((r) => r.table === table && NARROWED[table]!.some((k) => r.data[k] !== undefined && r.data[k] !== null)); for (let i = 0; i < mine.length; i += 100) { const batch = mine.slice(i, i + 100); const opened = new Map>(); const stageRows: Record[] = []; for (const r of batch) { const plain = await openRow(dk, db, table, r.id, r.data); opened.set(r.id, plain); const clear: Record = {}; const inside: Record = {}; for (const [k, v] of Object.entries(plain)) (clearNow(table).includes(k) ? clear : inside)[k] = v; stageRows.push({ id: r.id, expect_version: r.version, data: { ...clear, ...(await sealRow(dk, db, table, r.id, inside)) }, blind: await rowTokens(bk, raw, spec, plain) }); } const staged = await act("seal_stage", { table, rows: stageRows }); if (staged.status !== 200) fail(`seal_stage ${table}: ${staged.status} ${JSON.stringify(staged.body).slice(0, 300)}`); const twinIds = (staged.body.staged as { id: string; twin: string }[]).map((t) => t.twin); const twins = (await phone<{ twins: { twin: string; id: string; data: Record }[] }>("GET", `/v1/seal/twins?table=${table}&twins=${twinIds.join(",")}`)).body.twins; const verified: string[] = []; for (const t of twins) { const back = await openRow(dk, db, table, t.id, t.data); if (canonical(back) === canonical(opened.get(t.id))) verified.push(t.twin); } const committed = await act("seal_commit", { table, twins: verified }); if (committed.status !== 200) fail(`seal_commit ${table}: ${committed.status} ${JSON.stringify(committed.body).slice(0, 300)}`); resealed += (committed.body.sealed as string[]).length; } const purged = await act("seal_purge", { table }); if (purged.status !== 200) fail(`seal_purge ${table}: ${purged.status} ${JSON.stringify(purged.body).slice(0, 200)}`); } say(`resealed ${resealed} rows (staged, twins read back and opened, committed), act log purged`); // 3a. The server holds none. let held = ""; for (let afterKey: string | null = null; ; ) { const page: { rows: { table: string; data: unknown }[]; next: string | null } = (await asAdmin<{ rows: { table: string; data: unknown }[]; next: string | null }>("GET", `/v1/admin/export?limit=5000${afterKey ? `&after=${encodeURIComponent(afterKey)}` : ""}`)).body; held += JSON.stringify(page.rows.filter((r) => r.table in NARROWED)); if (!page.next) break; afterKey = page.next; } const inClear = PLANTED.filter((w) => held.includes(w)); const after = await check(); say(`after: ${standing(after)}; export ${inClear.length ? `HOLDS ${inClear.join(", ")}` : "holds none of the planted words"}`); if (inClear.length || after.some((t) => (t.clear_left ?? 0) > 0 || (t.acts_plain ?? 0) > 0 || (t.twins ?? 0) > 0)) fail("the server still reads planted words"); // 3b. The phone opens every row to what was planted; a plain sync serves every row; a clear edit is taken. const served = await synced(); const byKey = new Map(served.map((r) => [`${r.table}/${r.id}`, r])); const differs: string[] = []; for (const p of planted) { const r = byKey.get(`${p.table}/${p.id}`) ?? fail(`${p.table}/${p.id} is not served`); const got = await openRow(dk, db, p.table, p.id, r.data); for (const [k, v] of Object.entries(p.data)) if (canonical(got[k]) !== canonical(v)) differs.push(`${p.table}/${p.id}.${k}`); } const film = byKey.get(`film/${uuid(1, 0)}`)!; const edit = await act("update", { table: "film", id: film.id, data: { watched_on: "2026-11-21" } }); const clearEdit = await act("update", { table: "film", id: film.id, data: { subtitle_note: "a clear note" } }); say(`owner: the phone opened ${planted.length - differs.length} of ${planted.length} rows to what was planted; a plain sync serves ${served.length}; an edit of a clear column ${edit.status}${edit.status === 200 ? "" : ` ${JSON.stringify(edit.body).slice(0, 160)}`}, a clear write of a sealed one ${clearEdit.status} ${String((clearEdit.body as { code?: string }).code ?? "")}`); if (differs.length || served.length !== planted.length || edit.status !== 200 || clearEdit.status === 200) fail(`the owner does not read all: ${differs.slice(0, 5).join(", ")}`); say("LOCK TABLES 1 proven: rows sealed under the wider lists are sealed again whole; the server holds none of them, the owner reads all"); } main().catch((error) => { console.error(`[narrow-seal] ${error instanceof Error ? error.message : String(error)}`); process.exit(1); });