Cotton code
807 lines · 44.3 KB · TypeScriptRaw
/** * DELETING AN ACCOUNT (owner, 22 Nov 2026: the stores' blocker; Apple 5.1.1(v), * Play's account deletion policy). A person deletes their own account, and * nothing else can: every way in ends with a fresh code sent to the * database's own number at that moment and typed back. * *   POST /v1/account/delete/code   a signed-in device of the owner {}: *        a code to the owner's number → { challenge_id, expires_in } *   POST /v1/account/delete        the same device { challenge_id, code, *        confirm: "delete" } → 202 { deleting: true, started_at } *   Without the app (cottondb.com/delete, src/open.ts): the door finds the *   number's object in the directory, never making one, and the object's *   `deleteCode` / `deleteConfirm` do the same with the browser's own id. * * A code asked here is bound to the device as `delete:<device id>` (a * browser's as `delete:web:<id>`), so a sign-in's code never deletes and a * deletion's code never signs in. Admin tokens, MCP tokens, the assistant * and every other caller are refused: only a device credential of the * owner, or the code on the web, reaches it. * * THIRTY DAYS TO CHANGE YOUR MIND (owner, 22 Nov 2026: nobody loses everything * by a mistaken tap). The confirmed tap erases nothing. It writes the row at * `pending`, with `erase_at` thirty days on, and at once: every device's * sign-in is revoked, every open socket closed, and from then on the object * answers every request 410 `account_deleted` whose message names the date * (so each phone forgets its copy and says when), every assistant and token * included; nothing runs on its alarm but the wait (the Google pull and every * import stop; the Google grant is kept, so keeping the account resumes it, * and is revoked at Google only in the erasure). Only these still answer: * a code and a sign-in for the owner's number (`POST /v1/code`, * `/v1/sign-in`, whose answer carries `deleting: { erase_at }`), and with * that sign-in's credential `GET /v1/account/deleting`, `POST * /v1/account/keep` (the row goes, everything is as it was, the alarm runs * again) and `POST /v1/account/leave` (that sign-in ends). Asked again * meanwhile, the first date stands. The directory keeps the number on the * same database until the erasure, so signing up again is this account, and * counts the accounts set, kept and erased (src/directory.ts `deleting`). * There is no reminder text: the only sender is Twilio Verify, which sends * its own code message and nothing else. * * WHAT HAPPENS ON THE DATE. The alarm moves the row past `pending`, and from * that moment the object answers every request 410 `account_deleted`, so no * phone, token or assistant reads or writes it again. The rest runs on the * object's alarm, a step at a time, each step's place kept in that row, so * an eviction or a failure anywhere carries on at the next alarm: * *   reports    (first since DELETE ACCOUNT 2, while the number is still this account's: see below) *   directory  the number's entry goes (the number key and the database it *              owns), with its waits, discovery counts and approval routes; *              the database id is kept as erased, so a phone's credential *              is answered 410 `account_deleted` at the door and the number *              can sign up again, empty, at once *   revoke     every Google grant revoked at Google (three tries a minute *              apart; after that it goes on, and the receipt says how many *              Google did not take: the person can remove it in their *              Google Account). Spotify keeps no grant to revoke. *   reports    every Report a problem the number sent, in Cotton's own *              database, with its picture and log *   files      everything under `<slug>/` in both buckets, a thousand keys a *              list, and the person's chat pictures and profile picture *   storage    the alarm deleted, then the object's whole storage *              (`deleteAll`): every row, sealed or clear, the act log, the *              change log, secrets, devices, keys, codes, sessions *   closing    the receipt handed to the directory, and the one table left *              here says `done` * * THE RECEIPT. Counts and dates only, never a number, a name or a word of * the person's: when it started and finished, who started it (`app` or * `web`), how many records, files and bytes went, how many Google grants * were held and revoked, how many reports went. The directory keeps it by * database id (src/directory.ts `erased`); the object keeps its one row. * * WHY FILES BEFORE ROWS. The rows name files that live outside the slug (chat pictures, the profile picture) and the * uploads still open: were the rows erased first, those files could never be found again. So the files go while the * rows that name them are still there, and the rows last, in one `deleteAll`. * * NEVER STOPPING SHORT, NEVER ERASING WHAT WAS KEPT (DELETE ACCOUNT 1 and 2, 27 Nov 2026). Only this object's own * row, written by this object, can move an erase: no row, no table, or a row that cannot be read is a LIVE account. * The alarm is kept in the object's storage, so a deploy or an eviction keeps it; a step that throws comes back later * each time (BACKOFF_MS doubling, at most an hour); every request the object answers sets the alarm again if it is * missing (`ensureAlarm`). The directory's sweep only knocks (src/directory.ts `sweep`): it asks the object to check * its own job, carrying no date and no authority, at most MAX_KNOCKS times a deletion. Keep and the admin hold write * `keeping` first and delete the row last, so a Keep cut off is completed, never lost and never answered 410. The one * cut that leaves no row (between `deleteAll` and the closing row) is recognised by the object's own wipe mark, written * under its own Durable Object id by the `storage` step alone, and only beside an empty storage (`resume`). * Order: reports (while the number is still the account's), then shared spaces and the directory, Google, files, the * storage. Spaces that do not take word are asked again with the back-off, and after a day recorded in the receipt. * * NINETY DAYS ON (FORGET_AFTER_MS): the database id is let go, the receipt kept in the directory under a random id, * and every request is answered as one for no account. * * AN ERASED OBJECT. Once storage is gone the object holds only * `account_delete`; its constructor sees it and makes no other table, so * nothing a stray request does can grow the object back. */import { devWorker, type Env } from "./env.ts";import { json, refuse } from "./http.ts";import * as neverAgain from "./never_again.ts";import { hiddenPrefixes } from "./restore.ts";export const TABLE = "account_delete";export const DELETE_PATH = /^\/v1\/account\/delete(\/code)?$/;/** * THE SWITCH (coordinator, 22 Nov 2026: live is held until the thirty days to change one's mind are in and proven). * Deleting an account is answered only where the Worker's var `ACCOUNT_DELETE` is `on` (dev, and live since 25 Nov 2026); anywhere * else, OFF by default, every delete-account route and the /delete page answer a plain not-available, before any * object is reached, and the object itself refuses to start one. */export function switchedOn(env: { ACCOUNT_DELETE?: string }): boolean {  return env.ACCOUNT_DELETE === "on";}/** The page itself, which the site answers while deleting is off (src/index.ts). */export const SITE_PAGE = /^\/delete\/?$/;/** Every path that asks for or starts a deletion, on any host or `/b/<slug>` prefix. */export const ANY_DELETE_PATH = /^\/delete\/?$|(^|\/)v1\/account\/delete(\/code|\/web|\/web\/code)?\/?$/;/** The switch off: not available, said plainly, as a page for the page and as JSON for the rest. */export function notAvailable(path: string): Response {  if (/^\/delete\/?$/.test(path)) {    return new Response("<!doctype html><meta charset=utf-8><meta name=viewport content=\"width=device-width, initial-scale=1\"><title>Not available</title><p>Deleting an account is not available here yet.</p>", { status: 404, headers: { "content-type": "text/html; charset=utf-8", "cache-control": "no-store" } });  }  return json({ code: "not_available", message: "Deleting an account is not available yet." }, 404);}/** What a sign-in may still ask in the thirty days. */export const GRACE_PATH = /^\/v1\/account\/(deleting|keep|leave)$/;/** * In the thirty days the account's public links (its photos, a Loom link), which the Worker serves from R2 before * any object, answer as gone: a marker beside them says so, written at the tap, removed on Keep, and erased with * everything under the slug on the date. */export const marker = (slug: string): string => `${slug}/.deleting`;export async function marked(env: { PHOTOS: R2Bucket }, slug: string): Promise<boolean> {  return (await env.PHOTOS.head(marker(slug))) !== null;}/** * THE HOLD (coordinator, 23 Nov 2026: the store reviewer's account and the owner's must not go by a mistaken tap). * An account the admin holds (`POST /v1/admin/account/hold { hold: true }`, kept in meta) still lets its person ask, * confirm and be signed out, exactly as anyone (a store reviewer sees deletion work), but on the date it is KEPT, as * if they had signed in and kept it, and nothing is erased. Taken away (`hold: false`), the date erases as for anyone. */export const HOLD = "account_delete_hold";export function onHold(sql: SqlStorage): boolean {  return sql.exec<{ value: string }>("SELECT value FROM meta WHERE key = ?", HOLD).toArray()[0]?.value === "on";}/** A Worker where the erase may be brought to now, to walk it (dev and the tests): never live. */export function mayEraseNow(env: { ENV_LABEL?: string }): boolean {  return devWorker(env);}/** * Dev only (mayEraseNow): the thirty days ended now, so the erase runs at the next alarm, in a moment. Answers the * date it set, or a refusal when nothing is set to be deleted. */export async function eraseNow(host: DeleteHost): Promise<{ erase_at: string }> {  const j = pending(host.sql);  if (!j) refuse(409, "not_pending", "this account is not set to be deleted");  const at = host.now().toISOString();  host.sql.exec(`UPDATE ${TABLE} SET erase_at = ? WHERE id = 1`, at);  neverAgain.note(host.sql, { kind: "account_delete", started_at: j.startedAt, erase_at: at, by: j.by, at });  await host.storage.setAlarm(Date.now());  return { erase_at: at };}/** The word the confirmation must carry: the tap that deletes is deliberate. */export const CONFIRM = "delete";/** A device's deletion code is bound to it under this prefix (a browser's under `delete:web:`). */export const DEVICE_PREFIX = "delete:";export const WEB_PREFIX = "delete:web:";/** Pages of a thousand keys one alarm lists and deletes, per bucket: well inside an alarm's subrequests. */export const PAGES_PER_STEP = 20;/** Google revocation tries before the erase goes on without it. */export const REVOKE_TRIES = 3;export const RETRY_MS = 60_000;const DAY_MS = 24 * 60 * 60 * 1000;/** How long a person has to change their mind (owner, 22 Nov 2026). */export const GRACE_MS = 30 * 24 * 60 * 60 * 1000;export const SCHEMA = `CREATE TABLE IF NOT EXISTS ${TABLE} (  id INTEGER PRIMARY KEY CHECK (id = 1),  phase TEXT NOT NULL,  started_at TEXT NOT NULL,  by TEXT NOT NULL,  database_id TEXT,  slug TEXT NOT NULL,  owner_phone TEXT,  tries INTEGER NOT NULL DEFAULT 0,  receipt TEXT NOT NULL,  finished_at TEXT,  erase_at TEXT)`;/** A row written before the thirty days (an object deleted at once, 22 Nov 2026) has no `erase_at`: it gains it. */function upgrade(sql: SqlStorage): void {  const columns = sql.exec<{ name: string }>(`PRAGMA table_info(${TABLE})`).toArray().map((c) => c.name);  if (!columns.includes("erase_at")) sql.exec(`ALTER TABLE ${TABLE} ADD COLUMN erase_at TEXT`);}export type Phase = "pending" | "keeping" | "directory" | "revoke" | "reports" | "files" | "storage" | "closing" | "done" | "forgotten";/** * FORGOTTEN (DELETE ACCOUNT 1, 27 Nov 2026). Ninety days after the erase finished, the database id itself is let go: * the directory keeps the receipt under a fresh random id instead (src/directory.ts `forgetReceipt`), and this object * keeps one row that names nothing (no database id, no counts), so it still never grows tables back. From then a * credential naming the database is answered as one for no account at all (401 `invalid_credential`, sign in again), * no longer `account_deleted`. Why ninety days: every credential a phone could hold was issued at most ninety days * before the tap (src/auth.ts CREDENTIAL_TTL_SECONDS) and the erase runs thirty days after it, so by the erase plus * sixty days none is still good; ninety leaves a margin, and a phone away for months still hears, on its return, * that the account was deleted rather than only that it is signed out. */export const FORGET_AFTER_MS = 90 * 24 * 60 * 60 * 1000;/** A failed step tries again after this, doubling each time it fails again, up to MAX_BACKOFF_MS: never given up. */export const BACKOFF_MS = 60_000;export const MAX_BACKOFF_MS = 60 * 60 * 1000;export interface Receipt {  started_at: string;  finished_at: string | null;  by: "app" | "web";  records: number;  files: number;  bytes: number;  google: { held: number; revoked: number };  reports: number;  /**   * What the deletion found still there when it closed, counted then: tables in the object's storage besides   * this receipt's own, and keys under the database's prefix in MEDIA and PHOTOS. Both 0 is a deletion done.   */  left?: { tables: number; keys: number };  /** Files being sent in parts and never finished, aborted at R2 before the files went. */  uploads?: number;  /** Shared spaces that did not take word of the erase within a day (their ids, no one's name): for an admin. */  spaces_not_told?: string[];  /** When this person's people were told the account is going (the Circle's "left Cotton"). */  people_told_at?: string;  /** When a shared space first failed to take word of the erase: the day's wait counts from here. */  spaces_failing_since?: string;  /** People this one helped back in, or this one's helper, not told of the erase within a day (short hashes, no number): for an admin. */  recovery_not_told?: string[];  /** When telling a trusted person first failed: the day's wait counts from here. */  recovery_failing_since?: string;  /** The version the object had reached when its storage went: a restore of the erased account (dev only) raises past it (RESTORE 2, L3). */  last_version?: number;}export interface Job {  phase: Phase;  startedAt: string;  by: "app" | "web";  databaseId: string | null;  slug: string;  ownerPhone: string | null;  tries: number;  receipt: Receipt;  /** When the erasure runs: thirty days after the confirmed tap. */  eraseAt: string | null;}/** What the object lends the erase. */export interface DeleteHost {  sql: SqlStorage;  storage: DurableObjectStorage;  env: Env;  now: () => Date;  /** Every Google grant revoked at Google: how many were held, how many Google no longer honours. */  revokeGoogle: () => Promise<{ held: number; revoked: number }>;  /** The directory forgets the number and keeps the database id as erased. */  forgetInDirectory: (databaseId: string, slug: string) => Promise<void>;  /** Each shared space this person is in is told their database is gone (src/space/space.ts `gone`), before the number is let go: the ids of those that did not take it (none when all did). */  leaveSpaces?: () => Promise<string[]>;  /** The people this person helps back in, and their own helper, are told (src/recovery.ts `leave`): the short ids of those not told (none when all were). */  leaveRecovery?: () => Promise<string[]>;  /** Each of this person's people is told their account is going (the Circle's "left Cotton"), best effort: how many were. */  tellPeople?: () => Promise<number>;  /** Cotton's own database forgets the reports this number sent; how many went. */  forgetReports: (phone: string) => Promise<number>;  /** The directory keeps the finished receipt. */  closeInDirectory: (databaseId: string, receipt: Receipt) => Promise<void>;  /** At the confirmed tap: every sign-in revoked, every socket closed, the directory told the date. */  closeForGrace: (eraseAt: string) => Promise<void>;  /** The person kept the account: the directory told, the object's own alarm running again. */  reopen: () => Promise<void>;  /** Every file still being sent in parts (the person's own uploads, and copies to people they sent to), aborted at R2: how many. */  abortUploads?: () => Promise<number>;  /** Waits out a copy of the never-again ledger in flight (RESTORE 2 SERVER 5): none lands after this step empties `_restore/<slug>/`. */  ledgerQuiet?: () => Promise<void>;  /** Ninety days on: the directory keeps the receipt under a fresh random id, and the database id is let go. */  forgetReceipt?: (databaseId: string) => Promise<void>;  /** The object's own mark that it began wiping its storage (R2, under its own Durable Object id): see the `storage` step. */  erasing?: { put: (mark: ErasingMark) => Promise<void>; get: () => Promise<ErasingMark | null>; clear: () => Promise<void> };  /** Whether the object's storage still holds an account (its meta names a database). */  holdsAccount?: () => boolean;  /** Dev and the tests only: the object is cut off here, as an eviction mid-step would (src/business.ts `erase-now`). */  killPoint?: (at: KillPoint) => void;}/** Where a dev erase may be cut off once (`erase-now { kill_after }`): after a page of files, after the wipe mark, after `deleteAll`, after the closing row. */export type KillPoint = "files" | "mark" | "storage" | "closed";export const KILL_POINTS: readonly KillPoint[] = ["files", "mark", "storage", "closed"];/** What the object writes of itself just before its storage goes. */export interface ErasingMark {  databaseId: string | null;  slug: string;  startedAt: string;  by: "app" | "web";  receipt: Receipt;}/** The closing row, alone in the storage: no number, no name. */function writeClosing(sql: SqlStorage, m: ErasingMark): void {  sql.exec(SCHEMA);  sql.exec(`INSERT OR REPLACE INTO ${TABLE} (id, phase, started_at, by, database_id, slug, owner_phone, receipt) VALUES (1, 'closing', ?, ?, ?, ?, NULL, ?)`, m.startedAt, m.by, m.databaseId, m.slug, JSON.stringify(m.receipt));}/** Whether this object's storage holds the deletion's table (read before any other table is made). */export function held(sql: SqlStorage): boolean {  return sql.exec<{ n: number }>("SELECT count(*) AS n FROM sqlite_master WHERE type = 'table' AND name = ?", TABLE).one().n > 0;}/** The deletion under way or done, or null. */export function job(sql: SqlStorage): Job | null {  if (!held(sql)) return null;  upgrade(sql);  const row = sql    .exec<{ phase: string; started_at: string; by: string; database_id: string | null; slug: string; owner_phone: string | null; tries: number; receipt: string; erase_at: string | null }>(`SELECT phase, started_at, by, database_id, slug, owner_phone, tries, receipt, erase_at FROM ${TABLE} WHERE id = 1`)    .toArray()[0];  if (!row) return null;  return {    phase: row.phase as Phase,    startedAt: row.started_at,    by: row.by === "web" ? "web" : "app",    databaseId: row.database_id,    slug: row.slug,    ownerPhone: row.owner_phone,    tries: row.tries,    receipt: JSON.parse(row.receipt) as Receipt,    eraseAt: row.erase_at,  };}/** Whether the account is in its thirty days: set to be deleted, nothing erased yet. */export function pending(sql: SqlStorage): Job | null {  const j = job(sql);  return j && j.phase === "pending" ? j : null;}/** An object whose storage is already gone: nothing but the receipt is held. */export function erased(sql: SqlStorage): boolean {  const j = job(sql);  return j !== null && (j.phase === "closing" || j.phase === "done" || j.phase === "forgotten");}/** The answer every request gets once the person has deleted the account. */export function refuseDeleted(): never {  refuse(410, "account_deleted", "This account was deleted.");}/** * The same answer at the object's own door, with where the deletion stands: its step, when it began and ended, * and what it found left when it closed (both 0 when it is done). Never the receipt's counts: this is said * before any credential is read. */export function deletedAnswer(j: Job): Response {  // Ninety days after the erase the account is no one's: answered as a credential for no account (FORGET_AFTER_MS).  if (j.phase === "forgotten") return json({ code: "invalid_credential", message: "sign in again" }, 401);  return json({ code: "account_deleted", message: said(j), deleting: { phase: j.phase, started_at: j.startedAt, erase_at: j.eraseAt, finished_at: j.receipt.finished_at, left: j.receipt.left ?? null } }, 410);}/** The refusal's words. In the thirty days they carry the date (ISO), which the phone reads to say when. */export function said(j: Job): string {  return j.phase === "pending" && j.eraseAt ? `This account is set to be deleted on ${j.eraseAt.slice(0, 10)}. Sign in to keep it.` : "This account was deleted.";}/** * The confirmed tap: the row written, so the object refuses everything from * now on, and the first step set for the alarm. Asked twice, the second is * answered as the first. */export async function start(host: DeleteHost, by: "app" | "web", meta: { databaseId: string | null; slug: string; ownerPhone: string | null }): Promise<{ deleting: true; started_at: string; erase_at: string | null }> {  const held = job(host.sql);  if (held) return { deleting: true, started_at: held.startedAt, erase_at: held.eraseAt };  const now = host.now();  const startedAt = now.toISOString();  const records = tableExists(host.sql, "rows") ? host.sql.exec<{ n: number }>("SELECT count(*) AS n FROM rows WHERE deleted = 0").one().n : 0;  const receipt: Receipt = { started_at: startedAt, finished_at: null, by, records, files: 0, bytes: 0, google: { held: 0, revoked: 0 }, reports: 0 };  host.sql.exec(SCHEMA);  const eraseAt = new Date(now.getTime() + GRACE_MS).toISOString();  host.sql.exec(`INSERT INTO ${TABLE} (id, phase, started_at, by, database_id, slug, owner_phone, receipt, erase_at) VALUES (1, 'pending', ?, ?, ?, ?, ?, ?, ?)`, startedAt, by, meta.databaseId, meta.slug, meta.ownerPhone, JSON.stringify(receipt), eraseAt);  // Set for good, whatever a restore puts back (src/never_again.ts): written here, beside the row, so no caller forgets.  neverAgain.note(host.sql, { kind: "account_delete", started_at: startedAt, erase_at: eraseAt, by, at: startedAt });  await host.closeForGrace(eraseAt);  await host.storage.setAlarm(Date.parse(eraseAt));  console.log(`cottondb: account delete ${meta.slug}: set by ${by} for ${eraseAt}, ${records} records`);  return { deleting: true, started_at: startedAt, erase_at: eraseAt };}/** * The person kept the account in its thirty days (or the admin's hold keeps it on its date): nothing was erased, and * the object is as it was. ORDERED SO A FAILURE IS RETRIED, NEVER LOST (DELETE ACCOUNT 2): the row first says * `keeping` (which authorises nothing: no step erases from it), then the directory is told and the public links' * marker goes (`reopen`, each part safe to run again), and the row goes LAST. A Keep cut off anywhere leaves the row at * `keeping`: the next Keep, any request to the object, or its own alarm completes it, and never answers 410. */export async function keep(host: DeleteHost): Promise<{ kept: true }> {  const j = job(host.sql);  if (!j || (j.phase !== "pending" && j.phase !== "keeping")) refuse(410, "account_deleted", "This account was deleted.");  if (j.phase === "pending") {    host.sql.exec(`UPDATE ${TABLE} SET phase = 'keeping', tries = 0 WHERE id = 1`);    // Kept, whatever a restore puts back (src/never_again.ts): every Keep (the person's, the admin hold's on the date,    // one finished by a request, the alarm or `resume`) passes here.    neverAgain.note(host.sql, { kind: "account_keep", at: host.now().toISOString() });  }  await host.reopen();  // The row goes, not the table (DELETE GO-LIVE on a local dev, 25 Nov 2026: SQLite refuses DROP TABLE while any read  // on the object is still open). With no row, `job` answers that nothing is set and a later `start` writes row 1.  // Only a row still `keeping` (DELETE ACCOUNT 3): a Keep that woke late never takes away a deletion asked since.  host.sql.exec(`DELETE FROM ${TABLE} WHERE phase = 'keeping'`);  console.log("cottondb: account delete: kept");  return { kept: true };}/** * The alarm's turn: steps run one after another until the deletion is done * or a step asks to come back (a page budget spent, Google to try again). * Answers when the next alarm should come, or null when there is none. */export async function run(host: DeleteHost): Promise<number | null> {  for (let guard = 0; guard < 16; guard++) {    const j = job(host.sql);    if (!j || j.phase === "forgotten") return null;    let next: "again" | number | null;    try {      next = await step(host, j);    } catch (error) {      // Any step that throws (R2, the directory, a space not answering) comes back on its own alarm, later each time,      // never given up (DELETE ACCOUNT 1): the alarm the platform retries only six times is not relied on.      const tries = j.tries + 1;      if (held(host.sql)) host.sql.exec(`UPDATE ${TABLE} SET tries = ? WHERE id = 1`, tries);      const wait = Math.min(BACKOFF_MS * 2 ** Math.min(tries - 1, 10), MAX_BACKOFF_MS);      console.error(`cottondb: account delete ${j.slug}: step ${j.phase} failed (try ${tries}), again in ${Math.round(wait / 1000)} s`, error instanceof Error ? error.message : "unknown");      return wait;    }    if (next === "again") continue;    return next;  }  return 1000;}/** * The alarm this deletion needs, set when none is (DELETE ACCOUNT 1): called on every request the object answers * while a deletion is held, and by the directory's sweep. An alarm is kept in the object's storage across deploys and * evictions; this covers one lost to a platform that gave up retrying, or never set because a write was cut short. */export async function ensureAlarm(host: DeleteHost): Promise<void> {  const j = job(host.sql);  if (!j || j.phase === "forgotten") return;  const due = whenDue(j);  if (!Number.isFinite(due)) {    console.error(`cottondb: account delete ${j.slug}: its date does not read (${JSON.stringify(j.eraseAt)}); not due, left for an admin`);    return;  }  const held = await host.storage.getAlarm();  // An alarm already set no later than when this is due stands; one missing, or set past it, is brought to it.  if (held !== null && held <= Math.max(due, Date.now()) + 1000) return;  await host.storage.setAlarm(Math.max(due, Date.now()));}/** When the deletion's next step is due: the date in the thirty days, ninety days on once done, and now otherwise. */function whenDue(j: Job): number {  // A date that does not read is never due (DELETE ACCOUNT 3): no alarm for it, and the sweep lists it as stuck.  if (j.phase === "pending") return Date.parse(j.eraseAt ?? "");  if (j.phase === "done") return (Date.parse(j.receipt.finished_at ?? "") || Date.now()) + FORGET_AFTER_MS;  return Date.now();}/** * THE SWEEP ONLY KNOCKS (DELETE ACCOUNT 2). The directory asks the object to check its own job; it carries no date and * no authority. Only this object's own row, written by this object, can move an erase: with a row, its alarm is made * sure of and its phase and date are answered; with no row (no table, an empty table, or a row this cannot read) the * account is LIVE, said so, and nothing is touched. Nothing here erases. */export async function resume(host: DeleteHost): Promise<{ phase: Phase | "live"; erase_at: string | null }> {  let j: Job | null;  try {    j = job(host.sql);  } catch (error) {    console.error("cottondb: account delete: a knock found a row it could not read; answered live", error instanceof Error ? error.message : "unknown");    return { phase: "live", erase_at: null };  }  if (!j) {    // No row of its own. Only the object's own mark (written by its `storage` step) with nothing of an account left    // says it was cut off mid-wipe; anything else is a live account, left alone.    const mark = host.erasing ? await host.erasing.get() : null;    if (!mark) return { phase: "live", erase_at: null };    if (host.holdsAccount?.() !== false) {      console.error(`cottondb: account delete ${mark.slug}: its wipe mark is there but the object still holds an account; left alone`);      return { phase: "live", erase_at: null };    }    await host.storage.deleteAll();    writeClosing(host.sql, mark);    await host.erasing!.clear();    await host.storage.setAlarm(Date.now());    console.log(`cottondb: account delete ${mark.slug}: cut off mid-wipe; closed from its own mark`);    return { phase: "closing", erase_at: null };  }  if (j.phase === "keeping") {    // A Keep cut off before it finished: finished now, or on its own alarm.    try {      await keep(host);      return { phase: "live", erase_at: null };    } catch {      await ensureAlarm(host);      return { phase: "keeping", erase_at: null };    }  }  await ensureAlarm(host);  return { phase: j.phase, erase_at: j.eraseAt };}/** What the object says of its own deletion, read only (the admin's check, src/open.ts): its phase, or live. */export function standing(sql: SqlStorage): Phase | "live" {  try {    return job(sql)?.phase ?? "live";  } catch {    return "live";  }}async function step(host: DeleteHost, j: Job): Promise<"again" | number | null> {  const { sql } = host;  const save = (phase: Phase, receipt: Receipt, tries = 0): void => {    sql.exec(`UPDATE ${TABLE} SET phase = ?, receipt = ?, tries = ? WHERE id = 1`, phase, JSON.stringify(receipt), tries);  };  switch (j.phase) {    case "pending": {      const left = Date.parse(j.eraseAt ?? "") - host.now().getTime();      // A date that does not read is not due (DELETE ACCOUNT 3): nothing runs, and the directory's sweep lists it as stuck.      if (Number.isNaN(left)) {        console.error(`cottondb: account delete ${j.slug}: its date does not read (${JSON.stringify(j.eraseAt)}); not due, left for an admin`);        return null;      }      if (left > 0) return left;      // An account the admin holds (Cotton's own: the store reviewer's, the owner's) is kept on the date, never erased.      if (onHold(sql)) {        await keep(host);        console.log(`cottondb: account delete ${j.slug}: held by the admin, kept on its date`);        return null;      }      // Reports first, while the number is still this account's (DELETE ACCOUNT 2): freed, a new sign-up's could go too.      save("reports", j.receipt);      console.log(`cottondb: account delete ${j.slug}: thirty days passed, erasing`);      return "again";    }    case "keeping": {      await keep(host);      return null;    }    case "revoke": {      try {        const google = await host.revokeGoogle();        if (google.revoked < google.held && j.tries + 1 < REVOKE_TRIES) {          save("revoke", j.receipt, j.tries + 1);          return RETRY_MS;        }        save("files", { ...j.receipt, google });      } catch (error) {        console.error(`cottondb: account delete ${j.slug}: Google's revocation failed (try ${j.tries + 1})`, error instanceof Error ? error.message : "unknown");        if (j.tries + 1 < REVOKE_TRIES) {          save("revoke", j.receipt, j.tries + 1);          return RETRY_MS;        }        save("files", j.receipt);      }      return "again";    }    case "directory": {      // The shared spaces first, while the number is still this database's (SHARED SPACE 2, review item 1): each is      // told the database is gone. One that does not take it is asked again with the erase's own back-off (a throw      // here); after a day the erase goes on, and the spaces not told are kept in the receipt for an admin.      let receipt = j.receipt;      // Their people first, best effort and once: anyone not told sees "left Cotton" once the number leads nowhere.      if (host.tellPeople && !receipt.people_told_at) {        await host.tellPeople().catch(() => 0);        receipt = { ...receipt, people_told_at: host.now().toISOString() };      }      if (host.leaveSpaces) {        const notTold = await host.leaveSpaces();        if (notTold.length) {          const since = receipt.spaces_failing_since ?? host.now().toISOString();          if (host.now().getTime() - Date.parse(since) < DAY_MS) {            if (!receipt.spaces_failing_since) save("directory", { ...receipt, spaces_failing_since: since }, j.tries);            throw new Error(`${notTold.length} shared space(s) did not take word of the erase`);          }          console.error(`cottondb: account delete ${j.slug}: shared spaces not told after a day, going on: ${notTold.join(", ")}`);          receipt = { ...receipt, spaces_not_told: notTold };        }      }      // A way back in never dies silently (TRUSTED RECOVERY): the people this one helps are told, exactly as the spaces are.      if (host.leaveRecovery) {        const notTold = await host.leaveRecovery();        if (notTold.length) {          const since = receipt.recovery_failing_since ?? host.now().toISOString();          if (host.now().getTime() - Date.parse(since) < DAY_MS) {            if (!receipt.recovery_failing_since) save("directory", { ...receipt, recovery_failing_since: since }, j.tries);            throw new Error(`${notTold.length} trusted person(s) did not take word of the erase`);          }          console.error(`cottondb: account delete ${j.slug}: trusted people not told after a day, going on: ${notTold.join(", ")}`);          receipt = { ...receipt, recovery_not_told: notTold };        }      }      if (j.databaseId) await host.forgetInDirectory(j.databaseId, j.slug);      save("revoke", receipt);      return "again";    }    case "reports": {      const reports = j.ownerPhone ? await host.forgetReports(j.ownerPhone) : 0;      save("directory", { ...j.receipt, reports });      return "again";    }    case "files": {      const receipt = { ...j.receipt };      // Files still being sent in parts first: R2 lists no unfinished upload, so they are aborted by the ids kept.      if (host.abortUploads) receipt.uploads = (receipt.uploads ?? 0) + (await host.abortUploads());      // A ledger copy that checked the phase before this step began lands first, and is erased below with the rest.      if (host.ledgerQuiet) await host.ledgerQuiet();      let left = false;      // The person's files (counted in the receipt), then restore's own: snapshots, exports, the ledger and the marker      // (src/restore.ts `hiddenPrefixes`; outside the slug, never served), erased too but not counted as the person's.      const hidden = hiddenPrefixes(j.slug);      for (const [bucket, prefix, counted] of [[host.env.MEDIA, `${j.slug}/`, true], [host.env.PHOTOS, `${j.slug}/`, true], ...hidden.media.map((p) => [host.env.MEDIA, p, false] as const), ...hidden.photos.map((p) => [host.env.PHOTOS, p, false] as const)] as const) {        const gone = await deletePrefix(bucket, prefix, PAGES_PER_STEP);        if (counted) {          receipt.files += gone.files;          receipt.bytes += gone.bytes;        }        left ||= gone.more;        // Counted as each bucket's pages go, so a cut off here keeps what went (one cut between a page's delete and        // this save counts that page short: the receipt's files and bytes are "at least").        save("files", receipt);        await host.storage.sync();        host.killPoint?.("files");      }      if (left) {        save("files", receipt);        return 1000;      }      // The person's chat pictures and profile picture live outside the slug (src/chat/chat.ts), named in its tables.      const chat = await deleteKeys(host.env.MEDIA, [...namedIn(sql, "chat_file", "chat-files/"), ...namedIn(sql, "chat_profile_file", "chat-profile/")]);      receipt.files += chat.files;      receipt.bytes += chat.bytes;      save("storage", receipt);      return "again";    }    case "storage": {      // RESTORE 2 (L3): the version reached, kept in the receipt the erasing mark holds, so a restore (dev only) raises past it.      const versionRow = sql.exec<{ value: string }>("SELECT value FROM meta WHERE key = 'version'").toArray()[0];      const receipt: Receipt = { ...j.receipt, ...(versionRow ? { last_version: Number(versionRow.value) || 0 } : {}) };      // THE OBJECT'S OWN MARK (DELETE ACCOUNT 2): written by this object, under its own Durable Object id, just before      // its storage goes, and cleared once the closing row is written. It is the one positive evidence that this      // object itself began wiping: if it is cut off between `deleteAll` and the closing row, a knock finds the mark      // and an empty object, and closes from it (`resume`). A live account never shows it: only this step writes it,      // reached only from this object's own row past its date and past the files.      // The alarm is never taken away here (DELETE ACCOUNT 3): one stays set at every await, so a cut anywhere in this      // step comes back by itself; set again after `deleteAll`, which may take it with the storage.      await host.storage.setAlarm(Date.now() + BACKOFF_MS);      if (host.erasing) await host.erasing.put({ databaseId: j.databaseId, slug: j.slug, startedAt: j.startedAt, by: j.by, receipt });      host.killPoint?.("mark");      await host.storage.deleteAll();      host.killPoint?.("storage");      await host.storage.setAlarm(Date.now() + BACKOFF_MS);      writeClosing(sql, { databaseId: j.databaseId, slug: j.slug, startedAt: j.startedAt, by: j.by, receipt });      host.killPoint?.("closed");      if (host.erasing) await host.erasing.clear();      return "again";    }    case "closing": {      if (host.erasing) await host.erasing.clear();      const receipt: Receipt = { ...j.receipt, finished_at: host.now().toISOString(), left: await left(host, j.slug) };      if (j.databaseId) await host.closeInDirectory(j.databaseId, receipt);      sql.exec(`UPDATE ${TABLE} SET phase = 'done', receipt = ?, finished_at = ? WHERE id = 1`, JSON.stringify(receipt), receipt.finished_at);      console.log(`cottondb: account delete ${j.slug}: done, ${receipt.records} records, ${receipt.files} files, ${receipt.bytes} bytes, ${receipt.reports} reports, Google ${receipt.google.revoked}/${receipt.google.held}`);      return FORGET_AFTER_MS;    }    case "done": {      const wait = whenDue(j) - host.now().getTime();      if (wait > 0) return wait;      // Ninety days on: the directory's receipt is moved to a random id, then this row names nothing.      if (j.databaseId && host.forgetReceipt) await host.forgetReceipt(j.databaseId);      sql.exec(`UPDATE ${TABLE} SET phase = 'forgotten', database_id = NULL, slug = '', owner_phone = NULL, receipt = '{}', started_at = '', by = 'app', finished_at = NULL, erase_at = NULL WHERE id = 1`);      console.log("cottondb: account delete: a deleted account's id let go, ninety days after its erase");      return null;    }    default:      return null;  }}/** What is still there as the deletion closes: the object's other tables, and keys under the prefix in both buckets. */async function left(host: DeleteHost, slug: string): Promise<{ tables: number; keys: number }> {  const tables = host.sql.exec<{ n: number }>("SELECT count(*) AS n FROM sqlite_master WHERE type = 'table' AND name <> ? AND name NOT LIKE '_cf_%' AND name NOT LIKE 'sqlite_%'", TABLE).one().n;  let keys = 0;  for (const [bucket, prefix] of [[host.env.MEDIA, `${slug}/`], [host.env.PHOTOS, `${slug}/`], ...hiddenPrefixes(slug).media.map((p) => [host.env.MEDIA, p] as const), ...hiddenPrefixes(slug).photos.map((p) => [host.env.PHOTOS, p] as const)] as const) keys += (await bucket.list({ prefix, limit: 1000 })).objects.length;  return { tables, keys };}/** Up to `pages` pages of a thousand keys under `prefix`, deleted; what went and whether more is left. */export async function deletePrefix(bucket: R2Bucket, prefix: string, pages: number): Promise<{ files: number; bytes: number; more: boolean }> {  let files = 0;  let bytes = 0;  for (let page = 0; page < pages; page++) {    const listed = await bucket.list({ prefix, limit: 1000 });    if (!listed.objects.length) return { files, bytes, more: false };    await bucket.delete(listed.objects.map((o) => o.key));    // The thirty days' marker goes with the rest, and is not the person's: the receipt does not count it.    const theirs = listed.objects.filter((o) => !o.key.endsWith("/.deleting"));    files += theirs.length;    bytes += theirs.reduce((n, o) => n + o.size, 0);    if (!listed.truncated && listed.objects.length < 1000) return { files, bytes, more: false };  }  return { files, bytes, more: true };}async function deleteKeys(bucket: R2Bucket, keys: string[]): Promise<{ files: number; bytes: number }> {  let files = 0;  let bytes = 0;  for (let i = 0; i < keys.length; i += 1000) {    const chunk = keys.slice(i, i + 1000);    const heads = await Promise.all(chunk.map((k) => bucket.head(k)));    const present = heads.filter((h): h is R2Object => h !== null);    if (present.length) await bucket.delete(present.map((h) => h.key));    files += present.length;    bytes += present.reduce((n, h) => n + h.size, 0);  }  return { files, bytes };}function namedIn(sql: SqlStorage, table: string, prefix: string): string[] {  if (!tableExists(sql, table)) return [];  return sql.exec<{ id: string }>(`SELECT id FROM ${table}`).toArray().map((r) => `${prefix}${r.id}`);}function tableExists(sql: SqlStorage, table: string): boolean {  return sql.exec<{ n: number }>("SELECT count(*) AS n FROM sqlite_master WHERE type = 'table' AND name = ?", table).one().n > 0;}/** * FILES SENT IN PARTS (DELETE ACCOUNT 1). R2 lists no unfinished multipart upload, so a deletion could not find one * by its prefix: the object keeps each upload's id from its start until it is finished, and the erase aborts every * one still held. (The bucket's own rule aborts an unfinished upload after seven days besides; the thirty days are * longer, so this only matters where that rule is missing.) */export const UPLOADS = "media_upload_open";const UPLOADS_SCHEMA = `CREATE TABLE IF NOT EXISTS ${UPLOADS} (upload TEXT PRIMARY KEY, key TEXT NOT NULL, at INTEGER NOT NULL)`;export function uploadOpened(sql: SqlStorage, key: string, upload: string): void {  sql.exec(UPLOADS_SCHEMA);  sql.exec(`INSERT OR REPLACE INTO ${UPLOADS} (upload, key, at) VALUES (?, ?, ?)`, upload, key, Date.now());}export function uploadClosed(sql: SqlStorage, upload: string): void {  if (tableExists(sql, UPLOADS)) sql.exec(`DELETE FROM ${UPLOADS} WHERE upload = ?`, upload);}/** Every upload still open, the person's own and Send's copies to other people (src/send/send.ts `send_copy`), aborted; how many. */export async function abortOpenUploads(sql: SqlStorage, bucket: R2Bucket): Promise<number> {  const open: { upload: string; key: string }[] = [];  if (tableExists(sql, UPLOADS)) open.push(...sql.exec<{ upload: string; key: string }>(`SELECT upload, key FROM ${UPLOADS}`).toArray());  if (tableExists(sql, "send_copy")) open.push(...sql.exec<{ upload: string; key: string }>("SELECT upload, dest AS key FROM send_copy WHERE upload IS NOT NULL AND done = 0").toArray());  let aborted = 0;  for (const u of open) {    try {      await bucket.resumeMultipartUpload(u.key, u.upload).abort();      aborted += 1;    } catch {      // Already finished, aborted, or expired at R2: nothing of it is left to abort.    }    uploadClosed(sql, u.upload);  }  if (tableExists(sql, "send_copy")) sql.exec("UPDATE send_copy SET upload = NULL WHERE upload IS NOT NULL AND done = 0");  return aborted;}/** Where the admin's holds are logged, in meta: each set and taken away, with when (THE HOLD). */export const HOLD_LOG = "account_delete_hold_log";export function holdLog(store: { meta(key: string): string | null }): { hold: boolean; at: string }[] {  try {    return JSON.parse(store.meta(HOLD_LOG) ?? "[]") as { hold: boolean; at: string }[];  } catch {    return [];  }}/** A hold set or taken away: kept in the object's log (erased with it) and said in the Worker's log by the object's name. */export function holdLogged(_sql: SqlStorage, store: { meta(key: string): string | null; setMeta(key: string, value: string | null): void }, hold: boolean, slug: string): void {  const at = new Date().toISOString();  store.setMeta(HOLD_LOG, JSON.stringify([...holdLog(store), { hold, at }].slice(-50)));  console.log(`cottondb: account delete ${slug}: the admin ${hold ? "set" : "took away"} the hold at ${at}`);}