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

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

Closed opened this
Closed without merging

mason/forge:mason/1618-passkeys-part-2-sign-up-takes-a-passkey → main 11 commits fork 5 threads · 5 unresolved

  • Closed without merging. Nothing was applied to main.

Review

Sign in to review this change.
104 files changed +1691 −846
README.md +11 −13
@@ -53,17 +53,17 @@ refuses every form a browser posts to `localhost`: run it with
5353 `env -u FORGE_URL bun run src/main.ts`, or set `FORGE_URL` to wherever you
5454 will actually browse it.
5555
56 The first account you create becomes the admin — from the browser, the API, or
57 a terminal (`ssh -p 2222 localhost` on a fresh forge offers to create it). Then:
56 The first account you create becomes the admin. Sign up at `/signup` in a
57 browser: a new account is made with a passkey and an email, never with only a
58 password, so neither the API (`POST /api/v1/users` answers
59 `passkey_required`) nor the terminal creates accounts. Accounts made before
60 that still sign in with their password, and Settings invites them to add a
61 passkey. A verified email recovers: `/recover` mails a one-hour, single-use
62 link that registers a new passkey. Then:
5863
5964 ```sh
60 # mint a token, create a repo, push to it
61 curl -sX POST localhost:3000/api/v1/users \
62 -d '{"username":"you","email":"[email protected]","password":"a-good-passphrase"}'
63
64 TOKEN=$(curl -sX POST localhost:3000/api/v1/tokens \
65 -d '{"username":"you","password":"a-good-passphrase","name":"cli","scope":"rw"}' \
66 | grep -o '"token":"[^"]*"' | cut -d'"' -f4)
65 # mint a token at /settings/tokens, then create a repo and push to it
66 TOKEN=...
6767
6868 curl -sX POST localhost:3000/api/v1/repos -H "authorization: Bearer $TOKEN" \
6969 -d '{"name":"hello","visibility":"public"}'
@@ -160,10 +160,8 @@ mail is sent and a newcomer waits for the owner to verify them. With
160160 boot with only the secret), `/signup` renders the Turnstile widget, its CSP
161161 allows `https://challenges.cloudflare.com`, and signup asks Cloudflare's
162162 siteverify about the posted `cf-turnstile-response` (API: `turnstile_token`),
163 refusing a missing or bad token before it hashes a password or makes an
164 account. Unset, signup is open. The terminal (SSH) cannot show a widget, so
165 with Turnstile on it can create only the first account (the admin); everyone
166 else is told to sign up on the web page. Accounts made through the platform edge are not checked. Behind a
163 refusing a missing or bad token before it makes an account. Unset, signup is
164 open. Accounts made through the platform edge are not checked. Behind a
167165 proxy, `FORGE_TRUSTED_PROXIES` (comma-separated CIDR ranges, e.g.
168166 `10.42.0.0/16` for a k3s ingress) names the proxies allowed to say who the
169167 client is; limits for strangers and the signup audit then see each outside
scripts/gate.ts +1
@@ -49,6 +49,7 @@ export const GATE: readonly string[] = [
4949 "test/thoughts.test.ts",
5050 "test/triage.test.ts",
5151 "test/passkeys.test.ts",
52 "test/signup-passkey.test.ts",
5253 "test/webauthn.test.ts",
5354 "test/chaos.test.ts",
5455 "test/flow-stage.test.ts",
src/actions/recovery.ts added +106
@@ -0,0 +1,106 @@
1 /**
2 * Recovering an account that lost its passkeys. A proven address may be
3 * sent a link (`core/recovery.ts`): time-limited and single-use. Following
4 * it registers a new passkey for the account, and nothing else — the
5 * account's other passkeys, sessions and password are left as they are.
6 */
7
8 import type { App } from "../app.ts";
9 import type { Credential } from "../auth/webauthn.ts";
10 import { addPasskey } from "../core/passkeys.ts";
11 import {
12 consumeRecovery,
13 issueRecovery,
14 recoveryAccount,
15 } from "../core/recovery.ts";
16 import { getUserByEmail, getUserById, isActive, type User } from "../core/users.ts";
17 import { emailVerified } from "../core/verify.ts";
18 import { err, ok, type Result } from "../kernel/result.ts";
19 import { mayMail, sendCapped } from "./mail.ts";
20 import { mailerOf, tokenUrl } from "./verify.ts";
21
22 /** A person who may be recovered: active, signs in, address proven. */
23 function recoverable(app: App, user: User | undefined): user is User {
24 return (
25 user !== undefined &&
26 user.kind === "user" &&
27 isActive(user) &&
28 emailVerified(app.db, user.id)
29 );
30 }
31
32 /**
33 * Send a recovery link to the account at `email`, if there is one whose
34 * address is proven. The caller says the same thing whatever comes back —
35 * "nobody" included — so the answer never tells a stranger who has an
36 * account; the outcome is for the log and the tests.
37 */
38 export async function sendRecovery(
39 app: App,
40 email: string,
41 now: number = Date.now(),
42 ): Promise<"sent" | "nobody" | "too_soon" | "no_mail" | "capped" | "failed"> {
43 const user = getUserByEmail(app.db, email.trim());
44 if (!recoverable(app, user)) return "nobody";
45 const mailer = mailerOf(app, user);
46 if (mailer === undefined) {
47 app.log.warn("mail is not configured; a recovery link was not sent", {
48 user: user.username,
49 });
50 return "no_mail";
51 }
52 if (!mayMail(app, user.email, now)) return "capped";
53 const token = issueRecovery(app.db, user.id, now);
54 if (token === undefined) return "too_soon";
55 const outcome = await sendCapped(app, mailer, {
56 to: user.email,
57 subject: "Add a new passkey to your forge account",
58 text: [
59 `Hello ${user.username},`,
60 "",
61 "Someone asked to recover this account. Follow this link to add a new passkey. It works once, for an hour:",
62 "",
63 tokenUrl(app, "/recover", token),
64 "",
65 "If it was not you, ignore this message: nothing changes until the link is followed.",
66 ].join("\n"),
67 }, now);
68 if (outcome === "failed")
69 app.log.warn("a recovery link could not be sent", { user: user.username });
70 return outcome;
71 }
72
73 /** The account a live link would recover, without spending the link. */
74 export function recoveryFor(
75 app: App,
76 token: string,
77 now: number = Date.now(),
78 ): Result<User, "invalid"> {
79 const userId = recoveryAccount(app.db, token, now);
80 const user = userId === undefined ? undefined : getUserById(app.db, userId);
81 return recoverable(app, user) ? ok(user) : err("invalid");
82 }
83
84 /**
85 * Spend the link and keep the passkey the browser just registered for it
86 * (verified by the adapter, `auth/webauthn.ts`). `invalid` for a link that
87 * is used, expired or never was.
88 */
89 export function recover(
90 app: App,
91 token: string,
92 passkey: { name: string; credential: Credential },
93 now: number = Date.now(),
94 ): Result<User, "invalid" | "too_many" | "duplicate"> {
95 const userId = consumeRecovery(app.db, token, now);
96 const user = userId === undefined ? undefined : getUserById(app.db, userId);
97 if (!recoverable(app, user)) return err("invalid");
98 const added = addPasskey(app.db, user.id, passkey.name, passkey.credential);
99 if (!added.ok) return added;
100 app.bus.append({
101 kind: "account.recovered",
102 actorId: user.id,
103 payload: { passkeyId: added.value },
104 });
105 return ok(user);
106 }
src/actions/users.ts +53 −26
@@ -11,6 +11,8 @@ import {
1111 parseAuthorizedKey,
1212 type UserKey,
1313 } from "../core/keys.ts";
14 import type { Credential } from "../auth/webauthn.ts";
15 import { addPasskey, findPasskey } from "../core/passkeys.ts";
1416 import { turnstileVerifier } from "../core/turnstile.ts";
1517 import { reservedName } from "../core/reserved.ts";
1618 import { setUserSetting } from "../core/settings.ts";
@@ -23,7 +25,6 @@ import {
2325 changePassword as rehash,
2426 cleanDisplayName,
2527 createUser,
26 hasAnyUser,
2728 updateProfile as writeProfile,
2829 verifyPassword,
2930 type CreateUserError,
@@ -31,54 +32,80 @@ import {
3132 type UpdateProfileError,
3233 type User,
3334 } from "../core/users.ts";
35 import { defect } from "../kernel/error.ts";
3436 import { err, ok, type Result } from "../kernel/result.ts";
3537 import { requireUser } from "./access.ts";
3638
3739 export interface SignUpInput {
3840 username: string;
3941 email: string;
40 password: string;
41 /** The Turnstile token the browser's widget gave; read only when a secret is set. */
42 humanToken?: string;
42 /**
43 * The passkey the browser just registered, already verified by the
44 * adapter (`auth/webauthn.ts`). A new account has no password (#1618):
45 * this is how it signs in, and a proven email is how it recovers.
46 */
47 passkey: { name: string; credential: Credential };
4348 }
4449
45 export type SignUpError = CreateUserError | "human_check";
50 /** No password is asked for, so none can be too weak. */
51 export type SignUpError = Exclude<CreateUserError, "weak_password"> | "passkey_taken";
4652
4753 /** What a person is told when the check fails. */
4854 export const HUMAN_CHECK_MESSAGE =
4955 "We could not tell you are a person. Reload the page and try again.";
5056
57 /**
58 * Whether the one asking is a person: the Turnstile token the browser's
59 * widget gave, put to Cloudflare. Always yes when the forge has no secret.
60 * A token answers once, so a sign-up asks at its first step — before the
61 * forge says whether a name or address is free — and the challenge that
62 * step issues is the proof from then on (`web/pages/site.ts`).
63 */
64 export async function isHuman(
65 app: App,
66 token: string,
67 address?: string,
68 ): Promise<boolean> {
69 const secret = app.config.turnstileSecret;
70 if (secret === undefined) return true;
71 const verify = app.config.verifyHuman ?? turnstileVerifier(secret);
72 return verify(token, address);
73 }
74
5175 /**
5276 * The first account on a fresh forge is the admin — no setup wizard. A name
5377 * the crew, the owner or the forge itself answers to is not free
54 * (`core/reserved.ts`).
78 * (`core/reserved.ts`). Every new account is made with a passkey and an
79 * email; none with only a password, on any surface.
5580 */
5681 export async function signUp(
5782 app: App,
5883 input: SignUpInput,
5984 /** Where the request came from, for the owner's audit of who joined. */
60 from: {
61 address?: string | undefined;
62 /**
63 * The terminal cannot render a widget, so it is let past the Turnstile
64 * check for the first account only (the bootstrap admin); once anyone
65 * exists, the terminal is asked like everyone else and, having no
66 * token, is refused: sign up on the web page.
67 */
68 door?: "terminal";
69 } = {},
85 from: { address?: string | undefined } = {},
7086 ): Promise<Result<User, SignUpError>> {
71 const secret = app.config.turnstileSecret;
72 const bootstrap = from.door === "terminal" && !hasAnyUser(app.db);
73 if (secret !== undefined && !bootstrap) {
74 const verify = app.config.verifyHuman ?? turnstileVerifier(secret);
75 // Before a password is hashed or a row is written.
76 if (!(await verify(input.humanToken ?? "", from.address)))
77 return err("human_check");
87 const { credential } = input.passkey;
88 if (findPasskey(app.db, credential.id) !== undefined)
89 return err("passkey_taken");
90 const created = await createUser(app.db, {
91 username: input.username,
92 email: input.email,
93 adminIfFirst: true,
94 });
95 if (!created.ok) {
96 // No password was given: only a defect lands here.
outdated

Low: await createUser(...) sits between the findPasskey check and here, so "nothing awaited since" is not true. Also, an account row is left behind with neither a password nor a passkey when defect fires. Do the user insert and addPasskey in one transaction, or fix the comment.

97 if (created.error === "weak_password")
98 defect("signup_password", "an account made without a password was refused one");
99 return err(created.error);
100 }
101 const added = addPasskey(app.db, created.value.id, input.passkey.name, credential);
102 if (!added.ok) {
103 // A new account has no passkeys, so only "duplicate" lands here: another
104 // sign-up kept this one while createUser was awaited. The account goes
105 // with it, so none is left with no way to sign in.
106 app.db.query("DELETE FROM user WHERE id = ?1").run(created.value.id);
107 return err("passkey_taken");
78108 }
79 const { humanToken: _token, ...account } = input;
80 const created = await createUser(app.db, { ...account, adminIfFirst: true });
81 if (!created.ok) return created;
82109 app.bus.append({
83110 kind: "user.created",
84111 actorId: created.value.id,
src/actions/verify.ts +5 −4
@@ -53,7 +53,7 @@ export function mailConfigured(app: App): boolean {
5353 return MAIL_SECRETS.every((name) => set.has(name));
5454 }
5555
56 function mailerOf(app: App, forUser: User): Mailer | undefined {
56 export function mailerOf(app: App, forUser: User): Mailer | undefined {
5757 if (app.config.mailer !== undefined) return app.config.mailer;
5858 const stored = resolveSecrets(
5959 app.db,
@@ -70,9 +70,10 @@ function mailerOf(app: App, forUser: User): Mailer | undefined {
7070 return config === undefined ? undefined : (mail) => sendMail(config, mail);
7171 }
7272
73 function verifyUrl(app: App, token: string): string {
73 /** A one-time link on the forge's public address: `/verify`, `/recover`. */
74 export function tokenUrl(app: App, path: string, token: string): string {
7475 const base = app.config.url ?? `http://localhost:${app.config.port}`;
75 return `${new URL("/verify", base).toString()}?token=${token}`;
76 return `${new URL(path, base).toString()}?token=${token}`;
7677 }
7778
7879 /**
@@ -97,7 +98,7 @@ export async function sendVerification(
9798 if (!mayMail(app, user.email, now)) return "capped";
9899 const token = issueLink(app.db, user.id, user.email, now);
99100 if (token === undefined) return "too_soon";
100 const link = verifyUrl(app, token);
101 const link = tokenUrl(app, "/verify", token);
101102 const outcome = await sendCapped(app, mailer, {
102103 to: user.email,
103104 subject: "Verify your email for the forge",
src/core/recovery.ts added +82
@@ -0,0 +1,82 @@
1 /**
2 * Recovery links: how a person who lost every passkey registers a new one.
3 * A link goes only to a proven address (`actions/recovery.ts` decides that);
4 * this is what is kept. One live link per account, its secret stored only
5 * as a hash; it expires, and following it deletes it, so it works once.
6 */
7
8 import type { Database } from "bun:sqlite";
9 import { sha256 } from "../kernel/hash.ts";
10
11 /** How long a link works: long enough to reach a mailbox, short enough to go stale. */
12 export const RECOVERY_TTL_MS = 60 * 60_000;
13 /** How soon another link may be sent to the same account. */
14 export const RECOVERY_RESEND_MS = 5 * 60_000;
15
16 const secret = (): string =>
17 Buffer.from(crypto.getRandomValues(new Uint8Array(32))).toString("base64url");
18
19 /**
20 * Mint a link for the account, replacing any older one: the secret is
21 * returned once. Undefined inside the resend window, so asking again and
22 * again cannot turn the forge into a way to flood a mailbox.
23 */
24 export function issueRecovery(
25 db: Database,
26 userId: string,
27 now: number,
28 ): string | undefined {
29 const row = db
30 .query<{ sent_at: string }, [string]>(
31 "SELECT sent_at FROM recovery_link WHERE user_id = ?1",
32 )
33 .get(userId);
34 if (row && now - Date.parse(row.sent_at) < RECOVERY_RESEND_MS) return undefined;
35 const token = secret();
36 db.query(
37 `INSERT INTO recovery_link (user_id, token_hash, expires_at, sent_at)
38 VALUES (?1, ?2, ?3, ?4)
39 ON CONFLICT(user_id) DO UPDATE SET token_hash = excluded.token_hash,
40 expires_at = excluded.expires_at, sent_at = excluded.sent_at`,
41 ).run(
42 userId,
43 sha256(token),
44 new Date(now + RECOVERY_TTL_MS).toISOString(),
45 new Date(now).toISOString(),
46 );
47 return token;
48 }
49
50 /** The account a live link is for, without spending it. */
51 export function recoveryAccount(
52 db: Database,
53 token: string,
54 now: number,
55 ): string | undefined {
56 if (token === "") return undefined;
57 const row = db
58 .query<{ user_id: string; expires_at: string }, [string]>(
59 "SELECT user_id, expires_at FROM recovery_link WHERE token_hash = ?1",
60 )
61 .get(sha256(token));
62 if (row === null || Date.parse(row.expires_at) <= now) return undefined;
63 return row.user_id;
64 }
65
66 /**
67 * Spend a link: the account it was for, once, while it is fresh. The read
68 * and the delete are one statement, so two racing uses cannot both win.
69 */
70 export function consumeRecovery(
71 db: Database,
72 token: string,
73 now: number,
74 ): string | undefined {
75 if (token === "") return undefined;
76 const row = db
77 .query<{ user_id: string }, [string, string]>(
78 "DELETE FROM recovery_link WHERE token_hash = ?1 AND expires_at > ?2 RETURNING user_id",
79 )
80 .get(sha256(token), new Date(now).toISOString());
81 return row?.user_id;
82 }
src/core/reserved.ts +1
@@ -86,6 +86,7 @@ export const SYSTEM_NAMES: readonly string[] = [
8686 "og",
8787 "organizations",
8888 "origins",
89 "recover",
8990 "robots.txt",
9091 "llms.txt",
9192 "runs",
src/core/users.ts +59 −21
@@ -145,6 +145,40 @@ export interface CreateUserInput {
145145 reservedSelf?: string;
146146 }
147147
148 /**
149 * Why a new account could not have this name and address, or undefined when
150 * it could. Asked by `createUser`, and by sign-up before the browser makes a
151 * passkey for an account that would then be refused.
152 */
153 export function accountClash(
154 db: Database,
155 input: Pick<
156 CreateUserInput,
157 "username" | "email" | "agent" | "allowReserved" | "reservedSelf"
158 >,
159 ): Exclude<CreateUserError, "weak_password"> | undefined {
160 if (!isSafeName(input.username)) return "invalid_username";
161 const existing = db
162 .query<
163 { username: string; email: string },
164 [string, string]
165 >("SELECT username, email FROM user WHERE username = ?1 OR email = ?2")
166 .get(input.username, input.email);
167 if (existing) {
168 return existing.username.toLowerCase() === input.username.toLowerCase()
169 ? "username_taken"
170 : "email_taken";
171 }
172 // Taken is said first; only a name nobody holds can be a reserved one.
173 if (
174 input.agent !== true &&
175 input.allowReserved !== true &&
176 reservedName(db, input.username, input.reservedSelf) !== undefined
177 )
178 return "username_reserved";
179 return undefined;
180 }
181
148182 export async function createUser(
149183 db: Database,
150184 input: CreateUserInput,
@@ -154,27 +188,8 @@ export async function createUser(
154188 const password = agent ? undefined : input.password;
155189 if (password !== undefined && password.length < MIN_PASSWORD)
156190 return err("weak_password");
157
158 const existing = db
159 .query<
160 { username: string; email: string },
161 [string, string]
162 >("SELECT username, email FROM user WHERE username = ?1 OR email = ?2")
163 .get(input.username, input.email);
164 if (existing) {
165 return err(
166 existing.username.toLowerCase() === input.username.toLowerCase()
167 ? "username_taken"
168 : "email_taken",
169 );
170 }
171 // Taken is said first; only a name nobody holds can be a reserved one.
172 if (
173 !agent &&
174 input.allowReserved !== true &&
175 reservedName(db, input.username, input.reservedSelf) !== undefined
176 )
177 return err("username_reserved");
191 const clash = accountClash(db, input);
192 if (clash !== undefined) return err(clash);
178193
179194 const userId = id();
180195 // An account without a password has an empty hash, which no verifier
@@ -296,6 +311,29 @@ export function getUserById(db: Database, userId: string): User | undefined {
296311 return row ? toUser(row) : undefined;
297312 }
298313
314 /** The account an address belongs to, case aside; an exact match first. */
315 export function getUserByEmail(db: Database, email: string): User | undefined {
316 const row = db
317 .query<UserRow, [string]>("SELECT * FROM user WHERE email = ?1 COLLATE NOCASE ORDER BY email = ?1 DESC LIMIT 1")
318 .get(email);
319 return row ? toUser(row) : undefined;
320 }
321
322 /**
323 * Whether the account signs in with a password: one made before sign-up
324 * took a passkey (#1618). An account the edge, a claim or sign-up made has
325 * none.
326 */
327 export function hasPassword(db: Database, userId: string): boolean {
328 return (
329 db
330 .query<{ n: number }, [string]>(
331 "SELECT count(*) AS n FROM user WHERE id = ?1 AND kind = 'user' AND password_hash != ''",
332 )
333 .get(userId)!.n > 0
334 );
335 }
336
299337 export function getUserByName(
300338 db: Database,
301339 username: string,
src/http/api.ts +11 −23
@@ -141,8 +141,6 @@ import {
141141 createToken,
142142 deleteSshKey,
143143 deleteToken,
144 HUMAN_CHECK_MESSAGE,
145 signUp,
146144 updateProfile,
147145 } from "../actions/users.ts";
148146 import { listEvents } from "../core/events.ts";
@@ -365,7 +363,7 @@ import { frontInput, frontJson, setFront } from "../actions/front.ts";
365363 import { COPIES_PER_DAY, makeItYours } from "../actions/make_it_yours.ts";
366364 import { passportRoutes } from "./passport_edge.ts";
367365 import type { Router } from "./router.ts";
368 import { clientAddress, clientBucket } from "./peer.ts";
366 import { clientBucket } from "./peer.ts";
369367 import { manifestFor } from "../actions/here.ts";
370368 import {
371369 acceptReport,
@@ -1120,26 +1118,16 @@ export function apiRoutes(router: Router<Handler>): void {
11201118 passportRoutes(router);
11211119 // ── accounts ─────────────────────────────────────────────────────────
11221120
1123 router.add("POST", "/api/v1/users", async (ctx) => {
1124 // Anyone may call this, so its body is a stranger's (`http/limits.ts`).
1125 const input = await boundedBody(ctx.request, STRANGER_MAX);
1126 if (input === "too_large")
1127 return apiError("too_large", 413, `at most ${STRANGER_MAX} bytes`);
1128 const created = await signUp(
1129 ctx.app,
1130 {
1131 username: str(input.username),
1132 email: str(input.email),
1133 password: str(input.password),
1134 humanToken: str(input.turnstile_token),
1135 },
1136 { address: clientAddress(ctx.request) },
1137 );
1138 if (!created.ok && created.error === "human_check")
1139 return apiError("human_check", 422, HUMAN_CHECK_MESSAGE);
1140 if (!created.ok) return json({ error: created.error }, 422);
1141 return json(publicUser(created.value), 201);
1142 });
1121 // A new account is made with a passkey (#1618), and a passkey is made by a
1122 // person's browser or device, not by an API client: there is no way to
1123 // sign up here, only the word on where to.
1124 router.add("POST", "/api/v1/users", () =>
1125 apiError(
1126 "passkey_required",
1127 422,
1128 "a new account needs a passkey: sign up at /signup in a browser",
1129 ),
1130 );
11431131
11441132 router.add("GET", "/api/v1/users/:username", (ctx) => {
11451133 const user = getUserByName(ctx.app.db, ctx.params.username!);
src/http/server.ts +12
@@ -90,6 +90,7 @@ import {
9090 signinPage,
9191 signinSubmit,
9292 signupPage,
93 signupOptions,
9394 signupSubmit,
9495 verifyPage,
9596 themeSubmit,
@@ -102,6 +103,12 @@ import {
102103 signinOptions,
103104 signinPasskey,
104105 } from "../web/pages/passkeys.ts";
106 import {
107 recoverOptions,
108 recoverPageGet,
109 recoverPasskey,
110 recoverSubmit,
111 } from "../web/pages/recover.ts";
105112 import { confirmPage, searchPage } from "../web/pages/search.ts";
106113 import { followingSubmit } from "../web/pages/following.ts";
107114 import { reconnectSubmit } from "../web/pages/frozen.ts";
@@ -685,6 +692,11 @@ export function buildRouter(): Router<Handler> {
685692 router.add("POST", "/settings/passkeys/:id/delete", passkeyDelete);
686693 router.add("POST", "/signin/passkey/options", signinOptions);
687694 router.add("POST", "/signin/passkey", signinPasskey);
695 router.add("POST", "/signup/passkey/options", signupOptions);
696 router.add("GET", "/recover", recoverPageGet);
697 router.add("POST", "/recover", recoverSubmit);
698 router.add("POST", "/recover/passkey/options", recoverOptions);
699 router.add("POST", "/recover/passkey", recoverPasskey);
688700 // The crew: a forge admin's section, hidden from everyone else.
689701 router.add("GET", "/settings/subscriptions", subscriptionsPage);
690702 router.add("POST", "/settings/subscriptions", subscriptionAdd);
src/tui/screens/signin.ts +14 −57
@@ -4,11 +4,11 @@
44 * same connection is that user. No reconnect, and no impersonation: the only
55 * account a session can take on is one whose password was just verified.
66 *
7 * On a forge with no users at all, the same screen creates the first account,
8 * which is the admin — the terminal equivalent of the web's first-run signup.
7 * Nobody signs up here: a new account is made with a passkey (#1618), and a
8 * terminal cannot make one. On a forge with no users at all the screen says
9 * where the first account, the admin, is made instead.
910 */
1011
11 import { signUp } from "../../actions/users.ts";
1212 import { hasAnyUser } from "../../core/users.ts";
1313 import type { Ctx, Screen } from "../app/app.ts";
1414 import { binding } from "../app/keys.ts";
@@ -30,23 +30,16 @@ const SIGN_IN: Field[] = [
3030 { label: "Password", secret: true, hint: "Your key is linked on success." },
3131 ];
3232
33 const CREATE: Field[] = [
34 { label: "Username" },
35 { label: "Email" },
36 { label: "Password", secret: true, hint: "At least 10 characters." },
37 ];
38
3933 export function signInScreen(f: Session, ctx: Ctx, onDone: () => void): Screen {
4034 // "Is this forge empty?" is a existence question, not a count: `COUNT(*)`
4135 // walks the whole user table on the one screen every session paints.
4236 const first = !hasAnyUser(f.db);
43 let mode: "signin" | "create" = first ? "create" : "signin";
44 let values = ["", "", ""];
37 const values = ["", ""];
4538 let focus = 0;
4639 let error: string | undefined;
4740 let busy = false;
4841
49 const fields = (): Field[] => (mode === "create" ? CREATE : SIGN_IN);
42 const fields = (): Field[] => SIGN_IN;
5043
5144 const submit = (): void => {
5245 if (busy) return;
@@ -54,36 +47,11 @@ export function signInScreen(f: Session, ctx: Ctx, onDone: () => void): Screen {
5447 error = undefined;
5548 runAsync(ctx, async () => {
5649 try {
57 if (mode === "create") {
58 const [username, email, password] = values as [
59 string,
60 string,
61 string,
62 ];
63 const created = await signUp(
64 f.app,
65 { username, email, password },
66 {
67 address: f.identity.remoteAddress,
68 ...(first ? { door: "terminal" as const } : {}),
69 },
70 );
71 if (!created.ok) {
72 error = errorText(created.error);
73 return;
74 }
75 const adopted = f.adopt(created.value);
76 if (!adopted.ok) {
77 error = errorText(adopted.error);
78 return;
79 }
80 } else {
81 const [username, password] = values as [string, string, string];
82 const signedIn = await f.signIn(username, password);
83 if (!signedIn.ok) {
84 error = errorText(signedIn.error);
85 return;
86 }
50 const [username, password] = values as [string, string];
51 const signedIn = await f.signIn(username, password);
52 if (!signedIn.ok) {
53 error = errorText(signedIn.error);
54 return;
8755 }
8856 ctx.toast(`signed in as ${f.user?.username ?? ""}`, "success");
8957 onDone();
@@ -96,26 +64,22 @@ export function signInScreen(f: Session, ctx: Ctx, onDone: () => void): Screen {
9664 };
9765
9866 return {
99 title: mode === "create" ? "Create account" : "Sign in",
67 title: "Sign in",
10068 keys: [
10169 binding(["tab"], "next field"),
102 binding(["enter"], mode === "create" ? "create" : "sign in"),
103 binding(["ctrl+t"], first ? "sign in instead" : "create account"),
70 binding(["enter"], "sign in"),
10471 binding(["esc"], "back"),
10572 ],
10673 render(area, s) {
10774 const c = ctx.theme.c;
10875 const [head, body] = split(area, "v", [len(2), fill(1)]);
109 segmented(s, head!, c, {
110 items: ["Sign in", "Create account"],
111 active: mode === "create" ? 1 : 0,
112 });
76 segmented(s, head!, c, { items: ["Sign in"], active: 0 });
11377 s.text(
11478 head!.x,
11579 head!.y + 1,
11680 truncate(
11781 first
118 ? "This forge has no accounts yet — the first one is the admin."
82 ? "This forge has no accounts yet. Make the first, the admin, in a browser at /signup."
11983 : `Connected from ${f.identity.remoteAddress} with ${f.identity.fingerprint ?? "no key"}`,
12084 head!.w,
12185 ),
@@ -151,13 +115,6 @@ export function signInScreen(f: Session, ctx: Ctx, onDone: () => void): Screen {
151115 ctx.setCursor(cursor);
152116 },
153117 key(e) {
154 if (e.ctrl && e.key === "t") {
155 mode = mode === "create" ? "signin" : "create";
156 values = ["", "", ""];
157 focus = 0;
158 error = undefined;
159 return true;
160 }
161118 if (
162119 e.key === "tab" ||
163120 (e.key === "enter" && focus < fields().length - 1)
src/web/pages/account.ts +23 −2
@@ -9,6 +9,7 @@
99 * has been read once.
1010 */
1111
12 import { passkeyIds } from "../../core/passkeys.ts";
1213 import { resendVerification } from "../../actions/verify.ts";
1314 import { emailVerified } from "../../core/verify.ts";
1415 import {
@@ -30,7 +31,7 @@ import { listKeys } from "../../core/keys.ts";
3031 import { endAccountSession } from "../../actions/signins.ts";
3132 import { listSessions, type SessionInfo } from "../../core/sessions.ts";
3233 import { listTokens, type TokenScope } from "../../core/tokens.ts";
33 import type { CommitEmail, User } from "../../core/users.ts";
34 import { hasPassword, type CommitEmail, type User } from "../../core/users.ts";
3435 import { cookieValue, type Ctx } from "../../http/context.ts";
3536 import { sshCommand } from "../../ssh/command.ts";
3637 import {
@@ -158,9 +159,29 @@ export async function resendVerifyLink(ctx: Ctx): Promise<Response> {
158159 return flashTo(ctx, "/settings", { message });
159160 }
160161
162 /**
163 * An account that still signs in with only a password — one made before
164 * sign-up took a passkey (#1618) — is asked to add one. Password sign-in
165 * goes when nobody needs it (see `signinSubmit`, `web/pages/site.ts`).
166 */
167 function passkeyInvite(ctx: Ctx): Html {
168 const user = ctx.auth.user!;
169 if (!hasPassword(ctx.app.db, user.id) || passkeyIds(ctx.app.db, user.id).length > 0)
170 return html``;
171 return card(
172 html`<p id="passkey-invite">
173 You sign in with a password. Add a passkey: it signs you in with a
174 fingerprint, face or device PIN, cannot be phished, and is how
175 accounts sign in from now on.
176 </p>
177 ${btn("Add a passkey", { href: "/settings/passkeys", variant: "primary" })}`,
178 { tone: "attn" },
179 );
180 }
181
161182 function profileView(ctx: Ctx, values: ProfileForm): Html {
162183 const user = ctx.auth.user!;
163 return html`${unverifiedNotice(ctx)}${card(
184 return html`${unverifiedNotice(ctx)}${passkeyInvite(ctx)}${card(
164185 html`<form method="post" action="/settings">
165186 <div class="field">
166187 <label for="f-username">Username</label>
src/web/pages/passkeys.ts +13 −36
@@ -6,8 +6,7 @@
66 * same-origin checked, and a challenge answers once.
77 */
88
9 import { challenges, verifyAssertion, verifyRegistration } from "../../auth/webauthn.ts";
10 import type { App } from "../../app.ts";
9 import { verifyAssertion } from "../../auth/webauthn.ts";
1110 import {
1211 addPasskey,
1312 findPasskey,
@@ -28,23 +27,11 @@ import { readForm } from "../form.ts";
2827 import { html } from "../html.ts";
2928 import { flashTo } from "../layout.ts";
3029 import { passkeyJs } from "../passkey-client.ts";
30 import { creationOptions, registered, relying, store } from "../passkey-ceremony.ts";
3131 import { card, empty, confirmAction, time } from "../ui.ts";
3232 import { accountShell } from "./account.ts";
3333 import { safeNext, sessionCookie, signinAllowed } from "./site.ts";
3434
35 /** One-time challenges, one store per ceremony per forge. */
36 const stores = new WeakMap<App, { add: ReturnType<typeof challenges>; signin: ReturnType<typeof challenges> }>();
37 function store(app: App) {
38 let s = stores.get(app);
39 if (!s) stores.set(app, (s = { add: challenges(), signin: challenges() }));
40 return s;
41 }
42
43 /** What the browser must see as the relying party: the forge's public address. */
44 function relying(ctx: Ctx) {
45 return { origin: ctx.url.origin, rpId: ctx.url.hostname };
46 }
47
4835 const refuse = (status: number, message: string) =>
4936 json({ error: "refused", message }, status);
5037
@@ -104,17 +91,14 @@ export function passkeyOptions(ctx: Ctx): Response {
10491 const denied = sessionOnly(ctx);
10592 if (denied) return denied;
10693 const user = ctx.auth.user!;
107 return json({
108 challenge: store(ctx.app).add.issue(),
109 rpId: relying(ctx).rpId,
110 rpName: "forge",
111 user: {
112 id: Buffer.from(user.id).toString("base64url"),
113 name: user.username,
114 displayName: user.displayName || user.username,
115 },
116 exclude: passkeyIds(ctx.app.db, user.id),
117 });
94 return json(
95 creationOptions(
96 ctx,
97 "add",
98 { handle: user.id, name: user.username, displayName: user.displayName || user.username },
99 passkeyIds(ctx.app.db, user.id),
100 ),
101 );
118102 }
119103
120104 // POST /settings/passkeys — verify the browser's answer and keep the key.
@@ -123,16 +107,9 @@ export async function passkeyAdd(ctx: Ctx): Promise<Response> {
123107 if (denied) return denied;
124108 const data = await boundedBody(ctx.request, STRANGER_MAX);
125109 if (data === "too_large") return refuse(413, "payload too large");
126 const challenge = str(data.challenge);
127 if (!store(ctx.app).add.consume(challenge))
128 return refuse(400, "That request expired. Try again.");
129 const made = await verifyRegistration(
130 { clientDataJSON: str(data.clientDataJSON), attestationObject: str(data.attestationObject) },
131 { challenge, ...relying(ctx) },
132 );
133 if (!made.ok) return refuse(400, "That passkey was not accepted.");
134 const name = str(data.name).replace(/[\u0000-\u001f\u007f]/g, " ").trim().slice(0, PASSKEY_NAME_MAX) || "Passkey";
135 const added = addPasskey(ctx.app.db, ctx.auth.user!.id, name, made);
110 const made = await registered(ctx, "add", data);
111 if (!made) return refuse(400, "That passkey was not accepted. Try again.");
112 const added = addPasskey(ctx.app.db, ctx.auth.user!.id, made.name, made.credential);
136113 if (!added.ok)
137114 return refuse(
138115 409,
src/web/pages/recover.ts added +142
@@ -0,0 +1,142 @@
1 /**
2 * Getting back in after losing every passkey: ask for a link by email, and
3 * follow it to register a new passkey (`actions/recovery.ts`). The page that
4 * asks says the same thing whoever is asked about, and the link works once,
5 * for an hour. Registering signs the person in, as a passkey does.
6 */
7
8 import { recover, recoveryFor, sendRecovery } from "../../actions/recovery.ts";
9 import { createSession } from "../../core/sessions.ts";
10 import { crossOrigin, type Ctx } from "../../http/context.ts";
11 import { STRANGER_MAX } from "../../http/limits.ts";
12 import { clientAddress } from "../../http/peer.ts";
13 import { boundedBody, json, str } from "../../http/respond.ts";
14 import { pageHead } from "../chrome.ts";
15 import { field as formField, readForm } from "../form.ts";
16 import { html, type Html } from "../html.ts";
17 import { page } from "../layout.ts";
18 import { creationOptions, registered } from "../passkey-ceremony.ts";
19 import { passkeyJs } from "../passkey-client.ts";
20 import { btn, card, field } from "../ui.ts";
21 import { sessionCookie, signinAllowed } from "./site.ts";
22
23 const refuse = (status: number, message: string) =>
24 json({ error: "refused", message }, status);
25
26 function recoverPage(ctx: Ctx, body: Html, status = 200): Response {
27 return page(
28 {
29 ctx,
30 title: "Recover your account",
31 body: html`<div class="narrow">${pageHead("Recover your account")}${card(body)}</div>`,
32 scriptJs: passkeyJs,
33 },
34 status,
35 );
36 }
37
38 const STALE = html`<p>This link has been used, or it has expired.</p>
39 <p><a href="/recover">Ask for another</a>, or <a href="/signin">sign in</a>.</p>`;
40
41 // GET /recover — the form that asks for a link, or (with ?token=) the page
42 // that link opens, where a new passkey is made.
43 export function recoverPageGet(ctx: Ctx): Response {
44 const token = ctx.url.searchParams.get("token");
45 if (token === null) return recoverPage(ctx, askForm());
46 const user = recoveryFor(ctx.app, token);
47 if (!user.ok) return recoverPage(ctx, STALE, 400);
48 return recoverPage(
49 ctx,
50 html`<p>
51 Make a new passkey for <strong>${user.value.username}</strong>. Your
52 device asks for a fingerprint, face or PIN; the new passkey signs you
53 in from now on.
54 </p>
55 <input type="hidden" id="recover-token" value="${token}" />
56 <noscript><p class="error mb">Making a passkey needs JavaScript.</p></noscript>
57 <p class="error-note" id="passkey-recover-note" role="status"></p>
58 <div class="form-actions">
59 <button type="button" id="passkey-recover" class="btn" data-variant="primary">Make a new passkey</button>
60 </div>`,
61 );
62 }
63
64 function askForm(note?: Html): Html {
65 return html`<form method="post" action="/recover">
66 <p class="muted small mb">
67 Lost your passkey? Enter your account's email. If the address is
68 verified, we send a link that lets you make a new one. It works once,
69 for an hour.
70 </p>
71 ${note ?? ""}
72 ${field({ label: "Email", name: "email", type: "email", autocomplete: "email", required: true, autofocus: true })}
73 <div class="form-actions">${btn("Send a link", { variant: "primary" })}</div>
74 </form>`;
75 }
76
77 // POST /recover — send a link, saying the same whoever the address is.
78 export async function recoverSubmit(ctx: Ctx): Promise<Response> {
79 const form = await readForm(ctx, undefined, STRANGER_MAX);
80 if (form instanceof Response) return form;
81 const wait = signinAllowed(ctx, `recover:${clientAddress(ctx.request)}`);
82 if (wait !== undefined) {
83 const response = recoverPage(
84 ctx,
85 askForm(html`<p class="error mb" role="alert">Too many attempts. Try again in ${String(wait)}s.</p>`),
86 429,
87 );
88 response.headers.set("retry-after", String(wait));
89 return response;
90 }
91 // Not awaited: a send takes the mailer's round trip and "nobody" none, so
outdated

Medium: nobody returns at once, while sent waits for the mailer's round trip. The response time tells a stranger which addresses are verified accounts. Don't await the send on the request path (log its outcome from the promise), or wait the same either way.

92 // waiting would tell by the clock what the page will not say in words.
93 void sendRecovery(ctx.app, formField(form, "email")).then(
94 (outcome) => {
95 if (outcome !== "sent" && outcome !== "nobody")
96 ctx.app.log.info("a recovery link was asked for and not sent", { outcome });
97 },
98 (error: unknown) =>
99 ctx.app.log.warn("a recovery link could not be sent", { error: String(error) }),
100 );
101 return recoverPage(
102 ctx,
103 html`<p>
104 If that address is verified on an account here, a link is on its way.
105 It works once, for an hour.
106 </p>
107 <p class="muted small">Nothing arrived? Check spam, or ask the forge's owner.</p>`,
108 );
109 }
110
111 // POST /recover/passkey/options — a challenge, for a live link only.
112 export async function recoverOptions(ctx: Ctx): Promise<Response> {
113 if (crossOrigin(ctx.request, ctx.url, ctx.app.log)) return refuse(403, "forbidden");
114 const data = await boundedBody(ctx.request, STRANGER_MAX);
115 if (data === "too_large") return refuse(413, "payload too large");
116 const user = recoveryFor(ctx.app, str(data.token));
117 if (!user.ok) return refuse(400, "This link has been used, or it has expired.");
118 const u = user.value;
119 return json(
120 creationOptions(ctx, "recover", { handle: u.id, name: u.username, displayName: u.displayName || u.username }),
121 );
122 }
123
124 // POST /recover/passkey — spend the link, keep the passkey, sign in.
125 export async function recoverPasskey(ctx: Ctx): Promise<Response> {
126 if (crossOrigin(ctx.request, ctx.url, ctx.app.log)) return refuse(403, "forbidden");
127 const data = await boundedBody(ctx.request, STRANGER_MAX);
128 if (data === "too_large") return refuse(413, "payload too large");
129 const passkey = await registered(ctx, "recover", { ...data, name: "Recovered passkey" });
130 if (passkey === undefined) return refuse(400, "That passkey was not accepted. Try again.");
131 const done = recover(ctx.app, str(data.token), passkey);
132 if (!done.ok)
133 return done.error === "invalid"
134 ? refuse(400, "This link has been used, or it has expired.")
135 : refuse(409, done.error === "too_many" ? "That is as many passkeys as an account keeps." : "That passkey is already registered.");
136 const session = createSession(ctx.app.db, done.value.id);
137 return json(
138 { ok: true, next: "/settings/passkeys" },
139 200,
140 { "set-cookie": sessionCookie(session.token, session.expiresAt, ctx.url, ctx.app.config.url) },
141 );
142 }
src/web/pages/site.ts +116 −42
@@ -11,11 +11,11 @@
1111 import { limitValue } from "../../settings/limits.ts";
1212 import { mayView } from "../../core/sealed.ts";
1313 import { signOutHere } from "../../actions/signins.ts";
14 import { clientAddress } from "../../http/peer.ts";
14 import { clientAddress, clientBucket } from "../../http/peer.ts";
1515 import { verifyEmail } from "../../actions/verify.ts";
1616 import { STRANGER_MAX } from "../../http/limits.ts";
1717 import { createRepo } from "../../actions/repos.ts";
18 import { HUMAN_CHECK_MESSAGE, signUp } from "../../actions/users.ts";
18 import { HUMAN_CHECK_MESSAGE, isHuman, signUp } from "../../actions/users.ts";
1919 import { listAssignedTo, type Issue } from "../../core/issues.ts";
2020 import { joinMany } from "../../core/pulls.ts";
2121 import { conflictsOf } from "../../crew/stale_asks.ts";
@@ -28,7 +28,7 @@ import {
2828 type Repo,
2929 } from "../../core/repos.ts";
3030 import { createSession } from "../../core/sessions.ts";
31 import { hasAnyUser, verifyPassword, type User } from "../../core/users.ts";
31 import { accountClash, hasAnyUser, verifyPassword, type User } from "../../core/users.ts";
3232 import { isThemeName } from "../../design/themes.ts";
3333 import { cookieValue, crossOrigin, type Ctx } from "../../http/context.ts";
3434 import { studioDoor, studioHome } from "../studio/home.ts";
@@ -41,6 +41,8 @@ import { hostOf, pageHead, signInFirst } from "../chrome.ts";
4141 import { RateLimiter } from "../../core/ratelimit.ts";
4242 import { field, readForm } from "../form.ts";
4343 import { passkeyJs } from "../passkey-client.ts";
44 import { creationOptions, registered } from "../passkey-ceremony.ts";
45 import { boundedBody, json, str } from "../../http/respond.ts";
4446 import { html, when, type Html } from "../html.ts";
4547 import { icon } from "../icons.ts";
4648 import { flashTo, page, redirect } from "../layout.ts";
@@ -337,6 +339,7 @@ interface AuthErrors {
337339 username?: string;
338340 email?: string;
339341 password?: string;
342 passkey?: string;
340343 human?: string;
341344 }
342345
@@ -374,13 +377,13 @@ function authForm(
374377 <p class="muted small">
375378 ${kind === "signin"
376379 ? `Accounts made through ${name} sign in there and have no password here. The form below is for an account that was given one.`
377 : `Signing in through ${name} makes your account on first sight; the form below makes one with a password instead.`}
380 : `Signing in through ${name} makes your account on first sight; the form below makes one with a passkey instead.`}
378381 </p>
379382 </div>`,
380383 );
381384
382385 const body = html`${throughEdge}
383 <form method="post" action="${action}">
386 <form method="post" action="${action}"${kind === "signup" ? html` id="signup-form"` : ""}>
384387 ${formField({
385388 label: "Username",
386389 name: "username",
@@ -407,17 +410,25 @@ function authForm(
407410 ...(errors.email ? { error: errors.email } : {}),
408411 }),
409412 )}
410 ${formField({
411 label: "Password",
412 name: "password",
413 type: "password",
414 autocomplete: kind === "signin" ? "current-password" : "new-password",
415 required: true,
416 ...(kind === "signup"
417 ? { minlength: 10, hint: "At least 10 characters." }
418 : {}),
419 ...(errors.password ? { error: errors.password } : {}),
420 })}
413 ${kind === "signin"
414 ? formField({
415 label: "Password",
416 name: "password",
417 type: "password",
418 autocomplete: "current-password",
419 required: true,
420 ...(errors.password ? { error: errors.password } : {}),
421 })
422 : html`<input type="hidden" name="challenge" />
423 <input type="hidden" name="clientDataJSON" />
424 <input type="hidden" name="attestationObject" />
425 <p class="muted small mb">
426 Your account signs in with a passkey: your device asks for a
427 fingerprint, face or PIN when you press the button. Your email
428 is how you get back in if you lose it.
429 </p>
430 <noscript><p class="error mb">Making a passkey needs JavaScript.</p></noscript>
431 <p class="error-note" id="passkey-signup-note" role="status">${errors.passkey ?? ""}</p>`}
421432 ${when(
422433 kind === "signup" ? siteKey(ctx) : undefined,
423434 (key) =>
@@ -436,9 +447,9 @@ function authForm(
436447 </p>`,
437448 )}
438449 <div class="form-actions">
439 ${btn(kind === "signin" ? "Sign in" : "Create account", {
440 variant: "primary",
441 })}
450 ${kind === "signin"
451 ? btn("Sign in", { variant: "primary" })
452 : html`<button type="submit" id="passkey-signup" class="btn" data-variant="primary">Create account with a passkey</button>`}
442453 <span class="spacer"></span>
443454 ${kind === "signin"
444455 ? btn("Need an account? Sign up", {
@@ -466,7 +477,8 @@ function authForm(
466477 () => html`<p class="mt">
467478 <button type="button" id="passkey-signin" class="btn" data-variant="outline">Sign in with a passkey</button>
468479 <span class="error-note small" id="passkey-signin-note" role="status"></span>
469 </p>`,
480 </p>
481 <p class="muted small mt">Lost your passkey? <a href="/recover">Get a link by email</a>.</p>`,
470482 )}
471483 ${claimable
472484 ? html`<p class="muted small mt" id="claim-door">
@@ -497,6 +509,7 @@ export function signupPage(ctx: Ctx): Response {
497509 title: "Sign up",
498510 body: authForm(ctx, "signup"),
499511 turnstile: siteKey(ctx) !== undefined,
512 scriptJs: passkeyJs,
500513 });
501514 }
502515
@@ -530,6 +543,16 @@ export function signinAllowed(ctx: Ctx, username: string): number | undefined {
530543 return one.allowed ? undefined : one.retryAfter;
531544 }
532545
546 /**
547 * Password sign-in, kept for the accounts made before sign-up took a passkey
548 * (#1618); no account made since has a password. Settings invites each of
549 * them to add a passkey. This handler, `POST /api/v1/sessions`, the
550 * terminal's password field and Settings → Password can be removed once no
551 * active person signs in with only a password —
552 * `SELECT count(*) FROM user u WHERE u.kind = 'user' AND u.password_hash != ''
553 * AND u.removed_at IS NULL AND NOT EXISTS (SELECT 1 FROM passkey p WHERE
554 * p.user_id = u.id)` answers 0.
555 */
533556 export async function signinSubmit(ctx: Ctx): Promise<Response> {
534557 // Posted by people with no account yet: a stranger's form.
535558 const form = await readForm(ctx, undefined, STRANGER_MAX);
@@ -602,43 +625,94 @@ export function verifyPage(ctx: Ctx): Response {
602625 );
603626 }
604627
628 /** What a person is told when a name or address cannot be had. */
629 const SIGNUP_REFUSALS: Record<NonNullable<ReturnType<typeof accountClash>>, AuthErrors> = {
630 invalid_username: { username: "Usernames are letters, digits, dots, dashes." },
631 username_taken: { username: "That username is taken." },
632 username_reserved: { username: "That name is reserved." },
633 email_taken: { email: "That email already has an account." },
634 };
635
636 // POST /signup/passkey/options — a challenge for the passkey a new account
637 // is made with. The name and address are checked first, so the browser
638 // never keeps a passkey for an account that would be refused; and the
639 // person before them, so the answer is no oracle of who has an account.
640 // The challenge issued is that person's proof from here on: the widget's
641 // token answers once, and this is where it was spent.
642 export async function signupOptions(ctx: Ctx): Promise<Response> {
643 if (crossOrigin(ctx.request, ctx.url, ctx.app.log))
644 return json({ error: "forbidden", message: "forbidden" }, 403);
645 const data = await boundedBody(ctx.request, STRANGER_MAX);
646 if (data === "too_large")
outdated

High: this is an email and username oracle that never passes Turnstile. It answers email_taken to anyone who posts. Verify the human token here first when turnstileSecret is set, and give this endpoint its own signinAllowed-style limit on clientBucket. Every call also issues a challenge into the signup store, which holds 10k: a flood evicts the challenges of people in the middle of signing up.

647 return json({ error: "too_large", message: "payload too large" }, 413);
648 const wait = signinAllowed(ctx, `signup:${clientBucket(ctx.request)}`);
649 if (wait !== undefined)
650 return json(
651 { error: "rate_limited", message: `Too many attempts. Try again in ${String(wait)}s.` },
652 429,
653 { "retry-after": String(wait) },
654 );
655 if (!(await isHuman(ctx.app, str(data["cf-turnstile-response"]), clientAddress(ctx.request))))
656 return json({ error: "human_check", message: HUMAN_CHECK_MESSAGE }, 422);
657 const username = str(data.username);
658 const clash = accountClash(ctx.app.db, { username, email: str(data.email) });
659 if (clash !== undefined) {
660 const said = SIGNUP_REFUSALS[clash];
661 return json({ error: clash, message: said.username ?? said.email ?? "" }, 422);
662 }
663 // The account has no id yet; the handle only has to be its own.
664 const handle = Buffer.from(crypto.getRandomValues(new Uint8Array(16))).toString("hex");
665 return json(creationOptions(ctx, "signup", { handle, name: username, displayName: username }));
666 }
667
668 // POST /signup — the form, carrying the passkey the browser just made.
605669 export async function signupSubmit(ctx: Ctx): Promise<Response> {
606670 // Posted by people with no account yet: a stranger's form.
607671 const form = await readForm(ctx, undefined, STRANGER_MAX);
608672 if (form instanceof Response) return form;
609673 const username = field(form, "username");
610674 const email = field(form, "email");
611 const created = await signUp(
612 ctx.app,
613 {
614 username,
615 email,
616 password: field(form, "password"),
617 humanToken: field(form, "cf-turnstile-response"),
618 },
619 { address: clientAddress(ctx.request) },
620 );
621 if (!created.ok) {
622 const errors: AuthErrors = {
623 invalid_username: {
624 username: "Usernames are letters, digits, dots, dashes.",
625 },
626 username_taken: { username: "That username is taken." },
627 username_reserved: { username: "That name is reserved." },
628 email_taken: { email: "That email already has an account." },
629 weak_password: { password: "Passwords need at least 10 characters." },
630 human_check: { human: HUMAN_CHECK_MESSAGE },
631 }[created.error] ?? { username: "Something went wrong." };
632 return page(
675 const refused = (errors: AuthErrors): Response =>
676 page(
outdated

High: on main, Turnstile was checked before an account clash could be said. Here the clash is said first, so a bot without a token still learns which emails exist. Run the human check before accountClash, or move both into signUp in that order.

633677 {
634678 ctx,
635679 title: "Sign up",
636680 body: authForm(ctx, "signup", { values: { username, email }, errors }),
637681 turnstile: siteKey(ctx) !== undefined,
682 scriptJs: passkeyJs,
638683 },
639684 422,
640685 );
686 // The passkey first: its challenge was issued only to a person
687 // (`signupOptions`), so with one the name may be judged.
688 const passkey = await registered(ctx, "signup", {
689 challenge: field(form, "challenge"),
690 clientDataJSON: field(form, "clientDataJSON"),
691 attestationObject: field(form, "attestationObject"),
692 name: "Sign-up passkey",
693 });
694 if (passkey === undefined) {
695 // Without one nothing has proven a person yet: ask, and only then say
696 // what was wrong with the name, so a form posted bare still hears it.
697 if (!(await isHuman(ctx.app, field(form, "cf-turnstile-response"), clientAddress(ctx.request))))
698 return refused({ human: HUMAN_CHECK_MESSAGE });
699 const clash = accountClash(ctx.app.db, { username, email });
700 if (clash !== undefined) return refused(SIGNUP_REFUSALS[clash]);
701 return refused({
702 passkey: "A new account needs a passkey, and that one was not made. Press the button to try again.",
703 });
641704 }
705 const created = await signUp(
706 ctx.app,
707 { username, email, passkey },
708 { address: clientAddress(ctx.request) },
709 );
710 if (!created.ok)
711 return refused(
712 created.error === "passkey_taken"
713 ? { passkey: "That passkey already belongs to an account." }
714 : SIGNUP_REFUSALS[created.error],
715 );
642716 const session = createSession(ctx.app.db, created.value.id);
643717 return redirect(
644718 safeNext(ctx.url.searchParams.get("next")) ?? "/",
src/web/passkey-ceremony.ts added +68
@@ -0,0 +1,68 @@
1 /**
2 * The server half of a passkey ceremony, shared by every page that runs
3 * one — adding a passkey, signing in, signing up, recovering: the one-time
4 * challenges, the relying party the browser must have seen, and the
5 * verified answer to a creation. The cryptography is `auth/webauthn.ts`.
6 */
7
8 import type { App } from "../app.ts";
9 import { challenges, verifyRegistration, type Credential } from "../auth/webauthn.ts";
10 import { PASSKEY_NAME_MAX } from "../core/passkeys.ts";
11 import type { Ctx } from "../http/context.ts";
12 import { str } from "../http/respond.ts";
13
14 type Ceremony = "add" | "signin" | "signup" | "recover";
15 type Store = Record<Ceremony, ReturnType<typeof challenges>>;
16
17 /** One-time challenges, one store per ceremony per forge. */
18 const stores = new WeakMap<App, Store>();
19 export function store(app: App): Store {
20 let s = stores.get(app);
21 if (!s)
22 stores.set(app, (s = { add: challenges(), signin: challenges(), signup: challenges(), recover: challenges() }));
23 return s;
24 }
25
26 /** What the browser must see as the relying party: the forge's public address. */
27 export function relying(ctx: Ctx) {
28 return { origin: ctx.url.origin, rpId: ctx.url.hostname };
29 }
30
31 /** A challenge for a ceremony that makes a passkey, and what the browser needs beside it. */
32 export function creationOptions(
33 ctx: Ctx,
34 ceremony: "add" | "signup" | "recover",
35 user: { handle: string; name: string; displayName: string },
36 exclude: string[] = [],
37 ) {
38 return {
39 challenge: store(ctx.app)[ceremony].issue(),
40 rpId: relying(ctx).rpId,
41 rpName: "forge",
42 user: { id: Buffer.from(user.handle).toString("base64url"), name: user.name, displayName: user.displayName },
43 exclude,
44 };
45 }
46
47 /** A passkey's display name as it is kept: no control bytes, bounded, never empty. */
48 const passkeyName = (raw: unknown): string =>
49 str(raw).replace(/[\u0000-\u001f\u007f]/g, " ").trim().slice(0, PASSKEY_NAME_MAX) || "Passkey";
50
51 /**
52 * The browser's answer to a creation challenge, verified: the challenge is
53 * spent whatever the outcome, so an answer works once. Undefined when it was
54 * not this forge's challenge or not a good registration.
55 */
56 export async function registered(
57 ctx: Ctx,
58 ceremony: "add" | "signup" | "recover",
59 data: Record<string, unknown>,
60 ): Promise<{ name: string; credential: Credential } | undefined> {
61 const challenge = str(data.challenge);
62 if (!store(ctx.app)[ceremony].consume(challenge)) return undefined;
63 const made = await verifyRegistration(
64 { clientDataJSON: str(data.clientDataJSON), attestationObject: str(data.attestationObject) },
65 { challenge, ...relying(ctx) },
66 );
67 return made.ok ? { name: passkeyName(data.name), credential: made } : undefined;
68 }
src/web/passkey-client.ts +45 −22
@@ -1,7 +1,9 @@
11 /**
2 * The browser half of passkeys: two small ceremonies, inlined (nonce'd) on
3 * the two pages that need them. A page without script still works; it just
4 * has no passkey button. Binary travels as base64url, as the server expects.
2 * The browser half of passkeys: small ceremonies, inlined (nonce'd) on the
3 * pages that need them — Settings → Passkeys, sign-in, sign-up, recovery.
4 * Without script, sign-in by password still works and the passkey buttons
5 * do nothing; sign-up says it needs script. Binary travels as base64url, as
6 * the server expects.
57 */
68 export const passkeyJs = /* js */ `
79 (function () {
@@ -45,33 +47,54 @@ export const passkeyJs = /* js */ `
4547 el.disabled = true;
4648 if (note) note.textContent = '';
4749 run().catch(function (err) {
48 if (note) note.textContent = err && err.name === 'NotAllowedError' ? 'Cancelled.' : (err && err.message) || 'That did not work.';
50 // A form the browser already explained is not an error to repeat.
51 if (note) note.textContent = err && err.name === 'NotAllowedError' ? 'Cancelled.' : err && err.name === 'Unfilled' ? '' : (err && err.message) || 'That did not work.';
4952 el.disabled = false;
5053 });
5154 });
5255 }
5356 wire('passkey-add', function () {
5457 var name = doc.getElementById('passkey-name');
55 return post('/settings/passkeys/options').then(function (o) {
56 return navigator.credentials.create({ publicKey: {
57 challenge: bytes(o.challenge),
58 rp: { id: o.rpId, name: o.rpName },
59 user: { id: bytes(o.user.id), name: o.user.name, displayName: o.user.displayName },
60 pubKeyCredParams: [{ type: 'public-key', alg: -7 }, { type: 'public-key', alg: -257 }],
61 excludeCredentials: o.exclude.map(function (c) { return { type: 'public-key', id: bytes(c) }; }),
62 authenticatorSelection: { residentKey: 'preferred', userVerification: 'required' },
63 attestation: 'none',
64 timeout: 120000
65 } }).then(function (cred) {
66 return post('/settings/passkeys', {
67 name: name ? name.value : '',
68 challenge: o.challenge,
69 clientDataJSON: text(cred.response.clientDataJSON),
70 attestationObject: text(cred.response.attestationObject)
71 });
72 });
58 return post('/settings/passkeys/options').then(created).then(function (made) {
59 made.name = name ? name.value : '';
60 return post('/settings/passkeys', made);
7361 }).then(function () { location.reload(); });
7462 });
63 function created(o) {
64 return navigator.credentials.create({ publicKey: {
65 challenge: bytes(o.challenge),
66 rp: { id: o.rpId, name: o.rpName },
67 user: { id: bytes(o.user.id), name: o.user.name, displayName: o.user.displayName },
68 pubKeyCredParams: [{ type: 'public-key', alg: -7 }, { type: 'public-key', alg: -257 }],
69 excludeCredentials: o.exclude.map(function (c) { return { type: 'public-key', id: bytes(c) }; }),
70 authenticatorSelection: { residentKey: 'preferred', userVerification: 'required' },
71 attestation: 'none',
72 timeout: 120000
73 } }).then(function (cred) {
74 return {
75 challenge: o.challenge,
76 clientDataJSON: text(cred.response.clientDataJSON),
77 attestationObject: text(cred.response.attestationObject)
78 };
79 });
80 }
81 // Sign-up: make the passkey, then post the form as it is, carrying it.
82 wire('passkey-signup', function () {
83 var form = doc.getElementById('signup-form');
84 if (!form.reportValidity()) { var e = new Error(''); e.name = 'Unfilled'; return Promise.reject(e); }
85 // The form's fields, the human check's token among them when it has one.
86 return post('/signup/passkey/options', Object.fromEntries(new FormData(form))).then(created).then(function (made) {
87 for (var k in made) form.elements[k].value = made[k];
88 form.submit();
89 });
90 });
91 wire('passkey-recover', function () {
92 var token = doc.getElementById('recover-token').value;
93 return post('/recover/passkey/options', { token: token }).then(created).then(function (made) {
94 made.token = token;
95 return post('/recover/passkey', made);
96 }).then(function (r) { location.href = r.next; });
97 });
7598 wire('passkey-signin', function () {
7699 return post('/signin/passkey/options').then(function (o) {
77100 return navigator.credentials.get({ publicKey: {
test/accounts-retire.test.ts +2 −1
@@ -13,6 +13,7 @@ import { listReposOwnedBy } from "../src/core/repos.ts";
1313 import { repoDir } from "../src/git/repos.ts";
1414 import { serve, type Servers } from "../src/http/server.ts";
1515 import { proveAll } from "./helpers/verified.ts";
16 import { testPasskey } from "./helpers/passkey.ts";
1617
1718 describe("accounts: the confirm page for removing an organization too", () => {
1819 let dataDir: string;
@@ -31,7 +32,7 @@ describe("accounts: the confirm page for removing an organization too", () => {
3132 const u = await signUp(app, {
3233 username,
3334 email: `${username}@f.dev`,
34 password: "a-long-passphrase",
35 passkey: testPasskey(),
3536 });
3637 if (!u.ok) throw new Error(u.error);
3738 return u.value;
test/accounts.test.ts +27 −9
@@ -27,6 +27,7 @@ import { createUser as insertAgent, getUserByName } from "../src/core/users.ts";
2727 import { serve, type Servers } from "../src/http/server.ts";
2828 import { forgeSshSession, identityFor } from "../src/tui/ssh.ts";
2929 import { proveAll } from "./helpers/verified.ts";
30 import { device, passwordAccount, testPasskey, webSignUp } from "./helpers/passkey.ts";
3031
3132 const EDGE = "edge-secret-for-accounts";
3233 const KEY_LINE =
@@ -66,7 +67,7 @@ describe("accounts: the owner sees, suspends and removes", () => {
6667 const owner = await signUp(app, {
6768 username: "olive",
6869 email: "[email protected]",
69 password: "owner-passphrase",
70 passkey: testPasskey(),
7071 });
7172 if (!owner.ok) throw new Error(owner.error);
7273 ownerToken = createToken(app.db, owner.value.id, "t", "admin").token;
@@ -90,16 +91,33 @@ describe("accounts: the owner sees, suspends and removes", () => {
9091 await rm(dataDir, { recursive: true, force: true });
9192 });
9293
93 const outsider = async (name: string) => {
94 const res = await api("/api/v1/users", {
95 method: "POST",
96 body: JSON.stringify({
94 // `fromBefore`: an account made before sign-up took a passkey (#1618),
95 // which still signs in with its password.
96 const outsider = async (name: string, fromBefore = false) => {
97 if (fromBefore) {
98 const made = await passwordAccount(app, {
9799 username: name,
98100 email: `${name}@outsider.test`,
99101 password: "outsider-passphrase",
100 }),
101 });
102 expect(res.status).toBe(201);
102 });
103 if (!made.ok) throw new Error(made.error);
104 } else {
105 const res = await webSignUp(
106 base,
107 "",
108 {
109 method: "POST",
110 headers: { origin: "https://forge.example" },
111 body: new URLSearchParams({
112 username: name,
113 email: `${name}@outsider.test`,
114 }),
115 redirect: "manual",
116 },
117 await device("https://forge.example", "forge.example"),
118 );
119 expect(res.status).toBe(303);
120 }
103121 // This suite is about standing, not email: its outsiders are proven.
104122 proveAll(app);
105123 const user = getUserByName(app.db, name)!;
@@ -191,7 +209,7 @@ describe("accounts: the owner sees, suspends and removes", () => {
191209 });
192210
193211 test("suspending stops every credential at once", async () => {
194 const { user, token } = await outsider("eve");
212 const { user, token } = await outsider("eve", true);
195213 const cookie = `forge_session=${createSession(app.db, user.id).token}`;
196214 const parsed = parseAuthorizedKey(KEY_LINE);
197215 if (!parsed.ok) throw new Error("key");
test/actions.test.ts +9 −8
@@ -33,6 +33,7 @@ import { getOrg, listTeams, OWNERS_TEAM } from "../src/core/orgs.ts";
3333 import { getPull } from "../src/core/pulls.ts";
3434 import { getRepo, type Repo } from "../src/core/repos.ts";
3535 import type { User } from "../src/core/users.ts";
36 import { testPasskey } from "./helpers/passkey.ts";
3637
3738 /** Event kinds in chronological order (listEvents returns newest first). */
3839 const kinds = (app: App, repoId?: string) =>
@@ -54,12 +55,12 @@ describe("actions own authorization and events", () => {
5455 const a = await signUp(app, {
5556 username: "alice",
5657 email: "[email protected]",
57 password: "a-long-passphrase",
58 passkey: testPasskey(),
5859 });
5960 const b = await signUp(app, {
6061 username: "bob",
6162 email: "[email protected]",
62 password: "a-long-passphrase",
63 passkey: testPasskey(),
6364 });
6465 if (!a.ok || !b.ok) throw new Error("signup failed");
6566 alice = a.value;
@@ -165,7 +166,7 @@ describe("actions own authorization and events", () => {
165166 const carol = await signUp(app, {
166167 username: "carol",
167168 email: "[email protected]",
168 password: "a-long-passphrase",
169 passkey: testPasskey(),
169170 });
170171 if (!carol.ok) throw new Error("signup failed");
171172
@@ -320,8 +321,8 @@ describe("sign-up races", () => {
320321 const fresh = createApp({ dataDir: dir });
321322 try {
322323 const [a, b] = await Promise.all([
323 signUp(fresh, { username: "one", email: "[email protected]", password: "a-good-passphrase" }),
324 signUp(fresh, { username: "two", email: "[email protected]", password: "a-good-passphrase" }),
324 signUp(fresh, { username: "one", email: "[email protected]", passkey: testPasskey() }),
325 signUp(fresh, { username: "two", email: "[email protected]", passkey: testPasskey() }),
325326 ]);
326327 if (!a.ok || !b.ok) throw new Error("sign-ups failed");
327328 expect([a.value.isAdmin, b.value.isAdmin].filter(Boolean)).toHaveLength(1);
@@ -336,8 +337,8 @@ describe("sign-up races", () => {
336337 const fresh = createApp({ dataDir: dir });
337338 try {
338339 const results = await Promise.all([
339 signUp(fresh, { username: "same", email: "[email protected]", password: "a-good-passphrase" }),
340 signUp(fresh, { username: "same", email: "[email protected]", password: "a-good-passphrase" }),
340 signUp(fresh, { username: "same", email: "[email protected]", passkey: testPasskey() }),
341 signUp(fresh, { username: "same", email: "[email protected]", passkey: testPasskey() }),
341342 ]);
342343 const errors = results.filter((r) => !r.ok).map((r) => (r as { error: string }).error);
343344 expect(results.filter((r) => r.ok)).toHaveLength(1);
@@ -354,7 +355,7 @@ describe("free-text caps", () => {
354355 const dir = await mkdtemp(join(tmpdir(), "forge-caps-"));
355356 const fresh = createApp({ dataDir: dir });
356357 try {
357 const u = await signUp(fresh, { username: "cap", email: "[email protected]", password: "a-good-passphrase" });
358 const u = await signUp(fresh, { username: "cap", email: "[email protected]", passkey: testPasskey() });
358359 if (!u.ok) throw new Error("sign-up failed");
359360 const r = await createRepo(fresh, u.value, { name: "caps", visibility: "public" });
360361 if (!r.ok) throw new Error("repo failed");
test/agents.test.ts +7 −18
@@ -12,6 +12,7 @@
1212 */
1313
1414 import { afterAll, beforeAll, describe, expect, test } from "bun:test";
15 import { passwordAccount } from "./helpers/passkey.ts";
1516 import { mkdtemp, rm } from "node:fs/promises";
1617 import { tmpdir } from "node:os";
1718 import { join } from "node:path";
@@ -67,15 +68,11 @@ describe("fifty agents at once", () => {
6768 app = createApp({ dataDir, port: 0 });
6869 servers = await serve(app);
6970 base = servers.url;
70 await fetch(`${base}/api/v1/users`, {
71 method: "POST",
72 headers: { "content-type": "application/json" },
73 body: JSON.stringify({
71 await passwordAccount(app, {
7472 username: "cora",
7573 email: "[email protected]",
7674 password: "a-long-crew-password",
77 }),
78 });
75 });
7976 token = await fetch(`${base}/api/v1/tokens`, {
8077 method: "POST",
8178 headers: { "content-type": "application/json" },
@@ -281,15 +278,11 @@ describe("Idempotency-Key", () => {
281278 app = createApp({ dataDir, port: 0 });
282279 servers = await serve(app);
283280 base = servers.url;
284 await fetch(`${base}/api/v1/users`, {
285 method: "POST",
286 headers: { "content-type": "application/json" },
287 body: JSON.stringify({
281 await passwordAccount(app, {
288282 username: "mira",
289283 email: "[email protected]",
290284 password: "a-long-bot-password",
291 }),
292 });
285 });
293286 token = await fetch(`${base}/api/v1/tokens`, {
294287 method: "POST",
295288 headers: { "content-type": "application/json" },
@@ -571,15 +564,11 @@ describe("rate limits over HTTP", () => {
571564 servers = await serve(app);
572565 delete process.env["FORGE_RATE_LIMIT"];
573566 base = servers.url;
574 await fetch(`${base}/api/v1/users`, {
575 method: "POST",
576 headers: { "content-type": "application/json" },
577 body: JSON.stringify({
567 await passwordAccount(app, {
578568 username: "loop",
579569 email: "[email protected]",
580570 password: "a-long-loop-password",
581 }),
582 });
571 });
583572 token = await fetch(`${base}/api/v1/tokens`, {
584573 method: "POST",
585574 headers: { "content-type": "application/json" },
test/api-errors.test.ts +3 −6
@@ -1,5 +1,6 @@
11 import { afterAll, beforeAll, describe, expect, test } from "bun:test";
22 import { mkdtemp, rm } from "node:fs/promises";
3 import { passwordAccount } from "./helpers/passkey.ts";
34 import { tmpdir } from "node:os";
45 import { join } from "node:path";
56 import { createApp, type App } from "../src/app.ts";
@@ -28,15 +29,11 @@ describe("API errors are distinguishable and self-describing", () => {
2829 base = servers.url;
2930 // A real user + public repo so a *resource* miss is reachable (a private
3031 // repo would mask the route itself).
31 await fetch(`${base}/api/v1/users`, {
32 method: "POST",
33 headers: { "content-type": "application/json" },
34 body: JSON.stringify({
32 await passwordAccount(app, {
3533 username: "dev",
3634 email: "[email protected]",
3735 password: "api-errors-pass",
38 }),
39 });
36 });
4037 });
4138
4239 afterAll(async () => {
test/app.test.ts +26 −28
@@ -5,6 +5,7 @@ import { join } from "node:path";
55 import { createApp, type App } from "../src/app.ts";
66 import { serve, type Servers } from "../src/http/server.ts";
77 import { gitClientEnv } from "./helpers/git-client.ts";
8 import { passwordAccount } from "./helpers/passkey.ts";
89
910 const clientEnv = gitClientEnv({
1011 GIT_AUTHOR_NAME: "Alice",
@@ -72,7 +73,8 @@ describe("the forge, end to end", () => {
7273 });
7374
7475 test("register: first user is admin, duplicates rejected", async () => {
75 const created = await api("/api/v1/users", {
76 // The API makes no account (#1618): sign-up takes a passkey, in a browser.
77 const refused = await api("/api/v1/users", {
7678 method: "POST",
7779 body: JSON.stringify({
7880 username: "alice",
@@ -80,36 +82,32 @@ describe("the forge, end to end", () => {
8082 password: "correct-horse-battery",
8183 }),
8284 });
83 expect(created.status).toBe(201);
84 const user = (await created.json()) as {
85 username: string;
86 isAdmin: boolean;
87 };
88 expect(user.isAdmin).toBe(true);
89
90 const dupe = await api("/api/v1/users", {
91 method: "POST",
92 body: JSON.stringify({
93 username: "ALICE",
94 email: "[email protected]",
95 password: "correct-horse-battery",
96 }),
97 });
98 expect(dupe.status).toBe(422);
99 expect(((await dupe.json()) as { error: string }).error).toBe(
100 "username_taken",
85 expect(refused.status).toBe(422);
86 expect(((await refused.json()) as { error: string }).error).toBe(
87 "passkey_required",
10188 );
10289
103 const second = await api("/api/v1/users", {
104 method: "POST",
105 body: JSON.stringify({
106 username: "bob",
107 email: "[email protected]",
108 password: "bobs-long-password",
109 }),
90 // Accounts from before still sign in with their password.
91 const created = await passwordAccount(app, {
92 username: "alice",
93 email: "[email protected]",
94 password: "correct-horse-battery",
11095 });
111 expect(second.status).toBe(201);
112 expect(((await second.json()) as { isAdmin: boolean }).isAdmin).toBe(false);
96 expect(created.ok && created.value.isAdmin).toBe(true);
97
98 const dupe = await passwordAccount(app, {
99 username: "ALICE",
100 email: "[email protected]",
101 password: "correct-horse-battery",
102 });
103 expect(dupe.ok ? "made" : dupe.error).toBe("username_taken");
104
105 const second = await passwordAccount(app, {
106 username: "bob",
107 email: "[email protected]",
108 password: "bobs-long-password",
109 });
110 expect(second.ok && !second.value.isAdmin).toBe(true);
113111 });
114112
115113 test("login yields a working session cookie", async () => {
test/apps-api.test.ts +11 −18
@@ -16,6 +16,7 @@ import { getRepo } from "../src/core/repos.ts";
1616 import { getUserByName } from "../src/core/users.ts";
1717 import { serve, type Servers } from "../src/http/server.ts";
1818 import { startCrew, type CrewHandle } from "../src/crew/dispatch.ts";
19 import { passwordAccount } from "./helpers/passkey.ts";
1920
2021 /** Read from an SSE body until `predicate(buffer)` holds or we time out —
2122 * never to a "done" that #284's still-live stream no longer sends. */
@@ -109,15 +110,11 @@ describe("apps, runs and the crew over the API", () => {
109110 budgetUsd: 1,
110111 runTimeoutMs: 60_000,
111112 });
112 await post(
113 "/api/v1/users",
114 {
115 username: "alice",
116 email: "[email protected]",
117 password: "a-good-passphrase",
118 },
119 null,
120 );
113 await passwordAccount(app, {
114 username: "alice",
115 email: "[email protected]",
116 password: "a-good-passphrase",
117 });
121118 const mint = async (scope: string) =>
122119 (
123120 (await (
@@ -449,15 +446,11 @@ describe("apps, runs and the crew over the API", () => {
449446 expect((await api(env, { token: null })).status).toBe(401);
450447 expect((await put("GREETING", "x", rw)).status).toBe(403);
451448 expect((await put("GREETING", "x", null)).status).toBe(401);
452 await post(
453 "/api/v1/users",
454 {
455 username: "mallory",
456 email: "[email protected]",
457 password: "a-good-passphrase",
458 },
459 null,
460 );
449 await passwordAccount(app, {
450 username: "mallory",
451 email: "[email protected]",
452 password: "a-good-passphrase",
453 });
461454 const mallory = (
462455 (await (
463456 await post(
test/asks-expiry.test.ts +2 −1
@@ -26,6 +26,7 @@ import { readFeed } from "../src/feed/feed.ts";
2626 import { serve, type Servers } from "../src/http/server.ts";
2727 import { ASK_WORDS, ROW_PLURAL, askLinesFor, asksAnswer } from "../src/web/studio/asks.ts";
2828 import { quietLogs } from "./helpers/globals.ts";
29 import { webSignUp } from "./helpers/passkey.ts";
2930
3031 quietLogs();
3132
@@ -93,7 +94,7 @@ describe("asks that expire, hold and collapse", () => {
9394 dataDir = await mkdtemp(join(tmpdir(), "forge-asks-expiry-"));
9495 app = createApp({ dataDir, port: 0 });
9596 servers = await serve(app);
96 const response = await fetch(`${servers.url}/signup`, {
97 const response = await webSignUp(servers.url, ``, {
9798 method: "POST",
9899 body: new URLSearchParams({
99100 username: "alice",
test/asks.test.ts +2 −1
@@ -21,6 +21,7 @@ import type { Ctx } from "../src/http/context.ts";
2121 import { serve, type Servers } from "../src/http/server.ts";
2222 import { decisionsFor } from "../src/web/studio/asks.ts";
2323 import { quietLogs } from "./helpers/globals.ts";
24 import { webSignUp } from "./helpers/passkey.ts";
2425
2526 quietLogs();
2627
@@ -44,7 +45,7 @@ describe("the asks page", () => {
4445 };
4546
4647 const signUp = async (username: string): Promise<string> => {
47 const response = await fetch(`${servers.url}/signup`, {
48 const response = await webSignUp(servers.url, ``, {
4849 method: "POST",
4950 body: new URLSearchParams({
5051 username,
test/body-limits.test.ts +13 −3
@@ -11,6 +11,7 @@ import { createToken } from "../src/core/tokens.ts";
1111 import { STRANGER_MAX } from "../src/http/limits.ts";
1212 import { serve, type Servers } from "../src/http/server.ts";
1313 import { gitClientEnv } from "./helpers/git-client.ts";
14 import { testPasskey } from "./helpers/passkey.ts";
1415
1516 // No request a stranger can make has the forge read an unbounded body: a
1617 // declared length and an undeclared (chunked) one are both stopped at the
@@ -33,7 +34,7 @@ describe("request body limits", () => {
3334 const owner = await signUp(app, {
3435 username: "ada",
3536 email: "[email protected]",
36 password: "owner-passphrase",
37 passkey: testPasskey(),
3738 });
3839 if (!owner.ok) throw new Error(owner.error);
3940 ownerToken = createToken(app.db, owner.value.id, "t", "admin").token;
@@ -66,7 +67,16 @@ describe("request body limits", () => {
6667 const big = STRANGER_MAX * 4;
6768
6869 const routes: { name: string; path: string; type: string }[] = [
69 { name: "signup (API)", path: "/api/v1/users", type: "application/json" },
70 {
71 name: "a sign-up passkey challenge",
72 path: "/signup/passkey/options",
73 type: "application/json",
74 },
75 {
76 name: "a recovery passkey",
77 path: "/recover/passkey",
78 type: "application/json",
79 },
7080 {
7181 name: "a session (API)",
7282 path: "/api/v1/sessions",
@@ -169,7 +179,7 @@ describe("request body limits", () => {
169179 test("the next request on a reused connection after a refused body is read as itself", async () => {
170180 // Bun's own fetch reuses a connection whatever the answer says; the
171181 // forge must not depend on a client honouring "Connection: close".
172 const refused = await fetch(`${base}/api/v1/users`, {
182 const refused = await fetch(`${base}/signup/passkey/options`, {
173183 method: "POST",
174184 headers: { "content-type": "application/json" },
175185 body: chunked(big),
test/branches.test.ts +4 −19
@@ -15,6 +15,7 @@ import { mkdtemp, rm } from "node:fs/promises";
1515 import { tmpdir } from "node:os";
1616 import { join } from "node:path";
1717 import { createApp, type App } from "../src/app.ts";
18 import { passwordAccount } from "./helpers/passkey.ts";
1819 import { listEvents } from "../src/core/events.ts";
1920 import { serve, type Servers } from "../src/http/server.ts";
2021 import {
@@ -54,15 +55,7 @@ describe("branches on a native repo", () => {
5455 fetch(`${base}${path}`, { ...init, headers: auth(token) });
5556
5657 const signUp = async (username: string, password: string, scope: string) => {
57 await fetch(`${base}/api/v1/users`, {
58 method: "POST",
59 headers: { "content-type": "application/json" },
60 body: JSON.stringify({
61 username,
62 email: `${username}@forge.test`,
63 password,
64 }),
65 });
58 await passwordAccount(app, { username, email: `${username}@forge.test`, password });
6659 const made = await read<{ token: string }>(
6760 await fetch(`${base}/api/v1/tokens`, {
6861 method: "POST",
@@ -318,14 +311,10 @@ describe("branches on a mirror go through the origin", () => {
318311
319312 originApp = createApp({ dataDir: originDataDir, port: 0 });
320313 originServers = await serve(originApp);
321 await fetch(`${originServers.url}/api/v1/users`, {
322 method: "POST",
323 headers: { "content-type": "application/json" },
324 body: JSON.stringify({
314 await passwordAccount(originApp, {
325315 username: ORIGIN_LOGIN,
326316 email: "[email protected]",
327317 password: ORIGIN_TOKEN,
328 }),
329318 });
330319 await upstream("/api/v1/repos", {
331320 method: "POST",
@@ -352,14 +341,10 @@ describe("branches on a mirror go through the origin", () => {
352341 app = createApp({ dataDir, port: 0 });
353342 servers = await serve(app);
354343 base = servers.url;
355 await fetch(`${base}/api/v1/users`, {
356 method: "POST",
357 headers: { "content-type": "application/json" },
358 body: JSON.stringify({
344 await passwordAccount(app, {
359345 username: "alice",
360346 email: "[email protected]",
361347 password: ALICE_PASSWORD,
362 }),
363348 });
364349
365350 const connected = await read<{ id: string }>(
test/cli-sync.test.ts +5 −7
@@ -14,6 +14,7 @@ import { mkdtemp, rm, stat, writeFile } from "node:fs/promises";
1414 import { tmpdir } from "node:os";
1515 import { join } from "node:path";
1616 import { createApp, type App } from "../src/app.ts";
17 import { passwordAccount } from "./helpers/passkey.ts";
1718 import { serve, type Servers } from "../src/http/server.ts";
1819 import { hostDir } from "../src/cli/config.ts";
1920 import { changesBetween, type RepoReport, type SyncReport } from "../src/cli/sync.ts";
@@ -103,13 +104,10 @@ describe("the local client, against a real forge", () => {
103104 base = servers.url;
104105 host = hostDir(base);
105106
106 await api("/api/v1/users", {
107 method: "POST",
108 body: JSON.stringify({
109 username: "alice",
110 email: "[email protected]",
111 password: "correct horse battery",
112 }),
107 await passwordAccount(app, {
108 username: "alice",
109 email: "alice@forge.local",
110 password: "correct horse battery",
113111 });
114112 const minted = await fetch(`${base}/api/v1/tokens`, {
115113 method: "POST",
test/commit-identity.test.ts +2 −1
@@ -29,6 +29,7 @@ import {
2929 } from "../src/core/users.ts";
3030 import { repoDir } from "../src/git/repos.ts";
3131 import { serve, type Servers } from "../src/http/server.ts";
32 import { webSignUp } from "./helpers/passkey.ts";
3233
3334 describe("commitIdentity", () => {
3435 const person = {
@@ -248,7 +249,7 @@ describe("choosing the commit address", () => {
248249 app = createApp({ dataDir, port: 0, host: "forge.example" });
249250 servers = await serve(app);
250251 base = servers.url;
251 const res = await fetch(`${base}/signup`, {
252 const res = await webSignUp(base, ``, {
252253 method: "POST",
253254 body: form({
254255 username: "dana",
test/contents-api.test.ts +3 −6
@@ -1,5 +1,6 @@
11 import { afterAll, beforeAll, describe, expect, test } from "bun:test";
22 import { mkdtemp, rm } from "node:fs/promises";
3 import { passwordAccount } from "./helpers/passkey.ts";
34 import { tmpdir } from "node:os";
45 import { join } from "node:path";
56 import { createApp, type App } from "../src/app.ts";
@@ -21,15 +22,11 @@ describe("commit via API (no git client)", () => {
2122 app = createApp({ dataDir, port: 0 });
2223 servers = await serve(app);
2324 base = servers.url;
24 await fetch(`${base}/api/v1/users`, {
25 method: "POST",
26 headers: { "content-type": "application/json" },
27 body: JSON.stringify({
25 await passwordAccount(app, {
2826 username: "mira",
2927 email: "[email protected]",
3028 password: "contents-api-pass",
31 }),
32 });
29 });
3330 token = await fetch(`${base}/api/v1/tokens`, {
3431 method: "POST",
3532 headers: { "content-type": "application/json" },
test/counts.test.ts +2 −1
@@ -33,6 +33,7 @@ import type { User } from "../src/core/users.ts";
3333 import { serve, type Servers } from "../src/http/server.ts";
3434 import { id } from "../src/kernel/id.ts";
3535 import { unwrap } from "../src/kernel/result.ts";
36 import { testPasskey } from "./helpers/passkey.ts";
3637
3738 /**
3839 * Count the SQL statements a block of work runs. `db.query` is the one door
@@ -104,7 +105,7 @@ describe("counts are grouped, and stay grouped", () => {
104105 await signUp(app, {
105106 username: "alice",
106107 email: "[email protected]",
107 password: "alice-counts-secret",
108 passkey: testPasskey(),
108109 }),
109110 );
110111 token = await fetch(`${base}/api/v1/tokens`, {
test/crew-totals.test.ts +2 −1
@@ -11,6 +11,7 @@ import {
1111 } from "../src/core/runs.ts";
1212 import { getUserByName } from "../src/core/users.ts";
1313 import { serve, type Servers } from "../src/http/server.ts";
14 import { webSignUp } from "./helpers/passkey.ts";
1415
1516 describe("what an agent has done, in totals", () => {
1617 let dataDir: string;
@@ -26,7 +27,7 @@ describe("what an agent has done, in totals", () => {
2627 app = createApp({ dataDir, port: 0 });
2728 servers = await serve(app);
2829 base = servers.url;
29 const signed = await fetch(`${base}/signup`, {
30 const signed = await webSignUp(base, ``, {
3031 method: "POST",
3132 body: new URLSearchParams({
3233 username: "ada",
test/cross-repo-pull.test.ts +3 −2
@@ -6,6 +6,7 @@ import { createApp, type App } from "../src/app.ts";
66 import { serve, type Servers } from "../src/http/server.ts";
77 import { gitClientEnv } from "./helpers/git-client.ts";
88 import { proveAll } from "./helpers/verified.ts";
9 import { webSignUp } from "./helpers/passkey.ts";
910
1011 const gitEnv = gitClientEnv({
1112 GIT_AUTHOR_NAME: "X",
@@ -45,7 +46,7 @@ describe("cross-repo pull requests (fork → upstream)", () => {
4546 async function mkUser(
4647 username: string,
4748 ): Promise<{ token: string; cookie: string }> {
48 const signup = await fetch(`${base}/signup`, {
49 const signup = await webSignUp(base, ``, {
4950 method: "POST",
5051 body: form({
5152 username,
@@ -57,7 +58,7 @@ describe("cross-repo pull requests (fork → upstream)", () => {
5758 const cookie = (signup.headers.get("set-cookie") ?? "").split(";")[0]!;
5859 const token = await fetch(`${base}/api/v1/tokens`, {
5960 method: "POST",
60 headers: { "content-type": "application/json" },
61 headers: { "content-type": "application/json", cookie },
6162 body: JSON.stringify({ adminConfirm: true,
6263 username,
6364 password: "cross-repo-pass",
test/cut-wave.test.ts +2 −2
@@ -10,6 +10,7 @@ import { getRepo, type Repo } from "../src/core/repos.ts";
1010 import { getUserByName } from "../src/core/users.ts";
1111 import { serve, type Servers } from "../src/http/server.ts";
1212 import { cutWave } from "../src/story/cut.ts";
13 import { webSignUp } from "./helpers/passkey.ts";
1314 import { parseWave, writeWave } from "../src/story/wave.ts";
1415
1516 const link = (n: number) => `https://f.test/o/r/pulls/${n}`;
@@ -112,8 +113,7 @@ describe("Cut a wave in Settings", () => {
112113 let repo: Repo;
113114
114115 const signup = async (username: string) => {
115 const res = await fetch(`${base}/signup`, {
116 method: "POST",
116 const res = await webSignUp(base, "", {
117117 body: new URLSearchParams({ username, email: `${username}@f.dev`, password: "cut-wave-password" }),
118118 redirect: "manual",
119119 });
test/diff-edge-cases.test.ts +3 −2
@@ -9,6 +9,7 @@ import { join } from "node:path";
99 import { createApp, type App } from "../src/app.ts";
1010 import { serve, type Servers } from "../src/http/server.ts";
1111 import { gitClientEnv } from "./helpers/git-client.ts";
12 import { webSignUp } from "./helpers/passkey.ts";
1213
1314 describe("diff engine + resource edge cases", () => {
1415 let dataDir: string;
@@ -51,7 +52,7 @@ describe("diff engine + resource edge cases", () => {
5152 servers = await serve(app);
5253 base = servers.url;
5354
54 const signup = await fetch(`${base}/signup`, {
55 const signup = await webSignUp(base, ``, {
5556 method: "POST",
5657 body: new URLSearchParams({
5758 username: "ada",
@@ -75,7 +76,7 @@ describe("diff engine + resource edge cases", () => {
7576
7677 const minted = await fetch(`${base}/api/v1/tokens`, {
7778 method: "POST",
78 headers: { "content-type": "application/json" },
79 headers: { "content-type": "application/json", cookie },
7980 body: JSON.stringify({ adminConfirm: true,
8081 username: "ada",
8182 password: "analytical-engine",
test/domain-drill.test.ts +3 −2
@@ -4,6 +4,7 @@ import { tmpdir } from "node:os";
44 import { join } from "node:path";
55 import { createApp, type App } from "../src/app.ts";
66 import { signUp } from "../src/actions/users.ts";
7 import { testPasskey } from "./helpers/passkey.ts";
78 import { createToken } from "../src/core/tokens.ts";
89 import { drillVerdict } from "../src/kernel/domain_drill.ts";
910 import { DOMAINS } from "../src/kernel/domains.ts";
@@ -39,8 +40,8 @@ describe("POST /api/v1/drills", () => {
3940 dataDir = await mkdtemp(join(tmpdir(), "forge-drill-"));
4041 app = createApp({ dataDir, port: 0 });
4142 servers = await serve(app);
42 const a = await signUp(app, { username: "ada", email: "[email protected]", password: "owner-passphrase" });
43 const b = await signUp(app, { username: "bob", email: "[email protected]", password: "bob-passphrase" });
43 const a = await signUp(app, { username: "ada", email: "[email protected]", passkey: testPasskey() });
44 const b = await signUp(app, { username: "bob", email: "[email protected]", passkey: testPasskey() });
4445 if (!a.ok || !b.ok) throw new Error("signup");
4546 admin = createToken(app.db, a.value.id, "t", "admin").token;
4647 plain = createToken(app.db, b.value.id, "t", "admin").token;
test/edits-security.test.ts +13 −24
@@ -20,6 +20,7 @@ import {
2020 serveFakeForge,
2121 type FakeForge,
2222 } from "./fake-origin.ts";
23 import { passwordAccount } from "./helpers/passkey.ts";
2324
2425 const read = async <T>(response: Response): Promise<T> =>
2526 (await response.json()) as T;
@@ -83,14 +84,10 @@ describe("edits: refusals that must leave nothing behind", () => {
8384 app = createApp({ dataDir, port: 0 });
8485 servers = await serve(app);
8586 base = servers.url;
86 await fetch(`${base}/api/v1/users`, {
87 method: "POST",
88 headers: { "content-type": "application/json" },
89 body: JSON.stringify({
90 username: "alice",
91 email: "[email protected]",
92 password: "alice-password-1",
93 }),
87 await passwordAccount(app, {
88 username: "alice",
89 email: "[email protected]",
90 password: "alice-password-1",
9491 });
9592 rw = (
9693 await read<{ token: string }>(
@@ -424,14 +421,10 @@ describe("edits on a mirror: the origin's refusal is final", () => {
424421
425422 originApp = createApp({ dataDir: originDataDir, port: 0 });
426423 originServers = await serve(originApp);
427 await fetch(`${originServers.url}/api/v1/users`, {
428 method: "POST",
429 headers: { "content-type": "application/json" },
430 body: JSON.stringify({
431 username: ORIGIN_LOGIN,
432 email: "[email protected]",
433 password: ORIGIN_TOKEN,
434 }),
424 await passwordAccount(originApp, {
425 username: ORIGIN_LOGIN,
426 email: "[email protected]",
427 password: ORIGIN_TOKEN,
435428 });
436429 await upstream("/api/v1/repos", {
437430 method: "POST",
@@ -461,14 +454,10 @@ describe("edits on a mirror: the origin's refusal is final", () => {
461454 app = createApp({ dataDir, port: 0 });
462455 servers = await serve(app);
463456 base = servers.url;
464 await fetch(`${base}/api/v1/users`, {
465 method: "POST",
466 headers: { "content-type": "application/json" },
467 body: JSON.stringify({
468 username: "alice",
469 email: "[email protected]",
470 password: ALICE_PASSWORD,
471 }),
457 await passwordAccount(app, {
458 username: "alice",
459 email: "[email protected]",
460 password: ALICE_PASSWORD,
472461 });
473462
474463 const connected = await read<{ id: string }>(
test/edits.test.ts +13 −24
@@ -21,6 +21,7 @@ import {
2121 serveFakeForge,
2222 type FakeForge,
2323 } from "./fake-origin.ts";
24 import { passwordAccount } from "./helpers/passkey.ts";
2425
2526 const read = async <T>(response: Response): Promise<T> =>
2627 (await response.json()) as T;
@@ -61,14 +62,10 @@ describe("edits: files, branches and a pull in one call", () => {
6162 ).then((t) => t.token);
6263
6364 const signUp = async (username: string, password: string) => {
64 await fetch(`${base}/api/v1/users`, {
65 method: "POST",
66 headers: { "content-type": "application/json" },
67 body: JSON.stringify({
68 username,
69 email: `${username}@forge.test`,
70 password,
71 }),
65 await passwordAccount(app, {
66 username,
67 email: `${username}@forge.test`,
68 password,
7269 });
7370 };
7471
@@ -381,14 +378,10 @@ describe("edits on a mirror land upstream first", () => {
381378
382379 originApp = createApp({ dataDir: originDataDir, port: 0 });
383380 originServers = await serve(originApp);
384 await fetch(`${originServers.url}/api/v1/users`, {
385 method: "POST",
386 headers: { "content-type": "application/json" },
387 body: JSON.stringify({
388 username: ORIGIN_LOGIN,
389 email: "[email protected]",
390 password: ORIGIN_TOKEN,
391 }),
381 await passwordAccount(originApp, {
382 username: ORIGIN_LOGIN,
383 email: "[email protected]",
384 password: ORIGIN_TOKEN,
392385 });
393386 await upstream("/api/v1/repos", {
394387 method: "POST",
@@ -415,14 +408,10 @@ describe("edits on a mirror land upstream first", () => {
415408 app = createApp({ dataDir, port: 0 });
416409 servers = await serve(app);
417410 base = servers.url;
418 await fetch(`${base}/api/v1/users`, {
419 method: "POST",
420 headers: { "content-type": "application/json" },
421 body: JSON.stringify({
422 username: "alice",
423 email: "[email protected]",
424 password: ALICE_PASSWORD,
425 }),
411 await passwordAccount(app, {
412 username: "alice",
413 email: "[email protected]",
414 password: ALICE_PASSWORD,
426415 });
427416
428417 const connected = await read<{ id: string }>(
test/flow-stage.test.ts +2 −1
@@ -7,6 +7,7 @@ import { mkdtemp, rm } from "node:fs/promises";
77 import { tmpdir } from "node:os";
88 import { join } from "node:path";
99 import { createApp, type App } from "../src/app.ts";
10 import { passwordAccount } from "./helpers/passkey.ts";
1011 import { serve, type Servers } from "../src/http/server.ts";
1112 import {
1213 flowStage,
@@ -198,7 +199,7 @@ describe("GET /flow", () => {
198199 headers: { "content-type": "application/json", ...extra },
199200 body: JSON.stringify(body),
200201 });
201 await post("/api/v1/users", {
202 await passwordAccount(app, {
202203 username: "mira",
203204 email: "[email protected]",
204205 password: "flow-stage-pass",
test/fork-flow.test.ts +7 −14
@@ -1,5 +1,6 @@
11 import { afterAll, beforeAll, describe, expect, test } from "bun:test";
22 import { mkdtemp, rm } from "node:fs/promises";
3 import { passwordAccount } from "./helpers/passkey.ts";
34 import { tmpdir } from "node:os";
45 import { join } from "node:path";
56 import { createApp, type App } from "../src/app.ts";
@@ -89,16 +90,8 @@ describe("the fork flow", () => {
8990 return fetch(`${originServers.url}${path}`, { ...init, headers });
9091 };
9192
92 async function mkAccount(server: Servers, username: string): Promise<string> {
93 await fetch(`${server.url}/api/v1/users`, {
94 method: "POST",
95 headers: { "content-type": "application/json" },
96 body: JSON.stringify({
97 username,
98 email: `${username}@f.dev`,
99 password: PASSWORD,
100 }),
101 });
93 async function mkAccount(forge: App, server: Servers, username: string): Promise<string> {
94 await passwordAccount(forge, { username, email: `${username}@f.dev`, password: PASSWORD });
10295 const token = await read<{ token: string }>(
10396 await fetch(`${server.url}/api/v1/tokens`, {
10497 method: "POST",
@@ -162,8 +155,8 @@ describe("the fork flow", () => {
162155 // ---- the upstream forge: the git host behind every fake clone URL ----
163156 originApp = createApp({ dataDir: originDataDir, port: 0 });
164157 originServers = await serve(originApp);
165 await mkAccount(originServers, UPSTREAM_OWNER);
166 originToken = await mkAccount(originServers, ORIGIN_LOGIN);
158 await mkAccount(originApp, originServers, UPSTREAM_OWNER);
159 originToken = await mkAccount(originApp, originServers, ORIGIN_LOGIN);
167160 proveAll(originApp);
168161
169162 await seedUpstream("gears");
@@ -229,8 +222,8 @@ describe("the fork flow", () => {
229222 app = createApp({ dataDir, port: 0 });
230223 servers = await serve(app);
231224 base = servers.url;
232 aliceToken = await mkAccount(servers, "alice");
233 bobToken = await mkAccount(servers, "bob");
225 aliceToken = await mkAccount(app, servers, "alice");
226 bobToken = await mkAccount(app, servers, "bob");
234227 proveAll(app);
235228
236229 forgejoOrigin = await connect(forgejo);
test/git-ssh.test.ts +4 −3
@@ -34,6 +34,7 @@ import type { SshServer } from "../src/ssh/server.ts";
3434 import { serve, type Servers } from "../src/http/server.ts";
3535 import { gitClientEnv } from "./helpers/git-client.ts";
3636 import { missing } from "./helpers/tools.ts";
37 import { testPasskey } from "./helpers/passkey.ts";
3738
3839 quietLogs();
3940
@@ -111,12 +112,12 @@ describe.skipIf(NO_OPENSSH)("git over ssh", () => {
111112 const a = await signUp(forge, {
112113 username: "alice",
113114 email: "[email protected]",
114 password: "a-long-passphrase",
115 passkey: testPasskey(),
115116 });
116117 const b = await signUp(forge, {
117118 username: "bob",
118119 email: "[email protected]",
119 password: "another-long-passphrase",
120 passkey: testPasskey(),
120121 });
121122 if (!a.ok || !b.ok) throw new Error("signup failed");
122123 alice = a.value;
@@ -322,7 +323,7 @@ describe.skipIf(NO_OPENSSH)("a git service outlives neither the channel nor the
322323 const alice = await signUp(forge, {
323324 username: "alice",
324325 email: "[email protected]",
325 password: "a-long-passphrase",
326 passkey: testPasskey(),
326327 });
327328 if (!alice.ok) throw new Error("signup failed");
328329 const repo = await createRepo(forge, alice.value, {
test/hardening.test.ts +3 −2
@@ -17,6 +17,7 @@ import { repoDir } from "../src/git/repos.ts";
1717 import { serve, type Servers } from "../src/http/server.ts";
1818 import { renderMarkdown } from "../src/web/markdown.ts";
1919 import { gitClientEnv } from "./helpers/git-client.ts";
20 import { webSignUp } from "./helpers/passkey.ts";
2021
2122 const gitEnv = gitClientEnv({
2223 GIT_AUTHOR_NAME: "T",
@@ -206,7 +207,7 @@ describe("running-forge attacks", () => {
206207 servers = await serve(app);
207208 base = servers.url;
208209
209 await fetch(`${base}/signup`, {
210 await webSignUp(base, ``, {
210211 method: "POST",
211212 body: new URLSearchParams({
212213 username: "t",
@@ -219,7 +220,7 @@ describe("running-forge attacks", () => {
219220 });
220221 token = await fetch(`${base}/api/v1/tokens`, {
221222 method: "POST",
222 headers: { "content-type": "application/json" },
223 headers: { "content-type": "application/json", cookie },
223224 body: JSON.stringify({ adminConfirm: true,
224225 username: "t",
225226 password: "long-enough-pass",
test/helpers/passkey.ts added +136
@@ -0,0 +1,136 @@
1 /**
2 * Being a new account under test. Sign-up takes a passkey (#1618), so a
3 * suite that needs people makes them the way a browser would: a software
4 * authenticator that signs like one (`device`), the sign-up form posted
5 * with what it made (`webSignUp`), or — for the action — a passkey that
6 * was already verified (`testPasskey`). `passwordAccount` is an account
7 * from before, which still signs in with a password.
8 */
9
10 import type { App } from "../../src/app.ts";
11 import { welcome } from "../../src/actions/verify.ts";
12 import { b64u, type Credential } from "../../src/auth/webauthn.ts";
13 import { createUser, type CreateUserError, type User } from "../../src/core/users.ts";
14 import type { Result } from "../../src/kernel/result.ts";
15
16 const te = new TextEncoder();
17 const sha = async (d: Uint8Array<ArrayBuffer>) => new Uint8Array(await crypto.subtle.digest("SHA-256", d));
18 const cat = (...p: Uint8Array[]): Uint8Array<ArrayBuffer> => { const o: Uint8Array<ArrayBuffer> = new Uint8Array(p.reduce((n, a) => n + a.length, 0)); let i = 0; for (const a of p) { o.set(a, i); i += a.length; } return o; };
19 function head(major: number, n: number): Uint8Array {
20 if (n < 24) return Uint8Array.of((major << 5) | n);
21 if (n < 256) return Uint8Array.of((major << 5) | 24, n);
22 return Uint8Array.of((major << 5) | 25, n >> 8, n & 255);
23 }
24 type V = number | string | Uint8Array | [V, V][];
25 function enc(v: V): Uint8Array {
26 if (typeof v === "number") return v >= 0 ? head(0, v) : head(1, -1 - v);
27 if (typeof v === "string") { const b = te.encode(v); return cat(head(3, b.length), b); }
28 if (v instanceof Uint8Array) return cat(head(2, v.length), v);
29 return cat(head(5, v.length), ...v.flatMap(([k, x]) => [enc(k), enc(x)]));
30 }
31 function rawToDer(raw: Uint8Array): Uint8Array<ArrayBuffer> {
32 const int = (b: Uint8Array) => { let i = 0; while (i < b.length - 1 && b[i] === 0) i++; b = b.subarray(i); if (b[0]! & 0x80) b = cat(Uint8Array.of(0), b); return cat(Uint8Array.of(2, b.length), b); };
33 const body = cat(int(raw.subarray(0, 32)), int(raw.subarray(32)));
34 return cat(Uint8Array.of(0x30, body.length), body);
35 }
36
37 /** A software authenticator for `origin`, as a browser's would answer. */
38 export async function device(origin: string, rp: string) {
39 const pair = (await crypto.subtle.generateKey({ name: "ECDSA", namedCurve: "P-256" }, true, ["sign"])) as CryptoKeyPair;
40 const jwk = await crypto.subtle.exportKey("jwk", pair.publicKey);
41 const unb = (s: string) => new Uint8Array(Buffer.from(s, "base64url"));
42 const cose: [number, V][] = [[1, 2], [3, -7], [-1, 1], [-2, unb(jwk.x!)], [-3, unb(jwk.y!)]];
43 const id = crypto.getRandomValues(new Uint8Array(32));
44 let count = 0;
45 const cd = (type: string, challenge: string) => te.encode(JSON.stringify({ type, challenge, origin }));
46 const counter = (n: number) => Uint8Array.of(n >>> 24, (n >>> 16) & 255, (n >>> 8) & 255, n & 255);
47 return {
48 credId: b64u(id),
49 async create(challenge: string) {
50 const authData = cat(await sha(te.encode(rp)), Uint8Array.of(0x45), counter(0), new Uint8Array(16), Uint8Array.of(0, id.length), id, enc(cose as V));
51 return { clientDataJSON: b64u(cd("webauthn.create", challenge)), attestationObject: b64u(enc([["fmt", "none"], ["attStmt", []], ["authData", authData]])) };
52 },
53 async get(challenge: string) {
54 const clientData = cd("webauthn.get", challenge);
55 const authData = cat(await sha(te.encode(rp)), Uint8Array.of(0x05), counter(++count));
56 const sig = rawToDer(new Uint8Array(await crypto.subtle.sign({ name: "ECDSA", hash: "SHA-256" }, pair.privateKey, cat(authData, await sha(clientData)))));
57 return { id: b64u(id), clientDataJSON: b64u(clientData), authenticatorData: b64u(authData), signature: b64u(sig) };
58 },
59 };
60 }
61 export type Device = Awaited<ReturnType<typeof device>>;
62
63 /** The device a base URL's browser would use. */
64 export const deviceFor = (base: string): Promise<Device> =>
65 device(new URL(base).origin, new URL(base).hostname);
66
67 /**
68 * Sign up at `${base}/signup${query}` as a browser does: ask for a challenge,
69 * let a device answer it, post the form with the answer. `init` is the
70 * request the old password form was (its body's `password` is ignored);
71 * the response is the form's — a 303 with the session cookie, or the page
72 * that says why not. A name the options refuse is posted without a passkey,
73 * so the page names what was wrong with it.
74 */
75 export async function webSignUp(
76 base: string,
77 query: string,
78 init: RequestInit & { body?: unknown },
79 using?: Device,
80 ): Promise<Response> {
81 const raw = init.body;
82 const fields = new URLSearchParams(
83 raw instanceof URLSearchParams || typeof raw === "string"
84 ? raw
85 : raw instanceof FormData
86 ? ([...raw.entries()].filter(([, v]) => typeof v === "string") as [string, string][])
87 : (raw as Record<string, string> | undefined),
88 );
89 fields.delete("password");
90 const headers = new Headers(init.headers);
91 headers.delete("content-type");
92 const options = await fetch(`${base}/signup/passkey/options`, {
93 method: "POST",
94 headers: { ...Object.fromEntries(headers), "content-type": "application/json" },
95 body: JSON.stringify({
96 username: fields.get("username") ?? "",
97 email: fields.get("email") ?? "",
98 "cf-turnstile-response": fields.get("cf-turnstile-response") ?? "",
99 }),
100 });
101 if (options.ok) {
102 const { challenge } = (await options.json()) as { challenge: string };
103 const made = await (using ?? (await deviceFor(base))).create(challenge);
104 fields.set("challenge", challenge);
105 fields.set("clientDataJSON", made.clientDataJSON);
106 fields.set("attestationObject", made.attestationObject);
107 }
108 return fetch(`${base}/signup${query}`, { ...init, method: "POST", headers, body: fields });
109 }
110
111 /** A passkey as the adapter hands it to `signUp`: already verified. */
112 export function testPasskey(name = "Test key"): { name: string; credential: Credential } {
113 const coord = () => b64u(crypto.getRandomValues(new Uint8Array(32)));
114 return {
115 name,
116 credential: {
117 id: b64u(crypto.getRandomValues(new Uint8Array(32))),
118 alg: "ES256",
119 key: { kty: "EC", crv: "P-256", x: coord(), y: coord() },
120 signCount: 0,
121 },
122 };
123 }
124
125 /**
126 * An account made before sign-up took a passkey: it has a password and no
127 * passkey, the first one is the admin, and its email starts as sign-up's did.
128 */
129 export async function passwordAccount(
130 app: App,
131 input: { username: string; email: string; password: string; displayName?: string },
132 ): Promise<Result<User, CreateUserError>> {
133 const made = await createUser(app.db, { ...input, adminIfFirst: true });
134 if (made.ok) await welcome(app, made.value);
135 return made;
136 }
test/issues.test.ts +4 −3
@@ -7,6 +7,7 @@ import { createIssue, listIssues, nextNumber } from "../src/core/issues.ts";
77 import { createRepo } from "../src/core/repos.ts";
88 import { createUser } from "../src/core/users.ts";
99 import { serve, type Servers } from "../src/http/server.ts";
10 import { webSignUp } from "./helpers/passkey.ts";
1011
1112 describe("issue core", () => {
1213 test("numbers are unique and monotonic across issues and pulls", async () => {
@@ -82,7 +83,7 @@ describe("issue pages end to end", () => {
8283 app = createApp({ dataDir, port: 0 });
8384 servers = await serve(app);
8485 base = servers.url;
85 const signup = await fetch(`${base}/signup`, {
86 const signup = await webSignUp(base, ``, {
8687 method: "POST",
8788 body: form({
8889 username: "mel",
@@ -208,7 +209,7 @@ describe("issue pages end to end", () => {
208209 test("the JSON API drives the full issue lifecycle", async () => {
209210 const minted = await fetch(`${base}/api/v1/tokens`, {
210211 method: "POST",
211 headers: { "content-type": "application/json" },
212 headers: { "content-type": "application/json", cookie },
212213 body: JSON.stringify({ adminConfirm: true,
213214 username: "mel",
214215 password: "issue-tracker-pass",
@@ -258,7 +259,7 @@ describe("issue pages end to end", () => {
258259 test("a read-only token cannot open an issue via API", async () => {
259260 const minted = await fetch(`${base}/api/v1/tokens`, {
260261 method: "POST",
261 headers: { "content-type": "application/json" },
262 headers: { "content-type": "application/json", cookie },
262263 body: JSON.stringify({ adminConfirm: true,
263264 username: "mel",
264265 password: "issue-tracker-pass",
test/keys.test.ts +3 −2
@@ -20,6 +20,7 @@ import {
2020 import type { User } from "../src/core/users.ts";
2121 import { serve, type Servers } from "../src/http/server.ts";
2222 import { missing } from "./helpers/tools.ts";
23 import { testPasskey } from "./helpers/passkey.ts";
2324
2425 /** Real keys come from real ssh-keygen; without it these skip, loudly. */
2526 const NO_KEYGEN = missing("ssh-keygen");
@@ -60,12 +61,12 @@ describe.skipIf(NO_KEYGEN)("ssh keys", () => {
6061 const a = await signUp(app, {
6162 username: "alice",
6263 email: "[email protected]",
63 password: "a-long-passphrase",
64 passkey: testPasskey(),
6465 });
6566 const b = await signUp(app, {
6667 username: "bob",
6768 email: "[email protected]",
68 password: "a-long-passphrase",
69 passkey: testPasskey(),
6970 });
7071 if (!a.ok || !b.ok) throw new Error("signup failed");
7172 alice = a.value;
test/onboarding.test.ts +30 −26
@@ -5,6 +5,24 @@ import { join, relative } from "node:path";
55 import { createApp, type App } from "../src/app.ts";
66 import { serve, type Servers } from "../src/http/server.ts";
77 import { gitClientEnv } from "./helpers/git-client.ts";
8 import { passwordAccount } from "./helpers/passkey.ts";
9
10 // Git over HTTP takes the account password, so these people are accounts
11 // from before sign-up took a passkey (#1618), signed in with that password.
12 async function passwordSession(
13 app: App,
14 base: string,
15 input: { username: string; email: string; password: string },
16 ): Promise<string> {
17 const made = await passwordAccount(app, input);
18 if (!made.ok) throw new Error(made.error);
19 const signin = await fetch(`${base}/signin`, {
20 method: "POST",
21 body: new URLSearchParams({ username: input.username, password: input.password }),
22 redirect: "manual",
23 });
24 return (signin.headers.get("set-cookie") ?? "").split(";")[0]!;
25 }
826
927 const gitEnv = gitClientEnv({
1028 GIT_AUTHOR_NAME: "N",
@@ -40,16 +58,11 @@ describe("onboarding: a person with just a login", () => {
4058 servers = await serve(app);
4159 base = servers.url;
4260 port = servers.port;
43 const signup = await fetch(`${base}/signup`, {
44 method: "POST",
45 body: form({
46 username: "nora",
47 email: "[email protected]",
48 password: "nora-login-secret",
49 }),
50 redirect: "manual",
61 cookie = await passwordSession(app, base, {
62 username: "nora",
63 email: "[email protected]",
64 password: "nora-login-secret",
5165 });
52 cookie = (signup.headers.get("set-cookie") ?? "").split(";")[0]!;
5366 });
5467
5568 afterAll(async () => {
@@ -100,14 +113,10 @@ describe("onboarding: a person with just a login", () => {
100113 });
101114
102115 test("push-to-create is refused into someone else's namespace", async () => {
103 await fetch(`${base}/signup`, {
104 method: "POST",
105 body: form({
106 username: "mallory",
107 email: "[email protected]",
108 password: "mallory-secret",
109 }),
110 redirect: "manual",
116 await passwordAccount(app, {
117 username: "mallory",
118 email: "[email protected]",
119 password: "mallory-secret",
111120 });
112121 const repo = join(work, "evil");
113122 await git(["init", "-q", "-b", "main", repo], work);
@@ -222,16 +231,11 @@ describe("a forge booted from a relative data dir still accepts pushes", () => {
222231 app = createApp({ dataDir, port: 0 });
223232 servers = await serve(app);
224233 port = servers.port;
225 const signup = await fetch(`${servers.url}/signup`, {
226 method: "POST",
227 body: new URLSearchParams({
228 username: "rel",
229 email: "[email protected]",
230 password: "rel-secret",
231 }),
232 redirect: "manual",
234 cookie = await passwordSession(app, servers.url, {
235 username: "rel",
236 email: "[email protected]",
237 password: "rel-secret",
233238 });
234 cookie = (signup.headers.get("set-cookie") ?? "").split(";")[0]!;
235239 });
236240
237241 afterAll(async () => {
test/orgs.test.ts +3 −6
@@ -1,5 +1,6 @@
11 import { afterAll, beforeAll, describe, expect, test } from "bun:test";
22 import { mkdtemp, rm } from "node:fs/promises";
3 import { passwordAccount } from "./helpers/passkey.ts";
34 import { tmpdir } from "node:os";
45 import { join } from "node:path";
56 import { createApp, type App } from "../src/app.ts";
@@ -206,15 +207,11 @@ describe("orgs over HTTP", () => {
206207 return await p.exited;
207208 }
208209 async function mkUser(username: string): Promise<string> {
209 await fetch(`${base}/api/v1/users`, {
210 method: "POST",
211 headers: { "content-type": "application/json" },
212 body: JSON.stringify({
210 await passwordAccount(app, {
213211 username,
214212 email: `${username}@f.dev`,
215213 password: "org-http-pass",
216 }),
217 });
214 });
218215 return fetch(`${base}/api/v1/tokens`, {
219216 method: "POST",
220217 headers: { "content-type": "application/json" },
test/origins-oauth.test.ts +3 −6
@@ -1,5 +1,6 @@
11 import { afterAll, beforeAll, describe, expect, test } from "bun:test";
22 import { mkdtemp, rm } from "node:fs/promises";
3 import { passwordAccount } from "./helpers/passkey.ts";
34 import { tmpdir } from "node:os";
45 import { join } from "node:path";
56 import { createApp, type App } from "../src/app.ts";
@@ -60,15 +61,11 @@ async function boot(kind: "github" | "forgejo"): Promise<Fixture> {
6061 const app = createApp({ dataDir, port: 0 });
6162 const servers = await serve(app);
6263 for (const username of ["alice", "bob", "carol"]) {
63 await fetch(`${servers.url}/api/v1/users`, {
64 method: "POST",
65 headers: { "content-type": "application/json" },
66 body: JSON.stringify({
64 await passwordAccount(app, {
6765 username,
6866 email: `${username}@forge.test`,
6967 password: PASSWORD,
70 }),
71 });
68 });
7269 }
7370 forgetProviders(dataDir);
7471 return { dataDir, app, servers, fake, oauth, base: servers.url };
test/origins-reconnect.test.ts +5 −12
@@ -1,5 +1,6 @@
11 import { afterAll, beforeAll, describe, expect, test } from "bun:test";
22 import { mkdtemp, rm } from "node:fs/promises";
3 import { passwordAccount } from "./helpers/passkey.ts";
34 import { tmpdir } from "node:os";
45 import { join } from "node:path";
56 import { createApp, type App } from "../src/app.ts";
@@ -218,15 +219,11 @@ describe("a frozen mirror is said, and reconnected in one click", () => {
218219 // The other forge, whose git we clone from.
219220 originApp = createApp({ dataDir: originDataDir, port: 0 });
220221 originServers = await serve(originApp);
221 await fetch(`${originServers.url}/api/v1/users`, {
222 method: "POST",
223 headers: { "content-type": "application/json" },
224 body: JSON.stringify({
222 await passwordAccount(originApp, {
225223 username: ORIGIN_LOGIN,
226224 email: "[email protected]",
227225 password: ORIGIN_TOKEN,
228 }),
229 });
226 });
230227 proveAll(originApp);
231228 await fetch(`${originServers.url}/api/v1/repos`, {
232229 method: "POST",
@@ -258,15 +255,11 @@ describe("a frozen mirror is said, and reconnected in one click", () => {
258255 ["alice", ALICE_PASSWORD],
259256 ["bob", BOB_PASSWORD],
260257 ] as const) {
261 await fetch(`${base}/api/v1/users`, {
262 method: "POST",
263 headers: { "content-type": "application/json" },
264 body: JSON.stringify({
258 await passwordAccount(app, {
265259 username,
266260 email: `${username}@forge.test`,
267261 password,
268 }),
269 });
262 });
270263 }
271264 proveAll(app);
272265
test/origins-security-auth.test.ts +11 −18
@@ -7,6 +7,7 @@ import {
77 test,
88 } from "bun:test";
99 import { mkdtemp, readFile, rm } from "node:fs/promises";
10 import { passwordAccount } from "./helpers/passkey.ts";
1011 import { tmpdir } from "node:os";
1112 import { join } from "node:path";
1213 import { createApp, type App } from "../src/app.ts";
@@ -70,17 +71,13 @@ function callerFor(base: string): Caller {
7071 };
7172 }
7273
73 async function createUsers(base: string, names: string[]): Promise<void> {
74 async function createUsers(app: App, names: string[]): Promise<void> {
7475 for (const username of names) {
75 await fetch(`${base}/api/v1/users`, {
76 method: "POST",
77 headers: { "content-type": "application/json" },
78 body: JSON.stringify({
76 await passwordAccount(app, {
7977 username,
8078 email: `${username}@forge.test`,
8179 password: PASSWORD,
82 }),
83 });
80 });
8481 }
8582 }
8683
@@ -130,7 +127,7 @@ describe("OAuth code flow: state, PKCE, redirects, and the callback URI", () =>
130127 let accounts = 0;
131128 const fresh = async (): Promise<string> => {
132129 const name = `flow${++accounts}`;
133 await createUsers(base, [name]);
130 await createUsers(app, [name]);
134131 proveAll(app);
135132 // A code flow needs the client registered by the account that starts it.
136133 await caller("/api/v1/user/origin-apps", {
@@ -175,7 +172,7 @@ describe("OAuth code flow: state, PKCE, redirects, and the callback URI", () =>
175172 servers = await serve(app);
176173 base = servers.url;
177174 caller = callerFor(base);
178 await createUsers(base, ["alice", "bob"]);
175 await createUsers(app, ["alice", "bob"]);
179176 proveAll(app);
180177 forgetProviders(dataDir);
181178 await api("/api/v1/user/origin-apps", {
@@ -478,7 +475,7 @@ describe("OAuth device flow: a flow is private to the user who started it", () =
478475 app = createApp({ dataDir, port: 0 });
479476 servers = await serve(app);
480477 api = callerFor(servers.url);
481 await createUsers(servers.url, ["alice", "bob"]);
478 await createUsers(app, ["alice", "bob"]);
482479 proveAll(app);
483480 forgetProviders(dataDir);
484481 process.env.FORGE_GITHUB_CLIENT_ID = CLIENT_ID;
@@ -590,7 +587,7 @@ describe("refresh serialisation and needs_reauth", () => {
590587 app = createApp({ dataDir, port: 0 });
591588 servers = await serve(app);
592589 api = callerFor(servers.url);
593 await createUsers(servers.url, ["alice"]);
590 await createUsers(app, ["alice"]);
594591 proveAll(app);
595592 forgetProviders(dataDir);
596593 await api("/api/v1/user/origin-apps", {
@@ -736,15 +733,11 @@ describe("authorization across origins, mirrors, pins and disconnect", () => {
736733 // The git host the mirrors fetch from: a second real forge.
737734 upstream = createApp({ dataDir: upstreamDataDir, port: 0 });
738735 upstreamServers = await serve(upstream);
739 await fetch(`${upstreamServers.url}/api/v1/users`, {
740 method: "POST",
741 headers: { "content-type": "application/json" },
742 body: JSON.stringify({
736 await passwordAccount(upstream, {
743737 username: LOGIN,
744738 email: "[email protected]",
745739 password: ORIGIN_TOKEN,
746 }),
747 });
740 });
748741 for (const name of ["widgets", "secret"]) {
749742 await fetch(`${upstreamServers.url}/api/v1/repos`, {
750743 method: "POST",
@@ -803,7 +796,7 @@ describe("authorization across origins, mirrors, pins and disconnect", () => {
803796 // Bob first: the first account is the site admin, which makes him a
804797 // writer of every repo — the one kind of non-owner writer a personal
805798 // mirror can have.
806 await createUsers(base, ["bob", "alice", "carol"]);
799 await createUsers(app, ["bob", "alice", "carol"]);
807800 proveAll(app);
808801 forgetProviders(dataDir);
809802
test/origins-security-provider.test.ts +5 −12
@@ -1,5 +1,6 @@
11 import { afterAll, beforeAll, describe, expect, test } from "bun:test";
22 import { existsSync, readdirSync, readFileSync } from "node:fs";
3 import { passwordAccount } from "./helpers/passkey.ts";
34 import { mkdtemp, rm } from "node:fs/promises";
45 import { tmpdir } from "node:os";
56 import { join } from "node:path";
@@ -408,15 +409,11 @@ describe("a hostile origin cannot reach git or the filesystem", () => {
408409 // A real git host for the one legitimate repo.
409410 upstreamApp = createApp({ dataDir: upstreamDataDir, port: 0 });
410411 upstreamServers = await serve(upstreamApp);
411 await fetch(`${upstreamServers.url}/api/v1/users`, {
412 method: "POST",
413 headers: { "content-type": "application/json" },
414 body: JSON.stringify({
412 await passwordAccount(upstreamApp, {
415413 username: LOGIN,
416414 email: "[email protected]",
417415 password: TOKEN,
418 }),
419 });
416 });
420417 await fetch(`${upstreamServers.url}/api/v1/repos`, {
421418 method: "POST",
422419 headers: {
@@ -514,15 +511,11 @@ describe("a hostile origin cannot reach git or the filesystem", () => {
514511 app = createApp({ dataDir, port: 0 });
515512 servers = await serve(app);
516513 base = servers.url;
517 await fetch(`${base}/api/v1/users`, {
518 method: "POST",
519 headers: { "content-type": "application/json" },
520 body: JSON.stringify({
514 await passwordAccount(app, {
521515 username: "alice",
522516 email: "[email protected]",
523517 password: PASSWORD,
524 }),
525 });
518 });
526519 const connected = await read<{ id: string; kind: string }>(
527520 await api("/api/v1/user/origins", {
528521 method: "POST",
test/origins-security-push.test.ts +6 −9
@@ -11,6 +11,7 @@ import {
1111 import { tmpdir } from "node:os";
1212 import { join } from "node:path";
1313 import { createApp, type App } from "../src/app.ts";
14 import { passwordAccount } from "./helpers/passkey.ts";
1415 import {
1516 advertiseRefs,
1617 isGitService,
@@ -433,15 +434,11 @@ describe("push-through, adversarially", () => {
433434 for (const [username, password] of [
434435 ["alice", ALICE_PASSWORD],
435436 ["bob", BOB_PASSWORD],
436 ]) {
437 await fetch(`${base}/api/v1/users`, {
438 method: "POST",
439 headers: { "content-type": "application/json" },
440 body: JSON.stringify({
441 username,
442 email: `${username}@forge.test`,
443 password,
444 }),
437 ] as const) {
438 await passwordAccount(app, {
439 username,
440 email: `${username}@forge.test`,
441 password,
445442 });
446443 }
447444
test/origins-sync.test.ts +9 −24
@@ -1,5 +1,6 @@
11 import { afterAll, beforeAll, describe, expect, test } from "bun:test";
22 import { mkdtemp, rm } from "node:fs/promises";
3 import { passwordAccount } from "./helpers/passkey.ts";
34 import { tmpdir } from "node:os";
45 import { join } from "node:path";
56 import { createApp, type App } from "../src/app.ts";
@@ -65,15 +66,11 @@ describe("origin sync: incremental, event-shaped, and polite", () => {
6566
6667 originApp = createApp({ dataDir: originDataDir, port: 0 });
6768 originServers = await serve(originApp);
68 await fetch(`${originServers.url}/api/v1/users`, {
69 method: "POST",
70 headers: { "content-type": "application/json" },
71 body: JSON.stringify({
69 await passwordAccount(originApp, {
7270 username: LOGIN,
7371 email: "[email protected]",
7472 password: TOKEN,
75 }),
76 });
73 });
7774 await fetch(`${originServers.url}/api/v1/repos`, {
7875 method: "POST",
7976 headers: {
@@ -129,15 +126,11 @@ describe("origin sync: incremental, event-shaped, and polite", () => {
129126 app = createApp({ dataDir, port: 0 });
130127 servers = await serve(app);
131128 base = servers.url;
132 await fetch(`${base}/api/v1/users`, {
133 method: "POST",
134 headers: { "content-type": "application/json" },
135 body: JSON.stringify({
129 await passwordAccount(app, {
136130 username: "alice",
137131 email: "[email protected]",
138132 password: PASSWORD,
139 }),
140 });
133 });
141134
142135 // GitHub is discovered by name, so connect by kind and let the fake API
143136 // stand in for api.github.com.
@@ -360,15 +353,11 @@ describe("a mirror follows the origin's visibility", () => {
360353 const upDir = await mkdtemp(join(tmpdir(), "forge-vis-up-"));
361354 const upApp = createApp({ dataDir: upDir, port: 0 });
362355 const upServers = await serve(upApp);
363 await fetch(`${upServers.url}/api/v1/users`, {
364 method: "POST",
365 headers: { "content-type": "application/json" },
366 body: JSON.stringify({
356 await passwordAccount(upApp, {
367357 username: LOGIN,
368358 email: "[email protected]",
369359 password: TOKEN,
370 }),
371 });
360 });
372361 await fetch(`${upServers.url}/api/v1/repos`, {
373362 method: "POST",
374363 headers: {
@@ -391,15 +380,11 @@ describe("a mirror follows the origin's visibility", () => {
391380
392381 const app2 = createApp({ dataDir, port: 0 });
393382 const servers2 = await serve(app2);
394 await fetch(`${servers2.url}/api/v1/users`, {
395 method: "POST",
396 headers: { "content-type": "application/json" },
397 body: JSON.stringify({
383 await passwordAccount(app2, {
398384 username: "alice",
399385 email: "[email protected]",
400386 password: PASSWORD,
401 }),
402 });
387 });
403388 const auth = { authorization: basic("alice", PASSWORD) };
404389 const connected = await read<{ id: string }>(
405390 await fetch(`${servers2.url}/api/v1/user/origins`, {
test/origins.test.ts +5 −12
@@ -1,5 +1,6 @@
11 import { afterAll, beforeAll, describe, expect, test } from "bun:test";
22 import { mkdtemp, readdir, readFile, rm } from "node:fs/promises";
3 import { passwordAccount } from "./helpers/passkey.ts";
34 import { tmpdir } from "node:os";
45 import { join } from "node:path";
56 import { createApp, type App } from "../src/app.ts";
@@ -70,15 +71,11 @@ describe("origins: connecting, mirroring, writing through", () => {
7071 // The "other forge" whose git server we actually clone from.
7172 originApp = createApp({ dataDir: originDataDir, port: 0 });
7273 originServers = await serve(originApp);
73 await fetch(`${originServers.url}/api/v1/users`, {
74 method: "POST",
75 headers: { "content-type": "application/json" },
76 body: JSON.stringify({
74 await passwordAccount(originApp, {
7775 username: ORIGIN_LOGIN,
7876 email: "[email protected]",
7977 password: ORIGIN_TOKEN,
80 }),
81 });
78 });
8279 await fetch(`${originServers.url}/api/v1/repos`, {
8380 method: "POST",
8481 headers: {
@@ -160,15 +157,11 @@ describe("origins: connecting, mirroring, writing through", () => {
160157 ["alice", ALICE_PASSWORD],
161158 ["bob", BOB_PASSWORD],
162159 ] as const) {
163 await fetch(`${base}/api/v1/users`, {
164 method: "POST",
165 headers: { "content-type": "application/json" },
166 body: JSON.stringify({
160 await passwordAccount(app, {
167161 username,
168162 email: `${username}@forge.test`,
169163 password,
170 }),
171 });
164 });
172165 }
173166 proveAll(app);
174167 });
test/parity.test.ts +3 −4
@@ -12,6 +12,7 @@ import { mkdtemp, rm } from "node:fs/promises";
1212 import { tmpdir } from "node:os";
1313 import { join } from "node:path";
1414 import { createApp, type App } from "../src/app.ts";
15 import { passwordAccount } from "./helpers/passkey.ts";
1516 import { listEvents } from "../src/core/events.ts";
1617 import { createSession, pruneSessions } from "../src/core/sessions.ts";
1718 import { getRepo } from "../src/core/repos.ts";
@@ -117,10 +118,8 @@ describe("parity: full control through actions and the API", () => {
117118 base = servers.url;
118119
119120 for (const username of ["alice", "bob", "carol"]) {
120 const res = await call("POST", "/api/v1/users", {
121 body: { username, email: `${username}@forge.test`, password: PASS },
122 });
123 expect(res.status).toBe(201);
121 const made = await passwordAccount(app, { username, email: `${username}@forge.test`, password: PASS });
122 expect(made.ok).toBe(true);
124123 }
125124 proveAll(app);
126125 aliceRw = await mint("alice", "rw");
test/passkeys.test.ts +3 −2
@@ -12,6 +12,7 @@ import { b64u } from "../src/auth/webauthn.ts";
1212 import { createToken } from "../src/core/tokens.ts";
1313 import { serve, type Servers } from "../src/http/server.ts";
1414 import { setLimit } from "../src/settings/limits.ts";
15 import { webSignUp } from "./helpers/passkey.ts";
1516
1617 const te = new TextEncoder();
1718 const sha = async (d: Uint8Array<ArrayBuffer>) => new Uint8Array(await crypto.subtle.digest("SHA-256", d));
@@ -85,7 +86,7 @@ describe("passkeys", () => {
8586 app = createApp({ dataDir, port: 0 });
8687 servers = await serve(app);
8788 base = servers.url;
88 const res = await fetch(`${base}/signup`, {
89 const res = await webSignUp(base, ``, {
8990 method: "POST",
9091 body: new URLSearchParams({ username: "pat", email: "[email protected]", password: "passkey-password" }),
9192 redirect: "manual",
@@ -174,7 +175,7 @@ describe("passkeys", () => {
174175 });
175176
176177 const signup = async (username: string) => {
177 const res = await fetch(`${base}/signup`, {
178 const res = await webSignUp(base, ``, {
178179 method: "POST",
179180 body: new URLSearchParams({ username, email: `${username}@f.dev`, password: "passkey-password" }),
180181 redirect: "manual",
test/public-url.test.ts +8 −15
@@ -5,6 +5,9 @@ import { join } from "node:path";
55 import { createApp, type App } from "../src/app.ts";
66 import { crossOrigin, publicUrl } from "../src/http/context.ts";
77 import { serve, type Servers } from "../src/http/server.ts";
8 import { createToken } from "../src/core/tokens.ts";
9 import { getUserByName } from "../src/core/users.ts";
10 import { device, webSignUp } from "./helpers/passkey.ts";
811
912 describe("publicUrl", () => {
1013 test("without a configured origin the request's URL is the truth", () => {
@@ -56,16 +59,15 @@ describe("a forge behind a TLS-terminating proxy", () => {
5659 });
5760
5861 test("signing up from the public origin succeeds and the cookie is Secure", async () => {
59 const response = await fetch(`${base}/signup`, {
62 const response = await webSignUp(base, ``, {
6063 method: "POST",
6164 headers: { origin: "https://forge.example" },
6265 body: new URLSearchParams({
6366 username: "ada",
6467 email: "[email protected]",
65 password: "analytical-engine",
6668 }),
6769 redirect: "manual",
68 });
70 }, await device("https://forge.example", "forge.example"));
6971 expect(response.status).toBe(303);
7072 const cookie = response.headers.get("set-cookie") ?? "";
7173 expect(cookie).toStartWith("forge_session=");
@@ -73,7 +75,7 @@ describe("a forge behind a TLS-terminating proxy", () => {
7375 });
7476
7577 test("the proxy's own origin is a stranger", async () => {
76 const response = await fetch(`${base}/signup`, {
78 const response = await webSignUp(base, ``, {
7779 method: "POST",
7880 headers: { origin: base },
7981 body: new URLSearchParams({
@@ -87,17 +89,8 @@ describe("a forge behind a TLS-terminating proxy", () => {
8789 });
8890
8991 test("clone URLs name the public address", async () => {
90 const token = await fetch(`${base}/api/v1/tokens`, {
91 method: "POST",
92 body: JSON.stringify({ adminConfirm: true,
93 username: "ada",
94 password: "analytical-engine",
95 name: "cli",
96 scope: "rw",
97 }),
98 })
99 .then((r) => r.json() as Promise<{ token: string }>)
100 .then((body) => body.token);
92 const ada = getUserByName(app.db, "ada")!;
93 const token = createToken(app.db, ada.id, "cli", "rw").token;
10194 const created = await fetch(`${base}/api/v1/repos`, {
10295 method: "POST",
10396 headers: { authorization: `Bearer ${token}` },
test/pull-mergeable.test.ts +7 −6
@@ -5,6 +5,7 @@ import { join } from "node:path";
55 import { createApp, type App } from "../src/app.ts";
66 import { serve, type Servers } from "../src/http/server.ts";
77 import { gitClientEnv } from "./helpers/git-client.ts";
8 import { webSignUp } from "./helpers/passkey.ts";
89
910 const gitEnv = gitClientEnv();
1011
@@ -71,7 +72,7 @@ describe("a pull says whether it merges", () => {
7172 app = createApp({ dataDir, port: 0 });
7273 servers = await serve(app);
7374 base = servers.url;
74 await fetch(`${base}/signup`, {
75 const cookie = await webSignUp(base, ``, {
7576 method: "POST",
7677 body: new URLSearchParams({
7778 username: "dev",
@@ -79,10 +80,10 @@ describe("a pull says whether it merges", () => {
7980 password: "pull-mergeable-pass",
8081 }),
8182 redirect: "manual",
82 });
83 }).then((r) => (r.headers.get("set-cookie") ?? "").split(";")[0]!);
8384 token = await fetch(`${base}/api/v1/tokens`, {
8485 method: "POST",
85 headers: { "content-type": "application/json" },
86 headers: { "content-type": "application/json", cookie },
8687 body: JSON.stringify({
8788 adminConfirm: true,
8889 username: "dev",
@@ -157,7 +158,7 @@ describe("a pull says whether it merges", () => {
157158 test("a sealed pull answers no_such_pull to a reader who cannot see it", async () => {
158159 const sealed = await mcp("seal", { repo: "dev/app", number: 1, sealed: true });
159160 expect(sealed.sealed).toBe(true);
160 await fetch(`${base}/signup`, {
161 const cookie = await webSignUp(base, ``, {
161162 method: "POST",
162163 body: new URLSearchParams({
163164 username: "eve",
@@ -165,10 +166,10 @@ describe("a pull says whether it merges", () => {
165166 password: "eve-reader-pass-1",
166167 }),
167168 redirect: "manual",
168 });
169 }).then((r) => (r.headers.get("set-cookie") ?? "").split(";")[0]!);
169170 const eve = await fetch(`${base}/api/v1/tokens`, {
170171 method: "POST",
171 headers: { "content-type": "application/json" },
172 headers: { "content-type": "application/json", cookie },
172173 body: JSON.stringify({
173174 adminConfirm: true,
174175 username: "eve",
test/pull-variants.test.ts +4 −3
@@ -16,6 +16,7 @@ import { createToken } from "../src/core/tokens.ts";
1616 import { createUser, type User } from "../src/core/users.ts";
1717 import { queueAgentRun, startCrew, type CrewHandle } from "../src/crew/dispatch.ts";
1818 import { gitClientEnv } from "./helpers/git-client.ts";
19 import { webSignUp } from "./helpers/passkey.ts";
1920
2021 const gitEnv = gitClientEnv();
2122
@@ -82,7 +83,7 @@ describe("a pull says its variant group and siblings", () => {
8283 app = createApp({ dataDir, port: 0 });
8384 servers = await serve(app);
8485 base = servers.url;
85 await fetch(`${base}/signup`, {
86 const cookie = await webSignUp(base, ``, {
8687 method: "POST",
8788 body: new URLSearchParams({
8889 username: "dev",
@@ -90,10 +91,10 @@ describe("a pull says its variant group and siblings", () => {
9091 password: "pull-variants-pass",
9192 }),
9293 redirect: "manual",
93 });
94 }).then((r) => (r.headers.get("set-cookie") ?? "").split(";")[0]!);
9495 token = await fetch(`${base}/api/v1/tokens`, {
9596 method: "POST",
96 headers: { "content-type": "application/json" },
97 headers: { "content-type": "application/json", cookie },
9798 body: JSON.stringify({
9899 adminConfirm: true,
99100 username: "dev",
test/pulls.test.ts +3 −2
@@ -5,6 +5,7 @@ import { join } from "node:path";
55 import { createApp, type App } from "../src/app.ts";
66 import { serve, type Servers } from "../src/http/server.ts";
77 import { gitClientEnv } from "./helpers/git-client.ts";
8 import { webSignUp } from "./helpers/passkey.ts";
89
910 const gitEnv = gitClientEnv();
1011
@@ -55,7 +56,7 @@ describe("pull requests end to end", () => {
5556 servers = await serve(app);
5657 base = servers.url;
5758
58 const signup = await fetch(`${base}/signup`, {
59 const signup = await webSignUp(base, ``, {
5960 method: "POST",
6061 body: form({
6162 username: "dev",
@@ -67,7 +68,7 @@ describe("pull requests end to end", () => {
6768 cookie = (signup.headers.get("set-cookie") ?? "").split(";")[0]!;
6869 token = await fetch(`${base}/api/v1/tokens`, {
6970 method: "POST",
70 headers: { "content-type": "application/json" },
71 headers: { "content-type": "application/json", cookie },
7172 body: JSON.stringify({ adminConfirm: true,
7273 username: "dev",
7374 password: "pull-request-pass",
test/push-through.test.ts +5 −12
@@ -1,5 +1,6 @@
11 import { afterAll, beforeAll, describe, expect, test } from "bun:test";
22 import { mkdtemp, readFile, rm } from "node:fs/promises";
3 import { passwordAccount } from "./helpers/passkey.ts";
34 import { tmpdir } from "node:os";
45 import { join } from "node:path";
56 import { createApp, type App } from "../src/app.ts";
@@ -90,15 +91,11 @@ describe("push-through: the origin gets the last word", () => {
9091
9192 originApp = createApp({ dataDir: originDataDir, port: 0 });
9293 originServers = await serve(originApp);
93 await fetch(`${originServers.url}/api/v1/users`, {
94 method: "POST",
95 headers: { "content-type": "application/json" },
96 body: JSON.stringify({
94 await passwordAccount(originApp, {
9795 username: ORIGIN_LOGIN,
9896 email: "[email protected]",
9997 password: ORIGIN_TOKEN,
100 }),
101 });
98 });
10299 await upstream("/api/v1/repos", {
103100 method: "POST",
104101 body: JSON.stringify({ name: "gears", visibility: "public" }),
@@ -124,15 +121,11 @@ describe("push-through: the origin gets the last word", () => {
124121 app = createApp({ dataDir, port: 0 });
125122 servers = await serve(app);
126123 base = servers.url;
127 await fetch(`${base}/api/v1/users`, {
128 method: "POST",
129 headers: { "content-type": "application/json" },
130 body: JSON.stringify({
124 await passwordAccount(app, {
131125 username: "alice",
132126 email: "[email protected]",
133127 password: ALICE_PASSWORD,
134 }),
135 });
128 });
136129
137130 const connected = await read<{ id: string }>(
138131 await api("/api/v1/user/origins", {
test/read-api.test.ts +3 −6
@@ -1,5 +1,6 @@
11 import { afterAll, beforeAll, describe, expect, test } from "bun:test";
22 import { mkdtemp, rm } from "node:fs/promises";
3 import { passwordAccount } from "./helpers/passkey.ts";
34 import { tmpdir } from "node:os";
45 import { join } from "node:path";
56 import { createApp, type App } from "../src/app.ts";
@@ -29,15 +30,11 @@ describe("read-back API (contents, branches, commits)", () => {
2930 app = createApp({ dataDir, port: 0 });
3031 servers = await serve(app);
3132 base = servers.url;
32 await fetch(`${base}/api/v1/users`, {
33 method: "POST",
34 headers: { "content-type": "application/json" },
35 body: JSON.stringify({
33 await passwordAccount(app, {
3634 username: "dev",
3735 email: "[email protected]",
3836 password: "read-api-pass",
39 }),
40 });
37 });
4138 token = await fetch(`${base}/api/v1/tokens`, {
4239 method: "POST",
4340 headers: { "content-type": "application/json" },
test/reserved-names.test.ts +28 −18
@@ -14,7 +14,10 @@ import {
1414 } from "../src/core/users.ts";
1515 import { isSafeName } from "../src/git/guard.ts";
1616 import { buildRouter, serve, type Servers } from "../src/http/server.ts";
17 import { createSession } from "../src/core/sessions.ts";
1718 import { proveAll } from "./helpers/verified.ts";
19 import { setLimit } from "../src/settings/limits.ts";
20 import { webSignUp, testPasskey } from "./helpers/passkey.ts";
1821
1922 // A fresh outsider tries every way in with a name that is not theirs to take:
2023 // an agent's, the owner's, a system name, or a page of the forge itself.
@@ -33,9 +36,12 @@ describe("reserved names", () => {
3336 const owner = await signUp(app, {
3437 username: "trevato",
3538 email: "[email protected]",
36 password: "owner-passphrase",
39 passkey: testPasskey(),
3740 });
3841 if (!owner.ok) throw new Error(owner.error);
42 // One client tries many names in a minute here, which the sign-up
43 // options' own limit (#1891) is there to stop; this suite is about names.
44 setLimit(app.db, "signin.per_account", 1_000, owner.value.id);
3945 for (const name of ["scout", "torque"]) {
4046 const made = await createUser(app.db, { trusted: true,
4147 username: name,
@@ -52,16 +58,27 @@ describe("reserved names", () => {
5258 await rm(dataDir, { recursive: true, force: true });
5359 });
5460
55 const signup = (username: string) =>
56 fetch(`${base}/api/v1/users`, {
61 // Sign up as a browser does (#1618), answered as the API once was: 201
62 // when the account is made, 422 with the reason the name was refused.
63 const signup = async (username: string): Promise<Response> => {
64 const email = `${username.toLowerCase()}-${Math.random()}@outsider.test`;
65 const options = await fetch(`${base}/signup/passkey/options`, {
5766 method: "POST",
5867 headers: { "content-type": "application/json" },
59 body: JSON.stringify({
60 username,
61 email: `${username.toLowerCase()}-${Math.random()}@outsider.test`,
62 password: "outsider-passphrase",
63 }),
68 body: JSON.stringify({ username, email }),
6469 });
70 if (!options.ok) {
71 const { error } = (await options.json()) as { error: string };
72 return Response.json({ error }, { status: options.status });
73 }
74 await options.body?.cancel();
75 const res = await webSignUp(base, "", {
76 method: "POST",
77 body: new URLSearchParams({ username, email }),
78 redirect: "manual",
79 });
80 return new Response(null, { status: res.status === 303 ? 201 : res.status });
81 };
6582
6683 test("a skeleton folds case, separators and look-alike digits", () => {
6784 expect(skeleton("Sc0ut")).toBe(skeleton("scout"));
@@ -133,7 +150,7 @@ describe("reserved names", () => {
133150 });
134151
135152 test("the signup page says the name is reserved", async () => {
136 const res = await fetch(`${base}/signup`, {
153 const res = await webSignUp(base, ``, {
137154 method: "POST",
138155 headers: {
139156 "content-type": "application/x-www-form-urlencoded",
@@ -327,15 +344,8 @@ describe("reserved names", () => {
327344 expect(bare.ok).toBe(false);
328345 if (!bare.ok) expect(bare.error).toBe("name_reserved");
329346 expect(foundOrg(app.db, "security", ada.id, { allowReserved: true }).ok).toBe(true);
330 // The API door, as a signed-in person.
331 const signin = await fetch(`${base}/signin`, {
332 method: "POST",
333 headers: { origin: base },
334 body: new URLSearchParams({ username: "ada", password: "outsider-passphrase" }),
335 redirect: "manual",
336 });
337 const cookie = (signin.headers.get("set-cookie") ?? "").split(";")[0]!;
338 expect(cookie).toContain("=");
347 // The API door, as a signed-in person (a passkey account: no password).
348 const cookie = `forge_session=${createSession(app.db, ada.id).token}`;
339349 for (const name of ["trevat0", "scout-bot", "settings"]) {
340350 const res = await fetch(`${base}/api/v1/orgs`, {
341351 method: "POST",
test/review-wait.test.ts +2 −2
@@ -20,6 +20,7 @@ import { getUserByName } from "../src/core/users.ts";
2020 import { serve, type Servers } from "../src/http/server.ts";
2121 import { pullWord, type WordCtx } from "../src/web/studio/words.ts";
2222 import { quietLogs } from "./helpers/globals.ts";
23 import { webSignUp } from "./helpers/passkey.ts";
2324
2425 quietLogs();
2526
@@ -70,8 +71,7 @@ describe("a green agent pull and its reviewer", () => {
7071 dataDir = await mkdtemp(join(tmpdir(), "forge-review-wait-"));
7172 app = createApp({ dataDir, port: 0 });
7273 servers = await serve(app);
73 const signup = await fetch(`${servers.url}/signup`, {
74 method: "POST",
74 const signup = await webSignUp(servers.url, "", {
7575 body: new URLSearchParams({
7676 username: "alice",
7777 email: "[email protected]",
test/reviews-states.test.ts +3 −6
@@ -1,5 +1,6 @@
11 import { afterAll, beforeAll, describe, expect, test } from "bun:test";
22 import { mkdtemp, rm } from "node:fs/promises";
3 import { passwordAccount } from "./helpers/passkey.ts";
34 import { tmpdir } from "node:os";
45 import { join } from "node:path";
56 import { createApp, type App } from "../src/app.ts";
@@ -42,15 +43,11 @@ describe("review states, and the merge they gate", () => {
4243 (await response.json()) as T;
4344
4445 async function mkUser(username: string): Promise<void> {
45 await fetch(`${base}/api/v1/users`, {
46 method: "POST",
47 headers: { "content-type": "application/json" },
48 body: JSON.stringify({
46 await passwordAccount(app, {
4947 username,
5048 email: `${username}@f.dev`,
5149 password: PASSWORD,
52 }),
53 });
50 });
5451 const token = await read<{ token: string }>(
5552 await fetch(`${base}/api/v1/tokens`, {
5653 method: "POST",
test/reviews.test.ts +4 −3
@@ -6,6 +6,7 @@ import { createApp, type App } from "../src/app.ts";
66 import { serve, type Servers } from "../src/http/server.ts";
77 import { hashLine } from "../src/core/reviews.ts";
88 import { gitClientEnv } from "./helpers/git-client.ts";
9 import { webSignUp } from "./helpers/passkey.ts";
910
1011 const gitEnv = gitClientEnv({
1112 GIT_AUTHOR_NAME: "Rev",
@@ -56,7 +57,7 @@ describe("review comments on diff lines", () => {
5657 servers = await serve(app);
5758 base = servers.url;
5859
59 const signup = await fetch(`${base}/signup`, {
60 const signup = await webSignUp(base, ``, {
6061 method: "POST",
6162 body: form({
6263 username: "rev",
@@ -68,7 +69,7 @@ describe("review comments on diff lines", () => {
6869 cookie = (signup.headers.get("set-cookie") ?? "").split(";")[0]!;
6970 token = await fetch(`${base}/api/v1/tokens`, {
7071 method: "POST",
71 headers: { "content-type": "application/json" },
72 headers: { "content-type": "application/json", cookie },
7273 body: JSON.stringify({ adminConfirm: true,
7374 username: "rev",
7475 password: "review-me-please",
@@ -181,7 +182,7 @@ describe("review comments on diff lines", () => {
181182 test("a read-only token cannot post a review comment", async () => {
182183 const roToken = await fetch(`${base}/api/v1/tokens`, {
183184 method: "POST",
184 headers: { "content-type": "application/json" },
185 headers: { "content-type": "application/json", cookie },
185186 body: JSON.stringify({ adminConfirm: true,
186187 username: "rev",
187188 password: "review-me-please",
test/scale.test.ts +9 −8
@@ -53,6 +53,7 @@ import {
5353 } from "../src/git/read.ts";
5454 import { quietLogs } from "./helpers/globals.ts";
5555 import type { User } from "../src/core/users.ts";
56 import { testPasskey } from "./helpers/passkey.ts";
5657
5758 quietLogs();
5859
@@ -81,12 +82,12 @@ describe("the index carries the hot queries", () => {
8182 const a = await signUp(app, {
8283 username: "alice",
8384 email: "[email protected]",
84 password: "a-long-alice-password",
85 passkey: testPasskey(),
8586 });
8687 const b = await signUp(app, {
8788 username: "bob",
8889 email: "[email protected]",
89 password: "a-long-bob-password",
90 passkey: testPasskey(),
9091 });
9192 if (!a.ok || !b.ok) throw new Error("seed users");
9293 alice = a.value;
@@ -233,7 +234,7 @@ describe("grouped reads answer exactly what the per-row ones did", () => {
233234 const a = await signUp(app, {
234235 username: "alice",
235236 email: "[email protected]",
236 password: "a-long-alice-password",
237 passkey: testPasskey(),
237238 });
238239 if (!a.ok) throw new Error("seed");
239240 alice = a.value;
@@ -406,18 +407,18 @@ describe("visibility is enforced in SQL, not after the fact", () => {
406407 const admin = await signUp(app, {
407408 username: "keeper",
408409 email: "[email protected]",
409 password: "a-long-keeper-password",
410 passkey: testPasskey(),
410411 });
411412 if (!admin.ok) throw new Error(`the admin could not sign up: ${admin.error}`);
412413 const a = await signUp(app, {
413414 username: "alice",
414415 email: "[email protected]",
415 password: "a-long-alice-password",
416 passkey: testPasskey(),
416417 });
417418 const b = await signUp(app, {
418419 username: "bob",
419420 email: "[email protected]",
420 password: "a-long-bob-password",
421 passkey: testPasskey(),
421422 });
422423 if (!a.ok || !b.ok) throw new Error("seed");
423424 alice = a.value;
@@ -509,7 +510,7 @@ describe("the cat-file reader pool", () => {
509510 const a = await signUp(app, {
510511 username: "alice",
511512 email: "[email protected]",
512 password: "a-long-alice-password",
513 passkey: testPasskey(),
513514 });
514515 if (!a.ok) throw new Error("seed");
515516 const made = await createRepo(app, a.value, {
@@ -572,7 +573,7 @@ describe("a token in constant use is not a write per request", () => {
572573 const a = await signUp(app, {
573574 username: "alice",
574575 email: "[email protected]",
575 password: "a-long-alice-password",
576 passkey: testPasskey(),
576577 });
577578 if (!a.ok) throw new Error("seed");
578579 const minted = createToken(app.db, a.value.id, "hot", "ro");
test/search.test.ts +2 −9
@@ -18,6 +18,7 @@ import { tmpdir } from "node:os";
1818 import { join } from "node:path";
1919 import { LIVE_BUDGET_MS, search } from "../src/actions/search.ts";
2020 import { createApp, type App } from "../src/app.ts";
21 import { passwordAccount } from "./helpers/passkey.ts";
2122 import { getRepo, listReposVisibleTo } from "../src/core/repos.ts";
2223 import { searchLocalIssues, MAX_CODE_HITS } from "../src/core/search.ts";
2324 import { getUserByName, type User } from "../src/core/users.ts";
@@ -103,15 +104,7 @@ describe("search: one query, four sources", () => {
103104 };
104105
105106 const signUp = async (username: string, password: string, scope = "rw") => {
106 await fetch(`${base}/api/v1/users`, {
107 method: "POST",
108 headers: { "content-type": "application/json" },
109 body: JSON.stringify({
110 username,
111 email: `${username}@forge.test`,
112 password,
113 }),
114 });
107 await passwordAccount(app, { username, email: `${username}@forge.test`, password });
115108 return read<{ token: string }>(
116109 await fetch(`${base}/api/v1/tokens`, {
117110 method: "POST",
test/security-merge.test.ts +8 −10
@@ -15,6 +15,7 @@ import { join } from "node:path";
1515 import { createApp, type App } from "../src/app.ts";
1616 import { serve, type Servers } from "../src/http/server.ts";
1717 import { gitClientEnv } from "./helpers/git-client.ts";
18 import { passwordAccount, webSignUp } from "./helpers/passkey.ts";
1819
1920 const gitEnv = gitClientEnv({
2021 GIT_AUTHOR_NAME: "Dev",
@@ -55,14 +56,11 @@ describe("security: read-only token scope bypass on web mutation routes", () =>
5556 servers = await serve(app);
5657 base = servers.url;
5758
58 await fetch(`${base}/api/v1/users`, {
59 method: "POST",
60 headers: { "content-type": "application/json" },
61 body: JSON.stringify({
62 username: "alice",
63 password: "password12345",
64 displayName: "Alice",
65 }),
59 await passwordAccount(app, {
60 username: "alice",
61 email: "[email protected]",
62 password: "password12345",
63 displayName: "Alice",
6664 });
6765
6866 rwToken = await fetch(`${base}/api/v1/tokens`, {
@@ -262,7 +260,7 @@ describe("merge correctness (clean results, recorded for regression)", () => {
262260 servers = await serve(app);
263261 base = servers.url;
264262
265 const signup = await fetch(`${base}/signup`, {
263 const signup = await webSignUp(base, ``, {
266264 method: "POST",
267265 body: form({
268266 username: "bob",
@@ -274,7 +272,7 @@ describe("merge correctness (clean results, recorded for regression)", () => {
274272 cookie = (signup.headers.get("set-cookie") ?? "").split(";")[0]!;
275273 token = await fetch(`${base}/api/v1/tokens`, {
276274 method: "POST",
277 headers: { "content-type": "application/json" },
275 headers: { "content-type": "application/json", cookie },
278276 body: JSON.stringify({ adminConfirm: true,
279277 username: "bob",
280278 password: "merge-test-pass",
test/security-xss.test.ts +5 −7
@@ -12,6 +12,7 @@ import { join } from "node:path";
1212 import { createApp, type App } from "../src/app.ts";
1313 import { serve, type Servers } from "../src/http/server.ts";
1414 import { gitClientEnv } from "./helpers/git-client.ts";
15 import { passwordAccount } from "./helpers/passkey.ts";
1516
1617 const clientEnv = gitClientEnv({
1718 GIT_AUTHOR_NAME: "Alice",
@@ -61,13 +62,10 @@ describe("XSS through diff/highlight rendering (real server, real git)", () => {
6162 servers = await serve(app);
6263 base = servers.url;
6364
64 await api("/api/v1/users", {
65 method: "POST",
66 body: JSON.stringify({
67 username: "alice",
68 email: "[email protected]",
69 password: "correct-horse-battery",
70 }),
65 await passwordAccount(app, {
66 username: "alice",
67 email: "alice@forge.local",
68 password: "correct-horse-battery",
7169 });
7270 const minted = await api("/api/v1/tokens", {
7371 method: "POST",
test/settings.test.ts +2 −1
@@ -6,6 +6,7 @@ import { createApp, type App } from "../src/app.ts";
66 import { getRepo } from "../src/core/repos.ts";
77 import { listLabels } from "../src/core/issues.ts";
88 import { serve, type Servers } from "../src/http/server.ts";
9 import { webSignUp } from "./helpers/passkey.ts";
910
1011 describe("repo settings", () => {
1112 let dataDir: string;
@@ -18,7 +19,7 @@ describe("repo settings", () => {
1819 const form = (fields: Record<string, string>) => new URLSearchParams(fields);
1920
2021 async function signup(username: string): Promise<string> {
21 const res = await fetch(`${base}/signup`, {
22 const res = await webSignUp(base, ``, {
2223 method: "POST",
2324 body: form({
2425 username,
test/signup-passkey.test.ts added +229
@@ -0,0 +1,229 @@
1 import { afterAll, beforeAll, describe, expect, test } from "bun:test";
2 import { mkdtemp, rm } from "node:fs/promises";
3 import { tmpdir } from "node:os";
4 import { join } from "node:path";
5 import { createApp, type App } from "../src/app.ts";
6 import { recover, sendRecovery } from "../src/actions/recovery.ts";
7 import { signUp } from "../src/actions/users.ts";
8 import { passkeyIds } from "../src/core/passkeys.ts";
9 import { issueRecovery, RECOVERY_TTL_MS } from "../src/core/recovery.ts";
10 import { getUserByName, hasPassword } from "../src/core/users.ts";
11 import { serve, type Servers } from "../src/http/server.ts";
12 import type { Mail } from "../src/kernel/mail.ts";
13 import { deviceFor, passwordAccount, testPasskey, webSignUp } from "./helpers/passkey.ts";
14 import { proveAll } from "./helpers/verified.ts";
15
16 // #1618: a new account is made with a passkey and an email, never with
17 // only a password; a proven email gets a one-hour, single-use link that
18 // registers a new passkey.
19 describe("sign-up takes a passkey; a verified email recovers", () => {
20 let dataDir: string;
21 let app: App;
22 let servers: Servers;
23 let base: string;
24 const sent: Mail[] = [];
25
26 beforeAll(async () => {
27 dataDir = await mkdtemp(join(tmpdir(), "forge-signup-passkey-"));
28 app = createApp({
29 dataDir,
30 port: 0,
31 mailer: async (mail) => {
32 sent.push(mail);
33 return true;
34 },
35 });
36 servers = await serve(app);
37 base = servers.url;
38 // The owner, so the people below are not the bootstrap admin.
39 const owner = await signUp(app, { username: "olive", email: "[email protected]", passkey: testPasskey() });
40 if (!owner.ok) throw new Error(owner.error);
41 });
42 afterAll(async () => {
43 servers.stop();
44 app.close();
45 await rm(dataDir, { recursive: true, force: true });
46 });
47
48 const tokenIn = (mail: Mail | undefined): string => {
49 const match = /\/recover\?token=([A-Za-z0-9_-]+)/.exec(mail?.text ?? "");
50 if (match === null) throw new Error("no recovery link in the mail");
51 return match[1]!;
52 };
53 const post = (path: string, body: unknown, cookie?: string) =>
54 fetch(`${base}${path}`, {
55 method: "POST",
56 headers: { "content-type": "application/json", ...(cookie ? { cookie } : {}) },
57 body: JSON.stringify(body),
58 });
59
60 test("the web form signs up with a passkey and no password", async () => {
61 const res = await webSignUp(base, "", {
62 body: new URLSearchParams({ username: "pia", email: "[email protected]" }),
63 redirect: "manual",
64 });
65 expect(res.status).toBe(303);
66 expect(res.headers.get("set-cookie") ?? "").toContain("forge_session=");
67 const pia = getUserByName(app.db, "pia")!;
68 expect(passkeyIds(app.db, pia.id)).toHaveLength(1);
69 expect(hasPassword(app.db, pia.id)).toBe(false);
70 });
71
72 test("the web form refuses a password without a passkey", async () => {
73 const res = await fetch(`${base}/signup`, {
74 method: "POST",
75 body: new URLSearchParams({ username: "pwonly", email: "[email protected]", password: "a-long-password" }),
76 redirect: "manual",
77 });
78 expect(res.status).toBe(422);
79 expect(await res.text()).toContain("A new account needs a passkey");
80 expect(getUserByName(app.db, "pwonly")).toBeUndefined();
81 });
82
83 test("a passkey answering another challenge is refused", async () => {
84 const options = await post("/signup/passkey/options", { username: "forged", email: "[email protected]" });
85 const { challenge } = (await options.json()) as { challenge: string };
86 const made = await (await deviceFor(base)).create("not-the-challenge");
87 const res = await fetch(`${base}/signup`, {
88 method: "POST",
89 body: new URLSearchParams({ username: "forged", email: "[email protected]", challenge, ...made }),
90 redirect: "manual",
91 });
92 expect(res.status).toBe(422);
93 expect(getUserByName(app.db, "forged")).toBeUndefined();
94 });
95
96 test("one passkey does not make two accounts", async () => {
97 const key = testPasskey();
98 expect((await signUp(app, { username: "uno", email: "[email protected]", passkey: key })).ok).toBe(true);
99 const again = await signUp(app, { username: "dos", email: "[email protected]", passkey: key });
100 expect(again.ok ? "made" : again.error).toBe("passkey_taken");
101 expect(getUserByName(app.db, "dos")).toBeUndefined();
102 });
103
104 test("the API makes no account, password or not", async () => {
105 const res = await post("/api/v1/users", { username: "apiuser", email: "[email protected]", password: "a-long-password" });
106 expect(res.status).toBe(422);
107 expect(((await res.json()) as { error: string }).error).toBe("passkey_required");
108 expect(getUserByName(app.db, "apiuser")).toBeUndefined();
109 });
110
111 test("Settings invites a password account to add a passkey, and only it", async () => {
112 const old = await passwordAccount(app, { username: "petra", email: "[email protected]", password: "petra-passphrase" });
113 if (!old.ok) throw new Error(old.error);
114 proveAll(app);
115 const signin = await fetch(`${base}/signin`, {
116 method: "POST",
117 body: new URLSearchParams({ username: "petra", password: "petra-passphrase" }),
118 redirect: "manual",
119 });
120 expect(signin.status).toBe(303);
121 const cookie = (signin.headers.get("set-cookie") ?? "").split(";")[0]!;
122 expect(await (await fetch(`${base}/settings`, { headers: { cookie } })).text()).toContain('id="passkey-invite"');
123
124 const fresh = await webSignUp(base, "", {
125 body: new URLSearchParams({ username: "quinn", email: "[email protected]" }),
126 redirect: "manual",
127 });
128 const quinn = (fresh.headers.get("set-cookie") ?? "").split(";")[0]!;
129 expect(await (await fetch(`${base}/settings`, { headers: { cookie: quinn } })).text()).not.toContain('id="passkey-invite"');
130 });
131
132 test("a passkey another sign-up kept meanwhile leaves no account behind", async () => {
133 const key = testPasskey();
134 // Both pass the passkey check before either keeps it: the first to
135 // resume keeps it, and the other's account goes with its refusal.
136 const [first, second] = await Promise.all([
137 signUp(app, { username: "uma", email: "[email protected]", passkey: key }),
138 signUp(app, { username: "vic", email: "[email protected]", passkey: key }),
139 ]);
140 expect(first.ok).toBe(true);
141 expect(second.ok ? "made" : second.error).toBe("passkey_taken");
142 expect(getUserByName(app.db, "vic")).toBeUndefined();
143 });
144
145 test("a verified email's link registers a new passkey, once", async () => {
146 await webSignUp(base, "", { body: new URLSearchParams({ username: "rosa", email: "[email protected]" }), redirect: "manual" });
147 proveAll(app);
148 const rosa = getUserByName(app.db, "rosa")!;
149 const before = sent.length;
150 const asked = await fetch(`${base}/recover`, { method: "POST", body: new URLSearchParams({ email: "[email protected]" }) });
151 expect(asked.status).toBe(200);
152 const mail = sent.slice(before).find((m) => m.to === "[email protected]");
153 const token = tokenIn(mail);
154
155 expect((await fetch(`${base}/recover?token=${token}`)).status).toBe(200);
156 const options = await post("/recover/passkey/options", { token });
157 expect(options.status).toBe(200);
158 const { challenge } = (await options.json()) as { challenge: string };
159 const phone = await deviceFor(base);
160 const res = await post("/recover/passkey", { token, challenge, ...(await phone.create(challenge)) });
161 expect(res.status).toBe(200);
162 expect(res.headers.get("set-cookie") ?? "").toContain("forge_session=");
163 expect(passkeyIds(app.db, rosa.id)).toHaveLength(2);
164
165 // Spent: the page, the options and the registration all refuse it.
166 expect((await fetch(`${base}/recover?token=${token}`)).status).toBe(400);
167 expect((await post("/recover/passkey/options", { token })).status).toBe(400);
168 const again = await post("/recover/passkey", { token, challenge, ...(await (await deviceFor(base)).create(challenge)) });
169 expect(again.status).toBe(400);
170 expect(passkeyIds(app.db, rosa.id)).toHaveLength(2);
171 });
172
173 test("an expired link is refused", () => {
174 const rosa = getUserByName(app.db, "rosa")!;
175 const now = Date.now() + 24 * 60 * 60_000; // past the resend window
176 const token = issueRecovery(app.db, rosa.id, now)!;
177 const late = recover(app, token, testPasskey(), now + RECOVERY_TTL_MS + 1);
178 expect(late.ok ? "recovered" : late.error).toBe("invalid");
179 expect(passkeyIds(app.db, rosa.id)).toHaveLength(2);
180 });
181
182 test("an unproven email is sent nothing, and the page says the same", async () => {
183 await webSignUp(base, "", { body: new URLSearchParams({ username: "sven", email: "[email protected]" }), redirect: "manual" });
184 expect(await sendRecovery(app, "[email protected]")).toBe("nobody");
185 expect(await sendRecovery(app, "[email protected]")).toBe("nobody");
186 const before = sent.length;
187 const unproven = await (await fetch(`${base}/recover`, { method: "POST", body: new URLSearchParams({ email: "[email protected]" }) })).text();
188 const stranger = await (await fetch(`${base}/recover`, { method: "POST", body: new URLSearchParams({ email: "[email protected]" }) })).text();
189 expect(sent.length).toBe(before);
190 expect(unproven).toContain("If that address is verified");
191 expect(stranger).toContain("If that address is verified");
192 });
193 });
194
195 // The page that asks for a link says the same whoever is asked about; it
196 // must answer in the same time too, so it does not wait for the mailer.
197 describe("asking for a recovery link does not wait for the mail", () => {
198 test("a mailer that never answers does not hold the page", async () => {
199 const dataDir = await mkdtemp(join(tmpdir(), "forge-recover-timing-"));
200 let asked = 0;
201 const app = createApp({
202 dataDir,
203 port: 0,
204 mailer: () => {
205 asked++;
206 return new Promise<boolean>(() => {});
207 },
208 });
209 const servers = await serve(app);
210 try {
211 const owner = await signUp(app, { username: "wes", email: "[email protected]", passkey: testPasskey() });
212 if (!owner.ok) throw new Error(owner.error);
213 proveAll(app);
214 const before = asked;
215 const answer = fetch(`${servers.url}/recover`, {
216 method: "POST",
217 body: new URLSearchParams({ email: "[email protected]" }),
218 });
219 const held = new Promise<"held">((done) => setTimeout(() => done("held"), 2000));
220 const res = await Promise.race([answer, held]);
221 expect(res === "held" ? res : res.status).toBe(200);
222 expect(asked).toBe(before + 1);
223 } finally {
224 servers.stop();
225 app.close();
226 await rm(dataDir, { recursive: true, force: true });
227 }
228 });
229 });
test/sse.test.ts +2 −1
@@ -4,6 +4,7 @@ import { tmpdir } from "node:os";
44 import { join } from "node:path";
55 import { createApp, type App } from "../src/app.ts";
66 import { serve, type Servers } from "../src/http/server.ts";
7 import { webSignUp } from "./helpers/passkey.ts";
78
89 /** Read from an SSE body until `predicate(buffer)` holds or we time out. */
910 async function readUntil(
@@ -48,7 +49,7 @@ describe("SSE live event stream", () => {
4849 app = createApp({ dataDir, port: 0 });
4950 servers = await serve(app);
5051 base = servers.url;
51 const signup = await fetch(`${base}/signup`, {
52 const signup = await webSignUp(base, ``, {
5253 method: "POST",
5354 body: form({
5455 username: "sse",
test/ssh-app.test.ts +2 −1
@@ -21,6 +21,7 @@ import { createLog } from "../src/kernel/log.ts";
2121 import { serveForgeSsh } from "../src/tui/ssh.ts";
2222 import type { SshServer } from "../src/ssh/server.ts";
2323 import { missing } from "./helpers/tools.ts";
24 import { testPasskey } from "./helpers/passkey.ts";
2425
2526 quietLogs();
2627 const log = createLog("ssh-app-test");
@@ -105,7 +106,7 @@ describe.skipIf(NO_OPENSSH)("ssh into the forge", () => {
105106 const alice = await signUp(forge, {
106107 username: "alice",
107108 email: "[email protected]",
108 password: "a-long-passphrase",
109 passkey: testPasskey(),
109110 });
110111 if (!alice.ok) throw new Error("signup failed");
111112 await createRepo(forge, alice.value, {
test/ssh-site.test.ts +2 −1
@@ -5,6 +5,7 @@ import { join } from "node:path";
55 import { createApp, type App } from "../src/app.ts";
66 import { serve, type Servers } from "../src/http/server.ts";
77 import { sshCommand } from "../src/ssh/command.ts";
8 import { webSignUp } from "./helpers/passkey.ts";
89
910 describe("sshCommand", () => {
1011 test("is undefined without a listener, and names host and port with one", async () => {
@@ -51,7 +52,7 @@ describe("the terminal on the website", () => {
5152 "SHA256:abcdefghijklmnopqrstuvwxyz0123456789ABCDEFG";
5253 servers = await serve(app);
5354 base = servers.url;
54 const response = await fetch(`${base}/signup`, {
55 const response = await webSignUp(base, ``, {
5556 method: "POST",
5657 body: new URLSearchParams({
5758 username: "ada",
test/subscriptions.test.ts +3 −2
@@ -31,6 +31,7 @@ import { createUser, type User } from "../src/core/users.ts";
3131 import { startCrew, type CrewHandle } from "../src/crew/dispatch.ts";
3232 import { isRateLimited, resumeAt } from "../src/crew/limits.ts";
3333 import { serve, type Servers } from "../src/http/server.ts";
34 import { webSignUp } from "./helpers/passkey.ts";
3435
3536 const OAT = "sk-ant-oat01-personal-token-for-the-test";
3637 const KEY = "sk-ant-api03-work-key-for-the-test";
@@ -468,7 +469,7 @@ describe("the pages", () => {
468469 app = createApp({ dataDir, port: 0 });
469470 servers = await serve(app);
470471 base = servers.url;
471 const signed = await fetch(`${base}/signup`, {
472 const signed = await webSignUp(base, ``, {
472473 method: "POST",
473474 body: new URLSearchParams({
474475 username: "ada",
@@ -609,7 +610,7 @@ describe("the pages", () => {
609610 });
610611
611612 test("nobody but an admin reaches the pool", async () => {
612 const signed = await fetch(`${base}/signup`, {
613 const signed = await webSignUp(base, ``, {
613614 method: "POST",
614615 body: new URLSearchParams({
615616 username: "guest",
test/surfaces-adversarial.test.ts +2 −1
@@ -37,6 +37,7 @@ import type { App as TuiApp, Screen } from "../src/tui/app/app.ts";
3737 import { headlessTerminal } from "../src/tui/term/terminal.ts";
3838 import { statements } from "./helpers/statements.ts";
3939 import { settleApp } from "./helpers/tui.ts";
40 import { webSignUp } from "./helpers/passkey.ts";
4041
4142 quietLogs();
4243
@@ -86,7 +87,7 @@ describe("surfaces adversarial: web", () => {
8687 username: string,
8788 password = "a-good-passphrase-1",
8889 ): Promise<string> => {
89 const response = await fetch(`${base}/signup`, {
90 const response = await webSignUp(base, ``, {
9091 method: "POST",
9192 body: new URLSearchParams({
9293 username,
test/thoughts.test.ts +2 −5
@@ -1,5 +1,6 @@
11 import { afterAll, beforeAll, describe, expect, test } from "bun:test";
22 import { mkdtemp, readdir, readFile, rm } from "node:fs/promises";
3 import { passwordAccount } from "./helpers/passkey.ts";
34 import { tmpdir } from "node:os";
45 import { join } from "node:path";
56 import { createApp, type App } from "../src/app.ts";
@@ -19,11 +20,7 @@ describe("thoughts", () => {
1920 servers = await serve(app);
2021 base = servers.url;
2122 const json = { "content-type": "application/json" };
22 await fetch(`${base}/api/v1/users`, {
23 method: "POST",
24 headers: json,
25 body: JSON.stringify({ username: "mira", email: "[email protected]", password: "thoughts-pass-1" }),
26 });
23 await passwordAccount(app, { username: "mira", email: "[email protected]", password: "thoughts-pass-1" });
2724 token = await fetch(`${base}/api/v1/tokens`, {
2825 method: "POST",
2926 headers: json,
test/tui-code.test.ts +2 −1
@@ -32,6 +32,7 @@ import type { TuiIdentity } from "../src/tui/session.ts";
3232 import { headlessTerminal } from "../src/tui/term/terminal.ts";
3333 import { indexPaths, rankPaths } from "../src/tui/ui/fuzzy.ts";
3434 import { settleApp, settleUntil } from "./helpers/tui.ts";
35 import { testPasskey } from "./helpers/passkey.ts";
3536
3637 quietLogs();
3738
@@ -107,7 +108,7 @@ describe("the terminal, around the workspace", () => {
107108 const a = await signUp(forge, {
108109 username: "alice",
109110 email: "[email protected]",
110 password: "a-long-passphrase",
111 passkey: testPasskey(),
111112 });
112113 if (!a.ok) throw new Error("signup failed");
113114 alice = a.value;
test/tui-deploys.test.ts +3 −2
@@ -6,6 +6,7 @@ import { tmpdir } from "node:os";
66 import { join } from "node:path";
77 import { createRepo } from "../src/actions/repos.ts";
88 import { signUp } from "../src/actions/users.ts";
9 import { testPasskey } from "./helpers/passkey.ts";
910 import { createApp, type App as Forge } from "../src/app.ts";
1011 import { createRun } from "../src/core/runs.ts";
1112 import type { Repo } from "../src/core/repos.ts";
@@ -29,7 +30,7 @@ beforeAll(async () => {
2930 const a = await signUp(forge, {
3031 username: "alice",
3132 email: "[email protected]",
32 password: "a-long-passphrase",
33 passkey: testPasskey(),
3334 });
3435 if (!a.ok) throw new Error("signup failed");
3536 alice = a.value;
@@ -95,7 +96,7 @@ test("a non-reader sees nothing of a private repo's deploys", async () => {
9596 const b = await signUp(forge, {
9697 username: "bob",
9798 email: "[email protected]",
98 password: "a-long-passphrase",
99 passkey: testPasskey(),
99100 });
100101 if (!b.ok) throw new Error("signup failed");
101102 const r = await createRepo(forge, alice, { name: "vault", visibility: "private" });
test/tui-editor.test.ts +2 −1
@@ -33,6 +33,7 @@ import type { TuiIdentity } from "../src/tui/session.ts";
3333 import { headlessTerminal } from "../src/tui/term/terminal.ts";
3434 import { Editor, colFromDisplay, displayCol } from "../src/tui/ui/editor.ts";
3535 import { settleApp, settleUntil } from "./helpers/tui.ts";
36 import { testPasskey } from "./helpers/passkey.ts";
3637
3738 quietLogs();
3839
@@ -251,7 +252,7 @@ describe("editing a file in the terminal workspace", () => {
251252 const a = await signUp(forge, {
252253 username: "alice",
253254 email: "[email protected]",
254 password: "a-long-passphrase",
255 passkey: testPasskey(),
255256 });
256257 if (!a.ok) throw new Error("signup failed");
257258 alice = a.value;
test/tui-icons.test.ts +2 −1
@@ -34,6 +34,7 @@ import {
3434 } from "../src/tui/ui/icons.ts";
3535 import { clusterWidth, clusters, displayWidth } from "../src/tui/term/width.ts";
3636 import { settleApp, settleUntil } from "./helpers/tui.ts";
37 import { testPasskey } from "./helpers/passkey.ts";
3738
3839 quietLogs();
3940
@@ -271,7 +272,7 @@ describe("the icon set a session actually draws", () => {
271272 const a = await signUp(forge, {
272273 username: "alice",
273274 email: "[email protected]",
274 password: "a-long-passphrase",
275 passkey: testPasskey(),
275276 });
276277 if (!a.ok) throw new Error("signup failed");
277278 alice = a.value;
test/tui-mouse.test.ts +2 −1
@@ -31,6 +31,7 @@ import {
3131 type HeadlessTerminal,
3232 } from "../src/tui/term/terminal.ts";
3333 import { settleApp, settleUntil } from "./helpers/tui.ts";
34 import { testPasskey } from "./helpers/passkey.ts";
3435
3536 quietLogs();
3637
@@ -145,7 +146,7 @@ describe("the pointer", () => {
145146 const a = await signUp(forge, {
146147 username: "alice",
147148 email: "[email protected]",
148 password: "a-long-passphrase",
149 passkey: testPasskey(),
149150 });
150151 if (!a.ok) throw new Error("signup failed");
151152 alice = a.value;
test/tui-onyou.test.ts +3 −2
@@ -23,6 +23,7 @@ import { createForgeApp } from "../src/tui/forge.ts";
2323 import { headlessTerminal } from "../src/tui/term/terminal.ts";
2424 import { quietLogs } from "./helpers/globals.ts";
2525 import { settleApp } from "./helpers/tui.ts";
26 import { testPasskey } from "./helpers/passkey.ts";
2627
2728 quietLogs();
2829
@@ -76,8 +77,8 @@ describe("terminal On you: mutes and many in one move", () => {
7677 beforeAll(async () => {
7778 dir = await mkdtemp(join(tmpdir(), "forge-onyou-"));
7879 forge = createApp({ dataDir: dir, port: 0 });
79 const a = await signUp(forge, { username: "alice", email: "[email protected]", password: "a-long-passphrase" });
80 const b = await signUp(forge, { username: "bob", email: "[email protected]", password: "another-long-passphrase" });
80 const a = await signUp(forge, { username: "alice", email: "[email protected]", passkey: testPasskey() });
81 const b = await signUp(forge, { username: "bob", email: "[email protected]", passkey: testPasskey() });
8182 if (!a.ok || !b.ok) throw new Error("signup failed");
8283 alice = a.value;
8384 bob = b.value;
test/tui-screens.test.ts +11 −16
@@ -41,6 +41,7 @@ import type { TuiIdentity } from "../src/tui/session.ts";
4141 import { headlessTerminal } from "../src/tui/term/terminal.ts";
4242 import type { SshSession } from "../src/ssh/channels.ts";
4343 import { settleApp } from "./helpers/tui.ts";
44 import { passwordAccount, testPasskey } from "./helpers/passkey.ts";
4445
4546 quietLogs();
4647
@@ -147,7 +148,8 @@ describe("the terminal UI, against a real forge", () => {
147148 beforeAll(async () => {
148149 dataDir = await mkdtemp(join(tmpdir(), "forge-tui-"));
149150 forge = createApp({ dataDir, port: 0 });
150 const a = await signUp(forge, {
151 // alice is an account from before passkeys: she signs in with a password.
152 const a = await passwordAccount(forge, {
151153 username: "alice",
152154 email: "[email protected]",
153155 password: "a-long-passphrase",
@@ -155,7 +157,7 @@ describe("the terminal UI, against a real forge", () => {
155157 const b = await signUp(forge, {
156158 username: "bob",
157159 email: "[email protected]",
158 password: "another-long-passphrase",
160 passkey: testPasskey(),
159161 });
160162 if (!a.ok || !b.ok) throw new Error("signup failed");
161163 alice = a.value;
@@ -593,7 +595,8 @@ describe("a forge with no accounts", () => {
593595 await rm(dataDir, { recursive: true, force: true });
594596 });
595597
596 test("the first key through the door can create the admin account", async () => {
598 test("the first key through the door is sent to the web to make the admin account", async () => {
599 // Sign-up takes a passkey (#1618) and a terminal cannot make one.
597600 const h = boot(forge, {
598601 sshUsername: "git",
599602 remoteAddress: "127.0.0.1",
@@ -605,23 +608,15 @@ describe("a forge with no accounts", () => {
605608
606609 await h.press("s");
607610 expect(h.text()).toContain("no accounts yet");
611 expect(h.text()).toContain("/signup");
612 expect(h.text()).not.toContain("Create account");
608613 await h.typeText("founder");
609614 await h.press("tab");
610 await h.typeText("[email protected]");
611 await h.press("tab");
612615 await h.typeText("a-long-passphrase");
613616 await h.press("enter");
614617 await h.settle();
615618
616 const founder = getUserByName(forge.db, "founder");
617 expect(founder?.isAdmin).toBe(true);
618 // The key that created the account is registered to it, so the next
619 // connection needs no password.
620 const key = forge.db
621 .query<{ user_id: string }, []>("SELECT user_id FROM user_key")
622 .get();
623 expect(key?.user_id).toBe(founder!.id);
624 expect(h.text()).toContain("founder");
619 expect(getUserByName(forge.db, "founder")).toBeUndefined();
625620 h.stop();
626621 });
627622 });
@@ -733,12 +728,12 @@ describe("the forge's health in the terminal", () => {
733728 const a = await signUp(forge, {
734729 username: "chief",
735730 email: "[email protected]",
736 password: "a-long-passphrase",
731 passkey: testPasskey(),
737732 });
738733 const b = await signUp(forge, {
739734 username: "bob",
740735 email: "[email protected]",
741 password: "another-long-passphrase",
736 passkey: testPasskey(),
742737 });
743738 if (!a.ok || !b.ok) throw new Error("signup failed");
744739 expect(a.value.isAdmin).toBe(true);
test/tui-size.test.ts +2 −1
@@ -45,6 +45,7 @@ import {
4545 import { theme } from "../src/tui/ui/theme.ts";
4646 import { row, table } from "../src/tui/ui/widgets.ts";
4747 import { settleApp } from "./helpers/tui.ts";
48 import { testPasskey } from "./helpers/passkey.ts";
4849
4950 quietLogs();
5051
@@ -128,7 +129,7 @@ describe("the terminal lays out for the terminal it is in", () => {
128129 const a = await signUp(forge, {
129130 username: "alice",
130131 email: "[email protected]",
131 password: "a-long-passphrase",
132 passkey: testPasskey(),
132133 });
133134 if (!a.ok) throw new Error("signup failed");
134135 alice = a.value;
test/tui-workflows.test.ts +3 −2
@@ -43,6 +43,7 @@ import {
4343 type HeadlessTerminal,
4444 } from "../src/tui/term/terminal.ts";
4545 import { settleApp } from "./helpers/tui.ts";
46 import { testPasskey } from "./helpers/passkey.ts";
4647
4748 quietLogs();
4849
@@ -199,12 +200,12 @@ describe("reviews, threads and the merge gate", () => {
199200 const one = await signUp(forge, {
200201 username: "alice",
201202 email: "[email protected]",
202 password: "a-long-passphrase",
203 passkey: testPasskey(),
203204 });
204205 const two = await signUp(forge, {
205206 username: "bob",
206207 email: "[email protected]",
207 password: "another-long-passphrase",
208 passkey: testPasskey(),
208209 });
209210 if (!one.ok || !two.ok) throw new Error("signup failed");
210211 alice = one.value;
test/tui-workspace.test.ts +2 −1
@@ -35,6 +35,7 @@ import {
3535 type HeadlessTerminal,
3636 } from "../src/tui/term/terminal.ts";
3737 import { settleApp, settleUntil } from "./helpers/tui.ts";
38 import { testPasskey } from "./helpers/passkey.ts";
3839
3940 quietLogs();
4041
@@ -159,7 +160,7 @@ describe("the terminal workspace", () => {
159160 const a = await signUp(forge, {
160161 username: "alice",
161162 email: "[email protected]",
162 password: "a-long-passphrase",
163 passkey: testPasskey(),
163164 });
164165 if (!a.ok) throw new Error("signup failed");
165166 alice = a.value;
test/turnstile.test.ts +77 −30
@@ -10,10 +10,12 @@ import { tmpdir } from "node:os";
1010 import { join } from "node:path";
1111 import { createApp, type App } from "../src/app.ts";
1212 import { turnstileVerifier } from "../src/core/turnstile.ts";
13 import { setLimit } from "../src/settings/limits.ts";
1314 import { settleApp } from "./helpers/tui.ts";
1415 import { createForgeApp } from "../src/tui/forge.ts";
1516 import { headlessTerminal } from "../src/tui/term/terminal.ts";
1617 import { serve, type Servers } from "../src/http/server.ts";
18 import { webSignUp } from "./helpers/passkey.ts";
1719
1820 const dirs: string[] = [];
1921 const running: { app: App; servers: Servers }[] = [];
@@ -53,29 +55,30 @@ afterEach(async () => {
5355 const users = (app: App) =>
5456 app.db.query<{ n: number }, []>("SELECT COUNT(*) AS n FROM user").get()!.n;
5557
58 // Sign-up is the web form with a passkey (#1618); the API makes no accounts.
5659 const signup = (base: string, token?: string) =>
57 fetch(`${base}/api/v1/users`, {
60 webSignUp(base, ``, {
5861 method: "POST",
59 headers: { "content-type": "application/json" },
60 body: JSON.stringify({
62 redirect: "manual",
63 headers: { origin: base },
64 body: new URLSearchParams({
6165 username: "casey",
6266 email: "[email protected]",
63 password: "correct horse battery",
64 ...(token === undefined ? {} : { turnstile_token: token }),
67 ...(token === undefined ? {} : { "cf-turnstile-response": token }),
6568 }),
6669 });
6770
6871 describe("turnstile signup", () => {
6972 test("off: signup works and nobody is asked", async () => {
7073 const { app, base, asked } = await boot();
71 expect((await signup(base)).status).toBe(201);
74 expect((await signup(base)).status).toBe(303);
7275 expect(users(app)).toBe(1);
7376 expect(asked).toEqual([]);
7477 });
7578
7679 test("a good token makes the account", async () => {
7780 const { app, base, asked } = await boot({ turnstileSecret: "s" });
78 expect((await signup(base, "good")).status).toBe(201);
81 expect((await signup(base, "good")).status).toBe(303);
7982 expect(users(app)).toBe(1);
8083 expect(asked).toEqual(["good"]);
8184 });
@@ -85,9 +88,7 @@ describe("turnstile signup", () => {
8588 for (const token of [undefined, "", "bad"]) {
8689 const response = await signup(base, token);
8790 expect(response.status).toBe(422);
88 const body = (await response.json()) as { error: string; message: string };
89 expect(body.error).toBe("human_check");
90 expect(body.message).toContain("person");
91 expect(await response.text()).toContain("person");
9192 }
9293 expect(users(app)).toBe(0);
9394 });
@@ -95,7 +96,7 @@ describe("turnstile signup", () => {
9596 test("the form posts the widget's field; a bad one shows the sentence", async () => {
9697 const { app, base } = await boot({ turnstileSecret: "s" });
9798 const post = (token: string) =>
98 fetch(`${base}/signup`, {
99 webSignUp(base, ``, {
99100 method: "POST",
100101 redirect: "manual",
101102 headers: {
@@ -118,6 +119,64 @@ describe("turnstile signup", () => {
118119 });
119120 });
120121
122 // The answer to "is this address taken?" is behind the human check, at the
123 // options step and at the form, or a script could ask it one address after
124 // another (#1891).
125 describe("turnstile before an account clash", () => {
126 const options = (base: string, body: Record<string, string>) =>
127 fetch(`${base}/signup/passkey/options`, {
128 method: "POST",
129 headers: { "content-type": "application/json", origin: base },
130 body: JSON.stringify(body),
131 });
132
133 test("options for a taken email with no token answers human_check, not email_taken", async () => {
134 const { app, base } = await boot({ turnstileSecret: "s" });
135 expect((await signup(base, "good")).status).toBe(303);
136 const asked = await options(base, { username: "other", email: "[email protected]" });
137 expect(asked.status).toBe(422);
138 expect(((await asked.json()) as { error: string }).error).toBe("human_check");
139 const proven = await options(base, {
140 username: "other",
141 email: "[email protected]",
142 "cf-turnstile-response": "good",
143 });
144 expect(((await proven.json()) as { error: string }).error).toBe("email_taken");
145 expect(users(app)).toBe(1);
146 });
147
148 test("the form posted bare for a taken email says the person check, not the clash", async () => {
149 const { base } = await boot({ turnstileSecret: "s" });
150 expect((await signup(base, "good")).status).toBe(303);
151 const bare = await fetch(`${base}/signup`, {
152 method: "POST",
153 headers: { origin: base },
154 body: new URLSearchParams({ username: "other", email: "[email protected]" }),
155 });
156 expect(bare.status).toBe(422);
157 const text = await bare.text();
158 expect(text).toContain("could not tell you are a person");
159 expect(text).not.toContain("already has an account");
160 });
161
162 test("a good token is asked once: the challenge carries it to the form", async () => {
163 const { base, asked } = await boot({ turnstileSecret: "s" });
164 expect((await signup(base, "good")).status).toBe(303);
165 expect(asked).toEqual(["good"]);
166 });
167
168 test("options have their own limit per client", async () => {
169 const { app, base } = await boot();
170 setLimit(app.db, "signin.per_account", 2, "test");
171 const ask = () => options(base, { username: "ann", email: "[email protected]" });
172 expect((await ask()).status).toBe(200);
173 expect((await ask()).status).toBe(200);
174 const third = await ask();
175 expect(third.status).toBe(429);
176 expect(third.headers.get("retry-after")).not.toBeNull();
177 });
178 });
179
121180 describe("turnstileVerifier", () => {
122181 const answer = (body: unknown, status = 200) =>
123182 (async (_url: unknown, init?: RequestInit) => {
@@ -171,14 +230,9 @@ describe("turnstile doors", () => {
171230
172231 test("the admin settings line says on when Turnstile is on, and never the secret", async () => {
173232 const { base } = await boot({ turnstileSecret: "SECRET-VALUE", turnstileSiteKey: "0xSITE" });
174 expect((await signup(base, "good")).status).toBe(201);
175 const signedIn = await fetch(`${base}/signin`, {
176 method: "POST",
177 redirect: "manual",
178 headers: { "content-type": "application/x-www-form-urlencoded", origin: base },
179 body: new URLSearchParams({ username: "casey", password: "correct horse battery" }),
180 });
181 const cookie = (signedIn.headers.get("set-cookie") ?? "").split(";")[0] ?? "";
233 const signedUp = await signup(base, "good");
234 expect(signedUp.status).toBe(303);
235 const cookie = (signedUp.headers.get("set-cookie") ?? "").split(";")[0] ?? "";
182236 const page = await fetch(`${base}/settings/secrets`, { headers: { cookie } });
183237 expect(page.status).toBe(200);
184238 const text = await page.text();
@@ -229,18 +283,11 @@ describe("turnstile doors", () => {
229283 return text;
230284 }
231285
232 test("the terminal makes the first account without a token, and is never asked", async () => {
286 test("the terminal makes no account, even the first, and asks nobody", async () => {
233287 const { app, asked } = await boot({ turnstileSecret: "s" });
234 await terminalSignup(app, "casey");
235 expect(users(app)).toBe(1);
288 const text = await terminalSignup(app, "casey");
289 expect(users(app)).toBe(0);
236290 expect(asked).toEqual([]);
237 });
238
239 test("once an account exists the terminal cannot create another", async () => {
240 const { app } = await boot({ turnstileSecret: "s" });
241 await terminalSignup(app, "casey");
242 const text = await terminalSignup(app, "robin");
243 expect(users(app)).toBe(1);
244 expect(text).toContain("sign up on the web page");
291 expect(text).toContain("/signup");
245292 });
246293 });
test/variants-deck.test.ts +10 −6
@@ -9,6 +9,7 @@ import { listComments } from "../src/core/issues.ts";
99 import { getPull } from "../src/core/pulls.ts";
1010 import { getRepo } from "../src/core/repos.ts";
1111 import { gitClientEnv } from "./helpers/git-client.ts";
12 import { passwordAccount } from "./helpers/passkey.ts";
1213
1314 const gitEnv = gitClientEnv();
1415
@@ -35,15 +36,18 @@ describe("a deck chooses among sibling pulls", () => {
3536 ]);
3637 if (code !== 0) throw new Error(`git ${args.join(" ")}: ${err}`);
3738 }
39 // An account from before sign-up took a passkey: the token below is
40 // minted with its password.
3841 async function signUp(username: string): Promise<string> {
39 const res = await fetch(`${base}/signup`, {
42 await passwordAccount(app, {
43 username,
44 email: `${username}@f.dev`,
45 password: "variants-deck-pass",
46 });
47 const res = await fetch(`${base}/signin`, {
4048 method: "POST",
4149 headers: { origin: base },
42 body: new URLSearchParams({
43 username,
44 email: `${username}@f.dev`,
45 password: "variants-deck-pass",
46 }),
50 body: new URLSearchParams({ username, password: "variants-deck-pass" }),
4751 redirect: "manual",
4852 });
4953 return res.headers
test/verify-email.test.ts +9 −12
@@ -13,6 +13,7 @@ import { emailVerified } from "../src/core/verify.ts";
1313 import { missing } from "./helpers/tools.ts";
1414 import { sendMail, type Mail } from "../src/kernel/mail.ts";
1515 import { serve, type Servers } from "../src/http/server.ts";
16 import { testPasskey } from "./helpers/passkey.ts";
1617
1718 // A fresh outsider signs up and, until the link in its email is followed,
1819 // can read but cannot make or cost anything.
@@ -40,7 +41,7 @@ describe("verified email", () => {
4041 const owner = await signUp(app, {
4142 username: "olive",
4243 email: "[email protected]",
43 password: "owner-passphrase",
44 passkey: testPasskey(),
4445 });
4546 if (!owner.ok) throw new Error(owner.error);
4647 });
@@ -61,16 +62,12 @@ describe("verified email", () => {
6162
6263 const join_ = async (name: string) => {
6364 const before = sent.length;
64 const res = await fetch(`${base}/api/v1/users`, {
65 method: "POST",
66 headers: { "content-type": "application/json" },
67 body: JSON.stringify({
68 username: name,
69 email: `${name}@outsider.test`,
70 password: "outsider-passphrase",
71 }),
65 const made = await signUp(app, {
66 username: name,
67 email: `${name}@outsider.test`,
68 passkey: testPasskey(),
7269 });
73 expect(res.status).toBe(201);
70 expect(made.ok).toBe(true);
7471 const user = getUserByName(app.db, name)!;
7572 const mail = sent
7673 .slice(before)
@@ -531,11 +528,11 @@ describe("mail settings come from the secrets store first", () => {
531528 const live = createApp({ dataDir: dir, port: 0, url: "https://forge.example" });
532529 try {
533530 // Before the secrets are set the forge sends nothing.
534 const first = await signUp(live, { username: "founder", email: "[email protected]", password: "founder-passphrase" });
531 const first = await signUp(live, { username: "founder", email: "[email protected]", passkey: testPasskey() });
535532 expect(first.ok).toBe(true);
536533 setSecret(live.db, live.config.dataDir, "forge", "", "MAIL_SMTP_URL", `smtp://127.0.0.1:${relay.port}`);
537534 setSecret(live.db, live.config.dataDir, "forge", "", "MAIL_FROM", "[email protected]");
538 const made = await signUp(live, { username: "newcomer", email: "[email protected]", password: "newcomer-passphrase" });
535 const made = await signUp(live, { username: "newcomer", email: "[email protected]", passkey: testPasskey() });
539536 expect(made.ok).toBe(true);
540537 expect(rcpts).toContain("RCPT TO:<[email protected]>");
541538 } finally {
test/view-source.test.ts +10 −17
@@ -21,6 +21,7 @@ import {
2121 type FakeForge,
2222 } from "./fake-origin.ts";
2323 import { fastFirstFetch } from "./helpers/globals.ts";
24 import { passwordAccount } from "./helpers/passkey.ts";
2425
2526 /**
2627 * Browsing before mirroring.
@@ -114,15 +115,11 @@ describe("RepoSource: one repository, two places to read it from", () => {
114115 },
115116 body: JSON.stringify(body),
116117 });
117 await up(
118 "/api/v1/users",
119 {
120 username: ORIGIN_LOGIN,
121 email: "[email protected]",
122 password: ORIGIN_TOKEN,
123 },
124 false,
125 );
118 await passwordAccount(originApp, {
119 username: ORIGIN_LOGIN,
120 email: "[email protected]",
121 password: ORIGIN_TOKEN,
122 });
126123 await up("/api/v1/repos", { name: "widgets", visibility: "public" });
127124 await up("/api/v1/repos/octo/widgets/contents", {
128125 branch: "main",
@@ -271,14 +268,10 @@ describe("RepoSource: one repository, two places to read it from", () => {
271268 ["alice", ALICE_PASSWORD],
272269 ["bob", BOB_PASSWORD],
273270 ] as const) {
274 await fetch(`${base}/api/v1/users`, {
275 method: "POST",
276 headers: { "content-type": "application/json" },
277 body: JSON.stringify({
278 username,
279 email: `${username}@forge.test`,
280 password,
281 }),
271 await passwordAccount(app, {
272 username,
273 email: `${username}@forge.test`,
274 password,
282275 });
283276 }
284277 alice = getUserByName(app.db, "alice")!;
test/vitals.test.ts +2 −1
@@ -5,6 +5,7 @@ import { mkdtemp, rm } from "node:fs/promises";
55 import { tmpdir } from "node:os";
66 import { join } from "node:path";
77 import { createApp, type App } from "../src/app.ts";
8 import { passwordAccount } from "./helpers/passkey.ts";
89 import { createRun } from "../src/core/runs.ts";
910 import { vitals } from "../src/kernel/vitals.ts";
1011 import { fetchInternal } from "../src/git/hook-address.ts";
@@ -48,7 +49,7 @@ beforeAll(async () => {
4849 app = createApp({ dataDir, port: 0 });
4950 servers = await serve(app);
5051 for (const username of ["alice", "bob"])
51 await post("/api/v1/users", {
52 await passwordAccount(app, {
5253 username,
5354 email: `${username}@forge.local`,
5455 password: "a-good-passphrase",
test/web-apps.test.ts +2 −1
@@ -30,6 +30,7 @@ import { isTerminal, listRuns, type Run } from "../src/core/runs.ts";
3030 import { getUserByName, type User } from "../src/core/users.ts";
3131 import { serve, type Servers } from "../src/http/server.ts";
3232 import { quietLogs } from "./helpers/globals.ts";
33 import { webSignUp } from "./helpers/passkey.ts";
3334
3435 quietLogs();
3536
@@ -110,7 +111,7 @@ describe("apps, runs and the crew on the web", () => {
110111 };
111112
112113 const signUp = async (username: string): Promise<string> => {
113 const response = await fetch(`${base}/signup`, {
114 const response = await webSignUp(base, ``, {
114115 method: "POST",
115116 body: new URLSearchParams({
116117 username,
test/web-browse.test.ts +7 −10
@@ -31,6 +31,7 @@ import { clearViewCache } from "../src/view/cache.ts";
3131 import { quietLogs } from "./helpers/globals.ts";
3232 import { newFakeState, serveFakeForge, type FakeForge } from "./fake-origin.ts";
3333 import { codeJs } from "../src/web/client.ts";
34 import { webSignUp, passwordAccount } from "./helpers/passkey.ts";
3435
3536 quietLogs();
3637
@@ -85,7 +86,7 @@ describe("browsing an origin repository on the web", () => {
8586 };
8687
8788 const signUp = async (username: string): Promise<string> => {
88 const response = await fetch(`${base}/signup`, {
89 const response = await webSignUp(base, ``, {
8990 method: "POST",
9091 body: new URLSearchParams({
9192 username,
@@ -113,15 +114,11 @@ describe("browsing an origin repository on the web", () => {
113114 },
114115 body: JSON.stringify(body),
115116 });
116 await up(
117 "/api/v1/users",
118 {
119 username: ORIGIN_LOGIN,
120 email: "[email protected]",
121 password: ORIGIN_TOKEN,
122 },
123 false,
124 );
117 await passwordAccount(originApp, {
118 username: ORIGIN_LOGIN,
119 email: "[email protected]",
120 password: ORIGIN_TOKEN,
121 });
125122 await up("/api/v1/repos", { name: "widgets", visibility: "public" });
126123 await up("/api/v1/repos/octo/widgets/contents", {
127124 branch: "main",
test/web-code.test.ts +3 −2
@@ -43,6 +43,7 @@ import {
4343 import { liveClientJs } from "../src/web/live.ts";
4444 import { spineOf } from "../src/web/pages/explorer.ts";
4545 import { markMatch } from "../src/web/pages/search.ts";
46 import { testPasskey } from "./helpers/passkey.ts";
4647
4748 quietLogs();
4849
@@ -76,12 +77,12 @@ describe("the code browser on the web", () => {
7677 const a = await signUp(app, {
7778 username: "alice",
7879 email: "[email protected]",
79 password: PASSWORD,
80 passkey: testPasskey(),
8081 });
8182 const k = await signUp(app, {
8283 username: "kim",
8384 email: "[email protected]",
84 password: PASSWORD,
85 passkey: testPasskey(),
8586 });
8687 if (!a.ok || !k.ok) throw new Error("signup failed");
8788 alice = `forge_session=${createSession(app.db, a.value.id).token}`;
test/web-editor.test.ts +3 −2
@@ -40,6 +40,7 @@ import {
4040 } from "../src/web/pages/edit.ts";
4141 import { highlightAsset } from "../src/web/asset.ts";
4242 import { highlightToHtml } from "../src/web/highlight-html.ts";
43 import { testPasskey } from "./helpers/passkey.ts";
4344
4445 quietLogs();
4546
@@ -115,12 +116,12 @@ describe("editing files on the web", () => {
115116 const a = await signUp(app, {
116117 username: "alice",
117118 email: "[email protected]",
118 password: PASSWORD,
119 passkey: testPasskey(),
119120 });
120121 const k = await signUp(app, {
121122 username: "kim",
122123 email: "[email protected]",
123 password: PASSWORD,
124 passkey: testPasskey(),
124125 });
125126 if (!a.ok || !k.ok) throw new Error("signup failed");
126127 aliceUser = a.value;
test/web-origins.test.ts +3 −6
@@ -32,6 +32,7 @@ import {
3232 type FakeForge,
3333 type FakeOAuth,
3434 } from "./fake-origin.ts";
35 import { passwordAccount, webSignUp } from "./helpers/passkey.ts";
3536
3637 quietLogs();
3738
@@ -86,7 +87,7 @@ describe("origins on the web", () => {
8687 };
8788
8889 const signUp = async (username: string): Promise<string> => {
89 const response = await fetch(`${base}/signup`, {
90 const response = await webSignUp(base, ``, {
9091 method: "POST",
9192 body: new URLSearchParams({
9293 username,
@@ -105,14 +106,10 @@ describe("origins on the web", () => {
105106 // A second real forge, so the mirror's git fetch speaks real smart HTTP.
106107 originApp = createApp({ dataDir: originDataDir, port: 0 });
107108 originServers = await serve(originApp);
108 await fetch(`${originServers.url}/api/v1/users`, {
109 method: "POST",
110 headers: { "content-type": "application/json" },
111 body: JSON.stringify({
109 await passwordAccount(originApp, {
112110 username: ORIGIN_LOGIN,
113111 email: "[email protected]",
114112 password: ORIGIN_TOKEN,
115 }),
116113 });
117114 await fetch(`${originServers.url}/api/v1/repos`, {
118115 method: "POST",

4 more files not shown.

↑↓ navigate ↵ open ⌘↵ its app esc close

Keyboard shortcuts

Docs