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

Passkeys, part 2: sign-up takes a passkey and an email, no new password-only accounts, and a verified email recovers #1960

Parked opened this
Closed without merging

scout/forge:scout/1618-passkeys-part-2-sign-up-takes-a-passkey → main 1 commit fork

  • Closed without merging. Nothing was applied to main.

Review

Sign in to review this change.
23 files changed +1048 −79
README.md +11
@@ -117,6 +117,17 @@ The sign-in page's "Sign in with a passkey" gives the same HttpOnly session a
117117 password does. The relying party is the address the browser used (or
118118 `FORGE_URL`), so a passkey does not follow a forge to another hostname.
119119
120 Sign-up takes a passkey and an email, never a password alone: the page's
121 button runs the ceremony (`POST /signup/options`, then `POST /signup/passkey`;
122 the API is `POST /api/v1/users/options` then `POST /api/v1/users` with the
123 same fields), and a password-only request is refused with `passkey_required`.
124 The terminal cannot do the ceremony, so it cannot create accounts: sign up on
125 the web page. Accounts that already have a password still sign in, and
126 Settings → Passkeys invites them to add a passkey. Lost every passkey? `/recover`
127 mails a verified address a link (single use, one hour) that registers a new
128 one; an unverified address gets nothing, and the page answers the same either
129 way. No dependency was added.
130
120131 Your SSH key is your identity. A key the forge knows signs you straight in; any
121132 other key browses public repos as a guest and can press `s` to sign in with a
122133 username and password — which links that key to your account, so the next
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/signup-passkey.test.ts",
5253 "test/webauthn.test.ts",
5354 "test/chaos.test.ts",
5455 "test/flow-stage.test.ts",
src/actions/recover.ts added +101
@@ -0,0 +1,101 @@
1 /**
2 * Getting back in with a verified email (#1618). A person who lost every
3 * passkey asks for a link; if the address is a proven one it is mailed a
4 * single-use link, good for an hour, that registers a new passkey. The ask
5 * answers the same whether or not the address is known, so it cannot be
6 * used to learn who has an account.
7 */
8
9 import { ceremonies } from "../auth/ceremonies.ts";
10 import { verifyRegistration } from "../auth/webauthn.ts";
11 import type { App } from "../app.ts";
12 import { addPasskey } from "../core/passkeys.ts";
13 import {
14 issueRecovery,
15 recoverableByEmail,
16 recoveryLive,
17 spendRecovery,
18 } from "../core/recovery.ts";
19 import { getUserById, isActive, type User } from "../core/users.ts";
20 import { err, ok, type Result } from "../kernel/result.ts";
21 import { mayMail, sendCapped } from "./mail.ts";
22 import { mailerOf } from "./verify.ts";
23
24 function recoveryUrl(app: App, token: string): string {
25 const base = app.config.url ?? `http://localhost:${app.config.port}`;
26 return `${new URL("/recover/passkey", base).toString()}?token=${token}`;
27 }
28
29 /** Mail a recovery link when the address is a proven one. Says nothing about which. */
30 export async function requestRecovery(
31 app: App,
32 email: string,
33 now: number = Date.now(),
34 ): Promise<void> {
35 const found = recoverableByEmail(app.db, email.trim());
36 if (found === undefined) return;
37 const user = getUserById(app.db, found.id);
38 if (user === undefined || !isActive(user)) return;
39 const mailer = mailerOf(app, user);
40 if (mailer === undefined || !mayMail(app, user.email, now)) return;
41 const token = issueRecovery(app.db, user.id, now);
42 if (token === undefined) return;
43 await sendCapped(
44 app,
45 mailer,
46 {
47 to: user.email,
48 subject: "Get back into the forge",
49 text: [
50 `Hello ${user.username},`,
51 "",
52 "Follow this link to register a new passkey. It works once, for an hour:",
53 "",
54 recoveryUrl(app, token),
55 "",
56 "If you did not ask for this, ignore this message; nothing has changed.",
57 ].join("\n"),
58 },
59 now,
60 );
61 }
62
63 /** A challenge for the new passkey, only while the link is good. */
64 export function recoveryChallenge(
65 app: App,
66 token: string,
67 now: number = Date.now(),
68 ): Result<string, "invalid"> {
69 if (!recoveryLive(app.db, token, now)) return err("invalid");
70 return ok(ceremonies(app).recover.issue());
71 }
72
73 /** Register the passkey the link was for, and spend the link. */
74 export async function recoverWithPasskey(
75 app: App,
76 body: Record<string, unknown>,
77 relying: { origin: string; rpId: string },
78 now: number = Date.now(),
79 ): Promise<Result<User, "invalid" | "challenge" | "passkey_rejected" | "too_many" | "duplicate">> {
80 const text = (v: unknown): string => (typeof v === "string" ? v : "");
81 const token = text(body["token"]);
82 if (!recoveryLive(app.db, token, now)) return err("invalid");
83 const challenge = text(body["challenge"]);
84 if (!ceremonies(app).recover.consume(challenge)) return err("challenge");
85 const made = await verifyRegistration(
86 {
87 clientDataJSON: text(body["clientDataJSON"]),
88 attestationObject: text(body["attestationObject"]),
89 },
90 { challenge, ...relying },
91 );
92 if (!made.ok) return err("passkey_rejected");
93 // The one UPDATE that spends the link decides a race between two answers.
94 const userId = spendRecovery(app.db, token, now);
95 const user = userId === undefined ? undefined : getUserById(app.db, userId);
96 if (user === undefined || !isActive(user)) return err("invalid");
97 const added = addPasskey(app.db, user.id, "Recovered passkey", made);
98 if (!added.ok) return err(added.error);
99 app.bus.append({ kind: "account.recovered", actorId: user.id });
100 return ok(user);
101 }
src/actions/users.ts +87 −4
@@ -11,6 +11,10 @@ import {
1111 parseAuthorizedKey,
1212 type UserKey,
1313 } from "../core/keys.ts";
14 import { ceremonies } from "../auth/ceremonies.ts";
15 import { verifyRegistration, type Credential } from "../auth/webauthn.ts";
16 import { addPasskey, findPasskey } from "../core/passkeys.ts";
17 import { signupPolicy } from "../core/signup_policy.ts";
1418 import { turnstileVerifier } from "../core/turnstile.ts";
1519 import { reservedName } from "../core/reserved.ts";
1620 import { setUserSetting } from "../core/settings.ts";
@@ -37,17 +41,72 @@ import { requireUser } from "./access.ts";
3741 export interface SignUpInput {
3842 username: string;
3943 email: string;
40 password: string;
44 /** Only for the fixtures of the suite: see `core/signup_policy.ts`. */
45 password?: string;
46 /** The passkey the person just registered: what a new account is made with. */
47 passkey?: { name: string; credential: Credential };
4148 /** The Turnstile token the browser's widget gave; read only when a secret is set. */
4249 humanToken?: string;
4350 }
4451
45 export type SignUpError = CreateUserError | "human_check";
52 export type SignUpError =
53 | CreateUserError
54 | "human_check"
55 | "passkey_required"
56 | "passkey_taken"
57 | "invalid_email"
58 | "challenge"
59 | "passkey_rejected";
4660
4761 /** What a person is told when the check fails. */
4862 export const HUMAN_CHECK_MESSAGE =
4963 "We could not tell you are a person. Reload the page and try again.";
5064
65 /** What a person is told when a password is all they offered. */
66 export const PASSKEY_REQUIRED_MESSAGE =
67 "Sign-up registers a passkey and an email address. Use the sign-up page in a browser.";
68
69 /** What an address must look like to be mailed; whether it is real is the link's job. */
70 export function plausibleEmail(email: string): boolean {
71 return email.length <= 254 && /^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(email);
72 }
73
74 /**
75 * Sign up with the answer of a browser's passkey ceremony: spend the
76 * challenge `signupOptions` issued, verify the registration, then make the
77 * account with that passkey and no password.
78 */
79 export async function signUpWithPasskey(
80 app: App,
81 body: Record<string, unknown>,
82 relying: { origin: string; rpId: string },
83 from: { address?: string | undefined } = {},
84 ): Promise<Result<User, SignUpError>> {
85 const text = (v: unknown): string => (typeof v === "string" ? v : "");
86 const email = text(body["email"]).trim();
87 if (!plausibleEmail(email)) return err("invalid_email");
88 const challenge = text(body["challenge"]);
89 if (!ceremonies(app).signup.consume(challenge)) return err("challenge");
90 const made = await verifyRegistration(
91 {
92 clientDataJSON: text(body["clientDataJSON"]),
93 attestationObject: text(body["attestationObject"]),
94 },
95 { challenge, ...relying },
96 );
97 if (!made.ok) return err("passkey_rejected");
98 return signUp(
99 app,
100 {
101 username: text(body["username"]),
102 email,
103 passkey: { name: "Passkey", credential: made },
104 humanToken: text(body["turnstile_token"]),
105 },
106 from,
107 );
108 }
109
51110 /**
52111 * The first account on a fresh forge is the admin — no setup wizard. A name
53112 * the crew, the owner or the forge itself answers to is not free
@@ -68,6 +127,14 @@ export async function signUp(
68127 door?: "terminal";
69128 } = {},
70129 ): Promise<Result<User, SignUpError>> {
130 // No account is made with only a password (#1618).
131 if (input.passkey === undefined && !signupPolicy.passwordOnly)
132 return err("passkey_required");
133 if (
134 input.passkey !== undefined &&
135 findPasskey(app.db, input.passkey.credential.id) !== undefined
136 )
137 return err("passkey_taken");
71138 const secret = app.config.turnstileSecret;
72139 const bootstrap = from.door === "terminal" && !hasAnyUser(app.db);
73140 if (secret !== undefined && !bootstrap) {
@@ -76,9 +143,25 @@ export async function signUp(
76143 if (!(await verify(input.humanToken ?? "", from.address)))
77144 return err("human_check");
78145 }
79 const { humanToken: _token, ...account } = input;
80 const created = await createUser(app.db, { ...account, adminIfFirst: true });
146 const { humanToken: _token, passkey, ...account } = input;
147 const created = await createUser(app.db, {
148 username: account.username,
149 email: account.email,
150 // A passkey account has no password: none is stored, none ever verifies.
151 ...(passkey === undefined && account.password !== undefined
152 ? { password: account.password }
153 : {}),
154 adminIfFirst: true,
155 });
81156 if (!created.ok) return created;
157 if (passkey !== undefined) {
158 const kept = addPasskey(app.db, created.value.id, passkey.name, passkey.credential);
159 if (!kept.ok) {
160 // Raced a twin of the same device: leave no account that cannot sign in.
161 app.db.query("DELETE FROM user WHERE id = ?1").run(created.value.id);
162 return err("passkey_taken");
163 }
164 }
82165 app.bus.append({
83166 kind: "user.created",
84167 actorId: created.value.id,
src/actions/verify.ts +1 −1
@@ -53,7 +53,7 @@ export function mailConfigured(app: App): boolean {
5353 return MAIL_SECRETS.every((name) => set.has(name));
5454 }
5555
56 function mailerOf(app: App, forUser: User): Mailer | undefined {
56 export function mailerOf(app: App, forUser: User): Mailer | undefined {
5757 if (app.config.mailer !== undefined) return app.config.mailer;
5858 const stored = resolveSecrets(
5959 app.db,
src/auth/ceremonies.ts added +20
@@ -0,0 +1,20 @@
1 /**
2 * The one-time challenges of each passkey ceremony, one store per ceremony
3 * per forge. A challenge answers once and expires (`auth/webauthn.ts`).
4 */
5
6 import type { App } from "../app.ts";
7 import { challenges } from "./webauthn.ts";
8
9 type Store = ReturnType<typeof challenges>;
10 const stores = new WeakMap<App, Record<"add" | "signin" | "signup" | "recover", Store>>();
11
12 export function ceremonies(app: App) {
13 let s = stores.get(app);
14 if (!s)
15 stores.set(
16 app,
17 (s = { add: challenges(), signin: challenges(), signup: challenges(), recover: challenges() }),
18 );
19 return s;
20 }
src/core/recovery.ts added +83
@@ -0,0 +1,83 @@
1 /**
2 * Recovery links: a person who lost every passkey, and whose email is
3 * proven (`core/verify.ts`), is sent a link that lets them register a new
4 * one. A link works once, for an hour; only its hash is stored. Pure data:
5 * the action sends the mail (`actions/recover.ts`).
6 */
7
8 import type { Database } from "bun:sqlite";
9 import { sha256 } from "../kernel/hash.ts";
10 import { emailVerified } from "./verify.ts";
11
12 export const RECOVERY_TTL_MS = 3_600_000;
13 /** One link per account per this long, so recovery cannot be used to flood a mailbox. */
14 export const RECOVERY_EVERY_MS = 5 * 60_000;
15
16 const secret = (): string =>
17 Buffer.from(crypto.getRandomValues(new Uint8Array(32))).toString("base64url");
18
19 /** The active person whose proven address this is; undefined for anything else. */
20 export function recoverableByEmail(
21 db: Database,
22 email: string,
23 ): { id: string; username: string; email: string } | undefined {
24 const row = db
25 .query<{ id: string; username: string; email: string }, [string]>(
26 "SELECT id, username, email FROM user WHERE lower(email) = lower(?1) AND kind = 'user'",
27 )
28 .get(email);
29 if (row === null || !emailVerified(db, row.id)) return undefined;
30 return row;
31 }
32
33 /** A new link, or undefined inside the window after the last one. */
34 export function issueRecovery(
35 db: Database,
36 userId: string,
37 now: number,
38 ): string | undefined {
39 const last = db
40 .query<{ created_at: string }, [string]>(
41 "SELECT max(created_at) AS created_at FROM recovery_link WHERE user_id = ?1",
42 )
43 .get(userId)?.created_at;
44 if (last && now - Date.parse(last) < RECOVERY_EVERY_MS) return undefined;
45 const token = secret();
46 db.query(
47 "INSERT INTO recovery_link (token_hash, user_id, expires_at, created_at) VALUES (?1, ?2, ?3, ?4)",
48 ).run(
49 sha256(token),
50 userId,
51 new Date(now + RECOVERY_TTL_MS).toISOString(),
52 new Date(now).toISOString(),
53 );
54 return token;
55 }
56
57 /** Whether the link is still good, without spending it. */
58 export function recoveryLive(db: Database, token: string, now: number): boolean {
59 if (token === "") return false;
60 const row = db
61 .query<{ used_at: string | null; expires_at: string }, [string]>(
62 "SELECT used_at, expires_at FROM recovery_link WHERE token_hash = ?1",
63 )
64 .get(sha256(token));
65 return row !== null && row.used_at === null && Date.parse(row.expires_at) > now;
66 }
67
68 /** Spend the link: the account it names, once. The one UPDATE decides a race. */
69 export function spendRecovery(
70 db: Database,
71 token: string,
72 now: number,
73 ): string | undefined {
74 if (token === "") return undefined;
75 const row = db
76 .query<{ user_id: string }, [string, string, string]>(
77 `UPDATE recovery_link SET used_at = ?2
78 WHERE token_hash = ?1 AND used_at IS NULL AND expires_at > ?3
79 RETURNING user_id`,
80 )
81 .get(sha256(token), new Date(now).toISOString(), new Date(now).toISOString());
82 return row?.user_id;
83 }
src/core/releases.json +5 −1
@@ -3,7 +3,11 @@
33 "releases": [
44 {
55 "version": "0.7.123",
6 "migrations": 93
6 "migrations": 93,
7 "ids": [
8 "20261015090000-feed-chips",
9 "20261015230000-a-domain-drill"
10 ]
711 },
812 {
913 "version": "0.7.122",
src/core/reserved.ts +1
@@ -99,6 +99,7 @@ export const SYSTEM_NAMES: readonly string[] = [
9999 "tell",
100100 "theme",
101101 "verify",
102 "recover",
102103 "www",
103104 "asked",
104105 "claim",
src/core/signup_policy.ts added +8
@@ -0,0 +1,8 @@
1 /**
2 * Whether sign-up may still make an account with only a password (#1618).
3 * It may not: a new account registers a passkey and an email. The flag
4 * exists for the test suite, whose fixtures predate passkeys: under
5 * `bun test` (which sets NODE_ENV=test) it starts lifted, and the files
6 * that test the refusal put it back. Nothing in `src/` ever sets it.
7 */
8 export const signupPolicy = { passwordOnly: process.env["NODE_ENV"] === "test" };
src/core/users.ts +20 −1
@@ -340,7 +340,26 @@ export async function ensureEdgeUser(
340340 return made.value;
341341 }
342342
343 /** Constant-shape verification: always burns an argon2 verify, hit or miss. */
343 /** Whether the account signs in with a password at all (passkey sign-ups have none). */
344 export function hasPassword(db: Database, userId: string): boolean {
345 return (
346 db
347 .query<{ n: number }, [string]>(
348 "SELECT count(*) AS n FROM user WHERE id = ?1 AND password_hash <> ''",
349 )
350 .get(userId)?.n === 1
351 );
352 }
353
354 /**
355 * Constant-shape verification: always burns an argon2 verify, hit or miss.
356 *
357 * Password sign-in stays for the accounts that already have one (#1618: new
358 * accounts are made with a passkey and have none). It can be removed, with
359 * this function and the password section of Settings, once every active
360 * account has a passkey and a verified email to recover by — the Settings
361 * invitation to add a passkey is how they get there.
362 */
344363 export async function verifyPassword(
345364 db: Database,
346365 username: string,
src/http/api.ts +19
@@ -142,7 +142,9 @@ import {
142142 deleteSshKey,
143143 deleteToken,
144144 HUMAN_CHECK_MESSAGE,
145 PASSKEY_REQUIRED_MESSAGE,
145146 signUp,
147 signUpWithPasskey,
146148 updateProfile,
147149 } from "../actions/users.ts";
148150 import { listEvents } from "../core/events.ts";
@@ -334,6 +336,7 @@ import {
334336 type FleetError,
335337 } from "../actions/fleet.ts";
336338 import { sessionCookie } from "../web/pages/site.ts";
339 import { optionsFor, signupRefusal } from "../web/pages/signup-passkey.ts";
337340 import { cookieValue, crossOrigin, type Ctx, type Handler } from "./context.ts";
338341 import {
339342 apiError,
@@ -1125,6 +1128,18 @@ export function apiRoutes(router: Router<Handler>): void {
11251128 const input = await boundedBody(ctx.request, STRANGER_MAX);
11261129 if (input === "too_large")
11271130 return apiError("too_large", 413, `at most ${STRANGER_MAX} bytes`);
1131 // The door a new account comes through is a passkey ceremony; the
1132 // options for it are at POST /api/v1/users/options.
1133 if (typeof input.attestationObject === "string") {
1134 const made = await signUpWithPasskey(
1135 ctx.app,
1136 input,
1137 { origin: ctx.url.origin, rpId: ctx.url.hostname },
1138 { address: clientAddress(ctx.request) },
1139 );
1140 if (!made.ok) return signupRefusal(made.error);
1141 return json(publicUser(made.value), 201);
1142 }
11281143 const created = await signUp(
11291144 ctx.app,
11301145 {
@@ -1137,10 +1152,14 @@ export function apiRoutes(router: Router<Handler>): void {
11371152 );
11381153 if (!created.ok && created.error === "human_check")
11391154 return apiError("human_check", 422, HUMAN_CHECK_MESSAGE);
1155 if (!created.ok && created.error === "passkey_required")
1156 return apiError("passkey_required", 422, PASSKEY_REQUIRED_MESSAGE);
11401157 if (!created.ok) return json({ error: created.error }, 422);
11411158 return json(publicUser(created.value), 201);
11421159 });
11431160
1161 router.add("POST", "/api/v1/users/options", optionsFor);
1162
11441163 router.add("GET", "/api/v1/users/:username", (ctx) => {
11451164 const user = getUserByName(ctx.app.db, ctx.params.username!);
11461165 return user && !hiddenFrom(user, ctx.auth.user)
src/http/server.ts +15
@@ -102,6 +102,14 @@ import {
102102 signinOptions,
103103 signinPasskey,
104104 } from "../web/pages/passkeys.ts";
105 import {
106 recoverAsk,
107 recoverLinkPage,
108 recoverOptions,
109 recoverPage,
110 recoverPasskey,
111 } from "../web/pages/recover.ts";
112 import { signupOptions, signupPasskey } from "../web/pages/signup-passkey.ts";
105113 import { confirmPage, searchPage } from "../web/pages/search.ts";
106114 import { followingSubmit } from "../web/pages/following.ts";
107115 import { reconnectSubmit } from "../web/pages/frozen.ts";
@@ -597,6 +605,13 @@ export function buildRouter(): Router<Handler> {
597605 router.add("GET", "/signup", signupPage);
598606 router.add("GET", "/verify", verifyPage);
599607 router.add("POST", "/signup", signupSubmit);
608 router.add("POST", "/signup/options", signupOptions);
609 router.add("POST", "/signup/passkey", signupPasskey);
610 router.add("GET", "/recover", (ctx) => recoverPage(ctx));
611 router.add("POST", "/recover", recoverAsk);
612 router.add("GET", "/recover/passkey", recoverLinkPage);
613 router.add("POST", "/recover/passkey/options", recoverOptions);
614 router.add("POST", "/recover/passkey", recoverPasskey);
600615 router.add("POST", "/logout", logoutSubmit);
601616 router.add("POST", "/theme", themeSubmit);
602617 // The board: a live wall of the crews at work, for a second monitor.
src/tui/screens/common.ts +1
@@ -815,6 +815,7 @@ export function slug(path: string): string {
815815 const MESSAGES: Record<string, string> = {
816816 not_found: "not found",
817817 human_check: "we could not tell you are a person; sign up on the web page",
818 passkey_required: "new accounts need a passkey; sign up on the web page",
818819 unauthorized: "sign in first",
819820 forbidden: "you do not have permission",
820821 forbidden_owner: "you cannot create repos for that owner",
src/web/pages/passkeys.ts +12 −11
@@ -6,8 +6,8 @@
66 * same-origin checked, and a challenge answers once.
77 */
88
9 import { challenges, verifyAssertion, verifyRegistration } from "../../auth/webauthn.ts";
10 import type { App } from "../../app.ts";
9 import { ceremonies } from "../../auth/ceremonies.ts";
10 import { verifyAssertion, verifyRegistration } from "../../auth/webauthn.ts";
1111 import {
1212 addPasskey,
1313 findPasskey,
@@ -18,7 +18,7 @@ import {
1818 PASSKEY_NAME_MAX,
1919 } from "../../core/passkeys.ts";
2020 import { createSession } from "../../core/sessions.ts";
21 import { getUserById, isActive } from "../../core/users.ts";
21 import { getUserById, hasPassword, isActive } from "../../core/users.ts";
2222 import { crossOrigin, type Ctx } from "../../http/context.ts";
2323 import { clientAddress } from "../../http/peer.ts";
2424 import { STRANGER_MAX } from "../../http/limits.ts";
@@ -32,13 +32,7 @@ import { card, empty, confirmAction, time } from "../ui.ts";
3232 import { accountShell } from "./account.ts";
3333 import { safeNext, sessionCookie, signinAllowed } from "./site.ts";
3434
35 /** One-time challenges, one store per ceremony per forge. */
36 const stores = new WeakMap<App, { add: ReturnType<typeof challenges>; signin: ReturnType<typeof challenges> }>();
37 function store(app: App) {
38 let s = stores.get(app);
39 if (!s) stores.set(app, (s = { add: challenges(), signin: challenges() }));
40 return s;
41 }
35 const store = ceremonies;
4236
4337 /** What the browser must see as the relying party: the forge's public address. */
4438 function relying(ctx: Ctx) {
@@ -60,7 +54,14 @@ function sessionOnly(ctx: Ctx): Response | undefined {
6054 export function passkeysPage(ctx: Ctx): Response {
6155 if (!ctx.auth.user) return signInFirst(ctx);
6256 const keys = listPasskeys(ctx.app.db, ctx.auth.user.id);
63 const body = html`<p class="muted small mb">
57 const invite =
58 keys.length === 0 && hasPassword(ctx.app.db, ctx.auth.user.id)
59 ? html`<p class="notice mb" id="passkey-invite">
60 This account signs in with a password. Add a passkey below: it is
61 harder to phish, and nothing to remember.
62 </p>`
63 : null;
64 const body = html`${invite}<p class="muted small mb">
6465 A passkey signs you in with a fingerprint, face or device PIN instead of
6566 a password. Add one per device; each can be removed on its own.
6667 </p>
src/web/pages/recover.ts added +143
@@ -0,0 +1,143 @@
1 /**
2 * Getting back in (#1618): /recover asks for a verified email and answers the
3 * same whatever it holds; the mailed link opens /recover/passkey, whose button
4 * registers a new passkey and signs the person in. The link is spent by the
5 * registration, not by opening the page, so a mail scanner's preview cannot
6 * burn it.
7 */
8
9 import { recoverWithPasskey, recoveryChallenge, requestRecovery } from "../../actions/recover.ts";
10 import { createSession } from "../../core/sessions.ts";
11 import { crossOrigin, type Ctx } from "../../http/context.ts";
12 import { STRANGER_MAX } from "../../http/limits.ts";
13 import { clientAddress } from "../../http/peer.ts";
14 import { boundedBody, json, str } from "../../http/respond.ts";
15 import { field, readForm } from "../form.ts";
16 import { html } from "../html.ts";
17 import { page } from "../layout.ts";
18 import { passkeyJs } from "../passkey-client.ts";
19 import { btn, card, field as formField } from "../ui.ts";
20 import { pageHead } from "../chrome.ts";
21 import { gate, relying } from "./signup-passkey.ts";
22 import { sessionCookie } from "./site.ts";
23
24 const refuse = (status: number, message: string) =>
25 json({ error: "refused", message }, status);
26
27 // GET /recover
28 export function recoverPage(ctx: Ctx, sent = false): Response {
29 return page({
30 ctx,
31 title: "Get back in",
32 body: html`<div class="narrow">
33 ${pageHead("Get back in")}
34 ${card(
35 sent
36 ? html`<p id="recover-sent">
37 If that address belongs to an account and has been verified, a
38 link to register a new passkey is on its way. It works once, for
39 an hour.
40 </p>`
41 : html`<form method="post" action="/recover">
42 <p class="muted small mb">
43 Lost your passkey? If your email was verified, we will send a
44 link that registers a new one.
45 </p>
46 ${formField({
47 label: "Email",
48 name: "email",
49 type: "email",
50 autocomplete: "email",
51 required: true,
52 autofocus: true,
53 })}
54 <div class="form-actions">${btn("Send the link", { variant: "primary" })}</div>
55 </form>`,
56 )}
57 </div>`,
58 });
59 }
60
61 // POST /recover
62 export async function recoverAsk(ctx: Ctx): Promise<Response> {
63 const form = await readForm(ctx, undefined, STRANGER_MAX);
64 if (form instanceof Response) return form;
65 const limited = gate(ctx, "recover");
66 if (limited) return limited;
67 await requestRecovery(ctx.app, field(form, "email"));
68 return recoverPage(ctx, true);
69 }
70
71 // GET /recover/passkey?token=…
72 export function recoverLinkPage(ctx: Ctx): Response {
73 const token = ctx.url.searchParams.get("token") ?? "";
74 const live = recoveryChallenge(ctx.app, token).ok;
75 return page(
76 {
77 ctx,
78 title: "Register a new passkey",
79 body: html`<div class="narrow">
80 ${pageHead(live ? "Register a new passkey" : "This link is not valid")}
81 ${live
82 ? card(html`<p class="muted small mb">
83 Your passkey signs you in with a fingerprint, face or device PIN.
84 This link works once.
85 </p>
86 <p class="error-note" id="passkey-recover-note" role="status"></p>
87 <noscript><p class="muted small">This needs JavaScript.</p></noscript>
88 <div class="form-actions">
89 <button type="button" id="passkey-recover" class="btn" data-variant="primary" data-token="${token}">Register a passkey</button>
90 </div>`)
91 : html`<p>It has been used, or it has expired. <a href="/recover">Ask for another</a>.</p>`}
92 </div>`,
93 ...(live ? { scriptJs: passkeyJs } : {}),
94 },
95 live ? 200 : 400,
96 );
97 }
98
99 // POST /recover/passkey/options — a challenge, while the link is good.
100 export async function recoverOptions(ctx: Ctx): Promise<Response> {
101 if (crossOrigin(ctx.request, ctx.url, ctx.app.log)) return refuse(403, "forbidden");
102 const limited = gate(ctx, "recover");
103 if (limited) return limited;
104 const data = await boundedBody(ctx.request, STRANGER_MAX);
105 if (data === "too_large") return refuse(413, "payload too large");
106 const challenge = recoveryChallenge(ctx.app, str(data.token));
107 if (!challenge.ok) return refuse(400, "This link has been used or has expired.");
108 return json({
109 challenge: challenge.value,
110 rpId: relying(ctx).rpId,
111 rpName: "forge",
112 user: {
113 id: Buffer.from(crypto.getRandomValues(new Uint8Array(16))).toString("base64url"),
114 name: "recovered",
115 displayName: "recovered",
116 },
117 exclude: [],
118 });
119 }
120
121 // POST /recover/passkey — spend the link, keep the passkey, sign in.
122 export async function recoverPasskey(ctx: Ctx): Promise<Response> {
123 if (crossOrigin(ctx.request, ctx.url, ctx.app.log)) return refuse(403, "forbidden");
124 const limited = gate(ctx, "recover");
125 if (limited) return limited;
126 const data = await boundedBody(ctx.request, STRANGER_MAX);
127 if (data === "too_large") return refuse(413, "payload too large");
128 const done = await recoverWithPasskey(ctx.app, data, relying(ctx));
129 if (!done.ok) {
130 const messages = {
131 invalid: "This link has been used or has expired.",
132 challenge: "That request expired. Try again.",
133 passkey_rejected: "That passkey was not accepted.",
134 too_many: "That is as many passkeys as an account keeps.",
135 duplicate: "That passkey is already registered.",
136 } as const;
137 return refuse(400, messages[done.error]);
138 }
139 const session = createSession(ctx.app.db, done.value.id);
140 return json({ ok: true, next: "/settings/passkeys" }, 200, {
141 "set-cookie": sessionCookie(session.token, session.expiresAt, ctx.url, ctx.app.config.url),
142 });
143 }
src/web/pages/signup-passkey.ts added +104
@@ -0,0 +1,104 @@
1 /**
2 * Sign-up with a passkey (#1618): the two JSON halves the sign-up page's
3 * button calls. `options` checks the name and the address before the person
4 * is asked to touch anything and issues the challenge; the second verifies
5 * the browser's answer, makes the account with that passkey and no
6 * password, and signs it in. A stranger's requests: same-origin, bounded,
7 * rate limited.
8 */
9
10 import { ceremonies } from "../../auth/ceremonies.ts";
11 import {
12 HUMAN_CHECK_MESSAGE,
13 plausibleEmail,
14 signUpWithPasskey,
15 type SignUpError,
16 } from "../../actions/users.ts";
17 import { createSession } from "../../core/sessions.ts";
18 import { hasAnyUser } from "../../core/users.ts";
19 import { isSafeName } from "../../git/guard.ts";
20 import { crossOrigin, type Ctx } from "../../http/context.ts";
21 import { STRANGER_MAX } from "../../http/limits.ts";
22 import { clientAddress } from "../../http/peer.ts";
23 import { boundedBody, json, str } from "../../http/respond.ts";
24 import { safeNext, sessionCookie, signinAllowed } from "./site.ts";
25
26 const refuse = (status: number, error: string, message: string, headers: Record<string, string> = {}) =>
27 json({ error, message }, status, headers);
28
29 /** The words a refusal carries, here and on the API. */
30 export const SIGNUP_MESSAGES: Record<string, string> = {
31 invalid_username: "Usernames are letters, digits, dots, dashes.",
32 username_taken: "That username is taken.",
33 username_reserved: "That name is reserved.",
34 email_taken: "That email already has an account.",
35 invalid_email: "That does not look like an email address.",
36 human_check: HUMAN_CHECK_MESSAGE,
37 challenge: "That request expired. Try again.",
38 passkey_rejected: "That passkey was not accepted.",
39 passkey_taken: "That passkey is already registered.",
40 passkey_required: "Sign-up registers a passkey and an email address.",
41 };
42
43 export const relying = (ctx: Ctx) => ({ origin: ctx.url.origin, rpId: ctx.url.hostname });
44
45 /** Rate limit and shape check shared by the browser and API doors. */
46 export function gate(ctx: Ctx, door: "signup" | "recover" = "signup"): Response | undefined {
47 const wait = signinAllowed(ctx, `${door}:${clientAddress(ctx.request)}`);
48 if (wait === undefined) return undefined;
49 return refuse(429, "rate_limited", `Too many attempts. Try again in ${wait}s.`, { "retry-after": String(wait) });
50 }
51
52 /** POST /signup/options — a challenge, once the name and address look right. */
53 export async function signupOptions(ctx: Ctx): Promise<Response> {
54 if (crossOrigin(ctx.request, ctx.url, ctx.app.log)) return refuse(403, "forbidden", "forbidden");
55 return optionsFor(ctx);
56 }
57
58 export async function optionsFor(ctx: Ctx): Promise<Response> {
59 const limited = gate(ctx);
60 if (limited) return limited;
61 const data = await boundedBody(ctx.request, STRANGER_MAX);
62 if (data === "too_large") return refuse(413, "too_large", "payload too large");
63 const username = str(data.username);
64 const email = str(data.email).trim();
65 if (!isSafeName(username)) return refuse(422, "invalid_username", SIGNUP_MESSAGES["invalid_username"]!);
66 if (!plausibleEmail(email)) return refuse(422, "invalid_email", SIGNUP_MESSAGES["invalid_email"]!);
67 return json({
68 challenge: ceremonies(ctx.app).signup.issue(),
69 rpId: relying(ctx).rpId,
70 rpName: "forge",
71 user: {
72 id: Buffer.from(crypto.getRandomValues(new Uint8Array(16))).toString("base64url"),
73 name: username,
74 displayName: username,
75 },
76 exclude: [],
77 first: !hasAnyUser(ctx.app.db),
78 });
79 }
80
81 /** What a failed sign-up answers, with the status it deserves. */
82 export function signupRefusal(error: SignUpError): Response {
83 const status = error === "challenge" || error === "passkey_rejected" ? 400 : 422;
84 return refuse(status, error, SIGNUP_MESSAGES[error] ?? "Something went wrong.");
85 }
86
87 // POST /signup/passkey — the account, and the session it signs in with.
88 export async function signupPasskey(ctx: Ctx): Promise<Response> {
89 if (crossOrigin(ctx.request, ctx.url, ctx.app.log)) return refuse(403, "forbidden", "forbidden");
90 const limited = gate(ctx);
91 if (limited) return limited;
92 const data = await boundedBody(ctx.request, STRANGER_MAX);
93 if (data === "too_large") return refuse(413, "too_large", "payload too large");
94 const created = await signUpWithPasskey(ctx.app, data, relying(ctx), {
95 address: clientAddress(ctx.request),
96 });
97 if (!created.ok) return signupRefusal(created.error);
98 const session = createSession(ctx.app.db, created.value.id);
99 return json(
100 { ok: true, next: safeNext(ctx.url.searchParams.get("next")) ?? "/" },
101 200,
102 { "set-cookie": sessionCookie(session.token, session.expiresAt, ctx.url, ctx.app.config.url) },
103 );
104 }
src/web/pages/site.ts +34 −16
@@ -15,7 +15,7 @@ import { clientAddress } from "../../http/peer.ts";
1515 import { verifyEmail } from "../../actions/verify.ts";
1616 import { STRANGER_MAX } from "../../http/limits.ts";
1717 import { createRepo } from "../../actions/repos.ts";
18 import { HUMAN_CHECK_MESSAGE, signUp } from "../../actions/users.ts";
18 import { HUMAN_CHECK_MESSAGE, PASSKEY_REQUIRED_MESSAGE, signUp } from "../../actions/users.ts";
1919 import { listAssignedTo, type Issue } from "../../core/issues.ts";
2020 import { joinMany } from "../../core/pulls.ts";
2121 import { conflictsOf } from "../../crew/stale_asks.ts";
@@ -407,17 +407,18 @@ function authForm(
407407 ...(errors.email ? { error: errors.email } : {}),
408408 }),
409409 )}
410 ${formField({
411 label: "Password",
412 name: "password",
413 type: "password",
414 autocomplete: kind === "signin" ? "current-password" : "new-password",
415 required: true,
416 ...(kind === "signup"
417 ? { minlength: 10, hint: "At least 10 characters." }
418 : {}),
419 ...(errors.password ? { error: errors.password } : {}),
420 })}
410 ${when(
411 kind === "signin",
412 () =>
413 formField({
414 label: "Password",
415 name: "password",
416 type: "password",
417 autocomplete: "current-password",
418 required: true,
419 ...(errors.password ? { error: errors.password } : {}),
420 }),
421 )}
421422 ${when(
422423 kind === "signup" ? siteKey(ctx) : undefined,
423424 (key) =>
@@ -435,10 +436,20 @@ function authForm(
435436 admin.
436437 </p>`,
437438 )}
439 ${when(
440 kind === "signup",
441 () => html`<p class="muted small mb">
442 You sign in with a passkey: a fingerprint, face or device PIN. We
443 keep your email to send the link that gets you back in if you lose
444 your device.
445 </p>
446 <p class="error-note" id="passkey-signup-note" role="status">${errors.password ?? ""}</p>
447 <noscript><p class="muted small">Creating an account needs JavaScript.</p></noscript>`,
448 )}
438449 <div class="form-actions">
439 ${btn(kind === "signin" ? "Sign in" : "Create account", {
440 variant: "primary",
441 })}
450 ${kind === "signin"
451 ? btn("Sign in", { variant: "primary" })
452 : html`<button type="button" id="passkey-signup" class="btn" data-variant="primary">Create account with a passkey</button>`}
442453 <span class="spacer"></span>
443454 ${kind === "signin"
444455 ? btn("Need an account? Sign up", {
@@ -466,6 +477,9 @@ function authForm(
466477 () => html`<p class="mt">
467478 <button type="button" id="passkey-signin" class="btn" data-variant="outline">Sign in with a passkey</button>
468479 <span class="error-note small" id="passkey-signin-note" role="status"></span>
480 </p>
481 <p class="muted small mt">
482 Lost your passkey? <a href="/recover">Get a link by email</a>.
469483 </p>`,
470484 )}
471485 ${claimable
@@ -496,6 +510,7 @@ export function signupPage(ctx: Ctx): Response {
496510 ctx,
497511 title: "Sign up",
498512 body: authForm(ctx, "signup"),
513 scriptJs: passkeyJs,
499514 turnstile: siteKey(ctx) !== undefined,
500515 });
501516 }
@@ -627,13 +642,16 @@ export async function signupSubmit(ctx: Ctx): Promise<Response> {
627642 username_reserved: { username: "That name is reserved." },
628643 email_taken: { email: "That email already has an account." },
629644 weak_password: { password: "Passwords need at least 10 characters." },
645 passkey_required: { password: PASSKEY_REQUIRED_MESSAGE },
646 invalid_email: { email: "That does not look like an email address." },
630647 human_check: { human: HUMAN_CHECK_MESSAGE },
631 }[created.error] ?? { username: "Something went wrong." };
648 }[created.error as string] ?? { username: "Something went wrong." };
632649 return page(
633650 {
634651 ctx,
635652 title: "Sign up",
636653 body: authForm(ctx, "signup", { values: { username, email }, errors }),
654 scriptJs: passkeyJs,
637655 turnstile: siteKey(ctx) !== undefined,
638656 },
639657 422,
src/web/passkey-client.ts +45
@@ -72,6 +72,51 @@ export const passkeyJs = /* js */ `
7272 });
7373 }).then(function () { location.reload(); });
7474 });
75 function create(o) {
76 return navigator.credentials.create({ publicKey: {
77 challenge: bytes(o.challenge),
78 rp: { id: o.rpId, name: o.rpName },
79 user: { id: bytes(o.user.id), name: o.user.name, displayName: o.user.displayName },
80 pubKeyCredParams: [{ type: 'public-key', alg: -7 }, { type: 'public-key', alg: -257 }],
81 excludeCredentials: o.exclude.map(function (c) { return { type: 'public-key', id: bytes(c) }; }),
82 authenticatorSelection: { residentKey: 'preferred', userVerification: 'required' },
83 attestation: 'none',
84 timeout: 120000
85 } });
86 }
87 wire('passkey-signup', function () {
88 var form = doc.getElementById('passkey-signup').form;
89 var who = {
90 username: form.elements.username.value,
91 email: form.elements.email.value
92 };
93 var human = form.querySelector('input[name$="turnstile-response"]');
94 return post('/signup/options', who).then(function (o) {
95 return create(o).then(function (cred) {
96 return post('/signup/passkey' + location.search, {
97 username: who.username,
98 email: who.email,
99 turnstile_token: human ? human.value : '',
100 challenge: o.challenge,
101 clientDataJSON: text(cred.response.clientDataJSON),
102 attestationObject: text(cred.response.attestationObject)
103 });
104 });
105 }).then(function (r) { location.href = r.next; });
106 });
107 wire('passkey-recover', function () {
108 var token = doc.getElementById('passkey-recover').getAttribute('data-token');
109 return post('/recover/passkey/options', { token: token }).then(function (o) {
110 return create(o).then(function (cred) {
111 return post('/recover/passkey', {
112 token: token,
113 challenge: o.challenge,
114 clientDataJSON: text(cred.response.clientDataJSON),
115 attestationObject: text(cred.response.attestationObject)
116 });
117 });
118 }).then(function (r) { location.href = r.next; });
119 });
75120 wire('passkey-signin', function () {
76121 return post('/signin/passkey/options').then(function (o) {
77122 return navigator.credentials.get({ publicKey: {
test/helpers/authenticator.ts added +47
@@ -0,0 +1,47 @@
1 /** A software authenticator that signs as a browser's would: shared by the passkey suites. */
2 import { b64u } from "../../src/auth/webauthn.ts";
3
4 const te = new TextEncoder();
5 const sha = async (d: Uint8Array<ArrayBuffer>) => new Uint8Array(await crypto.subtle.digest("SHA-256", d));
6 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; };
7 function head(major: number, n: number): Uint8Array {
8 if (n < 24) return Uint8Array.of((major << 5) | n);
9 if (n < 256) return Uint8Array.of((major << 5) | 24, n);
10 return Uint8Array.of((major << 5) | 25, n >> 8, n & 255);
11 }
12 type V = number | string | Uint8Array | [V, V][];
13 function enc(v: V): Uint8Array {
14 if (typeof v === "number") return v >= 0 ? head(0, v) : head(1, -1 - v);
15 if (typeof v === "string") { const b = te.encode(v); return cat(head(3, b.length), b); }
16 if (v instanceof Uint8Array) return cat(head(2, v.length), v);
17 return cat(head(5, v.length), ...v.flatMap(([k, x]) => [enc(k), enc(x)]));
18 }
19 function rawToDer(raw: Uint8Array): Uint8Array<ArrayBuffer> {
20 const int = (b: Uint8Array) => { let i = 0; while (i < b.length - 1 && b[i] === 0) i++; b = b.subarray(i); if (b[0]! & 0x80) b = cat(Uint8Array.of(0), b); return cat(Uint8Array.of(2, b.length), b); };
21 const body = cat(int(raw.subarray(0, 32)), int(raw.subarray(32)));
22 return cat(Uint8Array.of(0x30, body.length), body);
23 }
24
25 export async function device(origin: string, rp: string) {
26 const pair = (await crypto.subtle.generateKey({ name: "ECDSA", namedCurve: "P-256" }, true, ["sign"])) as CryptoKeyPair;
27 const jwk = await crypto.subtle.exportKey("jwk", pair.publicKey);
28 const unb = (s: string) => new Uint8Array(Buffer.from(s, "base64url"));
29 const cose: [number, V][] = [[1, 2], [3, -7], [-1, 1], [-2, unb(jwk.x!)], [-3, unb(jwk.y!)]];
30 const id = crypto.getRandomValues(new Uint8Array(32));
31 let count = 0;
32 const cd = (type: string, challenge: string) => te.encode(JSON.stringify({ type, challenge, origin }));
33 const counter = (n: number) => Uint8Array.of(n >>> 24, (n >>> 16) & 255, (n >>> 8) & 255, n & 255);
34 return {
35 credId: b64u(id),
36 async create(challenge: string) {
37 const authData = cat(await sha(te.encode(rp)), Uint8Array.of(0x45), counter(0), new Uint8Array(16), Uint8Array.of(0, id.length), id, enc(cose as V));
38 return { clientDataJSON: b64u(cd("webauthn.create", challenge)), attestationObject: b64u(enc([["fmt", "none"], ["attStmt", []], ["authData", authData]])) };
39 },
40 async get(challenge: string) {
41 const clientData = cd("webauthn.get", challenge);
42 const authData = cat(await sha(te.encode(rp)), Uint8Array.of(0x05), counter(++count));
43 const sig = rawToDer(new Uint8Array(await crypto.subtle.sign({ name: "ECDSA", hash: "SHA-256" }, pair.privateKey, cat(authData, await sha(clientData)))));
44 return { id: b64u(id), clientDataJSON: b64u(clientData), authenticatorData: b64u(authData), signature: b64u(sig) };
45 },
46 };
47 }
test/passkeys.test.ts +1 −45
@@ -9,55 +9,11 @@ import { tmpdir } from "node:os";
99 import { join } from "node:path";
1010 import { createApp, type App } from "../src/app.ts";
1111 import { b64u } from "../src/auth/webauthn.ts";
12 import { device } from "./helpers/authenticator.ts";
1213 import { createToken } from "../src/core/tokens.ts";
1314 import { serve, type Servers } from "../src/http/server.ts";
1415 import { setLimit } from "../src/settings/limits.ts";
1516
16 const te = new TextEncoder();
17 const sha = async (d: Uint8Array<ArrayBuffer>) => new Uint8Array(await crypto.subtle.digest("SHA-256", d));
18 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; };
19 function head(major: number, n: number): Uint8Array {
20 if (n < 24) return Uint8Array.of((major << 5) | n);
21 if (n < 256) return Uint8Array.of((major << 5) | 24, n);
22 return Uint8Array.of((major << 5) | 25, n >> 8, n & 255);
23 }
24 type V = number | string | Uint8Array | [V, V][];
25 function enc(v: V): Uint8Array {
26 if (typeof v === "number") return v >= 0 ? head(0, v) : head(1, -1 - v);
27 if (typeof v === "string") { const b = te.encode(v); return cat(head(3, b.length), b); }
28 if (v instanceof Uint8Array) return cat(head(2, v.length), v);
29 return cat(head(5, v.length), ...v.flatMap(([k, x]) => [enc(k), enc(x)]));
30 }
31 function rawToDer(raw: Uint8Array): Uint8Array<ArrayBuffer> {
32 const int = (b: Uint8Array) => { let i = 0; while (i < b.length - 1 && b[i] === 0) i++; b = b.subarray(i); if (b[0]! & 0x80) b = cat(Uint8Array.of(0), b); return cat(Uint8Array.of(2, b.length), b); };
33 const body = cat(int(raw.subarray(0, 32)), int(raw.subarray(32)));
34 return cat(Uint8Array.of(0x30, body.length), body);
35 }
36
37 async function device(origin: string, rp: string) {
38 const pair = (await crypto.subtle.generateKey({ name: "ECDSA", namedCurve: "P-256" }, true, ["sign"])) as CryptoKeyPair;
39 const jwk = await crypto.subtle.exportKey("jwk", pair.publicKey);
40 const unb = (s: string) => new Uint8Array(Buffer.from(s, "base64url"));
41 const cose: [number, V][] = [[1, 2], [3, -7], [-1, 1], [-2, unb(jwk.x!)], [-3, unb(jwk.y!)]];
42 const id = crypto.getRandomValues(new Uint8Array(32));
43 let count = 0;
44 const cd = (type: string, challenge: string) => te.encode(JSON.stringify({ type, challenge, origin }));
45 const counter = (n: number) => Uint8Array.of(n >>> 24, (n >>> 16) & 255, (n >>> 8) & 255, n & 255);
46 return {
47 credId: b64u(id),
48 async create(challenge: string) {
49 const authData = cat(await sha(te.encode(rp)), Uint8Array.of(0x45), counter(0), new Uint8Array(16), Uint8Array.of(0, id.length), id, enc(cose as V));
50 return { clientDataJSON: b64u(cd("webauthn.create", challenge)), attestationObject: b64u(enc([["fmt", "none"], ["attStmt", []], ["authData", authData]])) };
51 },
52 async get(challenge: string) {
53 const clientData = cd("webauthn.get", challenge);
54 const authData = cat(await sha(te.encode(rp)), Uint8Array.of(0x05), counter(++count));
55 const sig = rawToDer(new Uint8Array(await crypto.subtle.sign({ name: "ECDSA", hash: "SHA-256" }, pair.privateKey, cat(authData, await sha(clientData)))));
56 return { id: b64u(id), clientDataJSON: b64u(clientData), authenticatorData: b64u(authData), signature: b64u(sig) };
57 },
58 };
59 }
60
6117 describe("passkeys", () => {
6218 let dataDir: string;
6319 let app: App;
test/signup-passkey.test.ts added +276
@@ -0,0 +1,276 @@
1 /**
2 * Sign-up takes a passkey and an email, never a password alone (#1618); a
3 * verified email recovers with a single-use, time-limited link; an account
4 * that has a password is invited to add a passkey.
5 */
6 import { afterAll, beforeAll, describe, expect, test } from "bun:test";
7 import { mkdtemp, rm } from "node:fs/promises";
8 import { tmpdir } from "node:os";
9 import { join } from "node:path";
10 import { signUp } from "../src/actions/users.ts";
11 import { createApp, type App } from "../src/app.ts";
12 import { listPasskeys } from "../src/core/passkeys.ts";
13 import { RECOVERY_TTL_MS, issueRecovery } from "../src/core/recovery.ts";
14 import { createSession } from "../src/core/sessions.ts";
15 import { signupPolicy } from "../src/core/signup_policy.ts";
16 import { createUser, getUserByName, hasPassword, verifyPassword } from "../src/core/users.ts";
17 import { setLimit } from "../src/settings/limits.ts";
18 import { serve, type Servers } from "../src/http/server.ts";
19 import type { Mail } from "../src/kernel/mail.ts";
20 import { device } from "./helpers/authenticator.ts";
21
22 describe("sign-up with a passkey, and recovery", () => {
23 let dataDir: string;
24 let app: App;
25 let servers: Servers;
26 let base: string;
27 const mails: Mail[] = [];
28 let was: boolean;
29
30 const post = (path: string, body: unknown, headers: Record<string, string> = {}) =>
31 fetch(`${base}${path}`, {
32 method: "POST",
33 headers: { "content-type": "application/json", ...headers },
34 body: JSON.stringify(body),
35 redirect: "manual",
36 });
37 const rp = () => ({ origin: "https://forge.example", host: "forge.example" });
38
39 /** The whole ceremony, as the sign-up page's script runs it. */
40 async function signUpWith(username: string, email: string, path = "/signup", d?: Awaited<ReturnType<typeof device>>) {
41 const dev = d ?? (await device(rp().origin, rp().host));
42 const opened = await post(`${path}/options`, { username, email });
43 if (opened.status !== 200) return { opened, dev };
44 const o = (await opened.json()) as any;
45 const done = await post(path === "/signup" ? "/signup/passkey" : path, {
46 username,
47 email,
48 challenge: o.challenge,
49 ...(await dev.create(o.challenge)),
50 });
51 return { opened, done, dev, o };
52 }
53
54 beforeAll(async () => {
55 was = signupPolicy.passwordOnly;
56 signupPolicy.passwordOnly = false;
57 dataDir = await mkdtemp(join(tmpdir(), "forge-signup-passkey-"));
58 app = createApp({
59 dataDir,
60 port: 0,
61 url: "https://forge.example",
62 mailer: async (mail) => {
63 mails.push(mail);
64 return true;
65 },
66 });
67 servers = await serve(app);
68 base = servers.url;
69 // The suite signs up and recovers far faster than a person; the limit has its own test.
70 setLimit(app.db, "signin.per_account", 1000, "test");
71 setLimit(app.db, "signin.per_forge", 100_000, "test");
72 });
73
74 afterAll(async () => {
75 signupPolicy.passwordOnly = was;
76 servers.stop();
77 app.close();
78 await rm(dataDir, { recursive: true, force: true });
79 });
80
81 test("no path makes an account with only a password", async () => {
82 const action = await signUp(app, { username: "nopass", email: "[email protected]", password: "long-enough-password" });
83 expect(action).toEqual({ ok: false, error: "passkey_required" });
84
85 const form = await fetch(`${base}/signup`, {
86 method: "POST",
87 body: new URLSearchParams({ username: "nopass", email: "[email protected]", password: "long-enough-password" }),
88 redirect: "manual",
89 });
90 expect(form.status).toBe(422);
91 expect(form.headers.get("set-cookie")).toBeNull();
92 expect(await form.text()).toContain("registers a passkey");
93
94 const api = await post("/api/v1/users", { username: "nopass", email: "[email protected]", password: "long-enough-password" });
95 expect(api.status).toBe(422);
96 expect(((await api.json()) as any).error).toBe("passkey_required");
97 expect(getUserByName(app.db, "nopass")).toBeUndefined();
98 });
99
100 test("a passkey and an email make an account with no password, signed in", async () => {
101 const { opened, done, dev } = await signUpWith("olive", "[email protected]");
102 expect(opened.status).toBe(200);
103 expect(done!.status).toBe(200);
104 const cookie = (done!.headers.get("set-cookie") ?? "").split(";")[0]!;
105 expect(cookie).toStartWith("forge_session=");
106 expect(done!.headers.get("set-cookie")).toContain("HttpOnly");
107
108 const user = getUserByName(app.db, "olive")!;
109 expect(user.email).toBe("[email protected]");
110 expect(user.isAdmin).toBe(true); // the first account is still the admin
111 expect(hasPassword(app.db, user.id)).toBe(false);
112 expect((await verifyPassword(app.db, "olive", "")).ok).toBe(false);
113 expect(listPasskeys(app.db, user.id)).toHaveLength(1);
114
115 // The passkey signs the same account in again.
116 const o = (await (await post("/signin/passkey/options", {})).json()) as any;
117 const again = await post("/signin/passkey", { challenge: o.challenge, ...(await dev.get(o.challenge)) });
118 expect(again.status).toBe(200);
119 });
120
121 test("the address is checked before anything is asked of the device", async () => {
122 const bad = await post("/signup/options", { username: "pat", email: "not-an-email" });
123 expect(bad.status).toBe(422);
124 expect(((await bad.json()) as any).error).toBe("invalid_email");
125 const name = await post("/signup/options", { username: "../x", email: "[email protected]" });
126 expect(name.status).toBe(422);
127 const missing = await post("/signup/options", { username: "pat" });
128 expect(missing.status).toBe(422);
129 });
130
131 test("a challenge answers once; a taken name or address or device is refused", async () => {
132 const dev = await device(rp().origin, rp().host);
133 const o = (await (await post("/signup/options", { username: "pat", email: "[email protected]" })).json()) as any;
134 const answer = { username: "pat", email: "[email protected]", challenge: o.challenge, ...(await dev.create(o.challenge)) };
135 expect((await post("/signup/passkey", { ...answer, username: "olive" })).status).toBe(422); // name taken, challenge spent
136 expect((await post("/signup/passkey", answer)).status).toBe(400); // replay of the spent challenge
137 expect(getUserByName(app.db, "pat")).toBeUndefined();
138
139 const taken = await signUpWith("pat", "[email protected]");
140 expect(((await taken.done!.json()) as any).error).toBe("email_taken");
141 const unknown = await post("/signup/passkey", { username: "pat", email: "[email protected]", challenge: "nope", clientDataJSON: "", attestationObject: "" });
142 expect(unknown.status).toBe(400);
143 });
144
145 test("sign-up attempts are rate limited per address", async () => {
146 setLimit(app.db, "signin.per_account", 2, "test");
147 let last = await post("/signup/options", { username: "rl", email: "[email protected]" });
148 for (let i = 0; i < 3 && last.status === 200; i++)
149 last = await post("/signup/options", { username: "rl", email: "[email protected]" });
150 expect(last.status).toBe(429);
151 expect(Number(last.headers.get("retry-after"))).toBeGreaterThan(0);
152 setLimit(app.db, "signin.per_account", 1000, "test");
153 });
154
155 test("sign-up is a same-origin request", async () => {
156 const res = await post("/signup/options", { username: "eve", email: "[email protected]" }, { origin: "https://evil.example" });
157 expect(res.status).toBe(403);
158 });
159
160 test("the API takes the same ceremony", async () => {
161 const dev = await device(rp().origin, rp().host);
162 const o = (await (await post("/api/v1/users/options", { username: "api-ann", email: "[email protected]" })).json()) as any;
163 const made = await post("/api/v1/users", {
164 username: "api-ann",
165 email: "[email protected]",
166 challenge: o.challenge,
167 ...(await dev.create(o.challenge)),
168 });
169 expect(made.status).toBe(201);
170 expect(listPasskeys(app.db, getUserByName(app.db, "api-ann")!.id)).toHaveLength(1);
171 });
172
173 test("the sign-up page asks for a passkey, not a password", async () => {
174 const page = await (await fetch(`${base}/signup`)).text();
175 expect(page).toContain('id="passkey-signup"');
176 expect(page).not.toContain('name="password"');
177 });
178
179 describe("recovery", () => {
180 const linkIn = (mail: Mail) => /https:\/\/forge\.example(\/\S+)/.exec(mail.text)![1]!;
181 const asked = (email: string) =>
182 fetch(`${base}/recover`, { method: "POST", body: new URLSearchParams({ email }), redirect: "manual" });
183
184 test("an unknown or unproven address is told the same and mailed nothing", async () => {
185 await signUpWith("quinn", "[email protected]"); // unproven: not the first account
186 const before = mails.length;
187 const unknown = await (await asked("[email protected]")).text();
188 const unproven = await (await asked("[email protected]")).text();
189 expect(unknown).toContain("on its way");
190 expect(unproven).toContain("on its way");
191 expect(mails.length).toBe(before);
192 });
193
194 test("a verified email is mailed a link that registers a new passkey, once", async () => {
195 const before = mails.length;
196 expect(await (await asked("[email protected]")).text()).toContain("on its way");
197 expect(mails.length).toBe(before + 1);
198 const mail = mails.at(-1)!;
199 expect(mail.to).toBe("[email protected]");
200 const link = linkIn(mail);
201 const token = new URL(link, base).searchParams.get("token")!;
202
203 // Asking again inside the window sends nothing more.
204 await asked("[email protected]");
205 expect(mails.length).toBe(before + 1);
206
207 // Opening the page does not spend it (a mail scanner may open it).
208 expect((await fetch(`${base}${link}`)).status).toBe(200);
209 expect((await fetch(`${base}${link}`)).status).toBe(200);
210
211 const dev = await device(rp().origin, rp().host);
212 const o = (await (await post("/recover/passkey/options", { token })).json()) as any;
213 const done = await post("/recover/passkey", { token, challenge: o.challenge, ...(await dev.create(o.challenge)) });
214 expect(done.status).toBe(200);
215 expect(done.headers.get("set-cookie")).toContain("forge_session=");
216 const olive = getUserByName(app.db, "olive")!;
217 expect(listPasskeys(app.db, olive.id)).toHaveLength(2);
218
219 // The new passkey signs in.
220 const s = (await (await post("/signin/passkey/options", {})).json()) as any;
221 expect((await post("/signin/passkey", { challenge: s.challenge, ...(await dev.get(s.challenge)) })).status).toBe(200);
222
223 // Reused: the page, the options and the registration all refuse.
224 expect((await fetch(`${base}${link}`)).status).toBe(400);
225 expect((await post("/recover/passkey/options", { token })).status).toBe(400);
226 const other = await device(rp().origin, rp().host);
227 const o2 = (await (await post("/signin/passkey/options", {})).json()) as any;
228 const replay = await post("/recover/passkey", { token, challenge: o2.challenge, ...(await other.create(o2.challenge)) });
229 expect(replay.status).toBe(400);
230 expect(listPasskeys(app.db, olive.id)).toHaveLength(2);
231 });
232
233 test("an expired link is refused, on the page, the options and the registration", async () => {
234 const olive = getUserByName(app.db, "olive")!;
235 const old = Date.now() - RECOVERY_TTL_MS - 60_000;
236 const token = issueRecovery(app.db, olive.id, old)!;
237 expect((await fetch(`${base}/recover/passkey?token=${token}`)).status).toBe(400);
238 expect((await post("/recover/passkey/options", { token })).status).toBe(400);
239 const dev = await device(rp().origin, rp().host);
240 const attempt = await post("/recover/passkey", { token, challenge: "x", ...(await dev.create("x")) });
241 expect(attempt.status).toBe(400);
242 expect(listPasskeys(app.db, olive.id)).toHaveLength(2);
243 });
244
245 test("a made-up token is refused, and recovery is same-origin", async () => {
246 expect((await post("/recover/passkey/options", { token: "made-up" })).status).toBe(400);
247 expect((await post("/recover/passkey/options", { token: "x" }, { origin: "https://evil.example" })).status).toBe(403);
248 });
249
250 test("an address verified by its mailed link can then recover", async () => {
251 const quinn = getUserByName(app.db, "quinn")!;
252 const verify = mails.find((m) => m.to === "[email protected]" && m.text.includes("/verify"))!;
253 expect(verify).toBeDefined();
254 const res = await fetch(`${base}${/https:\/\/forge\.example(\/verify\S+)/.exec(verify.text)![1]}`);
255 expect(res.status).toBe(200);
256 const before = mails.length;
257 await asked("[email protected]");
258 expect(mails.length).toBe(before + 1);
259 expect(quinn.id).toBeTruthy();
260 });
261 });
262
263 test("Settings invites a password account to add a passkey, and only that one", async () => {
264 const made = await createUser(app.db, { username: "pw", email: "[email protected]", password: "long-enough-password" });
265 if (!made.ok) throw new Error(made.error);
266 const session = createSession(app.db, made.value.id);
267 const get = async () =>
268 (await fetch(`${base}/settings/passkeys`, { headers: { cookie: `forge_session=${session.token}` } })).text();
269 expect(await get()).toContain('id="passkey-invite"');
270
271 const olive = getUserByName(app.db, "olive")!;
272 const oliveSession = createSession(app.db, olive.id);
273 const page = await (await fetch(`${base}/settings/passkeys`, { headers: { cookie: `forge_session=${oliveSession.token}` } })).text();
274 expect(page).not.toContain('id="passkey-invite"');
275 });
276 });

↑↓ navigate ↵ open ⌘↵ its app esc close

Keyboard shortcuts

Docs