Public: anyone can read this; the crew can change it.
After the grace, a closed account is erased and its history keeps only "a former member" #15776
Check · Review · Land · Live done — Landed and live in production.
torque/forge:torque/15620-after-the-grace-a-closed-account-is-eras → main 0 commits fork
16 files
changed +818
−18
docs/features/maintenance-duties.md +16
| @@ -38,6 +38,22 @@ The `edge-kept` duty notices when the edge is not keeping the pages the forge ma | ||
| 38 | 38 | |
| 39 | 39 | Tests: `test/maintain-edge-kept.test.ts`. |
| 40 | 40 | |
| 41 | ## Account purge (#15620) | |
| 42 | ||
| 43 | The `account-purge` duty erases a closed account once its grace has run. A person asks to close their account on `/settings/password` (#15619). For 7 days Keep my account undoes it. After that, the hourly duty erases at most 20 accounts a run. For each one it: | |
| 44 | ||
| 45 | 1. asks again what stands in front of closing (the forge's only admin is never erased); | |
| 46 | 2. checks every repository the person owns and stops, deleting nothing, if any is a fork that is the head of a pull into another repository (no one may delete such a fork); | |
| 47 | 3. deletes the person's repositories, ends every browser, and removes the person's own rows in one transaction. | |
| 48 | ||
| 49 | What they wrote in other people's repositories stays, as "a former member". So do events whose payload named them: the username, the id and the person's `name/repo` paths are rewritten to the placeholder's. | |
| 50 | ||
| 51 | The audit is admins-only events. `account.purged` carries counts only. `account.purge_failed` names the account and why, and is written once a reason, not once each daily retry. A held account is tried again a day later. Every run also lists the held accounts and their reasons as a finding on `/maintenance`, and the person's own settings page says "It is held, and an admin will look." For a held fork, an admin transfers it to an owner who keeps it (the repository's settings, Transfer), and the next try erases the rest. If a repository fails to delete partway, the reason says how many went before it, and the next try goes on from there. | |
| 52 | ||
| 53 | Try it: close a test account, set its `close_requested_at` back 8 days, and wait for the next run (or run the duty from `/maintenance`). | |
| 54 | ||
| 55 | Tests: `test/account-purge.test.ts`, `test/account-close.test.ts`. | |
| 56 | ||
| 41 | 57 | ## Duty idle (#13406) |
| 42 | 58 | |
| 43 | 59 | The `duty-idle` duty watches the other duties for silence. Hourly, it looks at when each duty last started (budget stops do not count as a start). A duty whose last start is more than twice its interval ago is idle; exactly 2x is not. A duty that has never run is skipped, because there is no last run to name. The watcher never watches itself. |
src/actions/account_close.ts +22 −5
| @@ -42,10 +42,22 @@ export function closesOn(at: string): string { | ||
| 42 | 42 | } |
| 43 | 43 | |
| 44 | 44 | /** The sentence the account page and the first page after sign-in show. */ |
| 45 | export function closingSays(at: string): string { | |
| 45 | export function closingSays(at: string, held = false): string { | |
| 46 | // Past its grace and held by the purge (#15620): the day has gone, and an admin is shown why. | |
| 47 | if (held) return `This account was due to close on ${closesOn(at)}. It is held, and an admin will look.`; | |
| 46 | 48 | return `This account closes on ${closesOn(at)}.`; |
| 47 | 49 | } |
| 48 | 50 | |
| 51 | /** The close request and whether the purge has held it, in one read. */ | |
| 52 | export function closeState(db: Database, userId: string): { at: string | null; held: boolean } { | |
| 53 | const r = db | |
| 54 | .query<{ at: string | null; held: number }, [string]>( | |
| 55 | "SELECT close_requested_at AS at, purge_tried_at IS NOT NULL AS held FROM user WHERE id = ?1", | |
| 56 | ) | |
| 57 | .get(userId); | |
| 58 | return { at: r?.at ?? null, held: r?.held === 1 }; | |
| 59 | } | |
| 60 | ||
| 49 | 61 | /** |
| 50 | 62 | * What stands in front of closing, the first that applies: being the forge's |
| 51 | 63 | * only admin, being the only admin of an organization whose repositories |
| @@ -88,7 +100,10 @@ export function requestClose(db: Database, userId: string, now = new Date()): bo | ||
| 88 | 100 | export function keepAccount(db: Database, userId: string): boolean { |
| 89 | 101 | return ( |
| 90 | 102 | db |
| 91 | .query("UPDATE user SET close_requested_at = NULL WHERE id = ?1 AND close_requested_at IS NOT NULL") | |
| 103 | .query( | |
| 104 | // A hold the purge noted (#15620) goes with the request it held. | |
| 105 | "UPDATE user SET close_requested_at = NULL, purge_tried_at = NULL, purge_held_why = NULL WHERE id = ?1 AND close_requested_at IS NOT NULL", | |
| 106 | ) | |
| 92 | 107 | .run(userId).changes > 0 |
| 93 | 108 | ); |
| 94 | 109 | } |
| @@ -171,19 +186,21 @@ export const PROOF_FIELDS = ["challenge", "id", "clientDataJSON", "authenticator | ||
| 171 | 186 | */ |
| 172 | 187 | export interface CloseStanding { |
| 173 | 188 | readonly at: string | null; |
| 189 | /** The purge has tried and held it (#15620). */ | |
| 190 | readonly held: boolean; | |
| 174 | 191 | readonly password: boolean; |
| 175 | 192 | readonly passkey: boolean; |
| 176 | 193 | } |
| 177 | 194 | export function closeStanding(db: Database, userId: string): CloseStanding { |
| 178 | 195 | const r = db |
| 179 | .query<{ at: string | null; password: number; passkey: number }, [string]>( | |
| 180 | `SELECT close_requested_at AS at, | |
| 196 | .query<{ at: string | null; held: number; password: number; passkey: number }, [string]>( | |
| 197 | `SELECT close_requested_at AS at, purge_tried_at IS NOT NULL AS held, | |
| 181 | 198 | (password_hash <> '' AND kind <> 'org' AND is_agent = 0) AS password, |
| 182 | 199 | EXISTS (SELECT 1 FROM passkey WHERE user_id = user.id) AS passkey |
| 183 | 200 | FROM user WHERE id = ?1`, |
| 184 | 201 | ) |
| 185 | 202 | .get(userId); |
| 186 | return { at: r?.at ?? null, password: r?.password === 1, passkey: r?.passkey === 1 }; | |
| 203 | return { at: r?.at ?? null, held: r?.held === 1, password: r?.password === 1, passkey: r?.passkey === 1 }; | |
| 187 | 204 | } |
| 188 | 205 | |
| 189 | 206 | /** A fresh challenge for this person, and the keys that may answer it. */ |
src/core/account_export.ts +2
| @@ -38,6 +38,8 @@ export const COLUMNS: Record<string, { exported: readonly string[]; withheld: Re | ||
| 38 | 38 | removed_at: "a moderator's record", |
| 39 | 39 | waiting_at: "a moderator's record", |
| 40 | 40 | close_requested_at: "a pending close, said on the account page", |
| 41 | purge_tried_at: "when the purge last held a closed account, an operational mark", | |
| 42 | purge_held_why: "why the purge held a closed account, for the forge's admins", | |
| 41 | 43 | }, |
| 42 | 44 | }, |
| 43 | 45 | user_key: { |
src/core/account_purge.ts added +358
| @@ -0,0 +1,358 @@ | ||
| 1 | /** | |
| 2 | * Erasing a closed account once its grace has run (#15620, the second half | |
| 3 | * of #15619). The person's own rows go; what they wrote where other people | |
| 4 | * work stays, authored by one placeholder account, "a former member". | |
| 5 | * | |
| 6 | * Every column that names a user is covered here or by its foreign key: | |
| 7 | * `ON DELETE CASCADE` and `SET NULL` do their own work when the user row | |
| 8 | * goes; a column with no cascade (`NO ACTION`, or no foreign key at all) is | |
| 9 | * a row of `COVERED`, saying whether its rows are the person's own | |
| 10 | * (`delete`) or shared history (`former`, rewritten to the placeholder). | |
| 11 | * `test/account-purge.test.ts` walks the schema and fails on a column that | |
| 12 | * names a user and is in neither, so a new table cannot be forgotten. | |
| 13 | * | |
| 14 | * Plain data in, plain data out: `purgeAccount` takes a database and an id | |
| 15 | * and returns counts. The duty (`maintain/duties/account_purge.ts`) picks | |
| 16 | * the accounts, ends their browsers, deletes their repositories through the | |
| 17 | * same action a person uses, and writes the audit line. | |
| 18 | */ | |
| 19 | ||
| 20 | import type { Database } from "bun:sqlite"; | |
| 21 | ||
| 22 | /** The placeholder's fixed id, and the words every page shows for it. */ | |
| 23 | export const FORMER_ID = "former-member"; | |
| 24 | export const FORMER_NAME = "a former member"; | |
| 25 | /** | |
| 26 | * `.invalid` is reserved (RFC 2606 §2): no mail is ever delivered there, so | |
| 27 | * no real person holds it. | |
| 28 | */ | |
| 29 | const FORMER_EMAIL = "[email protected]"; | |
| 30 | ||
| 31 | /** At most this many accounts a run, so one tick stays short. */ | |
| 32 | export const PURGE_BATCH = 20; | |
| 33 | /** The grace, in days (the same seven `account_close.ts` promises). */ | |
| 34 | export const PURGE_AFTER_DAYS = 7; | |
| 35 | const DAY_MS = 86_400_000; | |
| 36 | ||
| 37 | /** | |
| 38 | * What happens to a column that names a user and has no cascade: | |
| 39 | * `delete`: the row is the person's own and goes with them; | |
| 40 | * `former`: the row is shared history and now names the placeholder; | |
| 41 | * `none`: the column is not a user id (its reason says what it holds). | |
| 42 | */ | |
| 43 | export type Coverage = { readonly do: "delete" | "former" } | { readonly do: "none"; readonly why: string }; | |
| 44 | ||
| 45 | const DELETE: Coverage = { do: "delete" }; | |
| 46 | const FORMER: Coverage = { do: "former" }; | |
| 47 | ||
| 48 | /** Keyed `table.column`. Ordered as the schema walk prints them. */ | |
| 49 | export const COVERED: Readonly<Record<string, Coverage>> = { | |
| 50 | // A person's own: sign-in links, notices, asks, search, grants, sessions. | |
| 51 | "access_link.user_id": DELETE, | |
| 52 | "access_link.created_by": FORMER, | |
| 53 | "account_ceiling.set_by": FORMER, | |
| 54 | "account_notice.user_id": DELETE, | |
| 55 | "account_request.decided_by": FORMER, | |
| 56 | "admin_ask.user_id": DELETE, | |
| 57 | "admin_ask.answered_by": FORMER, | |
| 58 | "app_feature.absorbed_by": FORMER, | |
| 59 | "app_feature_setting.set_by": FORMER, | |
| 60 | "bet.backed_by": FORMER, | |
| 61 | "check_proven.proven_by": FORMER, | |
| 62 | "check_runner.created_by": FORMER, | |
| 63 | "child_reach_ask.asked_by": FORMER, | |
| 64 | "child_reach_ask.answered_by": FORMER, | |
| 65 | "child_reach_grant.granted_by": FORMER, | |
| 66 | // What they wrote in other people's repositories stays, as the placeholder's. | |
| 67 | "comment.author_id": FORMER, | |
| 68 | "comment.origin_author": { do: "none", why: "the outside author's name a mirrored comment came with" }, | |
| 69 | "conversation_find.user_id": DELETE, | |
| 70 | "curated_pack_change.actor": FORMER, | |
| 71 | "decision.by": FORMER, | |
| 72 | "domain_drill.run_by": FORMER, | |
| 73 | "egress_grant.granted_by": FORMER, | |
| 74 | "entitlement.payer": { do: "none", why: "an address, not an id: \`purgeAccount\` clears it by the person's email" }, | |
| 75 | "entitlement_change.actor_id": FORMER, | |
| 76 | // `event.actor_id` is handled by `purgeAccount` itself: a repository's | |
| 77 | // history keeps the event as the placeholder's, the person's own | |
| 78 | // (no repository) go. | |
| 79 | "event.actor_id": FORMER, | |
| 80 | "file_hold.by": FORMER, | |
| 81 | "first_ask_refusals.actor_id": DELETE, | |
| 82 | "fleet_operation.undone_by": FORMER, | |
| 83 | "fold_in_stop.by": FORMER, | |
| 84 | "heap_census.by_type": { do: "none", why: "a memory reading's per-type sizes" }, | |
| 85 | "forge_setting.updated_by": FORMER, | |
| 86 | "forge_setting_change.actor_id": FORMER, | |
| 87 | "gate_snooze.set_by": FORMER, | |
| 88 | "gift_code.made_by": FORMER, | |
| 89 | "guest_approval.approved_by": FORMER, | |
| 90 | "guest_pull_made.owner_id": DELETE, | |
| 91 | "invite.created_by": FORMER, | |
| 92 | "invite.used_by": FORMER, | |
| 93 | "issue.author_id": FORMER, | |
| 94 | "issue.origin_author": { do: "none", why: "the outside author's name a mirrored issue came with" }, | |
| 95 | "issue_dependency.actor_id": FORMER, | |
| 96 | "issue_dependency.blocked_by_id": { do: "none", why: "an issue id" }, | |
| 97 | "issue_estimate.by_id": FORMER, | |
| 98 | "issue_estimate.by_kind": { do: "none", why: "an estimate's base rates by kind" }, | |
| 99 | "issue_first.actor_id": FORMER, | |
| 100 | "issue_rank.actor_id": FORMER, | |
| 101 | "issue_rank.by_owner": { do: "none", why: "a 0/1 flag" }, | |
| 102 | "keeper_hold.lifted_by": FORMER, | |
| 103 | "keeper_now.by": FORMER, | |
| 104 | "limb_replan.by_user": FORMER, | |
| 105 | "look.attached_by": FORMER, | |
| 106 | "machine_sessions.owner_id": DELETE, | |
| 107 | "maintenance_duty_state.by": FORMER, | |
| 108 | "maintenance_quiet.set_by": FORMER, | |
| 109 | "member.promoted_by": FORMER, | |
| 110 | "model_grant.granted_by": FORMER, | |
| 111 | "model_review.decided_by": FORMER, | |
| 112 | "oauth_refresh.user_id": DELETE, | |
| 113 | "pinned_change.by": FORMER, | |
| 114 | "placement.decided_by": FORMER, | |
| 115 | "plan_proposal.author_id": FORMER, | |
| 116 | "pull.merged_by": FORMER, | |
| 117 | "pull_hold.held_by": FORMER, | |
| 118 | "pull_hold.released_by": FORMER, | |
| 119 | "pull_landing.actor_id": FORMER, | |
| 120 | "pull_pass.reviewer_id": FORMER, | |
| 121 | "pull_review_steps.set_by": FORMER, | |
| 122 | "pull_run_grant.user_id": FORMER, | |
| 123 | "reach_ask.user_id": DELETE, | |
| 124 | "repo.autonomy_by": FORMER, | |
| 125 | "repo.decisions_by": { do: "none", why: "who decides, a word ('owner', 'crew')" }, | |
| 126 | // A personal repository is deleted before the row goes; one that could not | |
| 127 | // be holds the purge (`ownedRepos`), so this never rewrites an owner. | |
| 128 | "repo.owner_id": { do: "none", why: "deleted first; a repository left holds the purge" }, | |
| 129 | "repo_crew_off.set_by": FORMER, | |
| 130 | "repo_redirect.moved_by": FORMER, | |
| 131 | "repo_source.by_id": FORMER, | |
| 132 | "repo_transfer.actor_id": FORMER, | |
| 133 | "repo_upstream.by_id": FORMER, | |
| 134 | "repo_wallet.set_by": FORMER, | |
| 135 | "review.author_id": FORMER, | |
| 136 | "review.origin_author": { do: "none", why: "the outside author's name a mirrored review came with" }, | |
| 137 | "review_thread.resolved_by": FORMER, | |
| 138 | "rp_login.link_user": DELETE, | |
| 139 | "run.holder": { do: "none", why: "the process that holds a run's lease" }, | |
| 140 | "secret_grant.granted_by": FORMER, | |
| 141 | "start_account.claimed_by": FORMER, | |
| 142 | "telemetry_grant.granted_by": FORMER, | |
| 143 | "thought.author": DELETE, | |
| 144 | "trusted_source.set_by": FORMER, | |
| 145 | "week_retro_taken.actor_id": FORMER, | |
| 146 | }; | |
| 147 | ||
| 148 | /** | |
| 149 | * The columns a schema walk treats as naming a user: a foreign key to | |
| 150 | * `user`, or a name that reads like one. Shared with the test, so the walk | |
| 151 | * the test checks is the walk the purge trusts. | |
| 152 | */ | |
| 153 | export const USERISH = | |
| 154 | /(^|_)(user|actor|author|owner|by|creator|person|member|payer|holder|requester|reporter|assignee|reviewer)(_id)?$|user_id|^by_|_by_|_by$/; | |
| 155 | ||
| 156 | export interface UserColumn { | |
| 157 | readonly table: string; | |
| 158 | readonly column: string; | |
| 159 | /** The foreign key's `on_delete`, or null when the column has none to `user`. */ | |
| 160 | readonly onDelete: string | null; | |
| 161 | } | |
| 162 | ||
| 163 | /** Every column outside `user` that names a user, by foreign key or by name. */ | |
| 164 | export function userColumns(db: Database): UserColumn[] { | |
| 165 | const all = db | |
| 166 | .query<{ name: string; sql: string | null }, []>( | |
| 167 | "SELECT name, sql FROM sqlite_master WHERE type = 'table' AND name NOT LIKE 'sqlite_%' ORDER BY name", | |
| 168 | ) | |
| 169 | .all(); | |
| 170 | // A full-text table's shadow tables (`<name>_data` and the like) are its own storage. | |
| 171 | const virtual = all.filter((t) => t.sql?.startsWith("CREATE VIRTUAL") === true).map((t) => `${t.name}_`); | |
| 172 | const tables = all | |
| 173 | .map((t) => t.name) | |
| 174 | .filter((n) => n !== "user" && !virtual.some((v) => n.startsWith(v))); | |
| 175 | const out: UserColumn[] = []; | |
| 176 | for (const table of tables) { | |
| 177 | const fks = new Map<string, string>(); | |
| 178 | for (const f of db.query<{ table: string; from: string; on_delete: string }, []>(`PRAGMA foreign_key_list("${table}")`).all()) | |
| 179 | if (f.table === "user") fks.set(f.from, f.on_delete); | |
| 180 | for (const c of db.query<{ name: string }, []>(`PRAGMA table_info("${table}")`).all()) | |
| 181 | if (fks.has(c.name) || USERISH.test(c.name)) out.push({ table, column: c.name, onDelete: fks.get(c.name) ?? null }); | |
| 182 | } | |
| 183 | return out; | |
| 184 | } | |
| 185 | ||
| 186 | /** True when the foreign key does its own work when the user row goes. */ | |
| 187 | export const cascades = (c: UserColumn): boolean => c.onDelete === "CASCADE" || c.onDelete === "SET NULL"; | |
| 188 | ||
| 189 | /** The columns neither a cascade nor `COVERED` speaks for: what the test fails on. */ | |
| 190 | export function uncovered(db: Database): string[] { | |
| 191 | return userColumns(db) | |
| 192 | .filter((c) => !cascades(c) && COVERED[`${c.table}.${c.column}`] === undefined) | |
| 193 | .map((c) => `${c.table}.${c.column}`); | |
| 194 | } | |
| 195 | ||
| 196 | /** | |
| 197 | * The accounts whose grace has run, at most `limit`: never tried first, | |
| 198 | * oldest request first; an account the purge could not erase is tried again | |
| 199 | * a day after its last try, so a held account never fills a run. | |
| 200 | */ | |
| 201 | export function duePurges(db: Database, now: Date, limit = PURGE_BATCH): { id: string; username: string }[] { | |
| 202 | const cutoff = new Date(now.getTime() - PURGE_AFTER_DAYS * DAY_MS).toISOString(); | |
| 203 | const retry = new Date(now.getTime() - DAY_MS).toISOString(); | |
| 204 | return db | |
| 205 | .query<{ id: string; username: string }, [string, string, number]>( | |
| 206 | `SELECT id, username FROM user | |
| 207 | WHERE close_requested_at IS NOT NULL AND close_requested_at <= ?1 | |
| 208 | AND (purge_tried_at IS NULL OR purge_tried_at <= ?2) | |
| 209 | AND kind = 'user' AND is_agent = 0 AND id <> '${FORMER_ID}' | |
| 210 | ORDER BY purge_tried_at IS NOT NULL, purge_tried_at, close_requested_at, id LIMIT ?3`, | |
| 211 | ) | |
| 212 | .all(cutoff, retry, limit); | |
| 213 | } | |
| 214 | ||
| 215 | /** | |
| 216 | * Note a try that did not erase the account, and why, so the next run tries | |
| 217 | * the others first. True when the reason is new (the first hold, or a | |
| 218 | * different one): the audit line is written then, never once a daily retry. | |
| 219 | */ | |
| 220 | export function notePurgeHeld(db: Database, userId: string, now: Date, why: string): boolean { | |
| 221 | const before = db.query<{ why: string | null }, [string]>("SELECT purge_held_why AS why FROM user WHERE id = ?1").get(userId); | |
| 222 | db.query("UPDATE user SET purge_tried_at = ?1, purge_held_why = ?3 WHERE id = ?2").run(now.toISOString(), userId, why); | |
| 223 | return before?.why !== why; | |
| 224 | } | |
| 225 | ||
| 226 | /** An account past its grace that the purge could not erase: what /maintenance names. */ | |
| 227 | export interface HeldPurge { | |
| 228 | readonly username: string; | |
| 229 | readonly why: string; | |
| 230 | readonly since: string; | |
| 231 | } | |
| 232 | ||
| 233 | /** Every account held past its grace, oldest request first. */ | |
| 234 | export function heldPurges(db: Database): HeldPurge[] { | |
| 235 | return db | |
| 236 | .query<HeldPurge, []>( | |
| 237 | `SELECT username, COALESCE(purge_held_why, 'held') AS why, purge_tried_at AS since FROM user | |
| 238 | WHERE close_requested_at IS NOT NULL AND purge_tried_at IS NOT NULL AND id <> '${FORMER_ID}' | |
| 239 | ORDER BY close_requested_at, id`, | |
| 240 | ) | |
| 241 | .all(); | |
| 242 | } | |
| 243 | ||
| 244 | /** | |
| 245 | * The person's repositories no one may delete: a fork that is the head of a | |
| 246 | * pull into another repository (`removeRepo` refuses it, since a pull with no | |
| 247 | * head row would read as one from its base's own branch). Checked before any | |
| 248 | * repository is deleted, so a held account loses nothing. | |
| 249 | */ | |
| 250 | export function undeletableRepos(db: Database, userId: string): string[] { | |
| 251 | return db | |
| 252 | .query<{ name: string }, [string]>( | |
| 253 | `SELECT DISTINCT u.username || '/' || r.name AS name FROM repo r JOIN user u ON u.id = r.owner_id | |
| 254 | WHERE r.owner_id = ?1 AND EXISTS ( | |
| 255 | SELECT 1 FROM pull p JOIN issue i ON i.id = p.issue_id WHERE p.head_repo_id = r.id AND i.repo_id <> r.id) | |
| 256 | ORDER BY name`, | |
| 257 | ) | |
| 258 | .all(userId) | |
| 259 | .map((r) => r.name); | |
| 260 | } | |
| 261 | ||
| 262 | /** The repositories this person still owns, by id. */ | |
| 263 | export function ownedRepos(db: Database, userId: string): string[] { | |
| 264 | return db | |
| 265 | .query<{ id: string }, [string]>("SELECT id FROM repo WHERE owner_id = ?1 ORDER BY id") | |
| 266 | .all(userId) | |
| 267 | .map((r) => r.id); | |
| 268 | } | |
| 269 | ||
| 270 | /** The placeholder every shared row now names; made once, never able to sign in. */ | |
| 271 | export function ensureFormer(db: Database): void { | |
| 272 | db.query( | |
| 273 | `INSERT OR IGNORE INTO user (id, username, email, password_hash, display_name, kind, is_agent, suspended_at, removed_at) | |
| 274 | VALUES (?1, ?2, ?3, '', ?2, 'user', 0, ?4, ?4)`, | |
| 275 | ).run(FORMER_ID, FORMER_NAME, FORMER_EMAIL, "1970-01-01T00:00:00.000Z"); | |
| 276 | } | |
| 277 | ||
| 278 | /** What one purge removed and kept, as counts only: the audit line's payload. */ | |
| 279 | export interface PurgeCounts { | |
| 280 | readonly sessions: number; | |
| 281 | readonly tokens: number; | |
| 282 | readonly keys: number; | |
| 283 | readonly passkeys: number; | |
| 284 | /** Other rows of the person's own deleted by `COVERED` (cascades past these are not counted). */ | |
| 285 | readonly deleted: number; | |
| 286 | /** Rows of shared history now authored by the placeholder. */ | |
| 287 | readonly kept: number; | |
| 288 | /** Events of the person's own (no repository) removed. */ | |
| 289 | readonly events: number; | |
| 290 | /** Events that stay whose payload named the person, now naming the placeholder. */ | |
| 291 | readonly scrubbed: number; | |
| 292 | } | |
| 293 | ||
| 294 | export type PurgeOutcome = | |
| 295 | | { readonly ok: true; readonly counts: PurgeCounts } | |
| 296 | | { readonly ok: false; readonly reason: "not_due" | "owns_repos"; readonly repos?: number }; | |
| 297 | ||
| 298 | /** | |
| 299 | * Erase one account in one transaction: its own rows, its own events, the | |
| 300 | * user row (whose cascades take emails, keys, tokens, sessions, passkeys and | |
| 301 | * the rest), with every shared row rewritten to the placeholder first. Only | |
| 302 | * an account still closing and past its grace is touched, so a second run, | |
| 303 | * or a person who pressed Keep my account, finds nothing to do. | |
| 304 | */ | |
| 305 | export function purgeAccount(db: Database, userId: string, now: Date): PurgeOutcome { | |
| 306 | const cutoff = new Date(now.getTime() - PURGE_AFTER_DAYS * DAY_MS).toISOString(); | |
| 307 | const due = db | |
| 308 | .query( | |
| 309 | `SELECT 1 FROM user WHERE id = ?1 AND close_requested_at IS NOT NULL AND close_requested_at <= ?2 | |
| 310 | AND kind = 'user' AND is_agent = 0 AND id <> '${FORMER_ID}'`, | |
| 311 | ) | |
| 312 | .get(userId, cutoff); | |
| 313 | if (due === null) return { ok: false, reason: "not_due" }; | |
| 314 | const repos = ownedRepos(db, userId).length; | |
| 315 | if (repos > 0) return { ok: false, reason: "owns_repos", repos }; | |
| 316 | const columns = userColumns(db); | |
| 317 | return db.transaction((): PurgeOutcome => { | |
| 318 | ensureFormer(db); | |
| 319 | const count = (table: string): number => | |
| 320 | db.query<{ n: number }, [string]>(`SELECT COUNT(*) AS n FROM "${table}" WHERE user_id = ?1`).get(userId)?.n ?? 0; | |
| 321 | const own = { sessions: count("session"), tokens: count("token"), keys: count("user_key"), passkeys: count("passkey") }; | |
| 322 | let deleted = 0; | |
| 323 | let kept = 0; | |
| 324 | // The person's own events (no repository's history) go; the rest stay, as the placeholder's. | |
| 325 | const events = db.query("DELETE FROM event WHERE actor_id = ?1 AND repo_id IS NULL").run(userId).changes; | |
| 326 | for (const c of columns) { | |
| 327 | if (cascades(c)) continue; | |
| 328 | const cover = COVERED[`${c.table}.${c.column}`]; | |
| 329 | if (cover === undefined || cover.do === "none") continue; | |
| 330 | if (cover.do === "delete") deleted += db.query(`DELETE FROM "${c.table}" WHERE "${c.column}" = ?1`).run(userId).changes; | |
| 331 | else kept += db.query(`UPDATE "${c.table}" SET "${c.column}" = ?2 WHERE "${c.column}" = ?1`).run(userId, FORMER_ID).changes; | |
| 332 | } | |
| 333 | // What stays names nobody (#15620): a kept event's payload that carried the person's | |
| 334 | // username, id or one of their `name/repo` paths now carries the placeholder's. Matched as a | |
| 335 | // whole JSON string (or a path's prefix), so "bobby" is not touched for "bob". Payloads are | |
| 336 | // not indexed: this reads the table once an account, at most `PURGE_BATCH` an hour. | |
| 337 | const name = db.query<{ u: string }, [string]>("SELECT username AS u FROM user WHERE id = ?1").get(userId)?.u ?? ""; | |
| 338 | const scrubbed = | |
| 339 | name === "" | |
| 340 | ? 0 | |
| 341 | : db | |
| 342 | .query( | |
| 343 | `UPDATE event SET payload = replace(replace(replace(payload, ?1, ?2), ?3, ?4), ?5, ?6) | |
| 344 | WHERE instr(payload, ?1) > 0 OR instr(payload, ?3) > 0 OR instr(payload, ?5) > 0`, | |
| 345 | ) | |
| 346 | .run( | |
| 347 | JSON.stringify(name), JSON.stringify(FORMER_NAME), | |
| 348 | `${JSON.stringify(name).slice(0, -1)}/`, `${JSON.stringify(FORMER_NAME).slice(0, -1)}/`, | |
| 349 | JSON.stringify(userId), JSON.stringify(FORMER_ID), | |
| 350 | ).changes; | |
| 351 | // `entitlement.payer` is an address, not an id: an ended plan forgets who paid. | |
| 352 | const email = db.query<{ email: string }, [string]>("SELECT email FROM user WHERE id = ?1").get(userId)?.email ?? ""; | |
| 353 | if (email !== "") kept += db.query("UPDATE entitlement SET payer = '' WHERE payer = ?1 COLLATE NOCASE").run(email).changes; | |
| 354 | // The row itself; its cascades take emails, keys, tokens, sessions, passkeys and settings. | |
| 355 | db.query("DELETE FROM user WHERE id = ?1").run(userId); | |
| 356 | return { ok: true, counts: { ...own, deleted, kept, events, scrubbed } }; | |
| 357 | })(); | |
| 358 | } |
src/core/event_audience.ts +5 −1
| @@ -349,7 +349,11 @@ export function classifiedAudience(kind: string): EventAudience | undefined { | ||
| 349 | 349 | kind === "forge.host_sealed" || |
| 350 | 350 | // Which child forge was offered links to how many apps is the parent's admins' |
| 351 | 351 | // (`spawn/app_links.ts`). |
| 352 | kind === "forge.app_links" | |
| 352 | kind === "forge.app_links" || | |
| 353 | // An erased account's counts, and why one was held (`maintain/duties/account_purge.ts`, | |
| 354 | // #15620). | |
| 355 | kind === "account.purged" || | |
| 356 | kind === "account.purge_failed" | |
| 353 | 357 | ) |
| 354 | 358 | return "admins"; |
| 355 | 359 | // A broken adapter sync is for those who may write the repository (`apps/pull.ts`). |
src/core/migration-pins/20261123090000-account-purge-tried.pin added +1
| @@ -0,0 +1,1 @@ | ||
| 1 | 93e8709f5c3b9d22949a330ef2ff9b2f30228b4d6c594d02c4baef2dc0980df0 |
src/core/migration-pins/20261123100000-account-purge-held.pin added +1
| @@ -0,0 +1,1 @@ | ||
| 1 | 0a585262979de329957f221077e8bac1b23bac2548f9941ed9dcff9b1b749766 |
src/core/migrations/20261123090000-account-purge-tried.ts added +11
| @@ -0,0 +1,11 @@ | ||
| 1 | // When the purge last tried to erase a closed account and could not (#15620): a held account is | |
| 2 | // tried again once a day, after every account not yet tried, so it never fills a run's twenty. | |
| 3 | // The purge rewrites `comment.author_id` and `review.author_id` to the placeholder, and deleting | |
| 4 | // the user row walks `run.actor_id` for its SET NULL: each by its index, never a scan of a table | |
| 5 | // that grows (`test/account-purge.test.ts` reads the plans). | |
| 6 | export default ` | |
| 7 | ALTER TABLE user ADD COLUMN purge_tried_at TEXT; | |
| 8 | CREATE INDEX IF NOT EXISTS comment_author ON comment(author_id); | |
| 9 | CREATE INDEX IF NOT EXISTS review_author ON review(author_id); | |
| 10 | CREATE INDEX IF NOT EXISTS run_actor ON run(actor_id); | |
| 11 | `; |
src/core/migrations/20261123100000-account-purge-held.ts added +5
| @@ -0,0 +1,5 @@ | ||
| 1 | // Why the purge last held a closed account (#15620): the admins' /maintenance names it beside the | |
| 2 | // account, and the audit line is written once a reason, not once a daily retry. | |
| 3 | export default ` | |
| 4 | ALTER TABLE user ADD COLUMN purge_held_why TEXT; | |
| 5 | `; |
src/maintain/duties/account_purge.ts added +141
| @@ -0,0 +1,141 @@ | ||
| 1 | /** | |
| 2 | * Account purge (#15620): every hour, erase the accounts whose close request | |
| 3 | * (#15619) is past its seven days, at most `PURGE_BATCH` a run. For each: | |
| 4 | * ask again what stands in front of closing (a forge's only admin is never | |
| 5 | * erased), delete the person's repositories through the action a person | |
| 6 | * uses, end every browser, then `purgeAccount`. One account that fails is | |
| 7 | * named and the run goes on to the next. | |
| 8 | * | |
| 9 | * Nothing is deleted while anything still stands in front of the whole | |
| 10 | * erasure: the close refusal and every repository no one may delete are | |
| 11 | * asked first. A repository that fails to delete later is named with how | |
| 12 | * many went before it, and the next day's try picks up from there. | |
| 13 | * | |
| 14 | * Each account writes one audit line, an event for the forge's admins: | |
| 15 | * `account.purged` with counts only (the account is gone, so nothing names | |
| 16 | * it), or `account.purge_failed` with the username and why (the account | |
| 17 | * still stands, so naming it tells an admin what to fix) — once a reason, | |
| 18 | * not once a daily retry. Every run also names every held account as a | |
| 19 | * finding, so /maintenance shows them until an admin acts. | |
| 20 | */ | |
| 21 | ||
| 22 | import { closeRefusal } from "../../actions/account_close.ts"; | |
| 23 | import { deleteRepo } from "../../actions/repos.ts"; | |
| 24 | import { signOutEveryBrowser } from "../../actions/signins.ts"; | |
| 25 | import { | |
| 26 | duePurges, | |
| 27 | heldPurges, | |
| 28 | notePurgeHeld, | |
| 29 | ownedRepos, | |
| 30 | purgeAccount, | |
| 31 | undeletableRepos, | |
| 32 | PURGE_AFTER_DAYS, | |
| 33 | } from "../../core/account_purge.ts"; | |
| 34 | import { getRepoById } from "../../core/repos.ts"; | |
| 35 | import { getUserById } from "../../core/users.ts"; | |
| 36 | import type { App } from "../../app.ts"; | |
| 37 | import type { Duty, DutyResult } from "../duty.ts"; | |
| 38 | ||
| 39 | /** What each finding counted, in words: the probes read `user`, not a query worth quoting. */ | |
| 40 | const DUE_READ = `accounts in user whose close request is ${PURGE_AFTER_DAYS} days old or more and that the purge has not tried in the last day`; | |
| 41 | const HELD_READ = `accounts in user past their ${PURGE_AFTER_DAYS} days that the purge tried and could not erase (purge_tried_at set)`; | |
| 42 | ||
| 43 | /** One account's purge: the audit line's words, and whether it went. */ | |
| 44 | export interface PurgeLine { | |
| 45 | readonly ok: boolean; | |
| 46 | readonly says: string; | |
| 47 | } | |
| 48 | ||
| 49 | /** Erase one account, or say why not; never throws. */ | |
| 50 | export async function purgeOne(app: App, userId: string, now: Date): Promise<PurgeLine> { | |
| 51 | const user = getUserById(app.db, userId); | |
| 52 | if (user === undefined) return { ok: false, says: "already gone" }; | |
| 53 | const fail = (why: string): PurgeLine => { | |
| 54 | if (notePurgeHeld(app.db, user.id, now, why)) | |
| 55 | app.bus.append({ kind: "account.purge_failed", payload: { username: user.username, why } }); | |
| 56 | return { ok: false, says: `${user.username}: ${why}` }; | |
| 57 | }; | |
| 58 | let repos = 0; | |
| 59 | try { | |
| 60 | const refusal = closeRefusal(app.db, user); | |
| 61 | if (refusal !== undefined) return fail(`held (${refusal.reason}): ${refusal.says}`); | |
| 62 | const stuck = undeletableRepos(app.db, user.id); | |
| 63 | if (stuck.length > 0) | |
| 64 | return fail( | |
| 65 | `held (pull_head): ${stuck.join(", ")} is the head of a pull into another repository and no one may delete it; an admin transfers it to an owner who keeps it`, | |
| 66 | ); | |
| 67 | const owned = ownedRepos(app.db, user.id); | |
| 68 | for (const id of owned) { | |
| 69 | const repo = getRepoById(app.db, id); | |
| 70 | if (repo === undefined) continue; | |
| 71 | const deleted = await deleteRepo(app, user, repo); | |
| 72 | if (!deleted.ok) return fail(`${repo.ownerName}/${repo.name} could not be deleted (${deleted.error}); ${repos} of ${owned.length} repositories deleted so far`); | |
| 73 | repos++; | |
| 74 | } | |
| 75 | // Every repository is gone: what is left is one transaction. The browsers end first, since | |
| 76 | // each ended stream is an event that names the account, and `purgeAccount` takes those too. | |
| 77 | const signedOut = signOutEveryBrowser(app, user); | |
| 78 | const ended = signedOut.ok ? signedOut.value.ended : 0; | |
| 79 | const purged = purgeAccount(app.db, user.id, now); | |
| 80 | if (!purged.ok) return fail(purged.reason === "owns_repos" ? `still owns ${purged.repos} repositories` : "no longer due"); | |
| 81 | // The browsers ended above are this account's sessions too. | |
| 82 | const c = { ...purged.counts, sessions: purged.counts.sessions + ended }; | |
| 83 | app.bus.append({ kind: "account.purged", payload: { repos, ...c } }); | |
| 84 | return { | |
| 85 | ok: true, | |
| 86 | says: `an account: ${repos} repositories, ${c.sessions} sessions, ${c.tokens} tokens, ${c.keys} keys, ${c.passkeys} passkeys, ${c.deleted} other rows, ${c.events} events removed; ${c.kept} shared rows and ${c.scrubbed} events now a former member's`, | |
| 87 | }; | |
| 88 | } catch (error) { | |
| 89 | return fail(`failed after ${repos} repositories deleted: ${error instanceof Error ? error.message.slice(0, 200) : "unknown error"}`); | |
| 90 | } | |
| 91 | } | |
| 92 | ||
| 93 | /** | |
| 94 | * One run: every due account, at most `PURGE_BATCH`, each on its own; then every one still held. | |
| 95 | */ | |
| 96 | export async function purgeDue(app: App, now: Date): Promise<DutyResult> { | |
| 97 | const due = duePurges(app.db, now); | |
| 98 | const lines: PurgeLine[] = []; | |
| 99 | for (const u of due) lines.push(await purgeOne(app, u.id, now)); | |
| 100 | const erased = lines.filter((l) => l.ok).length; | |
| 101 | const at = now.toISOString(); | |
| 102 | const held = heldPurges(app.db); | |
| 103 | return { | |
| 104 | findings: [ | |
| 105 | ...(due.length === 0 | |
| 106 | ? [] | |
| 107 | : [ | |
| 108 | { | |
| 109 | summary: `${due.length} closed accounts past their ${PURGE_AFTER_DAYS} days: ${erased} erased, ${due.length - erased} held`, | |
| 110 | probe: { kind: "query" as const, what: DUE_READ, number: due.length, at }, | |
| 111 | }, | |
| 112 | ]), | |
| 113 | ...(held.length === 0 | |
| 114 | ? [] | |
| 115 | : [ | |
| 116 | { | |
| 117 | summary: `${held.length} closed accounts held past their grace, for an admin: ${held | |
| 118 | .slice(0, 10) | |
| 119 | .map((h) => `${h.username} (${h.why})`) | |
| 120 | .join("; ")}${held.length > 10 ? `; and ${held.length - 10} more` : ""}`, | |
| 121 | probe: { kind: "query" as const, what: HELD_READ, number: held.length, at }, | |
| 122 | }, | |
| 123 | ]), | |
| 124 | ], | |
| 125 | actions: lines.map((l) => (l.ok ? `Erased ${l.says}` : `Held ${l.says}`)), | |
| 126 | }; | |
| 127 | } | |
| 128 | ||
| 129 | export const duty: Duty = { | |
| 130 | name: "account-purge", | |
| 131 | intervalMs: 3_600_000, | |
| 132 | budget: { | |
| 133 | runsPerDay: 30, | |
| 134 | dollarsPerDay: 1, | |
| 135 | reason: "hourly is 24 a day, so an account goes within an hour of its grace; the rest is room for a catch-up, and it spends no money", | |
| 136 | }, | |
| 137 | async run({ now, app }) { | |
| 138 | if (app === undefined) return { findings: [], actions: [] }; | |
| 139 | return purgeDue(app, now); | |
| 140 | }, | |
| 141 | }; |
src/perf/page_budgets/maintenance.ts +3 −3
| @@ -5,6 +5,6 @@ import type { PageBudget } from "../page_budget.ts"; | ||
| 5 | 5 | // over the duties would still show. One query reads every dismissal (#13967), one every quieted |
| 6 | 6 | // finding (#14557); one grouped read of the degraded findings (#14577); +3: the edge-kept duty |
| 7 | 7 | // (#14682); one grouped read of every duty's last run (#14674); +3: the deepsec-sweep duty |
| 8 | // (#15026); +3: the daily-proof duty (#15625). 93 is the steady count measured | |
| 9 | // warm on every run, not a load-sensitive figure. | |
| 10 | export const budget: PageBudget = { page: "maintenance", pattern: "/maintenance", medianMs: 50, statements: 93 }; | |
| 8 | // (#15026); +3: the daily-proof duty (#15625); +3: the account-purge duty (#15620). 96 is the | |
| 9 | // steady count measured warm on every run, not a load-sensitive figure. | |
| 10 | export const budget: PageBudget = { page: "maintenance", pattern: "/maintenance", medianMs: 50, statements: 96 }; |
src/web/pages/account.ts +5 −4
| @@ -68,7 +68,7 @@ import { | ||
| 68 | 68 | askToClose, |
| 69 | 69 | CLOSE_WORDS, |
| 70 | 70 | GRACE_DAYS, |
| 71 | closeRequestedAt, | |
| 71 | closeState, | |
| 72 | 72 | closingSays, |
| 73 | 73 | keepMyAccount, |
| 74 | 74 | keptSays, |
| @@ -1206,11 +1206,12 @@ export function closeOptions(ctx: Ctx): Response { | ||
| 1206 | 1206 | } |
| 1207 | 1207 | |
| 1208 | 1208 | /** While a close request stands, the day it closes and Keep my account; nothing otherwise. */ |
| 1209 | function closingNotice(ctx: Ctx, at = closeRequestedAt(ctx.app.db, ctx.auth.user!.id)): Html | null { | |
| 1209 | function closingNotice(ctx: Ctx, state = closeState(ctx.app.db, ctx.auth.user!.id)): Html | null { | |
| 1210 | const { at, held } = state; | |
| 1210 | 1211 | if (at === null) return null; |
| 1211 | 1212 | return block( |
| 1212 | 1213 | "Close account", |
| 1213 | html`<p data-closing>${closingSays(at)}</p> | |
| 1214 | html`<p data-closing>${closingSays(at, held)}</p> | |
| 1214 | 1215 | <form method="post" action="/settings/account/keep"> |
| 1215 | 1216 | <div class="form-actions">${btn("Keep my account", { variant: "primary" })}</div> |
| 1216 | 1217 | </form>`, |
| @@ -1231,7 +1232,7 @@ type CloseSaid = | ||
| 1231 | 1232 | * closing notice. A passkey-only account gets the passkey button alone. |
| 1232 | 1233 | */ |
| 1233 | 1234 | function closeView(ctx: Ctx, standing: CloseStanding, said?: CloseSaid): Html { |
| 1234 | const notice = closingNotice(ctx, standing.at); | |
| 1235 | const notice = closingNotice(ctx, standing); | |
| 1235 | 1236 | if (notice !== null) return notice; |
| 1236 | 1237 | const { password, passkey } = standing; |
| 1237 | 1238 | const r = said === undefined ? undefined : refused(said.form, "field" in said ? { [said.field]: said.text } : {}); |
src/web/pages/site.ts +3 −3
| @@ -8,7 +8,7 @@ | ||
| 8 | 8 | * typed still in it. A dead end that loses input is a bug, not a message. |
| 9 | 9 | */ |
| 10 | 10 | |
| 11 | import { closeRequestedAt, closingSays } from "../../actions/account_close.ts"; | |
| 11 | import { closeState, closingSays } from "../../actions/account_close.ts"; | |
| 12 | 12 | import { USERNAME_PATTERN } from "../username_pattern.ts"; |
| 13 | 13 | import { expireCookie, setCookie } from "../../auth/cookies.ts"; |
| 14 | 14 | import { safeNext, withReturn } from "../return_to.ts"; |
| @@ -648,9 +648,9 @@ export async function signinSubmit(ctx: Ctx): Promise<Response> { | ||
| 648 | 648 | * its answer through here, a redirect or a passkey's JSON alike. |
| 649 | 649 | */ |
| 650 | 650 | export function withClosingNotice(ctx: Ctx, userId: string, res: Response): Response { |
| 651 | const at = closeRequestedAt(ctx.app.db, userId); | |
| 651 | const { at, held } = closeState(ctx.app.db, userId); | |
| 652 | 652 | if (at === null) return res; |
| 653 | const flash = { tone: "attn" as const, message: closingSays(at), link: { href: "/settings", label: "Keep my account" } }; | |
| 653 | const flash = { tone: "attn" as const, message: closingSays(at, held), link: { href: "/settings", label: "Keep my account" } }; | |
| 654 | 654 | res.headers.append("set-cookie", flashCookie(flash, ctx.url, ctx.app.config.url)); |
| 655 | 655 | return res; |
| 656 | 656 | } |
test/account-close.test.ts +5
| @@ -78,6 +78,11 @@ describe("closing an account", () => { | ||
| 78 | 78 | const page = await (await fetch(`${servers.url}/settings`, { headers: { cookie } })).text(); |
| 79 | 79 | expect(page).toContain(`closes on ${closesOn(at!)}`); |
| 80 | 80 | expect(page).toContain("Keep my account"); |
| 81 | // Past its grace and held by the purge (#15620), the page says so, not a day that has gone. | |
| 82 | app.db.query("UPDATE user SET purge_tried_at = ?1 WHERE id = ?2").run(at!, bob.id); | |
| 83 | const held = await (await fetch(`${servers.url}/settings`, { headers: { cookie } })).text(); | |
| 84 | expect(held).toContain("It is held, and an admin will look."); | |
| 85 | app.db.query("UPDATE user SET purge_tried_at = NULL WHERE id = ?1").run(bob.id); | |
| 81 | 86 | // The other browser is signed out. |
| 82 | 87 | const stale = await fetch(`${servers.url}/settings`, { headers: { cookie: other.cookie }, redirect: "manual" }); |
| 83 | 88 | expect(stale.status).not.toBe(200); |
test/account-purge.test.ts added +238
| @@ -0,0 +1,238 @@ | ||
| 1 | /** | |
| 2 | * After the grace a closed account is erased (#15620): not at day 6, at day | |
| 3 | * 7; what the person wrote in someone else's repository stays as "a former | |
| 4 | * member"; a second run does nothing; Keep my account is never purged; a | |
| 5 | * held account is named and does not stop the others; at most twenty a run; | |
| 6 | * and every column that names a user is covered, so a new table that holds | |
| 7 | * a user id fails here until the purge knows what to do with it. | |
| 8 | */ | |
| 9 | import { afterAll, beforeAll, describe, expect, test } from "bun:test"; | |
| 10 | import { mkdtempSync, rmSync } from "node:fs"; | |
| 11 | import { tmpdir } from "node:os"; | |
| 12 | import { join } from "node:path"; | |
| 13 | import { createApp, type App } from "../src/app.ts"; | |
| 14 | import { transferRepository } from "../src/actions/transfer.ts"; | |
| 15 | import { closeState, closingSays, keepAccount, requestClose } from "../src/actions/account_close.ts"; | |
| 16 | import { COVERED, FORMER_ID, FORMER_NAME, PURGE_BATCH, cascades, duePurges, heldPurges, uncovered, userColumns } from "../src/core/account_purge.ts"; | |
| 17 | import { addComment, createIssue } from "../src/core/issues.ts"; | |
| 18 | import { createRepo, getRepoById } from "../src/core/repos.ts"; | |
| 19 | import { createSession } from "../src/core/sessions.ts"; | |
| 20 | import { createToken } from "../src/core/tokens.ts"; | |
| 21 | import { createUser, getUserById } from "../src/core/users.ts"; | |
| 22 | import { duty, purgeDue } from "../src/maintain/duties/account_purge.ts"; | |
| 23 | ||
| 24 | const DAY = 86_400_000; | |
| 25 | const T0 = new Date("2026-11-01T12:00:00.000Z"); | |
| 26 | const at = (days: number, ms = 0) => new Date(T0.getTime() + days * DAY + ms); | |
| 27 | ||
| 28 | let root = ""; | |
| 29 | let app: App; | |
| 30 | const make = async (username: string, adminIfFirst = false) => { | |
| 31 | const made = await createUser(app.db, { origin: "seed", trusted: true, username, email: `${username}@forge.local`, password: "a-long-passphrase", adminIfFirst }); | |
| 32 | if (!made.ok) throw new Error(made.error); | |
| 33 | return made.value; | |
| 34 | }; | |
| 35 | const events = (kind: string) => | |
| 36 | app.db.query<{ payload: string }, [string]>("SELECT payload FROM event WHERE kind = ?1 ORDER BY seq").all(kind).map((e) => JSON.parse(e.payload) as Record<string, unknown>); | |
| 37 | const count = (sql: string, ...args: string[]) => app.db.query<{ n: number }, string[]>(`SELECT COUNT(*) AS n FROM ${sql}`).get(...args)!.n; | |
| 38 | ||
| 39 | beforeAll(() => { | |
| 40 | root = mkdtempSync(join(tmpdir(), "forge-account-purge-")); | |
| 41 | app = createApp({ dataDir: root, port: 0 }); | |
| 42 | }); | |
| 43 | afterAll(() => rmSync(root, { recursive: true, force: true })); | |
| 44 | ||
| 45 | describe("the purge", () => { | |
| 46 | test("is a duty on the roster, hourly", async () => { | |
| 47 | const { duties } = await import("../src/maintain/registry.ts"); | |
| 48 | expect(duties.some((d) => d.name === "account-purge")).toBe(true); | |
| 49 | expect(duty.intervalMs).toBe(3_600_000); | |
| 50 | }); | |
| 51 | ||
| 52 | test("erases at day 7 and not at day 6, keeping what was written in someone else's repository", async () => { | |
| 53 | await make("alice", true); | |
| 54 | const bob = await make("bob"); | |
| 55 | const carol = await make("carol"); | |
| 56 | const own = await createRepo(app.db, app.reposRoot, { ownerId: bob.id, name: "notes" }); | |
| 57 | const shared = await createRepo(app.db, app.reposRoot, { ownerId: carol.id, name: "garden", visibility: "public" }); | |
| 58 | if (!own.ok || !shared.ok) throw new Error("repos"); | |
| 59 | const issue = createIssue(app.db, { repoId: shared.value.id, authorId: bob.id, title: "The gate sticks" }); | |
| 60 | if (!issue.ok) throw new Error("issue"); | |
| 61 | const reply = addComment(app.db, { issueId: issue.value.id, authorId: bob.id, body: "Oiled it, still sticks." }); | |
| 62 | if (!reply.ok) throw new Error("comment"); | |
| 63 | createSession(app.db, bob.id); | |
| 64 | createToken(app.db, bob.id, "ci", "rw"); | |
| 65 | expect(requestClose(app.db, bob.id, T0)).toBe(true); | |
| 66 | ||
| 67 | const day6 = await purgeDue(app, at(6, DAY - 1)); | |
| 68 | expect(day6.findings).toEqual([]); | |
| 69 | expect(getUserById(app.db, bob.id)).toBeDefined(); | |
| 70 | ||
| 71 | const day7 = await purgeDue(app, at(7)); | |
| 72 | expect(day7.findings[0]!.summary).toBe("1 closed accounts past their 7 days: 1 erased, 0 held"); | |
| 73 | expect(day7.actions[0]).toStartWith("Erased an account: 1 repositories, 1 sessions, 1 tokens"); | |
| 74 | expect(getUserById(app.db, bob.id)).toBeUndefined(); | |
| 75 | expect(getRepoById(app.db, own.value.id)).toBeUndefined(); | |
| 76 | expect(count("session WHERE user_id = ?1", bob.id)).toBe(0); | |
| 77 | expect(count("token WHERE user_id = ?1", bob.id)).toBe(0); | |
| 78 | expect(count("user WHERE email = ?1", "[email protected]")).toBe(0); | |
| 79 | // Shared history survives, by the placeholder. | |
| 80 | const kept = app.db.query<{ author: string; name: string }, [string]>( | |
| 81 | "SELECT i.author_id AS author, u.display_name AS name FROM issue i JOIN user u ON u.id = i.author_id WHERE i.id = ?1", | |
| 82 | ).get(issue.value.id); | |
| 83 | expect(kept).toEqual({ author: FORMER_ID, name: FORMER_NAME }); | |
| 84 | expect(app.db.query<{ a: string }, [string]>("SELECT author_id AS a FROM comment WHERE id = ?1").get(reply.value.id)?.a).toBe(FORMER_ID); | |
| 85 | // The placeholder can never sign in, nor own a page that reads as a person's. | |
| 86 | const former = getUserById(app.db, FORMER_ID)!; | |
| 87 | expect(former.removedAt).not.toBeNull(); | |
| 88 | expect(app.db.query<{ h: string }, [string]>("SELECT password_hash AS h FROM user WHERE id = ?1").get(FORMER_ID)?.h).toBe(""); | |
| 89 | // One audit line, counts only. | |
| 90 | const lines = events("account.purged"); | |
| 91 | expect(lines.length).toBe(1); | |
| 92 | expect(JSON.stringify(lines[0])).not.toContain("bob"); | |
| 93 | expect(lines[0]).toMatchObject({ repos: 1, sessions: 1, tokens: 1 }); | |
| 94 | // Nothing of theirs is left in the outbox outside a repository's history. | |
| 95 | expect(count("event WHERE actor_id = ?1", bob.id)).toBe(0); | |
| 96 | }); | |
| 97 | ||
| 98 | test("a second run does nothing", async () => { | |
| 99 | const before = count("event"); | |
| 100 | const again = await purgeDue(app, at(8)); | |
| 101 | expect(again).toEqual({ findings: [], actions: [] }); | |
| 102 | expect(count("event")).toBe(before); | |
| 103 | }); | |
| 104 | ||
| 105 | test("a person who pressed Keep my account is never purged", async () => { | |
| 106 | const dave = await make("dave"); | |
| 107 | requestClose(app.db, dave.id, T0); | |
| 108 | expect(keepAccount(app.db, dave.id)).toBe(true); | |
| 109 | await purgeDue(app, at(30)); | |
| 110 | expect(getUserById(app.db, dave.id)).toBeDefined(); | |
| 111 | }); | |
| 112 | ||
| 113 | test("a held account is named, does not stop the others, and waits a day", async () => { | |
| 114 | // Alice is the forge's only admin: closing would leave it with none. | |
| 115 | const alice = app.db.query<{ id: string }, []>("SELECT id FROM user WHERE username = 'alice'").get()!; | |
| 116 | const erin = await make("erin"); | |
| 117 | app.db.query("UPDATE user SET close_requested_at = ?1 WHERE id IN (?2, ?3)").run(T0.toISOString(), alice.id, erin.id); | |
| 118 | const run = await purgeDue(app, at(7)); | |
| 119 | expect(run.findings[0]!.summary).toBe("2 closed accounts past their 7 days: 1 erased, 1 held"); | |
| 120 | expect(run.actions).toContain("Held alice: held (sole_admin): You are this forge's only admin: make someone else an admin first."); | |
| 121 | expect(getUserById(app.db, alice.id)).toBeDefined(); | |
| 122 | expect(getUserById(app.db, erin.id)).toBeUndefined(); | |
| 123 | expect(events("account.purge_failed").at(-1)).toMatchObject({ username: "alice" }); | |
| 124 | // Tried an hour later, alice is not due; a day later she is tried again. | |
| 125 | expect(duePurges(app.db, at(7, 3_600_000)).length).toBe(0); | |
| 126 | expect(duePurges(app.db, at(8)).map((u) => u.id)).toEqual([alice.id]); | |
| 127 | app.db.query("UPDATE user SET close_requested_at = NULL WHERE id = ?1").run(alice.id); | |
| 128 | }); | |
| 129 | ||
| 130 | test("at most twenty accounts a run", async () => { | |
| 131 | const insert = app.db.query("INSERT INTO user (id, username, email, password_hash, close_requested_at) VALUES (?1, ?2, ?3, '', ?4)"); | |
| 132 | for (let i = 0; i < PURGE_BATCH + 5; i++) insert.run(`many-${i}`, `many${i}`, `many${i}@forge.local`, T0.toISOString()); | |
| 133 | const first = await purgeDue(app, at(7)); | |
| 134 | expect(first.actions.length).toBe(PURGE_BATCH); | |
| 135 | expect(count("user WHERE id LIKE 'many-%'")).toBe(5); | |
| 136 | await purgeDue(app, at(7, 3_600_000)); | |
| 137 | expect(count("user WHERE id LIKE 'many-%'")).toBe(0); | |
| 138 | }); | |
| 139 | }); | |
| 140 | ||
| 141 | describe("a held account", () => { | |
| 142 | test("a fork that heads a pull elsewhere holds the purge before anything is deleted, once in the audit", async () => { | |
| 143 | const owner = await make("gina"); | |
| 144 | const frank = await make("frank"); | |
| 145 | const base = await createRepo(app.db, app.reposRoot, { ownerId: owner.id, name: "orchard", visibility: "public" }); | |
| 146 | const fork = await createRepo(app.db, app.reposRoot, { ownerId: frank.id, name: "orchard-fork" }); | |
| 147 | const plain = await createRepo(app.db, app.reposRoot, { ownerId: frank.id, name: "diary" }); | |
| 148 | if (!base.ok || !fork.ok || !plain.ok) throw new Error("repos"); | |
| 149 | const pr = createIssue(app.db, { repoId: base.value.id, authorId: frank.id, title: "Prune the pears" }); | |
| 150 | if (!pr.ok) throw new Error("issue"); | |
| 151 | app.db | |
| 152 | .query("INSERT INTO pull (issue_id, base_branch, head_branch, base_oid, head_oid, head_repo_id) VALUES (?1, 'main', 'pears', '', '', ?2)") | |
| 153 | .run(pr.value.id, fork.value.id); | |
| 154 | createSession(app.db, frank.id); | |
| 155 | requestClose(app.db, frank.id, T0); | |
| 156 | const before = events("account.purge_failed").length; | |
| 157 | ||
| 158 | const first = await purgeDue(app, at(7)); | |
| 159 | expect(first.actions.join("\n")).toContain("Held frank: held (pull_head): frank/orchard-fork is the head of a pull into another repository"); | |
| 160 | // Nothing went: not the other repository, not a browser. | |
| 161 | expect(getRepoById(app.db, plain.value.id)).toBeDefined(); | |
| 162 | expect(count("session WHERE user_id = ?1", frank.id)).toBe(1); | |
| 163 | // /maintenance names it, every run, even one with nothing due. | |
| 164 | const quiet = await purgeDue(app, at(7, 3_600_000)); | |
| 165 | expect(quiet.actions).toEqual([]); | |
| 166 | expect(quiet.findings.map((f) => f.summary).join("\n")).toContain("closed accounts held past their grace, for an admin: frank (held (pull_head)"); | |
| 167 | // The daily retries hold for the same reason: one audit line, not one a day. | |
| 168 | await purgeDue(app, at(8)); | |
| 169 | await purgeDue(app, at(9)); | |
| 170 | expect(events("account.purge_failed").length).toBe(before + 1); | |
| 171 | expect(heldPurges(app.db).map((h) => h.username)).toContain("frank"); | |
| 172 | // The person's page says it is held, not a day that has passed. | |
| 173 | const state = closeState(app.db, frank.id); | |
| 174 | expect(state.held).toBe(true); | |
| 175 | expect(closingSays(state.at!, state.held)).toBe("This account was due to close on 2026-11-08. It is held, and an admin will look."); | |
| 176 | ||
| 177 | // An admin moves the fork to an owner who keeps it: the next retry erases the rest. | |
| 178 | const admin = getUserById(app.db, app.db.query<{ id: string }, []>("SELECT id FROM user WHERE username = 'alice'").get()!.id)!; | |
| 179 | const moved = await transferRepository(app, admin, getRepoById(app.db, fork.value.id)!, "gina"); | |
| 180 | expect(moved.ok).toBe(true); | |
| 181 | const done = await purgeDue(app, at(10)); | |
| 182 | expect(done.actions[0]).toStartWith("Erased an account: 1 repositories"); | |
| 183 | expect(getUserById(app.db, frank.id)).toBeUndefined(); | |
| 184 | expect(getRepoById(app.db, plain.value.id)).toBeUndefined(); | |
| 185 | expect(heldPurges(app.db).map((h) => h.username)).not.toContain("frank"); | |
| 186 | }); | |
| 187 | ||
| 188 | test("Keep my account clears the hold with the request", async () => { | |
| 189 | const hal = await make("hal"); | |
| 190 | requestClose(app.db, hal.id, T0); | |
| 191 | app.db.query("UPDATE user SET purge_tried_at = ?1, purge_held_why = 'x' WHERE id = ?2").run(T0.toISOString(), hal.id); | |
| 192 | expect(keepAccount(app.db, hal.id)).toBe(true); | |
| 193 | expect(app.db.query("SELECT purge_tried_at AS t, purge_held_why AS w FROM user WHERE id = ?1").get(hal.id)).toEqual({ t: null, w: null }); | |
| 194 | expect(closingSays(T0.toISOString())).toBe("This account closes on 2026-11-08."); | |
| 195 | }); | |
| 196 | }); | |
| 197 | ||
| 198 | describe("what stays names nobody", () => { | |
| 199 | test("a kept event's payload loses the username, the id and the person's paths, and a longer name is untouched", async () => { | |
| 200 | const ivy = await make("ivy"); | |
| 201 | const ivan = await make("ivyleaf"); | |
| 202 | const host = await createRepo(app.db, app.reposRoot, { ownerId: ivan.id, name: "hedge", visibility: "public" }); | |
| 203 | if (!host.ok) throw new Error("repo"); | |
| 204 | app.bus.append({ | |
| 205 | kind: "label.created", | |
| 206 | repoId: host.value.id, | |
| 207 | actorId: ivan.id, | |
| 208 | payload: { by: "ivy", who: ivy.id, from: "ivy/old", other: "ivyleaf", note: "ivy wrote this" }, | |
| 209 | }); | |
| 210 | requestClose(app.db, ivy.id, T0); | |
| 211 | const run = await purgeDue(app, at(7)); | |
| 212 | expect(run.actions[0]).toContain("1 events now a former member's"); | |
| 213 | const kept = app.db | |
| 214 | .query<{ payload: string }, [string]>("SELECT payload FROM event WHERE repo_id = ?1 AND kind = 'label.created'") | |
| 215 | .get(host.value.id)!; | |
| 216 | expect(JSON.parse(kept.payload)).toEqual({ by: FORMER_NAME, who: FORMER_ID, from: `${FORMER_NAME}/old`, other: "ivyleaf", note: "ivy wrote this" }); | |
| 217 | }); | |
| 218 | }); | |
| 219 | ||
| 220 | describe("every column that names a user is covered", () => { | |
| 221 | test("by its cascade or by a row of COVERED", () => { | |
| 222 | // A new table that holds a user id with no ON DELETE CASCADE / SET NULL | |
| 223 | // fails here: add its column to COVERED in src/core/account_purge.ts. | |
| 224 | expect(uncovered(app.db)).toEqual([]); | |
| 225 | }); | |
| 226 | ||
| 227 | test("and COVERED names no column that is gone", () => { | |
| 228 | const columns = new Set(userColumns(app.db).filter((c) => !cascades(c)).map((c) => `${c.table}.${c.column}`)); | |
| 229 | expect(Object.keys(COVERED).filter((k) => !columns.has(k))).toEqual([]); | |
| 230 | }); | |
| 231 | ||
| 232 | test("the rewrites of tables that grow walk an index", () => { | |
| 233 | for (const [table, column] of [["event", "actor_id"], ["issue", "author_id"], ["comment", "author_id"], ["review", "author_id"], ["run", "actor_id"]] as const) { | |
| 234 | const plan = app.db.query<{ detail: string }, [string]>(`EXPLAIN QUERY PLAN SELECT 1 FROM "${table}" WHERE "${column}" = ?1`).all("x").map((r) => r.detail).join(" "); | |
| 235 | expect(plan).not.toContain("SCAN"); | |
| 236 | } | |
| 237 | }); | |
| 238 | }); |
test/pages-budget.test.ts +2 −2
| @@ -60,8 +60,8 @@ const HEAVIER: Record<string, { statements?: number; git?: number }> = { | ||
| 60 | 60 | "/api/v1/asks": { statements: 61 }, // +1: the stopped apps someone asked for, one read of the viewer's archived repositories (#12277) |
| 61 | 61 | "/board": { statements: 72 }, // +1: the forge-copy read for the tell box (#12037); +1: the vitals read the database's growth (#12025); +6: the money line (#510) — one settings read, then the month's and the 30 days' meter, storage and ledger reads; constant in the number of apps |
| 62 | 62 | "/settings/capacity": { statements: 70 }, |
| 63 | "/maintenance": { statements: 93 }, // +3: daily-proof (#15625); +3: deepsec-sweep (#15026); +3: edge-kept (#14682), one more duty reading its own state; +1: every duty's last run in one query (#14674); +1: quieted findings (#14557); +1: the findings fold (#14577); +5: slow-tests (#13966); +3: untested-sources (#14125) and the dismissal query (#13967); +4: flaky-tests (#13937), red apps (#13938), chapter stall (#14057), dead-doc-paths (#13977); +3: stale-branches (#14141) — each reads its own state and runs | |
| 64 | "/api/v1/maintenance/duties": { statements: 75 }, // the same duties as JSON; slow-tests (#13966), stale-branches (#14141), edge-kept (#14682), deepsec-sweep (#15026) and daily-proof (#15625) each add 3 | |
| 63 | "/maintenance": { statements: 96 }, // +3: account-purge (#15620); +3: daily-proof (#15625); +3: deepsec-sweep (#15026); +3: edge-kept (#14682), one more duty reading its own state; +1: every duty's last run in one query (#14674); +1: quieted findings (#14557); +1: the findings fold (#14577); +5: slow-tests (#13966); +3: untested-sources (#14125) and the dismissal query (#13967); +4: flaky-tests (#13937), red apps (#13938), chapter stall (#14057), dead-doc-paths (#13977); +3: stale-branches (#14141) — each reads its own state and runs | |
| 64 | "/api/v1/maintenance/duties": { statements: 78 }, // the same duties as JSON; slow-tests (#13966), stale-branches (#14141), edge-kept (#14682), deepsec-sweep (#15026), daily-proof (#15625) and account-purge (#15620) each add 3 | |
| 65 | 65 | }; |
| 66 | 66 | |
| 67 | 67 | /** Patterns with no fixture today: lower this as fixtures are added, never raise it silently. */ |
new above
offline