Public: anyone can read this; the crew can change it.
Connections: one place says an email is proven, with the sign-in proof reading it #18320
Merged 6h 6m ago, live in production
mason/forge:mason/18222-connections-one-place-says-an-email-is-p → main 0 commits fork
32 files
changed +478
−121
- docs/features/account-identities.md
- src/actions/identities.ts
- src/actions/users.ts
- src/actions/verify.ts
- src/core/accounts.ts
- src/core/identities.ts
- src/core/migration-pins/20261204221000-email-proof-in-connections.pin
- src/core/migrations/20261204221000-email-proof-in-connections.ts
- src/core/people_rows.ts
- src/core/proven_identities.ts
- src/core/roles.ts
- src/core/verify.ts
- src/http/api/identities.ts
- src/tui/screens/identities.ts
- src/web/pages/identities.ts
- test/first-ask-first-tell.test.ts
- test/guest-contribute.test.ts
- test/helpers/verified.ts
- test/home-feed.test.ts
- test/identities-doors.test.ts
- test/identities.test.ts
- test/mcp-crew.test.ts
- test/mcp-email-verify.test.ts
- test/mcp-tell.test.ts
- test/passkey-recovery.test.ts
- test/ssh-tell.test.ts
- test/tui-answers-tell.test.ts
- test/tui-deploy-act.test.ts
- test/tui-deploys-build.test.ts
- test/tui-deploys-preview-act.test.ts
- test/verify-recovery.test.ts
- test/verify.test.ts
docs/features/account-identities.md +13 −3
| @@ -43,8 +43,18 @@ uses are off, so the lookup no longer answers this account for a name someone el | ||
| 43 | 43 | - **Mail**: a member's sends are capped by account (20 a day, `connection:<id>` scope of |
| 44 | 44 | `sendCapped`, so add-then-remove cycles do not evade it), by address and by the forge. |
| 45 | 45 | - **Audit**: a key's rows older than a day are deleted on its next call. |
| 46 | - **Not yet**: the Apple app; the account's proven email stays where it is, not in this list; the | |
| 47 | game links themselves (one per box) stay on Settings › Minecraft. | |
| 46 | - **The address you sign in with** (#18222) is in this list too, and it is the one proof sign-in | |
| 47 | reads: proving it here (or by the sign-in link) proves it for sign-in, and changing your address | |
| 48 | leaves both the new one and the one it replaced unproven, so changing back needs a fresh proof. | |
| 49 | Its row says "you sign in with it" (`signIn: true` in the API), beside the words "This is the | |
| 50 | address you sign in with. Removing it means you must prove it again before you can write." | |
| 51 | Removing it asks first: the page's Remove needs its "Remove it anyway" box ticked, the | |
| 52 | terminal's `d` shows those words before its y/n, and the API's `DELETE /:id` answers 409 | |
| 53 | `confirm_sign_in` unless it carries `?confirm=true`. Once removed, the account is held back as | |
| 54 | an unproven one until the address is proven again. A stand-in address (`.invalid`) is never | |
| 55 | listed. | |
| 56 | - **Not yet**: the Apple app; the game links themselves (one per box) stay on Settings › Minecraft. | |
| 48 | 57 | |
| 49 | 58 | `test/identities.test.ts` walks add, prove, opt in, unlink, remove; |
| 50 | `test/identities-doors.test.ts` the page and the screen. | |
| 59 | `test/identities-doors.test.ts` the page and the screen, and removing the address you sign in | |
| 60 | with at the page, the API and the terminal; `test/verify.test.ts` the one proof sign-in reads. |
src/actions/identities.ts +16 −2
| @@ -23,7 +23,14 @@ import { sendCapped } from "./mail.ts"; | ||
| 23 | 23 | |
| 24 | 24 | export type ConnectionError = |
| 25 | 25 | | "invalid_email" | "invalid_minecraft" | "limit" | "taken" | "too_soon" | "no_mail" | "capped" | "failed" |
| 26 | | "wrong_code" | "not_found" | "invalid_use" | "invalid_name"; | |
| 26 | | "wrong_code" | "not_found" | "invalid_use" | "invalid_name" | "confirm_sign_in"; | |
| 27 | ||
| 28 | /** | |
| 29 | * What the account's own address says beside it, at every door (#18222): it is listed, proven, and | |
| 30 | * removing it puts the account back behind the email gate. | |
| 31 | */ | |
| 32 | export const SIGN_IN_ADDRESS = | |
| 33 | "This is the address you sign in with. Removing it means you must prove it again before you can write."; | |
| 27 | 34 | |
| 28 | 35 | /** What each refusal says, for the API, the settings page and the terminal alike. */ |
| 29 | 36 | export const CONNECTION_WORDS: Record<ConnectionError, string> = { |
| @@ -39,6 +46,7 @@ export const CONNECTION_WORDS: Record<ConnectionError, string> = { | ||
| 39 | 46 | not_found: "no such connection", |
| 40 | 47 | invalid_use: "use is feedback or profile, and on is true or false", |
| 41 | 48 | invalid_name: "a key's name is 1 to 60 letters, digits, spaces, dots, dashes or underscores", |
| 49 | confirm_sign_in: `${SIGN_IN_ADDRESS} Confirm to remove it; nothing was removed.`, | |
| 42 | 50 | }; |
| 43 | 51 | |
| 44 | 52 | /** What the settings page says beside the uses: removing or switching off is not retroactive. */ |
| @@ -113,7 +121,13 @@ export function confirmConnection( | ||
| 113 | 121 | return ok(listConnections(app.db, user.id).find((c) => c.id === id)!); |
| 114 | 122 | } |
| 115 | 123 | |
| 116 | export function dropConnection(app: App, user: User, id: string): Result<true, ConnectionError> { | |
| 124 | /** | |
| 125 | * Remove a connection. The address the account signs in with is removed only when `confirmed`: | |
| 126 | * without it, sign-in would silently lose its proof. | |
| 127 | */ | |
| 128 | export function dropConnection(app: App, user: User, id: string, confirmed = false): Result<true, ConnectionError> { | |
| 129 | const c = listConnections(app.db, user.id).find((x) => x.id === id); | |
| 130 | if (c?.signIn === true && !confirmed) return err("confirm_sign_in"); | |
| 117 | 131 | return removeConnection(app.db, user.id, id) ? ok(true) : err("not_found"); |
| 118 | 132 | } |
| 119 | 133 |
src/actions/users.ts +1 −1
| @@ -398,7 +398,7 @@ export function updateProfile( | ||
| 398 | 398 | // A new address is unproven at once; its link follows (and can be asked |
| 399 | 399 | // for again), so a send that fails never leaves the old proof standing. |
| 400 | 400 | if (updated.value.email.toLowerCase() !== user.value.email.toLowerCase()) |
| 401 | void emailChanged(app, updated.value); | |
| 401 | void emailChanged(app, updated.value, user.value.email); | |
| 402 | 402 | const fields = (["displayName", "email", "commitEmail"] as const).filter( |
| 403 | 403 | (k) => patch[k] !== undefined, |
| 404 | 404 | ); |
src/actions/verify.ts +5 −4
| @@ -149,11 +149,12 @@ export async function welcome(app: App, user: User): Promise<void> { | ||
| 149 | 149 | } |
| 150 | 150 | |
| 151 | 151 | /** |
| 152 | * A changed address must be proven again. The reset happens before the | |
| 153 | * first await, so a caller that does not wait still leaves it unproven. | |
| 152 | * A changed address must be proven again, and so must the one it replaced | |
| 153 | * (`was`) if the account changes back. The reset happens before the first | |
| 154 | * await, so a caller that does not wait still leaves it unproven. | |
| 154 | 155 | */ |
| 155 | export async function emailChanged(app: App, user: User): Promise<void> { | |
| 156 | resetVerification(app.db, user.id); | |
| 156 | export async function emailChanged(app: App, user: User, was: string): Promise<void> { | |
| 157 | resetVerification(app.db, user.id, was); | |
| 157 | 158 | await sendVerification(app, user); |
| 158 | 159 | } |
| 159 | 160 |
src/core/accounts.ts +2 −1
| @@ -13,6 +13,7 @@ | ||
| 13 | 13 | |
| 14 | 14 | import type { Database } from "bun:sqlite"; |
| 15 | 15 | import { forgetListings } from "./listings.ts"; |
| 16 | import { provenEmailAt } from "./proven_identities.ts"; | |
| 16 | 17 | |
| 17 | 18 | export interface AccountRow { |
| 18 | 19 | readonly username: string; |
| @@ -71,7 +72,7 @@ export function listAccounts(db: Database, only = ""): AccountRow[] { | ||
| 71 | 72 | >( |
| 72 | 73 | `SELECT u.id, u.username, u.display_name, u.is_admin, u.is_agent, |
| 73 | 74 | u.created_at, u.suspended_at, u.removed_at, u.waiting_at, |
| 74 | (SELECT c.verified_at FROM email_check c WHERE c.user_id = u.id) AS verified_at, | |
| 75 | ${provenEmailAt("u")} AS verified_at, | |
| 75 | 76 | (SELECT COUNT(*) FROM repo r WHERE r.owner_id = u.id) AS repos, |
| 76 | 77 | (SELECT COUNT(*) FROM app a JOIN repo r ON r.id = a.repo_id |
| 77 | 78 | WHERE r.owner_id = u.id) AS apps, |
src/core/identities.ts +22 −7
| @@ -9,6 +9,11 @@ | ||
| 9 | 9 | * address from an unproven or an opted-out one. A Minecraft name (#18221) is |
| 10 | 10 | * the second kind: no code, it is proven when the game door links that player |
| 11 | 11 | * to the account (`proveMinecraft`), and the same one-account rule holds. |
| 12 | * The account's own email is one of these rows (#18222): proving it here | |
| 13 | * proves it for sign-in, and removing it unproves sign-in (`core/verify.ts` | |
| 14 | * reads it; nothing else keeps that proof). A stand-in address (`.invalid`, | |
| 15 | * an account that gave none) is kept, proven by its maker's word, but never | |
| 16 | * listed: it is not an address anyone can use. | |
| 12 | 17 | */ |
| 13 | 18 | |
| 14 | 19 | import type { Database } from "bun:sqlite"; |
| @@ -36,6 +41,8 @@ export interface Connection { | ||
| 36 | 41 | readonly ident: string; |
| 37 | 42 | readonly proven: boolean; |
| 38 | 43 | readonly uses: Readonly<Record<Use, boolean>>; |
| 44 | /** It is the address the account signs in with: removing it unproves sign-in (#18222). */ | |
| 45 | readonly signIn: boolean; | |
| 39 | 46 | } |
| 40 | 47 | |
| 41 | 48 | /** |
| @@ -60,22 +67,30 @@ export function cleanMinecraft(raw: unknown): string | undefined { | ||
| 60 | 67 | |
| 61 | 68 | interface Row { |
| 62 | 69 | id: string; user_id: string; kind: Kind; ident: string; proven_at: string | null; |
| 63 | sent_at: string | null; use_feedback: number; use_profile: number; | |
| 70 | sent_at: string | null; use_feedback: number; use_profile: number; sign_in: number; | |
| 64 | 71 | } |
| 72 | /** SQL: connections `c` with whether each is the address its account signs in with. */ | |
| 73 | const SHOWN = `SELECT c.*, (c.kind = 'email' AND c.ident = lower(u.email)) AS sign_in | |
| 74 | FROM connection c JOIN user u ON u.id = c.user_id`; | |
| 65 | 75 | const shown = (r: Row): Connection => ({ |
| 66 | 76 | id: r.id, kind: r.kind, ident: r.ident, proven: r.proven_at !== null, |
| 67 | 77 | uses: { feedback: r.use_feedback === 1, profile: r.use_profile === 1 }, |
| 78 | signIn: r.sign_in === 1, | |
| 68 | 79 | }); |
| 80 | const byId = (db: Database, id: string): Connection => shown(db.query<Row, [string]>(`${SHOWN} WHERE c.id = ?1`).get(id)!); | |
| 69 | 81 | |
| 70 | 82 | export function listConnections(db: Database, userId: string): Connection[] { |
| 71 | return db.query<Row, [string]>("SELECT * FROM connection WHERE user_id = ?1 ORDER BY created_at, id").all(userId).map(shown); | |
| 83 | return db | |
| 84 | .query<Row, [string]>(`${SHOWN} WHERE c.user_id = ?1 AND NOT (c.kind = 'email' AND c.ident LIKE '%.invalid') ORDER BY c.created_at, c.id`) | |
| 85 | .all(userId) | |
| 86 | .map(shown); | |
| 72 | 87 | } |
| 73 | 88 | |
| 74 | 89 | /** Start a connection (unproven) and mint its code, returned once. */ |
| 75 | 90 | export function addEmail( |
| 76 | 91 | db: Database, userId: string, email: string, now: number, |
| 77 | 92 | ): { connection: Connection; code: string; held: boolean } | "limit" | "taken" | "too_soon" { |
| 78 | const mine = db.query<Row, [string, string]>("SELECT * FROM connection WHERE user_id = ?1 AND kind = 'email' AND ident = ?2").get(userId, email); | |
| 93 | const mine = db.query<Row, [string, string]>(`${SHOWN} WHERE c.user_id = ?1 AND c.kind = 'email' AND c.ident = ?2`).get(userId, email); | |
| 79 | 94 | if (mine === null) { |
| 80 | 95 | if (full(db, userId)) return "limit"; |
| 81 | 96 | } else if (mine.proven_at !== null) return "taken"; |
| @@ -92,7 +107,7 @@ export function addEmail( | ||
| 92 | 107 | ON CONFLICT(user_id, kind, ident) DO UPDATE SET code_hash = excluded.code_hash, |
| 93 | 108 | expires_at = excluded.expires_at, tries = 0, sent_at = excluded.sent_at`, |
| 94 | 109 | ).run(id, userId, email, sha256(`${id}:${code}`), new Date(now + CODE_TTL_MS).toISOString(), new Date(now).toISOString()); |
| 95 | return { connection: shown(db.query<Row, [string]>("SELECT * FROM connection WHERE id = ?1").get(id)!), code, held }; | |
| 110 | return { connection: byId(db, id), code, held }; | |
| 96 | 111 | } |
| 97 | 112 | |
| 98 | 113 | const full = (db: Database, userId: string): boolean => |
| @@ -104,13 +119,13 @@ const full = (db: Database, userId: string): boolean => | ||
| 104 | 119 | * never be proven, so the answer does not tell whether it is proven elsewhere. |
| 105 | 120 | */ |
| 106 | 121 | export function addMinecraft(db: Database, userId: string, name: string, now: number): Connection | "limit" { |
| 107 | const mine = db.query<Row, [string, string]>("SELECT * FROM connection WHERE user_id = ?1 AND kind = 'minecraft' AND ident = ?2").get(userId, name); | |
| 122 | const mine = db.query<Row, [string, string]>(`${SHOWN} WHERE c.user_id = ?1 AND c.kind = 'minecraft' AND c.ident = ?2`).get(userId, name); | |
| 108 | 123 | if (mine !== null) return shown(mine); |
| 109 | 124 | if (full(db, userId)) return "limit"; |
| 110 | 125 | const id = newId(); |
| 111 | 126 | db.query("INSERT INTO connection (id, user_id, kind, ident, created_at) VALUES (?1, ?2, 'minecraft', ?3, ?4)") |
| 112 | 127 | .run(id, userId, name, new Date(now).toISOString()); |
| 113 | return shown(db.query<Row, [string]>("SELECT * FROM connection WHERE id = ?1").get(id)!); | |
| 128 | return byId(db, id); | |
| 114 | 129 | } |
| 115 | 130 | |
| 116 | 131 | /** |
| @@ -176,7 +191,7 @@ export function setUse(db: Database, userId: string, id: string, use: Use, on: b | ||
| 176 | 191 | const col = use === "feedback" ? "use_feedback" : "use_profile"; |
| 177 | 192 | const done = db.query(`UPDATE connection SET ${col} = ?3 WHERE id = ?1 AND user_id = ?2 AND proven_at IS NOT NULL`).run(id, userId, on ? 1 : 0); |
| 178 | 193 | if (done.changes === 0) return undefined; |
| 179 | return shown(db.query<Row, [string]>("SELECT * FROM connection WHERE id = ?1").get(id)!); | |
| 194 | return byId(db, id); | |
| 180 | 195 | } |
| 181 | 196 | |
| 182 | 197 | /** The user a proven identifier belongs to, if that user switched this use on; nothing else. */ |
src/core/migration-pins/20261204221000-email-proof-in-connections.pin added +1
| @@ -0,0 +1,1 @@ | ||
| 1 | bb0d2ed763ee067b92e731d57fc78e89e16d794f8bf4a2b94b3ba88309187bfb |
src/core/migrations/20261204221000-email-proof-in-connections.ts added +20
| @@ -0,0 +1,20 @@ | ||
| 1 | // One place says an email is proven (#18222): the account's own email is proven by its email | |
| 2 | // connection (`core/verify.ts` reads `connection`), so `email_check` keeps only the links. Every | |
| 3 | // person whose email was proven gets a proven connection for that address, lowercased as a | |
| 4 | // connection keeps it; the account that holds the address outranks another account's proven extra | |
| 5 | // connection for it, which is unproven first so the one-proof index holds. `user.email` is unique | |
| 6 | // without case, so no two people meet here. `verified_at` stays for the releases still in play | |
| 7 | // during a roll (a migration is additive, #875); nothing in this release reads or writes it. | |
| 8 | export default ` | |
| 9 | UPDATE connection SET proven_at = NULL, use_feedback = 0, use_profile = 0 | |
| 10 | WHERE kind = 'email' AND proven_at IS NOT NULL AND EXISTS ( | |
| 11 | SELECT 1 FROM user u JOIN email_check c ON c.user_id = u.id | |
| 12 | WHERE c.verified_at IS NOT NULL AND u.kind = 'user' AND u.is_agent = 0 | |
| 13 | AND lower(u.email) = connection.ident AND u.id != connection.user_id); | |
| 14 | INSERT INTO connection (id, user_id, kind, ident, proven_at, created_at) | |
| 15 | SELECT lower(hex(randomblob(13))), u.id, 'email', lower(u.email), c.verified_at, c.verified_at | |
| 16 | FROM user u JOIN email_check c ON c.user_id = u.id | |
| 17 | WHERE c.verified_at IS NOT NULL AND u.kind = 'user' AND u.is_agent = 0 | |
| 18 | ON CONFLICT(user_id, kind, ident) DO UPDATE SET | |
| 19 | proven_at = COALESCE(connection.proven_at, excluded.proven_at), code_hash = NULL, expires_at = NULL; | |
| 20 | `; |
src/core/people_rows.ts +2 −2
| @@ -7,6 +7,7 @@ | ||
| 7 | 7 | */ |
| 8 | 8 | |
| 9 | 9 | import type { Database } from "bun:sqlite"; |
| 10 | import { provenEmailAt } from "./proven_identities.ts"; | |
| 10 | 11 | |
| 11 | 12 | export const WORDS = ["owner", "member", "guest", "crew member"] as const; |
| 12 | 13 | export type RoleWord = (typeof WORDS)[number]; |
| @@ -34,12 +35,11 @@ export function wordFilter(raw: string | null | undefined): RoleWord | null { | ||
| 34 | 35 | export function peopleByActivity(db: Database, only: RoleWord | null = null): PersonRow[] { |
| 35 | 36 | const rows = db |
| 36 | 37 | .query<{ username: string; is_admin: number; is_agent: number; member: string | null; seen: string | null; usd: number | null; suspended_at: string | null; verified_at: string | null }, []>( |
| 37 | `SELECT u.username, u.is_admin, u.is_agent, m.user_id AS member, g.usd_per_month AS usd, u.suspended_at, c.verified_at, | |
| 38 | `SELECT u.username, u.is_admin, u.is_agent, m.user_id AS member, g.usd_per_month AS usd, u.suspended_at, ${provenEmailAt("u")} AS verified_at, | |
| 38 | 39 | MAX(COALESCE((SELECT MAX(s.last_seen_at) FROM session s WHERE s.user_id = u.id), ''), |
| 39 | 40 | COALESCE((SELECT MAX(t.last_used_at) FROM token t WHERE t.user_id = u.id), '')) AS seen |
| 40 | 41 | FROM user u LEFT JOIN member m ON m.user_id = u.id |
| 41 | 42 | LEFT JOIN model_grant g ON g.user_id = u.id |
| 42 | LEFT JOIN email_check c ON c.user_id = u.id | |
| 43 | 43 | WHERE u.kind = 'user' AND u.removed_at IS NULL |
| 44 | 44 | ORDER BY (seen = '') , seen DESC, u.created_at DESC, u.username`, |
| 45 | 45 | ) |
src/core/proven_identities.ts +30 −14
| @@ -11,6 +11,15 @@ | ||
| 11 | 11 | */ |
| 12 | 12 | import type { Database } from "bun:sqlite"; |
| 13 | 13 | |
| 14 | /** | |
| 15 | * SQL for when the account aliased `u` proved its own email, or NULL: its proven email connection | |
| 16 | * for that address (`core/identities.ts`, #18222). Every reader of the proof asks this, so there is | |
| 17 | * no second answer. | |
| 18 | */ | |
| 19 | export const provenEmailAt = (u: string): string => | |
| 20 | `(SELECT k.proven_at FROM connection k WHERE k.user_id = ${u}.id AND k.kind = 'email' | |
| 21 | AND k.ident = lower(${u}.email) AND k.proven_at IS NOT NULL)`; | |
| 22 | ||
| 14 | 23 | export type IdentityKind = "email" | "minecraft"; |
| 15 | 24 | |
| 16 | 25 | export interface Identity { |
| @@ -37,8 +46,7 @@ export function emailIdentity(db: Database, userId: string): Identity | undefine | ||
| 37 | 46 | { email: string; kind: string; is_agent: number; verified_at: string | null }, |
| 38 | 47 | [string] |
| 39 | 48 | >( |
| 40 | `SELECT u.email, u.kind, u.is_agent, c.verified_at | |
| 41 | FROM user u LEFT JOIN email_check c ON c.user_id = u.id WHERE u.id = ?1`, | |
| 49 | `SELECT u.email, u.kind, u.is_agent, ${provenEmailAt("u")} AS verified_at FROM user u WHERE u.id = ?1`, | |
| 42 | 50 | ) |
| 43 | 51 | .get(userId); |
| 44 | 52 | if (user === null) return undefined; |
| @@ -84,9 +92,9 @@ export function listOf(db: Database, userId: string): { identities: Identity[]; | ||
| 84 | 92 | { kind: IdentityKind; name: string; proven: number; since: string | null; boxId: string | null; box: string | null; uuid: string | null; gameBox: number }, |
| 85 | 93 | [string] |
| 86 | 94 | >( |
| 87 | `SELECT 'email' AS kind, u.email AS name, (u.is_agent = 1 OR u.kind = 'org' OR c.verified_at IS NOT NULL) AS proven, | |
| 88 | c.verified_at AS since, NULL AS boxId, NULL AS box, NULL AS uuid, EXISTS (SELECT 1 FROM game_box) AS gameBox, 0 AS ord | |
| 89 | FROM user u LEFT JOIN email_check c ON c.user_id = u.id WHERE u.id = ?1 | |
| 95 | `SELECT 'email' AS kind, u.email AS name, (u.is_agent = 1 OR u.kind = 'org' OR ${provenEmailAt("u")} IS NOT NULL) AS proven, | |
| 96 | ${provenEmailAt("u")} AS since, NULL AS boxId, NULL AS box, NULL AS uuid, EXISTS (SELECT 1 FROM game_box) AS gameBox, 0 AS ord | |
| 97 | FROM user u WHERE u.id = ?1 | |
| 90 | 98 | UNION ALL |
| 91 | 99 | SELECT 'minecraft', l.player, l.uuid != '', l.created_at, l.box_id, b.name, l.uuid, 1, 1 |
| 92 | 100 | FROM game_link l JOIN user u ON u.id = l.user_id LEFT JOIN game_box b ON b.id = l.box_id WHERE l.user_id = ?1 |
| @@ -112,16 +120,24 @@ export const provenAs = (db: Database, userId: string, kind: IdentityKind): bool | ||
| 112 | 120 | /** |
| 113 | 121 | * Remove the account's email from its list (#18160): the address becomes its stand-in |
| 114 | 122 | * (`<username>@no-email.invalid`, as `noEmail` in `actions/users.ts` makes for an account that gave |
| 115 | * none) and its proof is cleared. Only a person's own address; an agent's, an organization's or a | |
| 116 | * stand-in is refused. Whether it was removed. Adding one again is the profile's email field. | |
| 123 | * none) and its email connection is unproven, so sign-in and the list both lose the proof. Only a | |
| 124 | * person's own address; an agent's, an organization's or a stand-in is refused. Whether it was | |
| 125 | * removed. Adding one again is the profile's email field. | |
| 117 | 126 | */ |
| 118 | export function removeEmail(db: Database, userId: string): boolean { | |
| 119 | const gone = db | |
| 120 | .query("UPDATE user SET email = lower(username) || '@no-email.invalid' WHERE id = ?1 AND kind = 'user' AND is_agent = 0 AND email NOT LIKE '%.invalid'") | |
| 121 | .run(userId).changes > 0; | |
| 122 | if (gone) db.query("UPDATE email_check SET verified_at = NULL, token_hash = NULL, expires_at = NULL WHERE user_id = ?1").run(userId); | |
| 123 | return gone; | |
| 124 | } | |
| 127 | export const removeEmail = (db: Database, userId: string): boolean => | |
| 128 | db.transaction((): boolean => { | |
| 129 | const was = db | |
| 130 | .query<{ email: string }, [string]>("SELECT lower(email) AS email FROM user WHERE id = ?1 AND kind = 'user' AND is_agent = 0 AND email NOT LIKE '%.invalid'") | |
| 131 | .get(userId); | |
| 132 | if (was === null) return false; | |
| 133 | db.query("UPDATE user SET email = lower(username) || '@no-email.invalid' WHERE id = ?1").run(userId); | |
| 134 | db.query( | |
| 135 | `UPDATE connection SET proven_at = NULL, use_feedback = 0, use_profile = 0 | |
| 136 | WHERE user_id = ?1 AND kind = 'email' AND ident = ?2`, | |
| 137 | ).run(userId, was.email); | |
| 138 | db.query("UPDATE email_check SET token_hash = NULL, expires_at = NULL WHERE user_id = ?1").run(userId); | |
| 139 | return true; | |
| 140 | })(); | |
| 125 | 141 | |
| 126 | 142 | /** What removing the email says, at both doors. */ |
| 127 | 143 | export const REMOVED_EMAIL = "Email removed. Add one again in the profile; it starts unproven."; |
src/core/roles.ts +4 −3
| @@ -11,6 +11,7 @@ | ||
| 11 | 11 | import { storedText } from "../kernel/blocked.ts"; |
| 12 | 12 | import type { Database } from "bun:sqlite"; |
| 13 | 13 | import { isUnclaimed } from "./starts.ts"; |
| 14 | import { provenEmailAt } from "./proven_identities.ts"; | |
| 14 | 15 | |
| 15 | 16 | export const ROLES = ["guest", "member", "admin"] as const; |
| 16 | 17 | export type Role = (typeof ROLES)[number]; |
| @@ -145,7 +146,7 @@ export interface Person { | ||
| 145 | 146 | readonly usdPerMonth: number | null; |
| 146 | 147 | /** When the owner suspended the account; null while it is in good standing. */ |
| 147 | 148 | readonly suspendedAt: string | null; |
| 148 | /** Whether the email is proven: a link followed or an owner's word (`core/verify.ts`). */ | |
| 149 | /** Whether the email is proven: its email connection (`core/verify.ts`). */ | |
| 149 | 150 | readonly verified: boolean; |
| 150 | 151 | } |
| 151 | 152 | |
| @@ -153,11 +154,11 @@ export interface Person { | ||
| 153 | 154 | export function listPeople(db: Database): Person[] { |
| 154 | 155 | return db |
| 155 | 156 | .query<{ username: string; is_admin: number; member: number | null; usd: number | null; suspended_at: string | null; verified_at: string | null }, []>( |
| 156 | `SELECT u.username, u.is_admin, m.user_id AS member, g.usd_per_month AS usd, u.suspended_at, c.verified_at | |
| 157 | `SELECT u.username, u.is_admin, m.user_id AS member, g.usd_per_month AS usd, u.suspended_at, | |
| 158 | ${provenEmailAt("u")} AS verified_at | |
| 157 | 159 | FROM user u |
| 158 | 160 | LEFT JOIN member m ON m.user_id = u.id |
| 159 | 161 | LEFT JOIN model_grant g ON g.user_id = u.id |
| 160 | LEFT JOIN email_check c ON c.user_id = u.id | |
| 161 | 162 | WHERE u.kind = 'user' AND u.is_agent = 0 AND u.removed_at IS NULL |
| 162 | 163 | ORDER BY u.created_at DESC, u.username`, |
| 163 | 164 | ) |
src/core/verify.ts +59 −22
| @@ -3,18 +3,25 @@ | ||
| 3 | 3 | * it. Pure data: the actions send the mail and decide what an unproven |
| 4 | 4 | * account may not do (`actions/verify.ts`). |
| 5 | 5 | * |
| 6 | * Fail closed: an account without a proven row is unproven. \`createUser\` | |
| 7 | * writes an unproven row for every person unless its caller vouches for the | |
| 8 | * address (\`trusted\`: a seeded admin, a claim, a fixture), and the | |
| 9 | * migration that made this table proved every account that already | |
| 10 | * existed. An agent is never held back (no mail reaches it), nor an | |
| 11 | * organization, which cannot sign in. A link's secret is stored only as its | |
| 12 | * hash, works once, and expires. | |
| 6 | * One place says an email is proven: the account's connections | |
| 7 | * (`core/identities.ts`, #18222). The account's email is proven when it has | |
| 8 | * a proven email connection for that address — by the link here, an owner's | |
| 9 | * word, or the connection's own code — and removing that connection unproves | |
| 10 | * it. `email_check` keeps only the links: their hashes, expiry and how many | |
| 11 | * were sent. | |
| 12 | * | |
| 13 | * Fail closed: an account without a proven connection for its address is | |
| 14 | * unproven. \`createUser\` proves only when its caller vouches for the | |
| 15 | * address (\`trusted\`: a seeded admin, a claim, a fixture). An agent is | |
| 16 | * never held back (no mail reaches it), nor an organization, which cannot | |
| 17 | * sign in. A link's secret is stored only as its hash, works once, and | |
| 18 | * expires. | |
| 13 | 19 | */ |
| 14 | 20 | |
| 15 | 21 | import type { Database } from "bun:sqlite"; |
| 16 | 22 | import { sha256 } from "../kernel/hash.ts"; |
| 17 | import { provenAs } from "./proven_identities.ts"; | |
| 23 | import { id as newId } from "../kernel/id.ts"; | |
| 24 | import { provenAs, provenEmailAt } from "./proven_identities.ts"; | |
| 18 | 25 | |
| 19 | 26 | /** How long a link works. */ |
| 20 | 27 | export const LINK_TTL_MS = 24 * 3_600_000; |
| @@ -24,6 +31,9 @@ export const RESEND_AFTER_MS = 5 * 60_000; | ||
| 24 | 31 | const secret = (): string => |
| 25 | 32 | Buffer.from(crypto.getRandomValues(new Uint8Array(32))).toString("base64url"); |
| 26 | 33 | |
| 34 | /** SQL: the `email_check` row's account has proven its email. */ | |
| 35 | const SLOT_PROVEN = `EXISTS (SELECT 1 FROM user u WHERE u.id = email_check.user_id AND ${provenEmailAt("u")} IS NOT NULL)`; | |
| 36 | ||
| 27 | 37 | /** Whether the account's email is proven: read from its one list of identities (#18160). */ |
| 28 | 38 | export const emailVerified = (db: Database, userId: string): boolean => provenAs(db, userId, "email"); |
| 29 | 39 | |
| @@ -32,22 +42,49 @@ export function markUnproven(db: Database, userId: string): void { | ||
| 32 | 42 | db.query("INSERT OR IGNORE INTO email_check (user_id) VALUES (?1)").run(userId); |
| 33 | 43 | } |
| 34 | 44 | |
| 35 | /** Mark proven without a link: an account its maker vouches for, an owner's word. */ | |
| 45 | /** | |
| 46 | * Mark proven without a link: an account its maker vouches for, an owner's | |
| 47 | * word, a link followed. The account's email connection is proven; a fresh | |
| 48 | * proof by the account that holds the address outranks an older one another | |
| 49 | * account kept as an extra connection, which is unproven. | |
| 50 | */ | |
| 36 | 51 | export function markVerified(db: Database, userId: string, at: string): void { |
| 37 | db.query( | |
| 38 | `INSERT INTO email_check (user_id, verified_at) VALUES (?1, ?2) | |
| 39 | ON CONFLICT(user_id) DO UPDATE SET verified_at = excluded.verified_at, | |
| 40 | token_hash = NULL, expires_at = NULL`, | |
| 41 | ).run(userId, at); | |
| 52 | db.transaction(() => { | |
| 53 | db.query( | |
| 54 | `INSERT INTO email_check (user_id) VALUES (?1) | |
| 55 | ON CONFLICT(user_id) DO UPDATE SET token_hash = NULL, expires_at = NULL`, | |
| 56 | ).run(userId); | |
| 57 | db.query( | |
| 58 | `UPDATE connection SET proven_at = NULL, use_feedback = 0, use_profile = 0 | |
| 59 | WHERE kind = 'email' AND proven_at IS NOT NULL AND user_id != ?1 | |
| 60 | AND ident = (SELECT lower(email) FROM user WHERE id = ?1)`, | |
| 61 | ).run(userId); | |
| 62 | db.query( | |
| 63 | `INSERT INTO connection (id, user_id, kind, ident, proven_at, created_at) | |
| 64 | SELECT ?2, id, 'email', lower(email), ?3, ?3 FROM user WHERE id = ?1 | |
| 65 | ON CONFLICT(user_id, kind, ident) DO UPDATE SET | |
| 66 | proven_at = COALESCE(connection.proven_at, excluded.proven_at), | |
| 67 | code_hash = NULL, expires_at = NULL, tries = 0`, | |
| 68 | ).run(userId, newId(), at); | |
| 69 | })(); | |
| 42 | 70 | } |
| 43 | 71 | |
| 44 | /** A new address is unproven again; any link to the old one stops working. */ | |
| 45 | export function resetVerification(db: Database, userId: string): void { | |
| 72 | /** | |
| 73 | * The address must be proven again (a sign-up, a changed address): its | |
| 74 | * connection is unproven with its uses off, and any link stops working. | |
| 75 | * `was`, the address before a change, is unproven too, so changing back to | |
| 76 | * it later needs a fresh proof. | |
| 77 | */ | |
| 78 | export function resetVerification(db: Database, userId: string, was?: string): void { | |
| 46 | 79 | db.query( |
| 47 | 80 | `INSERT INTO email_check (user_id) VALUES (?1) |
| 48 | ON CONFLICT(user_id) DO UPDATE SET verified_at = NULL, | |
| 49 | token_hash = NULL, expires_at = NULL`, | |
| 81 | ON CONFLICT(user_id) DO UPDATE SET token_hash = NULL, expires_at = NULL`, | |
| 50 | 82 | ).run(userId); |
| 83 | db.query( | |
| 84 | `UPDATE connection SET proven_at = NULL, use_feedback = 0, use_profile = 0 | |
| 85 | WHERE user_id = ?1 AND kind = 'email' AND proven_at IS NOT NULL | |
| 86 | AND ident IN ((SELECT lower(email) FROM user WHERE id = ?1), lower(?2))`, | |
| 87 | ).run(userId, was ?? null); | |
| 51 | 88 | } |
| 52 | 89 | |
| 53 | 90 | /** The most links one account may be sent in a UTC day, whatever the address. */ |
| @@ -107,7 +144,7 @@ export function consumeLink( | ||
| 107 | 144 | .query< |
| 108 | 145 | { user_id: string; expires_at: string | null }, |
| 109 | 146 | [string] |
| 110 | >("SELECT user_id, expires_at FROM email_check WHERE token_hash = ?1 AND verified_at IS NULL") | |
| 147 | >(`SELECT user_id, expires_at FROM email_check WHERE token_hash = ?1 AND NOT ${SLOT_PROVEN}`) | |
| 111 | 148 | .get(sha256(token)); |
| 112 | 149 | if (row === null || row.expires_at === null) return undefined; |
| 113 | 150 | if (Date.parse(row.expires_at) <= now) return undefined; |
| @@ -133,7 +170,7 @@ export function issueRecovery( | ||
| 133 | 170 | const changed = db |
| 134 | 171 | .query( |
| 135 | 172 | `UPDATE email_check SET token_hash = ?2, expires_at = ?3 |
| 136 | WHERE user_id = ?1 AND verified_at IS NOT NULL`, | |
| 173 | WHERE user_id = ?1 AND ${SLOT_PROVEN}`, | |
| 137 | 174 | ) |
| 138 | 175 | .run(userId, sha256(token), new Date(now + RECOVERY_TTL_MS).toISOString()); |
| 139 | 176 | return changed.changes > 0 ? token : undefined; |
| @@ -153,7 +190,7 @@ export function recoveryOwner( | ||
| 153 | 190 | db |
| 154 | 191 | .query<{ user_id: string }, [string, string]>( |
| 155 | 192 | `SELECT user_id FROM email_check |
| 156 | WHERE token_hash = ?1 AND verified_at IS NOT NULL AND expires_at > ?2`, | |
| 193 | WHERE token_hash = ?1 AND ${SLOT_PROVEN} AND expires_at > ?2`, | |
| 157 | 194 | ) |
| 158 | 195 | .get(sha256(token), new Date(now).toISOString())?.user_id ?? undefined |
| 159 | 196 | ); |
| @@ -170,7 +207,7 @@ export function spendRecovery( | ||
| 170 | 207 | db |
| 171 | 208 | .query<{ user_id: string }, [string, string]>( |
| 172 | 209 | `UPDATE email_check SET token_hash = NULL, expires_at = NULL |
| 173 | WHERE token_hash = ?1 AND verified_at IS NOT NULL AND expires_at > ?2 | |
| 210 | WHERE token_hash = ?1 AND ${SLOT_PROVEN} AND expires_at > ?2 | |
| 174 | 211 | RETURNING user_id`, |
| 175 | 212 | ) |
| 176 | 213 | .get(sha256(token), new Date(now).toISOString())?.user_id ?? undefined |
src/http/api/identities.ts +5 −3
| @@ -3,7 +3,8 @@ | ||
| 3 | 3 | * lists the caller's; `POST` adds an email and mails a code, or `{minecraft}` |
| 4 | 4 | * keeps a Minecraft name the game door proves (#18221); `POST |
| 5 | 5 | * /:id/confirm {code}` proves it; `PUT /:id/uses/:use {on}` chooses a use; |
| 6 | * `DELETE /:id` removes. `POST /lookup` is the integrations' question, | |
| 6 | * `DELETE /:id` removes (the address the account signs in with only with | |
| 7 | * `?confirm=true`). `POST /lookup` is the integrations' question, | |
| 7 | 8 | * carrying a lookup key in `X-Forge-Lookup-Key` (never a user token); an |
| 8 | 9 | * admin makes keys at `/lookup-keys`. The account itself acts, same-origin. |
| 9 | 10 | */ |
| @@ -21,7 +22,7 @@ import type { Router } from "../router.ts"; | ||
| 21 | 22 | /** The status each refusal answers with, 0 for the ones that wait; the words are the action's. */ |
| 22 | 23 | const STATUS: Record<ConnectionError, number> = { |
| 23 | 24 | invalid_email: 422, invalid_minecraft: 422, limit: 422, taken: 409, too_soon: 0, no_mail: 0, capped: 0, failed: 502, |
| 24 | wrong_code: 422, not_found: 404, invalid_use: 422, invalid_name: 422, | |
| 25 | wrong_code: 422, not_found: 404, invalid_use: 422, invalid_name: 422, confirm_sign_in: 409, | |
| 25 | 26 | }; |
| 26 | 27 | /** Seconds to wait, for the refusals that wait; the rest answer through apiError. */ |
| 27 | 28 | const WAITS: Partial<Record<ConnectionError, number>> = { too_soon: 60, no_mail: 3600, capped: 3600 }; |
| @@ -70,7 +71,8 @@ export function identityRoutes(router: Router<Handler>): void { | ||
| 70 | 71 | router.add("DELETE", "/api/v1/connections/:id", (ctx) => { |
| 71 | 72 | const denied = requireAccount(ctx, { adminToken: true }); |
| 72 | 73 | if (denied) return denied; |
| 73 | const done = dropConnection(ctx.app, ctx.auth.user!, ctx.params["id"] ?? ""); | |
| 74 | const confirmed = ctx.url.searchParams.get("confirm") === "true"; | |
| 75 | const done = dropConnection(ctx.app, ctx.auth.user!, ctx.params["id"] ?? "", confirmed); | |
| 74 | 76 | return done.ok ? json({ removed: true, note: NOT_RETROACTIVE }, 200, noStore) : refuse(done.error); |
| 75 | 77 | }); |
| 76 | 78 |
src/tui/screens/identities.ts +8 −6
| @@ -2,12 +2,13 @@ | ||
| 2 | 2 | * Proven identities in the terminal (#18108), as Settings › Proven identities: `a` adds an address |
| 3 | 3 | * and mails a code, `c` gives the code back, `m` keeps a Minecraft name the game door proves |
| 4 | 4 | * (#18221), `f` and `p` switch the feedback and profile uses on or |
| 5 | * off, `d` removes after a y/n. The same actions as the API and the page, so the same gates and | |
| 6 | * words; the list is the signed-in account's own. | |
| 5 | * off, `d` removes after a y/n (for the address the account signs in with, the y/n says first | |
| 6 | * that removing it means proving it again, #18222). The same actions as the API and the page, so | |
| 7 | * the same gates and words; the list is the signed-in account's own. | |
| 7 | 8 | */ |
| 8 | 9 | |
| 9 | 10 | import { |
| 10 | CONNECTION_WORDS, MINECRAFT_PROOF, NOT_RETROACTIVE, addConnection, addMinecraftConnection, chooseUse, | |
| 11 | CONNECTION_WORDS, MINECRAFT_PROOF, NOT_RETROACTIVE, SIGN_IN_ADDRESS, addConnection, addMinecraftConnection, chooseUse, | |
| 11 | 12 | confirmConnection, connectionsOf, dropConnection, |
| 12 | 13 | } from "../../actions/identities.ts"; |
| 13 | 14 | import type { Use } from "../../core/identities.ts"; |
| @@ -27,7 +28,7 @@ export function identitiesScreen(f: Session, ctx: Ctx): Screen { | ||
| 27 | 28 | items().map((c) => ({ |
| 28 | 29 | title: c.kind === "minecraft" ? `${c.ident} (Minecraft)` : c.ident, |
| 29 | 30 | meta: c.proven |
| 30 | ? `proven · feedback ${c.uses.feedback ? "on" : "off"} · profile ${c.uses.profile ? "on" : "off"}` | |
| 31 | ? `proven${c.signIn ? " · you sign in with it" : ""} · feedback ${c.uses.feedback ? "on" : "off"} · profile ${c.uses.profile ? "on" : "off"}` | |
| 31 | 32 | : c.kind === "minecraft" ? "not proven yet: link it in game" : "not proven yet: c gives the code", |
| 32 | 33 | })); |
| 33 | 34 | const toggle = (use: Use): boolean => { |
| @@ -98,12 +99,13 @@ export function identitiesScreen(f: Session, ctx: Ctx): Screen { | ||
| 98 | 99 | } |
| 99 | 100 | if (e.key === "d") { |
| 100 | 101 | ctx.push(confirmScreen(ctx, screen, { |
| 101 | title: "Remove connection", body: [`remove ${c.ident}? y/n`], | |
| 102 | title: "Remove connection", ...(c.signIn ? { width: 72 } : {}), | |
| 103 | body: c.signIn ? [...SIGN_IN_ADDRESS.split(/(?<=\.) /), `remove ${c.ident}? y/n`] : [`remove ${c.ident}? y/n`], | |
| 102 | 104 | actions: [{ label: "Remove", variant: "danger" }, { label: "Cancel", variant: "ghost" }], |
| 103 | 105 | selected: 1, yesNo: true, |
| 104 | 106 | onChoose: (i) => { |
| 105 | 107 | if (i !== 0) return; |
| 106 | const gone = dropConnection(f.app, user, c.id); | |
| 108 | const gone = dropConnection(f.app, user, c.id, true); | |
| 107 | 109 | note = gone.ok ? `Removed. ${NOT_RETROACTIVE}` : CONNECTION_WORDS[gone.error]; |
| 108 | 110 | ctx.invalidate(); |
| 109 | 111 | }, |
src/web/pages/identities.ts +14 −6
| @@ -3,12 +3,13 @@ | ||
| 3 | 3 | * (#18221, proven by the game door's link), each with its own uses, all off until chosen. |
| 4 | 4 | * Server-rendered; every act is a same-origin form (`readForm`), by the signed-in account alone, |
| 5 | 5 | * through the actions the API and the terminal use. The note beside the uses says what switching |
| 6 | * off does not undo. | |
| 6 | * off does not undo. The address the account signs in with (#18222) says so, and its Remove asks | |
| 7 | * for a tick first: removing it puts the account back behind the email gate. | |
| 7 | 8 | */ |
| 8 | 9 | |
| 9 | 10 | import { sshOn } from "../../settings/ssh.ts"; |
| 10 | 11 | import { |
| 11 | CONNECTION_WORDS, MINECRAFT_PROOF, NOT_RETROACTIVE, addConnection, addMinecraftConnection, chooseUse, | |
| 12 | CONNECTION_WORDS, MINECRAFT_PROOF, NOT_RETROACTIVE, SIGN_IN_ADDRESS, addConnection, addMinecraftConnection, chooseUse, | |
| 12 | 13 | confirmConnection, connectionsOf, dropConnection, |
| 13 | 14 | } from "../../actions/identities.ts"; |
| 14 | 15 | import { USES, type Connection, type Use } from "../../core/identities.ts"; |
| @@ -47,11 +48,18 @@ const card = (c: Connection): Html => { | ||
| 47 | 48 | placeholder="Code from the mail" aria-label="Code mailed to ${c.ident}" required /> |
| 48 | 49 | ${btn("Prove", { variant: "primary", size: "sm", label: `Prove ${c.ident}` })}`, |
| 49 | 50 | ); |
| 51 | const remove = btn("Remove", { size: "sm", icon: "x", label: `Remove ${c.ident}` }); | |
| 50 | 52 | return row({ |
| 51 | 53 | title: html`<span class="mono">${c.ident}</span>`, |
| 52 | meta: html`${c.kind === "minecraft" ? "Minecraft · " : ""}${c.proven ? "proven" : "not proven yet"}`, | |
| 53 | trail: act("delete", btn("Remove", { size: "sm", icon: "x", label: `Remove ${c.ident}` })), | |
| 54 | after: html`${uses}`, | |
| 54 | meta: html`${c.kind === "minecraft" ? "Minecraft · " : ""}${c.proven ? "proven" : "not proven yet"}${c.signIn ? " · you sign in with it" : ""}`, | |
| 55 | ...(c.signIn ? {} : { trail: act("delete", remove) }), | |
| 56 | after: c.signIn | |
| 57 | ? html`${uses}<p class="muted small">${SIGN_IN_ADDRESS}</p>${act( | |
| 58 | "delete", | |
| 59 | html`<label class="check"><input type="checkbox" name="confirm" value="sign-in" required /> | |
| 60 | <span>Remove it anyway</span></label>${remove}`, | |
| 61 | )}` | |
| 62 | : html`${uses}`, | |
| 55 | 63 | }); |
| 56 | 64 | }; |
| 57 | 65 | |
| @@ -134,6 +142,6 @@ export async function identityUse(ctx: Ctx): Promise<Response> { | ||
| 134 | 142 | export async function identityRemove(ctx: Ctx): Promise<Response> { |
| 135 | 143 | const got = await acting(ctx); |
| 136 | 144 | if (got instanceof Response) return got; |
| 137 | const done = dropConnection(ctx.app, ctx.auth.user!, ctx.params["id"] ?? ""); | |
| 145 | const done = dropConnection(ctx.app, ctx.auth.user!, ctx.params["id"] ?? "", field(got.form, "confirm") === "sign-in"); | |
| 138 | 146 | return said(ctx, done.ok ? "Removed. " + NOT_RETROACTIVE : CONNECTION_WORDS[done.error], done.ok); |
| 139 | 147 | } |
test/first-ask-first-tell.test.ts +2 −1
| @@ -11,6 +11,7 @@ import { firstBoot } from "../src/spawn/first-boot.ts"; | ||
| 11 | 11 | import { startedFromOf } from "../src/spawn/template_record.ts"; |
| 12 | 12 | import { startedForge, type StartedForge } from "./helpers/claimed-forge.ts"; |
| 13 | 13 | import { quietLogs } from "./helpers/globals.ts"; |
| 14 | import { unproveAll } from "./helpers/verified.ts"; | |
| 14 | 15 | |
| 15 | 16 | quietLogs(); |
| 16 | 17 | |
| @@ -63,7 +64,7 @@ test("the first ask is filed as the first tell, once, and leaves the record", as | ||
| 63 | 64 | }); |
| 64 | 65 | |
| 65 | 66 | test("a refused tell leaves the ask in the record", async () => { |
| 66 | forge.child.db.query("UPDATE email_check SET verified_at = NULL").run(); | |
| 67 | unproveAll(forge.child.db); | |
| 67 | 68 | const before = titles(); |
| 68 | 69 | await rebootWith({ id: "a/b", repo: "a/b", firstAsk: "Add a refused page" }); |
| 69 | 70 | expect(titles().filter((t) => !before.includes(t))).not.toContain("Add a refused page"); |
test/guest-contribute.test.ts +2 −3
| @@ -30,7 +30,7 @@ import { BECOME_A_MEMBER, NOT_A_MEMBER, setMember } from "../src/core/roles.ts"; | ||
| 30 | 30 | import { createSession } from "../src/core/sessions.ts"; |
| 31 | 31 | import { createToken } from "../src/core/tokens.ts"; |
| 32 | 32 | import { createUser, getUserByName, type User } from "../src/core/users.ts"; |
| 33 | import { markVerified } from "../src/core/verify.ts"; | |
| 33 | import { markVerified, resetVerification } from "../src/core/verify.ts"; | |
| 34 | 34 | import { foldWall } from "../src/crew/fold_walls.ts"; |
| 35 | 35 | import { landIfGreen } from "../src/crew/land_queue.ts"; |
| 36 | 36 | import { queueAgentRun } from "../src/crew/dispatch.ts"; |
| @@ -283,8 +283,7 @@ describe("a guest helps build a public repository", () => { | ||
| 283 | 283 | test("an account with no confirmed email is told to confirm it", async () => { |
| 284 | 284 | const made = await createUser(app.db, { origin: "seed", username: "unproven", email: "[email protected]", password: "correct-horse-battery" }); |
| 285 | 285 | if (!made.ok) throw new Error(made.error); |
| 286 | app.db.query("INSERT OR IGNORE INTO email_check (user_id) VALUES (?1)").run(made.value.id); | |
| 287 | app.db.query("UPDATE email_check SET verified_at = NULL WHERE user_id = ?1").run(made.value.id); | |
| 286 | resetVerification(app.db, made.value.id); | |
| 288 | 287 | const forked = await forkRepo(app, getUserByName(app.db, "unproven")!, lib); |
| 289 | 288 | expect(!forked.ok && forked.error).toBe("unverified"); |
| 290 | 289 | }); |
test/helpers/verified.ts +11 −5
| @@ -1,4 +1,6 @@ | ||
| 1 | import type { Database } from "bun:sqlite"; | |
| 1 | 2 | import type { App } from "../../src/app.ts"; |
| 3 | import { emailVerified, markVerified, resetVerification } from "../../src/core/verify.ts"; | |
| 2 | 4 | import { signUp as signUpAction } from "../../src/actions/users.ts"; |
| 3 | 5 | import { fixtureSlot } from "./slot.ts"; |
| 4 | 6 | |
| @@ -9,11 +11,15 @@ import { fixtureSlot } from "./slot.ts"; | ||
| 9 | 11 | * (`test/verify-email.test.ts`), and here it would only be in the way. |
| 10 | 12 | */ |
| 11 | 13 | export function proveAll(app: App): void { |
| 12 | app.db | |
| 13 | .query( | |
| 14 | "UPDATE email_check SET verified_at = ?1 WHERE verified_at IS NULL", | |
| 15 | ) | |
| 16 | .run(new Date().toISOString()); | |
| 14 | const at = new Date().toISOString(); | |
| 15 | for (const { user_id } of app.db.query<{ user_id: string }, []>("SELECT user_id FROM email_check").all()) | |
| 16 | if (!emailVerified(app.db, user_id)) markVerified(app.db, user_id, at); | |
| 17 | } | |
| 18 | ||
| 19 | /** Every person's email unproven again, as a fresh sign-up's is (`resetVerification`). */ | |
| 20 | export function unproveAll(db: Database): void { | |
| 21 | for (const { user_id } of db.query<{ user_id: string }, []>("SELECT user_id FROM email_check").all()) | |
| 22 | resetVerification(db, user_id); | |
| 17 | 23 | } |
| 18 | 24 | |
| 19 | 25 | /** `signUp`, with the new account's email already proven. */ |
test/home-feed.test.ts +3 −4
| @@ -6,6 +6,7 @@ | ||
| 6 | 6 | * `feed` tool answers the same posts. Nothing private, nor an admin's |
| 7 | 7 | * configuration, reaches a reader's timeline. |
| 8 | 8 | */ |
| 9 | import { markVerified, resetVerification } from "../src/core/verify.ts"; | |
| 9 | 10 | import { freshHome } from "./helpers/home-fresh.ts"; |
| 10 | 11 | import { afterAll, beforeAll, describe, expect, test } from "bun:test"; |
| 11 | 12 | import { mkdtemp, rm } from "node:fs/promises"; |
| @@ -311,7 +312,7 @@ describe("home is the feed", () => { | ||
| 311 | 312 | expect(forged.status).toBe(403); |
| 312 | 313 | // The one tell's refusals: an unverified writer is told to verify, and |
| 313 | 314 | // nothing is opened. |
| 314 | app.db.query(`UPDATE email_check SET verified_at = NULL WHERE user_id = ?1`).run(alice.id); | |
| 315 | resetVerification(app.db, alice.id); | |
| 315 | 316 | try { |
| 316 | 317 | const open = listIssues(app.db, garden.id, { state: "open" }).length; |
| 317 | 318 | const unverified = await fetch(`${servers.url}/tell`, { |
| @@ -326,9 +327,7 @@ describe("home is the feed", () => { | ||
| 326 | 327 | ); |
| 327 | 328 | expect(listIssues(app.db, garden.id, { state: "open" }).length).toBe(open); |
| 328 | 329 | } finally { |
| 329 | app.db | |
| 330 | .query(`UPDATE email_check SET verified_at = ?1 WHERE user_id = ?2`) | |
| 331 | .run(new Date().toISOString(), alice.id); | |
| 330 | markVerified(app.db, alice.id, new Date().toISOString()); | |
| 332 | 331 | } |
| 333 | 332 | }); |
| 334 | 333 |
test/identities-doors.test.ts +80 −10
| @@ -1,7 +1,8 @@ | ||
| 1 | 1 | /** |
| 2 | 2 | * The two doors of connections on an account (#18108): Settings › Proven identities and the |
| 3 | 3 | * terminal screen. Both gate on the signed-in account, answer a form only same-origin, escape what |
| 4 | * they show, and act through the same actions as the API. | |
| 4 | * they show, and act through the same actions as the API. The address the account signs in with | |
| 5 | * (#18222) is marked at every door, and removed only once confirmed. | |
| 5 | 6 | */ |
| 6 | 7 | import { afterAll, beforeAll, expect, test } from "bun:test"; |
| 7 | 8 | import { mkdtemp, rm } from "node:fs/promises"; |
| @@ -12,8 +13,10 @@ import { addEmail, listConnections, proveEmail } from "../src/core/identities.ts | ||
| 12 | 13 | import { createSession } from "../src/core/sessions.ts"; |
| 13 | 14 | import { createUser, type User } from "../src/core/users.ts"; |
| 14 | 15 | import { serve, type Servers } from "../src/http/server.ts"; |
| 15 | import type { Ctx } from "../src/tui/app/app.ts"; | |
| 16 | import type { Ctx, Screen } from "../src/tui/app/app.ts"; | |
| 16 | 17 | import { identitiesScreen } from "../src/tui/screens/identities.ts"; |
| 18 | import { SIGN_IN_ADDRESS } from "../src/actions/identities.ts"; | |
| 19 | import { emailVerified } from "../src/core/verify.ts"; | |
| 17 | 20 | import type { Session } from "../src/tui/session.ts"; |
| 18 | 21 | import type { KeyEvent } from "../src/tui/term/input.ts"; |
| 19 | 22 | import { Screen as Surface } from "../src/tui/term/screen.ts"; |
| @@ -44,6 +47,12 @@ afterAll(async () => { | ||
| 44 | 47 | await rm(dir, { recursive: true, force: true }); |
| 45 | 48 | }); |
| 46 | 49 | |
| 50 | /** | |
| 51 | * The connections added here: the account's own address is listed too, proven by its maker's word | |
| 52 | * (#18222). | |
| 53 | */ | |
| 54 | const added = () => listConnections(app.db, tess.id).filter((c) => c.ident !== tess.email); | |
| 55 | ||
| 47 | 56 | const form = (path: string, fields: Record<string, string>, origin = "https://forge.example", c = cookie) => |
| 48 | 57 | fetch(`${servers.url}${path}`, { |
| 49 | 58 | method: "POST", |
| @@ -57,27 +66,27 @@ test("the page needs a signed-in account and a same-origin form", async () => { | ||
| 57 | 66 | expect(anon.status).toBe(303); |
| 58 | 67 | expect((await form("/settings/identities", { email: "[email protected]" }, "https://forge.example", "")).status).toBe(303); |
| 59 | 68 | expect((await form("/settings/identities", { email: "[email protected]" }, "https://evil.example")).status).toBe(403); |
| 60 | expect(listConnections(app.db, tess.id)).toEqual([]); | |
| 69 | expect(added()).toEqual([]); | |
| 61 | 70 | }); |
| 62 | 71 | |
| 63 | 72 | test("add, prove, choose and remove by the page's forms; the note and the address are escaped", async () => { |
| 64 | 73 | expect((await form("/settings/identities", { email: "[email protected]" })).status).toBe(303); |
| 65 | const c = listConnections(app.db, tess.id)[0]!; | |
| 74 | const c = added()[0]!; | |
| 66 | 75 | expect(c.proven).toBe(false); |
| 67 | 76 | expect((await form(`/settings/identities/${c.id}/confirm`, { code: "000000" })).status).toBe(303); |
| 68 | expect(listConnections(app.db, tess.id)[0]!.proven).toBe(false); | |
| 77 | expect(added()[0]!.proven).toBe(false); | |
| 69 | 78 | const code = /code is (\d{6})/.exec(sent.at(-1)!)![1]!; |
| 70 | 79 | await form(`/settings/identities/${c.id}/confirm`, { code }); |
| 71 | expect(listConnections(app.db, tess.id)[0]!.proven).toBe(true); | |
| 80 | expect(added()[0]!.proven).toBe(true); | |
| 72 | 81 | await form(`/settings/identities/${c.id}/use`, { use: "feedback", on: "true" }); |
| 73 | expect(listConnections(app.db, tess.id)[0]!.uses).toEqual({ feedback: true, profile: false }); | |
| 82 | expect(added()[0]!.uses).toEqual({ feedback: true, profile: false }); | |
| 74 | 83 | await form(`/settings/identities/${c.id}/use`, { use: "bogus", on: "true" }); |
| 75 | expect(listConnections(app.db, tess.id)[0]!.uses.profile).toBe(false); | |
| 84 | expect(added()[0]!.uses.profile).toBe(false); | |
| 76 | 85 | const html = await (await fetch(`${servers.url}/settings/identities`, { headers: { cookie } })).text(); |
| 77 | 86 | expect(html).toContain("[email protected]"); |
| 78 | 87 | expect(html).toContain("Issues already filed are not rewritten"); |
| 79 | 88 | await form(`/settings/identities/${c.id}/delete`, {}); |
| 80 | expect(listConnections(app.db, tess.id)).toEqual([]); | |
| 89 | expect(added()).toEqual([]); | |
| 81 | 90 | }); |
| 82 | 91 | |
| 83 | 92 | test("another account's connection is not found through the page", async () => { |
| @@ -86,7 +95,7 @@ test("another account's connection is not found through the page", async () => { | ||
| 86 | 95 | const made = addEmail(app.db, o.value.id, "[email protected]", Date.now()); |
| 87 | 96 | if (typeof made === "string") throw new Error(made); |
| 88 | 97 | await form(`/settings/identities/${made.connection.id}/delete`, {}); |
| 89 | expect(listConnections(app.db, o.value.id)).toHaveLength(1); | |
| 98 | expect(listConnections(app.db, o.value.id).map((c) => c.ident)).toEqual(["[email protected]", "[email protected]"]); | |
| 90 | 99 | }); |
| 91 | 100 | |
| 92 | 101 | test("the terminal screen lists the account's own, switches a use and removes", () => { |
| @@ -134,3 +143,64 @@ test("a Minecraft name is added by the page's form and the terminal's m, shown u | ||
| 134 | 143 | expect(screen.key!({ type: "key", key: "m", ctrl: false, alt: false, shift: false })).toBe(true); |
| 135 | 144 | expect(pushed).toHaveLength(1); |
| 136 | 145 | }); |
| 146 | ||
| 147 | /** A fresh trusted account, its own address listed and proven, and its session cookie. */ | |
| 148 | const own = async (username: string): Promise<{ user: User; cookie: string; id: string }> => { | |
| 149 | const made = await createUser(app.db, { origin: "seed", trusted: true, username, email: `${username}@f.dev` }); | |
| 150 | if (!made.ok) throw new Error("user"); | |
| 151 | const id = listConnections(app.db, made.value.id).find((c) => c.signIn)!.id; | |
| 152 | return { user: made.value, cookie: `forge_session=${createSession(app.db, made.value.id).token}`, id }; | |
| 153 | }; | |
| 154 | ||
| 155 | test("the page marks the address you sign in with, says what removing it does, and removes it only when ticked", async () => { | |
| 156 | const una = await own("una"); | |
| 157 | const html = await (await fetch(`${servers.url}/settings/identities`, { headers: { cookie: una.cookie } })).text(); | |
| 158 | expect(html).toContain("you sign in with it"); | |
| 159 | expect(html).toContain(SIGN_IN_ADDRESS); | |
| 160 | expect(html).toContain('name="confirm" value="sign-in" required'); | |
| 161 | const refused = await form(`/settings/identities/${una.id}/delete`, {}, "https://forge.example", una.cookie); | |
| 162 | expect(refused.status).toBe(303); | |
| 163 | expect(emailVerified(app.db, una.user.id)).toBe(true); | |
| 164 | expect(listConnections(app.db, una.user.id).map((c) => c.id)).toEqual([una.id]); | |
| 165 | await form(`/settings/identities/${una.id}/delete`, { confirm: "sign-in" }, "https://forge.example", una.cookie); | |
| 166 | expect(listConnections(app.db, una.user.id)).toEqual([]); | |
| 167 | expect(emailVerified(app.db, una.user.id)).toBe(false); | |
| 168 | }); | |
| 169 | ||
| 170 | test("the API refuses to remove the address you sign in with without ?confirm=true, and says why", async () => { | |
| 171 | const vic = await own("vic"); | |
| 172 | const del = (q: string) => | |
| 173 | fetch(`${servers.url}/api/v1/connections/${vic.id}${q}`, { method: "DELETE", headers: { cookie: vic.cookie, origin: "https://forge.example" } }); | |
| 174 | const listedJson = (await (await fetch(`${servers.url}/api/v1/connections`, { headers: { cookie: vic.cookie } })).json()) as { | |
| 175 | connections: { id: string; signIn: boolean }[]; | |
| 176 | }; | |
| 177 | expect(listedJson.connections).toEqual([expect.objectContaining({ id: vic.id, signIn: true })]); | |
| 178 | const refused = await del(""); | |
| 179 | expect(refused.status).toBe(409); | |
| 180 | expect(JSON.stringify(await refused.json())).toContain(SIGN_IN_ADDRESS); | |
| 181 | expect(emailVerified(app.db, vic.user.id)).toBe(true); | |
| 182 | expect((await del("?confirm=true")).status).toBe(200); | |
| 183 | expect(emailVerified(app.db, vic.user.id)).toBe(false); | |
| 184 | }); | |
| 185 | ||
| 186 | test("the terminal's d on the address you sign in with says what removing it does before the y/n", async () => { | |
| 187 | const { user } = await own("wes"); | |
| 188 | const pushed: Screen[] = []; | |
| 189 | const ctx = { theme: theme("dark"), icons: "nerd", invalidate() {}, push: (s: Screen) => pushed.push(s), pop() {}, hit() {} } as unknown as Ctx; | |
| 190 | const screen = identitiesScreen({ app, db: app.db, user } as unknown as Session, ctx); | |
| 191 | const draw = (sc: Screen) => { | |
| 192 | const s = new Surface(100, 14); | |
| 193 | sc.render({ x: 0, y: 0, w: 100, h: 14 }, s); | |
| 194 | return s.toText(); | |
| 195 | }; | |
| 196 | expect(draw(screen)).toContain("you sign in with it"); | |
| 197 | const key = (k: string): KeyEvent => ({ type: "key", key: k, ctrl: false, alt: false, shift: false }); | |
| 198 | expect(screen.key!(key("d"))).toBe(true); | |
| 199 | const dialog = draw(pushed[0]!); | |
| 200 | expect(dialog).toContain("This is the address you sign in with."); | |
| 201 | expect(dialog).toContain("Removing it means you must prove it again before you can write."); | |
| 202 | expect(emailVerified(app.db, user.id)).toBe(true); | |
| 203 | pushed[0]!.key!(key("y")); | |
| 204 | expect(listConnections(app.db, user.id)).toEqual([]); | |
| 205 | expect(emailVerified(app.db, user.id)).toBe(false); | |
| 206 | }); |
test/identities.test.ts +3 −2
| @@ -89,7 +89,7 @@ describe("connections on an account", () => { | ||
| 89 | 89 | expect((await ask("[email protected]")).user).toBeNull(); |
| 90 | 90 | // A wrong code proves nothing; the stored value is a hash, not the code. |
| 91 | 91 | expect((await call("POST", `/api/v1/connections/${c.id}/confirm`, tessCookie, { code: "000000x" })).status).toBe(422); |
| 92 | const stored = app.db.query<{ code_hash: string }, []>("SELECT code_hash FROM connection").get()!; | |
| 92 | const stored = app.db.query<{ code_hash: string }, []>("SELECT code_hash FROM connection WHERE code_hash IS NOT NULL").get()!; | |
| 93 | 93 | expect(stored.code_hash).not.toContain(codeSent()); |
| 94 | 94 | // Another account cannot prove it with the code mailed to this one. |
| 95 | 95 | expect((await call("POST", `/api/v1/connections/${c.id}/confirm`, otherCookie, { code: codeSent() })).status).toBe(404); |
| @@ -133,7 +133,8 @@ describe("connections on an account", () => { | ||
| 133 | 133 | expect(after.ok && after.value.filedBy.how).toBe("anonymous"); |
| 134 | 134 | expect(during.ok && during.value.filedBy.name).toBe("tess"); |
| 135 | 135 | const listed = (await (await call("GET", "/api/v1/connections", tessCookie)).json()) as any; |
| 136 | expect(listed.connections).toEqual([]); | |
| 136 | // Left: the account's own address, proven by its maker's word (#18222). | |
| 137 | expect(listed.connections.map((x: { ident: string; proven: boolean }) => [x.ident, x.proven])).toEqual([["[email protected]", true]]); | |
| 137 | 138 | expect(listed.note).toContain("not rewritten"); |
| 138 | 139 | }); |
| 139 | 140 |
test/mcp-crew.test.ts +2 −1
| @@ -1,4 +1,5 @@ | ||
| 1 | 1 | /** The `crew` tool is Settings › Crew over MCP: list, plan, apply (admin token, never an agent). */ |
| 2 | import { resetVerification } from "../src/core/verify.ts"; | |
| 2 | 3 | import { afterAll, beforeAll, expect, test } from "bun:test"; |
| 3 | 4 | import { mkdtemp, rm } from "node:fs/promises"; |
| 4 | 5 | import { tmpdir } from "node:os"; |
| @@ -45,7 +46,7 @@ beforeAll(async () => { | ||
| 45 | 46 | const carolRepo = await createRepo(app, c.value, { name: "side", visibility: "public" }); |
| 46 | 47 | if (!carolRepo.ok) throw new Error(String(carolRepo.error)); |
| 47 | 48 | // Carol's address stops being proven once her repository exists. |
| 48 | app.db.query("UPDATE email_check SET verified_at = NULL WHERE user_id = ?1").run(c.value.id); | |
| 49 | resetVerification(app.db, c.value.id); | |
| 49 | 50 | carol = createToken(app.db, c.value.id, "admin", "admin").token; |
| 50 | 51 | bob = createToken(app.db, b.value.id, "admin", "admin").token; |
| 51 | 52 | ro = createToken(app.db, a.value.id, "ro", "ro").token; |
test/mcp-email-verify.test.ts +2 −2
| @@ -10,7 +10,7 @@ import { createApp, type App } from "../src/app.ts"; | ||
| 10 | 10 | import { setLimit } from "../src/settings/limits.ts"; |
| 11 | 11 | import { createToken } from "../src/core/tokens.ts"; |
| 12 | 12 | import { getUserByName } from "../src/core/users.ts"; |
| 13 | import { emailVerified } from "../src/core/verify.ts"; | |
| 13 | import { emailVerified, markVerified } from "../src/core/verify.ts"; | |
| 14 | 14 | import type { Mail } from "../src/kernel/mail.ts"; |
| 15 | 15 | import { serve, type Servers } from "../src/http/server.ts"; |
| 16 | 16 | import { seedAdmin } from "./helpers/admin.ts"; |
| @@ -89,7 +89,7 @@ describe("MCP email_verify", () => { | ||
| 89 | 89 | |
| 90 | 90 | test("a verified person is told so, and nothing is sent", async () => { |
| 91 | 91 | const { user, token } = await join_("grace"); |
| 92 | app.db.query("UPDATE email_check SET verified_at = '2020-01-01T00:00:00.000Z' WHERE user_id = ?1").run(user.id); | |
| 92 | markVerified(app.db, user.id, "2020-01-01T00:00:00.000Z"); | |
| 93 | 93 | if (!emailVerified(app.db, user.id)) throw new Error("fixture: not verified"); |
| 94 | 94 | const before = sent.length; |
| 95 | 95 | const res = await ask(token); |
test/mcp-tell.test.ts +2 −2
| @@ -17,7 +17,7 @@ import { getUserByName } from "../src/core/users.ts"; | ||
| 17 | 17 | import { serve, type Servers } from "../src/http/server.ts"; |
| 18 | 18 | import { seedAdmin } from "./helpers/admin.ts"; |
| 19 | 19 | import { tokenFor } from "./helpers/tokens.ts"; |
| 20 | import { proveAll } from "./helpers/verified.ts"; | |
| 20 | import { proveAll, unproveAll } from "./helpers/verified.ts"; | |
| 21 | 21 | |
| 22 | 22 | describe("MCP tell refusals", () => { |
| 23 | 23 | let dataDir: string; |
| @@ -112,7 +112,7 @@ describe("MCP tell refusals", () => { | ||
| 112 | 112 | // An over-long text is the schema's to refuse on the MCP door, naming the argument. |
| 113 | 113 | expect(mcp).toContain(text === long ? 'argument "text"' : web); |
| 114 | 114 | } |
| 115 | app.db.query("UPDATE email_check SET verified_at = NULL").run(); | |
| 115 | unproveAll(app.db); | |
| 116 | 116 | try { |
| 117 | 117 | const web = await composer("hello"); |
| 118 | 118 | expect(web).toBe(refusalWords("unverified", "")); |
test/passkey-recovery.test.ts +4 −3
| @@ -11,7 +11,7 @@ import { join } from "node:path"; | ||
| 11 | 11 | import { createApp, type App } from "../src/app.ts"; |
| 12 | 12 | import { b64u } from "../src/auth/webauthn.ts"; |
| 13 | 13 | import { addPasskey, PASSKEY_MAX } from "../src/core/passkeys.ts"; |
| 14 | import { consumeLink, issueRecovery, markVerified, RECOVERY_TTL_MS } from "../src/core/verify.ts"; | |
| 14 | import { consumeLink, issueRecovery, markVerified, RECOVERY_TTL_MS, resetVerification } from "../src/core/verify.ts"; | |
| 15 | 15 | import { sha256 } from "../src/kernel/hash.ts"; |
| 16 | 16 | import { serve, type Servers } from "../src/http/server.ts"; |
| 17 | 17 | import type { Mail } from "../src/kernel/mail.ts"; |
| @@ -106,7 +106,7 @@ describe("passkey recovery", () => { | ||
| 106 | 106 | const token = linkOf(sent[0]!); |
| 107 | 107 | |
| 108 | 108 | // Only a hash is kept. |
| 109 | const row = app.db.query<{ token_hash: string; expires_at: string }, []>("SELECT token_hash, expires_at FROM email_check WHERE token_hash IS NOT NULL AND verified_at IS NOT NULL").get()!; | |
| 109 | const row = app.db.query<{ token_hash: string; expires_at: string }, []>("SELECT token_hash, expires_at FROM email_check WHERE token_hash IS NOT NULL").get()!; | |
| 110 | 110 | expect(row.token_hash).toBe(sha256(token)); |
| 111 | 111 | expect(JSON.stringify(row)).not.toContain(token); |
| 112 | 112 | const life = Date.parse(row.expires_at) - Date.now(); |
| @@ -150,7 +150,8 @@ describe("passkey recovery", () => { | ||
| 150 | 150 | test("a pending verification link opens nothing here", async () => { |
| 151 | 151 | // una never proved the address: her verification link must not sign in. |
| 152 | 152 | const una = app.db.query<{ id: string }, []>("SELECT id FROM user WHERE username = 'una'").get()!.id; |
| 153 | app.db.query("UPDATE email_check SET verified_at = NULL, token_hash = ?2, expires_at = ?3 WHERE user_id = ?1").run(una, sha256("pending"), new Date(Date.now() + 60_000).toISOString()); | |
| 153 | resetVerification(app.db, una); | |
| 154 | app.db.query("UPDATE email_check SET token_hash = ?2, expires_at = ?3 WHERE user_id = ?1").run(una, sha256("pending"), new Date(Date.now() + 60_000).toISOString()); | |
| 154 | 155 | expect((await post("/recover/options", { token: "pending" })).status).toBe(400); |
| 155 | 156 | sent.length = 0; |
| 156 | 157 | await ask("[email protected]"); |
test/ssh-tell.test.ts +5 −3
| @@ -2,6 +2,8 @@ | ||
| 2 | 2 | * `ssh <forge> tell <words>` (#6110): an exec of `tell` drives the same |
| 3 | 3 | * `tell()` as the web composer, as the key's account, and says where it went. |
| 4 | 4 | */ |
| 5 | import { markVerified, resetVerification } from "../src/core/verify.ts"; | |
| 6 | import { proveAll } from "./helpers/verified.ts"; | |
| 5 | 7 | import { afterAll, beforeAll, describe, expect, test } from "bun:test"; |
| 6 | 8 | import { mkdtemp, rm } from "node:fs/promises"; |
| 7 | 9 | import { tmpdir } from "node:os"; |
| @@ -172,13 +174,13 @@ describe("ssh forge tell", () => { | ||
| 172 | 174 | |
| 173 | 175 | test("a verified account that may not direct the crew is told so, and records nothing", async () => { |
| 174 | 176 | app.db.query("UPDATE repo SET crew_outsiders = 0").run(); |
| 175 | app.db.query("UPDATE email_check SET verified_at = ?1 WHERE verified_at IS NULL").run(new Date().toISOString()); | |
| 177 | proveAll(app); | |
| 176 | 178 | try { |
| 177 | 179 | const r = await exec(KEY_B, "tell hello"); |
| 178 | 180 | expect([r.code, r.err]).toEqual([1, `forge: ${DIRECTION_NOTE}\r\n`]); |
| 179 | 181 | } finally { |
| 180 | 182 | app.db.query("UPDATE repo SET crew_outsiders = 1").run(); |
| 181 | app.db.query("UPDATE email_check SET verified_at = NULL WHERE user_id = (SELECT id FROM user WHERE username = 'bob')").run(); | |
| 183 | resetVerification(app.db, getUserByName(app.db, "bob")!.id); | |
| 182 | 184 | } |
| 183 | 185 | expect(issues().length).toBe(1); |
| 184 | 186 | }); |
| @@ -200,7 +202,7 @@ describe("ssh forge tell", () => { | ||
| 200 | 202 | expect(row.body).toContain(`Told from [${address}](${address})`); |
| 201 | 203 | expect(issues().length).toBe(before + 1); |
| 202 | 204 | // A reader who may tell: verified, and the crew takes outsiders. |
| 203 | app.db.query("UPDATE email_check SET verified_at = ?1 WHERE user_id = (SELECT id FROM user WHERE username = 'bob')").run(new Date().toISOString()); | |
| 205 | markVerified(app.db, getUserByName(app.db, "bob")!.id, new Date().toISOString()); | |
| 204 | 206 | const r = await exec(KEY_B, "tell and the footer", "notes"); |
| 205 | 207 | expect([r.code, r.err]).toEqual([0, ""]); |
| 206 | 208 | expect(issues().length).toBe(before + 2); |
test/tui-answers-tell.test.ts +2 −2
| @@ -20,7 +20,7 @@ import { answerLines, answersScreen } from "../src/tui/screens/answers.ts"; | ||
| 20 | 20 | import { headlessTerminal } from "../src/tui/term/terminal.ts"; |
| 21 | 21 | import { quietLogs } from "./helpers/globals.ts"; |
| 22 | 22 | import { settleApp } from "./helpers/tui.ts"; |
| 23 | import { proveAll } from "./helpers/verified.ts"; | |
| 23 | import { proveAll, unproveAll } from "./helpers/verified.ts"; | |
| 24 | 24 | |
| 25 | 25 | quietLogs(); |
| 26 | 26 | |
| @@ -115,7 +115,7 @@ describe("t on the answers screen", () => { | ||
| 115 | 115 | |
| 116 | 116 | test("an unverified owner hears the tell's own words and opens nothing", async () => { |
| 117 | 117 | const before = issues().length; |
| 118 | app.db.query("UPDATE email_check SET verified_at = NULL").run(); | |
| 118 | unproveAll(app.db); | |
| 119 | 119 | try { |
| 120 | 120 | const seen = await drive(alice, ["t", ..."Unseen.", "\r"]); |
| 121 | 121 | expect(seen.text).toContain(refusalWords("unverified", "")); |
test/tui-deploy-act.test.ts +2 −2
| @@ -19,7 +19,7 @@ import { createApp as createAppRecord } from "../src/core/apps.ts"; | ||
| 19 | 19 | import type { Repo } from "../src/core/repos.ts"; |
| 20 | 20 | import type { Run } from "../src/core/runs.ts"; |
| 21 | 21 | import type { User } from "../src/core/users.ts"; |
| 22 | import { markVerified } from "../src/core/verify.ts"; | |
| 22 | import { markVerified, resetVerification } from "../src/core/verify.ts"; | |
| 23 | 23 | import { createForgeApp } from "../src/tui/forge.ts"; |
| 24 | 24 | import { deploysScreen } from "../src/tui/screens/deploys.ts"; |
| 25 | 25 | import { headlessTerminal } from "../src/tui/term/terminal.ts"; |
| @@ -191,7 +191,7 @@ test("a refused redeploy toasts in red in the page's words and deploys nothing", | ||
| 191 | 191 | }); |
| 192 | 192 | |
| 193 | 193 | test("a writer whose email is unverified is told to verify it, and nothing deploys", async () => { |
| 194 | forge.db.query("UPDATE email_check SET verified_at = NULL WHERE user_id = ?1").run(alice.id); | |
| 194 | resetVerification(forge.db, alice.id); | |
| 195 | 195 | try { |
| 196 | 196 | const h = await open(alice); |
| 197 | 197 | await h.press("D", "enter"); |
test/tui-deploys-build.test.ts +2 −2
| @@ -19,7 +19,7 @@ import type { Run } from "../src/core/runs.ts"; | ||
| 19 | 19 | import type { User } from "../src/core/users.ts"; |
| 20 | 20 | import { repoDir } from "../src/git/repos.ts"; |
| 21 | 21 | import { gitClientEnv } from "./helpers/git-client.ts"; |
| 22 | import { markVerified } from "../src/core/verify.ts"; | |
| 22 | import { markVerified, resetVerification } from "../src/core/verify.ts"; | |
| 23 | 23 | import { createForgeApp } from "../src/tui/forge.ts"; |
| 24 | 24 | import { deploysScreen } from "../src/tui/screens/deploys.ts"; |
| 25 | 25 | import { headlessTerminal } from "../src/tui/term/terminal.ts"; |
| @@ -151,7 +151,7 @@ test("a reader is offered no key and pressing it does nothing", async () => { | ||
| 151 | 151 | }); |
| 152 | 152 | |
| 153 | 153 | test("a writer who is unverified is told to verify, and nothing is served", async () => { |
| 154 | forge.db.query("UPDATE email_check SET verified_at = NULL WHERE user_id = ?1").run(alice.id); | |
| 154 | resetVerification(forge.db, alice.id); | |
| 155 | 155 | try { |
| 156 | 156 | const h = await open(alice); |
| 157 | 157 | await h.press("b"); |
test/tui-deploys-preview-act.test.ts +2 −2
| @@ -16,7 +16,7 @@ import { createApp as createAppRecord } from "../src/core/apps.ts"; | ||
| 16 | 16 | import type { Repo } from "../src/core/repos.ts"; |
| 17 | 17 | import type { Run } from "../src/core/runs.ts"; |
| 18 | 18 | import type { User } from "../src/core/users.ts"; |
| 19 | import { markVerified } from "../src/core/verify.ts"; | |
| 19 | import { markVerified, resetVerification } from "../src/core/verify.ts"; | |
| 20 | 20 | import { createForgeApp } from "../src/tui/forge.ts"; |
| 21 | 21 | import { deploysScreen } from "../src/tui/screens/deploys.ts"; |
| 22 | 22 | import { headlessTerminal } from "../src/tui/term/terminal.ts"; |
| @@ -152,7 +152,7 @@ test("a reader is offered neither key", async () => { | ||
| 152 | 152 | }); |
| 153 | 153 | |
| 154 | 154 | test("a refused preview action toasts in red and calls nothing", async () => { |
| 155 | forge.db.query("UPDATE email_check SET verified_at = NULL WHERE user_id = ?1").run(alice.id); | |
| 155 | resetVerification(forge.db, alice.id); | |
| 156 | 156 | try { |
| 157 | 157 | const h = await open(alice); |
| 158 | 158 | await h.press("j", "D", "y"); |
test/verify-recovery.test.ts +4 −3
| @@ -42,8 +42,8 @@ describe("recovery links", () => { | ||
| 42 | 42 | }; |
| 43 | 43 | const row = (id: string) => |
| 44 | 44 | app.db |
| 45 | .query<{ verified_at: string | null }, [string]>( | |
| 46 | "SELECT verified_at FROM email_check WHERE user_id = ?1", | |
| 45 | .query<{ token_hash: string | null }, [string]>( | |
| 46 | "SELECT token_hash FROM email_check WHERE user_id = ?1", | |
| 47 | 47 | ) |
| 48 | 48 | .get(id); |
| 49 | 49 | |
| @@ -111,11 +111,12 @@ describe("recovery links", () => { | ||
| 111 | 111 | |
| 112 | 112 | test("markUnproven writes an unproven row, keeps a proven one, touches no other", async () => { |
| 113 | 113 | const dan = await make("dan"); |
| 114 | resetVerification(app.db, dan); // created trusted, so proven; make it unproven | |
| 114 | 115 | app.db.query("DELETE FROM email_check WHERE user_id = ?1").run(dan); |
| 115 | 116 | expect(row(dan)).toBeNull(); |
| 116 | 117 | const before = row(bob); |
| 117 | 118 | markUnproven(app.db, dan); |
| 118 | expect(row(dan)).toEqual({ verified_at: null }); | |
| 119 | expect(row(dan)).toEqual({ token_hash: null }); | |
| 119 | 120 | expect(emailVerified(app.db, dan)).toBe(false); |
| 120 | 121 | expect(row(bob)).toEqual(before); |
| 121 | 122 | expect(emailVerified(app.db, bob)).toBe(true); |
test/verify.test.ts added +148
| @@ -0,0 +1,148 @@ | ||
| 1 | /** | |
| 2 | * One place says an email is proven (#18222): the account's connections. A proof made once — the | |
| 3 | * connection's code, or the sign-in link — shows on the sign-in gate (`emailVerified`) and in the | |
| 4 | * connections list alike; removing the connection leaves no sign-in proof behind, and a changed | |
| 5 | * address is unproven again. The migration moves every proof that existed into a connection. | |
| 6 | */ | |
| 7 | import { afterAll, beforeAll, describe, expect, test } from "bun:test"; | |
| 8 | import { Database } from "bun:sqlite"; | |
| 9 | import { mkdtemp, rm } from "node:fs/promises"; | |
| 10 | import { tmpdir } from "node:os"; | |
| 11 | import { join } from "node:path"; | |
| 12 | import { createApp, type App } from "../src/app.ts"; | |
| 13 | import { createUser, getUserByName, type User } from "../src/core/users.ts"; | |
| 14 | import { addEmail, listConnections, lookup, proveEmail, removeConnection, setUse } from "../src/core/identities.ts"; | |
| 15 | import { consumeLink, emailVerified, issueLink, issueRecovery, markVerified, resetVerification } from "../src/core/verify.ts"; | |
| 16 | import { listPeople } from "../src/core/roles.ts"; | |
| 17 | import { updateProfile } from "../src/actions/users.ts"; | |
| 18 | import { migrationFiles } from "../src/core/schema.ts"; | |
| 19 | ||
| 20 | describe("an email is proven in one place", () => { | |
| 21 | let dataDir: string; | |
| 22 | let app: App; | |
| 23 | const NOW = Date.parse("2026-12-04T12:00:00Z"); | |
| 24 | ||
| 25 | const person = async (username: string, email = `${username}@f.dev`, trusted = false): Promise<User> => { | |
| 26 | const made = await createUser(app.db, { origin: "seed", trusted, username, email }); | |
| 27 | if (!made.ok) throw new Error(made.error); | |
| 28 | return made.value; | |
| 29 | }; | |
| 30 | const listed = (u: User) => listConnections(app.db, u.id).map((c) => [c.kind, c.ident, c.proven]); | |
| 31 | const gate = (u: User) => emailVerified(app.db, u.id); | |
| 32 | ||
| 33 | beforeAll(async () => { | |
| 34 | dataDir = await mkdtemp(join(tmpdir(), "forge-verify-")); | |
| 35 | app = createApp({ dataDir, port: 0 }); | |
| 36 | }); | |
| 37 | afterAll(async () => { | |
| 38 | app.db.close(); | |
| 39 | await rm(dataDir, { recursive: true, force: true }); | |
| 40 | }); | |
| 41 | ||
| 42 | test("the connection's code proves the address once: the sign-in gate and the list both say proven", async () => { | |
| 43 | const ada = await person("ada", "[email protected]"); | |
| 44 | expect(gate(ada)).toBe(false); | |
| 45 | expect(listed(ada)).toEqual([]); | |
| 46 | const added = addEmail(app.db, ada.id, "[email protected]", NOW); | |
| 47 | if (typeof added === "string") throw new Error(added); | |
| 48 | expect(gate(ada)).toBe(false); | |
| 49 | expect(proveEmail(app.db, ada.id, added.connection.id, added.code, NOW)).toBe("proven"); | |
| 50 | expect(gate(ada)).toBe(true); | |
| 51 | expect(listed(ada)).toEqual([["email", "[email protected]", true]]); | |
| 52 | expect(listPeople(app.db).find((p) => p.username === "ada")?.verified).toBe(true); | |
| 53 | }); | |
| 54 | ||
| 55 | test("removing the connection leaves no stale sign-in proof, nor a recovery link", async () => { | |
| 56 | const ada = getUserByName(app.db, "ada")!; | |
| 57 | const [c] = listConnections(app.db, ada.id); | |
| 58 | expect(removeConnection(app.db, ada.id, c!.id)).toBe(true); | |
| 59 | expect(gate(ada)).toBe(false); | |
| 60 | expect(listed(ada)).toEqual([]); | |
| 61 | expect(issueRecovery(app.db, ada.id, NOW)).toBeUndefined(); | |
| 62 | expect(listPeople(app.db).find((p) => p.username === "ada")?.verified).toBe(false); | |
| 63 | }); | |
| 64 | ||
| 65 | test("the sign-in link proves the address once, and the list shows it proven", async () => { | |
| 66 | const bea = await person("bea"); | |
| 67 | const token = issueLink(app.db, bea.id, bea.email, NOW)!; | |
| 68 | expect(consumeLink(app.db, token, NOW)).toBe(bea.id); | |
| 69 | expect(gate(bea)).toBe(true); | |
| 70 | expect(listed(bea)).toEqual([["email", "[email protected]", true]]); | |
| 71 | expect(consumeLink(app.db, token, NOW)).toBeUndefined(); | |
| 72 | expect(issueRecovery(app.db, bea.id, NOW)).toBeString(); | |
| 73 | }); | |
| 74 | ||
| 75 | test("a changed address is unproven again, its uses off; the old proof says nothing of the new one", async () => { | |
| 76 | const cy = await person("cy", "[email protected]", true); | |
| 77 | expect(gate(cy)).toBe(true); | |
| 78 | const [c] = listConnections(app.db, cy.id); | |
| 79 | setUse(app.db, cy.id, c!.id, "feedback", true); | |
| 80 | expect(lookup(app.db, "email", "[email protected]", "feedback")).toBe(cy.id); | |
| 81 | resetVerification(app.db, cy.id); | |
| 82 | expect(gate(cy)).toBe(false); | |
| 83 | expect(lookup(app.db, "email", "[email protected]", "feedback")).toBeUndefined(); | |
| 84 | expect(listed(cy)).toEqual([["email", "[email protected]", false]]); | |
| 85 | markVerified(app.db, cy.id, new Date(NOW).toISOString()); | |
| 86 | expect(listed(cy)).toEqual([["email", "[email protected]", true]]); | |
| 87 | app.db.query("UPDATE user SET email = '[email protected]' WHERE id = ?1").run(cy.id); | |
| 88 | expect(gate(cy)).toBe(false); | |
| 89 | }); | |
| 90 | ||
| 91 | test("changing the address A to B to A through the profile needs a fresh proof of A", async () => { | |
| 92 | const gus = await person("gus", "[email protected]", true); | |
| 93 | expect(gate(gus)).toBe(true); | |
| 94 | const change = (email: string): User => { | |
| 95 | const done = updateProfile(app, getUserByName(app.db, "gus")!, { email }); | |
| 96 | if (!done.ok) throw new Error(done.error); | |
| 97 | return done.value; | |
| 98 | }; | |
| 99 | // The new address is stored first, then the reset: B is unproven, and so is A, which it left. | |
| 100 | change("[email protected]"); | |
| 101 | expect(gate(gus)).toBe(false); | |
| 102 | expect(listed(gus)).toEqual([["email", "[email protected]", false]]); | |
| 103 | change("[email protected]"); | |
| 104 | expect(gate(gus)).toBe(false); | |
| 105 | expect(listed(gus)).toEqual([["email", "[email protected]", false]]); | |
| 106 | expect(issueRecovery(app.db, gus.id, NOW)).toBeUndefined(); | |
| 107 | markVerified(app.db, gus.id, new Date(NOW).toISOString()); | |
| 108 | expect(gate(gus)).toBe(true); | |
| 109 | }); | |
| 110 | ||
| 111 | test("the account holding an address outranks another account's older proof of it", async () => { | |
| 112 | const dee = await person("dee"); | |
| 113 | const eve = await person("eve"); | |
| 114 | const added = addEmail(app.db, eve.id, "[email protected]", NOW); | |
| 115 | if (typeof added === "string") throw new Error(added); | |
| 116 | expect(proveEmail(app.db, eve.id, added.connection.id, added.code, NOW)).toBe("proven"); | |
| 117 | markVerified(app.db, dee.id, new Date(NOW).toISOString()); | |
| 118 | expect(gate(dee)).toBe(true); | |
| 119 | expect(listed(eve)).toEqual([["email", "[email protected]", false]]); | |
| 120 | }); | |
| 121 | ||
| 122 | test("a stand-in address is proven by its maker's word but never listed", async () => { | |
| 123 | const fay = await person("fay", "[email protected]", true); | |
| 124 | expect(gate(fay)).toBe(true); | |
| 125 | expect(listed(fay)).toEqual([]); | |
| 126 | }); | |
| 127 | }); | |
| 128 | ||
| 129 | describe("the migration moves every proof into a connection", () => { | |
| 130 | test("a proven person keeps the gate open; an unproven one does not; another's extra proof yields", () => { | |
| 131 | const db = new Database(":memory:"); | |
| 132 | const mine = migrationFiles.findIndex((m) => m.name.includes("email-proof-in-connections")); | |
| 133 | expect(mine).toBeGreaterThan(0); | |
| 134 | for (const m of migrationFiles.slice(0, mine)) db.exec(m.sql); | |
| 135 | const user = db.query("INSERT INTO user (id, username, email, password_hash) VALUES (?1, ?2, ?3, '')"); | |
| 136 | user.run("u1", "una", "[email protected]"); | |
| 137 | user.run("u2", "val", "[email protected]"); | |
| 138 | user.run("u3", "wes", "[email protected]"); | |
| 139 | db.exec(`INSERT INTO email_check (user_id, verified_at) VALUES ('u1', '2026-01-01T00:00:00.000Z'), ('u2', NULL)`); | |
| 140 | db.exec(`INSERT INTO connection (id, user_id, kind, ident, proven_at, use_feedback, created_at) | |
| 141 | VALUES ('k1', 'u3', 'email', '[email protected]', '2026-02-01T00:00:00.000Z', 1, '2026-02-01T00:00:00.000Z')`); | |
| 142 | db.exec(migrationFiles[mine]!.sql); | |
| 143 | expect(emailVerified(db, "u1")).toBe(true); | |
| 144 | expect(emailVerified(db, "u2")).toBe(false); | |
| 145 | expect(listConnections(db, "u1").map((c) => [c.ident, c.proven])).toEqual([["[email protected]", true]]); | |
| 146 | expect(listConnections(db, "u3").map((c) => [c.ident, c.proven, c.uses.feedback])).toEqual([["[email protected]", false, false]]); | |
| 147 | }); | |
| 148 | }); |
new above
offline