/** * DELETE ACCOUNT 1 (27 Nov 2026): day thirty is real and automatic. * - a step that fails comes back on its own alarm, later each time, never given up; a lost alarm is set again by * any request, and by the directory's sweep; * - the object cut off mid-erase (after a page of files, and between its storage going and its closing row) carries * on, and the erase run twice changes nothing more; * - files still being sent in parts are aborted at R2; * - the directory keeps nothing that names the object (mail domain, bounces, the fourteen days, referrals); * - ninety days after the erase the database id is let go: the receipt stays under a random id, and a credential is * answered as one for no account; * - the admin's hold is logged. * Invented numbers and rows only. */ import { env, runDurableObjectAlarm, runInDurableObject } from "cloudflare:test"; import { describe, expect, it, vi } from "vitest"; import { BACKOFF_MS, FORGET_AFTER_MS, job, run, TABLE, type DeleteHost } from "../src/account_delete.ts"; import { 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 }); const ADMIN = bearer("test-admin-token"); 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")); async function keys(bucket: R2Bucket, prefix: string): Promise { return (await bucket.list({ prefix })).objects.map((o) => o.key); } async function tablesOf(slug: string): Promise> { return runInDurableObject(object(slug), (_i, state) => { const names = state.storage.sql.exec<{ name: string }>("SELECT name FROM sqlite_master WHERE type = 'table' AND name NOT LIKE 'sqlite_%' AND name NOT LIKE '_cf_%'").toArray().map((r) => r.name); return Object.fromEntries(names.map((n) => [n, state.storage.sql.exec<{ n: number }>(`SELECT count(*) AS n FROM "${n}"`).one().n])); }); } /** Inside the object, once more if the first try meets the object just cut off (its stub answers that once). */ async function inside(slug: string, fn: (state: DurableObjectState) => T | Promise): Promise { try { return await runInDurableObject(object(slug), (_i, state) => fn(state)); } catch { return runInDurableObject(object(slug), (_i, state) => fn(state)); } } type Kept = { id: string; started_at: string; finished_at: string | null; receipt: Record & { records: number; files: number } } | null; /** The directory's receipt for a database id, as the test reads it. */ const receiptOf = async (databaseId: string): Promise => (await directory(env).receipt(databaseId)) as unknown as Kept; const phaseOf = (slug: string) => inside(slug, (state) => job(state.storage.sql)?.phase ?? null); /** Signed up, a few sealed records and files in both buckets, set to be deleted, and its date brought to now. */ async function setAndDue(phone: string, device: string, eraseNow: Record = {}): Promise<{ credential: string; slug: string; databaseId: string }> { const credential = await signUp(phone, device); const slug = slugOf(credential); for (let i = 0; i < 4; i++) { const id = crypto.randomUUID(); const data = { ...(await sealRow(new Uint8Array(32).fill(7), "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/a.jpg`, new Uint8Array(1000)); await env.MEDIA.put(`${slug}/files/b.pdf`, new Uint8Array(2000)); await env.PHOTOS.put(`${slug}/c.png`, new Uint8Array(300)); 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); const now = await http(slug, "POST", "/v1/admin/account/erase-now", eraseNow, ADMIN); expect(now.status, JSON.stringify(now.body)).toBe(200); return { credential, slug, databaseId: databaseOf(credential) }; } /** The object's alarms run until its row says done (each run may be cut off, as asked). */ async function alarmsUntil(slug: string, phase = "done", most = 80): Promise { for (let n = 0; n < most; n++) { if ((await phaseOf(slug)) === phase) return; try { if (!(await runDurableObjectAlarm(object(slug)))) await new Promise((done) => setTimeout(done, 200)); } catch { // Cut off inside the alarm, as asked: the next one carries on. } } throw new Error(`the deletion never reached ${phase}; it is ${await phaseOf(slug)}`); } /** What is left of the account once it is done: the receipt's one row in the object, no file under its folder. */ async function nothingLeft(slug: string): Promise { expect(await tablesOf(slug)).toEqual({ [TABLE]: 1 }); expect(await keys(env.MEDIA, `${slug}/`)).toEqual([]); expect(await keys(env.PHOTOS, `${slug}/`)).toEqual([]); } describe("DELETE ACCOUNT 1: the erase carries on whatever happens", () => { it("cut off between its storage going and its closing row, the directory's sweep closes it with every count", async () => { const { slug, databaseId } = await setAndDue("+919000005101", "phone-d1-1", { kill_after: "storage" }); // The erase runs to the storage step, and the object is cut off there. for (let n = 0; n < 20 && (await phaseOf(slug)) !== null; n++) { try { await runDurableObjectAlarm(object(slug)); } catch { // Cut off, as asked. } } // The object holds nothing of the account and no closing row yet; its own wipe mark (DELETE ACCOUNT 2) holds the counts. expect(await phaseOf(slug)).toBeNull(); expect((await receiptOf(databaseId))?.finished_at).toBeNull(); const objectId = env.BUSINESS.idFromName(slug).toString(); const mark = (await (await env.PHOTOS.get(`erasing/${objectId}`))!.json()) as { receipt: { records: number; files: number } }; expect(mark.receipt.records).toBeGreaterThanOrEqual(4); expect(mark.receipt.files).toBe(3); // The sweep, an hour on, knocks: the object finds its own mark and an empty storage, and closes from the mark. const swept = await directory(env).sweep(Date.now() + SWEEP_LATE_MS + 60_000); expect(swept.failed).toBe(0); expect(swept.asked).toBeGreaterThanOrEqual(1); await alarmsUntil(slug); await nothingLeft(slug); expect(await env.PHOTOS.head(`erasing/${objectId}`)).toBeNull(); const closed = await receiptOf(databaseId); expect(closed?.finished_at).toBeTruthy(); expect(closed?.receipt).toMatchObject({ files: 3, bytes: 3300, left: { tables: 0, keys: 0 } }); // Run twice: the sweep and the alarm again change nothing more. await directory(env).sweep(Date.now() + SWEEP_LATE_MS + 60_000); await runDurableObjectAlarm(object(slug)); await nothingLeft(slug); expect((await receiptOf(databaseId))?.receipt).toEqual(closed?.receipt); }); it("cut off after a page of files, a request sets its alarm again and the erase carries on to the end", async () => { const { credential, slug, databaseId } = await setAndDue("+919000005102", "phone-d1-2", { kill_after: "files" }); await alarmsUntil(slug, "files"); try { await runDurableObjectAlarm(object(slug)); } catch { // Cut off after the first bucket's page, as asked. } // Whatever alarm was left is lost too: the next request to the object sets it again. await inside(slug, (state) => state.storage.deleteAlarm()); expect((await open<{ code: string }>("GET", "/v1/me", undefined, bearer(credential))).status).toBe(410); const viaObject = await http<{ code: string }>(slug, "GET", "/v1/me", undefined, bearer(credential)); expect(viaObject.body.code).toBe("account_deleted"); expect(await runInDurableObject(object(slug), (_i, state) => state.storage.getAlarm())).not.toBeNull(); await alarmsUntil(slug); await nothingLeft(slug); expect((await receiptOf(databaseId))?.receipt).toMatchObject({ files: 3, bytes: 3300, left: { tables: 0, keys: 0 } }); }); it("an account past its date whose alarm was lost is erased once the directory's sweep asks after it", async () => { const phone = "+919000005103"; const credential = await signUp(phone, "phone-d1-3"); const slug = slugOf(credential); const code = await open<{ challenge_id: string }>("POST", "/v1/account/delete/code", {}, bearer(credential)); expect((await open("POST", "/v1/account/delete", { challenge_id: code.body.challenge_id, code: "123456", confirm: "delete" }, bearer(credential))).status).toBe(202); // The date passes and the object's alarm is gone with nobody asking. await runInDurableObject(object(slug), async (_i, state) => { state.storage.sql.exec(`UPDATE ${TABLE} SET erase_at = '2000-01-01T00:00:00.000Z'`); await state.storage.deleteAlarm(); }); // Thirty days and an hour on, the sweep finds it. const swept = await directory(env).sweep(Date.now() + 30 * 86_400_000 + SWEEP_LATE_MS + 60_000); expect(swept.failed).toBe(0); // Its alarm set again (it may already be running): the erase goes to its end. await alarmsUntil(slug); expect(await directory(env).lookup(phone)).toBeNull(); expect(await directory(env).wasErased(databaseOf(credential))).toBe(true); }); it("a step that throws comes back later each time, never given up, and goes on once it takes", async () => { const credential = await signUp("+919000005104", "phone-d1-4"); const slug = slugOf(credential); const code = await open<{ challenge_id: string }>("POST", "/v1/account/delete/code", {}, bearer(credential)); expect((await open("POST", "/v1/account/delete", { challenge_id: code.body.challenge_id, code: "123456", confirm: "delete" }, bearer(credential))).status).toBe(202); const waits = await runInDurableObject(object(slug), async (_i, state) => { state.storage.sql.exec(`UPDATE ${TABLE} SET phase = 'directory'`); let fails = 3; const host = { sql: state.storage.sql, storage: state.storage, env, now: () => new Date(), forgetInDirectory: async () => { if (fails-- > 0) throw new Error("the directory did not answer"); }, revokeGoogle: async () => ({ held: 0, revoked: 0 }), forgetReports: async () => 0, closeInDirectory: async () => undefined, closeForGrace: async () => undefined, reopen: async () => undefined, } as unknown as DeleteHost; const out: (number | null)[] = []; for (let i = 0; i < 3; i++) out.push(await run(host)); const after = job(state.storage.sql)!; // Once the directory answers, the erase goes past it (to the files, which wait their next turn or finish). await run(host); return { out, tries: after.tries, phase: job(state.storage.sql)!.phase }; }); expect(waits.out).toEqual([BACKOFF_MS, BACKOFF_MS * 2, BACKOFF_MS * 4]); expect(waits.tries).toBe(3); expect(["revoke", "reports", "files", "storage", "closing", "done"]).toContain(waits.phase); }); }); describe("DELETE ACCOUNT 1: nothing that names the account is left", () => { it("aborts a file still being sent in parts, so no upload of theirs lingers at R2", async () => { const credential = await signUp("+919000005105", "phone-d1-5"); const slug = slugOf(credential); const started = await open<{ upload: string }>("POST", `/v1/media/${databaseOf(credential)}/files/half.bin?uploads`, { size: 12 * 1024 * 1024 }, bearer(credential)); expect(started.status, JSON.stringify(started.body)).toBe(201); const key = await runInDurableObject(object(slug), (_i, state) => state.storage.sql.exec<{ key: string }>("SELECT key FROM media_upload_open").one().key); await env.MEDIA.resumeMultipartUpload(key, started.body.upload).uploadPart(1, new Uint8Array(5 * 1024 * 1024)); const code = await open<{ challenge_id: string }>("POST", "/v1/account/delete/code", {}, bearer(credential)); expect((await open("POST", "/v1/account/delete", { challenge_id: code.body.challenge_id, code: "123456", confirm: "delete" }, bearer(credential))).status).toBe(202); expect((await http(slug, "POST", "/v1/admin/account/erase-now", {}, ADMIN)).status).toBe(200); await alarmsUntil(slug); await nothingLeft(slug); expect((await runInDurableObject(object(slug), (_i, state) => job(state.storage.sql)))?.receipt.uploads).toBe(1); // The upload is gone at R2: a part sent to it now is refused. await expect(env.MEDIA.resumeMultipartUpload(key, started.body.upload).uploadPart(2, new Uint8Array(10))).rejects.toThrow(); }); it("the directory forgets their mail domain, bounces, fourteen days and naming of an inviter; a referral stays counted for the other person", async () => { const credential = await signUp("+919000005106", "phone-d1-6"); const slug = slugOf(credential); const friend = slugOf(await signUp("+919000005107", "phone-d1-7")); await runInDurableObject(theDirectory(), (_i, state) => { const sql = state.storage.sql; sql.exec("INSERT INTO mail_domain (domain, slug, at) VALUES ('invented-d1.example', ?, 1)", slug); sql.exec("INSERT INTO mail_sent (message_id, slug, at) VALUES ('', ?, ?)", slug, Date.now()); sql.exec("INSERT INTO active14 (slug, at) VALUES (?, 1)", slug); sql.exec("INSERT INTO inviter_named (friend, at) VALUES (?, 1)", slug); sql.exec("INSERT INTO circle_invite_code (code, slug, ends_at) VALUES ('INVENTED-D1', ?, ?)", slug, Date.now() + 86_400_000); // They brought one friend, and were brought by no one; the friend's referral counted. sql.exec("INSERT INTO referral (friend, referrer, at, counted_at) VALUES (?, ?, 1, 2)", friend, slug); }); expect(await directory(env).friendsOf(friend)).toBe(1); const code = await open<{ challenge_id: string }>("POST", "/v1/account/delete/code", {}, bearer(credential)); expect((await open("POST", "/v1/account/delete", { challenge_id: code.body.challenge_id, code: "123456", confirm: "delete" }, bearer(credential))).status).toBe(202); expect((await http(slug, "POST", "/v1/admin/account/erase-now", {}, ADMIN)).status).toBe(200); await alarmsUntil(slug); const named = await runInDurableObject(theDirectory(), (_i, state) => { const sql = state.storage.sql; const n = (q: string) => sql.exec<{ n: number }>(q, slug).one().n; return { database: n("SELECT count(*) AS n FROM database WHERE slug = ?"), mailDomain: n("SELECT count(*) AS n FROM mail_domain WHERE slug = ?"), mailSent: n("SELECT count(*) AS n FROM mail_sent WHERE slug = ?"), active: n("SELECT count(*) AS n FROM active14 WHERE slug = ?"), inviter: n("SELECT count(*) AS n FROM inviter_named WHERE friend = ?"), referral: n("SELECT count(*) AS n FROM referral WHERE friend = ?1 OR referrer = ?1"), waiting: n("SELECT count(*) AS n FROM waiting WHERE slug = ?"), routes: n("SELECT count(*) AS n FROM approval_route WHERE slug = ?"), invites: n("SELECT count(*) AS n FROM circle_invite_code WHERE slug = ?"), }; }); expect(named).toEqual({ database: 0, mailDomain: 0, mailSent: 0, active: 0, inviter: 0, referral: 0, waiting: 0, routes: 0, invites: 0 }); // Mail to their domain is no longer theirs to route. expect(await directory(env).mailDomainOf("invented-d1.example")).toBeNull(); // The friend keeps the month it earned them. expect(await directory(env).friendsOf(friend)).toBe(1); }); it("ninety days after the erase the database id is let go: a receipt with a random id stays, and a credential is one for no account", async () => { const { credential, slug, databaseId } = await setAndDue("+919000005108", "phone-d1-8"); await alarmsUntil(slug); const receipt = (await receiptOf(databaseId))!; // Before the ninety days: still said to be deleted, and the alarm waits for the day. expect((await open<{ code: string }>("GET", "/v1/me", undefined, bearer(credential))).body.code).toBe("account_deleted"); const alarm = await runInDurableObject(object(slug), (_i, state) => state.storage.getAlarm()); expect(alarm).toBeGreaterThan(Date.now() + FORGET_AFTER_MS - 600_000); // Ninety days pass. await runInDurableObject(object(slug), (_i, state) => { const j = job(state.storage.sql)!; const past = new Date(Date.now() - FORGET_AFTER_MS - 60_000).toISOString(); state.storage.sql.exec(`UPDATE ${TABLE} SET receipt = ?, finished_at = ?`, JSON.stringify({ ...j.receipt, finished_at: past }), past); }); await runDurableObjectAlarm(object(slug)); expect(await phaseOf(slug)).toBe("forgotten"); // The object keeps one row naming nothing, and still grows no table. const row = await runInDurableObject(object(slug), (_i, state) => state.storage.sql.exec(`SELECT * FROM ${TABLE}`).toArray()); expect(JSON.stringify(row)).not.toContain(databaseId); expect(JSON.stringify(row)).not.toContain(slug); expect(await tablesOf(slug)).toEqual({ [TABLE]: 1 }); // The directory: the id let go, the receipt kept under a fresh random id with the same counts and dates. expect(await directory(env).wasErased(databaseId)).toBe(false); expect(await receiptOf(databaseId)).toBeNull(); const kept = await runInDurableObject(theDirectory(), (_i, state) => state.storage.sql.exec<{ id: string; slug: string; receipt: string; finished_at: string }>("SELECT id, slug, receipt, finished_at FROM erased WHERE finished_at = ?", receipt.finished_at).toArray()); expect(kept).toHaveLength(1); expect(kept[0]!.id).toMatch(/^r-[0-9a-f-]{36}$/); expect(kept[0]!.slug).toBe(""); expect(JSON.parse(kept[0]!.receipt)).toEqual(receipt.receipt); // A credential naming it, at the door and at the object: no account, sign in again. const door = await open<{ code: string }>("GET", "/v1/me", undefined, bearer(credential)); expect([door.status, door.body.code]).toEqual([401, "invalid_credential"]); const at = await http<{ code: string }>(slug, "GET", "/v1/me", undefined, bearer(credential)); expect([at.status, at.body.code]).toEqual([401, "invalid_credential"]); // Run again: nothing more changes. await runDurableObjectAlarm(object(slug)); expect(await phaseOf(slug)).toBe("forgotten"); }); it("logs the admin's hold, set and taken away", async () => { const credential = await signUp("+919000005109", "phone-d1-9"); const slug = slugOf(credential); expect((await http(slug, "POST", "/v1/admin/account/hold", { hold: true }, ADMIN)).status).toBe(200); const off = await http<{ log: { hold: boolean; at: string }[] }>(slug, "POST", "/v1/admin/account/hold", { hold: false }, ADMIN); expect(off.status).toBe(200); expect(off.body.log.map((l) => l.hold)).toEqual([true, false]); expect(off.body.log.every((l) => !Number.isNaN(Date.parse(l.at)))).toBe(true); }); });