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
scout/forge:scout/669-the-signup-and-sign-in-page-passkey-firs → main 4 commits fork 9 threads · 9 unresolved
README.md +9 −4
| @@ -298,18 +298,23 @@ The relying party is the address the browser used (or | ||
| 298 | 298 | 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. |
| 299 | 299 | |
| 300 | 300 | 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 | |
| 302 | 302 | registers itself once at the parent's `/oauth/register` (the client id is kept |
| 303 | 303 | in `rp_client`), sends the person through the parent's authorize page with |
| 304 | 304 | PKCE, and on return checks state (also bound to the browser by an HttpOnly |
| 305 | 305 | cookie), nonce, `iss`, `aud`, `exp` and the ES256 signature against the |
| 306 | 306 | parent's JWKS (`kernel/jwt.ts`; keys are cached ten minutes and an unknown |
| 307 | 307 | `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. | |
| 310 | 315 | The parent's answers are read by bytes and refused past 16 KiB (64 KiB for the |
| 311 | 316 | 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 | |
| 313 | 318 | door (`s`) cannot let that person in. They add an SSH key under Settings → Keys |
| 314 | 319 | once signed in on the web; after that the terminal signs them straight in as |
| 315 | 320 | that account, as for anyone with a key. |
src/core/federation.ts +42 −76
| @@ -2,7 +2,8 @@ | ||
| 2 | 2 | * Signing in through another forge (#748): what this forge, as a relying |
| 3 | 3 | * party, keeps. The client id it was given at the issuer (one per redirect |
| 4 | 4 | * 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. | |
| 6 | 7 | * The username is never the key: it can be renamed, and a name the parent |
| 7 | 8 | * frees may be taken by someone else. |
| 8 | 9 | */ |
| @@ -11,8 +12,7 @@ import { readFileSync } from "node:fs"; | ||
| 11 | 12 | import { join } from "node:path"; |
| 12 | 13 | import { sha256 } from "../kernel/hash.ts"; |
| 13 | 14 | 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"; | |
| 16 | 16 | |
| 17 | 17 | /** Where the parent sends a person back; the address registered at the parent. */ |
| 18 | 18 | export const CALLBACK_PATH = "/signin/parent/callback"; |
| @@ -44,6 +44,8 @@ export interface Login { | ||
| 44 | 44 | readonly nonce: string; |
| 45 | 45 | readonly issuer: string; |
| 46 | 46 | 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; | |
| 47 | 49 | } |
| 48 | 50 | |
| 49 | 51 | 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 | ||
| 53 | 55 | (SELECT state_hash FROM rp_login ORDER BY expires_at LIMIT max(0, (SELECT count(*) FROM rp_login) - ?1))`, |
| 54 | 56 | ).run(LOGIN_MAX - 1); |
| 55 | 57 | 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); | |
| 58 | 60 | } |
| 59 | 61 | |
| 60 | 62 | /** The sign-in a state began, used up by asking: a state works once. */ |
| 61 | 63 | export function takeLogin(db: Database, state: string, now = Date.now()): Login | undefined { |
| 62 | 64 | const row = db |
| 63 | 65 | .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 }, | |
| 65 | 67 | [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") | |
| 67 | 69 | .get(sha256(state)); |
| 68 | 70 | 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 | }; | |
| 70 | 78 | } |
| 71 | 79 | |
| 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. */ | |
| 96 | 81 | 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; | |
| 104 | 91 | } |
| 105 | 92 | |
| 106 | 93 | /** |
| 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`). | |
| 111 | 97 | */ |
| 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 | ); | |
| 145 | 111 | } |
| 146 | 112 | |
| 147 | 113 | /** The spawn record's upstream, read once per forge: it does not change while the process runs. */ |
src/core/migrations/20261019170000-link-login-user.ts added +6
| @@ -0,0 +1,6 @@ | ||
| 1 | // A sign-in through the parent that began as a link (#669): the account that | |
| 2 | // asked for it, so the callback links only for that person and a plain | |
| 3 | // sign-in never links. | |
| 4 | export default ` | |
| 5 | ALTER TABLE rp_login ADD COLUMN user_id TEXT; | |
| 6 | `; |
src/http/rp.ts +48 −22
| @@ -1,19 +1,22 @@ | ||
| 1 | 1 | /** |
| 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 | |
| 3 | 3 | * the OpenID provider its parent already is. `/signin/parent` registers |
| 4 | 4 | * this forge at the parent once (the client id is kept), then sends the |
| 5 | 5 | * person there with a state, a nonce and a PKCE challenge; the state also |
| 6 | 6 | * rides in an HttpOnly cookie so only the browser that began can finish. |
| 7 | 7 | * `/signin/parent/callback` trades the code, checks the id_token (state, |
| 8 | 8 | * 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. | |
| 12 | 14 | */ |
| 13 | 15 | import { createHash, randomBytes } from "node:crypto"; |
| 14 | 16 | import type { App } from "../app.ts"; |
| 15 | 17 | import { |
| 16 | 18 | accountFor, |
| 19 | linkIdentity, | |
| 17 | 20 | knownIdentity, |
| 18 | 21 | clientFor, |
| 19 | 22 | keepClient, |
| @@ -25,12 +28,13 @@ import { | ||
| 25 | 28 | } from "../core/federation.ts"; |
| 26 | 29 | import { readCapped } from "../origins/providers/http.ts"; |
| 27 | 30 | import { clientAddress } from "./peer.ts"; |
| 28 | import { signinAllowed, signupSlot } from "../web/pages/site.ts"; | |
| 31 | import { signinAllowed } from "../web/pages/site.ts"; | |
| 29 | 32 | import { createSession } from "../core/sessions.ts"; |
| 30 | 33 | import { verifyJwt } from "../kernel/jwt.ts"; |
| 31 | 34 | import { html } from "../web/html.ts"; |
| 32 | import { page, redirect } from "../web/layout.ts"; | |
| 35 | import { flashTo, page, redirect } from "../web/layout.ts"; | |
| 33 | 36 | import { sessionCookie } from "../web/pages/site.ts"; |
| 37 | import { readForm } from "../web/form.ts"; | |
| 34 | 38 | import { cookieValue, type Ctx } from "./context.ts"; |
| 35 | 39 | import { KeySet } from "./jwks.ts"; |
| 36 | 40 | |
| @@ -118,7 +122,18 @@ const cookieHeader = (value: string, maxAge: number, url: URL, forgeUrl?: string | ||
| 118 | 122 | return `${STATE_COOKIE}=${value}; Path=/signin/parent; HttpOnly; SameSite=Lax; Max-Age=${maxAge}${secure}`; |
| 119 | 123 | }; |
| 120 | 124 | |
| 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> { | |
| 122 | 137 | const issuer = parentIssuer(ctx.app); |
| 123 | 138 | if (issuer === undefined) return failure(ctx, "This forge has no parent to sign in through.", 404); |
| 124 | 139 | // 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> { | ||
| 139 | 154 | const state = rand(24); |
| 140 | 155 | const verifier = rand(48); |
| 141 | 156 | 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 }) }); | |
| 143 | 158 | const query = new URLSearchParams({ |
| 144 | 159 | response_type: "code", |
| 145 | 160 | client_id: client, |
| @@ -158,10 +173,6 @@ export async function parentStart(ctx: Ctx): Promise<Response> { | ||
| 158 | 173 | return new Response(null, { status: 303, headers }); |
| 159 | 174 | } |
| 160 | 175 | |
| 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 | ||
| 165 | 176 | export async function parentCallback(ctx: Ctx): Promise<Response> { |
| 166 | 177 | const q = ctx.url.searchParams; |
| 167 | 178 | const state = q.get("state") ?? ""; |
| @@ -207,17 +218,32 @@ export async function parentCallback(ctx: Ctx): Promise<Response> { | ||
| 207 | 218 | const sub = verified.value["sub"]; |
| 208 | 219 | if (typeof sub !== "string" || !SUB.test(sub)) |
| 209 | 220 | 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." })); | |
| 218 | 237 | } |
| 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; | |
| 221 | 247 | const session = createSession(ctx.app.db, user.id); |
| 222 | 248 | const done = redirect("/", sessionCookie(session.token, session.expiresAt, ctx.url, ctx.app.config.url)); |
| 223 | 249 | 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"; | ||
| 11 | 11 | import { toolbarComment, toolbarPage } from "../web/studio/toolbar.ts"; |
| 12 | 12 | import { TOOLBAR_NAME, toolbarResponse } from "../apps/toolbar.ts"; |
| 13 | 13 | import { unsealReleased } from "../actions/sealed.ts"; |
| 14 | import { parentCallback, parentStart } from "./rp.ts"; | |
| 14 | import { parentCallback, parentLink, parentStart } from "./rp.ts"; | |
| 15 | 15 | import { accessPage } from "../web/pages/access.ts"; |
| 16 | 16 | import { capacityPage, capacitySet } from "../web/pages/capacity.ts"; |
| 17 | 17 | import { systemPage, systemStream } from "../web/pages/system.ts"; |
| @@ -669,6 +669,7 @@ export function buildRouter(): Router<Handler> { | ||
| 669 | 669 | router.add("POST", "/signin", signinSubmit); |
| 670 | 670 | router.add("GET", "/signin/parent", parentStart); |
| 671 | 671 | router.add("GET", "/signin/parent/callback", parentCallback); |
| 672 | router.add("POST", "/settings/parent/link", parentLink); | |
| 672 | 673 | router.add("GET", "/signup", signupPage); |
| 673 | 674 | router.add("GET", "/verify", verifyPage); |
| 674 | 675 | router.add("POST", "/signup", signupSubmit); |
src/web/pages/account.ts +22
| @@ -9,6 +9,7 @@ | ||
| 9 | 9 | * has been read once. |
| 10 | 10 | */ |
| 11 | 11 | |
| 12 | import { parentIssuerOf } from "../../core/federation.ts"; | |
| 12 | 13 | import { resendVerification } from "../../actions/verify.ts"; |
| 13 | 14 | import { clientAddress } from "../../http/peer.ts"; |
| 14 | 15 | import { emailVerified } from "../../core/verify.ts"; |
| @@ -127,6 +128,22 @@ function notifyView(ctx: Ctx, error?: string): Html { | ||
| 127 | 128 | ); |
| 128 | 129 | } |
| 129 | 130 | |
| 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 |
||
| 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 | ======= | |
| 130 | 147 | /** open-platform.sh: linked as <login>, or not, with Link and Unlink. */ |
| 131 | 148 | function edgeLinkView(ctx: Ctx): Html { |
| 132 | 149 | const token = activeEdgeToken(ctx.app); |
| @@ -183,6 +200,7 @@ export async function edgeUnlink(ctx: Ctx): Promise<Response> { | ||
| 183 | 200 | return flashTo(ctx, "/settings", { message: "Unlinked." }); |
| 184 | 201 | } |
| 185 | 202 | |
| 203 | >>>>>>> origin/main | |
| 186 | 204 | /** Shown above the profile until the email is proven. */ |
| 187 | 205 | function unverifiedNotice(ctx: Ctx): Html { |
| 188 | 206 | const user = ctx.auth.user!; |
| @@ -303,7 +321,11 @@ export function accountPage(ctx: Ctx): Response { | ||
| 303 | 321 | ctx, |
| 304 | 322 | "profile", |
| 305 | 323 | "Settings", |
| 324 | <<<<<<< HEAD | |
| 325 | html`${pair}${profileView(ctx, currentProfile(ctx.auth.user))}${notifyView(ctx)}${parentLinkView(ctx) ?? ""}`, | |
| 326 | ======= | |
| 306 | 327 | html`${pair}${profileView(ctx, currentProfile(ctx.auth.user))}${edgeLinkView(ctx)}${notifyView(ctx)}`, |
| 328 | >>>>>>> origin/main | |
| 307 | 329 | 200, |
| 308 | 330 | // The everyday form makes its account with a passkey (#1890). |
| 309 | 331 | pair ? passkeyJs : undefined, |
src/web/pages/site.ts +35 −34
| @@ -28,6 +28,7 @@ import { activeEdgeToken, edgeIdentity, edgeLoginUrl, edgeStrangerLogin } from " | ||
| 28 | 28 | import { sshCommand } from "../../ssh/command.ts"; |
| 29 | 29 | import { hostOf, pageHead, signInFirst } from "../chrome.ts"; |
| 30 | 30 | import { SignupSlot, signupWindow } from "../../actions/signup-window.ts"; |
| 31 | import { getSignup } from "../../settings/signup.ts"; | |
| 31 | 32 | import { signinWindow } from "../../core/signin-window.ts"; |
| 32 | 33 | import { field, readForm } from "../form.ts"; |
| 33 | 34 | import { passkeyJs } from "../passkey-client.ts"; |
| @@ -243,9 +244,8 @@ function authForm( | ||
| 243 | 244 | // of the whole user table — and the sign-in screen paints on every session. |
| 244 | 245 | const firstAccount = kind === "signup" && !hasAnyUser(ctx.app.db); |
| 245 | 246 | |
| 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). | |
| 249 | 249 | // A newcomer the edge vouched for is already through it: no button to go |
| 250 | 250 | // round again, and the name is theirs alone. |
| 251 | 251 | const vouched = edgeStrangerLogin(ctx.request, activeEdgeToken(ctx.app), ctx.auth.user); |
| @@ -253,29 +253,11 @@ function authForm( | ||
| 253 | 253 | activeEdgeToken(ctx.app) === undefined || vouched !== undefined |
| 254 | 254 | ? undefined |
| 255 | 255 | : (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 | ||
| 273 | 256 | // No door makes a password-only account: sign-up is a name, an address and |
| 274 | 257 | // a passkey, made in the browser (`signup-passkey.ts`). |
| 275 | 258 | const byPasskey = kind === "signup" && ctx.app.config.passkeyOnlySignup === true; |
| 276 | 259 | |
| 277 | const body = html`${throughEdge} | |
| 278 | <form method="post" action="${action}"> | |
| 260 | const body = html`<form method="post" action="${action}"> | |
| 279 | 261 | ${formField({ |
| 280 | 262 | label: "Username", |
| 281 | 263 | name: "username", |
| @@ -372,25 +354,45 @@ function authForm( | ||
| 372 | 354 | const unowned = !hasAdmin(ctx.app.db); |
| 373 | 355 | const claimable = |
| 374 | 356 | 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. |
||
| 362 | ...(edge === undefined | |
| 363 | ? [] | |
| 364 | : [{ name: edge, href: edgeLoginUrl(next ?? "/") }]), | |
| 365 | ...(parent === undefined | |
| 366 | ? [] | |
| 367 | : [{ name: new URL(parent).host, href: "/signin/parent" }]), | |
| 368 | ]; | |
| 375 | 369 | return html`<div class="narrow"> |
| 376 | 370 | ${pageHead(kind === "signin" ? "Sign in" : "Create your account")} |
| 377 | ${card(body)} | |
| 378 | 371 | ${when( |
| 379 | 372 | 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> | |
| 382 | 375 | <span class="error-note small" id="passkey-signin-note" role="status"></span> |
outdated
This is a second filled primary on |
||
| 383 | 376 | <a class="small" href="/recover">Lost your device?</a> |
| 384 | 377 | </p>`, |
| 385 | 378 | )} |
| 386 | 379 | ${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 |
||
| 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. |
||
| 394 | ${linked.map((l) => btn(`Link an account from ${l.name}`, { href: l.href, variant: "outline" }))} | |
| 395 | </div>`, | |
outdated
For the parent, |
||
| 394 | 396 | )} |
| 395 | 397 | ${claimable |
| 396 | 398 | ? html`<p class="muted small mt" id="claim-door"> |
| @@ -463,8 +465,7 @@ export function signinAllowed(ctx: Ctx, key: string): number | undefined { | ||
| 463 | 465 | |
| 464 | 466 | /** |
| 465 | 467 | * 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. | |
| 468 | 469 | */ |
| 469 | 470 | export function signupAllowed(ctx: Ctx): number | undefined { |
| 470 | 471 | 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", () => { | ||
| 175 | 175 | r.text(), |
| 176 | 176 | ); |
| 177 | 177 | 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"); | |
| 179 | 179 | expect(page).toContain("have no password here"); |
| 180 | 180 | // The password form is still there for an account that was given one. |
| 181 | 181 | 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", () => { | ||
| 103 | 103 | |
| 104 | 104 | test("only a forge with a parent offers the button", async () => { |
| 105 | 105 | 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}`); | |
| 107 | 107 | 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"'); | |
| 109 | 110 | const none = await fetch(`${parentServers.url}/signin/parent`, { redirect: "manual" }); |
| 110 | 111 | expect(none.status).toBe(404); |
| 111 | 112 | }); |
| 112 | 113 | |
| 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 | ||
| 113 | 211 | test("a person signs into the child through the parent, and the account keys on sub", async () => { |
| 114 | 212 | const { callback, state } = await begin(aliceCookie); |
| 115 | 213 | expect(callback.origin).toBe(childServers.url); |
| @@ -205,11 +303,9 @@ describe("sign in through the parent forge", () => { | ||
| 205 | 303 | if (!local.ok) throw new Error(local.error); |
| 206 | 304 | const { callback, state } = await begin(`forge_session=${createSession(parent.db, bob.value.id).token}`); |
| 207 | 305 | 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 }); | |
| 213 | 309 | }); |
| 214 | 310 | |
| 215 | 311 | 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 @@ | ||
| 1 | 1 | /** |
| 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`. | |
| 5 | 5 | */ |
| 6 | 6 | import { afterAll, beforeAll, expect, test } from "bun:test"; |
| 7 | 7 | import { mkdtemp, rm } from "node:fs/promises"; |
| @@ -71,25 +71,20 @@ afterAll(async () => { | ||
| 71 | 71 | for (const dir of dirs) await rm(dir, { recursive: true, force: true }); |
| 72 | 72 | }); |
| 73 | 73 | |
| 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 () => { | |
| 77 | 76 | 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(""); | |
| 80 | 82 | 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 }); | |
| 82 | 85 | }); |
| 83 | 86 | } |
| 84 | 87 | |
| 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 | ||
| 93 | 88 | /** Each place in `src` that makes an account, and the origin it says. */ |
| 94 | 89 | async function callers(): Promise<Record<string, string[]>> { |
| 95 | 90 | const found: Record<string, string[]> = {}; |
| @@ -120,7 +115,6 @@ test("every caller of createUser says where its account comes from", async () => | ||
| 120 | 115 | "src/actions/spawn.ts": ["spawn", "spawn"], |
| 121 | 116 | "src/actions/users.ts": ["signup", "passkey"], |
| 122 | 117 | "src/chaos/world.ts": ["seed"], |
| 123 | "src/core/federation.ts": ["parent"], | |
| 124 | 118 | "src/web/pages/claim.ts": ["claim"], |
| 125 | 119 | "src/web/pages/everyday.ts": ["everyday"], |
| 126 | 120 | }); |
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: |
||
| 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 | }); |
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.