427 lines · 29.9 KB · TypeScriptRaw
/** * RESTORE 2 SERVER 2 (coordinator's review of adc3333e5c, 27 Nov 2026): the cases the review found untested. The * marker never read where the restore routes are off (live) and never latched on an R2 error (H1); one gate for every * way into the object (M1), with a test that fails when a new entry point skips it; the sentinel (M2); a pending * deletion restored as it was (M3); snapshots driven by the alarm alone (M4); the never-again ledger replayed over a * restore (M5); the chain restarted after one (M6); every part checked before a row goes (M7); the generation held on * every write route (L4). All accounts invented. */import { env, runDurableObjectAlarm, runInDurableObject } from "cloudflare:test";import { describe, expect, it } from "vitest";import SOURCE from "../src/business.ts?raw";import { markerKey } from "../src/restore.ts";import { ADMIN, http, mint, personalObject, TODOS_OPEN } from "./personal.ts";const object = (slug: string) => env.BUSINESS.get(env.BUSINESS.idFromName(slug));const phone = (credential: string, generation?: string) => ({ authorization: `Bearer ${credential}`, ...(generation ? { "x-cotton-generation": generation } : {}) });const todo = (title: string) => ({ act: "create", args: { table: "todo", data: { title } } });type Inside = { env: Record<string, unknown>; restoreMarker: unknown; slug: string; store: { frozen: boolean; bump(): number } };const inside = (i: unknown) => i as Inside;async function runUntilDone(slug: string, kind?: "full" | "daily"): Promise<{ kind: string; stamp: string; parts: { key: string }[] }> { for (let n = 0; n < 20; n++) { const got = await http<{ done?: boolean; manifest?: { kind: string; stamp: string; parts: { key: string }[] } }>(slug, "POST", "/v1/admin/snapshots/run", { ...(n === 0 && kind ? { kind } : {}) }, ADMIN); expect(got.status, JSON.stringify(got.body)).toBe(200); if (got.body.done && got.body.manifest) return got.body.manifest; } throw new Error("the copy never finished");}async function restoreSteps(slug: string): Promise<{ status: number; body: Record<string, unknown> }> { let step = { status: 0, body: {} as Record<string, unknown> }; for (let n = 0; n < 40; n++) { step = await http<Record<string, unknown>>(slug, "POST", "/v1/admin/snapshots/restore/step", {}, ADMIN); if (step.status !== 200 || step.body.done === true) return step; } return step;}async function count(slug: string, table: string): Promise<number> { return runInDurableObject(object(slug), (_i, state) => state.storage.sql.exec<{ n: number }>("SELECT count(*) AS n FROM rows WHERE table_id = ?", table).one().n);}describe("RESTORE 2 SERVER 2: the marker (H1)", () => { it("on live rules the restore routes are not there and the marker is never read: a frozen marker changes nothing", async () => { const slug = "r2s2-live"; const { credential } = await personalObject(slug, { open: TODOS_OPEN }); await env.PHOTOS.put(markerKey(slug), JSON.stringify({ frozen: true, frozen_at: null, reason: "left over", pending: null })); const answers = await runInDurableObject(object(slug), async (instance) => { const me = inside(instance); const was = me.env; let reads = 0; const photos = was.PHOTOS as R2Bucket; me.env = { ...was, ENV_LABEL: "live", PHOTOS: new Proxy(photos, { get: (t, k) => (k === "get" ? (key: string) => (key.endsWith("/marker.json") && reads++, t.get(key)) : Reflect.get(t, k)) }) }; me.restoreMarker = null; try { const ask = (path: string, method = "GET", auth = `Bearer ${credential}`) => instance.fetch(new Request(`https://x${path}`, { method, headers: { authorization: auth, "x-cotton-business": slug } })); const freeze = await ask("/v1/admin/restore/freeze", "POST", ADMIN.authorization); const state = await ask("/v1/admin/restore/state", "GET", ADMIN.authorization); const restoreFromSnapshots = await ask("/v1/admin/snapshots/restore/begin", "POST", ADMIN.authorization); const sync = await ask("/v1/sync?since=0&limit=1"); await (instance as unknown as { chatAccepts(n: string): Promise<boolean> }).chatAccepts("+15550000000").catch(() => false); return { freeze: freeze.status, state: state.status, snapshots: restoreFromSnapshots.status, sync: sync.status, reads }; } finally { me.env = was; me.restoreMarker = null; } }); expect(answers.freeze).toBe(404); expect(answers.state).toBe(404); expect(answers.snapshots).toBe(404); expect(answers.sync, "a marker on live is never read: the account answers").toBe(200); expect(answers.reads, "no R2 read of the marker on live").toBe(0); await env.PHOTOS.delete(markerKey(slug)); }); it("an R2 error reading the marker answers 503 retryable, is never kept, and never freezes", async () => { const slug = "r2s2-r2-error"; const { credential } = await personalObject(slug, { open: TODOS_OPEN }); const got = await runInDurableObject(object(slug), async (instance) => { const me = inside(instance); const was = me.env; const photos = was.PHOTOS as R2Bucket; let fail = 1; me.env = { ...was, PHOTOS: new Proxy(photos, { get: (t, k) => (k === "get" ? (key: string) => (key.endsWith("/marker.json") && fail-- > 0 ? Promise.reject(new Error("an invented R2 error")) : t.get(key)) : Reflect.get(t, k)) }) }; me.restoreMarker = null; try { const ask = async () => { const res = await instance.fetch(new Request("https://x/v1/sync?since=0&limit=1", { headers: { authorization: `Bearer ${credential}`, "x-cotton-business": slug } })); return { status: res.status, retry: res.headers.get("retry-after"), body: (await res.json()) as { code?: string } }; }; const first = await ask(); const second = await ask(); return { first, second, frozen: me.store.frozen }; } finally { me.env = was; me.restoreMarker = null; } }); expect(got.first).toMatchObject({ status: 503, retry: "5", body: { code: "try_again" } }); expect(got.second.status, "read again, not latched").toBe(200); expect(got.frozen).toBe(false); });});describe("RESTORE 2 SERVER 2: one gate (M1)", () => { it("every way into the object begins at the gate (this test fails when a new entry point does not)", () => { const body = SOURCE.slice(SOURCE.indexOf("export class Business")); const end = body.search(/\n}\n/); const lines = body.slice(0, end).split("\n"); // Not gated, each for its reason: the request door (restoreDoor gates it), the alarm (gated in its first lines), // a socket closing (writes nothing), the constructor, identity (a read of three meta values, sync), and alarmWatch // (JOBS OUT 4: the cron's dead-man check reads the freeze itself and leaves a frozen or restoring account alone; it // writes no row, only an alarm). const exempt = new Set(["constructor", "fetch", "alarm", "webSocketClose", "identity", "alarmWatch"]); const entries: string[] = []; const ungated: string[] = []; lines.forEach((line, i) => { const m = /^ {2}(?:override )?(?:async )?([a-zA-Z]\w*)\s*[<(]/.exec(line); if (!m || /^ {2}(private|protected|static|readonly|get |set )/.test(line)) return; const name = m[1]!; if (exempt.has(name)) return; entries.push(name); const next = lines.slice(i + 1, i + 3).join("\n"); if (!next.includes("await this.frozenGate();")) ungated.push(name); }); expect(entries.length, "the entry points found").toBeGreaterThan(50); expect(ungated, "public methods that do not begin with `await this.frozenGate();`").toEqual([]); // The alarm's first lines are the gate too. expect(SOURCE.slice(SOURCE.indexOf("override async alarm()"), SOURCE.indexOf("override async alarm()") + 400)).toContain("await this.frozenGate();"); }); it("while frozen: calls from other objects are told not delivered, the alarm is held, a socket's frame closes it, and no row write lands", async () => { const slug = "r2s2-gate"; await personalObject(slug, { open: TODOS_OPEN }); expect((await http(slug, "POST", "/v1/admin/restore/freeze", { reason: "invented" }, ADMIN)).status).toBe(200); const got = await runInDurableObject(object(slug), async (instance, state) => { const rpc = instance as unknown as Record<string, (...a: unknown[]) => Promise<unknown>>; const said = async (run: () => Promise<unknown>) => { try { await run(); return "delivered"; } catch (error) { return error instanceof Error ? error.message : String(error); } }; const calls = { chatDeliver: await said(() => rpc.chatDeliver!({ from: "+15550000001", id: "x" })), sendDeliver: await said(() => rpc.sendDeliver!({ from: "+15550000001" })), sharedPut: await said(() => rpc.sharedPut!("+15550000001", "list", "item", null)), mailArrive: await said(() => rpc.mailArrive!({})), secretDeliver: await said(() => rpc.secretDeliver!({})), inviteDeliver: await said(() => rpc.inviteDeliver!({})), spaceJoin: await said(() => rpc.spaceJoin!("s", "+15550000001", false, 1)), helpAsked: await said(() => rpc.helpAsked!("+15550000001", { id: "a", device_key: "k", code: "c" })), }; const closed: number[] = []; await instance.webSocketMessage({ close: (code: number) => closed.push(code) } as unknown as WebSocket, "{}"); let bump = "written"; try { inside(instance).store.bump(); } catch (error) { bump = error instanceof Error ? error.message : String(error); } const before = Date.now(); await state.storage.deleteAlarm(); await instance.alarm(); const alarm = await state.storage.getAlarm(); return { calls, closed, bump, alarmIn: (alarm ?? 0) - before }; }); for (const [name, answer] of Object.entries(got.calls)) expect(answer, name).toMatch(/^account_frozen: .*not delivered, try again/); expect(got.closed).toEqual([4503]); expect(got.bump).toMatch(/frozen/); expect(got.alarmIn, "the alarm held, asked again in a minute").toBeGreaterThan(50_000); expect((await http(slug, "POST", "/v1/admin/restore/unfreeze", {}, ADMIN)).status).toBe(200); // Unfrozen, the same call is delivered (or refused for its own reasons, never as frozen). const after = await runInDurableObject(object(slug), async (instance) => { try { await (instance as unknown as { sharedPut(a: string, b: string, c: string, d: null): Promise<boolean> }).sharedPut("+15550000001", "list", "item", null); return "delivered"; } catch (error) { return error instanceof Error ? error.message : String(error); } }); expect(after).not.toMatch(/account_frozen/); }); it("holds every write route to the generation it names (L4), and lets one that names none through", async () => { const slug = "r2s2-routes"; const { credential } = await personalObject(slug, { open: TODOS_OPEN }); const generation = (await http<{ generation: string }>(slug, "GET", "/v1/me", undefined, phone(credential))).body.generation; for (const [method, path] of [["POST", "/v1/photos"], ["POST", "/v1/import/contacts"], ["PUT", "/v1/media/x/y.jpg"], ["POST", "/v1/account/keep"], ["DELETE", "/v1/devices/x"]] as const) { const moved = await http<{ code: string }>(slug, method, path, {}, phone(credential, "AAAAAAAAAAAAAAAAAAAAAA")); expect(moved, `${method} ${path}`).toMatchObject({ status: 409, body: { code: "generation_moved" } }); } expect((await http(slug, "POST", "/v1/act", todo("same"), phone(credential, generation))).status).toBe(200); expect((await http(slug, "GET", "/v1/sync?since=0&limit=1", undefined, phone(credential, "AAAAAAAAAAAAAAAAAAAAAA"))).status, "a read is never held").toBe(200); });});describe("RESTORE 2 SERVER 2: finishing a point-in-time restore (M2, M3, M6)", () => { const pending = (version: number, sentinel: string) => ({ frozen: true, frozen_at: new Date().toISOString(), reason: null, pending: { version_before: version, generation: "CCCCCCCCCCCCCCCCCCCCCC", restored_to: "2026-11-27T09:00:00.000Z", bookmark_hash: "0", erased_before: false, asked_at: new Date().toISOString(), sentinel } }); it("finish refuses while the sentinel written before the restore is still there; cancel takes the ask back", async () => { const slug = "r2s2-sentinel"; const { credential } = await personalObject(slug, { open: TODOS_OPEN }); const version = (await http<{ version: number }>(slug, "GET", "/v1/me", undefined, phone(credential))).body.version; await http(slug, "POST", "/v1/admin/restore/freeze", {}, ADMIN); // As the restore route leaves it, before point-in-time recovery restarts the object (not available locally). await runInDurableObject(object(slug), (_i, state) => { state.storage.sql.exec("CREATE TABLE IF NOT EXISTS restore_sentinel (id INTEGER PRIMARY KEY CHECK (id = 1), token TEXT NOT NULL)"); state.storage.sql.exec("INSERT OR REPLACE INTO restore_sentinel (id, token) VALUES (1, 'invented-sentinel')"); }); await env.PHOTOS.put(markerKey(slug), JSON.stringify(pending(version, "invented-sentinel"))); expect((await http<{ code: string }>(slug, "POST", "/v1/admin/restore/finish", {}, ADMIN)).body.code).toBe("not_restored_yet"); expect((await http<{ code: string }>(slug, "POST", "/v1/admin/restore/unfreeze", {}, ADMIN)).body.code).toBe("restore_unfinished"); expect((await http<{ cancelled: boolean }>(slug, "POST", "/v1/admin/restore/cancel", {}, ADMIN)).body.cancelled).toBe(true); expect((await http<{ pending: unknown }>(slug, "GET", "/v1/admin/restore/state", undefined, ADMIN)).body.pending).toBeNull(); expect((await http(slug, "POST", "/v1/admin/restore/unfreeze", {}, ADMIN)).status).toBe(200); expect((await http<{ version: number }>(slug, "GET", "/v1/me", undefined, phone(credential))).body.version, "nothing moved").toBe(version); }); it("a restored moment with a deletion pending finishes with the deletion as it was, dates included, and the admin told", async () => { const slug = "r2s2-deletion"; const { credential } = await personalObject(slug, { open: TODOS_OPEN }); const version = (await http<{ version: number }>(slug, "GET", "/v1/me", undefined, phone(credential))).body.version; await http(slug, "POST", "/v1/admin/restore/freeze", {}, ADMIN); const startedAt = "2026-11-20T08:00:00.000Z"; const eraseAt = "2026-12-20T08:00:00.000Z"; // The restored moment: a deletion set on the 20th (the sentinel gone with the restore). await runInDurableObject(object(slug), (_i, state) => { const sql = state.storage.sql; sql.exec("CREATE TABLE IF NOT EXISTS account_delete (id INTEGER PRIMARY KEY CHECK (id = 1), phase TEXT NOT NULL, started_at TEXT NOT NULL, by TEXT NOT NULL, database_id TEXT, slug TEXT NOT NULL, owner_phone TEXT, tries INTEGER NOT NULL DEFAULT 0, receipt TEXT NOT NULL, finished_at TEXT, erase_at TEXT)"); sql.exec("INSERT INTO account_delete (id, phase, started_at, by, database_id, slug, owner_phone, receipt, erase_at) VALUES (1, 'pending', ?, 'app', NULL, ?, NULL, ?, ?)", startedAt, slug, JSON.stringify({ started_at: startedAt, finished_at: null, by: "app", records: 0, files: 0, bytes: 0, google: { held: 0, revoked: 0 }, reports: 0 }), eraseAt); }); await env.PHOTOS.put(markerKey(slug), JSON.stringify(pending(version, "gone-with-the-restore"))); const finished = await http<{ version: number; deletion: { phase: string; started_at: string; erase_at: string } | null }>(slug, "POST", "/v1/admin/restore/finish", {}, ADMIN); expect(finished.status, JSON.stringify(finished.body)).toBe(200); expect(finished.body.deletion).toEqual({ phase: "pending", started_at: startedAt, erase_at: eraseAt }); expect((await http(slug, "POST", "/v1/admin/restore/unfreeze", {}, ADMIN)).status, "a way forward: unfrozen").toBe(200); const told = await http<{ code: string; message: string }>(slug, "GET", "/v1/sync?since=0", undefined, phone(credential)); expect(told.status).toBe(410); expect(told.body.message).toContain("2026-12-20"); expect(await env.PHOTOS.head(`${slug}/.deleting`)).not.toBeNull(); const alarm = await runInDurableObject(object(slug), (_i, state) => state.storage.getAlarm()); expect(alarm).toBe(Date.parse(eraseAt)); }); it("restarts the snapshot chain after a restore: the copy half written is dropped and the next one is a full", async () => { const slug = "r2s2-chain"; const { credential } = await personalObject(slug, { open: TODOS_OPEN }); await http(slug, "POST", "/v1/act", todo("invented"), phone(credential)); await http(slug, "POST", "/v1/admin/snapshots", { on: true }, ADMIN); await runUntilDone(slug, "full"); await runUntilDone(slug, "daily"); // A copy half written when the restore comes. await runInDurableObject(object(slug), (_i, state) => { state.storage.sql.exec("INSERT OR REPLACE INTO meta (key, value) VALUES ('snapshot_job', ?)", JSON.stringify({ kind: "daily", stamp: "2026-11-27T00-00-00-000Z", base: 1, upto: 2, cursor: "[1,\"todo\",\"x\"]", part: 1, rows: 1, bytes: 1, started_at: new Date().toISOString() })); }); const version = (await http<{ version: number }>(slug, "GET", "/v1/me", undefined, phone(credential))).body.version; await http(slug, "POST", "/v1/admin/restore/freeze", {}, ADMIN); await env.PHOTOS.put(markerKey(slug), JSON.stringify(pending(version, "gone"))); expect((await http(slug, "POST", "/v1/admin/restore/finish", {}, ADMIN)).status).toBe(200); const listed = await http<{ job: unknown; last: unknown }>(slug, "GET", "/v1/admin/snapshots", undefined, ADMIN); expect(listed.status, JSON.stringify(listed.body)).toBe(200); expect(listed.body.job).toBeNull(); expect(listed.body.last).toBeNull(); await http(slug, "POST", "/v1/admin/restore/unfreeze", {}, ADMIN); const next = await runUntilDone(slug); expect(next.kind, "a new full, never a daily on the old chain").toBe("full"); });});describe("RESTORE 2 SERVER 2: snapshots (M4, M5, M7, L1, L2)", () => { it("run on an object woken only by its alarm", async () => { const slug = "r2s2-alarm-snapshot"; const { credential } = await personalObject(slug, { open: TODOS_OPEN }); await http(slug, "POST", "/v1/act", todo("invented"), phone(credential)); await http(slug, "POST", "/v1/admin/snapshots", { on: true }, ADMIN); for (let n = 0; n < 6; n++) { // As after a restart: the object knows no slug of a request. await runInDurableObject(object(slug), async (instance, state) => { inside(instance).slug = ""; if ((await state.storage.getAlarm()) === null) await state.storage.setAlarm(Date.now()); }); await runDurableObjectAlarm(object(slug)); } const listed = await http<{ weekly: string[]; daily: string[] }>(slug, "GET", "/v1/admin/snapshots", undefined, ADMIN); expect(listed.body.weekly.length, "a full written by the alarm alone").toBe(1); expect(listed.body.daily.length, "and the daily after it, at once").toBe(1); }); it("refuse a full alone, a missing key, a changed or moved part, all before any row goes; unfreeze waits for the restore", async () => { const slug = "r2s2-verify"; const { credential } = await personalObject(slug, { open: TODOS_OPEN }); for (let i = 0; i < 3; i++) await http(slug, "POST", "/v1/act", todo(`invented ${i}`), phone(credential)); await http(slug, "POST", "/v1/admin/snapshots", { on: true }, ADMIN); const full = await runUntilDone(slug, "full"); await http(slug, "POST", "/v1/admin/restore/freeze", {}, ADMIN); expect((await http<{ code: string }>(slug, "POST", "/v1/admin/snapshots/restore/begin", { full: full.stamp, override_devices: true }, ADMIN)).body.code).toBe("full_alone"); await http(slug, "POST", "/v1/admin/restore/unfreeze", {}, ADMIN); const daily = await runUntilDone(slug, "daily"); const before = await count(slug, "todo"); await http(slug, "POST", "/v1/admin/restore/freeze", {}, ADMIN); // A part changed by one byte. const key = `_snapshots/weekly/${slug}/${full.stamp}/${full.parts[0]!.key}`; const good = new Uint8Array(await (await env.MEDIA.get(key))!.arrayBuffer()); const bad = good.slice(); bad[bad.length - 1] = bad[bad.length - 1]! ^ 1; await env.MEDIA.put(key, bad); expect((await http(slug, "POST", "/v1/admin/snapshots/restore/begin", { full: full.stamp, override_devices: true }, ADMIN)).status).toBe(200); expect((await http<{ code: string }>(slug, "POST", "/v1/admin/restore/unfreeze", {}, ADMIN)).body.code, "unfreeze waits").toBe("restore_unfinished"); expect((await restoreSteps(slug)).body.code).toBe("part_refused"); expect(await count(slug, "todo"), "nothing emptied").toBe(before); expect((await http<{ cancelled: boolean }>(slug, "POST", "/v1/admin/snapshots/restore/cancel", {}, ADMIN)).body.cancelled).toBe(true); // The daily's part laid in the full's place (its SHA-256 written into the manifest would not help: the seal names its place). const dailyPart = new Uint8Array(await (await env.MEDIA.get(`_snapshots/daily/${slug}/${daily.stamp}/${daily.parts[0]!.key}`))!.arrayBuffer()); await env.MEDIA.put(key, dailyPart); expect((await http(slug, "POST", "/v1/admin/snapshots/restore/begin", { full: full.stamp, override_devices: true }, ADMIN)).status).toBe(200); expect((await restoreSteps(slug)).body.code).toBe("part_refused"); expect(await count(slug, "todo")).toBe(before); await http(slug, "POST", "/v1/admin/snapshots/restore/cancel", {}, ADMIN); // A manifest changed: refused at begin. await env.MEDIA.put(key, good); const manifestKey = `_snapshots/weekly/${slug}/${full.stamp}/manifest.json`; const manifest = (await (await env.MEDIA.get(manifestKey))!.json()) as { rows: number }; await env.MEDIA.put(manifestKey, JSON.stringify({ ...manifest, rows: manifest.rows + 1 })); expect((await http<{ code: string }>(slug, "POST", "/v1/admin/snapshots/restore/begin", { full: full.stamp, override_devices: true }, ADMIN)).body.code).toBe("manifest_refused"); expect(await count(slug, "todo")).toBe(before); expect((await http(slug, "POST", "/v1/admin/restore/unfreeze", {}, ADMIN)).status).toBe(200); }); it("replay the never-again ledger over a restore: a table erased stays erased, a token revoked stays revoked", async () => { const slug = "r2s2-ledger"; const { credential } = await personalObject(slug, { open: TODOS_OPEN }); await runInDurableObject(object(slug), (_i, state) => { const sql = state.storage.sql; let v = Number(sql.exec<{ value: string }>("SELECT value FROM meta WHERE key = 'version'").one().value); for (let i = 0; i < 5; i++) { v += 1; sql.exec("INSERT INTO rows (table_id, id, data, owner, version, deleted, created_at, updated_at) VALUES ('mood', ?, '{\"feeling\":\"calm\"}', NULL, ?, 0, '2026-11-01T00:00:00.000Z', '2026-11-01T00:00:00.000Z')", `mood-${i}`, v); } sql.exec("UPDATE meta SET value = ? WHERE key = 'version'", String(v)); }); await http(slug, "POST", "/v1/act", todo("kept"), phone(credential)); const token = await mint(slug, credential, "an invented assistant", ["owner"]); const asks = (t: string) => http(slug, "POST", "/mcp", { jsonrpc: "2.0", id: 1, method: "tools/list" }, { authorization: `Bearer ${t}` }); expect((await asks(token)).status).toBe(200); await http(slug, "POST", "/v1/admin/snapshots", { on: true }, ADMIN); const full = await runUntilDone(slug, "full"); await runUntilDone(slug, "daily"); // After the copies: the table erased for good, the token revoked. for (let i = 0; i < 20; i++) if ((await http<{ done: boolean }>(slug, "POST", "/v1/admin/erase", { set: "tables", tables: ["mood"], confirm: "erase" }, ADMIN)).body.done) break; expect(await count(slug, "mood")).toBe(0); const tokenId = await runInDurableObject(object(slug), (_i, state) => state.storage.sql.exec<{ id: string }>("SELECT id FROM rows WHERE table_id = 'mcp_token' ORDER BY version DESC LIMIT 1").one().id); expect((await http(slug, "POST", "/v1/act", { act: "revoke_token", args: { id: tokenId } }, phone(credential))).status).toBe(200); expect((await asks(token)).status).toBe(401); const ledger = await env.PHOTOS.list({ prefix: `_restore/${slug}/never-again/` }); expect(ledger.objects.length, "copied out of the object after each request").toBeGreaterThan(0); await http(slug, "POST", "/v1/admin/restore/freeze", {}, ADMIN); expect((await http(slug, "POST", "/v1/admin/snapshots/restore/begin", { full: full.stamp, override_devices: true }, ADMIN)).status).toBe(200); const done = await restoreSteps(slug); expect(done.status, JSON.stringify(done.body)).toBe(200); expect(done.body.ledger).toMatchObject({ tokens_revoked: 1 }); expect((done.body.ledger as { rows_erased: number }).rows_erased).toBeGreaterThanOrEqual(5); await http(slug, "POST", "/v1/admin/restore/unfreeze", {}, ADMIN); expect(await count(slug, "mood"), "the erased table did not come back").toBe(0); expect(await runInDurableObject(object(slug), (_i, state) => state.storage.sql.exec<{ n: number }>("SELECT count(*) AS n FROM rows WHERE table_id = 'todo' AND deleted = 0").one().n)).toBeGreaterThanOrEqual(1); expect((await asks(token)).status, "the revoked token did not come back").toBe(401); });});describe("RESTORE 2 SERVER 2: the devices that send the generation (the phone review's gap)", () => { it("records per device whether it ever sent x-cotton-generation and its last value, shows it, and refuses a restore until every active device has, unless overridden", async () => { const slug = "r2s2-devices"; const { credential } = await personalObject(slug, { open: TODOS_OPEN }); await http(slug, "POST", "/v1/act", todo("an older build: no header"), phone(credential)); type State = { devices: { device: string; sent_header: boolean; last_generation: string | null }[]; devices_unready: string[]; generation: string }; const first = (await http<State>(slug, "GET", "/v1/admin/restore/state", undefined, ADMIN)).body; expect(first.devices.length).toBe(1); expect(first.devices[0]).toMatchObject({ sent_header: false, last_generation: null }); expect(first.devices_unready).toEqual([first.devices[0]!.device]); await http(slug, "POST", "/v1/admin/restore/freeze", {}, ADMIN); const refused = await http<{ code: string; message: string }>(slug, "POST", "/v1/admin/restore", { bookmark: "x", restored_to: new Date().toISOString() }, ADMIN); expect(refused.status).toBe(409); expect(refused.body.code).toBe("devices_without_generation"); expect((await http<{ code: string }>(slug, "POST", "/v1/admin/snapshots/restore/begin", { full: "2026-11-01T00-00-00-000Z" }, ADMIN)).body.code).toBe("devices_without_generation"); // The override is explicit, and takes the ask on to the restore itself (no point-in-time recovery locally: 501). const overridden = await http<{ code?: string }>(slug, "POST", "/v1/admin/restore", { bookmark: "x", restored_to: new Date().toISOString(), override_devices: true }, ADMIN); expect(overridden.body.code).not.toBe("devices_without_generation"); if (overridden.status !== 200) await http(slug, "POST", "/v1/admin/restore/cancel", {}, ADMIN); await http(slug, "POST", "/v1/admin/restore/unfreeze", {}, ADMIN); // The phone updated: its writes name the generation. const generation = (await http<{ generation: string }>(slug, "GET", "/v1/me", undefined, phone(credential))).body.generation; expect((await http(slug, "POST", "/v1/act", todo("a new build"), phone(credential, generation))).status).toBe(200); const after = (await http<State>(slug, "GET", "/v1/admin/restore/state", undefined, ADMIN)).body; expect(after.devices[0]).toMatchObject({ sent_header: true, last_generation: generation }); expect(after.devices_unready).toEqual([]); await http(slug, "POST", "/v1/admin/restore/freeze", {}, ADMIN); const asked = await http<{ code?: string }>(slug, "POST", "/v1/admin/restore", { bookmark: "x", restored_to: new Date().toISOString() }, ADMIN); expect(asked.body.code, "every active device sends it: the ask goes on").not.toBe("devices_without_generation"); if (asked.status !== 200) await http(slug, "POST", "/v1/admin/restore/cancel", {}, ADMIN); await http(slug, "POST", "/v1/admin/restore/unfreeze", {}, ADMIN); }); it("after a restore every answer carries restored_to: /v1/me, every sync page and generation_moved", async () => { const slug = "r2s2-restored-to"; const { credential } = await personalObject(slug, { open: TODOS_OPEN }); const version = (await http<{ version: number }>(slug, "GET", "/v1/me", undefined, phone(credential))).body.version; await http(slug, "POST", "/v1/admin/restore/freeze", {}, ADMIN); const restoredTo = "2026-11-27T08:00:00.000Z"; await env.PHOTOS.put(markerKey(slug), JSON.stringify({ frozen: true, frozen_at: null, reason: null, pending: { version_before: version, generation: "DDDDDDDDDDDDDDDDDDDDDD", restored_to: restoredTo, bookmark_hash: "0", erased_before: false, asked_at: new Date().toISOString(), sentinel: "gone" } })); expect((await http(slug, "POST", "/v1/admin/restore/finish", {}, ADMIN)).status).toBe(200); await http(slug, "POST", "/v1/admin/restore/unfreeze", {}, ADMIN); expect((await http<{ restored_to: string }>(slug, "GET", "/v1/me", undefined, phone(credential))).body.restored_to).toBe(restoredTo); let cursor: string | null = null; for (let page = 0; page < 20; page++) { const got: { body: { restored_to: string; generation: string; next?: string | null } } = await http(slug, "GET", `/v1/sync?since=0&limit=2${cursor ? `&cursor=${encodeURIComponent(cursor)}` : ""}`, undefined, phone(credential)); expect(got.body).toMatchObject({ generation: "DDDDDDDDDDDDDDDDDDDDDD", restored_to: restoredTo }); cursor = got.body.next ?? null; if (!cursor) break; } expect((await http<{ restored_to: string }>(slug, "POST", "/v1/act", todo("old"), phone(credential, "AAAAAAAAAAAAAAAAAAAAAA"))).body.restored_to).toBe(restoredTo); });});