Cotton code
320 lines · 18.8 KB · TypeScriptRaw
/** * RESTORE PROOF 1 (coordinator for the owner, 27 Nov 2026). Durable Object point-in-time recovery on the DEV Worker, * proven row for row on a throwaway invented account, against three kinds of damage: * *   A. 1,000 rows deleted through the normal door (POST /v1/act delete from the account's own signed-in device), so *      their tombstones are what any phone's next pull would carry; *   B. a bad update over every row (seal_many from the same device: every sealed block replaced by garbage at its *      current version, as a broken build or migration would); *   C. deleteAll: the account deleted the app's way, its thirty days brought to now (erase-now, dev only), and the *      erase run to its end (rows, files and storage gone, the directory told). * * After each, the object is restored to bookmark B0 (taken before any damage) and the account's live rows are read * whole (admin export, every page) and hashed row by row: the restore holds only when the count, the version and the * hash of every row are B0's. Also printed: whether the tombstones of A were on the pull a phone makes, whether one * file put in R2 before B0 survives C (PITR restores the object, never R2), and what sign-in answers after C. * *   pnpm -s exec tsx scripts/restore-proof-1.ts [--base <the dev Worker's address (config/dev-server.json)>] *       [--admin-token-file ~/.cotton-credentials/cloudflare/business-dev-admin-token] *       [--code-file ~/.cotton-credentials/cotton/dev-otp] [--rows 1500] [--skip c] * * Refuses any base but the dev Worker. Prints counts, versions, times and hashes; never a token, a credential, a code * or a bookmark (bookmarks are shown by their hash). Exit 0 when every check held, 1 when one did not, 2 when it could * not run. */import { createHash, randomBytes } from "node:crypto";import { readFileSync } from "node:fs";import { homedir } from "node:os";import { devBase } from "./dev-server";const DEV_BASE = devBase();const arg = (name: string, fallback?: string): string | undefined => {  const i = process.argv.indexOf(`--${name}`);  return i > 0 ? process.argv[i + 1] : fallback;};const home = (p: string) => p.replace(/^~(?=\/)/, homedir());const BASE = (arg("base", DEV_BASE) ?? "").replace(/\/$/, "");if (BASE !== DEV_BASE) {  console.error(`restore-proof-1: ${BASE} is not the dev Worker (${DEV_BASE}); nothing was asked`);  process.exit(2);}const ADMIN = readFileSync(home(arg("admin-token-file", "~/.cotton-credentials/cloudflare/business-dev-admin-token")!), "utf8").trim();const CODE = readFileSync(home(arg("code-file", "~/.cotton-credentials/cotton/dev-otp")!), "utf8").replace(/\D/g, "");const ROWS = Number(arg("rows", "1500"));const SKIP = new Set((arg("skip", "") ?? "").split(",").filter(Boolean));if (!Number.isInteger(ROWS) || ROWS < 1100 || ROWS > 20_000) throw new Error("--rows is 1100 to 20000 (A deletes 1,000)");const t0 = Date.now();const say = (line: string) => console.log(`[restore-proof-1 +${String(Math.round((Date.now() - t0) / 1000)).padStart(4)}s] ${line}`);const h16 = (s: string) => createHash("sha256").update(s).digest("hex").slice(0, 16);const wait = (ms: number) => new Promise((done) => setTimeout(done, ms));const fail = (what: string): never => {  throw new Error(what);};type Answer = { status: number; body: Record<string, unknown> };async function call(method: string, path: string, body?: unknown, bearer?: string, tries = 5): Promise<Answer> {  for (let attempt = 0; ; attempt++) {    try {      const res = await fetch(`${BASE}${path}`, { method, headers: { "content-type": "application/json", "user-agent": "cotton-restore-proof-1/1", ...(bearer ? { authorization: `Bearer ${bearer}` } : {}) }, body: body === undefined ? undefined : JSON.stringify(body) });      const text = await res.text();      if (res.status >= 500 && attempt < tries - 1) throw new Error(`${res.status} ${text.slice(0, 160)}`);      let parsed: Record<string, unknown> = {};      try {        parsed = text ? (JSON.parse(text) as Record<string, unknown>) : {};      } catch {        parsed = { text: text.slice(0, 160) };      }      return { status: res.status, body: parsed };    } catch (error) {      if (attempt >= tries - 1) throw error;      await wait(2_000 * (attempt + 1));    }  }}/** An answer shown without anything secret: its status and code, never its body. */const brief = (a: Answer) => `${a.status}${typeof a.body.code === "string" ? ` ${a.body.code}` : ""}`;// ---- The throwaway accountconst number = `+1555${String(Math.floor(1_000_000 + Math.random() * 8_999_999))}`;const deviceId = randomBytes(32).toString("base64url");async function signIn(): Promise<{ database: string; credential: string } | Answer> {  const asked = await call("POST", "/v1/code", { phone: number, device_id: deviceId });  if (asked.status !== 200) return asked;  const signed = await call("POST", "/v1/sign-in", { database_id: asked.body.database_id, challenge_id: asked.body.challenge_id, code: CODE, device_id: deviceId });  if (signed.status !== 200) return signed;  return { database: String(asked.body.database_id), credential: String(signed.body.credential) };}let database = "";let credential = "";const admin = (method: string, path: string, body?: unknown) => call(method, `/b/p-${database}/v1/admin${path}`, body, ADMIN);type Live = { table: string; id: string; version: number; data: Record<string, unknown>; created_at: string; updated_at: string; owner?: unknown };/** Every live row, by the admin export's pages. */async function exportAll(): Promise<{ version: number; rows: Live[] }> {  const rows: Live[] = [];  let after: string | null = null;  let version = -1;  for (let page = 0; page < 1_000; page++) {    const got = await admin("GET", `/export?limit=5000${after ? `&after=${encodeURIComponent(after)}` : ""}`);    if (got.status !== 200) fail(`export: ${brief(got)}`);    if (page === 0) version = Number(got.body.version);    rows.push(...((got.body.rows ?? []) as Live[]));    after = (got.body.next as string | null) ?? null;    if (!after) break;  }  return { version, rows };}/** Every live row, read whole by the admin export, hashed one by one and together; counted by table. */async function fingerprint(): Promise<{ rows: number; version: number; hash: string; tables: Record<string, number>; perRow: Map<string, string> }> {  const perRow = new Map<string, string>();  const tables: Record<string, number> = {};  const all = createHash("sha256");  const { version, rows } = await exportAll();  for (const r of rows) {    const line = JSON.stringify([r.table, r.id, r.version, r.data, r.created_at, r.updated_at, r.owner ?? null]);    const h = createHash("sha256").update(line).digest("hex");    perRow.set(`${r.table}/${r.id}`, h);    all.update(`${h}\n`);    tables[r.table] = (tables[r.table] ?? 0) + 1;  }  return { rows: perRow.size, version, hash: all.digest("hex").slice(0, 16), tables, perRow };}type Print = Awaited<ReturnType<typeof fingerprint>>;const shown = (p: Print) => `rows ${p.rows}, version ${p.version}, hash ${p.hash}, by table ${JSON.stringify(p.tables)}`;/** How two fingerprints differ, row by row. */function differ(a: Print, b: Print): { missing: number; extra: number; changed: number } {  let missing = 0;  let changed = 0;  for (const [k, h] of a.perRow) {    const other = b.perRow.get(k);    if (other === undefined) missing++;    else if (other !== h) changed++;  }  let extra = 0;  for (const k of b.perRow.keys()) if (!a.perRow.has(k)) extra++;  return { missing, extra, changed };}/** Restore to `bookmark`, then wait for the restarted object to answer at the version wanted. */async function restoreTo(bookmark: string, wantVersion: number): Promise<{ ok: boolean; status: string; undo: string | null; waitedMs: number }> {  const started = Date.now();  const r = await admin("POST", "/restore", { bookmark });  const undo = typeof r.body.undo === "string" ? r.body.undo : null;  if (r.status !== 200) return { ok: false, status: brief(r), undo, waitedMs: Date.now() - started };  while (Date.now() - started < 120_000) {    await wait(1_000);    const b = await admin("GET", "/restore/bookmark?table=note").catch(() => null);    if (b && b.status === 200 && Number(b.body.version) === wantVersion) return { ok: true, status: brief(r), undo, waitedMs: Date.now() - started };  }  return { ok: false, status: `${brief(r)}, never back at version ${wantVersion}`, undo, waitedMs: Date.now() - started };}const checks: { check: string; ok: boolean }[] = [];const check = (name: string, ok: boolean, detail: string) => {  checks.push({ check: name, ok });  say(`${ok ? "HELD  " : "FAILED"} ${name}: ${detail}`);};/** Run `work` over `items`, `width` at a time. */async function pooled<T>(items: T[], width: number, work: (item: T) => Promise<void>): Promise<void> {  let next = 0;  await Promise.all(Array.from({ length: width }, async () => {    while (next < items.length) await work(items[next++]!);  }));}async function main(): Promise<number> {  const s = await signIn();  if ("status" in s) {    say(`could not sign in an invented number: ${brief(s)}`);    return 2;  }  ({ database, credential } = s);  say(`throwaway account: an invented +1555 number, database ${database.slice(0, 8)}… (sha ${h16(database)})`);  // Seed: invented sealed-shaped rows (plant-rows, dev only) by a one-day owner token, revoked after.  const minted = await call("POST", "/v1/act", { act: "mint_token", args: { name: "restore proof", scopes: ["owner"], expires_in_days: 1 } }, credential);  const token = typeof minted.body.token === "string" ? minted.body.token : fail(`mint: ${brief(minted)}`);  for (const [table, count] of [["note", ROWS], ["memory", 100]] as const) {    const planted = await call("POST", "/v1/admin/dev/plant-rows", { table, from: 0, count, bytes: 400 }, token);    if (planted.status !== 200) fail(`plant ${table}: ${brief(planted)}`);  }  await call("POST", "/v1/act", { act: "revoke_token", args: { id: String((minted.body.made as { id?: string } | undefined)?.id ?? "") } }, credential);  const file = `${database}/proof/${randomBytes(6).toString("hex")}.bin`;  const put = await fetch(`${BASE}/v1/media/${file}`, { method: "PUT", headers: { authorization: `Bearer ${credential}`, "content-type": "application/vnd.cotton.f1" }, body: randomBytes(4096) });  say(`seeded: ${ROWS} note rows and 100 memory rows (invented, sealed-shaped), one 4 KB file in R2 (${put.status})`);  const f0 = await fingerprint();  const b0 = await admin("GET", "/restore/bookmark?table=note");  if (b0.status !== 200 || typeof b0.body.now !== "string") {    say(`no bookmark: ${brief(b0)}`);    return 2;  }  const bookmark = b0.body.now;  say(`B0 noted (bookmark sha ${h16(bookmark)}); F0 ${shown(f0)}`);  // A bookmark by time, inside the account's life (before it existed, PITR answers an error: seen in the first run).  const seededAt = new Date(t0 + 1_000).toISOString();  const byTime = await admin("GET", `/restore/bookmark?at=${encodeURIComponent(seededAt)}`);  say(`a bookmark for a time (the run's first second) answers ${brief(byTime)}${typeof byTime.body.bookmark === "string" ? ` (sha ${h16(byTime.body.bookmark)})` : ""}`);  const after = async (name: string) => {    const f = await fingerprint();    const d = differ(f0, f);    check(`${name}: back to B0 row for row`, f.rows === f0.rows && f.version === f0.version && f.hash === f0.hash && d.missing + d.extra + d.changed === 0, `${shown(f)}; against F0 missing ${d.missing}, extra ${d.extra}, changed ${d.changed}`);  };  // ---- A. 1,000 rows deleted through the normal door  {    const ids = [...f0.perRow.keys()].filter((k) => k.startsWith("note/")).slice(0, 1_000).map((k) => k.slice(5));    let refused = 0;    const started = Date.now();    await pooled(ids, 8, async (id) => {      const d = await call("POST", "/v1/act", { act: "delete", args: { table: "note", id } }, credential);      if (d.status !== 200) refused++;    });    const fa = await fingerprint();    say(`A. damage: 1,000 deletes through POST /v1/act in ${Math.round((Date.now() - started) / 1000)}s (${refused} refused); now ${shown(fa)}`);    // What a phone that last pulled at B0 is handed next: the tombstones.    // A pull is paged: its first page is short (FIRST_PAGE_ROWS), and each answer names the `next` page.    let tombstones = 0;    let pages = 0;    let path = `/v1/sync?since=${f0.version}&limit=1000`;    for (; pages < 100; pages++) {      const got = await call("GET", path, undefined, credential);      if (got.status !== 200) fail(`pull: ${brief(got)}`);      tombstones += ((got.body.rows ?? []) as { deleted?: boolean }[]).filter((r) => r.deleted).length;      if (typeof got.body.next !== "string") break;      path = `/v1/sync?cursor=${encodeURIComponent(got.body.next)}`;    }    check("A. the deletes are on the pull a phone makes (tombstones)", tombstones === 1_000 - refused, `${tombstones} tombstones on GET /v1/sync?since=${f0.version}, ${pages + 1} pages`);    const r = await restoreTo(bookmark, f0.version);    say(`A. restore to B0: ${r.status}, the object answering at version ${f0.version} after ${r.waitedMs} ms (undo bookmark sha ${r.undo ? h16(r.undo) : "none"})`);    await after("A");  }  // ---- B. a bad update over every row  {    const notes = (await exportAll()).rows.filter((r) => r.table === "note");    let written = 0;    let refused = 0;    const codes: Record<string, number> = {};    const started = Date.now();    // Garbage the seal check takes as well formed (apps/business/src/seal.ts checkSealFields): a body of at least    // 12 + 16 + 64 bytes and a wrapped key of exactly 12 + 32 + 16, base64url, at table key version 1.    for (let i = 0; i < notes.length; i += 200) {      const rows = notes.slice(i, i + 200).map((r) => ({ table: "note", id: r.id, expect_version: r.version, data: { ...r.data, sealed_enc: `s1:${randomBytes(200).toString("base64url")}`, dek_enc: `d1:${randomBytes(60).toString("base64url")}`, seal_v: 1 } }));      const got = await call("POST", "/v1/act", { act: "seal_many", args: { rows } }, credential);      const results = (got.body.results ?? []) as { ok: boolean; code?: string }[];      written += results.filter((x) => x.ok).length;      for (const x of results.filter((x) => !x.ok)) codes[x.code ?? "?"] = (codes[x.code ?? "?"] ?? 0) + 1;      if (got.status !== 200) codes[brief(got)] = (codes[brief(got)] ?? 0) + rows.length;      refused += got.status === 200 ? results.filter((x) => !x.ok).length : rows.length;    }    const fb = await fingerprint();    const d = differ(f0, fb);    say(`B. damage: every note's sealed block overwritten by seal_many in ${Math.round((Date.now() - started) / 1000)}s (${written} written, ${refused} refused${refused ? ` ${JSON.stringify(codes)}` : ""}); now ${shown(fb)}; against F0 changed ${d.changed}`);    check("B. the damage landed on every note", written === notes.length && d.changed >= notes.length, `${written} of ${notes.length}`);    const r = await restoreTo(bookmark, f0.version);    say(`B. restore to B0: ${r.status}, back after ${r.waitedMs} ms (undo bookmark sha ${r.undo ? h16(r.undo) : "none"})`);    await after("B");  }  // ---- C. deleteAll: the account deleted and erased to its end  if (!SKIP.has("c")) {    const asked = await call("POST", "/v1/account/delete/code", {}, credential);    const confirmed = asked.status === 200 ? await call("POST", "/v1/account/delete", { challenge_id: asked.body.challenge_id, code: CODE, confirm: "delete" }, credential) : asked;    const now = await admin("POST", "/account/erase-now");    say(`C. damage: deleted the app's way (${brief(confirmed)}), thirty days brought to now (${brief(now)})`);    // The erase runs on the object's alarm in steps. Past `pending` the object answers every request, admin ones too,    // 410 account_deleted with where the deletion stands (`deleting.phase`); `done` once storage.deleteAll ran and    // the directory was told (apps/business/src/account_delete.ts).    const started = Date.now();    let phase = "?";    let left: unknown = null;    while (Date.now() - started < 420_000) {      await wait(5_000);      const b = await admin("GET", "/restore/bookmark?table=note").catch(() => null);      const deleting = (b?.body.deleting ?? null) as { phase?: string; left?: unknown } | null;      if (b && b.status === 410 && deleting?.phase) {        phase = deleting.phase;        left = deleting.left ?? null;      } else if (b && b.status === 410 && phase === "?") phase = `410 without a phase: ${String(b.body.message ?? "").slice(0, 60)}`;      if (phase === "done") break;    }    const oldSignIn = await call("POST", "/v1/media/missing", { keys: [file] }, credential);    say(`C. after ${Math.round((Date.now() - started) / 1000)}s the deletion is at "${phase}" (left ${JSON.stringify(left)}); the old sign-in answers ${brief(oldSignIn)}`);    check("C. the erase ran to its end (storage.deleteAll, directory told)", phase === "done", `phase ${phase}`);    const r = await restoreTo(bookmark, f0.version);    say(`C. restore to B0: ${r.status}, back after ${r.waitedMs} ms (undo bookmark sha ${r.undo ? h16(r.undo) : "none"})`);    if (r.status.startsWith("410")) {      // Not a failure of PITR: the restore route sits behind the deletion's door. Said, not counted (RESTORE 2).      say("C. KNOWN GAP: an erased account answers 410 before the restore route is reached; restoring it needs an admin route ahead of the deletion's door (see RESTORE.md). Nothing more of C can be proven on this Worker.");      for (const c of checks) console.log(JSON.stringify(c));      say(`done in ${Math.round((Date.now() - t0) / 1000)}s: ${checks.filter((c) => c.ok).length} of ${checks.length} checks held, C's restore a known gap`);      return checks.every((c) => c.ok) ? 0 : 1;    }    await after("C");    // What PITR does not bring back: R2, and the directory outside the object.    const missing = await call("POST", "/v1/media/missing", { keys: [file] }, credential);    const stillMissing = missing.status === 200 ? ((missing.body.missing as string[]) ?? []).includes(file) : null;    say(`C. after the restore: the old device credential answers ${brief(missing)}; the file put in R2 before B0 is ${stillMissing === null ? "not answerable" : stillMissing ? "GONE (PITR restores the object, not R2)" : "there"}`);    const again = await signIn();    say(`C. after the restore: signing in the same number answers ${"status" in again ? brief(again) : `200 (database ${again.database.slice(0, 8)}…, ${again.database === database ? "the same database" : "A NEW DATABASE"})`}`);  }  say(`done in ${Math.round((Date.now() - t0) / 1000)}s: ${checks.filter((c) => c.ok).length} of ${checks.length} checks held`);  for (const c of checks) console.log(JSON.stringify(c));  return checks.every((c) => c.ok) ? 0 : 1;}main().then(  (code) => process.exit(code),  (error: unknown) => {    console.error(`restore-proof-1: ${error instanceof Error ? error.message : String(error)}`);    process.exit(2);  },);