160 lines · 12.6 KB · TypeScriptRaw
/** * RESTORE 2, the owner's own restore (src/restore_owner.ts; RESTORE-2-CONTRACT.md 8): the owner's signed-in phone * lists the days the snapshots kept, begins a restore, steps it (or leaves it to the alarm), and the account comes back * row for row with a new generation, unfrozen by itself. Nobody else may: an assistant's key, the admin token, another * person's phone. Refused once the account's delete has begun. Taken back while it is still checking. */import { env, runDurableObjectAlarm, runInDurableObject } from "cloudflare:test";import { describe, expect, it } from "vitest";import { restoreRoutesOn } from "../src/restore.ts";import { pointsOf } from "../src/restore_owner.ts";import { ADMIN, http, personalObject, TODOS_OPEN } from "./personal.ts";const device = (credential: string, generation?: string) => ({ authorization: `Bearer ${credential}`, ...(generation ? { "x-cotton-generation": generation } : {}) });const object = (slug: string) => env.BUSINESS.get(env.BUSINESS.idFromName(slug));const todo = (title: string) => ({ act: "create", args: { table: "todo", data: { title } } });type State = { stage: string; restore: { parts: number; checked: number; laid: number; done: number; total: number; to: string } | null; may_cancel: boolean; generation: string; restored_to: string | null; finished?: boolean; cancelled?: boolean };type Listed = State & { on: boolean; points: { id: string; to: string }[]; devices_unready: number };async function stored(slug: string): Promise<string[]> { return runInDurableObject(object(slug), (_i, state) => state.storage.sql .exec<Record<string, SqlStorageValue>>("SELECT table_id, id, data, owner, version, deleted, created_at, updated_at FROM rows ORDER BY table_id, id") .toArray() .map((r) => JSON.stringify(r)), );}async function snapshot(slug: string, kind: "full" | "daily"): Promise<void> { for (let n = 0; n < 20; n++) { const got = await http<{ done?: boolean; manifest?: unknown }>(slug, "POST", "/v1/admin/snapshots/run", n === 0 ? { kind } : {}, ADMIN); expect(got.status, JSON.stringify(got.body)).toBe(200); if (got.body.done && got.body.manifest) return; } throw new Error("the copy never finished");}/** An account with a weekly full and a daily after it, then damaged: every to-do deleted. Answers what the daily held. */async function keptThenDamaged(slug: string): Promise<{ credential: string; owner: string; kept: string[]; generation: string }> { const { credential, owner } = await personalObject(slug, { open: TODOS_OPEN }); const generation = (await http<{ generation: string }>(slug, "GET", "/v1/me", undefined, device(credential))).body.generation; const ids: string[] = []; for (let i = 0; i < 6; i++) ids.push((await http<{ changed: { id: string }[] }>(slug, "POST", "/v1/act", todo(`Invented ${i}`), device(credential, generation))).body.changed[0]!.id); await http(slug, "POST", "/v1/admin/snapshots", { on: true }, ADMIN); await snapshot(slug, "full"); await http(slug, "POST", "/v1/act", todo("Invented later"), device(credential, generation)); await snapshot(slug, "daily"); const kept = await stored(slug); for (const id of ids) await http(slug, "POST", "/v1/act", { act: "delete", args: { table: "todo", id } }, device(credential, generation)); expect(await stored(slug)).not.toEqual(kept); return { credential, owner, kept, generation };}describe("RESTORE 2, the owner's own restore", () => { it("answers only where the restore routes are on (dev and test); live answers nothing new", () => { expect(restoreRoutesOn({ ENV_LABEL: "production" })).toBe(false); expect(restoreRoutesOn({})).toBe(false); expect(restoreRoutesOn({ ENV_LABEL: "test" })).toBe(true); }); it("is the owner's own signed-in phone's alone: an assistant's key, the admin token, another person's phone and no credential are refused", async () => { const slug = "restore-owner-who"; const { credential, owner } = await personalObject(slug, { open: TODOS_OPEN }); expect((await http<{ code: string }>(slug, "GET", "/v1/restore")).body.code).toBe("sign_in"); expect((await http<{ code: string }>(slug, "GET", "/v1/restore", undefined, device(owner))).body.code).toBe("owner_device_only"); expect((await http<{ code: string }>(slug, "GET", "/v1/restore", undefined, ADMIN)).body.code).toBe("owner_device_only"); // Another person on the account (a member), signed in on their own phone. expect((await http(slug, "POST", "/v1/admin/person", { phone: "+919000000077", role: "member" }, ADMIN)).status).toBe(200); const code = await http<{ challenge_id: string }>(slug, "POST", "/v1/code", { phone: "+919000000077", device_id: "member-phone" }); const member = await http<{ credential: string; person: { role: string } }>(slug, "POST", "/v1/sign-in", { challenge_id: code.body.challenge_id, code: "123456", device_id: "member-phone" }); expect(member.body.person.role).toBe("member"); const refused = await http<{ code: string }>(slug, "POST", "/v1/restore/begin", { point: "x" }, device(member.body.credential)); expect([refused.status, refused.body.code]).toEqual([403, "owner_device_only"]); // The owner's phone: nothing kept yet (snapshots are off by default), so no day to restore. const listed = await http<Listed>(slug, "GET", "/v1/restore", undefined, device(credential)); expect(listed.status, JSON.stringify(listed.body)).toBe(200); expect(listed.body).toMatchObject({ on: false, points: [], stage: "none", restore: null }); }); it("lists the days, refuses while a device sends no generation (unless anyway), restores row for row, interrupted and resumed by the alarm, and unfreezes by itself", async () => { const slug = "restore-owner-cycle"; const { credential, kept, generation } = await keptThenDamaged(slug); const listed = (await http<Listed>(slug, "GET", "/v1/restore", undefined, device(credential))).body; expect(listed.on).toBe(true); expect(listed.points.length).toBeGreaterThanOrEqual(1); const point = listed.points[0]!; // Another phone of the owner's, an older build that never sends the generation: the phone is told how many such // devices there are, and may go on anyway. const code = await http<{ challenge_id: string }>(slug, "POST", "/v1/code", { phone: "+919000000009", device_id: "older-build" }); const older = await http<{ credential: string }>(slug, "POST", "/v1/sign-in", { challenge_id: code.body.challenge_id, code: "123456", device_id: "older-build" }); expect(older.status).toBe(200); const unready = await http<{ code: string; devices: number }>(slug, "POST", "/v1/restore/begin", { point: point.id }, device(credential)); expect([unready.status, unready.body.code, unready.body.devices]).toEqual([409, "devices_without_generation", 1]); expect((await http<{ code: string }>(slug, "POST", "/v1/restore/begin", { point: "no-such" }, device(credential))).body.code).toBe("no_such_point"); const begun = await http<State>(slug, "POST", "/v1/restore/begin", { point: point.id, anyway: true }, device(credential)); expect(begun.status, JSON.stringify(begun.body)).toBe(200); expect(begun.body).toMatchObject({ stage: "checking", may_cancel: true }); expect(begun.body.restore!.to).toBe(point.to); // Frozen to everyone else meanwhile; a second begin is told one is under way. expect((await http<{ code: string }>(slug, "GET", "/v1/sync?since=0", undefined, device(credential))).body.code).toBe("account_frozen"); expect((await http<{ code: string }>(slug, "POST", "/v1/restore/begin", { point: point.id, anyway: true }, device(credential))).body.code).toBe("restore_under_way"); // One step from the phone, then the phone goes away (interrupted): the alarm carries it on, and the phone, back, // reads where it stands and steps it to its end. const first = (await http<State>(slug, "POST", "/v1/restore/step", {}, device(credential))).body; expect(["checking", "laying", "none"]).toContain(first.stage); await runDurableObjectAlarm(object(slug)); let state = (await http<State>(slug, "GET", "/v1/restore/state", undefined, device(credential))).body; for (let n = 0; n < 20 && state.stage !== "none"; n++) state = (await http<State>(slug, "POST", "/v1/restore/step", {}, device(credential))).body; expect(state.stage).toBe("none"); expect(await stored(slug), "every row as the daily held it").toEqual(kept); expect(state.generation).not.toBe(generation); expect(state.restored_to).toBe(new Date(point.to).toISOString()); // Unfrozen by itself: the phone's pull answers the new generation and restored_to; its old copy's write is refused. const sync = await http<{ generation: string; restored_to: string }>(slug, "GET", "/v1/sync?since=0&limit=1", undefined, device(credential)); expect(sync.body).toMatchObject({ generation: state.generation, restored_to: state.restored_to }); expect((await http<{ code: string }>(slug, "POST", "/v1/act", todo("from the old copy"), device(credential, generation))).body.code).toBe("generation_moved"); }); it("is taken back while it checks (no row touched, unfrozen), and not once rows are being laid back", async () => { const slug = "restore-owner-cancel"; const { credential } = await keptThenDamaged(slug); const damaged = await stored(slug); const point = (await http<Listed>(slug, "GET", "/v1/restore", undefined, device(credential))).body.points[0]!; expect((await http<{ code: string }>(slug, "POST", "/v1/restore/cancel", {}, device(credential))).body.code).toBe("no_restore"); await http(slug, "POST", "/v1/restore/begin", { point: point.id, anyway: true }, device(credential)); const cancelled = await http<State>(slug, "POST", "/v1/restore/cancel", {}, device(credential)); expect(cancelled.status, JSON.stringify(cancelled.body)).toBe(200); expect(cancelled.body).toMatchObject({ stage: "none", cancelled: true }); expect(await stored(slug)).toEqual(damaged); expect((await http(slug, "GET", "/v1/sync?since=0&limit=1", undefined, device(credential))).status).toBe(200); // Begun again and stepped until it lays rows: no longer taken back. await http(slug, "POST", "/v1/restore/begin", { point: point.id, anyway: true }, device(credential)); let state = (await http<State>(slug, "GET", "/v1/restore/state", undefined, device(credential))).body; for (let n = 0; n < 20 && state.stage === "checking"; n++) state = (await http<State>(slug, "POST", "/v1/restore/step", {}, device(credential))).body; if (state.stage === "laying") expect((await http<{ code: string }>(slug, "POST", "/v1/restore/cancel", {}, device(credential))).body.code).toBe("restore_laying"); for (let n = 0; n < 20 && state.stage !== "none"; n++) state = (await http<State>(slug, "POST", "/v1/restore/step", {}, device(credential))).body; expect(state.stage).toBe("none"); }); it("is refused once the account's delete has begun", async () => { const slug = "restore-owner-deleting"; const { credential } = await keptThenDamaged(slug); const point = (await http<Listed>(slug, "GET", "/v1/restore", undefined, device(credential))).body.points[0]!; const code = await http<{ challenge_id: string }>(slug, "POST", "/v1/account/delete/code", {}, device(credential)); expect((await http(slug, "POST", "/v1/account/delete", { challenge_id: code.body.challenge_id, code: "123456", confirm: "delete" }, device(credential))).status).toBe(202); const refused = await http<{ code: string }>(slug, "POST", "/v1/restore/begin", { point: point.id, anyway: true }, device(credential)); expect([refused.status, refused.body.code]).toEqual([409, "account_deleting"]); expect(await env.PHOTOS.head(`_restore/${slug}/marker.json`), "nothing frozen").toBeNull(); }); it("counts each daily after a full as one day, newest first, and none past a break in the chain or the ledger's reach", () => { const m = (kind: "full" | "daily", stamp: string, base: number, upto: number) => ({ kind, stamp, slug: "s", base, upto, rows: 1, bytes: 1, parts: [], started_at: `${stamp}T00:00:00.000Z`, written_at: "", format: "ndjson.gz.aes256gcm+aad" as const }); const fulls = [m("full", "2026-11-01", 0, 10), m("full", "2026-11-08", 0, 20)]; const dailies = [m("daily", "2026-11-02", 10, 12), m("daily", "2026-11-03", 12, 14), m("daily", "2026-11-04", 99, 100), m("daily", "2026-11-09", 20, 22)]; const points = pointsOf(fulls, dailies, (at) => at >= "2026-11-01"); expect(points.map((p) => p.id)).toEqual(["2026-11-08~2026-11-09", "2026-11-01~2026-11-03", "2026-11-01~2026-11-02"]); expect(pointsOf(fulls, dailies, (at) => at >= "2026-11-05").map((p) => p.id)).toEqual(["2026-11-08~2026-11-09"]); });});