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

Every signup door goes through signupAllowed and a throttled signup says when to try again #2357

Parked opened this
Closed without merging

scout/forge:scout/2322-every-signup-door-goes-through-signupall → main 1 commit fork

  • Closed without merging. Nothing was applied to main.

Review

Sign in to review this change.
12 files changed +138 −7
README.md +2
@@ -1325,6 +1325,8 @@ Per-account quotas (`src/settings/quotas.ts`) — how many `repositories` and `a
13251325
13261326 The forge setting `signup` (`src/settings/signup.ts`) is `open`, `invite` or `closed`, and `open` is the default. A forge admin who is a person changes it live — **Signup** on `/admin/limits`, `PATCH /api/v1/admin/settings` (`{"signup":"closed"}`) or the `signup` MCP tool (dry by default, admin scope, never an agent) — with no restart; any other value is a 422. `FORGE_SIGNUP` sets it at boot, and a wrong value stops the boot with a plain message; while it stays set, every restart or deploy writes it again over a change made on the page (kept as a change by `boot`), so unset it to let the page decide. Every change is kept with who made it and when, and listed beside the form. While signup is `closed` (and `invite`, until #1143), `/signup` is one sentence with no form, the API and passkey signup answer 403 `signup_closed`, the terminal offers no Create account and refuses, and a first edge sign-in for a new name is 401. Existing accounts still sign in, and the forge's first account is always made.
13271327
1328 Every signup door — the `/signup` form, `POST /api/v1/users` and `POST /signup/passkey/options` — asks `signupAllowed` (`web/pages/site.ts`): `signup.per_source` (5) and `signup.per_forge` (60) a minute on `/admin/limits`, one window shared by all three. A throttled form says how long to wait; the API and the passkey door answer 429 `rate_limited` with `retry-after`. A suite that makes more accounts than that from loopback calls `raiseSignupLimit(app)` (`test/helpers/signup-limit.ts`).
1329
13281330 ## Choosing among variants
13291331
13301332 A tell with `variants: n` starts n builders whose pulls share a variant group.
src/http/api.ts +8 −1
@@ -358,7 +358,7 @@ import {
358358 undoFleetOp,
359359 type FleetError,
360360 } from "../actions/fleet.ts";
361 import { sessionCookie } from "../web/pages/site.ts";
361 import { sessionCookie, signupAllowed } from "../web/pages/site.ts";
362362 import { cookieValue, crossOrigin, type Ctx, type Handler } from "./context.ts";
363363 import {
364364 apiError,
@@ -1196,6 +1196,13 @@ export function apiRoutes(router: Router<Handler>): void {
11961196 const input = await boundedBody(ctx.request, STRANGER_MAX);
11971197 if (input === "too_large")
11981198 return apiError("too_large", 413, `at most ${STRANGER_MAX} bytes`);
1199 const wait = signupAllowed(ctx);
1200 if (wait !== undefined)
1201 return json(
1202 { error: "rate_limited", message: `Too many sign-ups. Try again in ${wait}s.` },
1203 429,
1204 { "retry-after": String(wait) },
1205 );
11991206 const created = await signUp(
12001207 ctx.app,
12011208 {
src/web/pages/signup-passkey.ts +8 −5
@@ -16,7 +16,7 @@ import { STRANGER_MAX } from "../../http/limits.ts";
1616 import { clientAddress } from "../../http/peer.ts";
1717 import { boundedBody, json, str } from "../../http/respond.ts";
1818 import { relying, store } from "./passkeys.ts";
19 import { safeNext, sessionCookie, signinAllowed } from "./site.ts";
19 import { safeNext, sessionCookie, signupAllowed } from "./site.ts";
2020
2121 const refuse = (status: number, message: string) =>
2222 json({ error: "refused", message }, status);
@@ -41,9 +41,12 @@ function problem(ctx: Ctx, username: string, email: string): string | undefined
4141 return undefined;
4242 }
4343
44 function guard(ctx: Ctx): Response | undefined {
44 // Same-origin on both calls; the window is taken once, where the flow starts
45 // (`options`), since the second call needs a challenge only that one issues.
46 function guard(ctx: Ctx, throttle: boolean): Response | undefined {
4547 if (crossOrigin(ctx.request, ctx.url, ctx.app.log)) return refuse(403, "forbidden");
46 const wait = signinAllowed(ctx, `signup:${clientAddress(ctx.request)}`);
48 if (!throttle) return undefined;
49 const wait = signupAllowed(ctx);
4750 if (wait !== undefined)
4851 return json({ error: "rate_limited", message: `Too many attempts. Try again in ${wait}s.` }, 429, { "retry-after": String(wait) });
4952 return undefined;
@@ -51,7 +54,7 @@ function guard(ctx: Ctx): Response | undefined {
5154
5255 // POST /signup/passkey/options — a challenge, once the name and address pass.
5356 export async function signupOptions(ctx: Ctx): Promise<Response> {
54 const denied = guard(ctx);
57 const denied = guard(ctx, true);
5558 if (denied) return denied;
5659 if (signupClosed(ctx.app)) return refuse(403, SIGNUP_CLOSED_MESSAGE);
5760 const data = await boundedBody(ctx.request, STRANGER_MAX);
@@ -71,7 +74,7 @@ export async function signupOptions(ctx: Ctx): Promise<Response> {
7174
7275 // POST /signup/passkey — verify the key, make the account, start the session.
7376 export async function signupPasskey(ctx: Ctx): Promise<Response> {
74 const denied = guard(ctx);
77 const denied = guard(ctx, false);
7578 if (denied) return denied;
7679 if (signupClosed(ctx.app)) return refuse(403, SIGNUP_CLOSED_MESSAGE);
7780 const data = await boundedBody(ctx.request, STRANGER_MAX);
src/web/pages/site.ts +22 −1
@@ -460,7 +460,8 @@ export function signinAllowed(ctx: Ctx, username: string): number | undefined {
460460 * Sign-ups, throttled the same way, by the socket's peer (`clientAddress`,
461461 * which reads a forwarding header only from a proxy the operator trusts):
462462 * a source may make a few accounts a minute and the forge as a whole more.
463 * Not yet asked by any signup door. A refused call is not counted.
463 * Every signup door asks it: the form, the API and the passkey options.
464 * A refused call is not counted.
464465 */
465466 const signupLimits = new WeakMap<Ctx["app"], RateLimiter>();
466467
@@ -559,6 +560,26 @@ export async function signupSubmit(ctx: Ctx): Promise<Response> {
559560 if (form instanceof Response) return form;
560561 const username = field(form, "username");
561562 const email = field(form, "email");
563 const wait = signupAllowed(ctx);
564 if (wait !== undefined) {
565 const response = page(
566 {
567 ctx,
568 title: "Sign up",
569 body: authForm(ctx, "signup", {
570 values: { username, email },
571 errors: {
572 username: `Too many sign-ups. Try again in ${wait === 1 ? "a second" : `${wait} seconds`}.`,
573 },
574 }),
575 turnstile: siteKey(ctx) !== undefined,
576 ...(ctx.app.config.passkeyOnlySignup === true ? { scriptJs: passkeyJs } : {}),
577 },
578 429,
579 );
580 response.headers.set("retry-after", String(wait));
581 return response;
582 }
562583 const created = await signUp(
563584 ctx.app,
564585 {
test/accounts.test.ts +2
@@ -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 { raiseSignupLimit } from "./helpers/signup-limit.ts";
3031
3132 const EDGE = "edge-secret-for-accounts";
3233 const KEY_LINE =
@@ -61,6 +62,7 @@ describe("accounts: the owner sees, suspends and removes", () => {
6162 url: "https://forge.example",
6263 edgeToken: EDGE,
6364 });
65 raiseSignupLimit(app);
6466 servers = await serve(app);
6567 base = servers.url;
6668 const owner = await signUp(app, {
test/helpers/signup-limit.ts added +12
@@ -0,0 +1,12 @@
1 /**
2 * A suite that makes more accounts from loopback than one source may in a
3 * minute raises the per-source window in its own setup, through the limits
4 * table, the way an operator would on /admin/limits.
5 */
6 import type { App } from "../../src/app.ts";
7 import { setLimit } from "../../src/settings/limits.ts";
8
9 export function raiseSignupLimit(app: App): void {
10 setLimit(app.db, "signup.per_source", 1_000, "test");
11 setLimit(app.db, "signup.per_forge", 100_000, "test");
12 }
test/reserved-names.test.ts +2
@@ -15,6 +15,7 @@ import {
1515 import { isSafeName } from "../src/git/guard.ts";
1616 import { buildRouter, serve, type Servers } from "../src/http/server.ts";
1717 import { proveAll } from "./helpers/verified.ts";
18 import { raiseSignupLimit } from "./helpers/signup-limit.ts";
1819
1920 // A fresh outsider tries every way in with a name that is not theirs to take:
2021 // an agent's, the owner's, a system name, or a page of the forge itself.
@@ -27,6 +28,7 @@ describe("reserved names", () => {
2728 beforeAll(async () => {
2829 dataDir = await mkdtemp(join(tmpdir(), "forge-reserved-"));
2930 app = createApp({ dataDir, port: 0 });
31 raiseSignupLimit(app);
3032 servers = await serve(app);
3133 base = servers.url;
3234 // The owner is the first account; the crew are agents.
test/signup-closed.test.ts +2
@@ -12,6 +12,7 @@ import { setSignup, type SignupMode } from "../src/settings/signup.ts";
1212 import { signUp, signUpWithPasskey } from "../src/actions/users.ts";
1313 import { getUserByName } from "../src/core/users.ts";
1414 import { serve, type Servers } from "../src/http/server.ts";
15 import { raiseSignupLimit } from "./helpers/signup-limit.ts";
1516
1617 const TOKEN = "edge-secret-0123456789";
1718 const edge = (login: string) => ({ "x-plat-user": login, "x-plat-edge-token": TOKEN });
@@ -25,6 +26,7 @@ describe("closed signup", () => {
2526 beforeAll(async () => {
2627 dataDir = await mkdtemp(join(tmpdir(), "forge-signup-closed-"));
2728 app = createApp({ dataDir, port: 0, url: "https://forge.example", edgeToken: TOKEN });
29 raiseSignupLimit(app);
2830 servers = await serve(app);
2931 base = servers.url;
3032 });
test/signup-doors.test.ts added +73
@@ -0,0 +1,73 @@
1 /**
2 * Every signup door asks signupAllowed: the form and the API share one
3 * per-source window, a throttled one says when to try again, and the
4 * passkey door draws on the same window.
5 */
6 import { afterAll, beforeAll, describe, expect, test } from "bun:test";
7 import { mkdtemp, rm } from "node:fs/promises";
8 import { tmpdir } from "node:os";
9 import { join } from "node:path";
10 import { createApp, type App } from "../src/app.ts";
11 import { setLimit } from "../src/settings/limits.ts";
12 import { serve, type Servers } from "../src/http/server.ts";
13
14 describe("signup doors share one window", () => {
15 let dataDir: string;
16 let app: App;
17 let servers: Servers;
18 let base: string;
19
20 const viaApi = (n: number) =>
21 fetch(`${base}/api/v1/users`, {
22 method: "POST",
23 headers: { "content-type": "application/json" },
24 body: JSON.stringify({ username: `api${n}`, email: `api${n}@f.dev`, password: "long-enough-password" }),
25 });
26 const viaForm = (n: number) =>
27 fetch(`${base}/signup`, {
28 method: "POST",
29 redirect: "manual",
30 headers: { "content-type": "application/x-www-form-urlencoded", origin: base },
31 body: new URLSearchParams({ username: `form${n}`, email: `form${n}@f.dev`, password: "long-enough-password" }),
32 });
33 const viaPasskey = () =>
34 fetch(`${base}/signup/passkey/options`, {
35 method: "POST",
36 headers: { "content-type": "application/json", origin: base },
37 body: JSON.stringify({ username: "keyed", email: "[email protected]" }),
38 });
39
40 beforeAll(async () => {
41 dataDir = await mkdtemp(join(tmpdir(), "forge-signup-doors-"));
42 app = createApp({ dataDir, port: 0 });
43 setLimit(app.db, "signup.per_source", 3, "test");
44 servers = await serve(app);
45 base = servers.url;
46 });
47
48 afterAll(async () => {
49 await servers.stop();
50 app.close();
51 await rm(dataDir, { recursive: true, force: true });
52 });
53
54 test("the form and the API draw on one per-source window, and a refusal says when to retry", async () => {
55 expect((await viaApi(1)).status).toBe(201);
56 expect((await viaForm(1)).status).toBe(303);
57 expect((await viaApi(2)).status).toBe(201);
58
59 const api = await viaApi(3);
60 expect(api.status).toBe(429);
61 expect(Number(api.headers.get("retry-after"))).toBeGreaterThan(0);
62 expect(((await api.json()) as { error: string }).error).toBe("rate_limited");
63
64 const form = await viaForm(2);
65 expect(form.status).toBe(429);
66 expect(Number(form.headers.get("retry-after"))).toBeGreaterThan(0);
67 expect(await form.text()).toMatch(/Try again in/);
68
69 const passkey = await viaPasskey();
70 expect(passkey.status).toBe(429);
71 expect(Number(passkey.headers.get("retry-after"))).toBeGreaterThan(0);
72 });
73 });
test/signup-passkey.test.ts +3
@@ -14,6 +14,7 @@ import { createUser } from "../src/core/users.ts";
1414 import { errorText } from "../src/tui/screens/common.ts";
1515 import { serve, type Servers } from "../src/http/server.ts";
1616 import { device } from "./helpers/passkey.ts";
17 import { raiseSignupLimit } from "./helpers/signup-limit.ts";
1718
1819 describe("passkey sign-up", () => {
1920 let dataDir: string;
@@ -34,6 +35,7 @@ describe("passkey sign-up", () => {
3435 beforeAll(async () => {
3536 dataDir = await mkdtemp(join(tmpdir(), "forge-signup-passkey-"));
3637 app = createApp({ dataDir, port: 0, passkeyOnlySignup: true });
38 raiseSignupLimit(app);
3739 servers = await serve(app);
3840 base = servers.url;
3941 await createUser(app.db, { username: "olive", email: "[email protected]", password: "olive-password-1", trusted: true });
@@ -180,6 +182,7 @@ describe("passkey sign-up and the bot check", () => {
180182 turnstileSiteKey: "site",
181183 verifyHuman: async () => human,
182184 });
185 raiseSignupLimit(app);
183186 servers = await serve(app);
184187 base = servers.url;
185188 });
test/signup.test.ts +2
@@ -15,6 +15,7 @@ import { createSession } from "../src/core/sessions.ts";
1515 import { createToken } from "../src/core/tokens.ts";
1616 import { createUser, getUserByName, type User } from "../src/core/users.ts";
1717 import { serve, type Servers } from "../src/http/server.ts";
18 import { raiseSignupLimit } from "./helpers/signup-limit.ts";
1819
1920 describe("signup setting", () => {
2021 let dataDir: string;
@@ -182,6 +183,7 @@ describe("signup closed (#2166)", () => {
182183 beforeAll(async () => {
183184 dataDir = await mkdtemp(join(tmpdir(), "forge-signup-closed-"));
184185 app = createApp({ dataDir, port: 0, edgeToken: EDGE });
186 raiseSignupLimit(app);
185187 servers = await serve(app);
186188 });
187189 afterAll(async () => {
test/verify-email.test.ts +2
@@ -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 { raiseSignupLimit } from "./helpers/signup-limit.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.
@@ -34,6 +35,7 @@ describe("verified email", () => {
3435 return true;
3536 },
3637 });
38 raiseSignupLimit(app);
3739 servers = await serve(app);
3840 base = servers.url;
3941 // The owner predates verification; the first account is never held back.

↑↓ navigate ↵ open ⌘↵ its app esc close

Keyboard shortcuts

Docs