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

The signup and sign-in page: passkey first, one way in, linked methods offered as "link" #2859

Parked opened this in answer to
Closed without merging

scout/forge:scout/669-the-signup-and-sign-in-page-passkey-firs → main 4 commits fork 9 threads · 9 unresolved

  • Closed without merging. Nothing was applied to main.

Review

Sign in to review this change.
12 files changed +386 −265
README.md +9 −4
@@ -298,18 +298,23 @@ The relying party is the address the browser used (or
298298 Sign-up is a username, an email address and a passkey (`/signup`, `src/web/pages/signup-passkey.ts`); the running server refuses a password-only sign-up on the form, `POST /api/v1/users` and the terminal (`passkeyOnlySignup`, set in `main.ts`). Accounts that already have a password still sign in. The owner claim of a spawned forge (`/claim`, `web/pages/claim.ts`) and an admin's everyday account (`web/pages/everyday.ts`) make their account with a passkey too (`web/passkey-ceremony.ts`, challenges from `POST /claim/options` and `POST /settings/everyday/options`); neither reads a password, and without JavaScript the page says a passkey needs it. A claim post with no passkey is refused and does not spend the link.
299299
300300 A forge with a parent (`FORGE_PARENT_URL`, or the `upstream` in a spawned
301 forge's `parent.json`) offers "Continue with <parent>" on `/signin`. The forge
301 forge's `parent.json`) offers "Link an account from <parent>" on `/signin`, under "Link an account you have" (after the passkey and the form; `/signin` also says in one sentence when `signup` is `invite` or `closed`). The forge
302302 registers itself once at the parent's `/oauth/register` (the client id is kept
303303 in `rp_client`), sends the person through the parent's authorize page with
304304 PKCE, and on return checks state (also bound to the browser by an HttpOnly
305305 cookie), nonce, `iss`, `aud`, `exp` and the ES256 signature against the
306306 parent's JWKS (`kernel/jwt.ts`; keys are cached ten minutes and an unknown
307307 `kid` refetches them once a minute at most). The parent's `sub` — never the
308 username — maps to a local account made on first sight with no password
309 (`core/federation.ts`; `http/rp.ts` has the two routes). No dependency added.
308 username — maps to a local account that was linked to it. The parent makes no
309 account: an unknown `sub` goes to the forge's own `/signup` with a note
310 saying why. Linking is its own same-origin POST, the **Link <parent>** button in
311 Settings (`POST /settings/parent/link`): it records the asking account on the
312 login, and the callback links only while that same account is signed in. The
313 plain `GET /signin/parent` never links, so a planted cross-site link cannot
314 attach someone else's parent identity (`core/federation.ts`; `http/rp.ts`). No dependency added.
310315 The parent's answers are read by bytes and refused past 16 KiB (64 KiB for the
311316 key set), and starting a sign-in is throttled like a password attempt.
312 An account made this way has no password, so the terminal's username-and-password
317 An account that has only a parent link has no password, so the terminal's username-and-password
313318 door (`s`) cannot let that person in. They add an SSH key under Settings → Keys
314319 once signed in on the web; after that the terminal signs them straight in as
315320 that account, as for anyone with a key.
src/core/federation.ts +42 −76
@@ -2,7 +2,8 @@
22 * Signing in through another forge (#748): what this forge, as a relying
33 * party, keeps. The client id it was given at the issuer (one per redirect
44 * address), a sign-in in flight (the state only as a hash, so a leaked
5 * database starts nothing), and which local account an issuer's `sub` is.
5 * database starts nothing), and which local account an issuer's `sub` is linked to. Nothing here makes an
6 * account: a person links the parent to an account they already have.
67 * The username is never the key: it can be renamed, and a name the parent
78 * frees may be taken by someone else.
89 */
@@ -11,8 +12,7 @@ import { readFileSync } from "node:fs";
1112 import { join } from "node:path";
1213 import { sha256 } from "../kernel/hash.ts";
1314 import { parentUrlProblem } from "./parent_releases.ts";
14 import { createUser, getUserById, getUserByName, isActive, type User } from "./users.ts";
15 import type { SignupSlot } from "../actions/signup-window.ts";
15 import { getUserById, isActive, type User } from "./users.ts";
1616
1717 /** Where the parent sends a person back; the address registered at the parent. */
1818 export const CALLBACK_PATH = "/signin/parent/callback";
@@ -44,6 +44,8 @@ export interface Login {
4444 readonly nonce: string;
4545 readonly issuer: string;
4646 readonly redirectUri: string;
47 /** Set when a signed-in person asked to link the parent; absent for a plain sign-in, which never links. */
48 readonly userId?: string;
4749 }
4850
4951 export function startLogin(db: Database, state: string, login: Login, now = Date.now()): void {
@@ -53,95 +55,59 @@ export function startLogin(db: Database, state: string, login: Login, now = Date
5355 (SELECT state_hash FROM rp_login ORDER BY expires_at LIMIT max(0, (SELECT count(*) FROM rp_login) - ?1))`,
5456 ).run(LOGIN_MAX - 1);
5557 db.query(
56 "INSERT INTO rp_login (state_hash, verifier, nonce, issuer, redirect_uri, expires_at) VALUES (?1, ?2, ?3, ?4, ?5, ?6)",
57 ).run(sha256(state), login.verifier, login.nonce, login.issuer, login.redirectUri, now + LOGIN_TTL_MS);
58 "INSERT INTO rp_login (state_hash, verifier, nonce, issuer, redirect_uri, expires_at, user_id) VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7)",
59 ).run(sha256(state), login.verifier, login.nonce, login.issuer, login.redirectUri, now + LOGIN_TTL_MS, login.userId ?? null);
5860 }
5961
6062 /** The sign-in a state began, used up by asking: a state works once. */
6163 export function takeLogin(db: Database, state: string, now = Date.now()): Login | undefined {
6264 const row = db
6365 .query<
64 { verifier: string; nonce: string; issuer: string; redirect_uri: string; expires_at: number },
66 { verifier: string; nonce: string; issuer: string; redirect_uri: string; expires_at: number; user_id: string | null },
6567 [string]
66 >("DELETE FROM rp_login WHERE state_hash = ?1 RETURNING verifier, nonce, issuer, redirect_uri, expires_at")
68 >("DELETE FROM rp_login WHERE state_hash = ?1 RETURNING verifier, nonce, issuer, redirect_uri, expires_at, user_id")
6769 .get(sha256(state));
6870 if (row === null || row.expires_at <= now) return undefined;
69 return { verifier: row.verifier, nonce: row.nonce, issuer: row.issuer, redirectUri: row.redirect_uri };
71 return {
72 verifier: row.verifier,
73 nonce: row.nonce,
74 issuer: row.issuer,
75 redirectUri: row.redirect_uri,
76 ...(row.user_id === null ? {} : { userId: row.user_id }),
77 };
7078 }
7179
72 /** A local username for a parent's person: their name if free and fit, else made unique by their `sub`. */
73 async function makeAccount(db: Database, sub: string, preferred: string, slot: SignupSlot): Promise<User | undefined> {
74 const base = preferred.toLowerCase().replace(/[^a-z0-9.-]/g, "").replace(/^[.-]+/, "").slice(0, 30);
75 const tail = sub.toLowerCase().replace(/[^a-z0-9]/g, "").slice(-8);
76 for (const username of [base, `${base}-${tail}`, `user-${tail}`]) {
77 if (username === "" || username.startsWith("-")) continue;
78 if (getUserByName(db, username) !== undefined) continue;
79 const made = await createUser(db, {
80 username,
81 // Unique, never mailed: `.invalid` is reserved and resolves nowhere.
82 email: `${sub.toLowerCase()}@sso.invalid`,
83 displayName: preferred,
84 origin: "parent",
85 slot,
86 });
87 if (made.ok) return made.value;
88 if (made.error === "signup_closed") return undefined;
89 }
90 return undefined;
91 }
92
93 const making = new Map<string, Promise<User | undefined>>();
94
95 /** Whether this issuer's `sub` already has a local account: a return, not a first sight. */
80 /** Whether this issuer's `sub` is linked to a local account: a return, not a first sight. */
9681 export function knownIdentity(db: Database, issuer: string, sub: string): boolean {
97 return (
98 db
99 .query<{ user_id: string }, [string, string]>(
100 "SELECT user_id FROM federated_identity WHERE issuer = ?1 AND sub = ?2",
101 )
102 .get(issuer, sub) !== null
103 );
82 return linkedUserId(db, issuer, sub) !== undefined;
83 }
84
85 function linkedUserId(db: Database, issuer: string, sub: string): string | undefined {
86 return db
87 .query<{ user_id: string }, [string, string]>(
88 "SELECT user_id FROM federated_identity WHERE issuer = ?1 AND sub = ?2",
89 )
90 .get(issuer, sub)?.user_id;
10491 }
10592
10693 /**
107 * The local account for an issuer's `sub`, made on first sight with no
108 * password — a stranger's sign-up, so only with a place in the sign-up
109 * window and while signup is open. Two returns of the same person at once
110 * make one account.
94 * The active local account an issuer's `sub` is linked to, if any. The parent
95 * makes no account here: an unknown `sub` is a stranger, and signing up is
96 * the forge's own (`/signup`).
11197 */
112 export function accountFor(
113 db: Database,
114 issuer: string,
115 sub: string,
116 preferred: string,
117 slot: SignupSlot | undefined,
118 ): Promise<User | undefined> {
119 const key = `${issuer}\0${sub}`;
120 const pending = making.get(key);
121 if (pending !== undefined) return pending;
122 const attempt = (async (): Promise<User | undefined> => {
123 const known = db
124 .query<{ user_id: string }, [string, string]>(
125 "SELECT user_id FROM federated_identity WHERE issuer = ?1 AND sub = ?2",
126 )
127 .get(issuer, sub);
128 if (known !== null) {
129 const user = getUserById(db, known.user_id);
130 return user !== undefined && isActive(user) ? user : undefined;
131 }
132 if (slot === undefined) return undefined;
133 const made = await makeAccount(db, sub, preferred, slot);
134 if (made === undefined) return undefined;
135 db.query("INSERT INTO federated_identity (issuer, sub, user_id) VALUES (?1, ?2, ?3)").run(
136 issuer,
137 sub,
138 made.id,
139 );
140 return made;
141 })();
142 making.set(key, attempt);
143 void attempt.finally(() => making.delete(key));
144 return attempt;
98 export function accountFor(db: Database, issuer: string, sub: string): User | undefined {
99 const id = linkedUserId(db, issuer, sub);
100 const user = id === undefined ? undefined : getUserById(db, id);
101 return user !== undefined && isActive(user) ? user : undefined;
102 }
103
104 /** Link an issuer's `sub` to an account that is signed in here; false if the `sub` is already linked. */
105 export function linkIdentity(db: Database, issuer: string, sub: string, userId: string): boolean {
106 return (
107 db
108 .query("INSERT INTO federated_identity (issuer, sub, user_id) VALUES (?1, ?2, ?3) ON CONFLICT DO NOTHING")
109 .run(issuer, sub, userId).changes === 1
110 );
145111 }
146112
147113 /** The spawn record's upstream, read once per forge: it does not change while the process runs. */
src/http/rp.ts +48 −22
@@ -1,19 +1,22 @@
11 /**
2 * Continue with the parent forge (#748): this forge as a relying party of
2 * Link the parent forge (#748): this forge as a relying party of
33 * the OpenID provider its parent already is. `/signin/parent` registers
44 * this forge at the parent once (the client id is kept), then sends the
55 * person there with a state, a nonce and a PKCE challenge; the state also
66 * rides in an HttpOnly cookie so only the browser that began can finish.
77 * `/signin/parent/callback` trades the code, checks the id_token (state,
88 * nonce, iss, aud, exp, signature against the parent's JWKS) and signs in
9 * the local account the parent's `sub` maps to, made on first sight.
10 * Both are GETs that change nothing a stranger could use: a callback with
11 * no matching cookie and state is refused before anything is fetched.
9 * the local account the parent's `sub` is linked to. An unknown `sub` makes no
10 * account: a stranger goes to `/signup`. Linking is its own same-origin POST
11 * (`/settings/parent/link`) that records the asking account on the login; the
12 * GET never links. A callback with no matching cookie and state is refused
13 * before anything is fetched.
1214 */
1315 import { createHash, randomBytes } from "node:crypto";
1416 import type { App } from "../app.ts";
1517 import {
1618 accountFor,
19 linkIdentity,
1720 knownIdentity,
1821 clientFor,
1922 keepClient,
@@ -25,12 +28,13 @@ import {
2528 } from "../core/federation.ts";
2629 import { readCapped } from "../origins/providers/http.ts";
2730 import { clientAddress } from "./peer.ts";
28 import { signinAllowed, signupSlot } from "../web/pages/site.ts";
31 import { signinAllowed } from "../web/pages/site.ts";
2932 import { createSession } from "../core/sessions.ts";
3033 import { verifyJwt } from "../kernel/jwt.ts";
3134 import { html } from "../web/html.ts";
32 import { page, redirect } from "../web/layout.ts";
35 import { flashTo, page, redirect } from "../web/layout.ts";
3336 import { sessionCookie } from "../web/pages/site.ts";
37 import { readForm } from "../web/form.ts";
3438 import { cookieValue, type Ctx } from "./context.ts";
3539 import { KeySet } from "./jwks.ts";
3640
@@ -118,7 +122,18 @@ const cookieHeader = (value: string, maxAge: number, url: URL, forgeUrl?: string
118122 return `${STATE_COOKIE}=${value}; Path=/signin/parent; HttpOnly; SameSite=Lax; Max-Age=${maxAge}${secure}`;
119123 };
120124
121 export async function parentStart(ctx: Ctx): Promise<Response> {
125 /** GET /signin/parent: a plain sign-in. It never links, whoever is signed in. */
126 export const parentStart = (ctx: Ctx): Promise<Response> => begin(ctx);
127
128 /** POST /settings/parent/link: a signed-in person, from this origin, asks to link the parent to their account. */
129 export async function parentLink(ctx: Ctx): Promise<Response> {
130 if (ctx.auth.user === undefined) return redirect("/signin");
131 const form = await readForm(ctx, "admin");
132 if (form instanceof Response) return form;
133 return begin(ctx, ctx.auth.user.id);
134 }
135
136 async function begin(ctx: Ctx, userId?: string): Promise<Response> {
122137 const issuer = parentIssuer(ctx.app);
123138 if (issuer === undefined) return failure(ctx, "This forge has no parent to sign in through.", 404);
124139 // Each start writes a row and the table is bounded: a flood must not push
@@ -139,7 +154,7 @@ export async function parentStart(ctx: Ctx): Promise<Response> {
139154 const state = rand(24);
140155 const verifier = rand(48);
141156 const nonce = rand(24);
142 startLogin(ctx.app.db, state, { verifier, nonce, issuer, redirectUri });
157 startLogin(ctx.app.db, state, { verifier, nonce, issuer, redirectUri, ...(userId === undefined ? {} : { userId }) });
143158 const query = new URLSearchParams({
144159 response_type: "code",
145160 client_id: client,
@@ -158,10 +173,6 @@ export async function parentStart(ctx: Ctx): Promise<Response> {
158173 return new Response(null, { status: 303, headers });
159174 }
160175
161 const clean = (s: unknown, max: number): string =>
162 // eslint-disable-next-line no-control-regex
163 typeof s === "string" ? s.replace(/[\u0000-\u001f\u007f]/g, "").trim().slice(0, max) : "";
164
165176 export async function parentCallback(ctx: Ctx): Promise<Response> {
166177 const q = ctx.url.searchParams;
167178 const state = q.get("state") ?? "";
@@ -207,17 +218,32 @@ export async function parentCallback(ctx: Ctx): Promise<Response> {
207218 const sub = verified.value["sub"];
208219 if (typeof sub !== "string" || !SUB.test(sub))
outdated

High: linking happens on the callback of a flow any cross-site GET can start, and it is not bound to an intent made on this forge. Record on the login row at start that this is a link by user X, start it only from a same-origin POST, and link here only when the row says so and ctx.auth.user.id === X. A plain sign-in must never link.

209220 return refuse("The parent forge's answer did not verify.", 502);
210 const name = clean(verified.value["preferred_username"], 64);
211 // A returning person is a sign-in; first sight of a sub makes an account,
212 // and that is a sign-up, held to the sign-up limit before it is made.
213 const slot = knownIdentity(ctx.app.db, login.issuer, sub) ? undefined : signupSlot(ctx);
214 if (typeof slot === "number") {
215 const slow = refuse(`Too many new accounts from here. Try again in ${slot}s.`, 429);
216 slow.headers.set("retry-after", String(slot));
217 return slow;
221 // The parent makes no account here. A returning `sub` signs in; only a
222 // link the signed-in person asked for by POST attaches a new one; a
223 // stranger goes to sign up.
224 const signedIn = ctx.auth.user;
225 const known = accountFor(ctx.app.db, login.issuer, sub);
226 const finished = (to: Response): Response => {
227 to.headers.append("set-cookie", clear);
228 to.headers.set("cache-control", "no-store");
229 return to;
230 };
231 if (login.userId !== undefined) {
232 if (signedIn?.id !== login.userId) return refuse("Sign in as the account that asked to link, then try again.", 403);
233 const linked = linkIdentity(ctx.app.db, login.issuer, sub, signedIn.id);
234 if (!linked && known?.id !== signedIn.id)
235 return refuse("That account at the parent is linked to another account here.", 409);
236 return finished(flashTo(ctx, "/settings", { message: "Parent account linked." }));
218237 }
219 const user = await accountFor(ctx.app.db, login.issuer, sub, name, slot);
220 if (user === undefined) return refuse("An account for you could not be made or is not allowed in.", 403);
238 if (known === undefined) {
239 if (knownIdentity(ctx.app.db, login.issuer, sub)) return refuse("Your account here is not allowed in.", 403);
240 if (signedIn !== undefined)
241 return refuse("That account at the parent is not linked to this one. Link it from Settings.", 409);
242 return finished(
243 redirect("/signup", { flash: { message: "That account isn't linked here; create one first.", tone: "danger" }, url: ctx.url }),
244 );
245 }
246 const user = known;
221247 const session = createSession(ctx.app.db, user.id);
222248 const done = redirect("/", sessionCookie(session.token, session.expiresAt, ctx.url, ctx.app.config.url));
223249 done.headers.append("set-cookie", clear);
src/http/server.ts +2 −1
@@ -11,7 +11,7 @@ import { signupOptions, signupPasskey } from "../web/pages/signup-passkey.ts";
1111 import { toolbarComment, toolbarPage } from "../web/studio/toolbar.ts";
1212 import { TOOLBAR_NAME, toolbarResponse } from "../apps/toolbar.ts";
1313 import { unsealReleased } from "../actions/sealed.ts";
14 import { parentCallback, parentStart } from "./rp.ts";
14 import { parentCallback, parentLink, parentStart } from "./rp.ts";
1515 import { accessPage } from "../web/pages/access.ts";
1616 import { capacityPage, capacitySet } from "../web/pages/capacity.ts";
1717 import { systemPage, systemStream } from "../web/pages/system.ts";
@@ -669,6 +669,7 @@ export function buildRouter(): Router<Handler> {
669669 router.add("POST", "/signin", signinSubmit);
670670 router.add("GET", "/signin/parent", parentStart);
671671 router.add("GET", "/signin/parent/callback", parentCallback);
672 router.add("POST", "/settings/parent/link", parentLink);
672673 router.add("GET", "/signup", signupPage);
673674 router.add("GET", "/verify", verifyPage);
674675 router.add("POST", "/signup", signupSubmit);
src/web/pages/account.ts +22
@@ -9,6 +9,7 @@
99 * has been read once.
1010 */
1111
12 import { parentIssuerOf } from "../../core/federation.ts";
1213 import { resendVerification } from "../../actions/verify.ts";
1314 import { clientAddress } from "../../http/peer.ts";
1415 import { emailVerified } from "../../core/verify.ts";
@@ -127,6 +128,22 @@ function notifyView(ctx: Ctx, error?: string): Html {
127128 );
128129 }
129130
131 <<<<<<< HEAD
132 /** Link the parent forge's account to this one: a POST, never a link. */
133 function parentLinkView(ctx: Ctx): Html | undefined {
134 const issuer = parentIssuerOf(ctx.app.config);
135 if (issuer === undefined) return undefined;
136 const host = new URL(issuer).host;
137 return card(
outdated

This card is the same whether or not the account is already linked. Pressing it again goes round the parent only to come back with "Parent account linked." Show the linked state ("Linked to <host>") when federated_identity has a row for this user, and only offer the button when it does not.

138 html`<form method="post" action="/settings/parent/link">
139 <p class="hint">Sign in here later with your account at ${host}.</p>
140 <div class="form-actions">${btn(`Link ${host}`)}</div>
141 </form>`,
142 { head: html`<h3>Linked account</h3>` },
143 );
144 }
145
146 =======
130147 /** open-platform.sh: linked as <login>, or not, with Link and Unlink. */
131148 function edgeLinkView(ctx: Ctx): Html {
132149 const token = activeEdgeToken(ctx.app);
@@ -183,6 +200,7 @@ export async function edgeUnlink(ctx: Ctx): Promise<Response> {
183200 return flashTo(ctx, "/settings", { message: "Unlinked." });
184201 }
185202
203 >>>>>>> origin/main
186204 /** Shown above the profile until the email is proven. */
187205 function unverifiedNotice(ctx: Ctx): Html {
188206 const user = ctx.auth.user!;
@@ -303,7 +321,11 @@ export function accountPage(ctx: Ctx): Response {
303321 ctx,
304322 "profile",
305323 "Settings",
324 <<<<<<< HEAD
325 html`${pair}${profileView(ctx, currentProfile(ctx.auth.user))}${notifyView(ctx)}${parentLinkView(ctx) ?? ""}`,
326 =======
306327 html`${pair}${profileView(ctx, currentProfile(ctx.auth.user))}${edgeLinkView(ctx)}${notifyView(ctx)}`,
328 >>>>>>> origin/main
307329 200,
308330 // The everyday form makes its account with a passkey (#1890).
309331 pair ? passkeyJs : undefined,
src/web/pages/site.ts +35 −34
@@ -28,6 +28,7 @@ import { activeEdgeToken, edgeIdentity, edgeLoginUrl, edgeStrangerLogin } from "
2828 import { sshCommand } from "../../ssh/command.ts";
2929 import { hostOf, pageHead, signInFirst } from "../chrome.ts";
3030 import { SignupSlot, signupWindow } from "../../actions/signup-window.ts";
31 import { getSignup } from "../../settings/signup.ts";
3132 import { signinWindow } from "../../core/signin-window.ts";
3233 import { field, readForm } from "../form.ts";
3334 import { passkeyJs } from "../passkey-client.ts";
@@ -243,9 +244,8 @@ function authForm(
243244 // of the whole user table — and the sign-in screen paints on every session.
244245 const firstAccount = kind === "signup" && !hasAnyUser(ctx.app.db);
245246
246 // Behind a platform edge, that is the door: the button first, and the
247 // password form kept for the accounts that have one — an account the edge
248 // made has none, and the note says so before anyone types.
247 // Behind a platform edge, its login is offered last, as a link to an
248 // account that exists (an account the edge made has no password here).
249249 // A newcomer the edge vouched for is already through it: no button to go
250250 // round again, and the name is theirs alone.
251251 const vouched = edgeStrangerLogin(ctx.request, activeEdgeToken(ctx.app), ctx.auth.user);
@@ -253,29 +253,11 @@ function authForm(
253253 activeEdgeToken(ctx.app) === undefined || vouched !== undefined
254254 ? undefined
255255 : (ctx.app.config.edgeName ?? "the platform");
256 const throughEdge = when(
257 edge,
258 (name) =>
259 html`<div class="stack mb">
260 ${btn(`Continue with ${name}`, {
261 href: edgeLoginUrl(next ?? "/"),
262 variant: "primary",
263 size: "lg",
264 })}
265 <p class="muted small">
266 ${kind === "signin"
267 ? `Accounts made through ${name} sign in there and have no password here. The form below is for an account that was given one.`
268 : `Signing in through ${name} does not make an account here; the form below does.`}
269 </p>
270 </div>`,
271 );
272
273256 // No door makes a password-only account: sign-up is a name, an address and
274257 // a passkey, made in the browser (`signup-passkey.ts`).
275258 const byPasskey = kind === "signup" && ctx.app.config.passkeyOnlySignup === true;
276259
277 const body = html`${throughEdge}
278 <form method="post" action="${action}">
260 const body = html`<form method="post" action="${action}">
279261 ${formField({
280262 label: "Username",
281263 name: "username",
@@ -372,25 +354,45 @@ function authForm(
372354 const unowned = !hasAdmin(ctx.app.db);
373355 const claimable =
374356 existsSync(join(ctx.app.config.dataDir, "parent.json")) && unowned;
357 const mode = getSignup(ctx.app.db);
358 const parent = kind === "signin" ? parentIssuerOf(ctx.app.config) : undefined;
359 // Linked methods sign in an account already linked here, or attach to one
360 // that is signed in; an unknown identity makes no account (it goes to /signup).
361 const linked = [
outdated

Not true yet. rp.ts → accountFor makes an account on first sight. Either make it true in federation.ts (preferred, matches #2779), or correct the comment and the copy.

362 ...(edge === undefined
363 ? []
364 : [{ name: edge, href: edgeLoginUrl(next ?? "/") }]),
365 ...(parent === undefined
366 ? []
367 : [{ name: new URL(parent).host, href: "/signin/parent" }]),
368 ];
375369 return html`<div class="narrow">
376370 ${pageHead(kind === "signin" ? "Sign in" : "Create your account")}
377 ${card(body)}
378371 ${when(
379372 kind === "signin",
380 () => html`<p class="mt">
381 <button type="button" id="passkey-signin" class="btn" data-variant="outline">Sign in with a passkey</button>
373 () => html`<p class="mb">
374 <button type="button" id="passkey-signin" class="btn" data-variant="primary" data-size="lg">Sign in with a passkey</button>
382375 <span class="error-note small" id="passkey-signin-note" role="status"></span>
outdated

This is a second filled primary on /signin; the form's Sign in is already primary. DESIGN.md allows one per page. Use btn(..., { type: "button", variant: "primary", size: "lg" }) here, make the form's submit outline on signin, and add a <noscript> note, because this button does nothing without JavaScript.

383376 <a class="small" href="/recover">Lost your device?</a>
384377 </p>`,
385378 )}
386379 ${when(
387 kind === "signin" ? parentIssuerOf(ctx.app.config) : undefined,
388 (parent) => html`<p class="mt">
389 ${btn(`Continue with ${new URL(parent).host}`, {
390 href: "/signin/parent",
391 variant: "outline",
392 })}
393 </p>`,
380 kind === "signin" && mode !== "open",
381 () => html`<p class="muted small mb" id="signup-mode">${
382 mode === "closed"
383 ? "This forge is closed to new accounts."
384 : "This forge is invite-only: new accounts need an invite link."
385 }</p>`,
outdated

This also renders on /signup?invite=<valid>, where it tells the person holding the invite that they need one. Show it on sign-in only (kind === "signin" && mode !== "open"), or leave it off when invite is set.

386 )}
387 ${card(body)}
388 ${when(
389 linked.length > 0,
390 () => html`<div class="stack mt" id="linked-methods">
391 <p class="muted small">
392 Link an account you have. A linked account signs in here; it never makes one${kind === "signin" ? ". Accounts made there have no password here" : ""}.
393 </p>
outdated

High: "it never makes one" is false for the parent door. accountFor in src/core/federation.ts creates a local account the first time it sees an unknown sub while signup is open. Make /signin/parent refuse unknown identities and send them to /signup, as #2779 did for the edge, with a test that fails today. Or stop calling it "link".

394 ${linked.map((l) => btn(`Link an account from ${l.name}`, { href: l.href, variant: "outline" }))}
395 </div>`,
outdated

For the parent, href="/signin/parent" is a GET that only signs in an already-linked account and never links (see rp.ts). Calling it "Link an account from …" sends people to a door that refuses them with a 409 or a redirect to /signup. Name it for what it does, e.g. "Sign in with <host>", and leave linking to the Settings button.

394396 )}
395397 ${claimable
396398 ? html`<p class="muted small mt" id="claim-door">
@@ -463,8 +465,7 @@ export function signinAllowed(ctx: Ctx, key: string): number | undefined {
463465
464466 /**
465467 * Sign-ups by the socket's peer (`actions/signup-window.ts`), asked by the
466 * signup form, the API signup, the terminal's create screen, the passkey door
467 * and the parent sign-in's first sight of a person, which share one window.
468 * signup form, the API signup, the terminal's create screen and the passkey door, which share one window.
468469 */
469470 export function signupAllowed(ctx: Ctx): number | undefined {
470471 return signupWindow(ctx.app, clientAddress(ctx.request));
test/edge-auth.test.ts +1 −1
@@ -175,7 +175,7 @@ describe("a forge behind the platform edge", () => {
175175 r.text(),
176176 );
177177 expect(page).toContain('href="/_plat/login?rd=%2Fnew"');
178 expect(page).toContain("Continue with the platform");
178 expect(page).toContain("Link an account from the platform");
179179 expect(page).toContain("have no password here");
180180 // The password form is still there for an account that was given one.
181181 expect(page).toContain('name="password"');
test/forge-signin-signup.test.ts deleted −102
@@ -1,102 +0,0 @@
1 /**
2 * First sight of a person through the parent is a sign-up: it shares the
3 * sign-up window with the passkey door, is refused with the wait when the
4 * window is spent, and makes no account. A returning person is a sign-in and
5 * is never held to that window.
6 */
7 import { afterAll, beforeAll, 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 { createSession } from "../src/core/sessions.ts";
13 import { createUser, getUserByName } from "../src/core/users.ts";
14 import { serve, type Servers } from "../src/http/server.ts";
15 import { setLimit } from "../src/settings/limits.ts";
16 import { device } from "./helpers/passkey.ts";
17 import { quietLogs } from "./helpers/globals.ts";
18
19 quietLogs();
20
21 let dirs: string[] = [];
22 let parent: App;
23 let child: App;
24 let ps: Servers;
25 let cs: Servers;
26 const cookies: Record<string, string> = {};
27
28 const cookieOf = (res: Response, name: string) =>
29 res.headers.getSetCookie().map((c) => c.split(";")[0]!).find((c) => c.startsWith(`${name}=`));
30
31 /** One full sign-in at the child as the parent's person with `cookie`; the callback's response. */
32 async function through(cookie: string): Promise<Response> {
33 const start = await fetch(`${cs.url}/signin/parent`, { redirect: "manual" });
34 const to = new URL(start.headers.get("location")!);
35 const consent = await fetch(`${ps.url}/oauth/authorize`, {
36 method: "POST",
37 redirect: "manual",
38 headers: { cookie, origin: ps.url },
39 body: new URLSearchParams({ ...Object.fromEntries(to.searchParams), decision: "allow" }),
40 });
41 const back = new URL(consent.headers.get("location")!);
42 return fetch(`${cs.url}${back.pathname}${back.search}`, { redirect: "manual", headers: { cookie: cookieOf(start, "forge_rp")! } });
43 }
44
45 const post = (path: string, body: unknown) =>
46 fetch(`${cs.url}${path}`, { method: "POST", headers: { "content-type": "application/json" }, body: JSON.stringify(body) });
47
48 async function passkeySignUp(name: string) {
49 const d = await device(new URL(cs.url).origin, new URL(cs.url).hostname);
50 const email = `${name}@f.dev`;
51 const o = (await (await post("/signup/passkey/options", { username: name, email })).json()) as any;
52 return post("/signup/passkey", { username: name, email, challenge: o.challenge, ...(await d.create(o.challenge)) });
53 }
54
55 beforeAll(async () => {
56 const make = async () => {
57 const dir = await mkdtemp(join(tmpdir(), "forge-signin-signup-"));
58 dirs.push(dir);
59 return dir;
60 };
61 parent = createApp({ dataDir: await make(), port: 0 });
62 ps = await serve(parent);
63 child = createApp({ dataDir: await make(), port: 0, parentUrl: ps.url, parentLoopback: true });
64 cs = await serve(child);
65 for (const name of ["amy", "ben"]) {
66 const made = await createUser(parent.db, { origin: "seed", username: name, email: `${name}@parent.local`, password: "a-long-family-passphrase", adminIfFirst: name === "amy" });
67 if (!made.ok) throw new Error(made.error);
68 cookies[name] = `forge_session=${createSession(parent.db, made.value.id).token}`;
69 }
70 const seeded = await createUser(child.db, { origin: "seed", username: "olive", email: "[email protected]", password: "a-long-family-passphrase", trusted: true });
71 if (!seeded.ok) throw new Error(seeded.error);
72 const actor = seeded.value.id;
73 // Two sign-ups a minute from this source, shared by every door.
74 setLimit(child.db, "signup.per_source", 2, actor);
75 });
76
77 afterAll(async () => {
78 ps.stop();
79 cs.stop();
80 for (const dir of dirs) await rm(dir, { recursive: true, force: true });
81 });
82
83 test("a new sub past the sign-up limit is refused with the wait and makes no account; a returning sub is not throttled; the passkey door shares the window", async () => {
84 expect((await through(cookies.amy!)).status).toBe(303);
85 expect(getUserByName(child.db, "amy")).toBeDefined();
86 expect((await passkeySignUp("pk1")).status).toBe(201);
87
88 const refused = await through(cookies.ben!);
89 expect(refused.status).toBe(429);
90 expect(Number(refused.headers.get("retry-after"))).toBeGreaterThan(0);
91 expect(await refused.text()).toContain("Try again in");
92 expect(getUserByName(child.db, "ben")).toBeUndefined();
93
94 // Amy is known here: signing in again is not a sign-up.
95 const again = await through(cookies.amy!);
96 expect(again.status).toBe(303);
97 expect(cookieOf(again, "forge_session")).toBeDefined();
98 expect(child.db.query("SELECT COUNT(*) AS n FROM user WHERE username = 'amy'").get()).toEqual({ n: 1 });
99
100 // And the spent window holds the passkey door too.
101 expect((await passkeySignUp("pk2")).status).toBe(429);
102 });
test/forge-signin.test.ts +103 −7
@@ -103,13 +103,111 @@ describe("sign in through the parent forge", () => {
103103
104104 test("only a forge with a parent offers the button", async () => {
105105 const onChild = await (await fetch(`${childServers.url}/signin`)).text();
106 expect(onChild).toContain(`Continue with ${new URL(parentServers.url).host}`);
106 expect(onChild).toContain(`Link an account from ${new URL(parentServers.url).host}`);
107107 expect(onChild).toContain('href="/signin/parent"');
108 expect(await (await fetch(`${parentServers.url}/signin`)).text()).not.toContain("Continue with");
108 expect(onChild).not.toContain("Continue with");
109 expect(await (await fetch(`${parentServers.url}/signin`)).text()).not.toContain('href="/signin/parent"');
109110 const none = await fetch(`${parentServers.url}/signin/parent`, { redirect: "manual" });
110111 expect(none.status).toBe(404);
111112 });
112113
114 test("a new parent identity on an open child forge gets no account and goes to /signup", async () => {
115 const before = child.db.query("SELECT COUNT(*) AS n FROM user").get();
116 const { callback, state } = await begin(aliceCookie);
117 const done = await finish(callback, state);
118 expect(done.status).toBe(303);
119 expect(done.headers.get("location")).toBe("/signup");
120 expect(cookieOf(done, "forge_session")).toBeUndefined();
121 expect(getUserByName(child.db, "alice")).toBeUndefined();
122 expect(child.db.query("SELECT COUNT(*) AS n FROM user").get()).toEqual(before);
123 });
124
125 /** The signed-in person at the child asks to link (the Settings button): consent at the parent as `parentCookie`; the callback and state cookie. */
126 const beginLink = async (mine: string, parentCookie: string, origin = childServers.url) => {
127 const start = await fetch(`${childServers.url}/settings/parent/link`, {
128 method: "POST",
129 redirect: "manual",
130 headers: { cookie: mine, origin },
131 });
132 if (start.status !== 303) return { start };
133 const to = new URL(start.headers.get("location")!);
134 const consent = await fetch(`${parentServers.url}/oauth/authorize`, {
135 method: "POST",
136 redirect: "manual",
137 headers: { cookie: parentCookie, origin: parentServers.url },
138 body: new URLSearchParams({ ...Object.fromEntries(to.searchParams), decision: "allow" }),
139 });
140 return { start, callback: new URL(consent.headers.get("location")!), state: cookieOf(start, "forge_rp")! };
141 };
142 const identities = () => child.db.query("SELECT COUNT(*) AS n FROM federated_identity").get();
143
144 test("linking is a same-origin POST by the signed-in person; a cross-site POST or a stranger starts nothing", async () => {
145 const made = await createUser(child.db, { origin: "seed", username: "alice", email: "[email protected]", trusted: true });
146 if (!made.ok) throw new Error(made.error);
147 const mine = `forge_session=${createSession(child.db, made.value.id).token}`;
148 const settings = await (await fetch(`${childServers.url}/settings`, { headers: { cookie: mine } })).text();
149 expect(settings).toContain('action="/settings/parent/link"');
150 expect(await (await fetch(`${parentServers.url}/signin`)).text()).not.toContain("never makes one");
151 const cross = await beginLink(mine, aliceCookie, "https://evil.example");
152 expect(cross.start.status).toBe(403);
153 expect(cross.start.headers.get("location")).toBeNull();
154 const anon = await fetch(`${childServers.url}/settings/parent/link`, { method: "POST", redirect: "manual", headers: { origin: childServers.url } });
155 expect(anon.status).toBe(303);
156 expect(anon.headers.get("location")).toBe("/signin");
157
158 const link = await beginLink(mine, aliceCookie);
159 const linked = await fetch(`${childServers.url}${link.callback!.pathname}${link.callback!.search}`, {
160 redirect: "manual",
161 headers: { cookie: `${link.state}; ${mine}` },
162 });
163 expect(linked.status).toBe(303);
164 expect(linked.headers.get("location")).toBe("/settings");
165 expect(child.db.query("SELECT user_id FROM federated_identity WHERE sub = ?1").get(alice)).toEqual({ user_id: made.value.id });
166 // A link finished by someone else's session (not the one that asked) links nothing.
167 const other = await createUser(child.db, { origin: "seed", username: "carol", email: "[email protected]", trusted: true });
168 if (!other.ok) throw new Error(other.error);
169 const carol = `forge_session=${createSession(child.db, other.value.id).token}`;
170 const again = await beginLink(mine, aliceCookie);
171 const swapped = await fetch(`${childServers.url}${again.callback!.pathname}${again.callback!.search}`, {
172 redirect: "manual",
173 headers: { cookie: `${again.state}; ${carol}` },
174 });
175 expect(swapped.status).toBe(403);
176 // Another account here cannot take an identity already linked.
177 const taken = await beginLink(carol, aliceCookie);
178 const refused = await fetch(`${childServers.url}${taken.callback!.pathname}${taken.callback!.search}`, {
179 redirect: "manual",
180 headers: { cookie: `${taken.state}; ${carol}` },
181 });
182 expect(refused.status).toBe(409);
183 expect(child.db.query("SELECT user_id FROM federated_identity WHERE sub = ?1").get(alice)).toEqual({ user_id: made.value.id });
184 });
185
186 test("a cross-site GET to /signin/parent from a signed-in browser links nothing, whoever the parent returns", async () => {
187 const made = await createUser(child.db, { origin: "seed", username: "dave", email: "[email protected]", trusted: true });
188 if (!made.ok) throw new Error(made.error);
189 const victim = `forge_session=${createSession(child.db, made.value.id).token}`;
190 const before = identities();
191 // The attacker's own parent identity; the victim's browser follows a planted link.
192 const attacker = await createUser(parent.db, { origin: "seed", username: "mallory", email: "[email protected]", password: PASSWORD });
193 if (!attacker.ok) throw new Error(attacker.error);
194 const start = await fetch(`${childServers.url}/signin/parent`, { redirect: "manual", headers: { cookie: victim, "sec-fetch-site": "cross-site" } });
195 const to = new URL(start.headers.get("location")!);
196 const consent = await fetch(`${parentServers.url}/oauth/authorize`, {
197 method: "POST",
198 redirect: "manual",
199 headers: { cookie: `forge_session=${createSession(parent.db, attacker.value.id).token}`, origin: parentServers.url },
200 body: new URLSearchParams({ ...Object.fromEntries(to.searchParams), decision: "allow" }),
201 });
202 const back = new URL(consent.headers.get("location")!);
203 const done = await fetch(`${childServers.url}${back.pathname}${back.search}`, {
204 redirect: "manual",
205 headers: { cookie: `${cookieOf(start, "forge_rp")!}; ${victim}` },
206 });
207 expect(done.status).toBe(409);
208 expect(identities()).toEqual(before);
209 });
210
113211 test("a person signs into the child through the parent, and the account keys on sub", async () => {
114212 const { callback, state } = await begin(aliceCookie);
115213 expect(callback.origin).toBe(childServers.url);
@@ -205,11 +303,9 @@ describe("sign in through the parent forge", () => {
205303 if (!local.ok) throw new Error(local.error);
206304 const { callback, state } = await begin(`forge_session=${createSession(parent.db, bob.value.id).token}`);
207305 const done = await finish(callback, state);
208 expect(done.status).toBe(303);
209 const row = child.db
210 .query<{ user_id: string }, [string]>("SELECT user_id FROM federated_identity WHERE sub = ?1")
211 .get(bob.value.id)!;
212 expect(row.user_id).not.toBe(local.value.id);
306 // A stranger at the parent is not the local bob: no sign-in, no link.
307 expect(done.headers.get("location")).toBe("/signup");
308 expect(child.db.query("SELECT COUNT(*) AS n FROM federated_identity WHERE sub = ?1").get(bob.value.id)).toEqual({ n: 0 });
213309 });
214310
215311 test("a callback is refused without its browser's cookie, with another state, or a second time", async () => {
test/signup-gate-parent.test.ts +12 −18
@@ -1,7 +1,7 @@
11 /**
2 * The parent forge's sign-in is a way in for strangers like any other: while
3 * the child's signup is `closed` or `invite`, a person the child has never
4 * seen gets no account and no session there. Open again, they get one.
2 * The parent forge's sign-in makes no account, in any signup mode: a person
3 * the child has never seen gets no account and no session, and is sent to the
4 * forge's own `/signup`.
55 */
66 import { afterAll, beforeAll, expect, test } from "bun:test";
77 import { mkdtemp, rm } from "node:fs/promises";
@@ -71,25 +71,20 @@ afterAll(async () => {
7171 for (const dir of dirs) await rm(dir, { recursive: true, force: true });
7272 });
7373
74 const shut: [SignupMode, string][] = [["closed", "alice"], ["invite", "bea"]];
75 for (const [mode, name] of shut) {
76 test(`signup ${mode}: a parent's person new to the child gets no account and no session`, async () => {
74 for (const mode of ["open", "invite", "closed"] as SignupMode[]) {
75 test(`signup ${mode}: a parent's person new to the child gets no account and goes to /signup`, async () => {
7776 setSignup(child.db, mode, owner);
78 const done = await through(name);
79 expect(done.status).toBe(403);
77 const done = await through("cleo");
78 expect(done.status).toBe(303);
79 expect(done.headers.get("location")).toBe("/signup");
80 // The stranger is told why they landed there.
81 expect(cookieOf(done, "forge_flash") ?? "").not.toBe("");
8082 expect(cookieOf(done, "forge_session")).toBe("");
81 expect(getUserByName(child.db, name)).toBeUndefined();
83 expect(getUserByName(child.db, "cleo")).toBeUndefined();
84 expect(child.db.query("SELECT COUNT(*) AS n FROM federated_identity").get()).toEqual({ n: 0 });
8285 });
8386 }
8487
85 test("signup open: the same door makes the account", async () => {
86 setSignup(child.db, "open", owner);
87 const done = await through("cleo");
88 expect(done.status).toBe(303);
89 expect(cookieOf(done, "forge_session")).not.toBe("");
90 expect(getUserByName(child.db, "cleo")).toBeDefined();
91 });
92
9388 /** Each place in `src` that makes an account, and the origin it says. */
9489 async function callers(): Promise<Record<string, string[]>> {
9590 const found: Record<string, string[]> = {};
@@ -120,7 +115,6 @@ test("every caller of createUser says where its account comes from", async () =>
120115 "src/actions/spawn.ts": ["spawn", "spawn"],
121116 "src/actions/users.ts": ["signup", "passkey"],
122117 "src/chaos/world.ts": ["seed"],
123 "src/core/federation.ts": ["parent"],
124118 "src/web/pages/claim.ts": ["claim"],
125119 "src/web/pages/everyday.ts": ["everyday"],
126120 });
test/signup-page.test.ts added +106
@@ -0,0 +1,106 @@
1 /**
2 * The sign-up and sign-in pages (#669): passkey first, each `signup` mode
3 * said in a sentence, and linked methods offered only as "link", never as a
4 * way to make an account.
5 */
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 { setSignup, type SignupMode } from "../src/settings/signup.ts";
13 import { mintInvite } from "../src/core/invites.ts";
14 import { serve, type Servers } from "../src/http/server.ts";
15
16 describe("signup and sign-in pages", () => {
17 let dataDir: string;
18 let app: App;
19 let servers: Servers;
20
21 beforeAll(async () => {
22 dataDir = await mkdtemp(join(tmpdir(), "forge-signup-page-"));
23 app = createApp({
24 dataDir,
25 port: 0,
26 url: "https://forge.example",
27 passkeyOnlySignup: true,
28 });
29 servers = await serve(app);
30 });
31 afterAll(async () => {
32 await servers.stop();
33 app.close();
34 await rm(dataDir, { recursive: true, force: true });
35 });
36
37 const get = (path: string) => fetch(`${servers.url}${path}`).then((r) => r.text());
38 const mode = (m: SignupMode) => setSignup(app.db, m, "boot");
39
40 test("open: sign-up offers a passkey and no password field", async () => {
41 mode("open");
42 const page = await get("/signup");
43 expect(page).toContain("Create account with a passkey");
44 expect(page).not.toContain('name="password"');
45 expect(page).not.toContain("invite-only");
46 });
47
48 test("sign-in leads with the passkey, before the form", async () => {
49 mode("open");
50 const page = await get("/signin");
51 expect(page.indexOf("Sign in with a passkey")).toBeGreaterThan(-1);
52 expect(page.indexOf("Sign in with a passkey")).toBeLessThan(page.indexOf(`action="/signin"`));
53 });
54
55 test("invite and closed say so in one sentence on sign-in", async () => {
56 mode("invite");
57 expect(await get("/signin")).toContain("invite-only");
58 mode("closed");
59 expect(await get("/signin")).toContain("closed to new accounts");
60 });
61
62 test("the invite-only sentence is not shown to a person holding an invite", async () => {

This passes on main too: #signup-mode is only ever rendered on /signin, so /signup never had it. Either drop the test or assert something the change actually does.

63 mode("invite");
64 const { token } = mintInvite(app.db, "someone");
65 const page = await get(`/signup?invite=${token}`);
66 expect(page).toContain("passkey-signup");
67 expect(page).not.toContain("signup-mode");
68 });
69
70 test("invite and closed: /signup is a sentence and no form", async () => {
71 for (const m of ["invite", "closed"] as const) {
72 mode(m);
73 const page = await get("/signup");
74 expect(page).toContain("Signup is closed on this forge.");
75 expect(page).not.toContain("passkey-signup");
76 }
77 });
78
79 test("a linked method is offered as a link, never as a way to create", async () => {
80 mode("open");
81 for (const path of ["/signin", "/signup"]) {
82 const page = await get(path);
83 expect(page).not.toContain("Continue with");
84 expect(page).not.toContain("Sign up with");
85 }
86 });
87 });
88
89 describe("linked methods behind a platform edge", () => {
90 test("sign-in offers the edge as 'link an account you have'", async () => {
91 const dataDir = await mkdtemp(join(tmpdir(), "forge-signup-page-edge-"));
92 const app = createApp({ dataDir, port: 0, edgeToken: "edge-secret-0123456789" });
93 const servers = await serve(app);
94 try {
95 const page = await fetch(`${servers.url}/signin`).then((r) => r.text());
96 expect(page).toContain("Link an account you have");
97 expect(page).toContain("it never makes one");
98 expect(page).toContain("Link an account from the platform");
99 expect(page).not.toContain("Continue with");
100 } finally {
101 await servers.stop();
102 app.close();
103 await rm(dataDir, { recursive: true, force: true });
104 }
105 });
106 });

↑↓ navigate ↵ open ⌘↵ its app esc close

Keyboard shortcuts

Docs