Public: anyone can read this; the crew can change it.
A person asks to close their account, with a 7-day grace and a one-tap undo #15677
Check · Review · Land · Live done — Landed and live in production.
scout/forge:scout/15619-a-person-asks-to-close-their-account-wit → main 0 commits fork 4 threads · 4 unresolved
20 files
changed +732
−18
src/actions/account_close.ts added +257
| @@ -0,0 +1,257 @@ | ||
| 1 | /** | |
| 2 | * Closing an account is a request that waits (#15619): asking records | |
| 3 | * `user.close_requested_at`, the account closes `GRACE_DAYS` later, and | |
| 4 | * Keep my account clears it. Nothing is deleted here; the purge is its own | |
| 5 | * change. Both doors, the page and the terminal, ask through `askToClose` | |
| 6 | * with what the person typed and how they proved it is them, and say the | |
| 7 | * answer in `CLOSE_WORDS` or the refusal's own sentence. A password is | |
| 8 | * verified here, through the sign-in throttle; a passkey is verified by the | |
| 9 | * page's ceremony before it calls, since only a browser can hold one. | |
| 10 | */ | |
| 11 | ||
| 12 | import type { Database } from "bun:sqlite"; | |
| 13 | import type { App } from "../app.ts"; | |
| 14 | import { challenges, verifyAssertion } from "../auth/webauthn.ts"; | |
| 15 | import { findPasskey, notePasskeyUsed, passkeyIds } from "../core/passkeys.ts"; | |
| 16 | import { hasPassword, verifyPasswordThrottled, type User } from "../core/users.ts"; | |
| 17 | import { signOutElsewhere, signOutEveryBrowser } from "./signins.ts"; | |
| 18 | ||
| 19 | /** How long a close request waits before the account closes. */ | |
| 20 | export const GRACE_DAYS = 7; | |
| 21 | const DAY_MS = 86_400_000; | |
| 22 | ||
| 23 | /** Why a close is refused now: one plain sentence and where to fix it. */ | |
| 24 | export interface CloseRefusal { | |
| 25 | readonly reason: "sole_admin" | "shared_repo" | "subscription"; | |
| 26 | readonly says: string; | |
| 27 | readonly link: { readonly href: string; readonly label: string }; | |
| 28 | } | |
| 29 | ||
| 30 | /** When this person asked to close, or null when they have not. */ | |
| 31 | export function closeRequestedAt(db: Database, userId: string): string | null { | |
| 32 | return ( | |
| 33 | db | |
| 34 | .query<{ at: string | null }, [string]>("SELECT close_requested_at AS at FROM user WHERE id = ?1") | |
| 35 | .get(userId)?.at ?? null | |
| 36 | ); | |
| 37 | } | |
| 38 | ||
| 39 | /** The day a request made at `at` closes the account, as YYYY-MM-DD. */ | |
| 40 | export function closesOn(at: string): string { | |
| 41 | return new Date(Date.parse(at) + GRACE_DAYS * DAY_MS).toISOString().slice(0, 10); | |
| 42 | } | |
| 43 | ||
| 44 | /** The sentence the account page and the first page after sign-in show. */ | |
| 45 | export function closingSays(at: string): string { | |
| 46 | return `This account closes on ${closesOn(at)}.`; | |
| 47 | } | |
| 48 | ||
| 49 | /** | |
| 50 | * What stands in front of closing, the first that applies: being the forge's | |
| 51 | * only admin, being the only admin of an organization whose repositories | |
| 52 | * other people write to, or paying for a forge whose plan is still running. | |
| 53 | */ | |
| 54 | export function closeRefusal(db: Database, user: { id: string; email: string; isAdmin: boolean }): CloseRefusal | undefined { | |
| 55 | if (user.isAdmin && otherAdmins(db, user.id) === 0) | |
| 56 | return { | |
| 57 | reason: "sole_admin", | |
| 58 | says: "You are this forge's only admin: make someone else an admin first.", | |
| 59 | link: { href: "/settings/accounts", label: "Accounts" }, | |
| 60 | }; | |
| 61 | const org = sharedOrg(db, user.id); | |
| 62 | if (org !== undefined) | |
| 63 | return { | |
| 64 | reason: "shared_repo", | |
| 65 | says: `Other people write to ${org}'s repositories and you are its only admin: give its admin team to someone else first.`, | |
| 66 | link: { href: `/${encodeURIComponent(org)}`, label: org }, | |
| 67 | }; | |
| 68 | const forge = paidForge(db, user.email); | |
| 69 | if (forge !== undefined) | |
| 70 | return { | |
| 71 | reason: "subscription", | |
| 72 | says: `You still pay for ${forge}: cancel that subscription first.`, | |
| 73 | link: { href: "/settings/payments", label: "Payments" }, | |
| 74 | }; | |
| 75 | return undefined; | |
| 76 | } | |
| 77 | ||
| 78 | /** Record the request; false when there is no such person or one already stands. */ | |
| 79 | export function requestClose(db: Database, userId: string, now = new Date()): boolean { | |
| 80 | return ( | |
| 81 | db | |
| 82 | .query("UPDATE user SET close_requested_at = ?1 WHERE id = ?2 AND kind = 'user' AND close_requested_at IS NULL") | |
| 83 | .run(now.toISOString(), userId).changes > 0 | |
| 84 | ); | |
| 85 | } | |
| 86 | ||
| 87 | /** Clear the request (Keep my account); false when none stood. */ | |
| 88 | export function keepAccount(db: Database, userId: string): boolean { | |
| 89 | return ( | |
| 90 | db | |
| 91 | .query("UPDATE user SET close_requested_at = NULL WHERE id = ?1 AND close_requested_at IS NOT NULL") | |
| 92 | .run(userId).changes > 0 | |
| 93 | ); | |
| 94 | } | |
| 95 | ||
| 96 | /** Keep my account, as a receipt: clears the request and records `account.close_kept`. */ | |
| 97 | export function keepMyAccount(app: App, user: { id: string; username: string }): boolean { | |
| 98 | const kept = keepAccount(app.db, user.id); | |
| 99 | if (kept) app.bus.append({ kind: "account.close_kept", actorId: user.id, payload: { username: user.username } }); | |
| 100 | return kept; | |
| 101 | } | |
| 102 | ||
| 103 | /** The words Keep my account answers with, for the page and the terminal. */ | |
| 104 | export const keptSays = (kept: boolean): string => | |
| 105 | kept ? "Your account stays: the close request is cleared." : "Your account was not closing."; | |
| 106 | ||
| 107 | /** How the person showed it is them: their password, or a passkey the page has verified. */ | |
| 108 | export type CloseProof = { readonly password: string; readonly source: string } | { readonly passkey: true }; | |
| 109 | ||
| 110 | export type CloseAsk = | |
| 111 | | { readonly ok: true; readonly at: string } | |
| 112 | | { readonly ok: false; readonly error: "username" | "password" | "no_password" } | |
| 113 | | { readonly ok: false; readonly error: "refused"; readonly refusal: CloseRefusal }; | |
| 114 | ||
| 115 | /** The words for each refusal that is not a standing reason. */ | |
| 116 | export const CLOSE_WORDS = { | |
| 117 | username: (username: string) => `Type ${username} exactly to confirm.`, | |
| 118 | password: "That password is not right.", | |
| 119 | no_password: "This account has no password: close it with a passkey, on Settings › Password.", | |
| 120 | } as const; | |
| 121 | ||
| 122 | /** | |
| 123 | * Check the typed username and the proof, then what stands in front of | |
| 124 | * closing; record the request and end the person's other browsers. `current` | |
| 125 | * is the browser session to keep; without it (the terminal) every browser ends. | |
| 126 | */ | |
| 127 | export async function askToClose( | |
| 128 | app: App, | |
| 129 | user: User, | |
| 130 | typed: { readonly username: string; readonly proof: CloseProof; readonly current?: string | undefined }, | |
| 131 | ): Promise<CloseAsk> { | |
| 132 | if (typed.username !== user.username) return { ok: false, error: "username" }; | |
| 133 | if ("password" in typed.proof) { | |
| 134 | if (!hasPassword(app.db, user.id)) return { ok: false, error: "no_password" }; | |
| 135 | const verified = await verifyPasswordThrottled(app.db, { | |
| 136 | username: user.username, | |
| 137 | password: typed.proof.password, | |
| 138 | source: typed.proof.source, | |
| 139 | }); | |
| 140 | if (!verified.ok || verified.value.id !== user.id) return { ok: false, error: "password" }; | |
| 141 | } | |
| 142 | const refusal = closeRefusal(app.db, user); | |
| 143 | if (refusal !== undefined) return { ok: false, error: "refused", refusal }; | |
| 144 | if (requestClose(app.db, user.id)) { | |
| 145 | app.bus.append({ kind: "account.close_requested", actorId: user.id, payload: { username: user.username } }); | |
| 146 | if (typed.current === undefined) signOutEveryBrowser(app, user); | |
| 147 | else signOutElsewhere(app, user, typed.current); | |
| 148 | } | |
| 149 | return { ok: true, at: closeRequestedAt(app.db, user.id)! }; | |
| 150 | } | |
| 151 | ||
| 152 | /* | |
| 153 | * A passkey confirms a close as a password does: the page asks for a | |
| 154 | * challenge, the browser signs it, and the signed answer rides back in the | |
| 155 | * close form's hidden fields, so the close stays one plain post. A challenge | |
| 156 | * answers once, and the key must be one of this person's. | |
| 157 | */ | |
| 158 | const closeChallenges = new WeakMap<App, ReturnType<typeof challenges>>(); | |
| 159 | function closeStore(app: App): ReturnType<typeof challenges> { | |
| 160 | let s = closeChallenges.get(app); | |
| 161 | if (s === undefined) closeChallenges.set(app, (s = challenges())); | |
| 162 | return s; | |
| 163 | } | |
| 164 | ||
| 165 | /** The hidden fields the signed answer fills, by name. */ | |
| 166 | export const PROOF_FIELDS = ["challenge", "id", "clientDataJSON", "authenticatorData", "signature"] as const; | |
| 167 | ||
| 168 | /** | |
| 169 | * What the close block needs to know, in one statement: the request, and which proofs this person | |
| 170 | * has. | |
| 171 | */ | |
| 172 | export interface CloseStanding { | |
| 173 | readonly at: string | null; | |
| 174 | readonly password: boolean; | |
| 175 | readonly passkey: boolean; | |
| 176 | } | |
| 177 | export function closeStanding(db: Database, userId: string): CloseStanding { | |
| 178 | const r = db | |
| 179 | .query<{ at: string | null; password: number; passkey: number }, [string]>( | |
| 180 | `SELECT close_requested_at AS at, | |
| 181 | (password_hash <> '' AND kind <> 'org' AND is_agent = 0) AS password, | |
| 182 | EXISTS (SELECT 1 FROM passkey WHERE user_id = user.id) AS passkey | |
| 183 | FROM user WHERE id = ?1`, | |
| 184 | ) | |
| 185 | .get(userId); | |
| 186 | return { at: r?.at ?? null, password: r?.password === 1, passkey: r?.passkey === 1 }; | |
| 187 | } | |
| 188 | ||
| 189 | /** A fresh challenge for this person, and the keys that may answer it. */ | |
| 190 | export function closeChallenge(app: App, userId: string): { challenge: string; allow: string[] } { | |
| 191 | return { challenge: closeStore(app).issue(userId), allow: passkeyIds(app.db, userId) }; | |
| 192 | } | |
| 193 | ||
| 194 | /** True when `answer` is a fresh challenge signed by one of `userId`'s passkeys. */ | |
| 195 | export async function passkeyProves( | |
| 196 | app: App, | |
| 197 | userId: string, | |
| 198 | answer: Readonly<Record<(typeof PROOF_FIELDS)[number], string>>, | |
| 199 | rp: { readonly origin: string; readonly rpId: string }, | |
| 200 | ): Promise<boolean> { | |
| 201 | if (!closeStore(app).consume(answer.challenge)) return false; | |
| 202 | const found = findPasskey(app.db, answer.id); | |
| 203 | if (found === undefined || found.userId !== userId) return false; | |
| 204 | const verified = await verifyAssertion(answer, { challenge: answer.challenge, ...rp }, found.credential); | |
| 205 | if (!verified.ok) return false; | |
| 206 | notePasskeyUsed(app.db, found.id, verified.signCount); | |
| 207 | return true; | |
| 208 | } | |
| 209 | ||
| 210 | /** The other admins who can still sign in and are not closing themselves. */ | |
| 211 | function otherAdmins(db: Database, userId: string): number { | |
| 212 | return ( | |
| 213 | db | |
| 214 | .query<{ n: number }, [string]>( | |
| 215 | `SELECT COUNT(*) AS n FROM user WHERE is_admin = 1 AND id <> ?1 AND kind = 'user' AND is_agent = 0 | |
| 216 | AND suspended_at IS NULL AND removed_at IS NULL AND close_requested_at IS NULL`, | |
| 217 | ) | |
| 218 | .get(userId)?.n ?? 0 | |
| 219 | ); | |
| 220 | } | |
| 221 | ||
| 222 | /** | |
| 223 | * An organization that owns a repository, where this person is on an admin | |
| 224 | * team, nobody else is, and another person is on a write or admin team. | |
| 225 | */ | |
| 226 | function sharedOrg(db: Database, userId: string): string | undefined { | |
| 227 | return ( | |
| 228 | db | |
| 229 | .query<{ name: string }, [string]>( | |
| 230 | `SELECT o.username AS name FROM user o | |
| 231 | JOIN team t ON t.org_id = o.id AND t.permission = 'admin' | |
| 232 | JOIN team_member m ON m.team_id = t.id AND m.user_id = ?1 | |
| 233 | WHERE o.kind = 'org' | |
| 234 | AND EXISTS (SELECT 1 FROM repo r WHERE r.owner_id = o.id) | |
| 235 | AND NOT EXISTS (SELECT 1 FROM team t2 JOIN team_member m2 ON m2.team_id = t2.id | |
| 236 | WHERE t2.org_id = o.id AND t2.permission = 'admin' AND m2.user_id <> ?1) | |
| 237 | AND EXISTS (SELECT 1 FROM team t3 JOIN team_member m3 ON m3.team_id = t3.id | |
| 238 | JOIN user p ON p.id = m3.user_id AND p.is_agent = 0 | |
| 239 | WHERE t3.org_id = o.id AND t3.permission IN ('write','admin') AND m3.user_id <> ?1) | |
| 240 | ORDER BY o.username LIMIT 1`, | |
| 241 | ) | |
| 242 | .get(userId)?.name | |
| 243 | ); | |
| 244 | } | |
| 245 | ||
| 246 | /** A forge this address pays for whose plan is still running. */ | |
| 247 | function paidForge(db: Database, email: string): string | undefined { | |
| 248 | if (email === "") return undefined; | |
| 249 | return ( | |
| 250 | db | |
| 251 | .query<{ forge: string }, [string]>( | |
| 252 | `SELECT forge FROM entitlement WHERE payer = ?1 COLLATE NOCASE AND status IN ('active','grace') | |
| 253 | AND provider <> 'none' ORDER BY forge LIMIT 1`, | |
| 254 | ) | |
| 255 | .get(email)?.forge | |
| 256 | ); | |
| 257 | } |
src/contract/openapi/routes/index.ts +1
| @@ -448,6 +448,7 @@ export { route as postApiV1UserOriginsOauth } from "./postApiV1UserOriginsOauth. | ||
| 448 | 448 | export { route as postApiV1UserPassword } from "./postApiV1UserPassword.ts"; |
| 449 | 449 | export { route as postApiV1Users } from "./postApiV1Users.ts"; |
| 450 | 450 | export { route as postMcp } from "./postMcp.ts"; |
| 451 | export { route as postSettingsAccountCloseOptions } from "./postSettingsAccountCloseOptions.ts"; | |
| 451 | 452 | export { route as putApiV1AdminBillingLinks } from "./putApiV1AdminBillingLinks.ts"; |
| 452 | 453 | export { route as putApiV1AdminCapacityKey } from "./putApiV1AdminCapacityKey.ts"; |
| 453 | 454 | export { route as putApiV1AdminLimitsKey } from "./putApiV1AdminLimitsKey.ts"; |
src/contract/openapi/routes/postSettingsAccountCloseOptions.ts added +13
| @@ -0,0 +1,13 @@ | ||
| 1 | import type { Route } from "../shared.ts"; | |
| 2 | ||
| 3 | export const route: Route = { | |
| 4 | method: "post", | |
| 5 | path: "/settings/account/close/options", | |
| 6 | summary: "A passkey challenge to confirm closing your own account (browser session, same origin)", | |
| 7 | detail: | |
| 8 | "Issues a one-use challenge and the ids of the caller's passkeys; the signed answer goes into the close form at /settings/account/close (#15619).", | |
| 9 | auth: false, | |
| 10 | role: "member", | |
| 11 | reply: { challenge: "string", allow: "array", rpId: "string" }, | |
| 12 | errorStatus: { 401: "Not signed in to the account itself", 403: "The request came from another origin" }, | |
| 13 | }; |
src/contract/tags.ts +1
| @@ -84,6 +84,7 @@ const ALIAS: Readonly<Record<string, string>> = { | ||
| 84 | 84 | usage: "billing", |
| 85 | 85 | forge: "forges", |
| 86 | 86 | passport: "user", |
| 87 | settings: "user", | |
| 87 | 88 | "proposal-tokens": "tokens", |
| 88 | 89 | asked: "asks", |
| 89 | 90 | decisions: "runs", |
src/core/account_export.ts +1
| @@ -37,6 +37,7 @@ export const COLUMNS: Record<string, { exported: readonly string[]; withheld: Re | ||
| 37 | 37 | suspended_at: "a moderator's record", |
| 38 | 38 | removed_at: "a moderator's record", |
| 39 | 39 | waiting_at: "a moderator's record", |
| 40 | close_requested_at: "a pending close, said on the account page", | |
| 40 | 41 | }, |
| 41 | 42 | }, |
| 42 | 43 | user_key: { |
src/core/event_audience.ts +3
| @@ -369,6 +369,9 @@ export function classifiedAudience(kind: string): EventAudience | undefined { | ||
| 369 | 369 | kind === "forge.claim_renewal_note" || |
| 370 | 370 | // A person signed their other browsers out (`actions/signins.ts`): their own receipt. |
| 371 | 371 | kind === "account.signed_out_elsewhere" || |
| 372 | // A person asked to close their account, or kept it (#15619): their own receipt. | |
| 373 | kind === "account.close_requested" || | |
| 374 | kind === "account.close_kept" || | |
| 372 | 375 | kind.startsWith("thought.") |
| 373 | 376 | ) |
| 374 | 377 | return "actor"; |
src/core/migration-pins/20261122090000-account-close-request.pin added +1
| @@ -0,0 +1,1 @@ | ||
| 1 | 68f52959314c9df0551adc961bb25cede2ea005888000b855ce714873088476d |
src/core/migrations/20261122090000-account-close-request.ts added +5
| @@ -0,0 +1,5 @@ | ||
| 1 | // When a person asked to close their account (#15619): the account closes seven days later | |
| 2 | // unless they keep it. Nothing is deleted here; the purge is its own change. | |
| 3 | export default ` | |
| 4 | ALTER TABLE user ADD COLUMN close_requested_at TEXT; | |
| 5 | `; |
src/http/marks/settings.json +3
| @@ -19,6 +19,9 @@ | ||
| 19 | 19 | "/settings/email/verify": "open", |
| 20 | 20 | "/settings/appearance": "open", |
| 21 | 21 | "/settings/password": "open", |
| 22 | "/settings/account/close": "open", | |
| 23 | "/settings/account/keep": "open", | |
| 24 | "/settings/account/close/options": "open", | |
| 22 | 25 | "/settings/everyday": "open", |
| 23 | 26 | "/settings/everyday/options": "admin", |
| 24 | 27 | "/settings/everyday/switch": "open", |
src/http/settings_routes.ts +7
| @@ -104,6 +104,9 @@ import { | ||
| 104 | 104 | crewPage, |
| 105 | 105 | } from "../web/pages/crew.ts"; |
| 106 | 106 | import { |
| 107 | accountClose, | |
| 108 | accountKeep, | |
| 109 | closeOptions, | |
| 107 | 110 | accountPage, |
| 108 | 111 | appearancePage, |
| 109 | 112 | shellsPage, |
| @@ -164,6 +167,10 @@ export function settingsRoutes(router: Router<Handler>, knownPatterns: () => rea | ||
| 164 | 167 | router.add("POST", "/settings/telemetry", telemetrySet); |
| 165 | 168 | router.add("GET", "/settings", accountPage); |
| 166 | 169 | router.add("POST", "/settings", accountUpdate); |
| 170 | // Closing waits seven days and Keep my account undoes it (#15619). | |
| 171 | router.add("POST", "/settings/account/close", accountClose); | |
| 172 | router.add("POST", "/settings/account/keep", accountKeep); | |
| 173 | router.add("POST", "/settings/account/close/options", closeOptions); | |
| 167 | 174 | router.add("POST", "/settings/notify", notifyUpdate); |
| 168 | 175 | router.add("POST", "/settings/dotfiles", dotfilesUpdate); |
| 169 | 176 | router.add("POST", "/settings/edge/link", edgeLink); |
src/web/pages/account.ts +138 −4
| @@ -47,7 +47,8 @@ import { ACTS_AS_ADMIN_WORDS, ADMIN_TOKEN_WORDS, type TokenScope } from "../../c | ||
| 47 | 47 | import { claudeInstall, opencodeInstall } from "../../core/plugin_install.ts"; |
| 48 | 48 | import type { CommitEmail, User } from "../../core/users.ts"; |
| 49 | 49 | import { isStandInEmail } from "../../core/users.ts"; |
| 50 | import { cookieValue, isAccountItself, type Ctx } from "../../http/context.ts"; | |
| 50 | import { cookieValue, crossOrigin, isAccountItself, type Ctx } from "../../http/context.ts"; | |
| 51 | import { json } from "../../http/respond.ts"; | |
| 51 | 52 | import { notePhase, takeSessionTime, timePhase } from "../../core/route_timing.ts"; |
| 52 | 53 | import { offeredPluginRepo } from "../../core/mcp_card.ts"; |
| 53 | 54 | import { publicOrigin } from "../../core/public_origin.ts"; |
| @@ -57,10 +58,29 @@ import { | ||
| 57 | 58 | settingsLayout, |
| 58 | 59 | signInFirst, |
| 59 | 60 | type SettingsSection, |
| 61 | CAME_FROM_ELSEWHERE, | |
| 60 | 62 | forbiddenPage, |
| 61 | 63 | notFoundPage, |
| 62 | 64 | } from "../chrome.ts"; |
| 63 | 65 | import { accountSections } from "./origins.ts"; |
| 66 | import { | |
| 67 | askToClose, | |
| 68 | CLOSE_WORDS, | |
| 69 | GRACE_DAYS, | |
| 70 | closeRequestedAt, | |
| 71 | closingSays, | |
| 72 | keepMyAccount, | |
| 73 | keptSays, | |
| 74 | closeChallenge, | |
| 75 | closeStanding, | |
| 76 | type CloseStanding, | |
| 77 | passkeyProves, | |
| 78 | PROOF_FIELDS, | |
| 79 | type CloseProof, | |
| 80 | type CloseRefusal, | |
| 81 | } from "../../actions/account_close.ts"; | |
| 82 | import { passkeyNote } from "../passkey-state.ts"; | |
| 83 | import { PASSKEY_REJECTED } from "../passkey-words.ts"; | |
| 64 | 84 | import { field, kept, readForm, refused, type Form, type Refused } from "../form.ts"; |
| 65 | 85 | import { html, when, type Html } from "../html.ts"; |
| 66 | 86 | import { mailCappedBlocked, noMailBlocked } from "../../actions/blocked_words.ts"; |
| @@ -613,7 +633,7 @@ export function accountPage(ctx: Ctx): Response { | ||
| 613 | 633 | ctx, |
| 614 | 634 | "profile", |
| 615 | 635 | "Settings", |
| 616 | html`${plan}${pair}${profile}${edge}${parent}${notify}${billsBlock(ctx.app, user)}`, | |
| 636 | html`${plan}${pair}${profile}${edge}${parent}${notify}${billsBlock(ctx.app, user)}${closingNotice(ctx)}`, | |
| 617 | 637 | 200, |
| 618 | 638 | // The everyday form makes its account with a passkey (#1890). |
| 619 | 639 | pair ? passkeyJs : undefined, |
| @@ -732,8 +752,10 @@ function passwordView(error?: { | ||
| 732 | 752 | export function passwordPage(ctx: Ctx): Response { |
| 733 | 753 | if (!ctx.auth.user) return signInFirst(ctx); |
| 734 | 754 | notePhase(ctx.request, "session", takeSessionTime(ctx.request)); |
| 735 | const body = passwordView(); | |
| 736 | return timePhase(ctx.request, "render", () => accountShell(ctx, "password", "Password", body)); | |
| 755 | const standing = closeStanding(ctx.app.db, ctx.auth.user.id); | |
| 756 | const body = html`${passwordView()}${closeView(ctx, standing)}`; | |
| 757 | const script = standing.passkey ? passkeyJs : undefined; | |
| 758 | return timePhase(ctx.request, "render", () => accountShell(ctx, "password", "Password", body, 200, script)); | |
| 737 | 759 | } |
| 738 | 760 | |
| 739 | 761 | // POST /settings/password |
| @@ -1139,3 +1161,115 @@ export async function keyDelete(ctx: Ctx): Promise<Response> { | ||
| 1139 | 1161 | : { tone: "danger" as const, message: "No such key." }), |
| 1140 | 1162 | }); |
| 1141 | 1163 | } |
| 1164 | ||
| 1165 | // ---- closing the account (#15619) ---- | |
| 1166 | ||
| 1167 | // POST /settings/account/close/options — a challenge, and the keys that may answer it. | |
| 1168 | export function closeOptions(ctx: Ctx): Response { | |
| 1169 | if (crossOrigin(ctx.request, ctx.url, ctx.app.log)) return json({ error: "refused", message: CAME_FROM_ELSEWHERE }, 403); | |
| 1170 | const user = ctx.auth.user; | |
| 1171 | if (user === undefined || !isAccountItself(ctx.auth)) | |
| 1172 | return json({ error: "refused", message: "Sign in to your account first." }, 401); | |
| 1173 | return json({ ...closeChallenge(ctx.app, user.id), rpId: ctx.url.hostname }); | |
| 1174 | } | |
| 1175 | ||
| 1176 | /** While a close request stands, the day it closes and Keep my account; nothing otherwise. */ | |
| 1177 | function closingNotice(ctx: Ctx, at = closeRequestedAt(ctx.app.db, ctx.auth.user!.id)): Html | null { | |
| 1178 | if (at === null) return null; | |
| 1179 | return block( | |
| 1180 | "Close account", | |
| 1181 | html`<p data-closing>${closingSays(at)}</p> | |
| 1182 | <form method="post" action="/settings/account/keep"> | |
| 1183 | <div class="form-actions">${btn("Keep my account", { variant: "primary" })}</div> | |
| 1184 | </form>`, | |
| 1185 | ); | |
| 1186 | } | |
| 1187 | ||
| 1188 | /** | |
| 1189 | * What the close form says back: a field the person got wrong, or a reason that stands, with its | |
| 1190 | * link. | |
| 1191 | */ | |
| 1192 | type CloseSaid = | |
| 1193 | | { readonly field: "password" | "username"; readonly text: string; readonly form: Form } | |
| 1194 | | { readonly stands: { readonly says: string; readonly link?: CloseRefusal["link"] }; readonly form: Form }; | |
| 1195 | ||
| 1196 | /** | |
| 1197 | * Close my account, on the password page since the password or a passkey | |
| 1198 | * confirms it (the settings page keeps its first-view budget), or the | |
| 1199 | * closing notice. A passkey-only account gets the passkey button alone. | |
| 1200 | */ | |
| 1201 | function closeView(ctx: Ctx, standing: CloseStanding, said?: CloseSaid): Html { | |
| 1202 | const notice = closingNotice(ctx, standing.at); | |
| 1203 | if (notice !== null) return notice; | |
| 1204 | const { password, passkey } = standing; | |
| 1205 | const r = said === undefined ? undefined : refused(said.form, "field" in said ? { [said.field]: said.text } : {}); | |
| 1206 | const stands = said !== undefined && "stands" in said ? said.stands : undefined; | |
| 1207 | return block( | |
| 1208 | "Close account", | |
| 1209 | html`<p>Closing waits ${GRACE_DAYS} days and can be undone until then; nothing is deleted when you ask.</p> | |
| 1210 | <form method="post" action="/settings/account/close"> | |
| 1211 | ${when(password, () => | |
| 1212 | uiField(kept(r, { | |
| 1213 | label: "Your password", | |
| 1214 | name: "password", | |
| 1215 | type: "password", | |
| 1216 | autocomplete: "current-password", | |
| 1217 | required: !passkey, | |
outdated
A refusal is not a username error. Show it as its own sentence with its link, not attached to the username field (which then re-renders as if the typed username were wrong). |
||
| 1218 | })), | |
| 1219 | )} | |
| 1220 | ${uiField(kept(r, { label: "Type your username", name: "username", autocomplete: "off", required: true }))} | |
| 1221 | ${PROOF_FIELDS.map((n) => html`<input type="hidden" name="${n}" value="" />`)} | |
| 1222 | <div class="form-actions"> | |
| 1223 | ${when(password, () => btn("Close my account", { variant: "danger" }))} | |
| 1224 | ${when(passkey, () => html`<button type="button" id="passkey-close" class="btn" data-variant="${password ? "outline" : "danger"}" data-options="/settings/account/close/options" data-passkey="on" hidden>Close with a passkey</button>`)} | |
| 1225 | </div> | |
| 1226 | ${when(passkey, () => passkeyNote("passkey-close-note"))} | |
| 1227 | ${when(stands, (w) => html`<div class="toast" data-tone="danger" role="alert" data-refusal> | |
| 1228 | ${icon("alert")} | |
outdated
accountClose rejects an access code via isAccountItself; keep does not. Apply the same check. |
||
| 1229 | <div class="toast-body">${w.says}${when(w.link, (l) => html` · <a href="${l.href}">${l.label}</a>`)}</div> | |
| 1230 | </div>`)} | |
| 1231 | </form>`, | |
| 1232 | ); | |
| 1233 | } | |
| 1234 | ||
| 1235 | /** The password page with the close block saying why not, 422. */ | |
| 1236 | function closeRefused(ctx: Ctx, said: CloseSaid): Response { | |
| 1237 | const standing = closeStanding(ctx.app.db, ctx.auth.user!.id); | |
| 1238 | const body = html`${passwordView()}${closeView(ctx, standing, said)}`; | |
| 1239 | return accountShell(ctx, "password", "Password", body, 422, standing.passkey ? passkeyJs : undefined); | |
| 1240 | } | |
| 1241 | ||
| 1242 | // POST /settings/account/close | |
| 1243 | export async function accountClose(ctx: Ctx): Promise<Response> { | |
| 1244 | if (!ctx.auth.user) return signInFirst(ctx); | |
| 1245 | if (!isAccountItself(ctx.auth)) return forbiddenPage(ctx, CLOSE_ITSELF); | |
| 1246 | const user = ctx.auth.user; | |
| 1247 | const form = await readForm(ctx, "admin"); | |
| 1248 | if (form instanceof Response) return form; | |
| 1249 | const username = field(form, "username"); | |
| 1250 | let proof: CloseProof; | |
| 1251 | if (field(form, "challenge") !== "") { | |
| 1252 | // The username is checked first, as for a password, so a typo spends no ceremony's verdict. | |
| 1253 | const answer = Object.fromEntries(PROOF_FIELDS.map((n) => [n, field(form, n)])) as Record<(typeof PROOF_FIELDS)[number], string>; | |
| 1254 | if (username === user.username && !(await passkeyProves(ctx.app, user.id, answer, { origin: ctx.url.origin, rpId: ctx.url.hostname }))) | |
| 1255 | return closeRefused(ctx, { field: "username", text: PASSKEY_REJECTED, form }); | |
| 1256 | proof = { passkey: true }; | |
| 1257 | } else proof = { password: field(form, "password"), source: clientAddress(ctx.request) }; | |
| 1258 | const asked = await askToClose(ctx.app, user, { username, proof, current: cookieValue(ctx.request, "forge_session") }); | |
| 1259 | if (asked.ok) return flashTo(ctx, "/settings", { tone: "attn", message: closingSays(asked.at) }); | |
| 1260 | if (asked.error === "refused") return closeRefused(ctx, { stands: asked.refusal, form }); | |
| 1261 | if (asked.error === "username") return closeRefused(ctx, { field: "username", text: CLOSE_WORDS.username(user.username), form }); | |
| 1262 | if (asked.error === "no_password") return closeRefused(ctx, { stands: { says: CLOSE_WORDS.no_password }, form }); | |
| 1263 | return closeRefused(ctx, { field: "password", text: CLOSE_WORDS.password, form }); | |
| 1264 | } | |
| 1265 | ||
| 1266 | const CLOSE_ITSELF = "Closing an account, or keeping it, is asked from the account itself, signed in, never by an access code."; | |
| 1267 | ||
| 1268 | // POST /settings/account/keep | |
| 1269 | export async function accountKeep(ctx: Ctx): Promise<Response> { | |
| 1270 | if (!ctx.auth.user) return signInFirst(ctx); | |
| 1271 | if (!isAccountItself(ctx.auth)) return forbiddenPage(ctx, CLOSE_ITSELF); | |
| 1272 | const form = await readForm(ctx, "admin"); | |
| 1273 | if (form instanceof Response) return form; | |
| 1274 | return flashTo(ctx, "/settings", { tone: "success", message: keptSays(keepMyAccount(ctx.app, ctx.auth.user)) }); | |
| 1275 | } |
src/web/pages/passkeys.ts +13 −8
| @@ -40,7 +40,7 @@ import { passkeyJs } from "../passkey-client.ts"; | ||
| 40 | 40 | import { passkeyNote } from "../passkey-state.ts"; |
| 41 | 41 | import { btn, confirmAction, row, time } from "../ui.ts"; |
| 42 | 42 | import { accountShell } from "./account.ts"; |
| 43 | import { safeNext, sessionCookie, signinAllowed } from "./site.ts"; | |
| 43 | import { safeNext, sessionCookie, signinAllowed, withClosingNotice } from "./site.ts"; | |
| 44 | 44 | import { PASSKEY_EXPIRED, PASSKEY_REJECTED, PASSKEY_TAKEN } from "../passkey-words.ts"; |
| 45 | 45 | |
| 46 | 46 | /** One-time challenges, one store per ceremony per forge. */ |
| @@ -217,10 +217,14 @@ export async function signinPasskey(ctx: Ctx): Promise<Response> { | ||
| 217 | 217 | if (waiting) |
| 218 | 218 | return json({ ok: true, waiting: true, next: requestOf(ctx.app.db, user.id)?.state === "declined" ? "/signup/requested?answer=declined" : "/signup/requested" }, 202); |
| 219 | 219 | const session = rotateSession(ctx.app.db, cookieValue(ctx.request, "forge_session"), user.id); |
| 220 | return json( | |
| 221 | { ok: true, next: safeNext(ctx.url.searchParams.get("next")) ?? "/" }, | |
| 222 | 200, | |
| 223 | { "set-cookie": sessionCookie(session.token, session.expiresAt, ctx.url, ctx.app.config.url) }, | |
| 220 | return withClosingNotice( | |
| 221 | ctx, | |
| 222 | user.id, | |
| 223 | json( | |
| 224 | { ok: true, next: safeNext(ctx.url.searchParams.get("next")) ?? "/" }, | |
| 225 | 200, | |
| 226 | { "set-cookie": sessionCookie(session.token, session.expiresAt, ctx.url, ctx.app.config.url) }, | |
| 227 | ), | |
| 224 | 228 | ); |
| 225 | 229 | } |
| 226 | 230 | |
| @@ -370,9 +374,10 @@ export async function recoverFinish(ctx: Ctx): Promise<Response> { | ||
| 370 | 374 | const added = addPasskey(ctx.app.db, spent.value.id, name, made); |
| 371 | 375 | if (!added.ok) return refuse(409, "That passkey could not be added."); |
| 372 | 376 | const session = rotateSession(ctx.app.db, cookieValue(ctx.request, "forge_session"), spent.value.id); |
| 373 | return json({ ok: true, next: "/settings/passkeys" }, 200, { | |
| 377 | const answer = json({ ok: true, next: "/settings/passkeys" }, 200, { | |
| 374 | 378 | "set-cookie": sessionCookie(session.token, session.expiresAt, ctx.url, ctx.app.config.url), |
| 375 | 379 | }); |
| 380 | return withClosingNotice(ctx, spent.value.id, answer); | |
| 376 | 381 | } |
| 377 | 382 | |
| 378 | 383 | const ACCESS_NOT_VALID = "This link has been used or has expired. Ask the admin who sent it for a new one."; |
| @@ -432,10 +437,10 @@ export async function accessSubmit(ctx: Ctx): Promise<Response> { | ||
| 432 | 437 | return accessForm(ctx, token, user?.username ?? "", CHANGE_PASSWORD_WORDS[done.error], 422); |
| 433 | 438 | } |
| 434 | 439 | const session = rotateSession(ctx.app.db, cookieValue(ctx.request, "forge_session"), done.value.id); |
| 435 | return redirect("/settings/passkeys", { | |
| 440 | return withClosingNotice(ctx, done.value.id, redirect("/settings/passkeys", { | |
| 436 | 441 | cookie: sessionCookie(session.token, session.expiresAt, ctx.url, ctx.app.config.url), |
| 437 | 442 | flash: { message: "Password set; you are signed in. You can add a passkey here too." }, |
| 438 | 443 | url: ctx.url, |
| 439 | 444 | forgeUrl: ctx.app.config.url, |
| 440 | }); | |
| 445 | })); | |
| 441 | 446 | } |
src/web/pages/site.ts +19 −3
| @@ -8,6 +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 | 12 | import { USERNAME_PATTERN } from "../username_pattern.ts"; |
| 12 | 13 | import { expireCookie, setCookie } from "../../auth/cookies.ts"; |
| 13 | 14 | import { safeNext, withReturn } from "../return_to.ts"; |
| @@ -57,6 +58,7 @@ import { passkeyNote } from "../passkey-state.ts"; | ||
| 57 | 58 | import { html, when, type Html } from "../html.ts"; |
| 58 | 59 | import { icon } from "../icons.ts"; |
| 59 | 60 | import { flashTo, page, redirect } from "../layout.ts"; |
| 61 | import { flashCookie } from "../flash.ts"; | |
| 60 | 62 | import { |
| 61 | 63 | btn, |
| 62 | 64 | field as formField, |
| @@ -633,12 +635,26 @@ export async function signinSubmit(ctx: Ctx): Promise<Response> { | ||
| 633 | 635 | ); |
| 634 | 636 | } |
| 635 | 637 | const session = rotateSession(ctx.app.db, cookieValue(ctx.request, "forge_session"), verified.value.id); |
| 636 | return redirect( | |
| 637 | safeNext(ctx.url.searchParams.get("next")) ?? "/", | |
| 638 | sessionCookie(session.token, session.expiresAt, ctx.url, ctx.app.config.url), | |
| 638 | return withClosingNotice( | |
| 639 | ctx, | |
| 640 | verified.value.id, | |
| 641 | redirect(safeNext(ctx.url.searchParams.get("next")) ?? "/", sessionCookie(session.token, session.expiresAt, ctx.url, ctx.app.config.url)), | |
| 639 | 642 | ); |
| 640 | 643 | } |
| 641 | 644 | |
| 645 | /** | |
| 646 | * A sign-in during the close grace says so on the first page, with the way | |
| 647 | * to keep the account (#15619): every door that signs an account in passes | |
| 648 | * its answer through here, a redirect or a passkey's JSON alike. | |
| 649 | */ | |
| 650 | export function withClosingNotice(ctx: Ctx, userId: string, res: Response): Response { | |
| 651 | const at = closeRequestedAt(ctx.app.db, userId); | |
| 652 | if (at === null) return res; | |
| 653 | const flash = { tone: "attn" as const, message: closingSays(at), link: { href: "/settings", label: "Keep my account" } }; | |
| 654 | res.headers.append("set-cookie", flashCookie(flash, ctx.url, ctx.app.config.url)); | |
| 655 | return res; | |
| 656 | } | |
| 657 | ||
| 642 | 658 | /** What a person whose request is in, waiting or declined is shown: a sentence, no owner's name. */ |
| 643 | 659 | export function requestPage(ctx: Ctx, said: string, title = "Your request is in", status = 200): Response { |
| 644 | 660 | return page( |
src/web/passkey-client.ts +25 −1
| @@ -62,7 +62,7 @@ export const passkeyJs = /* js */ ` | ||
| 62 | 62 | e.preventDefault(); |
| 63 | 63 | el.disabled = true; |
| 64 | 64 | say(note, '', false); |
| 65 | run().catch(function (err) { | |
| 65 | run(el).catch(function (err) { | |
| 66 | 66 | var cancelled = err && err.name === 'NotAllowedError'; |
| 67 | 67 | say(note, cancelled ? 'Cancelled.' : (err && err.message) || 'That did not work.', !cancelled); |
| 68 | 68 | el.disabled = false; |
| @@ -171,6 +171,30 @@ export const passkeyJs = /* js */ ` | ||
| 171 | 171 | }); |
| 172 | 172 | }); |
| 173 | 173 | }); |
| 174 | // Close my account with a passkey (#15619): the signed answer goes into the | |
| 175 | // close form's hidden fields and the form posts as it does with a password. | |
| 176 | wire('passkey-close', function (el) { | |
| 177 | var form = el.form; | |
| 178 | var pw = form.elements.password; | |
| 179 | if (pw) pw.required = false; | |
| 180 | if (form.reportValidity && !form.reportValidity()) { el.disabled = false; return Promise.resolve(); } | |
| 181 | return post(el.getAttribute('data-options')).then(function (o) { | |
| 182 | return navigator.credentials.get({ publicKey: { | |
| 183 | challenge: bytes(o.challenge), | |
| 184 | rpId: o.rpId, | |
| 185 | allowCredentials: o.allow.map(function (c) { return { type: 'public-key', id: bytes(c) }; }), | |
| 186 | userVerification: 'required', | |
| 187 | timeout: 120000 | |
| 188 | } }).then(function (cred) { | |
| 189 | form.elements.challenge.value = o.challenge; | |
| 190 | form.elements.id.value = text(cred.rawId); | |
| 191 | form.elements.clientDataJSON.value = text(cred.response.clientDataJSON); | |
| 192 | form.elements.authenticatorData.value = text(cred.response.authenticatorData); | |
| 193 | form.elements.signature.value = text(cred.response.signature); | |
| 194 | form.submit(); | |
| 195 | }); | |
| 196 | }); | |
| 197 | }); | |
| 174 | 198 | wire('passkey-signin', function () { |
| 175 | 199 | return post('/signin/passkey/options').then(function (o) { |
| 176 | 200 | return navigator.credentials.get({ publicKey: { |
test/account-close.test.ts added +239
| @@ -0,0 +1,239 @@ | ||
| 1 | /** | |
| 2 | * Closing an account waits seven days and can be undone (#15619): the | |
| 3 | * request, each refusal, the notice on the first page after sign-in, Keep | |
| 4 | * my account, and that nothing is deleted. | |
| 5 | */ | |
| 6 | import { afterAll, beforeAll, describe, expect, test } from "bun:test"; | |
| 7 | import { mkdtemp, rm } from "node:fs/promises"; | |
| 8 | import { tmpdir } from "node:os"; | |
| 9 | import { join } from "node:path"; | |
| 10 | import { createApp, type App } from "../src/app.ts"; | |
| 11 | import { createUser, getUserByName } from "../src/core/users.ts"; | |
| 12 | import { addTeamMember, createOrg, createTeam } from "../src/core/orgs.ts"; | |
| 13 | import { closeRefusal, closeRequestedAt, closesOn, keepAccount, requestClose } from "../src/actions/account_close.ts"; | |
| 14 | import { serve, type Servers } from "../src/http/server.ts"; | |
| 15 | import { verifyRegistration } from "../src/auth/webauthn.ts"; | |
| 16 | import { addPasskey } from "../src/core/passkeys.ts"; | |
| 17 | import { createToken } from "../src/core/tokens.ts"; | |
| 18 | import { device, type Device } from "./helpers/passkey.ts"; | |
| 19 | ||
| 20 | const PASSWORD = "a-long-passphrase"; | |
| 21 | ||
| 22 | describe("closing an account", () => { | |
| 23 | let dataDir: string; | |
| 24 | let app: App; | |
| 25 | let servers: Servers; | |
| 26 | ||
| 27 | const signIn = async (username: string) => { | |
| 28 | const res = await fetch(`${servers.url}/signin`, { | |
| 29 | method: "POST", | |
| 30 | body: new URLSearchParams({ username, password: PASSWORD }), | |
| 31 | redirect: "manual", | |
| 32 | }); | |
| 33 | const cookies = res.headers.getSetCookie(); | |
| 34 | return { cookie: cookies.find((c) => c.startsWith("forge_session="))!.split(";")[0]!, cookies }; | |
| 35 | }; | |
| 36 | const post = (path: string, cookie: string, form: Record<string, string>) => | |
| 37 | fetch(`${servers.url}${path}`, { method: "POST", headers: { cookie }, body: new URLSearchParams(form), redirect: "manual" }); | |
| 38 | const make = async (username: string, adminIfFirst = false) => { | |
| 39 | const made = await createUser(app.db, { origin: "seed", trusted: true, username, email: `${username}@forge.local`, password: PASSWORD, adminIfFirst }); | |
| 40 | if (!made.ok) throw new Error(made.error); | |
| 41 | return made.value; | |
| 42 | }; | |
| 43 | ||
| 44 | beforeAll(async () => { | |
| 45 | dataDir = await mkdtemp(join(tmpdir(), "forge-account-close-")); | |
| 46 | app = createApp({ dataDir, port: 0 }); | |
| 47 | servers = await serve(app); | |
| 48 | await make("alice", true); | |
| 49 | await make("bob"); | |
| 50 | await make("carol"); | |
| 51 | await make("dave"); | |
| 52 | }); | |
| 53 | afterAll(async () => { | |
| 54 | servers.stop(); | |
| 55 | await rm(dataDir, { recursive: true, force: true }); | |
| 56 | }); | |
| 57 | ||
| 58 | test("a wrong username or password is refused and records nothing", async () => { | |
| 59 | const { cookie } = await signIn("bob"); | |
| 60 | // The form is on the password page; the settings page shows nothing until a request stands. | |
| 61 | const passwordPage = await (await fetch(`${servers.url}/settings/password`, { headers: { cookie } })).text(); | |
| 62 | expect(passwordPage).toContain('action="/settings/account/close"'); | |
| 63 | const settings = await (await fetch(`${servers.url}/settings`, { headers: { cookie } })).text(); | |
| 64 | expect(settings).not.toContain("Keep my account"); | |
| 65 | expect((await post("/settings/account/close", cookie, { username: "bobby", password: PASSWORD })).status).toBe(422); | |
| 66 | expect((await post("/settings/account/close", cookie, { username: "bob", password: "not-the-password" })).status).toBe(422); | |
| 67 | expect(closeRequestedAt(app.db, getUserByName(app.db, "bob")!.id)).toBeNull(); | |
| 68 | }); | |
| 69 | ||
| 70 | test("the request records the day, signs out other sessions, and the page says when it closes", async () => { | |
| 71 | const other = await signIn("bob"); | |
| 72 | const { cookie } = await signIn("bob"); | |
| 73 | const res = await post("/settings/account/close", cookie, { username: "bob", password: PASSWORD }); | |
| 74 | expect(res.status).toBe(303); | |
| 75 | const bob = getUserByName(app.db, "bob")!; | |
| 76 | const at = closeRequestedAt(app.db, bob.id); | |
| 77 | expect(at).not.toBeNull(); | |
| 78 | const page = await (await fetch(`${servers.url}/settings`, { headers: { cookie } })).text(); | |
| 79 | expect(page).toContain(`closes on ${closesOn(at!)}`); | |
| 80 | expect(page).toContain("Keep my account"); | |
| 81 | // The other browser is signed out. | |
| 82 | const stale = await fetch(`${servers.url}/settings`, { headers: { cookie: other.cookie }, redirect: "manual" }); | |
| 83 | expect(stale.status).not.toBe(200); | |
| 84 | // Nothing is deleted: the account still stands and can sign in. | |
| 85 | expect(getUserByName(app.db, "bob")?.removedAt).toBeNull(); | |
| 86 | }); | |
| 87 | ||
| 88 | test("signing in during the grace shows the notice, and Keep my account clears it with a receipt", async () => { | |
| 89 | const { cookie, cookies } = await signIn("bob"); | |
| 90 | const flash = decodeURIComponent(cookies.find((c) => c.startsWith("forge_flash="))?.split(";")[0] ?? ""); | |
| 91 | expect(flash).toContain("closes on"); | |
| 92 | const kept = await post("/settings/account/keep", cookie, {}); | |
| 93 | expect(kept.status).toBe(303); | |
| 94 | const bob = getUserByName(app.db, "bob")!; | |
| 95 | expect(closeRequestedAt(app.db, bob.id)).toBeNull(); | |
| 96 | const receipts = app.db | |
| 97 | .query<{ kind: string }, [string]>("SELECT kind FROM event WHERE actor_id = ?1 AND kind LIKE 'account.close%' ORDER BY id") | |
| 98 | .all(bob.id) | |
| 99 | .map((r) => r.kind); | |
| 100 | expect(receipts).toEqual(["account.close_requested", "account.close_kept"]); | |
| 101 | expect(keepAccount(app.db, bob.id)).toBe(false); | |
| 102 | }); | |
| 103 | ||
| 104 | test("the forge's only admin is refused, through the page", async () => { | |
| 105 | const { cookie } = await signIn("alice"); | |
| 106 | const res = await post("/settings/account/close", cookie, { username: "alice", password: PASSWORD }); | |
| 107 | expect(res.status).toBe(422); | |
| 108 | expect(await res.text()).toContain("only admin"); | |
| 109 | expect(closeRequestedAt(app.db, getUserByName(app.db, "alice")!.id)).toBeNull(); | |
| 110 | }); | |
| 111 | ||
| 112 | /** | |
| 113 | * The refusal is its own line with its link; the username the person typed is not marked wrong. | |
| 114 | */ | |
| 115 | const refusedThroughPage = async (username: string, says: string, href: string) => { | |
| 116 | const { cookie } = await signIn(username); | |
| 117 | const res = await post("/settings/account/close", cookie, { username, password: PASSWORD }); | |
| 118 | expect(res.status).toBe(422); | |
| 119 | const page = await res.text(); | |
| 120 | const line = /<div class="toast"[^>]*data-refusal>[\s\S]*?<\/div>\s*<\/div>/.exec(page)?.[0] ?? ""; | |
| 121 | expect(line).toContain(says); | |
| 122 | expect(line).toContain(`href="${href}"`); | |
| 123 | expect(page).not.toMatch(/name="username"[^>]*aria-invalid="true"/); | |
| 124 | expect(closeRequestedAt(app.db, getUserByName(app.db, username)!.id)).toBeNull(); | |
| 125 | }; | |
| 126 | ||
| 127 | test("the only admin of an organization others write to is refused through the page, naming it", async () => { | |
| 128 | const carol = getUserByName(app.db, "carol")!; | |
| 129 | const dave = getUserByName(app.db, "dave")!; | |
| 130 | const org = createOrg(app.db, "acme", carol.id); | |
| 131 | if (!org.ok) throw new Error(org.error); | |
| 132 | app.db.query("INSERT INTO repo (id, owner_id, name) VALUES ('r-acme', ?1, 'site')").run(org.value.id); | |
| 133 | expect(closeRefusal(app.db, carol)).toBeUndefined(); | |
| 134 | const writers = createTeam(app.db, org.value.id, "writers", "write"); | |
| 135 | if (!writers.ok) throw new Error(writers.error); | |
| 136 | addTeamMember(app.db, writers.value, dave.id); | |
| 137 | expect(closeRefusal(app.db, carol)?.reason).toBe("shared_repo"); | |
| 138 | await refusedThroughPage("carol", "Other people write to acme", "/acme"); | |
| 139 | }); | |
| 140 | ||
| 141 | test("the forge's only admin's refusal is its own line too", async () => { | |
| 142 | await refusedThroughPage("alice", "only admin", "/settings/accounts"); | |
| 143 | }); | |
| 144 | ||
| 145 | test("an active subscription is refused through the page, linking payments", async () => { | |
| 146 | const dave = getUserByName(app.db, "dave")!; | |
| 147 | expect(closeRefusal(app.db, dave)).toBeUndefined(); | |
| 148 | app.db | |
| 149 | .query("INSERT INTO entitlement (forge, plan, status, payer, provider, source, updated_at) VALUES ('daves', 'small', 'active', ?1, 'stripe', 'stripe', '')") | |
| 150 | .run(dave.email); | |
| 151 | expect(closeRefusal(app.db, dave)?.reason).toBe("subscription"); | |
| 152 | await refusedThroughPage("dave", "You still pay for daves", "/settings/payments"); | |
| 153 | expect(requestClose(app.db, dave.id)).toBe(true); | |
| 154 | expect(requestClose(app.db, dave.id)).toBe(false); | |
| 155 | }); | |
| 156 | ||
| 157 | test("an access code can neither close nor keep the account", async () => { | |
| 158 | const bob = getUserByName(app.db, "bob")!; | |
| 159 | const { token } = createToken(app.db, bob.id, "ci", "rw"); | |
| 160 | const headers = { authorization: `Bearer ${token}`, origin: servers.url }; | |
| 161 | for (const path of ["/settings/account/close", "/settings/account/keep"]) { | |
| 162 | const res = await fetch(`${servers.url}${path}`, { method: "POST", headers, body: new URLSearchParams({ username: "bob", password: PASSWORD }), redirect: "manual" }); | |
| 163 | expect(res.status).toBe(403); | |
| 164 | } | |
| 165 | }); | |
| 166 | ||
| 167 | describe("an account whose only way in is a passkey", () => { | |
| 168 | let key: Device; | |
| 169 | const register = async (username: string, d: Device) => { | |
| 170 | const made = await verifyRegistration(await d.create("c"), { challenge: "c", origin: servers.url, rpId: new URL(servers.url).hostname }); | |
| 171 | if (!made.ok) throw new Error("registration refused"); | |
| 172 | const added = addPasskey(app.db, getUserByName(app.db, username)!.id, "test key", made); | |
| 173 | if (!added.ok) throw new Error(added.error); | |
| 174 | }; | |
| 175 | const passkeySignIn = async (d: Device) => { | |
| 176 | const o = (await (await fetch(`${servers.url}/signin/passkey/options`, { method: "POST", headers: { origin: servers.url } })).json()) as { challenge: string }; | |
| 177 | return fetch(`${servers.url}/signin/passkey`, { | |
| 178 | method: "POST", | |
| 179 | headers: { origin: servers.url, "content-type": "application/json" }, | |
| 180 | body: JSON.stringify({ challenge: o.challenge, ...(await d.get(o.challenge)) }), | |
| 181 | }); | |
| 182 | }; | |
| 183 | const answer = async (cookie: string, d: Device) => { | |
| 184 | const res = await fetch(`${servers.url}/settings/account/close/options`, { method: "POST", headers: { cookie, origin: servers.url } }); | |
| 185 | expect(res.status).toBe(200); | |
| 186 | const { challenge } = (await res.json()) as { challenge: string }; | |
| 187 | return { challenge, ...(await d.get(challenge)) }; | |
| 188 | }; | |
| 189 | ||
| 190 | beforeAll(async () => { | |
| 191 | await make("erin"); | |
| 192 | app.db.query("UPDATE user SET password_hash = '' WHERE username = 'erin'").run(); | |
| 193 | key = await device(servers.url); | |
| 194 | await register("erin", key); | |
| 195 | }); | |
| 196 | ||
| 197 | test("the page offers the passkey and no password; a signed answer closes, a stranger's key or a replay does not", async () => { | |
| 198 | const signed = await passkeySignIn(key); | |
| 199 | expect(signed.status).toBe(200); | |
| 200 | const cookie = signed.headers.getSetCookie().find((c) => c.startsWith("forge_session="))!.split(";")[0]!; | |
| 201 | const page = await (await fetch(`${servers.url}/settings/password`, { headers: { cookie } })).text(); | |
| 202 | expect(page).toContain('id="passkey-close"'); | |
| 203 | expect(page).not.toContain('name="password" type="password" autocomplete="current-password"'); | |
| 204 | ||
| 205 | const other = await device(servers.url); | |
| 206 | await make("frank"); | |
| 207 | await register("frank", other); | |
| 208 | const stranger = await answer(cookie, other); | |
| 209 | expect((await post("/settings/account/close", cookie, { username: "erin", ...stranger })).status).toBe(422); | |
| 210 | ||
| 211 | const good = await answer(cookie, key); | |
| 212 | const res = await post("/settings/account/close", cookie, { username: "erin", ...good }); | |
| 213 | expect(res.status).toBe(303); | |
| 214 | const erin = getUserByName(app.db, "erin")!; | |
| 215 | expect(closeRequestedAt(app.db, erin.id)).not.toBeNull(); | |
| 216 | keepAccount(app.db, erin.id); | |
| 217 | expect((await post("/settings/account/close", cookie, { username: "erin", ...good })).status).toBe(422); | |
| 218 | expect(closeRequestedAt(app.db, erin.id)).toBeNull(); | |
| 219 | }); | |
| 220 | ||
| 221 | test("a password-only close for this account is told to use the passkey", async () => { | |
| 222 | const signed = await passkeySignIn(key); | |
| 223 | const cookie = signed.headers.getSetCookie().find((c) => c.startsWith("forge_session="))!.split(";")[0]!; | |
| 224 | const res = await post("/settings/account/close", cookie, { username: "erin", password: PASSWORD }); | |
| 225 | expect(res.status).toBe(422); | |
| 226 | expect(await res.text()).toContain("This account has no password"); | |
| 227 | }); | |
| 228 | ||
| 229 | test("a passkey sign-in during the grace carries the notice", async () => { | |
| 230 | const erin = getUserByName(app.db, "erin")!; | |
| 231 | requestClose(app.db, erin.id); | |
| 232 | const signed = await passkeySignIn(key); | |
| 233 | const flash = decodeURIComponent(signed.headers.getSetCookie().find((c) => c.startsWith("forge_flash="))?.split(";")[0] ?? ""); | |
| 234 | expect(flash).toContain("closes on"); | |
| 235 | expect(flash).toContain("Keep my account"); | |
| 236 | keepAccount(app.db, erin.id); | |
| 237 | }); | |
| 238 | }); | |
| 239 | }); |
test/account-nojs.test.ts +1
| @@ -109,6 +109,7 @@ const EXPECTED = [ | ||
| 109 | 109 | "/settings/everyday/keep", |
| 110 | 110 | "/settings/email/verify", // shown to an unverified user only: bob |
| 111 | 111 | "/settings/password", |
| 112 | "/settings/account/close", // on the password page | |
| 112 | 113 | "/settings/tokens", |
| 113 | 114 | "/settings/keys", |
| 114 | 115 | "/settings/edge/link", |
test/cookie-flags.test.ts +1 −1
| @@ -113,7 +113,7 @@ const WALKED: Record<string, number> = { | ||
| 113 | 113 | "src/apps/proxy.ts": 3, // app grant, app sign-out, toolbar dismissal |
| 114 | 114 | "src/apps/feedback.ts": 2, // a stranger's note on an app host, both answers that may carry the visitor cookie |
| 115 | 115 | "src/web/pages/passkeys.ts": 5, // import, passkey sign-in, passkey add/recovery-link sign-in, access-link sign-in (+1 mention) |
| 116 | "src/web/pages/site.ts": 4, // sessionCookie() itself and its uses: password sign-in/sign-up, logout; the theme cookie | |
| 116 | "src/web/pages/site.ts": 5, // sessionCookie() itself and its uses: password sign-in/sign-up, logout; the theme cookie; the closing flash on a sign-in (#15619) | |
| 117 | 117 | "src/web/pages/first-admin.ts": 1, // the first admin made by passkey |
| 118 | 118 | "src/web/pages/signup-passkey.ts": 2, // import, sign-up by passkey |
| 119 | 119 | "src/web/pages/map.ts": 1, // the roadmap's last-looked cookie |
test/danger-buttons.test.ts +1
| @@ -15,6 +15,7 @@ const allowed: readonly { file: string; button: string; reason: string }[] = [ | ||
| 15 | 15 | { file: "src/web/pages/edit.ts", button: `"Delete this file"`, reason: "the delete page is the confirmation, reached by a link" }, |
| 16 | 16 | { file: "src/web/pages/pull.ts", button: `"Land past the gate"`, reason: "asks for a typed reason of at least 8 characters" }, |
| 17 | 17 | { file: "src/web/studio/change.ts", button: `"Send it back"`, reason: "a changes-requested verdict; the next review replaces it" }, |
| 18 | { file: "src/web/pages/account.ts", button: `"Close my account"`, reason: "asks for the password and the typed username, and waits 7 days with Keep my account" }, | |
| 18 | 19 | { file: "src/web/studio/notes.ts", button: "label", reason: "owner note ban; undone by unban on the same row" }, |
| 19 | 20 | { file: "src/web/studio/change.ts", button: `"Send it back"`, reason: "a changes-requested review with an optional why; the next review replaces it" }, |
| 20 | 21 | ]; |
test/openapi-drift.test.ts +2
| @@ -13,6 +13,7 @@ const NOT_ROUTED: Readonly<Record<string, string>> = { | ||
| 13 | 13 | "GET /health": "routed outside /api/v1 (src/http/api.ts), the monitor's alias of /api/v1/health (#13191)", |
| 14 | 14 | "GET /{}/{}/pulls/{}/check.txt": "routed outside /api/v1 (src/http/server.ts, check_text.ts); test/openapi-check-txt.test.ts pins it to server.ts", |
| 15 | 15 | "POST /mcp": "routed outside /api/v1 (src/http/mcp.ts); the MCP has its own card and tool list", |
| 16 | "POST /settings/account/close/options": "routed outside /api/v1 (src/http/settings_routes.ts): the close form's passkey challenge, a browser session's JSON (#15619)", | |
| 16 | 17 | "GET /oembed": "routed outside /api/v1 (src/http/server.ts, web/standards.ts): the oEmbed endpoint other tools discover from a page's head", |
| 17 | 18 | }; |
| 18 | 19 | const NOT_DESCRIBED: Readonly<Record<string, string>> = {}; |
| @@ -95,6 +96,7 @@ const SESSION_ONLY: ReadonlySet<string> = new Set([ | ||
| 95 | 96 | "DELETE /api/v1/tokens/{}", |
| 96 | 97 | "POST /api/v1/conversation-tokens", |
| 97 | 98 | "POST /api/v1/conversation-confirms/{}", |
| 99 | "POST /settings/account/close/options", | |
| 98 | 100 | ]); |
| 99 | 101 | |
| 100 | 102 | test("an anonymous route takes no token, a token route is never anonymous, and every /admin route is admin only", () => { |
test/openapi.test.ts +1 −1
| @@ -41,7 +41,7 @@ test("every http route the manifest names is described", () => { | ||
| 41 | 41 | }); |
| 42 | 42 | |
| 43 | 43 | test("every described route is registered in the router", () => { |
| 44 | const src = ["src/http/server.ts", "src/http/api.ts", "src/http/mcp.ts", "src/http/passport_edge.ts", "src/http/feed.ts", "src/http/checks_recheck.ts", "src/contract/served.ts", | |
| 44 | const src = ["src/http/server.ts", "src/http/api.ts", "src/http/mcp.ts", "src/http/passport_edge.ts", "src/http/feed.ts", "src/http/checks_recheck.ts", "src/http/settings_routes.ts", "src/contract/served.ts", | |
| 45 | 45 | ...readdirSync("src/http/api").map((f) => `src/http/api/${f}`)] |
| 46 | 46 | .map((f) => readFileSync(f, "utf8")) |
| 47 | 47 | .join("\n") |
new above
offline
Principle 1: this sentence and the hint 'Type X to confirm' under a field already labelled 'Type your username' say the same thing twice. Keep one confident sentence; drop the hint.