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

Signup resists bots and floods: a human check and rate limits #891

Closed opened this in answer to
Closed without merging

scout/forge:scout/661-signup-resists-bots-and-floods-a-human-c → main 1 commit fork

  • Closed without merging. Nothing was applied to main.

Review

Sign in to review this change.
11 files changed +338 −40
README.md +8 −1
@@ -95,7 +95,14 @@ adds `FORGE_URL` (the canonical public base URL, needed for OAuth callbacks),
9595 `FORGE_ORIGIN_ALLOW` (hosts an operator vouches for on a LAN). Behind a
9696 platform edge that signs people in for every app it serves, `FORGE_EDGE_TOKEN`
9797 is the edge's secret: a request carrying it and `X-Plat-User` is that person,
98 signed in by the platform, with an account made on first sight. Mail out
98 signed in by the platform, with an account made on first sight. Signup
99 resists bots: with `FORGE_TURNSTILE_SITE_KEY` and `FORGE_TURNSTILE_SECRET`
100 (Cloudflare Turnstile; both or neither) the signup form carries the widget and
101 the server verifies its token, at `/signup` and in `humanToken` on
102 `POST /api/v1/users`, before an account is made; unset, signup asks for no
103 check, so set them on any open forge. Signup, sign-in and an edge's first
104 sight of a person are also rate limited per socket client and for the forge as
105 a whole (429 with `Retry-After`); never keyed on a client header. Mail out
99106 (the link that proves a newcomer's email) is SMTP submission over TLS,
100107 configured by the forge-level secrets `MAIL_SMTP_URL`
101108 (`smtps://user:pass@host:465`) and `MAIL_FROM`, set live under Settings →
scripts/gate.ts +1
@@ -46,6 +46,7 @@ export const GATE: readonly string[] = [
4646 "test/settings.test.ts",
4747 "test/steer.test.ts",
4848 "test/session-settle.test.ts",
49 "test/signup-guard.test.ts",
4950 "test/landing.test.ts",
5051 "test/decide.test.ts",
5152 "test/ledger.test.ts",
src/app.ts +8
@@ -4,6 +4,7 @@
44 * side-effect-contained, so tests boot real forges by the dozen.
55 */
66
7 import type { HumanCheck } from "./core/humancheck.ts";
78 import type { MailConfig, Mailer } from "./kernel/mail.ts";
89 import type { Database } from "bun:sqlite";
910 import type { Decider } from "./crew/decide.ts";
@@ -41,6 +42,13 @@ export interface ForgeConfig {
4142 * in by the platform. Unset, those headers are a claim and are ignored.
4243 */
4344 edgeToken?: string;
45 /**
46 * The human check on signup (`core/humancheck.ts`). Unset, signup asks
47 * for none.
48 */
49 humanCheck?: HumanCheck;
50 /** Knocks a minute at a door, [per source, forge-wide], over `http/doors.ts`'s defaults. */
51 doorLimits?: Partial<Record<"signup" | "signin" | "account" | "edge", readonly [number, number]>>;
4452 /**
4553 * Let anyone, not only an admin, migrate from a host inside the network
4654 * (loopback, private ranges): a forge run for one person on one machine.
src/core/humancheck.ts added +53
@@ -0,0 +1,53 @@
1 /**
2 * The human check on signup: a Cloudflare Turnstile token, verified on the
3 * server before an account is made. Configured with a site key (shown to the
4 * browser) and a secret (never leaves the server); with neither, the check is
5 * off and the forge says so at boot. The verifier is a parameter so a test
6 * never calls out.
7 */
8
9 export interface HumanCheck {
10 readonly siteKey: string;
11 readonly secret: string;
12 /** Ask the verifier whether `token` is a human's. Default: Cloudflare. */
13 readonly verify?: (token: string, address: string) => Promise<boolean>;
14 }
15
16 export const TURNSTILE_VERIFY = "https://challenges.cloudflare.com/turnstile/v0/siteverify";
17 export const TURNSTILE_SCRIPT = "https://challenges.cloudflare.com/turnstile/v0/api.js";
18 /** A token is a short opaque string; anything longer is not one. */
19 const TOKEN_MAX = 2048;
20
21 async function cloudflare(secret: string, token: string, address: string): Promise<boolean> {
22 try {
23 const body = new URLSearchParams({ secret, response: token });
24 if (address !== "unknown") body.set("remoteip", address);
25 const res = await fetch(TURNSTILE_VERIFY, {
26 method: "POST",
27 body,
28 signal: AbortSignal.timeout(5000),
29 });
30 if (!res.ok) return false;
31 const answer = (await res.json()) as { success?: unknown };
32 return answer.success === true;
33 } catch {
34 // An unreachable verifier refuses: failing open is how a bot gets in.
35 return false;
36 }
37 }
38
39 /** True when `token` proves a human. No token, no proof. */
40 export async function isHuman(
41 check: HumanCheck,
42 token: string,
43 address: string,
44 ): Promise<boolean> {
45 if (token === "" || token.length > TOKEN_MAX) return false;
46 try {
47 return check.verify
48 ? (await check.verify(token, address)) === true
49 : await cloudflare(check.secret, token, address);
50 } catch {
51 return false;
52 }
53 }
src/http/api.ts +16 −1
@@ -302,6 +302,8 @@ import {
302302 import { frontInput, frontJson, setFront } from "../actions/front.ts";
303303 import type { Router } from "./router.ts";
304304 import { clientAddress, clientBucket } from "./peer.ts";
305 import { isHuman } from "../core/humancheck.ts";
306 import { knock, waitSentence } from "./doors.ts";
305307 import { manifestFor } from "../actions/here.ts";
306308 import {
307309 acceptReport,
@@ -978,6 +980,19 @@ export function apiRoutes(router: Router<Handler>): void {
978980 const input = await boundedBody(ctx.request, STRANGER_MAX);
979981 if (input === "too_large")
980982 return apiError("too_large", 413, `at most ${STRANGER_MAX} bytes`);
983 const address = clientAddress(ctx.request);
984 const wait = knock(ctx.app, "signup", address);
985 if (wait !== undefined) {
986 const refused = apiError("rate_limited", 429, waitSentence(wait));
987 refused.headers.set("retry-after", String(wait));
988 return refused;
989 }
990 const check = ctx.app.config.humanCheck;
991 if (
992 check !== undefined &&
993 !(await isHuman(check, str(input.humanToken), address))
994 )
995 return apiError("human_check", 422, "a valid humanToken (Turnstile) is required");
981996 const created = await signUp(
982997 ctx.app,
983998 {
@@ -985,7 +1000,7 @@ export function apiRoutes(router: Router<Handler>): void {
9851000 email: str(input.email),
9861001 password: str(input.password),
9871002 },
988 { address: clientAddress(ctx.request) },
1003 { address },
9891004 );
9901005 if (!created.ok) return json({ error: created.error }, 422);
9911006 return json(publicUser(created.value), 201);
src/http/doors.ts added +59
@@ -0,0 +1,59 @@
1 /**
2 * The doors a stranger knocks on: signup, sign-in, and the first sight of an
3 * account through the platform edge. Each is counted per source — the
4 * socket's client (`http/peer.ts`, never a header the client wrote) — and for
5 * the forge as a whole, so neither one machine nor a thousand of them can
6 * make accounts or guess passwords in bulk. A refused knock is not counted,
7 * so the door reopens exactly a window later. One limiter set per forge, so a
8 * test's forge never throttles another's.
9 */
10
11 import { RateLimiter } from "../core/ratelimit.ts";
12 import type { App } from "../app.ts";
13 import { bucketOf } from "./peer.ts";
14
15 export type Door = "signup" | "signin" | "account" | "edge";
16
17 /** Knocks a minute: [from one source, from everyone]. */
18 export const DOOR_LIMITS: Record<Door, readonly [number, number]> = {
19 signup: [20, 300],
20 signin: [60, 200],
21 /** Guesses at one account, keyed on its lowercased name. */
22 account: [20, 200],
23 edge: [20, 300],
24 };
25
26 const sets = new WeakMap<App, Map<Door, RateLimiter>>();
27
28 function limiterFor(app: App, door: Door): RateLimiter {
29 let doors = sets.get(app);
30 if (doors === undefined) sets.set(app, (doors = new Map()));
31 let limiter = doors.get(door);
32 if (limiter === undefined) {
33 const [perSource, perForge] = app.config.doorLimits?.[door] ?? DOOR_LIMITS[door];
34 limiter = new RateLimiter({
35 perMinute: perSource,
36 adminPerMinute: perForge,
37 enabled: true,
38 });
39 doors.set(door, limiter);
40 }
41 return limiter;
42 }
43
44 /**
45 * Count one knock at `door` from `address`. Undefined means come in; a number
46 * is the seconds to wait. The forge-wide window is checked first so a refused
47 * knock costs the source nothing.
48 */
49 export function knock(app: App, door: Door, address: string): number | undefined {
50 const limiter = limiterFor(app, door);
51 const whole = limiter.take("forge", "admin");
52 if (!whole.allowed) return whole.retryAfter;
53 const one = limiter.take(`source:${bucketOf(address)}`, "ro");
54 return one.allowed ? undefined : one.retryAfter;
55 }
56
57 /** The sentence a person is told when the door is shut. */
58 export const waitSentence = (seconds: number): string =>
59 `Too many attempts. Try again in ${seconds === 1 ? "a second" : `${seconds} seconds`}.`;
src/http/server.ts +5 −1
@@ -323,6 +323,7 @@ import { apiRoutes } from "./api.ts";
323323 import { feedRoutes } from "./feed.ts";
324324 import { mcpRoutes } from "./mcp.ts";
325325 import { oauthRoutes } from "./oauth.ts";
326 import { knock } from "./doors.ts";
326327 import { carryPeer, clientAddress, notePeer, type ProxyTrust } from "./peer.ts";
327328 import { parseCidrs } from "../kernel/cidr.ts";
328329 import {
@@ -379,7 +380,10 @@ async function resolveAuth(app: App, request: Request): Promise<Auth> {
379380 const login = edgeIdentity(request, app.config.edgeToken);
380381 if (login !== undefined) {
381382 const existed = getUserByName(app.db, login) !== undefined;
382 const user = await ensureEdgeUser(app.db, login, forgeHost(app.config));
383 // A first sight makes an account, so it is a knock like a signup is; a
384 // shut door is a request with no one behind it, not an error.
385 const shut = !existed && knock(app, "edge", clientAddress(request)) !== undefined;
386 const user = shut ? undefined : await ensureEdgeUser(app.db, login, forgeHost(app.config));
383387 if (user) {
384388 // An account the edge made is audited like one made at /signup.
385389 if (!existed) {
src/main.ts +12
@@ -69,6 +69,15 @@ const canonicalUrl = hosted ? hostedAt : (process.env.FORGE_URL ?? "").trim();
6969 // identity headers sign people in; without it they are ignored.
7070 const edgeToken = (process.env.FORGE_EDGE_TOKEN ?? "").trim();
7171
72 // FORGE_TURNSTILE_SITE_KEY and FORGE_TURNSTILE_SECRET turn on the human check
73 // at signup; one without the other is a typo, so it fails the boot.
74 const turnstileSite = (process.env.FORGE_TURNSTILE_SITE_KEY ?? "").trim();
75 const turnstileSecret = (process.env.FORGE_TURNSTILE_SECRET ?? "").trim();
76 if ((turnstileSite === "") !== (turnstileSecret === "")) {
77 console.error("FORGE_TURNSTILE_SITE_KEY and FORGE_TURNSTILE_SECRET go together");
78 process.exit(1);
79 }
80
7281 const dataDir =
7382 process.env.FORGE_DATA ??
7483 (hosted ? process.env.FORGE_APP_DATA : undefined) ??
@@ -103,6 +112,9 @@ const app = createApp({
103112 : { host: process.env.FORGE_HOST }),
104113 ...(canonicalUrl === "" ? {} : { url: new URL(canonicalUrl).origin }),
105114 ...(edgeToken === "" ? {} : { edgeToken }),
115 ...(turnstileSite === ""
116 ? {}
117 : { humanCheck: { siteKey: turnstileSite, secret: turnstileSecret } }),
106118 // Hosted, the host says how this forge's terminal is reached; printed
107119 // verbatim wherever the forge tells people how to connect.
108120 ...(hosted && (process.env.FORGE_APP_SSH ?? "").trim() !== ""
src/web/layout.ts +3 −1
@@ -87,6 +87,8 @@ export interface PageOptions {
8787 * origin" — so pages that do not ask for it keep the stricter policy.
8888 */
8989 scriptAsset?: string;
90 /** The human check's widget is on this page: let Turnstile's host in. */
91 humanCheck?: boolean;
9092 /** Extra palette rows for this page's context (a repo's own tabs). */
9193 palette?: PaletteItem[];
9294 /**
@@ -634,7 +636,7 @@ export function page(options: PageOptions, status = 200): Response {
634636 // The external stylesheet plus this page's own nonce'd <style>/<script>
635637 // are the only resources allowed; connect-src 'self' lets the live
636638 // event stream (EventSource) and fragment fetches reach same-origin.
637 "content-security-policy": `default-src 'none'; style-src 'self' 'nonce-${nonce}'; script-src 'nonce-${nonce}'${options.scriptAsset === undefined ? "" : " 'self'"}; connect-src 'self'; worker-src 'self'; manifest-src 'self'; img-src 'self' data:; form-action 'self'; base-uri 'none'; frame-ancestors 'none'`,
639 "content-security-policy": `default-src 'none'; style-src 'self' 'nonce-${nonce}'; script-src 'nonce-${nonce}'${options.scriptAsset === undefined ? "" : " 'self'"}${options.humanCheck ? " https://challenges.cloudflare.com" : ""}; connect-src 'self'; frame-src ${options.humanCheck ? "https://challenges.cloudflare.com" : "'none'"}; worker-src 'self'; manifest-src 'self'; img-src 'self' data:; form-action 'self'; base-uri 'none'; frame-ancestors 'none'`,
638640 "referrer-policy": "same-origin",
639641 "x-content-type-options": "nosniff",
640642 // Markup is revalidated every time; only the hashed assets it names are
src/web/pages/site.ts +50 −36
@@ -51,6 +51,8 @@ import {
5151 signInFirst,
5252 } from "../chrome.ts";
5353 import { RateLimiter } from "../../core/ratelimit.ts";
54 import { isHuman, TURNSTILE_SCRIPT } from "../../core/humancheck.ts";
55 import { knock, waitSentence } from "../../http/doors.ts";
5456 import { field, readForm } from "../form.ts";
5557 import { html, when, type Html } from "../html.ts";
5658 import { icon, type IconName } from "../icons.ts";
@@ -612,6 +614,7 @@ interface AuthErrors {
612614 username?: string;
613615 email?: string;
614616 password?: string;
617 human?: string;
615618 }
616619
617620 function authForm(
@@ -692,6 +695,13 @@ function authForm(
692695 : {}),
693696 ...(errors.password ? { error: errors.password } : {}),
694697 })}
698 ${when(
699 kind === "signup" ? ctx.app.config.humanCheck : undefined,
700 (check) =>
701 html`<div class="cf-turnstile mb" data-sitekey="${check.siteKey}"></div>
702 <script src="${TURNSTILE_SCRIPT}" async defer></script>
703 ${errors.human ? html`<span class="error">${errors.human}</span>` : null}`,
704 )}
695705 ${when(
696706 firstAccount,
697707 () =>
@@ -739,39 +749,27 @@ export function signinPage(ctx: Ctx): Response {
739749 }
740750
741751 export function signupPage(ctx: Ctx): Response {
742 return page({ ctx, title: "Sign up", body: authForm(ctx, "signup") });
752 return page({
753 ctx,
754 title: "Sign up",
755 body: authForm(ctx, "signup"),
756 humanCheck: ctx.app.config.humanCheck !== undefined,
757 });
743758 }
744759
760 const signinAllowed = (ctx: Ctx, username: string): number | undefined =>
761 knock(ctx.app, "signin", clientAddress(ctx.request)) ??
762 knock(ctx.app, "account", username.toLowerCase());
763
745764 /**
746765 * Sign-in attempts, throttled. The token limiter does not see a password
747766 * form — a stranger has no credential yet — so guessing a password runs at
748 * line speed and each guess costs a slow hash. Two sliding windows, checked
749 * before the hash: an account may be tried twenty times a minute, and the
750 * forge as a whole two hundred, so neither one account nor every account at
767 * line speed and each guess costs a slow hash. Sliding windows, checked
768 * before the hash (`http/doors.ts`): a source, an account (twenty a minute)
769 * and the forge as a whole, so neither one account nor every account at
751770 * once is worth the trying. A person signing in does not notice; a refused
752 * attempt is not counted, so the door reopens exactly a window later. One
753 * limiter per forge, so a test's forge never throttles another's.
771 * attempt is not counted, so the door reopens exactly a window later.
754772 */
755 const signinLimits = new WeakMap<Ctx["app"], RateLimiter>();
756 const SIGNIN_PER_ACCOUNT = 20;
757 const SIGNIN_PER_FORGE = 200;
758
759 function signinAllowed(ctx: Ctx, username: string): number | undefined {
760 let limiter = signinLimits.get(ctx.app);
761 if (limiter === undefined) {
762 limiter = new RateLimiter({
763 perMinute: SIGNIN_PER_ACCOUNT,
764 adminPerMinute: SIGNIN_PER_FORGE,
765 enabled: true,
766 });
767 signinLimits.set(ctx.app, limiter);
768 }
769 const whole = limiter.take("forge", "admin");
770 if (!whole.allowed) return whole.retryAfter;
771 const one = limiter.take(`account:${username.toLowerCase()}`, "ro");
772 return one.allowed ? undefined : one.retryAfter;
773 }
774
775773 export async function signinSubmit(ctx: Ctx): Promise<Response> {
776774 // Posted by people with no account yet: a stranger's form.
777775 const form = await readForm(ctx, undefined, STRANGER_MAX);
@@ -786,7 +784,7 @@ export async function signinSubmit(ctx: Ctx): Promise<Response> {
786784 body: authForm(ctx, "signin", {
787785 values: { username },
788786 errors: {
789 password: `Too many attempts. Try again in ${wait === 1 ? "a second" : `${wait} seconds`}.`,
787 password: `${waitSentence(wait)}`,
790788 },
791789 }),
792790 },
@@ -850,10 +848,33 @@ export async function signupSubmit(ctx: Ctx): Promise<Response> {
850848 if (form instanceof Response) return form;
851849 const username = field(form, "username");
852850 const email = field(form, "email");
851 const address = clientAddress(ctx.request);
852 const refuse = (errors: AuthErrors, status: number): Response =>
853 page(
854 {
855 ctx,
856 title: "Sign up",
857 body: authForm(ctx, "signup", { values: { username, email }, errors }),
858 humanCheck: ctx.app.config.humanCheck !== undefined,
859 },
860 status,
861 );
862 const wait = knock(ctx.app, "signup", address);
863 if (wait !== undefined) {
864 const response = refuse({ username: waitSentence(wait) }, 429);
865 response.headers.set("retry-after", String(wait));
866 return response;
867 }
868 const check = ctx.app.config.humanCheck;
869 if (
870 check !== undefined &&
871 !(await isHuman(check, field(form, "cf-turnstile-response"), address))
872 )
873 return refuse({ human: "Please complete the human check and try again." }, 422);
853874 const created = await signUp(
854875 ctx.app,
855876 { username, email, password: field(form, "password") },
856 { address: clientAddress(ctx.request) },
877 { address },
857878 );
858879 if (!created.ok) {
859880 const errors: AuthErrors = {
@@ -865,14 +886,7 @@ export async function signupSubmit(ctx: Ctx): Promise<Response> {
865886 email_taken: { email: "That email already has an account." },
866887 weak_password: { password: "Passwords need at least 10 characters." },
867888 }[created.error] ?? { username: "Something went wrong." };
868 return page(
869 {
870 ctx,
871 title: "Sign up",
872 body: authForm(ctx, "signup", { values: { username, email }, errors }),
873 },
874 422,
875 );
889 return refuse(errors, 422);
876890 }
877891 const session = createSession(ctx.app.db, created.value.id);
878892 return redirect(
test/signup-guard.test.ts added +123
@@ -0,0 +1,123 @@
1 /**
2 * Signup resists bots and floods: a human-check token is verified on the
3 * server before an account is made, and signup and sign-in are throttled per
4 * source and for the forge, keyed on the socket and never on a header.
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 { getUserByName } from "../src/core/users.ts";
12 import { serve, type Servers } from "../src/http/server.ts";
13
14 describe("signup and sign-in guards", () => {
15 let dataDir: string;
16 let app: App;
17 let servers: Servers;
18 const seen: string[] = [];
19
20 const signup = (name: string, extra: Record<string, string> = {}, headers = {}) =>
21 fetch(`${servers.url}/signup`, {
22 method: "POST",
23 headers: { origin: servers.url, ...headers },
24 body: new URLSearchParams({
25 username: name,
26 email: `${name}@forge.local`,
27 password: "a-good-passphrase",
28 ...extra,
29 }),
30 redirect: "manual",
31 });
32
33 beforeAll(async () => {
34 dataDir = await mkdtemp(join(tmpdir(), "forge-guard-"));
35 app = createApp({
36 dataDir,
37 port: 0,
38 doorLimits: { signin: [3, 200] }, // each wrong guess costs a real hash
39 trustedProxies: ["192.0.2.0/24"], // loopback is no proxy: a header is only a claim
40 humanCheck: {
41 siteKey: "site-key",
42 secret: "secret",
43 verify: async (token) => {
44 seen.push(token);
45 return token === "good";
46 },
47 },
48 });
49 servers = await serve(app);
50 });
51
52 afterAll(async () => {
53 servers.stop();
54 app.close();
55 await rm(dataDir, { recursive: true, force: true });
56 });
57
58 test("the signup page shows the widget and lets Turnstile's host in", async () => {
59 const r = await fetch(`${servers.url}/signup`);
60 const text = await r.text();
61 expect(text).toContain('data-sitekey="site-key"');
62 expect(text).not.toContain("secret");
63 expect(r.headers.get("content-security-policy")).toContain("https://challenges.cloudflare.com");
64 });
65
66 test("no token, or a bad one, makes no account", async () => {
67 const none = await signup("nobody");
68 expect(none.status).toBe(422);
69 expect(await none.text()).toContain("human check");
70 expect((await signup("nobody", { "cf-turnstile-response": "forged" })).status).toBe(422);
71 expect(getUserByName(app.db, "nobody")).toBeUndefined();
72 });
73
74 test("a good token makes the account and signs it in", async () => {
75 const r = await signup("human", { "cf-turnstile-response": "good" });
76 expect(r.status).toBe(303);
77 expect(r.headers.get("set-cookie")).toContain("HttpOnly");
78 expect(getUserByName(app.db, "human")).toBeDefined();
79 });
80
81 test("the API wants the token too", async () => {
82 const post = (humanToken?: string) =>
83 fetch(`${servers.url}/api/v1/users`, {
84 method: "POST",
85 headers: { "content-type": "application/json" },
86 body: JSON.stringify({
87 username: "apiuser",
88 email: "[email protected]",
89 password: "a-good-passphrase",
90 ...(humanToken === undefined ? {} : { humanToken }),
91 }),
92 });
93 expect((await post()).status).toBe(422);
94 expect((await post("good")).status).toBe(201);
95 });
96
97 test("rapid signups from one source are throttled, whatever a header says", async () => {
98 let shut: Response | undefined;
99 for (let i = 0; i < 40 && shut === undefined; i++) {
100 // A different claimed client each time must not buy another window.
101 const r = await signup(`flood${i}`, { "cf-turnstile-response": "bad" }, {
102 "x-forwarded-for": `203.0.113.${i + 1}`,
103 });
104 if (r.status === 429) shut = r;
105 }
106 expect(shut).toBeDefined();
107 expect(Number(shut!.headers.get("retry-after"))).toBeGreaterThan(0);
108 expect(await shut!.text()).toContain("Too many attempts");
109 });
110
111 test("rapid sign-ins from one source are throttled", async () => {
112 const attempt = (i: number) =>
113 fetch(`${servers.url}/signin`, {
114 method: "POST",
115 headers: { origin: servers.url },
116 body: new URLSearchParams({ username: `user${i}`, password: "nope" }),
117 redirect: "manual",
118 });
119 let status = 0;
120 for (let i = 0; i < 10 && status !== 429; i++) status = (await attempt(i)).status;
121 expect(status).toBe(429);
122 }, 30_000);
123 });

↑↓ navigate ↵ open ⌘↵ its app esc close

Keyboard shortcuts

Docs