Cotton code
295 lines · 18.1 KB · TypeScriptRaw
/** * RESTORE 2 RUNBOOK on DEV (coordinator for the owner, 27 Nov 2026; assets/design/shared/RESTORE-2.md and * RESTORE-2-CONTRACT.md). The whole safe-restore procedure, run against a throwaway invented account on the dev Worker * and proven with the three damages of RESTORE PROOF 1: * *   A. 1,000 rows deleted through the normal door        B. garbage sealed over every note *   C. the account deleted and erased to its end (storage.deleteAll, directory told) * * Each damage is undone by the procedure, step by step, each step checked: *   1. freeze        a phone's pull and write answer 503 account_frozen (Retry-After 30); the admin's 200 *   2. export        today's rows to R2, every page, the manifest's count *   3. restore       to bookmark B0 (taken before any damage) with the moment it stands for *   4. finish        on the restarted object: version past everything held before, a new generation, restored_to *   5. unfreeze      the phone's next pull answers the new generation and restored_to; a write from the old *                    generation is 409 generation_moved and lands nothing; every live row equals B0's, hashed one by one * and for C: the number's sign-in finds the same database again (the directory put back; dev only). * * DRY RUN FIRST (the default): it checks the Worker answers, the admin token is taken and the restore routes are * there, prints the plan, and changes nothing. `--go` runs it. * *   pnpm -s exec tsx scripts/restore-runbook.ts [--go] [--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, generations' hashes and row hashes; never a token, a * credential, a code or a bookmark. 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-runbook: ${BASE} is not the dev Worker (${DEV_BASE}); nothing was asked`);  process.exit(2);}const GO = process.argv.includes("--go");const ADMIN = readFileSync(home(arg("admin-token-file", "~/.cotton-credentials/cloudflare/business-dev-admin-token")!), "utf8").trim();const CODE = GO ? 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-runbook +${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>; headers: Headers };async function call(method: string, path: string, body?: unknown, bearer?: string, extra: Record<string, 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-runbook/1", ...(bearer ? { authorization: `Bearer ${bearer}` } : {}), ...extra }, body: body === undefined ? undefined : JSON.stringify(body) });      const text = await res.text();      // A frozen account answers 503 on purpose: that one is never retried.      if (res.status >= 500 && !text.includes("account_frozen") && 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, headers: res.headers };    } catch (error) {      if (attempt >= tries - 1) throw error;      await wait(2_000 * (attempt + 1));    }  }}const brief = (a: Answer) => `${a.status}${typeof a.body.code === "string" ? ` ${a.body.code}` : ""}`;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}`);};// ---- 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);/** The phone's own call, carrying the generation its copy holds. */const asPhone = (method: string, path: string, body: unknown, generation: string | null) => call(method, path, body, credential, generation ? { "x-cotton-generation": generation } : {});type Live = { table: string; id: string; version: number; data: Record<string, unknown>; created_at: string; updated_at: string; owner?: unknown };async function exportAll(): Promise<Live[]> {  const rows: Live[] = [];  let after: string | null = null;  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)}`);    rows.push(...((got.body.rows ?? []) as Live[]));    after = (got.body.next as string | null) ?? null;    if (!after) break;  }  return rows;}/** Every live row hashed (table, id, its version, data, times, owner): the rows alone, not the object's version. */async function fingerprint(): Promise<{ rows: number; hash: string; perRow: Map<string, string> }> {  const perRow = new Map<string, string>();  const all = createHash("sha256");  for (const r of await exportAll()) {    const h = createHash("sha256").update(JSON.stringify([r.table, r.id, r.version, r.data, r.created_at, r.updated_at, r.owner ?? null])).digest("hex");    perRow.set(`${r.table}/${r.id}`, h);    all.update(`${h}\n`);  }  return { rows: perRow.size, hash: all.digest("hex").slice(0, 16), perRow };}function differ(a: Map<string, string>, b: Map<string, string>): { missing: number; extra: number; changed: number } {  let missing = 0;  let changed = 0;  for (const [k, h] of a) {    const o = b.get(k);    if (o === undefined) missing++;    else if (o !== h) changed++;  }  let extra = 0;  for (const k of b.keys()) if (!a.has(k)) extra++;  return { missing, extra, changed };}async function state(): Promise<Record<string, unknown>> {  const s = await admin("GET", "/restore/state");  return s.status === 200 ? s.body : { status: s.status };}/** The whole procedure, from a damaged account back to B0. */async function procedure(name: string, b0: { bookmark: string; at: string; version: number }, f0: Awaited<ReturnType<typeof fingerprint>>, oldGeneration: string): Promise<string> {  // 1. Freeze.  const frozen = await admin("POST", "/restore/freeze", { reason: `runbook ${name}` });  const pull = await asPhone("GET", "/v1/sync?since=0&limit=1", undefined, oldGeneration);  const write = await asPhone("POST", "/v1/act", { act: "create", args: { table: "todo", data: { title: "written while frozen" } } }, oldGeneration);  const adminRead = await admin("GET", "/restore/state");  check(`${name} 1. freeze`, frozen.status === 200 && pull.status === 503 && pull.body.code === "account_frozen" && pull.headers.get("retry-after") === "30" && write.body.code === "account_frozen" && adminRead.status === 200, `freeze ${brief(frozen)}; a phone's pull ${brief(pull)} (Retry-After ${pull.headers.get("retry-after")}), its write ${brief(write)}; the admin ${brief(adminRead)}`);  // 2. Export today's rows.  let part = 1;  let after: string | null = null;  let stamp: string | null = null;  let manifestRows = -1;  for (; part < 500; part++) {    const got = await admin("POST", "/restore/export", { part, ...(after ? { after } : {}), ...(stamp ? { stamp } : {}) });    if (got.status !== 200) fail(`export: ${brief(got)}`);    stamp = String(got.body.stamp);    if (got.body.done === true) {      manifestRows = Number((got.body.manifest as { rows: number }).rows);      break;    }    after = String(got.body.after);  }  check(`${name} 2. export`, manifestRows >= 0, `${manifestRows} rows in ${part} part(s), manifest written${manifestRows === 0 ? " (an erased object holds none)" : ""}`);  // 3. Restore to B0.  const asked = await admin("POST", "/restore", { bookmark: b0.bookmark, restored_to: b0.at });  const versionBefore = Number(asked.body.version_before);  const started = Date.now();  let landed: Record<string, unknown> = {};  while (Date.now() - started < 120_000) {    await wait(1_000);    landed = await state();    if (landed.erased === false && Number(landed.version) === b0.version) break;  }  check(`${name} 3. restore`, asked.status === 200 && landed.erased === false && Number(landed.version) === b0.version, `asked ${brief(asked)} (version before ${versionBefore}); the object back at version ${String(landed.version)} after ${Date.now() - started} ms, still frozen: ${String(landed.frozen)}`);  // 4. Finish.  const finished = await admin("POST", "/restore/finish");  const generation = String(finished.body.generation ?? "");  check(`${name} 4. finish`, finished.status === 200 && Number(finished.body.version) > versionBefore && generation !== "" && generation !== oldGeneration && finished.body.restored_to === new Date(b0.at).toISOString(), `version ${String(finished.body.version)} (> ${versionBefore}), generation ${h16(generation)} (was ${h16(oldGeneration)}), restored_to ${String(finished.body.restored_to)}${finished.body.erased_before ? `, directory put back: ${String(finished.body.relinked)}` : ""}`);  // 5. Unfreeze, and what a phone then sees.  const unfrozen = await admin("POST", "/restore/unfreeze");  const next = await asPhone("GET", "/v1/sync?since=0&limit=1", undefined, oldGeneration);  const versionNow = Number((await state()).version);  const old = await asPhone("POST", "/v1/act", { act: "create", args: { table: "todo", data: { title: "from the old copy" } } }, oldGeneration);  const versionAfterOld = Number((await state()).version);  check(`${name} 5. unfreeze: the phone sees the new generation`, unfrozen.status === 200 && next.status === 200 && next.body.generation === generation && next.body.restored_to === new Date(b0.at).toISOString(), `unfreeze ${brief(unfrozen)}; the pull answers ${brief(next)}, generation ${h16(String(next.body.generation))}, restored_to ${String(next.body.restored_to)}`);  check(`${name} 5. a write from the old generation lands nothing`, old.status === 409 && old.body.code === "generation_moved" && old.body.generation === generation && versionAfterOld === versionNow, `${brief(old)}; version ${versionNow} → ${versionAfterOld}`);  const f = await fingerprint();  const d = differ(f0.perRow, f.perRow);  check(`${name} 5. every live row is B0's`, f.rows === f0.rows && f.hash === f0.hash && d.missing + d.extra + d.changed === 0, `rows ${f.rows}, hash ${f.hash} (B0 ${f0.hash}); missing ${d.missing}, extra ${d.extra}, changed ${d.changed}`);  return generation;}async function dryRun(): Promise<number> {  const health = await call("GET", "/health");  say(`DRY RUN: the dev Worker answers ${brief(health)} (build ${String(health.body.build ?? "?").slice(0, 10)})`);  const deletions = await call("GET", "/v1/admin/deletions", undefined, ADMIN);  say(`DRY RUN: the admin token is ${deletions.status === 200 ? "taken" : `refused (${brief(deletions)})`}`);  const routes = await call("GET", "/b/p-00000000-0000-4000-8000-000000000000/v1/admin/restore/state", undefined, ADMIN);  say(`DRY RUN: the restore routes answer ${brief(routes)} on an object nobody uses (200 means they are deployed)`);  say("DRY RUN: the plan, with --go: sign in an invented +1555 number; plant invented rows; bookmark B0; then for each of A (1,000 deletes), B (garbage sealed over every note), C (delete and erase): the damage, then freeze, export, restore to B0, finish, unfreeze, each step checked; nothing else is touched.");  return health.status === 200 && deletions.status === 200 && routes.status === 200 ? 0 : 2;}async function main(): Promise<number> {  if (!GO) return dryRun();  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)})`);  const minted = await call("POST", "/v1/act", { act: "mint_token", args: { name: "restore runbook", 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);  // The generation as the phone first holds it.  let generation = String((await asPhone("GET", "/v1/sync?since=0&limit=1", undefined, null)).body.generation ?? "");  const f0 = await fingerprint();  const b = await admin("GET", "/restore/bookmark");  if (b.status !== 200 || typeof b.body.now !== "string") {    say(`no bookmark: ${brief(b)}`);    return 2;  }  const b0 = { bookmark: b.body.now, at: String(b.body.at_now), version: Number(b.body.version) };  say(`seeded ${ROWS} note and 100 memory rows; B0 at version ${b0.version} (bookmark sha ${h16(b0.bookmark)}), F0 ${f0.rows} rows, hash ${f0.hash}, generation ${h16(generation)}`);  // ---- A  {    const ids = [...f0.perRow.keys()].filter((k) => k.startsWith("note/")).slice(0, 1_000).map((k) => k.slice(5));    let next = 0;    let refused = 0;    await Promise.all(Array.from({ length: 8 }, async () => {      while (next < ids.length) {        const d = await asPhone("POST", "/v1/act", { act: "delete", args: { table: "note", id: ids[next++]! } }, generation);        if (d.status !== 200) refused++;      }    }));    const fa = await fingerprint();    check("A. damage landed", fa.rows === f0.rows - 1_000 + refused && refused === 0, `1,000 deletes (${refused} refused); ${fa.rows} rows`);    generation = await procedure("A", b0, f0, generation);  }  // ---- B  {    const notes = (await exportAll()).filter((r) => r.table === "note");    let written = 0;    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 asPhone("POST", "/v1/act", { act: "seal_many", args: { rows } }, generation);      written += ((got.body.results ?? []) as { ok: boolean }[]).filter((x) => x.ok).length;    }    check("B. damage landed", written === notes.length, `${written} of ${notes.length} notes overwritten`);    generation = await procedure("B", b0, f0, generation);  }  // ---- C  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;    await admin("POST", "/account/erase-now");    const started = Date.now();    let phase = "?";    while (Date.now() - started < 420_000) {      await wait(5_000);      const probe = await call("GET", `/b/p-${database}/v1/admin/row-counts`, undefined, ADMIN);      const deleting = (probe.body.deleting ?? null) as { phase?: string } | null;      if (probe.status === 410 && deleting?.phase) phase = deleting.phase;      if (phase === "done") break;    }    check("C. damage landed (erased to the end)", phase === "done", `deleted (${brief(confirmed)}), erase at "${phase}" after ${Math.round((Date.now() - started) / 1000)}s`);    generation = await procedure("C", b0, f0, generation);    const again = await signIn();    check("C. the number signs in to the same database", !("status" in again) && again.database === database, "status" in again ? brief(again) : `database ${again.database === database ? "the same" : "A NEW ONE"}`);  }  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-runbook: ${error instanceof Error ? error.message : String(error)}`);    process.exit(2);  },);