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

opened this

Merged 6h 6m ago, live in production

mason/forge:mason/18222-connections-one-place-says-an-email-is-p → main 0 commits fork

  • Merged. mason/18222-connections-one-place-says-an-email-is-p was merged into main as 181d662.

Review

Sign in to review this change.
32 files changed +478 −121
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
4343 - **Mail**: a member's sends are capped by account (20 a day, `connection:<id>` scope of
4444 `sendCapped`, so add-then-remove cycles do not evade it), by address and by the forge.
4545 - **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.
4857
4958 `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";
2323
2424 export type ConnectionError =
2525 | "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.";
2734
2835 /** What each refusal says, for the API, the settings page and the terminal alike. */
2936 export const CONNECTION_WORDS: Record<ConnectionError, string> = {
@@ -39,6 +46,7 @@ export const CONNECTION_WORDS: Record<ConnectionError, string> = {
3946 not_found: "no such connection",
4047 invalid_use: "use is feedback or profile, and on is true or false",
4148 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.`,
4250 };
4351
4452 /** What the settings page says beside the uses: removing or switching off is not retroactive. */
@@ -113,7 +121,13 @@ export function confirmConnection(
113121 return ok(listConnections(app.db, user.id).find((c) => c.id === id)!);
114122 }
115123
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");
117131 return removeConnection(app.db, user.id, id) ? ok(true) : err("not_found");
118132 }
119133
src/actions/users.ts +1 −1
@@ -398,7 +398,7 @@ export function updateProfile(
398398 // A new address is unproven at once; its link follows (and can be asked
399399 // for again), so a send that fails never leaves the old proof standing.
400400 if (updated.value.email.toLowerCase() !== user.value.email.toLowerCase())
401 void emailChanged(app, updated.value);
401 void emailChanged(app, updated.value, user.value.email);
402402 const fields = (["displayName", "email", "commitEmail"] as const).filter(
403403 (k) => patch[k] !== undefined,
404404 );
src/actions/verify.ts +5 −4
@@ -149,11 +149,12 @@ export async function welcome(app: App, user: User): Promise<void> {
149149 }
150150
151151 /**
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.
154155 */
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);
157158 await sendVerification(app, user);
158159 }
159160
src/core/accounts.ts +2 −1
@@ -13,6 +13,7 @@
1313
1414 import type { Database } from "bun:sqlite";
1515 import { forgetListings } from "./listings.ts";
16 import { provenEmailAt } from "./proven_identities.ts";
1617
1718 export interface AccountRow {
1819 readonly username: string;
@@ -71,7 +72,7 @@ export function listAccounts(db: Database, only = ""): AccountRow[] {
7172 >(
7273 `SELECT u.id, u.username, u.display_name, u.is_admin, u.is_agent,
7374 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,
7576 (SELECT COUNT(*) FROM repo r WHERE r.owner_id = u.id) AS repos,
7677 (SELECT COUNT(*) FROM app a JOIN repo r ON r.id = a.repo_id
7778 WHERE r.owner_id = u.id) AS apps,
src/core/identities.ts +22 −7
@@ -9,6 +9,11 @@
99 * address from an unproven or an opted-out one. A Minecraft name (#18221) is
1010 * the second kind: no code, it is proven when the game door links that player
1111 * 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.
1217 */
1318
1419 import type { Database } from "bun:sqlite";
@@ -36,6 +41,8 @@ export interface Connection {
3641 readonly ident: string;
3742 readonly proven: boolean;
3843 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;
3946 }
4047
4148 /**
@@ -60,22 +67,30 @@ export function cleanMinecraft(raw: unknown): string | undefined {
6067
6168 interface Row {
6269 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;
6471 }
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`;
6575 const shown = (r: Row): Connection => ({
6676 id: r.id, kind: r.kind, ident: r.ident, proven: r.proven_at !== null,
6777 uses: { feedback: r.use_feedback === 1, profile: r.use_profile === 1 },
78 signIn: r.sign_in === 1,
6879 });
80 const byId = (db: Database, id: string): Connection => shown(db.query<Row, [string]>(`${SHOWN} WHERE c.id = ?1`).get(id)!);
6981
7082 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);
7287 }
7388
7489 /** Start a connection (unproven) and mint its code, returned once. */
7590 export function addEmail(
7691 db: Database, userId: string, email: string, now: number,
7792 ): { 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);
7994 if (mine === null) {
8095 if (full(db, userId)) return "limit";
8196 } else if (mine.proven_at !== null) return "taken";
@@ -92,7 +107,7 @@ export function addEmail(
92107 ON CONFLICT(user_id, kind, ident) DO UPDATE SET code_hash = excluded.code_hash,
93108 expires_at = excluded.expires_at, tries = 0, sent_at = excluded.sent_at`,
94109 ).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 };
96111 }
97112
98113 const full = (db: Database, userId: string): boolean =>
@@ -104,13 +119,13 @@ const full = (db: Database, userId: string): boolean =>
104119 * never be proven, so the answer does not tell whether it is proven elsewhere.
105120 */
106121 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);
108123 if (mine !== null) return shown(mine);
109124 if (full(db, userId)) return "limit";
110125 const id = newId();
111126 db.query("INSERT INTO connection (id, user_id, kind, ident, created_at) VALUES (?1, ?2, 'minecraft', ?3, ?4)")
112127 .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);
114129 }
115130
116131 /**
@@ -176,7 +191,7 @@ export function setUse(db: Database, userId: string, id: string, use: Use, on: b
176191 const col = use === "feedback" ? "use_feedback" : "use_profile";
177192 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);
178193 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);
180195 }
181196
182197 /** 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 @@
77 */
88
99 import type { Database } from "bun:sqlite";
10 import { provenEmailAt } from "./proven_identities.ts";
1011
1112 export const WORDS = ["owner", "member", "guest", "crew member"] as const;
1213 export type RoleWord = (typeof WORDS)[number];
@@ -34,12 +35,11 @@ export function wordFilter(raw: string | null | undefined): RoleWord | null {
3435 export function peopleByActivity(db: Database, only: RoleWord | null = null): PersonRow[] {
3536 const rows = db
3637 .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,
3839 MAX(COALESCE((SELECT MAX(s.last_seen_at) FROM session s WHERE s.user_id = u.id), ''),
3940 COALESCE((SELECT MAX(t.last_used_at) FROM token t WHERE t.user_id = u.id), '')) AS seen
4041 FROM user u LEFT JOIN member m ON m.user_id = u.id
4142 LEFT JOIN model_grant g ON g.user_id = u.id
42 LEFT JOIN email_check c ON c.user_id = u.id
4343 WHERE u.kind = 'user' AND u.removed_at IS NULL
4444 ORDER BY (seen = '') , seen DESC, u.created_at DESC, u.username`,
4545 )
src/core/proven_identities.ts +30 −14
@@ -11,6 +11,15 @@
1111 */
1212 import type { Database } from "bun:sqlite";
1313
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
1423 export type IdentityKind = "email" | "minecraft";
1524
1625 export interface Identity {
@@ -37,8 +46,7 @@ export function emailIdentity(db: Database, userId: string): Identity | undefine
3746 { email: string; kind: string; is_agent: number; verified_at: string | null },
3847 [string]
3948 >(
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`,
4250 )
4351 .get(userId);
4452 if (user === null) return undefined;
@@ -84,9 +92,9 @@ export function listOf(db: Database, userId: string): { identities: Identity[];
8492 { kind: IdentityKind; name: string; proven: number; since: string | null; boxId: string | null; box: string | null; uuid: string | null; gameBox: number },
8593 [string]
8694 >(
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
9098 UNION ALL
9199 SELECT 'minecraft', l.player, l.uuid != '', l.created_at, l.box_id, b.name, l.uuid, 1, 1
92100 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
112120 /**
113121 * Remove the account's email from its list (#18160): the address becomes its stand-in
114122 * (`<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.
117126 */
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 })();
125141
126142 /** What removing the email says, at both doors. */
127143 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 @@
1111 import { storedText } from "../kernel/blocked.ts";
1212 import type { Database } from "bun:sqlite";
1313 import { isUnclaimed } from "./starts.ts";
14 import { provenEmailAt } from "./proven_identities.ts";
1415
1516 export const ROLES = ["guest", "member", "admin"] as const;
1617 export type Role = (typeof ROLES)[number];
@@ -145,7 +146,7 @@ export interface Person {
145146 readonly usdPerMonth: number | null;
146147 /** When the owner suspended the account; null while it is in good standing. */
147148 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`). */
149150 readonly verified: boolean;
150151 }
151152
@@ -153,11 +154,11 @@ export interface Person {
153154 export function listPeople(db: Database): Person[] {
154155 return db
155156 .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
157159 FROM user u
158160 LEFT JOIN member m ON m.user_id = u.id
159161 LEFT JOIN model_grant g ON g.user_id = u.id
160 LEFT JOIN email_check c ON c.user_id = u.id
161162 WHERE u.kind = 'user' AND u.is_agent = 0 AND u.removed_at IS NULL
162163 ORDER BY u.created_at DESC, u.username`,
163164 )
src/core/verify.ts +59 −22
@@ -3,18 +3,25 @@
33 * it. Pure data: the actions send the mail and decide what an unproven
44 * account may not do (`actions/verify.ts`).
55 *
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.
1319 */
1420
1521 import type { Database } from "bun:sqlite";
1622 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";
1825
1926 /** How long a link works. */
2027 export const LINK_TTL_MS = 24 * 3_600_000;
@@ -24,6 +31,9 @@ export const RESEND_AFTER_MS = 5 * 60_000;
2431 const secret = (): string =>
2532 Buffer.from(crypto.getRandomValues(new Uint8Array(32))).toString("base64url");
2633
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
2737 /** Whether the account's email is proven: read from its one list of identities (#18160). */
2838 export const emailVerified = (db: Database, userId: string): boolean => provenAs(db, userId, "email");
2939
@@ -32,22 +42,49 @@ export function markUnproven(db: Database, userId: string): void {
3242 db.query("INSERT OR IGNORE INTO email_check (user_id) VALUES (?1)").run(userId);
3343 }
3444
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 */
3651 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 })();
4270 }
4371
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 {
4679 db.query(
4780 `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`,
5082 ).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);
5188 }
5289
5390 /** The most links one account may be sent in a UTC day, whatever the address. */
@@ -107,7 +144,7 @@ export function consumeLink(
107144 .query<
108145 { user_id: string; expires_at: string | null },
109146 [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}`)
111148 .get(sha256(token));
112149 if (row === null || row.expires_at === null) return undefined;
113150 if (Date.parse(row.expires_at) <= now) return undefined;
@@ -133,7 +170,7 @@ export function issueRecovery(
133170 const changed = db
134171 .query(
135172 `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}`,
137174 )
138175 .run(userId, sha256(token), new Date(now + RECOVERY_TTL_MS).toISOString());
139176 return changed.changes > 0 ? token : undefined;
@@ -153,7 +190,7 @@ export function recoveryOwner(
153190 db
154191 .query<{ user_id: string }, [string, string]>(
155192 `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`,
157194 )
158195 .get(sha256(token), new Date(now).toISOString())?.user_id ?? undefined
159196 );
@@ -170,7 +207,7 @@ export function spendRecovery(
170207 db
171208 .query<{ user_id: string }, [string, string]>(
172209 `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
174211 RETURNING user_id`,
175212 )
176213 .get(sha256(token), new Date(now).toISOString())?.user_id ?? undefined
src/http/api/identities.ts +5 −3
@@ -3,7 +3,8 @@
33 * lists the caller's; `POST` adds an email and mails a code, or `{minecraft}`
44 * keeps a Minecraft name the game door proves (#18221); `POST
55 * /: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,
78 * carrying a lookup key in `X-Forge-Lookup-Key` (never a user token); an
89 * admin makes keys at `/lookup-keys`. The account itself acts, same-origin.
910 */
@@ -21,7 +22,7 @@ import type { Router } from "../router.ts";
2122 /** The status each refusal answers with, 0 for the ones that wait; the words are the action's. */
2223 const STATUS: Record<ConnectionError, number> = {
2324 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,
2526 };
2627 /** Seconds to wait, for the refusals that wait; the rest answer through apiError. */
2728 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 {
7071 router.add("DELETE", "/api/v1/connections/:id", (ctx) => {
7172 const denied = requireAccount(ctx, { adminToken: true });
7273 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);
7476 return done.ok ? json({ removed: true, note: NOT_RETROACTIVE }, 200, noStore) : refuse(done.error);
7577 });
7678
src/tui/screens/identities.ts +8 −6
@@ -2,12 +2,13 @@
22 * Proven identities in the terminal (#18108), as Settings › Proven identities: `a` adds an address
33 * and mails a code, `c` gives the code back, `m` keeps a Minecraft name the game door proves
44 * (#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.
78 */
89
910 import {
10 CONNECTION_WORDS, MINECRAFT_PROOF, NOT_RETROACTIVE, addConnection, addMinecraftConnection, chooseUse,
11 CONNECTION_WORDS, MINECRAFT_PROOF, NOT_RETROACTIVE, SIGN_IN_ADDRESS, addConnection, addMinecraftConnection, chooseUse,
1112 confirmConnection, connectionsOf, dropConnection,
1213 } from "../../actions/identities.ts";
1314 import type { Use } from "../../core/identities.ts";
@@ -27,7 +28,7 @@ export function identitiesScreen(f: Session, ctx: Ctx): Screen {
2728 items().map((c) => ({
2829 title: c.kind === "minecraft" ? `${c.ident} (Minecraft)` : c.ident,
2930 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"}`
3132 : c.kind === "minecraft" ? "not proven yet: link it in game" : "not proven yet: c gives the code",
3233 }));
3334 const toggle = (use: Use): boolean => {
@@ -98,12 +99,13 @@ export function identitiesScreen(f: Session, ctx: Ctx): Screen {
9899 }
99100 if (e.key === "d") {
100101 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`],
102104 actions: [{ label: "Remove", variant: "danger" }, { label: "Cancel", variant: "ghost" }],
103105 selected: 1, yesNo: true,
104106 onChoose: (i) => {
105107 if (i !== 0) return;
106 const gone = dropConnection(f.app, user, c.id);
108 const gone = dropConnection(f.app, user, c.id, true);
107109 note = gone.ok ? `Removed. ${NOT_RETROACTIVE}` : CONNECTION_WORDS[gone.error];
108110 ctx.invalidate();
109111 },
src/web/pages/identities.ts +14 −6
@@ -3,12 +3,13 @@
33 * (#18221, proven by the game door's link), each with its own uses, all off until chosen.
44 * Server-rendered; every act is a same-origin form (`readForm`), by the signed-in account alone,
55 * 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.
78 */
89
910 import { sshOn } from "../../settings/ssh.ts";
1011 import {
11 CONNECTION_WORDS, MINECRAFT_PROOF, NOT_RETROACTIVE, addConnection, addMinecraftConnection, chooseUse,
12 CONNECTION_WORDS, MINECRAFT_PROOF, NOT_RETROACTIVE, SIGN_IN_ADDRESS, addConnection, addMinecraftConnection, chooseUse,
1213 confirmConnection, connectionsOf, dropConnection,
1314 } from "../../actions/identities.ts";
1415 import { USES, type Connection, type Use } from "../../core/identities.ts";
@@ -47,11 +48,18 @@ const card = (c: Connection): Html => {
4748 placeholder="Code from the mail" aria-label="Code mailed to ${c.ident}" required />
4849 ${btn("Prove", { variant: "primary", size: "sm", label: `Prove ${c.ident}` })}`,
4950 );
51 const remove = btn("Remove", { size: "sm", icon: "x", label: `Remove ${c.ident}` });
5052 return row({
5153 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}`,
5563 });
5664 };
5765
@@ -134,6 +142,6 @@ export async function identityUse(ctx: Ctx): Promise<Response> {
134142 export async function identityRemove(ctx: Ctx): Promise<Response> {
135143 const got = await acting(ctx);
136144 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");
138146 return said(ctx, done.ok ? "Removed. " + NOT_RETROACTIVE : CONNECTION_WORDS[done.error], done.ok);
139147 }
test/first-ask-first-tell.test.ts +2 −1
@@ -11,6 +11,7 @@ import { firstBoot } from "../src/spawn/first-boot.ts";
1111 import { startedFromOf } from "../src/spawn/template_record.ts";
1212 import { startedForge, type StartedForge } from "./helpers/claimed-forge.ts";
1313 import { quietLogs } from "./helpers/globals.ts";
14 import { unproveAll } from "./helpers/verified.ts";
1415
1516 quietLogs();
1617
@@ -63,7 +64,7 @@ test("the first ask is filed as the first tell, once, and leaves the record", as
6364 });
6465
6566 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);
6768 const before = titles();
6869 await rebootWith({ id: "a/b", repo: "a/b", firstAsk: "Add a refused page" });
6970 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";
3030 import { createSession } from "../src/core/sessions.ts";
3131 import { createToken } from "../src/core/tokens.ts";
3232 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";
3434 import { foldWall } from "../src/crew/fold_walls.ts";
3535 import { landIfGreen } from "../src/crew/land_queue.ts";
3636 import { queueAgentRun } from "../src/crew/dispatch.ts";
@@ -283,8 +283,7 @@ describe("a guest helps build a public repository", () => {
283283 test("an account with no confirmed email is told to confirm it", async () => {
284284 const made = await createUser(app.db, { origin: "seed", username: "unproven", email: "[email protected]", password: "correct-horse-battery" });
285285 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);
288287 const forked = await forkRepo(app, getUserByName(app.db, "unproven")!, lib);
289288 expect(!forked.ok && forked.error).toBe("unverified");
290289 });
test/helpers/verified.ts +11 −5
@@ -1,4 +1,6 @@
1 import type { Database } from "bun:sqlite";
12 import type { App } from "../../src/app.ts";
3 import { emailVerified, markVerified, resetVerification } from "../../src/core/verify.ts";
24 import { signUp as signUpAction } from "../../src/actions/users.ts";
35 import { fixtureSlot } from "./slot.ts";
46
@@ -9,11 +11,15 @@ import { fixtureSlot } from "./slot.ts";
911 * (`test/verify-email.test.ts`), and here it would only be in the way.
1012 */
1113 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);
1723 }
1824
1925 /** `signUp`, with the new account's email already proven. */
test/home-feed.test.ts +3 −4
@@ -6,6 +6,7 @@
66 * `feed` tool answers the same posts. Nothing private, nor an admin's
77 * configuration, reaches a reader's timeline.
88 */
9 import { markVerified, resetVerification } from "../src/core/verify.ts";
910 import { freshHome } from "./helpers/home-fresh.ts";
1011 import { afterAll, beforeAll, describe, expect, test } from "bun:test";
1112 import { mkdtemp, rm } from "node:fs/promises";
@@ -311,7 +312,7 @@ describe("home is the feed", () => {
311312 expect(forged.status).toBe(403);
312313 // The one tell's refusals: an unverified writer is told to verify, and
313314 // 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);
315316 try {
316317 const open = listIssues(app.db, garden.id, { state: "open" }).length;
317318 const unverified = await fetch(`${servers.url}/tell`, {
@@ -326,9 +327,7 @@ describe("home is the feed", () => {
326327 );
327328 expect(listIssues(app.db, garden.id, { state: "open" }).length).toBe(open);
328329 } 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());
332331 }
333332 });
334333
test/identities-doors.test.ts +80 −10
@@ -1,7 +1,8 @@
11 /**
22 * The two doors of connections on an account (#18108): Settings › Proven identities and the
33 * 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.
56 */
67 import { afterAll, beforeAll, expect, test } from "bun:test";
78 import { mkdtemp, rm } from "node:fs/promises";
@@ -12,8 +13,10 @@ import { addEmail, listConnections, proveEmail } from "../src/core/identities.ts
1213 import { createSession } from "../src/core/sessions.ts";
1314 import { createUser, type User } from "../src/core/users.ts";
1415 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";
1617 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";
1720 import type { Session } from "../src/tui/session.ts";
1821 import type { KeyEvent } from "../src/tui/term/input.ts";
1922 import { Screen as Surface } from "../src/tui/term/screen.ts";
@@ -44,6 +47,12 @@ afterAll(async () => {
4447 await rm(dir, { recursive: true, force: true });
4548 });
4649
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
4756 const form = (path: string, fields: Record<string, string>, origin = "https://forge.example", c = cookie) =>
4857 fetch(`${servers.url}${path}`, {
4958 method: "POST",
@@ -57,27 +66,27 @@ test("the page needs a signed-in account and a same-origin form", async () => {
5766 expect(anon.status).toBe(303);
5867 expect((await form("/settings/identities", { email: "[email protected]" }, "https://forge.example", "")).status).toBe(303);
5968 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([]);
6170 });
6271
6372 test("add, prove, choose and remove by the page's forms; the note and the address are escaped", async () => {
6473 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]!;
6675 expect(c.proven).toBe(false);
6776 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);
6978 const code = /code is (\d{6})/.exec(sent.at(-1)!)![1]!;
7079 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);
7281 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 });
7483 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);
7685 const html = await (await fetch(`${servers.url}/settings/identities`, { headers: { cookie } })).text();
7786 expect(html).toContain("[email protected]");
7887 expect(html).toContain("Issues already filed are not rewritten");
7988 await form(`/settings/identities/${c.id}/delete`, {});
80 expect(listConnections(app.db, tess.id)).toEqual([]);
89 expect(added()).toEqual([]);
8190 });
8291
8392 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 () => {
8695 const made = addEmail(app.db, o.value.id, "[email protected]", Date.now());
8796 if (typeof made === "string") throw new Error(made);
8897 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]"]);
9099 });
91100
92101 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
134143 expect(screen.key!({ type: "key", key: "m", ctrl: false, alt: false, shift: false })).toBe(true);
135144 expect(pushed).toHaveLength(1);
136145 });
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", () => {
8989 expect((await ask("[email protected]")).user).toBeNull();
9090 // A wrong code proves nothing; the stored value is a hash, not the code.
9191 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()!;
9393 expect(stored.code_hash).not.toContain(codeSent());
9494 // Another account cannot prove it with the code mailed to this one.
9595 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", () => {
133133 expect(after.ok && after.value.filedBy.how).toBe("anonymous");
134134 expect(during.ok && during.value.filedBy.name).toBe("tess");
135135 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]]);
137138 expect(listed.note).toContain("not rewritten");
138139 });
139140
test/mcp-crew.test.ts +2 −1
@@ -1,4 +1,5 @@
11 /** The `crew` tool is Settings › Crew over MCP: list, plan, apply (admin token, never an agent). */
2 import { resetVerification } from "../src/core/verify.ts";
23 import { afterAll, beforeAll, expect, test } from "bun:test";
34 import { mkdtemp, rm } from "node:fs/promises";
45 import { tmpdir } from "node:os";
@@ -45,7 +46,7 @@ beforeAll(async () => {
4546 const carolRepo = await createRepo(app, c.value, { name: "side", visibility: "public" });
4647 if (!carolRepo.ok) throw new Error(String(carolRepo.error));
4748 // 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);
4950 carol = createToken(app.db, c.value.id, "admin", "admin").token;
5051 bob = createToken(app.db, b.value.id, "admin", "admin").token;
5152 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";
1010 import { setLimit } from "../src/settings/limits.ts";
1111 import { createToken } from "../src/core/tokens.ts";
1212 import { getUserByName } from "../src/core/users.ts";
13 import { emailVerified } from "../src/core/verify.ts";
13 import { emailVerified, markVerified } from "../src/core/verify.ts";
1414 import type { Mail } from "../src/kernel/mail.ts";
1515 import { serve, type Servers } from "../src/http/server.ts";
1616 import { seedAdmin } from "./helpers/admin.ts";
@@ -89,7 +89,7 @@ describe("MCP email_verify", () => {
8989
9090 test("a verified person is told so, and nothing is sent", async () => {
9191 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");
9393 if (!emailVerified(app.db, user.id)) throw new Error("fixture: not verified");
9494 const before = sent.length;
9595 const res = await ask(token);
test/mcp-tell.test.ts +2 −2
@@ -17,7 +17,7 @@ import { getUserByName } from "../src/core/users.ts";
1717 import { serve, type Servers } from "../src/http/server.ts";
1818 import { seedAdmin } from "./helpers/admin.ts";
1919 import { tokenFor } from "./helpers/tokens.ts";
20 import { proveAll } from "./helpers/verified.ts";
20 import { proveAll, unproveAll } from "./helpers/verified.ts";
2121
2222 describe("MCP tell refusals", () => {
2323 let dataDir: string;
@@ -112,7 +112,7 @@ describe("MCP tell refusals", () => {
112112 // An over-long text is the schema's to refuse on the MCP door, naming the argument.
113113 expect(mcp).toContain(text === long ? 'argument "text"' : web);
114114 }
115 app.db.query("UPDATE email_check SET verified_at = NULL").run();
115 unproveAll(app.db);
116116 try {
117117 const web = await composer("hello");
118118 expect(web).toBe(refusalWords("unverified", ""));
test/passkey-recovery.test.ts +4 −3
@@ -11,7 +11,7 @@ import { join } from "node:path";
1111 import { createApp, type App } from "../src/app.ts";
1212 import { b64u } from "../src/auth/webauthn.ts";
1313 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";
1515 import { sha256 } from "../src/kernel/hash.ts";
1616 import { serve, type Servers } from "../src/http/server.ts";
1717 import type { Mail } from "../src/kernel/mail.ts";
@@ -106,7 +106,7 @@ describe("passkey recovery", () => {
106106 const token = linkOf(sent[0]!);
107107
108108 // 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()!;
110110 expect(row.token_hash).toBe(sha256(token));
111111 expect(JSON.stringify(row)).not.toContain(token);
112112 const life = Date.parse(row.expires_at) - Date.now();
@@ -150,7 +150,8 @@ describe("passkey recovery", () => {
150150 test("a pending verification link opens nothing here", async () => {
151151 // una never proved the address: her verification link must not sign in.
152152 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());
154155 expect((await post("/recover/options", { token: "pending" })).status).toBe(400);
155156 sent.length = 0;
156157 await ask("[email protected]");
test/ssh-tell.test.ts +5 −3
@@ -2,6 +2,8 @@
22 * `ssh <forge> tell <words>` (#6110): an exec of `tell` drives the same
33 * `tell()` as the web composer, as the key's account, and says where it went.
44 */
5 import { markVerified, resetVerification } from "../src/core/verify.ts";
6 import { proveAll } from "./helpers/verified.ts";
57 import { afterAll, beforeAll, describe, expect, test } from "bun:test";
68 import { mkdtemp, rm } from "node:fs/promises";
79 import { tmpdir } from "node:os";
@@ -172,13 +174,13 @@ describe("ssh forge tell", () => {
172174
173175 test("a verified account that may not direct the crew is told so, and records nothing", async () => {
174176 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);
176178 try {
177179 const r = await exec(KEY_B, "tell hello");
178180 expect([r.code, r.err]).toEqual([1, `forge: ${DIRECTION_NOTE}\r\n`]);
179181 } finally {
180182 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);
182184 }
183185 expect(issues().length).toBe(1);
184186 });
@@ -200,7 +202,7 @@ describe("ssh forge tell", () => {
200202 expect(row.body).toContain(`Told from [${address}](${address})`);
201203 expect(issues().length).toBe(before + 1);
202204 // 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());
204206 const r = await exec(KEY_B, "tell and the footer", "notes");
205207 expect([r.code, r.err]).toEqual([0, ""]);
206208 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";
2020 import { headlessTerminal } from "../src/tui/term/terminal.ts";
2121 import { quietLogs } from "./helpers/globals.ts";
2222 import { settleApp } from "./helpers/tui.ts";
23 import { proveAll } from "./helpers/verified.ts";
23 import { proveAll, unproveAll } from "./helpers/verified.ts";
2424
2525 quietLogs();
2626
@@ -115,7 +115,7 @@ describe("t on the answers screen", () => {
115115
116116 test("an unverified owner hears the tell's own words and opens nothing", async () => {
117117 const before = issues().length;
118 app.db.query("UPDATE email_check SET verified_at = NULL").run();
118 unproveAll(app.db);
119119 try {
120120 const seen = await drive(alice, ["t", ..."Unseen.", "\r"]);
121121 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";
1919 import type { Repo } from "../src/core/repos.ts";
2020 import type { Run } from "../src/core/runs.ts";
2121 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";
2323 import { createForgeApp } from "../src/tui/forge.ts";
2424 import { deploysScreen } from "../src/tui/screens/deploys.ts";
2525 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",
191191 });
192192
193193 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);
195195 try {
196196 const h = await open(alice);
197197 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";
1919 import type { User } from "../src/core/users.ts";
2020 import { repoDir } from "../src/git/repos.ts";
2121 import { gitClientEnv } from "./helpers/git-client.ts";
22 import { markVerified } from "../src/core/verify.ts";
22 import { markVerified, resetVerification } from "../src/core/verify.ts";
2323 import { createForgeApp } from "../src/tui/forge.ts";
2424 import { deploysScreen } from "../src/tui/screens/deploys.ts";
2525 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 () => {
151151 });
152152
153153 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);
155155 try {
156156 const h = await open(alice);
157157 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";
1616 import type { Repo } from "../src/core/repos.ts";
1717 import type { Run } from "../src/core/runs.ts";
1818 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";
2020 import { createForgeApp } from "../src/tui/forge.ts";
2121 import { deploysScreen } from "../src/tui/screens/deploys.ts";
2222 import { headlessTerminal } from "../src/tui/term/terminal.ts";
@@ -152,7 +152,7 @@ test("a reader is offered neither key", async () => {
152152 });
153153
154154 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);
156156 try {
157157 const h = await open(alice);
158158 await h.press("j", "D", "y");
test/verify-recovery.test.ts +4 −3
@@ -42,8 +42,8 @@ describe("recovery links", () => {
4242 };
4343 const row = (id: string) =>
4444 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",
4747 )
4848 .get(id);
4949
@@ -111,11 +111,12 @@ describe("recovery links", () => {
111111
112112 test("markUnproven writes an unproven row, keeps a proven one, touches no other", async () => {
113113 const dan = await make("dan");
114 resetVerification(app.db, dan); // created trusted, so proven; make it unproven
114115 app.db.query("DELETE FROM email_check WHERE user_id = ?1").run(dan);
115116 expect(row(dan)).toBeNull();
116117 const before = row(bob);
117118 markUnproven(app.db, dan);
118 expect(row(dan)).toEqual({ verified_at: null });
119 expect(row(dan)).toEqual({ token_hash: null });
119120 expect(emailVerified(app.db, dan)).toBe(false);
120121 expect(row(bob)).toEqual(before);
121122 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 });

Search
↑↓ navigate ↵ open ⌘↵ its app esc close

Keyboard shortcuts

Docs