/** * RESTORE AUDIT (coordinator, 27 Nov 2026): `GET /v1/admin/restore-audit`, read-only, the admin token alone. It answers * whether the act `restore` ever laid rows into mcp_token or device for a caller that was not the owner's phone, from * the acts log and from token or device rows no change row explains. Ids, times and counts only. Invented rows only. */ import { env, runInDurableObject } from "cloudflare:test"; import { describe, expect, it } from "vitest"; import type { Business } from "../src/business.ts"; import { SILENT_STAMPS } from "../src/row_witness.ts"; import BUSINESS_SOURCE from "../src/business.ts?raw"; import SYNC_STATUS_SOURCE from "../src/sync_status.ts?raw"; import { ADMIN, http, mint, personalObject, tool } from "./personal.ts"; const stub = (slug: string) => env.BUSINESS.get(env.BUSINESS.idFromName(slug)); interface Audit { restores: { total: number; by_owner_device: number; by_token_or_admin: number; by_token_or_admin_refused: number }; suspect_restores: { at: string; by: string; done: boolean; named: Record }[]; token_and_device_rows: number; unexplained_rows: { table: string; id: string; version: number; deleted: boolean; why?: string }[]; not_judged?: number; witness_from?: string | null; } describe("the restore audit", () => { const slug = "restore-audit"; it("is clean on an account that never let a token restore, and names a planted token row and its act, ids only", async () => { const { owner } = await personalObject(slug); expect((await http(slug, "GET", "/v1/admin/restore-audit", undefined, { authorization: `Bearer ${owner}` })).status).toBe(403); // A token's refused try is logged and counted, never a suspect. await http(slug, "POST", "/v1/act", { act: "restore", args: { rows: [{ table: "mcp_token", id: "tried", data: { name: "x" } }] } }, { authorization: `Bearer ${owner}` }); const clean = await http(slug, "GET", "/v1/admin/restore-audit", undefined, ADMIN); expect(clean.status, JSON.stringify(clean.body)).toBe(200); expect(clean.body.restores.by_token_or_admin_refused).toBe(1); expect(clean.body.suspect_restores).toEqual([]); expect(clean.body.token_and_device_rows).toBeGreaterThan(0); expect(clean.body.unexplained_rows, "a token and a device made the ordinary way are explained by the change log").toEqual([]); // What the hole would have left before ca7b919c69: a done restore by a token, and a token row with no change row. await runInDurableObject(stub(slug), (_i, state) => { const sql = state.storage.sql; const version = Number(sql.exec<{ v: number }>("SELECT MAX(version) AS v FROM change").one().v) + 1; sql.exec("INSERT INTO acts (id, at, person_id, act, args, outcome) VALUES ('planted-act', ?, NULL, 'restore', ?, 'done')", new Date().toISOString(), JSON.stringify({ rows: 1, tables: { mcp_token: 1 } })); sql.exec("INSERT INTO rows (table_id, id, data, owner, version, deleted, created_at, updated_at) VALUES ('mcp_token', 'planted-token', ?, NULL, ?, 0, ?, ?)", JSON.stringify({ name: "secret-name", token_hash: "f".repeat(64) }), version, "2026-01-01T00:00:00.000Z", "2026-01-01T00:00:00.000Z"); }); const found = await http(slug, "GET", "/v1/admin/restore-audit", undefined, ADMIN); expect(found.body.suspect_restores).toHaveLength(1); expect(found.body.suspect_restores[0]).toMatchObject({ by: "token_or_admin", done: true, named: { mcp_token: 1 } }); expect(found.body.unexplained_rows.map((r) => `${r.table}/${r.id}`)).toEqual(["mcp_token/planted-token"]); expect(JSON.stringify(found.body)).not.toMatch(/secret-name|ffff/); }); }); /** * RESTORE AUDIT 2 (coordinator, 27 Nov 2026): each token and device row is held to what its last logged write left * (src/row_witness.ts), less the object's own silent stamps. A row with none was laid by no logged create (a restore); * one that differs but for the stamps was rewritten; neither is laundered by a later stamp. */ describe("the restore audit decides", () => { const audit = async (slug: string) => (await http(slug, "GET", "/v1/admin/restore-audit", undefined, ADMIN)).body; const flagged = (a: Audit) => a.unexplained_rows.map((r) => `${r.table}/${r.id}:${r.why}`); const tokenId = async (slug: string, name: string) => 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') = ?", name).one().id); const bumpWith = (slug: string, sqlText: string, ...args: unknown[]) => runInDurableObject(stub(slug), (_i, state) => { const sql = state.storage.sql; const version = Number(sql.exec<{ v: number }>("SELECT MAX(version) AS v FROM rows").one().v) + 1; sql.exec(sqlText, ...args, version); }); it("is clean for tokens and devices made and stamped the ordinary way: last use, an end made early, a device's passes", async () => { const slug = "restore-audit-2-clean"; const { credential, owner } = await personalObject(slug); const used = await mint(slug, credential, "used token", ["read"]); // A device's passes: filed on its first page that names it, restated and its pass written after. const facts = `device_name=${encodeURIComponent("Invented Phone")}&platform=android&app_version=${encodeURIComponent("1.0 (1)")}`; await http(slug, "GET", `/v1/sync?since=0&${facts}`, undefined, { authorization: `Bearer ${credential}` }); await http(slug, "GET", `/v1/sync?since=0&${facts.replace("1.0%20(1)", "1.1%20(2)")}`, undefined, { authorization: `Bearer ${credential}` }); // A token's last use (stampUsed), and the object ending one early (renewLegacy's write). await tool(slug, used, "list_projects", {}); await tool(slug, owner, "list_projects", {}); const id = await tokenId(slug, "used token"); await runInDurableObject(stub(slug), (instance: Business) => { (instance as unknown as { renewLegacy(id: string, r: Request): Response }).renewLegacy(id, new Request("https://example.test/mcp", { method: "POST" })); }); const a = await audit(slug); expect(a.unexplained_rows, JSON.stringify(a.unexplained_rows)).toEqual([]); expect(a.token_and_device_rows).toBeGreaterThan(2); }); it("flags a row a restore laid, still after the object stamps it, and a row rewritten or given a later end", async () => { const slug = "restore-audit-2-flags"; const { credential } = await personalObject(slug); await mint(slug, credential, "rewritten token", ["read"]); await mint(slug, credential, "extended token", ["read"], 7); await mint(slug, credential, "ended early token", ["read"], 7); // Laid by a restore: no change row, no witness. await bumpWith(slug, "INSERT INTO rows (table_id, id, data, owner, version, deleted, created_at, updated_at) VALUES ('mcp_token', 'restored-token', ?, NULL, ?, 0, ?, ?)", JSON.stringify({ name: "restored", token_hash: "e".repeat(64), scopes: ["owner"] }), "2026-01-01T00:00:00.000Z", "2026-01-01T00:00:00.000Z"); // ...and stamped since by the object, as its first use would. await runInDurableObject(stub(slug), (instance: Business) => { (instance as unknown as { stampUsed(id: string): void }).stampUsed("restored-token"); }); // An existing token's hash and scopes rewritten in place; another's end moved later; a third's earlier. const rewritten = await tokenId(slug, "rewritten token"); const extended = await tokenId(slug, "extended token"); const early = await tokenId(slug, "ended early token"); await runInDurableObject(stub(slug), (_i, state) => { const sql = state.storage.sql; sql.exec("UPDATE rows SET data = json_set(data, '$.token_hash', ?, '$.scopes', json('[\"owner\"]')) WHERE table_id = 'mcp_token' AND id = ?", "d".repeat(64), rewritten); sql.exec("UPDATE rows SET data = json_set(data, '$.expires_at', '2099-01-01T00:00:00.000Z') WHERE table_id = 'mcp_token' AND id = ?", extended); sql.exec("UPDATE rows SET data = json_set(data, '$.expires_at', '2026-01-02T00:00:00.000Z') WHERE table_id = 'mcp_token' AND id = ?", early); }); const a = await audit(slug); expect(flagged(a).sort()).toEqual([`mcp_token/${extended}:differs`, `mcp_token/${rewritten}:differs`, "mcp_token/restored-token:no_logged_create"].sort()); // Ids, times and why only. expect(JSON.stringify(a)).not.toMatch(/eeee|dddd|restored"|rewritten token|"owner"/); }); it("adopts the rows standing when witnesses began as not judged, and judges a later restore over one", async () => { const slug = "restore-audit-2-adopted"; const { credential } = await personalObject(slug); await mint(slug, credential, "old token", ["read"]); const old = await tokenId(slug, "old token"); // As an object from before RESTORE AUDIT 2: no witness yet, then the first wake after the deploy adopts. await runInDurableObject(stub(slug), (_i, state) => { state.storage.sql.exec("DELETE FROM row_witness"); state.storage.sql.exec("DELETE FROM meta WHERE key = 'row_witness_from'"); }); await runInDurableObject(stub(slug), async (_i, state) => { const { adopt } = await import("../src/row_witness.ts"); adopt(state.storage.sql, new Date().toISOString(), { get: (k) => state.storage.sql.exec<{ value: string }>("SELECT value FROM meta WHERE key = ?", k).toArray()[0]?.value ?? null, set: (k, v) => void state.storage.sql.exec("INSERT INTO meta (key, value) VALUES (?, ?) ON CONFLICT (key) DO UPDATE SET value = excluded.value", k, v), }); }); const before = await audit(slug); expect(before.unexplained_rows).toEqual([]); expect(before.not_judged).toBe(before.token_and_device_rows); await runInDurableObject(stub(slug), (_i, state) => { state.storage.sql.exec("UPDATE rows SET data = json_set(data, '$.token_hash', ?) WHERE table_id = 'mcp_token' AND id = ?", "c".repeat(64), old); }); expect(flagged(await audit(slug))).toEqual([`mcp_token/${old}:differs`]); }); it("names every silent stamp on these tables in one list (row_witness SILENT_STAMPS), which the writes take their keys from", () => { // business.ts: every update with no journal (a thrown-away Outcome_) names its fields through stampOf, or is on a table the audit does not watch. const silent = BUSINESS_SOURCE.split("\n").filter((line) => /\.update\(/.test(line) && /new Outcome_\(\)/.test(line)); const OTHER_TABLES = ["state, status, answer"]; // ownerAsks' ask row for (const line of silent) expect(line.includes("stampOf(") || OTHER_TABLES.some((o) => line.includes(o)), line.trim()).toBe(true); for (const field of ["last_used_at", "expires_at"]) expect(BUSINESS_SOURCE).toContain(`stampOf("mcp_token", "${field}")`); // sync_status.ts: every patch it writes on a device row is a DeviceStamp, typed by SILENT_STAMPS.device. const patches = SYNC_STATUS_SOURCE.split("\n").filter((line) => /const patch\b/.test(line)); expect(patches.length).toBeGreaterThanOrEqual(2); for (const line of patches) expect(line, line.trim()).toContain(": DeviceStamp"); expect([...SILENT_STAMPS.device]).toEqual(expect.arrayContaining(["name", "platform", "app_version", "synced_at", "sync_version", "sync_rows_total", "sync_rows_done", "caught_up"])); }); });