/** * Deleting an account (src/account_delete.ts): only the person, with a * fresh code to their number; everything of theirs goes, step by step on the * object's alarm; a dated receipt with counts alone is left. */ import { env, runDurableObjectAlarm, runInDurableObject, SELF } from "cloudflare:test"; import { afterEach, describe, expect, it, vi } from "vitest"; import { GRACE_MS, job, keep, mayEraseNow, TABLE, type DeleteHost } from "../src/account_delete.ts"; import { directory } from "../src/directory.ts"; import { FEEDBACK_SLUG } from "../src/feedback.ts"; import { bearer, open, OPEN, signUp } from "./calling.ts"; import { sealRow } from "./seal-device.ts"; import { connectAccount, google, primary, quiet, revoked, tokens } from "./google.ts"; import { ADMIN, http, personalObject } from "./personal.ts"; // Each case signs up, fills, deletes and drives the alarms through every step: minutes on a loaded box. vi.setConfig({ testTimeout: 600_000 }); type Body = Record; const developerTools = import.meta.glob("../../../crates/cotton-core/kits/developer/tools/app_reports/manifest.json", { eager: true, import: "default" }) as Record; const developerTables = import.meta.glob("../../../crates/cotton-core/kits/developer/tables/app_report.json", { eager: true, import: "default" }) as Record; afterEach(() => { vi.restoreAllMocks(); }); let ips = 0; const network = (): Record => ({ "cf-connecting-ip": `192.0.2.${(ips += 1) % 250}` }); 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)); /** * The deletion run to its end. The object's own alarm fires by itself in the * test runtime too, so this runs a pending one and otherwise waits, until the * object's row says done. */ async function alarmsUntilDone(slug: string, most = 120): Promise { await thirtyDaysPass(slug); for (let n = 0; n < most; n++) { const phase = await runInDurableObject(object(slug), (_i, state) => job(state.storage.sql)?.phase ?? null); if (phase === "done") return; if (!(await runDurableObjectAlarm(object(slug)))) await new Promise((done) => setTimeout(done, 250)); } throw new Error("the deletion never finished"); } /** The thirty days to change one's mind run out: the date moved into the past, as the clock would. */ async function thirtyDaysPass(slug: string): Promise { 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'`); }); } /** Every table the object's storage holds, with its row count. */ 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])); }); } async function keys(bucket: R2Bucket, prefix: string): Promise { return (await bucket.list({ prefix })).objects.map((o) => o.key); } /** A few records, files in both buckets and a chat profile picture: what a person's account holds. */ async function fill(credential: string, slug: string): Promise { for (let i = 0; i < 5; i++) { const id = crypto.randomUUID(); const data = { ...(await sealRow(new Uint8Array(32).fill(9), "todo", id, 1, { title: `Invented to-do ${i}` })), status: "open" }; const made = await open("POST", "/v1/act", { act: "create", args: { table: "todo", id, data } }, bearer(credential)); expect(made.status, JSON.stringify(made.body)).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)); } async function askCode(credential: string): Promise { const code = await open<{ challenge_id: string }>("POST", "/v1/account/delete/code", {}, bearer(credential)); expect(code.status, JSON.stringify(code.body)).toBe(200); return code.body.challenge_id; } describe("deleting an account from the app", () => { it("takes a fresh code to the number, then everything goes and a receipt of counts stays", async () => { const phone = "+919000004401"; const credential = await signUp(phone, "phone-del-1"); const slug = slugOf(credential); const databaseId = databaseOf(credential); await fill(credential, slug); // SNAPSHOTS 1: REAL copies (a weekly full and the daily after it), outside its folder, their key in the directory. expect((await http(slug, "POST", "/v1/admin/snapshots", { on: true }, ADMIN)).status).toBe(200); for (const kind of ["full", "daily"]) { for (let n = 0; n < 10; n++) if ((await http<{ done?: boolean }>(slug, "POST", "/v1/admin/snapshots/run", n === 0 ? { kind } : {}, ADMIN)).body.done) break; } const copies = [...(await env.MEDIA.list({ prefix: `_snapshots/weekly/${slug}/` })).objects, ...(await env.MEDIA.list({ prefix: `_snapshots/daily/${slug}/` })).objects]; expect(copies.filter((o) => o.key.endsWith("manifest.json")).length, "two copies written").toBe(2); const copyBytes = copies.reduce((a, o) => a + o.size, 0); expect(await directory(env).snapshotKeyKept(slug)).toBe(true); // Another person's files sit beside: none of them goes. await env.MEDIA.put(`p-someone-else/photos/x.jpg`, new Uint8Array(10)); const challenge = await askCode(credential); const unconfirmed = await open("POST", "/v1/account/delete", { challenge_id: challenge, code: "123456" }, bearer(credential)); expect(unconfirmed.status).toBe(400); const wrong = await open("POST", "/v1/account/delete", { challenge_id: challenge, code: "000000", confirm: "delete" }, bearer(credential)); expect(wrong.status).toBe(401); const done = await open<{ deleting: boolean; started_at: string }>("POST", "/v1/account/delete", { challenge_id: challenge, code: "123456", confirm: "delete" }, bearer(credential)); expect(done.status, JSON.stringify(done.body)).toBe(202); expect(done.body.deleting).toBe(true); // From the tap on, the object answers nothing but that the account was deleted. const sync = await open<{ code: string }>("GET", "/v1/sync?since=0", undefined, bearer(credential)); expect(sync.status).toBe(410); expect(sync.body.code).toBe("account_deleted"); await alarmsUntilDone(slug); // The object's storage: the receipt's one row, and nothing else. expect(await tablesOf(slug)).toEqual({ [TABLE]: 1 }); const receipt = await runInDurableObject(object(slug), (_i, state) => job(state.storage.sql)); expect(receipt?.phase).toBe("done"); expect(receipt?.ownerPhone).toBeNull(); // The person's three files; the copies (and the ledger) are erased but are not the person's files. expect(receipt?.receipt).toMatchObject({ by: "app", files: 3, bytes: 3300, google: { held: 0, revoked: 0 } }); expect(copies.length && copyBytes).toBeGreaterThan(0); expect(receipt?.receipt.records).toBeGreaterThanOrEqual(5); expect(receipt?.receipt.left).toEqual({ tables: 0, keys: 0 }); // The object's own door says where the deletion stands, and nothing of the receipt's counts. const told = await runInDurableObject(object(slug), async (instance) => (await instance.fetch(new Request("https://x/v1/me"))).json() as Promise<{ deleting: Record }>); expect(told.deleting).toMatchObject({ phase: "done", left: { tables: 0, keys: 0 } }); expect(told.deleting.finished_at).toBeTruthy(); expect(JSON.stringify(told)).not.toContain("records"); expect(JSON.stringify(receipt)).not.toContain(phone); expect(JSON.stringify(receipt)).not.toContain("Invented to-do"); // The buckets: nothing under the person's folder; the other person's stays. expect(await keys(env.MEDIA, `${slug}/`)).toEqual([]); expect(await keys(env.PHOTOS, `${slug}/`)).toEqual([]); expect(await keys(env.MEDIA, `_snapshots/weekly/${slug}/`)).toEqual([]); expect(await keys(env.MEDIA, `_snapshots/daily/${slug}/`)).toEqual([]); expect(await directory(env).snapshotKeyKept(slug), "the snapshots' key is gone: any copy left anywhere no longer reads").toBe(false); expect(await keys(env.MEDIA, "p-someone-else/")).toEqual(["p-someone-else/photos/x.jpg"]); // The directory: the number is no one's, the database id is kept as erased with its receipt. expect(await directory(env).lookup(phone)).toBeNull(); expect(await directory(env).find(databaseId)).toBeNull(); expect(await directory(env).wasErased(databaseId)).toBe(true); const kept = (await directory(env).receipt(databaseId)) as { finished_at: string | null } | null; expect(kept?.finished_at).toBeTruthy(); expect(JSON.stringify(kept)).not.toContain(phone); // A phone's credential is told at the door, and the number signs up again, empty. const after = await open<{ code: string }>("GET", "/v1/me", undefined, bearer(credential)); expect(after.status).toBe(410); expect(after.body.code).toBe("account_deleted"); const again = await signUp(phone, "phone-del-1"); expect(databaseOf(again)).not.toBe(databaseId); const fresh = await open<{ rows: Body[] }>("GET", "/v1/sync?since=0", undefined, bearer(again)); expect(fresh.status).toBe(200); expect(JSON.stringify(fresh.body)).not.toContain("Invented to-do"); // Asked again, the deleted object grows nothing back. expect((await open("POST", "/v1/act", { act: "create", args: { table: "todo", data: { title: "x" } } }, bearer(credential))).status).toBe(410); expect(await tablesOf(slug)).toEqual({ [TABLE]: 1 }); }); it("refuses a sign-in's code, a token, the admin and a device not signed in", async () => { const phone = "+919000004402"; const credential = await signUp(phone, "phone-del-2"); const slug = slugOf(credential); // A code asked for signing in, on the same device, does not delete. const signInCode = await open<{ challenge_id: string }>("POST", "/v1/code", { phone, device_id: "phone-del-2" }, network()); const bySignIn = await open("POST", "/v1/account/delete", { challenge_id: signInCode.body.challenge_id, code: "123456", confirm: "delete" }, bearer(credential)); expect(bySignIn.status).toBe(401); const token = await mintOpen(credential); expect((await open("POST", "/v1/account/delete/code", {}, bearer(token))).status).toBe(403); expect((await http(slug, "POST", "/v1/account/delete/code", {}, ADMIN)).status).toBe(403); expect((await open("POST", "/v1/account/delete/code", {}, {})).status).toBe(401); // A deletion's code from one device does not delete from another. const challenge = await askCode(credential); const other = await signUp(phone, "phone-del-2b"); expect((await open("POST", "/v1/account/delete", { challenge_id: challenge, code: "123456", confirm: "delete" }, bearer(other))).status).toBe(401); // Nothing was deleted. expect((await open("GET", "/v1/me", undefined, bearer(credential))).status).toBe(200); }); it("carries on where it stopped: a step cut short is done at the next alarm", async () => { const credential = await signUp("+919000004403", "phone-del-3"); const slug = slugOf(credential); await fill(credential, slug); const challenge = await askCode(credential); expect((await open("POST", "/v1/account/delete", { challenge_id: challenge, code: "123456", confirm: "delete" }, bearer(credential))).status).toBe(202); // The object is cut off after the first steps, its place kept in its row. await runInDurableObject(object(slug), (_i, state) => { state.storage.sql.exec(`UPDATE ${TABLE} SET phase = 'files' WHERE id = 1`); }); await alarmsUntilDone(slug); expect(await tablesOf(slug)).toEqual({ [TABLE]: 1 }); expect(await keys(env.MEDIA, `${slug}/`)).toEqual([]); }); it("forgets the reports the number sent, with their pictures, and keeps everyone else's", async () => { await makeCotton(); const phone = "+919000004404"; const credential = await signUp(phone, "phone-del-4"); const slug = slugOf(credential); const png = btoa(String.fromCharCode(0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a, 4, 4, 0, 4)); const mine = await open("POST", "/v1/feedback", { id: crypto.randomUUID(), sentence: "Days froze on Sometime", app: "days", screenshot: { type: "image/png", base64: png } }, { ...bearer(credential), ...network() }); expect(mine.status, JSON.stringify(mine.body)).toBe(201); const anonymous = await open("POST", "/v1/feedback", { id: crypto.randomUUID(), sentence: "Someone else's report", app: "notes" }, network()); expect(anonymous.status).toBe(201); const challenge = await askCode(credential); expect((await open("POST", "/v1/account/delete", { challenge_id: challenge, code: "123456", confirm: "delete" }, bearer(credential))).status).toBe(202); await alarmsUntilDone(slug); const left = await open<{ rows: { table: string; data: Body }[] }>("GET", `/b/${FEEDBACK_SLUG}/v1/admin/export`, undefined, bearer("test-admin-token")); const reports = left.body.rows.filter((r) => r.table === "app_report").map((r) => r.data); expect(reports.map((r) => r.sentence)).toEqual(["Someone else's report"]); expect(await keys(env.PHOTOS, `${FEEDBACK_SLUG}/feedback/`)).toEqual([]); const receipt = await runInDurableObject(object(slug), (_i, state) => job(state.storage.sql)); expect(receipt?.receipt.reports).toBe(1); }); }); describe("deleting an account without the app", () => { it("sends a code to a number on Cotton and deletes on the code typed back", async () => { const phone = "+919000004405"; const credential = await signUp(phone, "phone-del-5"); const slug = slugOf(credential); const browser = { browser_id: "browser-0123456789abcdef" }; const code = await open<{ challenge_id: string }>("POST", "/v1/account/delete/web/code", { phone, ...browser }, network()); expect(code.status, JSON.stringify(code.body)).toBe(200); const confirmed = await open("POST", "/v1/account/delete/web", { phone, challenge_id: code.body.challenge_id, code: "123456", confirm: "delete", ...browser }, network()); expect(confirmed.status, JSON.stringify(confirmed.body)).toBe(202); await alarmsUntilDone(slug); expect(await tablesOf(slug)).toEqual({ [TABLE]: 1 }); const receipt = await runInDurableObject(object(slug), (_i, state) => job(state.storage.sql)); expect(receipt?.receipt.by).toBe("web"); expect((await open("GET", "/v1/me", undefined, bearer(credential))).status).toBe(410); }); it("answers a number with no account as one sent a code, makes nothing, and never proves", async () => { const phone = "+919000004406"; const browser = { browser_id: "browser-fedcba9876543210" }; const code = await open<{ challenge_id: string; expires_in: number }>("POST", "/v1/account/delete/web/code", { phone, ...browser }, network()); expect(code.status).toBe(200); expect(code.body.expires_in).toBe(300); expect(await directory(env).lookup(phone)).toBeNull(); const confirmed = await open("POST", "/v1/account/delete/web", { phone, challenge_id: code.body.challenge_id, code: "123456", confirm: "delete", ...browser }, network()); expect(confirmed.status).toBe(401); }); it("limits codes alike for a number on Cotton and one nobody holds (ROUTES-AUDIT 6)", async () => { const real = "+919000004418"; await signUp(real, "phone-del-18"); const nobody = "+919000004419"; const ask = (phone: string) => open<{ code?: string }>("POST", "/v1/account/delete/web/code", { phone, browser_id: "browser-0123456789abcdef" }, network()); const shape = (r: { status: number; body: Record }) => [r.status, Object.keys(r.body).sort().join(","), r.body.code ?? null]; for (let i = 0; i < 5; i++) expect(shape(await ask(real))).toEqual(shape(await ask(nobody))); const [sixthReal, sixthNobody] = [await ask(real), await ask(nobody)]; expect(shape(sixthReal)).toEqual([429, "code,message", "too_many_codes"]); expect(sixthNobody).toEqual(sixthReal); }); it("does not take a code asked from another browser, or one asked for signing in", async () => { const phone = "+919000004407"; const credential = await signUp(phone, "phone-del-7"); const code = await open<{ challenge_id: string }>("POST", "/v1/account/delete/web/code", { phone, browser_id: "browser-aaaaaaaaaaaaaaaa" }, network()); expect((await open("POST", "/v1/account/delete/web", { phone, challenge_id: code.body.challenge_id, code: "123456", confirm: "delete", browser_id: "browser-bbbbbbbbbbbbbbbb" }, network())).status).toBe(401); const signIn = await open<{ challenge_id: string }>("POST", "/v1/code", { phone, device_id: "browser-cccccccccccccccc" }, network()); expect((await open("POST", "/v1/account/delete/web", { phone, challenge_id: signIn.body.challenge_id, code: "123456", confirm: "delete", browser_id: "browser-cccccccccccccccc" }, network())).status).toBe(401); expect((await open("GET", "/v1/me", undefined, bearer(credential))).status).toBe(200); }); }); describe("the page cottondb.com/delete", () => { /** The page's form posted as a browser posts it. */ async function post(fields: Record): Promise<{ status: number; html: string }> { const res = await SELF.fetch(`${OPEN}/delete`, { method: "POST", headers: { "content-type": "application/x-www-form-urlencoded", ...network() }, body: new URLSearchParams(fields).toString() }); return { status: res.status, html: await res.text() }; } const hiddenOf = (html: string, name: string): string => new RegExp(`name="${name}" value="([^"]*)"`).exec(html)?.[1] ?? ""; it("works with no app and no script: the number, the code, the warning, then deleted", async () => { const phone = "+919000004409"; const credential = await signUp(phone, "phone-del-9"); const slug = slugOf(credential); const first = await SELF.fetch(`${OPEN}/delete`); const page = await first.text(); expect(first.status).toBe(200); expect(first.headers.get("content-security-policy")).toContain("default-src 'none'"); expect(page).toContain("30 days after you ask"); expect(page).not.toContain(" { const phone = "+919000004410"; const asked = await post({ step: "phone", phone }); expect(asked.status).toBe(200); expect(asked.html).toContain('name="code"'); expect(await directory(env).lookup(phone)).toBeNull(); }); }); describe("a Google grant", () => { it("is revoked at Google before the storage goes", async () => { const slug = "delete-google"; const { credential, owner } = await personalObject(slug); const calls = google(tokens, primary, revoked, quiet); await connectAccount(slug, owner); const code = await http<{ challenge_id: string }>(slug, "POST", "/v1/account/delete/code", {}, bearer(credential)); expect(code.status, JSON.stringify(code.body)).toBe(200); const done = await http(slug, "POST", "/v1/account/delete", { challenge_id: code.body.challenge_id, code: "123456", confirm: "delete" }, bearer(credential)); expect(done.status, JSON.stringify(done.body)).toBe(202); await alarmsUntilDone(slug); expect(calls.some((c) => c.url.href === "https://oauth2.googleapis.com/revoke")).toBe(true); const receipt = await runInDurableObject(object(slug), (_i, state) => job(state.storage.sql)); expect(receipt?.receipt.google).toEqual({ held: 1, revoked: 1 }); expect(await tablesOf(slug)).toEqual({ [TABLE]: 1 }); }); }); async function mintOpen(credential: string): Promise { const minted = await open<{ token?: string }>("POST", "/v1/act", { act: "mint_token", args: { name: "an assistant", scopes: ["owner"] } }, bearer(credential)); expect(minted.status, JSON.stringify(minted.body)).toBe(200); return minted.body.token!; } async function makeCotton(): Promise { const admin = bearer("test-admin-token"); const made = await open("PUT", `/b/${FEEDBACK_SLUG}/v1/admin/business`, { name: "Cotton", kind: "business", currency: "INR", timezone: "Asia/Kolkata" }, admin); expect(made.status, JSON.stringify(made.body)).toBe(200); const defs = await open("PUT", `/b/${FEEDBACK_SLUG}/v1/admin/definitions`, { tools: Object.values(developerTools), tables: Object.values(developerTables), flavour: { flavour: FEEDBACK_SLUG, name: "Cotton", public_views: {}, fan: null } }, admin); expect(defs.status, JSON.stringify(defs.body)).toBe(200); } describe("thirty days to change one's mind", () => { /** A signed-up owner with a few records and files, set to be deleted from the app; its date. */ async function setToGo(phone: string, device: string): Promise<{ credential: string; slug: string; databaseId: string; eraseAt: string; startedAt: string; records: number }> { const credential = await signUp(phone, device); const slug = slugOf(credential); await fill(credential, slug); const records = await runInDurableObject(object(slug), (_i, state) => state.storage.sql.exec<{ n: number }>("SELECT count(*) AS n FROM rows WHERE deleted = 0").one().n); const challenge = await askCode(credential); const asked = await open<{ erase_at: string; started_at: string }>("POST", "/v1/account/delete", { challenge_id: challenge, code: "123456", confirm: "delete" }, bearer(credential)); expect(asked.status, JSON.stringify(asked.body)).toBe(202); return { credential, slug, databaseId: databaseOf(credential), eraseAt: asked.body.erase_at, startedAt: asked.body.started_at, records }; } it("erases nothing at the tap: every sign-in ends, everything is refused with the date, the number stays on the account", async () => { const phone = "+919000004501"; const { credential, slug, databaseId, eraseAt, startedAt, records } = await setToGo(phone, "phone-grace-1"); expect(Date.parse(eraseAt) - Date.parse(startedAt)).toBe(GRACE_MS); expect(Math.abs(Date.parse(startedAt) - Date.now())).toBeLessThan(600_000); // Everything is refused, the date said, to the phone that asked and to any other. const sync = await open<{ code: string; message: string; deleting: { phase: string; erase_at: string } }>("GET", "/v1/sync?since=0", undefined, bearer(credential)); expect(sync.status).toBe(410); expect(sync.body.code).toBe("account_deleted"); expect(sync.body.message).toContain(eraseAt.slice(0, 10)); expect(sync.body.deleting).toMatchObject({ phase: "pending", erase_at: eraseAt }); // Every sign-in was ended. const sessions = await runInDurableObject(object(slug), (_i, state) => state.storage.sql.exec<{ n: number }>("SELECT count(*) AS n FROM sessions WHERE revoked = 0").one().n); expect(sessions).toBe(0); // Nothing erased: the rows, the files and the number's place in the directory are all as they were. const now = await runInDurableObject(object(slug), (_i, state) => state.storage.sql.exec<{ n: number }>("SELECT count(*) AS n FROM rows WHERE deleted = 0").one().n); expect(now).toBe(records); expect((await keys(env.MEDIA, `${slug}/`)).length).toBe(2); expect(await keys(env.PHOTOS, `${slug}/`)).toEqual([`${slug}/.deleting`, `${slug}/c.png`]); // The never-again ledger's chunk saying the account was set to be deleted: outside the publicly served `/` (src/never_again.ts). expect((await keys(env.PHOTOS, `_restore/${slug}/never-again/`)).length).toBeGreaterThan(0); // The account's public photo link answers as gone meanwhile. expect((await SELF.fetch(`https://x/b/${slug}/v1/photos/${slug}/c.png`)).status).toBe(404); expect(await directory(env).lookup(phone)).toBe(slug); expect(await directory(env).wasErased(databaseId)).toBe(false); // The alarm waits for the date and does nothing else. expect(await runDurableObjectAlarm(object(slug))).toBe(true); expect((await runInDurableObject(object(slug), (_i, state) => job(state.storage.sql)))?.phase).toBe("pending"); expect(await runInDurableObject(object(slug), (_i, state) => state.storage.getAlarm())).toBeGreaterThan(Date.now() + GRACE_MS - 120_000); const counts = await open<{ now_pending: number; days: { set: number }[] }>("GET", "/v1/admin/deletions", undefined, bearer("test-admin-token")); expect(counts.status).toBe(200); expect(counts.body.now_pending).toBeGreaterThanOrEqual(1); expect(JSON.stringify(counts.body)).not.toContain(databaseId); }); it("keeps an account the admin holds on its date (the store reviewer's, the owner's), and erases it once the hold is taken away", async () => { const phone = "+919000004591"; const { slug, databaseId, records } = await setToGo(phone, "phone-hold-1"); const admin = bearer("test-admin-token"); // Only the admin holds; in the thirty days too. expect((await http(slug, "POST", "/v1/admin/account/hold", { hold: true }, { authorization: "Bearer not-the-admin" })).status).toBe(403); const held = await http<{ hold: boolean; deleting: { erase_at: string } | null }>(slug, "POST", "/v1/admin/account/hold", { hold: true }, admin); expect(held.status, JSON.stringify(held.body)).toBe(200); expect(held.body.deleting).not.toBeNull(); // The date comes: kept, nothing erased, the number still this account. await thirtyDaysPass(slug); await runDurableObjectAlarm(object(slug)); expect(await runInDurableObject(object(slug), (_i, state) => job(state.storage.sql))).toBeNull(); expect(await runInDurableObject(object(slug), (_i, state) => state.storage.sql.exec<{ n: number }>("SELECT count(*) AS n FROM rows WHERE deleted = 0").one().n)).toBe(records); expect((await keys(env.MEDIA, `${slug}/`)).length).toBe(2); expect(await directory(env).lookup(phone)).toBe(slug); expect(await directory(env).wasErased(databaseId)).toBe(false); // The hold taken away, the next deletion's date erases as anyone's. expect((await http(slug, "POST", "/v1/admin/account/hold", { hold: false }, admin)).status).toBe(200); const again = await signUp(phone, "phone-hold-2"); const challenge = await askCode(again); expect((await open("POST", "/v1/account/delete", { challenge_id: challenge, code: "123456", confirm: "delete" }, bearer(again))).status).toBe(202); await alarmsUntilDone(slug); expect(await directory(env).wasErased(databaseId)).toBe(true); }); it("is brought to its date by the admin on the dev Worker only, to walk the erase", async () => { expect(mayEraseNow({ ENV_LABEL: "dev" })).toBe(true); expect(mayEraseNow({ ENV_LABEL: "test" })).toBe(true); expect(mayEraseNow({})).toBe(false); expect(mayEraseNow({ ENV_LABEL: "live" })).toBe(false); const phone = "+919000004592"; const { slug, databaseId } = await setToGo(phone, "phone-now-1"); const admin = bearer("test-admin-token"); expect((await http(slug, "POST", "/v1/admin/account/erase-now", {}, { authorization: "Bearer not-the-admin" })).status).toBe(403); const now = await http<{ erase_at: string }>(slug, "POST", "/v1/admin/account/erase-now", {}, admin); expect(now.status, JSON.stringify(now.body)).toBe(200); expect(Math.abs(Date.parse(now.body.erase_at) - Date.now())).toBeLessThan(60_000); await alarmsUntilDone(slug); expect(await directory(env).wasErased(databaseId)).toBe(true); expect(await keys(env.MEDIA, `${slug}/`)).toEqual([]); // Nothing set to be deleted: nothing to bring. const other = await signUp("+919000004593", "phone-now-2"); expect((await http(slugOf(other), "POST", "/v1/admin/account/erase-now", {}, admin)).status).toBe(409); }); it("signing in again is the same account: it says the date, and Keep brings everything back as it was", async () => { const phone = "+919000004502"; const { slug, databaseId, eraseAt, records } = await setToGo(phone, "phone-grace-2"); // A new sign-up with the number is this account, and its answer says the date. const code = await open<{ challenge_id: string; database_id: string }>("POST", "/v1/code", { phone, device_id: "phone-grace-2b" }, network()); expect(code.status, JSON.stringify(code.body)).toBe(200); expect(code.body.database_id).toBe(databaseId); const signed = await open<{ credential: string; deleting?: { erase_at: string } }>("POST", "/v1/sign-in", { database_id: databaseId, challenge_id: code.body.challenge_id, code: "123456", device_id: "phone-grace-2b" }, network()); expect(signed.status, JSON.stringify(signed.body)).toBe(200); expect(signed.body.deleting?.erase_at).toBe(eraseAt); const fresh = signed.body.credential; // That sign-in still reads nothing until Keep. expect((await open("GET", "/v1/sync?since=0", undefined, bearer(fresh))).status).toBe(410); const standing = await open<{ deleting: { erase_at: string } }>("GET", "/v1/account/deleting", undefined, bearer(fresh)); expect(standing.status).toBe(200); expect(standing.body.deleting.erase_at).toBe(eraseAt); const kept = await open<{ kept: boolean }>("POST", "/v1/account/keep", {}, bearer(fresh)); expect(kept.status, JSON.stringify(kept.body)).toBe(200); expect(kept.body.kept).toBe(true); // Everything as it was: the rows, the files, the object's work on its alarm again. const sync = await open<{ rows: Body[] }>("GET", "/v1/sync?since=0", undefined, bearer(fresh)); expect(sync.status).toBe(200); const now = await runInDurableObject(object(slug), (_i, state) => state.storage.sql.exec<{ n: number }>("SELECT count(*) AS n FROM rows WHERE deleted = 0").one().n); expect(now).toBe(records); expect((await keys(env.MEDIA, `${slug}/`)).length).toBe(2); expect(await keys(env.PHOTOS, `${slug}/`)).toEqual([`${slug}/c.png`]); expect((await SELF.fetch(`https://x/b/${slug}/v1/photos/${slug}/c.png`)).status).toBe(200); expect(await runInDurableObject(object(slug), (_i, state) => job(state.storage.sql))).toBeNull(); expect(await runInDurableObject(object(slug), (_i, state) => state.storage.getAlarm())).not.toBeNull(); const counts = await open<{ days: { kept: number }[] }>("GET", "/v1/admin/deletions", undefined, bearer("test-admin-token")); expect(counts.body.days.reduce((n, d) => n + d.kept, 0)).toBeGreaterThanOrEqual(1); }); it("keeps while another read on the object is still open (SQLite refuses DROP TABLE then, never a DELETE)", async () => { const phone = "+919000004509"; const { slug } = await setToGo(phone, "phone-grace-9"); const kept = await runInDurableObject(object(slug), async (instance, state) => { const open = state.storage.sql.exec("SELECT * FROM rows"); try { // The table drop this replaced fails exactly so here: database table is locked: SQLITE_LOCKED. state.storage.sql.exec("CREATE TABLE zz_probe (x)"); expect(() => state.storage.sql.exec("DROP TABLE zz_probe")).toThrow(/SQLITE_LOCKED/); return await keep((instance as unknown as { deleteHost(): DeleteHost }).deleteHost()); } finally { open.toArray(); state.storage.sql.exec("DROP TABLE IF EXISTS zz_probe"); } }); expect(kept).toEqual({ kept: true }); expect(await runInDurableObject(object(slug), (_i, state) => job(state.storage.sql))).toBeNull(); }); it("Leave it to be deleted ends that sign-in and the date stands; asked again on the web, the first date stands", async () => { const phone = "+919000004503"; const { databaseId, eraseAt } = await setToGo(phone, "phone-grace-3"); const code = await open<{ challenge_id: string }>("POST", "/v1/code", { phone, device_id: "phone-grace-3b" }, network()); const signed = await open<{ credential: string }>("POST", "/v1/sign-in", { database_id: databaseId, challenge_id: code.body.challenge_id, code: "123456", device_id: "phone-grace-3b" }, network()); const left = await open<{ left: boolean; erase_at: string }>("POST", "/v1/account/leave", {}, bearer(signed.body.credential)); expect(left.status).toBe(200); expect(left.body.erase_at).toBe(eraseAt); // That sign-in can no longer keep it. expect((await open("POST", "/v1/account/keep", {}, bearer(signed.body.credential))).status).toBe(401); const browser = { browser_id: "browser-grace-0123456789" }; const webCode = await open<{ challenge_id: string }>("POST", "/v1/account/delete/web/code", { phone, ...browser }, network()); expect(webCode.status).toBe(200); const again = await open<{ erase_at: string }>("POST", "/v1/account/delete/web", { phone, challenge_id: webCode.body.challenge_id, code: "123456", confirm: "delete", ...browser }, network()); expect(again.status, JSON.stringify(again.body)).toBe(202); expect(again.body.erase_at).toBe(eraseAt); }); it("refuses keeping to anything but the owner's own sign-in: no token, no admin, no stranger", async () => { const phone = "+919000004504"; const credential = await signUp(phone, "phone-grace-4"); const token = await mintOpen(credential); const challenge = await askCode(credential); expect((await open("POST", "/v1/account/delete", { challenge_id: challenge, code: "123456", confirm: "delete" }, bearer(credential))).status).toBe(202); expect([403, 410]).toContain((await open("POST", "/v1/account/keep", {}, bearer(token))).status); expect((await open("POST", `/b/${slugOf(credential)}/v1/account/keep`, {}, bearer("test-admin-token"))).status).toBe(403); expect((await open("POST", `/b/${slugOf(credential)}/v1/account/keep`, {}, {})).status).toBe(403); expect((await runInDurableObject(object(slugOf(credential)), (_i, state) => job(state.storage.sql)))?.phase).toBe("pending"); }); it("is out of reach of the person's people meanwhile: a delivery is refused and a shared list reads as gone", async () => { const { slug } = await setToGo("+919000004505", "phone-grace-5"); const stub = object(slug) as unknown as { sharedRead(from: string, id: string): Promise; sharedPut(from: string, id: string, item: string, sealed: string | null): Promise; chatAccepts(n: string): Promise; chatAskWithdrawn(from: string): Promise; helpAsked(from: string, ask: { id: string; device_key: string; code: string }): Promise }; expect(await stub.sharedRead("+919000004599", "invented-list")).toBeNull(); expect(await stub.sharedPut("+919000004599", "invented-list", "an item", null)).toBe(false); expect(await stub.chatAccepts("+919000004599")).toBe(false); // An RPC's own promise, settled here (an expect(…).rejects on it leaves the pipelined rejection unhandled). const refused = await stub.helpAsked("+919000004599", { id: "ask-1", device_key: "k", code: "c" }).then(() => null, (error: unknown) => error); expect(String(refused)).toMatch(/cannot be reached/); // A word that only tells is dropped quietly: it never stops a sender telling the rest. await stub.chatAskWithdrawn("+919000004599"); }); it("a phone away the whole month finds the account erased on its return", async () => { const { credential, slug } = await setToGo("+919000004506", "phone-grace-6"); await alarmsUntilDone(slug); const back = await open<{ code: string; message: string }>("GET", "/v1/sync?since=0", undefined, bearer(credential)); expect(back.status).toBe(410); expect(back.body.code).toBe("account_deleted"); expect(back.body.message).toBe("This account was deleted."); }); });