Cotton code
224 lines · 13.5 KB · TypeScriptRaw
/** * DELETE ACCOUNT 3 (second review of DELETE ACCOUNT 2, 27 Nov 2026): six small items. *   1. A wipe mark beside a KEPT account erases nothing: "no account" is judged by the account's meta alone. *   2. A Keep that wakes late never takes away a deletion asked since. *   3. The erase's knocks count afresh once it begins, and a cut at each await of the storage step closes, the *      waiting stage's knocks already spent. *   4. A deletion the sweep gives up on is `stuck` on its directory row, and listed for an admin. *   5. A date that does not read is never due: nothing erased, listed as stuck. *   6. The web's code while a Keep is unfinished says so in its own words; mail is refused by mailArrive itself. * 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 { job, keep, start, TABLE, type DeleteHost } from "../src/account_delete.ts";import { directory, MAX_KNOCKS, 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 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 };}/** 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 };    });  };}const knocksOf = (id: string) => runInDurableObject(theDirectory(), (_i, state) => state.storage.sql.exec<{ n: number }>("SELECT n FROM sweep_knock WHERE id = ?", id).toArray()[0]?.n ?? 0);describe("DELETE ACCOUNT 3", () => {  it("1. a wipe mark beside a kept account erases nothing", async () => {    const phone = "+919000005301";    const { slug, databaseId, records } = await setToGo(phone, "d3-1");    expect((await signInAndKeep(phone, databaseId, "d3-1b")).status).toBe(200);    // Kept: the deletion's table is still there, with no row.    expect(await runInDurableObject(object(slug), (_i, state) => state.storage.sql.exec<{ n: number }>("SELECT count(*) AS n FROM sqlite_master WHERE name = ?", TABLE).one().n)).toBe(1);    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, slug, startedAt: receipt.started_at, by: "app", receipt }));    expect((await object(slug).deleteResume()).phase).toBe("live");    await intact(phone, slug, records);    await env.PHOTOS.delete(`erasing/${id}`);  });  it("2. a Keep that wakes late never takes away a deletion asked since", async () => {    const { slug } = await setToGo("+919000005302", "d3-2");    const left = await runInDurableObject(object(slug), async (_i, state) => {      let wake: () => void = () => undefined;      const stalled = new Promise<void>((done) => (wake = done));      const base = { sql: state.storage.sql, storage: state.storage, env, now: () => new Date(), closeForGrace: async () => undefined } as unknown as DeleteHost;      // Keep A stalls inside reopen.      const a = keep({ ...base, reopen: () => stalled } as DeleteHost);      await Promise.resolve();      // Meanwhile the Keep is finished by another way in, and the person asks to delete again.      await keep({ ...base, reopen: async () => undefined } as DeleteHost);      await start({ ...base, reopen: async () => undefined } as DeleteHost, "app", { databaseId: "invented-d3-2", slug: "p-invented-d3-2", ownerPhone: null });      wake();      await a;      return job(state.storage.sql)?.phase ?? null;    });    expect(left).toBe("pending");  });  for (const cut of ["mark", "storage", "closed"] as const) {    it(`3. cut after ${cut} in the storage step, the waiting stage's knocks spent: the erase still closes`, async () => {      const phone = `+91900000531${["mark", "storage", "closed"].indexOf(cut)}`;      const { slug, databaseId } = await setToGo(phone, `d3-3-${cut}`);      await runInDurableObject(theDirectory(), (_i, state) => {        state.storage.sql.exec("CREATE TABLE IF NOT EXISTS sweep_knock (id TEXT PRIMARY KEY, n INTEGER NOT NULL, at INTEGER NOT NULL)");        state.storage.sql.exec("INSERT OR REPLACE INTO sweep_knock (id, n, at) VALUES (?, ?, 1)", databaseId, MAX_KNOCKS);      });      expect((await http(slug, "POST", "/v1/admin/account/erase-now", { kill_after: cut }, ADMIN)).status).toBe(200);      // The erase runs (its alarm fires by itself too) until it is cut off, past the directory step.      for (let n = 0; n < 40; n++) {        let ran = false;        try {          ran = await runDurableObjectAlarm(object(slug));        } catch {          /* cut off, as asked */        }        const p = await phaseOf(slug).catch(() => "cut");        if (p === "done" || p === null || p === "closing") break;        if (!ran) await new Promise((done) => setTimeout(done, 250));      }      // The erase began: its own knocks count afresh, whatever the waiting stage spent.      expect(await knocksOf(databaseId)).toBeLessThan(MAX_KNOCKS);      if ((await phaseOf(slug).catch(() => null)) !== "done") {        await directory(env).sweep(Date.now() + 2 * SWEEP_LATE_MS);        for (let n = 0; n < 30 && (await phaseOf(slug).catch(() => null)) !== "done"; n++) await runDurableObjectAlarm(object(slug)).catch(() => false);      }      expect(await phaseOf(slug)).toBe("done");      expect(await env.MEDIA.head(`${slug}/photos/kept.jpg`)).toBeNull();      expect(await env.PHOTOS.head(`erasing/${env.BUSINESS.idFromName(slug).toString()}`)).toBeNull();      expect(await directory(env).lookup(phone)).toBeNull();    });  }  it("4. a deletion the sweep leaves to an admin is stuck on its directory row and listed", async () => {    const credential = await signUp("+919000005304", "d3-4");    const slug = slugOf(credential);    const ghost = crypto.randomUUID();    await runInDurableObject(theDirectory(), (_i, state) => {      // Held as erased, but its object (a live one) holds no deletion: the sweep can do nothing for it.      state.storage.sql.exec("INSERT OR REPLACE INTO erased (id, slug, started_at) VALUES (?, ?, '2026-10-01T00:00:00.000Z')", ghost, slug);      state.storage.sql.exec("INSERT OR REPLACE INTO deleting (id, asked_at, erase_at, state, changed_at) VALUES (?, '2026-09-01T00:00:00.000Z', '2026-10-01T00:00:00.000Z', 'erased', '2026-10-01T00:00:00.000Z')", ghost);    });    await directory(env).sweep(Date.now() + 3 * SWEEP_LATE_MS);    expect((await directoryRow(ghost))?.state).toBe("stuck");    const check = await open<{ stuck: string[] }>("GET", "/v1/admin/deletions/check", undefined, ADMIN);    expect(check.body.stuck).toContain(ghost);    const counts = await open<{ stuck: number }>("GET", "/v1/admin/deletions", undefined, ADMIN);    expect(counts.body.stuck).toBeGreaterThanOrEqual(1);    expect(await rowsOf(slug)).toBeGreaterThanOrEqual(0);    await runInDurableObject(theDirectory(), (_i, state) => state.storage.sql.exec("DELETE FROM erased WHERE id = ?", ghost));  });  it("5. a date that does not read is never due: nothing erased, the directory lists it as stuck", async () => {    const phone = "+919000005305";    const { slug, databaseId, records } = await setToGo(phone, "d3-5");    await runInDurableObject(object(slug), (_i, state) => state.storage.sql.exec(`UPDATE ${TABLE} SET erase_at = 'not a date'`));    await runInDurableObject(theDirectory(), (_i, state) => state.storage.sql.exec("UPDATE deleting SET erase_at = '2000-01-01T00:00:00.000Z' WHERE id = ?", databaseId));    await runDurableObjectAlarm(object(slug));    expect(await phaseOf(slug)).toBe("pending");    expect(await rowsOf(slug)).toBe(records);    await directory(env).sweep(Date.now() + 2 * SWEEP_LATE_MS);    await runDurableObjectAlarm(object(slug)).catch(() => false);    expect(await phaseOf(slug)).toBe("pending");    expect(await rowsOf(slug)).toBe(records);    expect((await directoryRow(databaseId))?.state).toBe("stuck");  });  it("6. the web's code while a Keep is unfinished says it is being kept; mailArrive refuses an account set to be deleted", async () => {    const phone = "+919000005306";    const { slug, databaseId } = await setToGo(phone, "d3-6");    const mail = await object(slug)      .mailArrive({ raw: new TextEncoder().encode("From: a@example.com\r\nTo: b@example.com\r\nSubject: invented\r\n\r\nhello"), to: "b@example.com", forwarded: "none", received: Date.now() })      .then(() => "taken")      .catch((error: unknown) => String(error));    expect(mail).toMatch(/account_deleted|cannot be reached/);    const heal = await photosRefuseDeletes(slug);    expect((await signInAndKeep(phone, databaseId, "d3-6b")).status).toBeGreaterThanOrEqual(500);    expect(await phaseOf(slug)).toBe("keeping");    const code = await object(slug).deleteCode(phone, "browser-d3-6");    expect(code).toMatchObject({ refused: { status: 503, code: "keeping" } });    await heal();    const again = await object(slug).deleteCode(phone, "browser-d3-6");    expect("challenge_id" in again).toBe(true);    expect(await phaseOf(slug)).toBeNull();  });});