Public: anyone can read this; the crew can change it.

Passkeys, part 2b: a verified email gets a single-use, 30-minute link that registers a new passkey #2004

Parked opened this
Closed without merging

scout/forge:scout/1997-passkeys-part-2b-a-verified-email-gets-a → main 1 commit fork

  • Closed without merging. Nothing was applied to main.

Review

Sign in to review this change.
8 files changed +481 −5
scripts/gate.ts +1
@@ -49,6 +49,7 @@ export const GATE: readonly string[] = [
4949 "test/thoughts.test.ts",
5050 "test/triage.test.ts",
5151 "test/passkeys.test.ts",
52 "test/passkey-recovery.test.ts",
5253 "test/webauthn.test.ts",
5354 "test/chaos.test.ts",
5455 "test/flow-stage.test.ts",
src/actions/verify.ts +64 −1
@@ -12,11 +12,14 @@ import {
1212 consumeLink,
1313 emailVerified,
1414 issueLink,
15 issueRecovery,
16 recoveryOwner,
17 spendRecovery,
1518 markVerified,
1619 resetVerification,
1720 } from "../core/verify.ts";
1821 import { listSecretNames, resolveSecrets } from "../core/secret_store.ts";
19 import { getUserById, type User } from "../core/users.ts";
22 import { getUserById, isActive, type User } from "../core/users.ts";
2023 import { sendMail, type Mailer } from "../kernel/mail.ts";
2124 import { mayMail, sendCapped } from "./mail.ts";
2225 import { err, ok, type Result } from "../kernel/result.ts";
@@ -165,3 +168,63 @@ export async function resendVerification(
165168 const outcome = await sendVerification(app, user.value);
166169 return outcome === "sent" ? ok("sent") : err(outcome);
167170 }
171
172 function recoveryUrl(app: App, token: string): string {
173 const base = app.config.url ?? `http://localhost:${app.config.port}`;
174 return `${new URL("/recover", base).toString()}?token=${token}`;
175 }
176
177 /**
178 * Someone who cannot sign in asks for a way back by address. Nothing here
179 * tells an address with an account from one without: the caller answers the
180 * same either way. A link goes only to a person whose email is proven, is
181 * not suspended or removed, and only when the forge can send mail. The send
182 * is not waited for, so the answer takes as long for a stranger as for a
183 * member.
184 */
185 export function requestRecovery(
186 app: App,
187 email: string,
188 now: number = Date.now(),
189 ): void {
190 const row = app.db
191 .query<{ id: string }, [string]>(
192 "SELECT id FROM user WHERE email = ?1 COLLATE NOCASE AND kind = 'user' AND is_agent = 0",
193 )
194 .get(email.trim());
195 const user = row === null ? undefined : getUserById(app.db, row.id);
196 if (user === undefined || !isActive(user)) return;
197 const mailer = mailerOf(app, user);
198 if (mailer === undefined || !mayMail(app, user.email, now)) return;
199 const token = issueRecovery(app.db, user.id, now);
200 if (token === undefined) return;
201 void sendCapped(app, mailer, {
202 to: user.email,
203 subject: "Get back into your forge account",
204 text: [
205 `Hello ${user.username},`,
206 "",
207 "Follow this link to register a new passkey and sign in. It works once, for 30 minutes:",
208 "",
209 recoveryUrl(app, token),
210 "",
211 "If you did not ask for this, ignore this message.",
212 ].join("\n"),
213 }, now).catch(() => undefined);
214 }
215
216 /** The account a recovery link is for, if it still works; nothing is spent. */
217 export function recoveryAccount(app: App, token: string): User | undefined {
218 const id = recoveryOwner(app.db, token, Date.now());
219 const user = id === undefined ? undefined : getUserById(app.db, id);
220 return user !== undefined && isActive(user) ? user : undefined;
221 }
222
223 /** Spend the link: the account to sign in, or `invalid` for a used or stale one. */
224 export function spendRecoveryLink(app: App, token: string): Result<User, "invalid"> {
225 const id = spendRecovery(app.db, token, Date.now());
226 const user = id === undefined ? undefined : getUserById(app.db, id);
227 if (user === undefined || !isActive(user)) return err("invalid");
228 app.bus.append({ kind: "account.recovered", actorId: user.id });
229 return ok(user);
230 }
src/core/verify.ts +62
@@ -129,3 +129,65 @@ export function consumeLink(
129129 markVerified(db, row.user_id, new Date(now).toISOString());
130130 return row.user_id;
131131 }
132
133 /** How long a recovery link works. */
134 export const RECOVERY_TTL_MS = 30 * 60_000;
135
136 /**
137 * Mint a recovery link for an account whose email is proven: the same
138 * `email_check` slot a verification link uses, so there is one token store.
139 * A proven account holds no verification link, so nothing is overwritten.
140 * Undefined for an account that is not proven.
141 */
142 export function issueRecovery(
143 db: Database,
144 userId: string,
145 now: number,
146 ): string | undefined {
147 const token = secret();
148 const changed = db
149 .query(
150 `UPDATE email_check SET token_hash = ?2, expires_at = ?3
151 WHERE user_id = ?1 AND verified_at IS NOT NULL`,
152 )
153 .run(userId, sha256(token), new Date(now + RECOVERY_TTL_MS).toISOString());
154 return changed.changes > 0 ? token : undefined;
155 }
156
157 /**
158 * Whose recovery link this is, without spending it. Only a proven account's
159 * link counts, so a pending verification link opens nothing here.
160 */
161 export function recoveryOwner(
162 db: Database,
163 token: string,
164 now: number,
165 ): string | undefined {
166 if (token === "") return undefined;
167 return (
168 db
169 .query<{ user_id: string }, [string, string]>(
170 `SELECT user_id FROM email_check
171 WHERE token_hash = ?1 AND verified_at IS NOT NULL AND expires_at > ?2`,
172 )
173 .get(sha256(token), new Date(now).toISOString())?.user_id ?? undefined
174 );
175 }
176
177 /** Spend a recovery link: the account it was for, once; undefined after. */
178 export function spendRecovery(
179 db: Database,
180 token: string,
181 now: number,
182 ): string | undefined {
183 if (token === "") return undefined;
184 return (
185 db
186 .query<{ user_id: string }, [string, string]>(
187 `UPDATE email_check SET token_hash = NULL, expires_at = NULL
188 WHERE token_hash = ?1 AND verified_at IS NOT NULL AND expires_at > ?2
189 RETURNING user_id`,
190 )
191 .get(sha256(token), new Date(now).toISOString())?.user_id ?? undefined
192 );
193 }
src/http/server.ts +8
@@ -99,6 +99,10 @@ import {
9999 passkeyDelete,
100100 passkeyOptions,
101101 passkeysPage,
102 recoverFinish,
103 recoverOptions,
104 recoverPage,
105 recoverRequest,
102106 signinOptions,
103107 signinPasskey,
104108 } from "../web/pages/passkeys.ts";
@@ -685,6 +689,10 @@ export function buildRouter(): Router<Handler> {
685689 router.add("POST", "/settings/passkeys/:id/delete", passkeyDelete);
686690 router.add("POST", "/signin/passkey/options", signinOptions);
687691 router.add("POST", "/signin/passkey", signinPasskey);
692 router.add("GET", "/recover", recoverPage);
693 router.add("POST", "/recover", recoverRequest);
694 router.add("POST", "/recover/options", recoverOptions);
695 router.add("POST", "/recover/passkey", recoverFinish);
688696 // The crew: a forge admin's section, hidden from everyone else.
689697 router.add("GET", "/settings/subscriptions", subscriptionsPage);
690698 router.add("POST", "/settings/subscriptions", subscriptionAdd);
src/web/pages/passkeys.ts +132 −4
@@ -17,26 +17,28 @@ import {
1717 removePasskey,
1818 PASSKEY_NAME_MAX,
1919 } from "../../core/passkeys.ts";
20 import { RateLimiter } from "../../core/ratelimit.ts";
2021 import { createSession } from "../../core/sessions.ts";
22 import { recoveryAccount, requestRecovery, spendRecoveryLink } from "../../actions/verify.ts";
2123 import { getUserById, isActive } from "../../core/users.ts";
2224 import { crossOrigin, type Ctx } from "../../http/context.ts";
2325 import { clientAddress } from "../../http/peer.ts";
2426 import { STRANGER_MAX } from "../../http/limits.ts";
2527 import { boundedBody, json, str } from "../../http/respond.ts";
2628 import { signInFirst } from "../chrome.ts";
27 import { readForm } from "../form.ts";
29 import { field, readForm } from "../form.ts";
2830 import { html } from "../html.ts";
29 import { flashTo } from "../layout.ts";
31 import { flashTo, page } from "../layout.ts";
3032 import { passkeyJs } from "../passkey-client.ts";
3133 import { card, empty, confirmAction, time } from "../ui.ts";
3234 import { accountShell } from "./account.ts";
3335 import { safeNext, sessionCookie, signinAllowed } from "./site.ts";
3436
3537 /** One-time challenges, one store per ceremony per forge. */
36 const stores = new WeakMap<App, { add: ReturnType<typeof challenges>; signin: ReturnType<typeof challenges> }>();
38 const stores = new WeakMap<App, { add: ReturnType<typeof challenges>; signin: ReturnType<typeof challenges>; recover: ReturnType<typeof challenges> }>();
3739 function store(app: App) {
3840 let s = stores.get(app);
39 if (!s) stores.set(app, (s = { add: challenges(), signin: challenges() }));
41 if (!s) stores.set(app, (s = { add: challenges(), signin: challenges(), recover: challenges() }));
4042 return s;
4143 }
4244
@@ -196,3 +198,129 @@ export async function signinPasskey(ctx: Ctx): Promise<Response> {
196198 { "set-cookie": sessionCookie(session.token, session.expiresAt, ctx.url, ctx.app.config.url) },
197199 );
198200 }
201
202 /**
203 * Recovery by email: a proven address gets a 30-minute, single-use link
204 * (`actions/verify.ts`); opening it registers a new passkey and signs the
205 * person in. Asking is limited per address and per source, an hour at a
206 * time, and answers the same for an address with no account.
207 */
208 export const RECOVER_PER_ADDRESS = 3;
209 export const RECOVER_PER_SOURCE = 10;
210 const RECOVER_WINDOW_MS = 3_600_000;
211 const recoverLimits = new WeakMap<App, RateLimiter>();
212
213 function recoverWait(ctx: Ctx, email: string): number | undefined {
214 let limiter = recoverLimits.get(ctx.app);
215 if (limiter === undefined) {
216 limiter = new RateLimiter({ perMinute: 0, adminPerMinute: 0, enabled: true, windowMs: RECOVER_WINDOW_MS });
217 recoverLimits.set(ctx.app, limiter);
218 }
219 limiter.setLimits({ perMinute: RECOVER_PER_ADDRESS, adminPerMinute: RECOVER_PER_SOURCE, enabled: true, windowMs: RECOVER_WINDOW_MS });
220 const source = limiter.take(`from:${clientAddress(ctx.request)}`, "admin");
221 if (!source.allowed) return source.retryAfter;
222 const address = limiter.take(`to:${email.toLowerCase()}`, "ro");
223 return address.allowed ? undefined : address.retryAfter;
224 }
225
226 const NOT_VALID = "This link has expired, been used, or is not valid. Ask for a new one.";
227
228 // GET /recover — the request form, or (with ?token=) the new-passkey step.
229 export function recoverPage(ctx: Ctx): Response {
230 const token = ctx.url.searchParams.get("token");
231 if (token === null) {
232 return page({
233 ctx,
234 title: "Recover your account",
235 body: html`<div class="page-head"><h1>Recover your account</h1></div>
236 <p class="muted small mb">Give the email on your account. If it is verified, we send a link that lasts 30 minutes and works once; it lets you register a new passkey.</p>
237 <form method="post" action="/recover">
238 <div class="field"><label for="recover-email">Email</label>
239 <input id="recover-email" name="email" type="email" maxlength="254" autocomplete="email" required /></div>
240 <div class="form-actions"><button class="btn" data-variant="primary">Send the link</button></div>
241 </form>`,
242 });
243 }
244 const user = recoveryAccount(ctx.app, token);
245 if (user === undefined)
246 return page({ ctx, title: "Link not valid", body: html`<div class="page-head"><h1>Link not valid</h1></div><p>${NOT_VALID}</p><p><a href="/recover">Ask for a new link</a></p>` }, 400);
247 return page({
248 ctx,
249 title: "Register a new passkey",
250 scriptJs: passkeyJs,
251 body: html`<div class="page-head"><h1>Register a new passkey</h1></div>
252 <p class="muted small mb">This signs you in as ${user.username}. Name the device, then follow your browser's prompt.</p>
253 <div class="field"><label for="passkey-name">Name</label>
254 <input id="passkey-name" name="name" maxlength="${PASSKEY_NAME_MAX}" autocomplete="off" placeholder="Laptop, phone, security key" /></div>
255 <p class="error-note" id="passkey-recover-note" role="status"></p>
256 <noscript><p class="muted small">Registering a passkey needs JavaScript.</p></noscript>
257 <div class="form-actions"><button type="button" id="passkey-recover" class="btn" data-variant="primary">Register and sign in</button></div>`,
258 });
259 }
260
261 // POST /recover — ask for a link. The same page for every address.
262 export async function recoverRequest(ctx: Ctx): Promise<Response> {
263 const form = await readForm(ctx, undefined, STRANGER_MAX);
264 if (form instanceof Response) return form;
265 const email = field(form, "email").trim().slice(0, 254);
266 const wait = email === "" ? undefined : recoverWait(ctx, email);
267 if (wait !== undefined) {
268 const res = page({ ctx, title: "Recover your account", body: html`<div class="page-head"><h1>Too many requests</h1></div><p>Try again in ${wait} seconds.</p>` }, 429);
269 res.headers.set("retry-after", String(wait));
270 return res;
271 }
272 if (email !== "") requestRecovery(ctx.app, email);
273 return page({
274 ctx,
275 title: "Check your email",
276 body: html`<div class="page-head"><h1>Check your email</h1></div>
277 <p>If that address belongs to an account with a verified email, a link is on its way. It lasts 30 minutes and works once.</p>`,
278 });
279 }
280
281 // POST /recover/options — a challenge, for a link that still works.
282 export async function recoverOptions(ctx: Ctx): Promise<Response> {
283 if (crossOrigin(ctx.request, ctx.url, ctx.app.log)) return refuse(403, "forbidden");
284 const data = await boundedBody(ctx.request, STRANGER_MAX);
285 if (data === "too_large") return refuse(413, "payload too large");
286 const user = recoveryAccount(ctx.app, str(data.token));
287 if (user === undefined) return refuse(400, NOT_VALID);
288 return json({
289 challenge: store(ctx.app).recover.issue(),
290 rpId: relying(ctx).rpId,
291 rpName: "forge",
292 user: {
293 id: Buffer.from(user.id).toString("base64url"),
294 name: user.username,
295 displayName: user.displayName || user.username,
296 },
297 exclude: passkeyIds(ctx.app.db, user.id),
298 });
299 }
300
301 // POST /recover/passkey — a good registration spends the link and signs in.
302 export async function recoverFinish(ctx: Ctx): Promise<Response> {
303 if (crossOrigin(ctx.request, ctx.url, ctx.app.log)) return refuse(403, "forbidden");
304 const data = await boundedBody(ctx.request, STRANGER_MAX);
305 if (data === "too_large") return refuse(413, "payload too large");
306 const token = str(data.token);
307 const challenge = str(data.challenge);
308 if (!store(ctx.app).recover.consume(challenge)) return refuse(400, "That request expired. Try again.");
309 if (recoveryAccount(ctx.app, token) === undefined) return refuse(400, NOT_VALID);
310 const made = await verifyRegistration(
311 { clientDataJSON: str(data.clientDataJSON), attestationObject: str(data.attestationObject) },
312 { challenge, ...relying(ctx) },
313 );
314 if (!made.ok) return refuse(400, "That passkey was not accepted.");
315 const spent = spendRecoveryLink(ctx.app, token);
316 if (!spent.ok) return refuse(400, NOT_VALID);
317 const name = str(data.name).replace(/[\u0000-\u001f\u007f]/g, " ").trim().slice(0, PASSKEY_NAME_MAX) || "Passkey";
318 const added = addPasskey(ctx.app.db, spent.value.id, name, made);
319 if (!added.ok && added.error === "too_many")
320 return refuse(409, "That is as many passkeys as an account keeps. Remove one after signing in with another.");
321 if (!added.ok) return refuse(409, "That passkey is already registered.");
322 const session = createSession(ctx.app.db, spent.value.id);
323 return json({ ok: true, next: "/settings/passkeys" }, 200, {
324 "set-cookie": sessionCookie(session.token, session.expiresAt, ctx.url, ctx.app.config.url),
325 });
326 }
src/web/pages/site.ts +1
@@ -466,6 +466,7 @@ function authForm(
466466 () => html`<p class="mt">
467467 <button type="button" id="passkey-signin" class="btn" data-variant="outline">Sign in with a passkey</button>
468468 <span class="error-note small" id="passkey-signin-note" role="status"></span>
469 <a class="small" href="/recover">Lost your device?</a>
469470 </p>`,
470471 )}
471472 ${claimable
src/web/passkey-client.ts +24
@@ -72,6 +72,30 @@ export const passkeyJs = /* js */ `
7272 });
7373 }).then(function () { location.reload(); });
7474 });
75 wire('passkey-recover', function () {
76 var name = doc.getElementById('passkey-name');
77 var token = new URLSearchParams(location.search).get('token') || '';
78 return post('/recover/options', { token: token }).then(function (o) {
79 return navigator.credentials.create({ publicKey: {
80 challenge: bytes(o.challenge),
81 rp: { id: o.rpId, name: o.rpName },
82 user: { id: bytes(o.user.id), name: o.user.name, displayName: o.user.displayName },
83 pubKeyCredParams: [{ type: 'public-key', alg: -7 }, { type: 'public-key', alg: -257 }],
84 excludeCredentials: o.exclude.map(function (c) { return { type: 'public-key', id: bytes(c) }; }),
85 authenticatorSelection: { residentKey: 'preferred', userVerification: 'required' },
86 attestation: 'none',
87 timeout: 120000
88 } }).then(function (cred) {
89 return post('/recover/passkey', {
90 token: token,
91 name: name ? name.value : '',
92 challenge: o.challenge,
93 clientDataJSON: text(cred.response.clientDataJSON),
94 attestationObject: text(cred.response.attestationObject)
95 });
96 });
97 }).then(function (r) { location.href = r.next; });
98 });
7599 wire('passkey-signin', function () {
76100 return post('/signin/passkey/options').then(function (o) {
77101 return navigator.credentials.get({ publicKey: {
test/passkey-recovery.test.ts added +189
@@ -0,0 +1,189 @@
1 /**
2 * Recovering an account by email: a verified address gets a single-use,
3 * 30-minute link that registers a new passkey and signs in. Expired, reused
4 * and forged links are refused; an unknown address is answered like a known
5 * one; the token is stored only as a hash.
6 */
7 import { afterAll, beforeAll, describe, expect, test } from "bun:test";
8 import { mkdtemp, rm } from "node:fs/promises";
9 import { tmpdir } from "node:os";
10 import { join } from "node:path";
11 import { createApp, type App } from "../src/app.ts";
12 import { b64u } from "../src/auth/webauthn.ts";
13 import { markVerified, RECOVERY_TTL_MS } from "../src/core/verify.ts";
14 import { sha256 } from "../src/kernel/hash.ts";
15 import { serve, type Servers } from "../src/http/server.ts";
16 import type { Mail } from "../src/kernel/mail.ts";
17
18 const te = new TextEncoder();
19 const sha = async (d: Uint8Array<ArrayBuffer>) => new Uint8Array(await crypto.subtle.digest("SHA-256", d));
20 const cat = (...p: Uint8Array[]): Uint8Array<ArrayBuffer> => { const o: Uint8Array<ArrayBuffer> = new Uint8Array(p.reduce((n, a) => n + a.length, 0)); let i = 0; for (const a of p) { o.set(a, i); i += a.length; } return o; };
21 function head(major: number, n: number): Uint8Array {
22 if (n < 24) return Uint8Array.of((major << 5) | n);
23 if (n < 256) return Uint8Array.of((major << 5) | 24, n);
24 return Uint8Array.of((major << 5) | 25, n >> 8, n & 255);
25 }
26 type V = number | string | Uint8Array | [V, V][];
27 function enc(v: V): Uint8Array {
28 if (typeof v === "number") return v >= 0 ? head(0, v) : head(1, -1 - v);
29 if (typeof v === "string") { const b = te.encode(v); return cat(head(3, b.length), b); }
30 if (v instanceof Uint8Array) return cat(head(2, v.length), v);
31 return cat(head(5, v.length), ...v.flatMap(([k, x]) => [enc(k), enc(x)]));
32 }
33
34 /** A software authenticator that can only register. */
35 async function register(origin: string, rp: string, challenge: string) {
36 const pair = (await crypto.subtle.generateKey({ name: "ECDSA", namedCurve: "P-256" }, true, ["sign"])) as CryptoKeyPair;
37 const jwk = await crypto.subtle.exportKey("jwk", pair.publicKey);
38 const unb = (s: string) => new Uint8Array(Buffer.from(s, "base64url"));
39 const cose: [number, V][] = [[1, 2], [3, -7], [-1, 1], [-2, unb(jwk.x!)], [-3, unb(jwk.y!)]];
40 const id = crypto.getRandomValues(new Uint8Array(32));
41 const authData = cat(await sha(te.encode(rp)), Uint8Array.of(0x45), new Uint8Array(4), new Uint8Array(16), Uint8Array.of(0, id.length), id, enc(cose as V));
42 return {
43 clientDataJSON: b64u(te.encode(JSON.stringify({ type: "webauthn.create", challenge, origin }))),
44 attestationObject: b64u(enc([["fmt", "none"], ["attStmt", []], ["authData", authData]])),
45 };
46 }
47
48 describe("passkey recovery", () => {
49 let dataDir: string;
50 let app: App;
51 let servers: Servers;
52 let base: string;
53 const sent: Mail[] = [];
54
55 const post = (path: string, body: unknown) =>
56 fetch(`${base}${path}`, { method: "POST", headers: { "content-type": "application/json" }, body: JSON.stringify(body), redirect: "manual" });
57 const ask = (email: string, from = "10.0.0.1") =>
58 fetch(`${base}/recover`, {
59 method: "POST",
60 body: new URLSearchParams({ email }),
61 });
62 const linkOf = (mail: Mail): string => /token=([\w-]+)/.exec(mail.text)![1]!;
63 async function finish(token: string) {
64 const o = await post("/recover/options", { token });
65 if (o.status !== 200) return { options: o, done: undefined };
66 const opts = (await o.json()) as any;
67 const origin = new URL(base);
68 const reg = await register(origin.origin, origin.hostname, opts.challenge);
69 return { options: o, done: await post("/recover/passkey", { token, name: "Laptop", challenge: opts.challenge, ...reg }) };
70 }
71
72 beforeAll(async () => {
73 dataDir = await mkdtemp(join(tmpdir(), "forge-recover-"));
74 app = createApp({
75 dataDir,
76 port: 0,
77 mailer: async (mail) => { sent.push(mail); return true; },
78 });
79 servers = await serve(app);
80 base = servers.url;
81 for (const [name, email] of [["pat", "[email protected]"], ["una", "[email protected]"]] as const) {
82 await fetch(`${base}/signup`, {
83 method: "POST",
84 body: new URLSearchParams({ username: name, email, password: "recover-password" }),
85 redirect: "manual",
86 });
87 }
88 // The first account is the owner; pat is the person who verifies.
89 const id = (n: string) => app.db.query<{ id: string }, [string]>("SELECT id FROM user WHERE username = ?1").get(n)!.id;
90 markVerified(app.db, id("pat"), new Date().toISOString());
91 });
92
93 afterAll(async () => {
94 servers.stop();
95 app.close();
96 await rm(dataDir, { recursive: true, force: true });
97 });
98
99 test("a verified address gets a link that registers a passkey, signs in, and works once", async () => {
100 sent.length = 0;
101 const res = await ask("[email protected]");
102 expect(res.status).toBe(200);
103 expect(sent).toHaveLength(1);
104 expect(sent[0]!.to).toBe("[email protected]");
105 const token = linkOf(sent[0]!);
106
107 // Only a hash is kept.
108 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 expect(row.token_hash).toBe(sha256(token));
110 expect(JSON.stringify(row)).not.toContain(token);
111 const life = Date.parse(row.expires_at) - Date.now();
112 expect(life).toBeGreaterThan(RECOVERY_TTL_MS - 60_000);
113 expect(life).toBeLessThanOrEqual(RECOVERY_TTL_MS);
114
115 // Opening the page spends nothing.
116 expect((await fetch(`${base}/recover?token=${token}`)).status).toBe(200);
117
118 const { done } = await finish(token);
119 expect(done!.status).toBe(200);
120 expect(await done!.json()).toEqual({ ok: true, next: "/settings/passkeys" });
121 const cookie = done!.headers.get("set-cookie")!;
122 expect(cookie).toContain("HttpOnly");
123 const keys = await fetch(`${base}/settings/passkeys`, { headers: { cookie: cookie.split(";")[0]! } });
124 expect(await keys.text()).toContain("<strong>Laptop</strong>");
125
126 // Reused: refused, and no second session.
127 const again = await finish(token);
128 expect(again.options.status).toBe(400);
129 expect((await fetch(`${base}/recover?token=${token}`)).status).toBe(400);
130 });
131
132 test("an expired link and a forged one are refused with one sentence", async () => {
133 sent.length = 0;
134 await ask("[email protected]", "10.0.0.2");
135 const token = linkOf(sent[0]!);
136 app.db.query("UPDATE email_check SET expires_at = ?1 WHERE token_hash = ?2").run(new Date(Date.now() - 1000).toISOString(), sha256(token));
137 const expired = await finish(token);
138 expect(expired.options.status).toBe(400);
139 const sentence = ((await expired.options.json()) as any).message as string;
140 const forged = await post("/recover/options", { token: "not-a-real-token" });
141 expect(forged.status).toBe(400);
142 expect(((await forged.json()) as any).message).toBe(sentence);
143 const page = await fetch(`${base}/recover?token=${token}`);
144 expect(page.status).toBe(400);
145 expect(await page.text()).toContain(sentence);
146 expect((await post("/recover/options", {})).status).toBe(400);
147 });
148
149 test("a pending verification link opens nothing here", async () => {
150 // una never proved the address: her verification link must not sign in.
151 const una = app.db.query<{ id: string }, []>("SELECT id FROM user WHERE username = 'una'").get()!.id;
152 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 expect((await post("/recover/options", { token: "pending" })).status).toBe(400);
154 sent.length = 0;
155 await ask("[email protected]", "10.0.0.3");
156 expect(sent).toHaveLength(0);
157 });
158
159 test("an unknown address is answered exactly like a known one", async () => {
160 const known = await ask("[email protected]", "10.0.0.4");
161 const unknown = await ask("[email protected]", "10.0.0.5");
162 expect(unknown.status).toBe(known.status);
163 const plain = async (r: Response) => (await r.text()).replace(/nonce="[^"]*"/g, "");
164 expect(await plain(unknown)).toBe(await plain(known));
165 });
166
167 test("asking is limited per address and per source", async () => {
168 sent.length = 0;
169 const statuses: number[] = [];
170 for (let i = 0; i < 4; i++) statuses.push((await ask("[email protected]")).status);
171 expect(statuses).toEqual([200, 200, 200, 429]);
172 });
173
174 test("asking is limited per source, whatever the addresses", async () => {
175 const other = createApp({ dataDir: await mkdtemp(join(tmpdir(), "forge-recover-src-")), port: 0 });
176 const more = await serve(other);
177 try {
178 const source: number[] = [];
179 for (let i = 0; i < 11; i++)
180 source.push((await fetch(`${more.url}/recover`, { method: "POST", body: new URLSearchParams({ email: `s${i}@f.dev` }) })).status);
181 expect(source.slice(0, 10)).toEqual(Array(10).fill(200));
182 expect(source[10]).toBe(429);
183 } finally {
184 more.stop();
185 other.close();
186 await rm(other.config.dataDir, { recursive: true, force: true });
187 }
188 });
189 });

↑↓ navigate ↵ open ⌘↵ its app esc close

Keyboard shortcuts

Docs