Cotton code
347 lines · 19.3 KB · TypeScriptRaw
/** * DELETE ACCOUNT 2 (review of DELETE ACCOUNT 1, 27 Nov 2026): only the account object's own job row authorises an * erase; the directory's sweep only knocks; Keep and the admin hold are ordered so a failure leaves them retryable. *   - Keep, then the sweep a month on: nothing erased. A Keep whose marker delete throws, or whose directory call *     throws: retried, completed, and the sweep erases nothing either way. *   - The admin hold whose Keep fails on the date: completed later, nothing erased. *   - A second delete after a Keep: the directory's row is pending again, with the new dates, and erases. *   - The alarm before the date erases nothing. Folders `ab/` and `abc/` are kept apart. *   - The sweep's alarm ends: a row whose database is gone leaves the plan, a live object's row is marked kept. *   - Reports go before the number is let go; spaces that do not answer are waited for, then recorded after a day. * Invented numbers and rows only. */import { env, runDurableObjectAlarm, runInDurableObject } from "cloudflare:test";import { afterEach, describe, expect, it, vi } from "vitest";import type { Env } from "../src/env.ts";import { deletePrefix, job, run, TABLE, type DeleteHost } from "../src/account_delete.ts";import { Directory, directory, SWEEP_LATE_MS } from "../src/directory.ts";import { bearer, open, signUp } from "./calling.ts";import { sealRow } from "./seal-device.ts";import { http } from "./personal.ts";vi.setConfig({ testTimeout: 600_000 });afterEach(() => {  vi.restoreAllMocks();});const ADMIN = bearer("test-admin-token");const DAY = 86_400_000;const databaseOf = (credential: string): string => credential.split("_")[1]!;const slugOf = (credential: string): string => `p-${databaseOf(credential)}`;const object = (slug: string) => env.BUSINESS.get(env.BUSINESS.idFromName(slug));const theDirectory = () => env.DIRECTORY.get(env.DIRECTORY.idFromName("directory"));const rowsOf = (slug: string) => runInDurableObject(object(slug), (_i, state) => state.storage.sql.exec<{ n: number }>("SELECT count(*) AS n FROM rows WHERE deleted = 0").one().n);const phaseOf = (slug: string) => runInDurableObject(object(slug), (_i, state) => job(state.storage.sql)?.phase ?? null);const directoryRow = (databaseId: string) =>  runInDurableObject(theDirectory(), (_i, state) => state.storage.sql.exec<{ state: string; erase_at: string }>("SELECT state, erase_at FROM deleting WHERE id = ?", databaseId).toArray()[0] ?? null);/** Signed up with a few records and a file, set to be deleted from the app. */async function setToGo(phone: string, device: string): Promise<{ credential: string; slug: string; databaseId: string; records: number }> {  const credential = await signUp(phone, device);  const slug = slugOf(credential);  for (let i = 0; i < 3; i++) {    const id = crypto.randomUUID();    const data = { ...(await sealRow(new Uint8Array(32).fill(5), "todo", id, 1, { title: `Invented ${i}` })), status: "open" };    expect((await open("POST", "/v1/act", { act: "create", args: { table: "todo", id, data } }, bearer(credential))).status).toBe(200);  }  await env.MEDIA.put(`${slug}/photos/kept.jpg`, new Uint8Array(100));  await askDelete(credential);  return { credential, slug, databaseId: databaseOf(credential), records: await rowsOf(slug) };}async function askDelete(credential: string): Promise<void> {  const code = await open<{ challenge_id: string }>("POST", "/v1/account/delete/code", {}, bearer(credential));  expect(code.status, JSON.stringify(code.body)).toBe(200);  const asked = await open("POST", "/v1/account/delete", { challenge_id: code.body.challenge_id, code: "123456", confirm: "delete" }, bearer(credential));  expect(asked.status, JSON.stringify(asked.body)).toBe(202);}/** A sign-in in the thirty days, and Keep from it. */async function signInAndKeep(phone: string, databaseId: string, device: string): Promise<{ status: number; body: Record<string, unknown>; credential: string }> {  const code = await open<{ challenge_id: string }>("POST", "/v1/code", { phone, device_id: device }, { "cf-connecting-ip": "192.0.2.77" });  const signed = await open<{ credential: string }>("POST", "/v1/sign-in", { database_id: databaseId, challenge_id: code.body.challenge_id, code: "123456", device_id: device }, { "cf-connecting-ip": "192.0.2.77" });  expect(signed.status, JSON.stringify(signed.body)).toBe(200);  const kept = await open<Record<string, unknown>>("POST", "/v1/account/keep", {}, bearer(signed.body.credential));  return { ...kept, credential: signed.body.credential };}/** A month and a day on, the date long past as the object sees it, then the sweep a month and a day on. */async function monthOnAndSweep(slug: string): Promise<{ asked: number; failed: number }> {  await runInDurableObject(object(slug), (_i, state) => {    if (state.storage.sql.exec<{ n: number }>("SELECT count(*) AS n FROM sqlite_master WHERE name = ?", TABLE).one().n) state.storage.sql.exec(`UPDATE ${TABLE} SET erase_at = '2000-01-01T00:00:00.000Z' WHERE phase = 'pending'`);  });  return directory(env).sweep(Date.now() + 31 * DAY + SWEEP_LATE_MS);}/** Every alarm the object has run, until none is left or it is set past now. */async function alarmsSettle(slug: string, most = 30): Promise<void> {  for (let n = 0; n < most; n++) {    const at = await runInDurableObject(object(slug), (_i, state) => state.storage.getAlarm());    if (at === null || at > Date.now() + 60_000) return;    try {      await runDurableObjectAlarm(object(slug));    } catch {      /* a step that threw comes back on its own alarm */    }  }}/** The account as it was: every record, its file, the number still on it, no deletion row, no marker. */async function intact(phone: string, slug: string, records: number): Promise<void> {  expect(await phaseOf(slug)).toBeNull();  expect(await rowsOf(slug)).toBe(records);  expect((await env.MEDIA.head(`${slug}/photos/kept.jpg`)) !== null).toBe(true);  expect(await env.PHOTOS.head(`${slug}/.deleting`)).toBeNull();  expect(await directory(env).lookup(phone)).toBe(slug);}/** The object's PHOTOS bucket made to refuse deletes until `heal` is called (an R2 that did not answer). */async function photosRefuseDeletes(slug: string): Promise<() => Promise<void>> {  await runInDurableObject(object(slug), (instance) => {    const self = instance as unknown as { env: Env & { __photos?: R2Bucket } };    const real = self.env.PHOTOS;    const broken = new Proxy(real, {      get(target, prop) {        if (prop === "delete") return async () => Promise.reject(new Error("R2 did not answer"));        const value = Reflect.get(target, prop) as unknown;        return typeof value === "function" ? (value as (...a: unknown[]) => unknown).bind(target) : value;      },    });    self.env = { ...self.env, PHOTOS: broken, __photos: real };  });  return async () => {    await runInDurableObject(object(slug), (instance) => {      const self = instance as unknown as { env: Env & { __photos?: R2Bucket } };      if (self.env.__photos) self.env = { ...self.env, PHOTOS: self.env.__photos };    });  };}describe("DELETE ACCOUNT 2: what the person kept is never erased", () => {  it("Keep, then the sweep a month on: nothing erased, the directory marks it kept", async () => {    const phone = "+919000005201";    const { slug, databaseId, records } = await setToGo(phone, "d2-1");    const kept = await signInAndKeep(phone, databaseId, "d2-1b");    expect(kept.status, JSON.stringify(kept.body)).toBe(200);    await monthOnAndSweep(slug);    await alarmsSettle(slug);    await intact(phone, slug, records);    expect((await directoryRow(databaseId))?.state).toBe("kept");  });  it("Keep whose marker delete throws: answered as a failure, retried and completed; the sweep erases nothing meanwhile", async () => {    const phone = "+919000005202";    const { slug, databaseId, records } = await setToGo(phone, "d2-2");    const heal = await photosRefuseDeletes(slug);    const first = await signInAndKeep(phone, databaseId, "d2-2b");    expect(first.status).toBeGreaterThanOrEqual(500);    // Half done: the sweep a month on knocks, and nothing of theirs goes.    await monthOnAndSweep(slug);    await alarmsSettle(slug);    expect(await rowsOf(slug)).toBe(records);    expect(["keeping", null]).toContain(await phaseOf(slug));    // R2 answers again: a second Keep completes it (never 410).    await heal();    const again = await open<Record<string, unknown>>("POST", "/v1/account/keep", {}, bearer(first.credential));    expect(again.status, JSON.stringify(again.body)).toBe(200);    expect(again.body).toMatchObject({ kept: true });    await intact(phone, slug, records);    await monthOnAndSweep(slug);    await intact(phone, slug, records);  });  it("Keep whose directory call throws: retried by the object's own alarm, completed, nothing erased", async () => {    const phone = "+919000005203";    const { slug, databaseId, records } = await setToGo(phone, "d2-3");    const broken = vi.spyOn(Directory.prototype, "deletingKept").mockImplementation(() => {      throw new Error("the directory did not answer");    });    const first = await signInAndKeep(phone, databaseId, "d2-3b");    expect(first.status).toBeGreaterThanOrEqual(500);    expect(await rowsOf(slug)).toBe(records);    broken.mockRestore();    // Nobody retries by hand: the object's own alarm completes the Keep.    await alarmsSettle(slug);    await intact(phone, slug, records);    expect((await directoryRow(databaseId))?.state).toBe("kept");    await monthOnAndSweep(slug);    await intact(phone, slug, records);  });  it("an account the admin holds, whose Keep fails on the date, is kept later and never erased", async () => {    const phone = "+919000005204";    const { slug, records } = await setToGo(phone, "d2-4");    expect((await http(slug, "POST", "/v1/admin/account/hold", { hold: true }, ADMIN)).status).toBe(200);    const broken = vi.spyOn(Directory.prototype, "deletingKept").mockImplementation(() => {      throw new Error("the directory did not answer");    });    await monthOnAndSweep(slug);    try {      await runDurableObjectAlarm(object(slug));    } catch {      /* the Keep on the date failed */    }    expect(await rowsOf(slug)).toBe(records);    broken.mockRestore();    await directory(env).sweep(Date.now() + 31 * DAY + 2 * SWEEP_LATE_MS);    await alarmsSettle(slug);    await intact(phone, slug, records);  });  it("a second delete after a Keep sets the directory's row pending again with the new dates, and erases on them", async () => {    const phone = "+919000005205";    const { slug, databaseId } = await setToGo(phone, "d2-5");    const first = (await directoryRow(databaseId))!;    const kept = await signInAndKeep(phone, databaseId, "d2-5b");    expect(kept.status).toBe(200);    expect((await directoryRow(databaseId))?.state).toBe("kept");    await new Promise((done) => setTimeout(done, 20));    await askDelete(kept.credential);    const second = (await directoryRow(databaseId))!;    expect(second.state).toBe("pending");    expect(Date.parse(second.erase_at)).toBeGreaterThan(Date.parse(first.erase_at));    expect((await http(slug, "POST", "/v1/admin/account/erase-now", {}, ADMIN)).status).toBe(200);    for (let n = 0; n < 40 && (await phaseOf(slug)) !== "done"; n++) await runDurableObjectAlarm(object(slug)).catch(() => false);    expect(await phaseOf(slug)).toBe("done");    expect(await directory(env).lookup(phone)).toBeNull();  });  it("a wipe mark beside a live account is never taken as leave to erase: the object answers live and keeps all", async () => {    const phone = "+919000005211";    const credential = await signUp(phone, "d2-11");    const slug = slugOf(credential);    const records = await rowsOf(slug);    const id = env.BUSINESS.idFromName(slug).toString();    const receipt = { started_at: "2026-10-01T00: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(`erasing/${id}`, JSON.stringify({ databaseId: databaseOf(credential), slug, startedAt: receipt.started_at, by: "app", receipt }));    const answer = await object(slug).deleteResume();    expect(answer.phase).toBe("live");    expect(await rowsOf(slug)).toBe(records);    expect(await phaseOf(slug)).toBeNull();    expect(await directory(env).lookup(phone)).toBe(slug);    await env.PHOTOS.delete(`erasing/${id}`);  });  it("an alarm before the date erases nothing", async () => {    const phone = "+919000005206";    const { slug, records } = await setToGo(phone, "d2-6");    await runDurableObjectAlarm(object(slug));    expect(await phaseOf(slug)).toBe("pending");    expect(await rowsOf(slug)).toBe(records);    // The sweep knocking early changes nothing either.    await directory(env).sweep();    expect(await phaseOf(slug)).toBe("pending");  });  it("deletes one folder and never another whose name it begins (ab/ and abc/)", async () => {    await env.MEDIA.put("ab/x.jpg", new Uint8Array(3));    await env.MEDIA.put("abc/y.jpg", new Uint8Array(3));    expect((await deletePrefix(env.MEDIA, "ab/", 5)).files).toBe(1);    expect(await env.MEDIA.head("ab/x.jpg")).toBeNull();    expect(await env.MEDIA.head("abc/y.jpg")).not.toBeNull();  });});describe("DELETE ACCOUNT 2: the sweep only knocks, and its alarm ends", () => {  it("drops a pending row whose database is gone, marks a live object's row kept, and sets no alarm after", async () => {    const phone = "+919000005207";    const credential = await signUp(phone, "d2-7");    const live = databaseOf(credential);    const ghost = crypto.randomUUID();    await runInDurableObject(theDirectory(), async (_i, state) => {      // A Keep half done on main (the directory never told) and a row whose database is no longer in the directory.      state.storage.sql.exec("INSERT OR REPLACE INTO deleting (id, asked_at, erase_at, state, changed_at) VALUES (?, '2026-10-01T00:00:00.000Z', '2026-10-31T00:00:00.000Z', 'pending', '2026-10-01T00:00:00.000Z')", live);      state.storage.sql.exec("INSERT OR REPLACE INTO deleting (id, asked_at, erase_at, state, changed_at) VALUES (?, '2026-10-01T00:00:00.000Z', '2026-10-31T00:00:00.000Z', 'pending', '2026-10-01T00:00:00.000Z')", ghost);    });    const checked = await open<{ pending: number; live: string[]; gone: string[] }>("GET", "/v1/admin/deletions/check", undefined, ADMIN);    expect(checked.status, JSON.stringify(checked.body)).toBe(200);    expect(checked.body.live).toContain(live);    expect(checked.body.gone).toContain(ghost);    await directory(env).sweep();    expect((await directoryRow(live))?.state).toBe("kept");    expect((await directoryRow(ghost))?.state).toBe("gone");    expect(await rowsOf(slugOf(credential))).toBeGreaterThanOrEqual(0);    expect(await phaseOf(slugOf(credential))).toBeNull();    // Nothing left for the sweep to look after from these: no row of theirs is in its plan.    const planned = await runInDurableObject(theDirectory(), (_i, state) => state.storage.sql.exec<{ n: number }>("SELECT count(*) AS n FROM deleting WHERE id IN (?, ?) AND state = 'pending'", live, ghost).one().n);    expect(planned).toBe(0);  });  it("stops knocking at an object that never moves: the alarm ends after its knocks", async () => {    const stuck = crypto.randomUUID();    const phone = "+919000005208";    const credential = await signUp(phone, "d2-8");    const slug = slugOf(credential);    await runInDurableObject(theDirectory(), (_i, state) => {      // An erase the directory holds as begun and never closed, for an object that answers live.      state.storage.sql.exec("INSERT OR REPLACE INTO erased (id, slug, started_at) VALUES (?, ?, '2026-10-01T00:00:00.000Z')", stuck, slug);    });    for (let n = 0; n < 40; n++) await directory(env).sweep(Date.now() + n * SWEEP_LATE_MS * 2);    const knocks = await runInDurableObject(theDirectory(), (_i, state) => state.storage.sql.exec<{ n: number }>("SELECT n FROM sweep_knock WHERE id = ?", stuck).toArray()[0]?.n ?? 0);    expect(knocks).toBeLessThanOrEqual(24);    expect(await phaseOf(slug)).toBeNull();    expect(await rowsOf(slug)).toBeGreaterThanOrEqual(0);    await runInDurableObject(theDirectory(), (_i, state) => state.storage.sql.exec("DELETE FROM erased WHERE id = ?", stuck));  });});describe("DELETE ACCOUNT 2: the order of the erase", () => {  /** A host whose every step records its name, over a real object's storage. */  async function recorded(slug: string, spaces: () => Promise<string[]>, recovery: () => Promise<string[]> = async () => []): Promise<{ calls: string[]; outs: (number | null)[]; receipt: Record<string, unknown>; phase: string }> {    return runInDurableObject(object(slug), async (_i, state) => {      state.storage.sql.exec(`UPDATE ${TABLE} SET erase_at = '2000-01-01T00:00:00.000Z'`);      const calls: string[] = [];      let clock = Date.now();      const host = {        sql: state.storage.sql,        storage: state.storage,        env,        now: () => new Date(clock),        forgetReports: async () => (calls.push("reports"), 0),        leaveSpaces: async () => (calls.push("spaces"), spaces()),        leaveRecovery: async () => (calls.push("recovery"), recovery()),        forgetInDirectory: async () => void calls.push("directory"),        revokeGoogle: async () => (calls.push("revoke"), { held: 0, revoked: 0 }),        closeInDirectory: async () => undefined,        closeForGrace: async () => undefined,        reopen: async () => undefined,      } as unknown as DeleteHost;      const outs: (number | null)[] = [];      for (let i = 0; i < 4 && job(state.storage.sql)!.phase !== "revoke" && job(state.storage.sql)!.phase !== "files"; i++) {        outs.push(await run(host));        clock += 25 * 3_600_000;      }      const j = job(state.storage.sql)!;      return { calls, outs, receipt: j.receipt as unknown as Record<string, unknown>, phase: j.phase };    });  }  it("forgets the reports while the number is still the account's, before the directory lets it go", async () => {    const { slug } = await setToGo("+919000005209", "d2-9");    const { calls } = await recorded(slug, async () => []);    expect(calls.indexOf("reports")).toBeGreaterThanOrEqual(0);    expect(calls.indexOf("reports")).toBeLessThan(calls.indexOf("directory"));  });  it("waits for spaces that do not answer, later each time, and after a day goes on and records them", async () => {    const { slug } = await setToGo("+919000005210", "d2-10");    const { outs, receipt, calls } = await recorded(slug, async () => ["space-invented-1"]);    // Waited at least once, with the erase's own back-off, then went on past the directory with the space recorded.    expect(outs[0]).toBeGreaterThan(0);    expect(calls.filter((c) => c === "directory")).toHaveLength(1);    expect(receipt.spaces_not_told).toEqual(["space-invented-1"]);  });  // TRUSTED RECOVERY BUILD 2, review H2: the people this one helps back in are told the same way, and never stall it.  it("waits for trusted people who do not take word, and after a day goes on and records them by short id", async () => {    const { slug } = await setToGo("+919000005211", "d2-11");    const { outs, receipt, calls } = await recorded(slug, async () => [], async () => ["a1b2c3d4e5f6"]);    expect(outs[0]).toBeGreaterThan(0);    expect(calls.indexOf("recovery")).toBeLessThan(calls.indexOf("directory"));    expect(calls.filter((c) => c === "directory")).toHaveLength(1);    expect(receipt.recovery_not_told).toEqual(["a1b2c3d4e5f6"]);  });});