/** * RESTORE 2 SERVER 3 (coordinator's second review of 0b59eeb02d, 27 Nov 2026). Restore's own files are never served * (M1); the never-again ledger is written where each thing happens, so no caller forgets (M2); a Keep in progress is * finished by a restore and a frozen object's knock is not counted (M3); the generation is checked only once the caller * is someone, a half-laid restore has a way forward, the ledger is folded, and on live rules restore reads nothing * (LOW); a delivery refused by a frozen account is kept and tried again (open point 1). All accounts invented. */ import { env, runDurableObjectAlarm, runInDurableObject, SELF } from "cloudflare:test"; import { describe, expect, it } from "vitest"; import * as accountDelete from "../src/account_delete.ts"; import * as handover from "../src/handover.ts"; import * as neverAgain from "../src/never_again.ts"; 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; restoreMarker: unknown; deleteHost(): accountDelete.DeleteHost; alarm(): Promise }; const inside = (i: unknown) => i as Inside; const outbox = (slug: string) => runInDurableObject(object(slug), (_i, state) => { try { return state.storage.sql.exec<{ entry: string }>("SELECT entry FROM never_again_outbox ORDER BY seq").toArray().map((r) => JSON.parse(r.entry) as neverAgain.Entry); } catch { return [] as neverAgain.Entry[]; } }); describe("RESTORE 2 SERVER 3: never served (M1)", () => { it("a photo path with a segment beginning with . or _ is refused, and so is the erasing mark's word; a real photo is served", async () => { const slug = "r2s3-photos"; await env.PHOTOS.put(`${slug}/abc.jpg`, new Uint8Array([0xff, 0xd8, 0xff]), { httpMetadata: { contentType: "image/jpeg" } }); await env.PHOTOS.put(`${slug}/.hidden`, "invented"); await env.PHOTOS.put(`${slug}/_restore/x`, "invented"); await env.PHOTOS.put(`${slug}/a/.b/c`, "invented"); await env.PHOTOS.put("erasing/0123abcd", "invented"); const get = (path: string) => SELF.fetch(`https://example.test${path}`); expect((await get(`/b/${slug}/v1/photos/${slug}/abc.jpg`)).status).toBe(200); for (const path of [`/b/${slug}/v1/photos/${slug}/.hidden`, `/b/${slug}/v1/photos/${slug}/_restore/x`, `/b/${slug}/v1/photos/${slug}/a/.b/c`, `/b/${slug}/v1/photos/${slug}/%2Ehidden`, "/b/erasing/v1/photos/erasing/0123abcd"]) { expect((await get(path)).status, path).toBe(404); } }); it("keeps the ledger, the marker, snapshots and exports outside every prefix a public route maps", async () => { const slug = "r2s3-prefixes"; const { credential } = await personalObject(slug, { open: TODOS_OPEN }); const token = await mint(slug, credential, "an invented assistant", ["owner"]); 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(token).toBeTruthy(); expect((await http(slug, "POST", "/v1/act", { act: "revoke_token", args: { id: tokenId } }, phone(credential))).status).toBe(200); await http(slug, "POST", "/v1/admin/restore/freeze", {}, ADMIN); expect((await env.PHOTOS.list({ prefix: `${slug}/` })).objects.map((o) => o.key), "nothing of restore's under the public prefix").toEqual([]); expect((await env.PHOTOS.list({ prefix: `_restore/${slug}/never-again/` })).objects.length).toBeGreaterThan(0); expect(markerKey(slug).startsWith("_restore/")).toBe(true); expect(await env.PHOTOS.head(markerKey(slug))).not.toBeNull(); await http(slug, "POST", "/v1/admin/restore/unfreeze", {}, ADMIN); }); }); describe("RESTORE 2 SERVER 3: the ledger where it happens (M2)", () => { it("a deletion set, then kept by any path (the admin hold's on the date included), is in the ledger; a revoked device and an OAuth token too", async () => { const slug = "r2s3-ledger-paths"; const { credential } = await personalObject(slug, { open: TODOS_OPEN }); await runInDurableObject(object(slug), async (instance) => { const host = inside(instance).deleteHost(); await accountDelete.start(host, "app", { databaseId: null, slug, ownerPhone: null }); await accountDelete.keep(host); }); // A device row revoked by a phone's own write, and a token revoked the way OAuth does it: both through Store.update. await runInDurableObject(object(slug), (instance) => { const store = (instance as unknown as { store: { insert(t: string, id: string, data: Record, owner: string | null, version: number): { table: string; id: string; data: Record }; update(row: unknown, data: Record, owner: string | null, version: number): unknown } }).store; const device = store.insert("device", "dev-invented", { name: "An invented phone" }, null, 1); store.update(device, { ...device.data, revoked_at: "2026-11-27T10:00:00.000Z" }, null, 2); }); const kinds = (await outbox(slug)).map((e) => e.kind); // Copied out after each request; whatever is left in the outbox plus what is in R2 is the ledger. const copied = await runInDurableObject(object(slug), async () => neverAgain.read(env.PHOTOS, slug)); const all = [...copied.map((e) => e.kind), ...kinds]; expect(all).toContain("account_delete"); expect(all).toContain("sessions_all_revoked"); expect(all.lastIndexOf("account_keep")).toBeGreaterThan(all.lastIndexOf("account_delete")); expect(all).toContain("row_revoked"); expect(credential).toBeTruthy(); }); }); describe("RESTORE 2 SERVER 3: the account-delete work (M3)", () => { it("a restored moment with a Keep half done finishes the Keep; it is never held as a deletion", async () => { const slug = "r2s3-keeping"; 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); await runInDurableObject(object(slug), (_i, state) => { const sql = state.storage.sql; sql.exec(accountDelete.SCHEMA); sql.exec(`INSERT INTO ${accountDelete.TABLE} (id, phase, started_at, by, database_id, slug, owner_phone, receipt, erase_at) VALUES (1, 'keeping', '2026-11-20T08:00:00.000Z', 'app', NULL, ?, NULL, ?, '2026-12-20T08:00:00.000Z')`, slug, JSON.stringify({ started_at: "2026-11-20T08:00:00.000Z", finished_at: null, by: "app", records: 0, files: 0, bytes: 0, google: { held: 0, revoked: 0 }, reports: 0 })); }); await env.PHOTOS.put(markerKey(slug), JSON.stringify({ frozen: true, frozen_at: null, reason: null, pending: { version_before: version, generation: "EEEEEEEEEEEEEEEEEEEEEE", restored_to: "2026-11-21T00:00:00.000Z", bookmark_hash: "0", erased_before: false, asked_at: new Date().toISOString(), sentinel: "gone" } })); const finished = await http<{ deletion: unknown }>(slug, "POST", "/v1/admin/restore/finish", {}, ADMIN); expect(finished.status, JSON.stringify(finished.body)).toBe(200); expect(finished.body.deletion).toBeNull(); await http(slug, "POST", "/v1/admin/restore/unfreeze", {}, ADMIN); expect((await http(slug, "GET", "/v1/sync?since=0&limit=1", undefined, phone(credential))).status, "kept: the account answers").toBe(200); }); it("the directory's knock on a frozen object is not counted against its knocks", async () => { const slug = "r2s3-knock"; await personalObject(slug, { open: TODOS_OPEN }); await http(slug, "POST", "/v1/admin/restore/freeze", {}, ADMIN); const directoryStub = env.DIRECTORY.get(env.DIRECTORY.idFromName("directory")); const n = await runInDurableObject(directoryStub, async (instance, state) => { const sql = state.storage.sql; sql.exec("INSERT OR REPLACE INTO database (id, slug, phone, region, created_at, provisioned) VALUES ('22222222-2222-4222-8222-222222222222', ?, '+15550000099', 'apac', '2026-11-01T00:00:00.000Z', 1)", slug); sql.exec("INSERT OR REPLACE INTO deleting (id, asked_at, erase_at, state, changed_at) VALUES ('22222222-2222-4222-8222-222222222222', '2026-10-01T00:00:00.000Z', '2026-10-31T00:00:00.000Z', 'pending', '2026-10-01T00:00:00.000Z')"); await (instance as unknown as { sweep(now?: number): Promise }).sweep(); return sql.exec<{ n: number }>("SELECT coalesce((SELECT n FROM sweep_knock WHERE id = '22222222-2222-4222-8222-222222222222'), 0) AS n").one().n; }); expect(n, "not counted").toBe(0); await http(slug, "POST", "/v1/admin/restore/unfreeze", {}, ADMIN); }); }); describe("RESTORE 2 SERVER 3: LOW", () => { it("a stranger learns nothing from the generation: a write with a stale header and no credential is refused as signed out, not 409", async () => { const slug = "r2s3-stranger"; await personalObject(slug, { open: TODOS_OPEN }); const stranger = await http<{ code: string }>(slug, "POST", "/v1/act", todo("x"), { "x-cotton-generation": "AAAAAAAAAAAAAAAAAAAAAA" }); expect(stranger.status).toBe(401); expect(stranger.body.code).not.toBe("generation_moved"); }); it("a part failing after the rows were emptied leaves a way forward: step again once it reads, and a new restore may begin", async () => { const slug = "r2s3-lay-fail"; 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 run = async (kind: string) => { for (let n = 0; n < 20; n++) { const got = await http<{ done?: boolean; manifest?: { stamp: string; parts: { key: string }[] } }>(slug, "POST", "/v1/admin/snapshots/run", n === 0 ? { kind } : {}, ADMIN); if (got.body.done) return got.body.manifest!; } throw new Error("never finished"); }; const full = await run("full"); await run("daily"); 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); // Step through the checking only (one step does all of it here), then break a part before laying. const checked = await http<{ phase: string }>(slug, "POST", "/v1/admin/snapshots/restore/step", {}, ADMIN); expect(checked.body.phase).toBe("lay"); const key = `_snapshots/weekly/${slug}/${full.stamp}/${full.parts[0]!.key}`; const good = new Uint8Array(await (await env.MEDIA.get(key))!.arrayBuffer()); await env.MEDIA.put(key, new Uint8Array([1, 2, 3])); expect((await http<{ code: string }>(slug, "POST", "/v1/admin/snapshots/restore/step", {}, ADMIN)).body.code).toBe("part_refused"); expect((await http<{ code: string }>(slug, "POST", "/v1/admin/snapshots/restore/cancel", {}, ADMIN)).body.code).toBe("restore_laying"); // A new restore may begin over a half-laid one; with the part back, it checks, empties and lays. await env.MEDIA.put(key, good); expect((await http(slug, "POST", "/v1/admin/snapshots/restore/begin", { full: full.stamp, override_devices: true }, ADMIN)).status).toBe(200); let step = { status: 0, body: {} as { done?: boolean } }; for (let n = 0; n < 10 && !step.body.done; n++) step = await http(slug, "POST", "/v1/admin/snapshots/restore/step", {}, ADMIN); expect(step.body.done).toBe(true); expect((await http(slug, "POST", "/v1/admin/restore/unfreeze", {}, ADMIN)).status).toBe(200); }); it("folds the ledger's chunks into one on the alarm, a week after the last fold, every entry kept in order", async () => { const slug = "r2s3-fold"; const { credential } = await personalObject(slug, { open: TODOS_OPEN }); for (let i = 0; i < 3; i++) { await mint(slug, credential, `invented ${i}`, ["owner"]); const id = await runInDurableObject(object(slug), (_i, state) => state.storage.sql.exec<{ id: string }>("SELECT id FROM rows WHERE table_id = 'mcp_token' AND json_extract(data, '$.revoked_at') IS NULL ORDER BY version DESC LIMIT 1").one().id); await http(slug, "POST", "/v1/act", { act: "revoke_token", args: { id } }, phone(credential)); } const before = await runInDurableObject(object(slug), async () => neverAgain.read(env.PHOTOS, slug)); expect((await env.PHOTOS.list({ prefix: `_restore/${slug}/never-again/` })).objects.length, "more than one chunk to fold").toBeGreaterThanOrEqual(2); await runInDurableObject(object(slug), async (_i, state) => { state.storage.sql.exec("INSERT OR REPLACE INTO meta (key, value) VALUES (?, '0')", neverAgain.COMPACTED); // A minute ahead: one set for now fires by itself, racing the run below. await state.storage.setAlarm(Date.now() + 60_000); }); expect(await runDurableObjectAlarm(object(slug)), "the alarm ran here").toBe(true); expect((await env.PHOTOS.list({ prefix: `_restore/${slug}/never-again/` })).objects.length).toBe(1); const after = await runInDurableObject(object(slug), async () => neverAgain.read(env.PHOTOS, slug)); expect(after).toEqual(before); }); it("on live rules a write, the alarm and a revoke read nothing of R2 and ask the directory nothing; a failed ledger copy leaves the request at 200", async () => { const slug = "r2s3-live-cost"; const { credential } = await personalObject(slug, { open: TODOS_OPEN }); await mint(slug, credential, "an invented assistant", ["owner"]); 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); const counts = await runInDurableObject(object(slug), async (instance) => { const me = inside(instance); const was = me.env; const reads = { r2: 0, directory: 0, puts: 0 }; const counting = (bucket: R2Bucket, failPuts: boolean) => new Proxy(bucket, { get: (t, k) => { if (k === "get" || k === "head" || k === "list") return (...a: unknown[]) => (reads.r2++, (Reflect.get(t, k) as (...x: unknown[]) => unknown).apply(t, a)); if (k === "put") return (...a: unknown[]) => (reads.puts++, failPuts && String(a[0]).startsWith("_restore/") ? Promise.reject(new Error("an invented R2 failure")) : (Reflect.get(t, k) as (...x: unknown[]) => unknown).apply(t, a)); return Reflect.get(t, k); }, }); const dir = was.DIRECTORY as DurableObjectNamespace; me.env = { ...was, ENV_LABEL: "live", PHOTOS: counting(was.PHOTOS as R2Bucket, true), MEDIA: counting(was.MEDIA as R2Bucket, false), DIRECTORY: new Proxy(dir, { get: (t, k) => (k === "get" ? (...a: unknown[]) => (reads.directory++, (Reflect.get(t, k) as (...x: unknown[]) => unknown).apply(t, a)) : Reflect.get(t, k)) }) }; me.restoreMarker = null; try { const ask = (body: unknown) => instance.fetch(new Request("https://x/v1/act", { method: "POST", headers: { authorization: `Bearer ${credential}`, "content-type": "application/json", "x-cotton-business": slug }, body: JSON.stringify(body) })); const write = (await ask(todo("invented"))).status; const revoke = (await ask({ act: "revoke_token", args: { id: tokenId } })).status; await me.alarm(); return { write, revoke, ...reads }; } finally { me.env = was; me.restoreMarker = null; } }); expect(counts.write).toBe(200); expect(counts.revoke, "the ledger's copy failed; the revoke stands").toBe(200); expect(counts.r2, "no R2 read").toBe(0); expect(counts.directory, "no directory call").toBe(0); const left = await outbox(slug); expect(left.some((e) => e.kind === "row_revoked"), "kept in the outbox for the next copy").toBe(true); }); }); describe("RESTORE 2 SERVER 3: deliveries to a frozen account are kept and tried again (open point 1)", () => { it("keeps a delivery refused as frozen, tries it again with a growing wait, hands it over once the account answers, and drops it after two days or on a real refusal", async () => { await runInDurableObject(object("r2s3-handover"), async (_i, state) => { const sql = state.storage.sql; const now = Date.now(); expect(handover.retryable(new Error("account_frozen: this account is frozen for a restore; not delivered, try again"))).toBe(true); expect(handover.retryable(new Error("blocked"))).toBe(false); expect(handover.keep(sql, "chat", "+15550000001", { id: "a" }, now)).toBe(true); expect(handover.keep(sql, "secret", "+15550000002", { id: "b" }, now)).toBe(true); const due = now + 61_000; let frozen = true; const tried: string[] = []; const deliver = async (kind: handover.Kind, to: string) => { tried.push(`${kind} ${to}`); if (kind === "secret") throw new Error("not one of their people"); if (frozen) throw new Error("account_frozen: not delivered, try again"); }; expect(await handover.retryDue(sql, deliver, due)).toEqual({ delivered: 0, waiting: 1, dropped: 1 }); const next = handover.nextDue(sql)!; expect(next - due).toBe(5 * 60_000); frozen = false; expect(await handover.retryDue(sql, deliver, next)).toEqual({ delivered: 1, waiting: 0, dropped: 0 }); expect(handover.nextDue(sql)).toBeNull(); // Two days on, still frozen: given up. handover.keep(sql, "send", "+15550000003", { id: "c" }, now); frozen = true; expect(await handover.retryDue(sql, deliver, now + handover.KEEP_MS + 1)).toEqual({ delivered: 0, waiting: 0, dropped: 1 }); expect(tried.length).toBe(4); }); }); });