Public: anyone can read this; the crew can change it.
Signup resists bots and floods: a human check and rate limits #938
scout/forge:scout/661-signup-resists-bots-and-floods-a-human-c → main 2 commits fork
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), | ||
| 95 | 95 | `FORGE_ORIGIN_ALLOW` (hosts an operator vouches for on a LAN). Behind a |
| 96 | 96 | platform edge that signs people in for every app it serves, `FORGE_EDGE_TOKEN` |
| 97 | 97 | 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 | |
| 99 | 106 | (the link that proves a newcomer's email) is SMTP submission over TLS, |
| 100 | 107 | configured by the forge-level secrets `MAIL_SMTP_URL` |
| 101 | 108 | (`smtps://user:pass@host:465`) and `MAIL_FROM`, set live under Settings → |
scripts/gate.ts +1
| @@ -57,6 +57,7 @@ export const GATE: readonly string[] = [ | ||
| 57 | 57 | "test/sealed-issues.test.ts", |
| 58 | 58 | "test/sealed-preview.test.ts", |
| 59 | 59 | "test/session-settle.test.ts", |
| 60 | "test/signup-guard.test.ts", | |
| 60 | 61 | "test/landing.test.ts", |
| 61 | 62 | "test/decide.test.ts", |
| 62 | 63 | "test/ledger.test.ts", |
src/app.ts +8
| @@ -4,6 +4,7 @@ | ||
| 4 | 4 | * side-effect-contained, so tests boot real forges by the dozen. |
| 5 | 5 | */ |
| 6 | 6 | |
| 7 | import type { HumanCheck } from "./core/humancheck.ts"; | |
| 7 | 8 | import type { MailConfig, Mailer } from "./kernel/mail.ts"; |
| 8 | 9 | import type { Database } from "bun:sqlite"; |
| 9 | 10 | import type { Decider } from "./crew/decide.ts"; |
| @@ -41,6 +42,13 @@ export interface ForgeConfig { | ||
| 41 | 42 | * in by the platform. Unset, those headers are a claim and are ignored. |
| 42 | 43 | */ |
| 43 | 44 | 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]>>; | |
| 44 | 52 | /** |
| 45 | 53 | * Let anyone, not only an admin, migrate from a host inside the network |
| 46 | 54 | * (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
| @@ -333,6 +333,8 @@ import { frontInput, frontJson, setFront } from "../actions/front.ts"; | ||
| 333 | 333 | import { COPIES_PER_DAY, makeItYours } from "../actions/make_it_yours.ts"; |
| 334 | 334 | import type { Router } from "./router.ts"; |
| 335 | 335 | import { clientAddress, clientBucket } from "./peer.ts"; |
| 336 | import { isHuman } from "../core/humancheck.ts"; | |
| 337 | import { knock, waitSentence } from "./doors.ts"; | |
| 336 | 338 | import { manifestFor } from "../actions/here.ts"; |
| 337 | 339 | import { |
| 338 | 340 | acceptReport, |
| @@ -1016,6 +1018,19 @@ export function apiRoutes(router: Router<Handler>): void { | ||
| 1016 | 1018 | const input = await boundedBody(ctx.request, STRANGER_MAX); |
| 1017 | 1019 | if (input === "too_large") |
| 1018 | 1020 | return apiError("too_large", 413, `at most ${STRANGER_MAX} bytes`); |
| 1021 | const address = clientAddress(ctx.request); | |
| 1022 | const wait = knock(ctx.app, "signup", address); | |
| 1023 | if (wait !== undefined) { | |
| 1024 | const refused = apiError("rate_limited", 429, waitSentence(wait)); | |
| 1025 | refused.headers.set("retry-after", String(wait)); | |
| 1026 | return refused; | |
| 1027 | } | |
| 1028 | const check = ctx.app.config.humanCheck; | |
| 1029 | if ( | |
| 1030 | check !== undefined && | |
| 1031 | !(await isHuman(check, str(input.humanToken), address)) | |
| 1032 | ) | |
| 1033 | return apiError("human_check", 422, "a valid humanToken (Turnstile) is required"); | |
| 1019 | 1034 | const created = await signUp( |
| 1020 | 1035 | ctx.app, |
| 1021 | 1036 | { |
| @@ -1023,7 +1038,7 @@ export function apiRoutes(router: Router<Handler>): void { | ||
| 1023 | 1038 | email: str(input.email), |
| 1024 | 1039 | password: str(input.password), |
| 1025 | 1040 | }, |
| 1026 | { address: clientAddress(ctx.request) }, | |
| 1041 | { address }, | |
| 1027 | 1042 | ); |
| 1028 | 1043 | if (!created.ok) return json({ error: created.error }, 422); |
| 1029 | 1044 | 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
| @@ -352,6 +352,7 @@ import { apiRoutes } from "./api.ts"; | ||
| 352 | 352 | import { feedRoutes } from "./feed.ts"; |
| 353 | 353 | import { mcpRoutes } from "./mcp.ts"; |
| 354 | 354 | import { oauthRoutes } from "./oauth.ts"; |
| 355 | import { knock } from "./doors.ts"; | |
| 355 | 356 | import { carryPeer, clientAddress, notePeer, type ProxyTrust } from "./peer.ts"; |
| 356 | 357 | import { parseCidrs } from "../kernel/cidr.ts"; |
| 357 | 358 | import { |
| @@ -408,7 +409,10 @@ async function resolveAuth(app: App, request: Request): Promise<Auth> { | ||
| 408 | 409 | const login = edgeIdentity(request, app.config.edgeToken); |
| 409 | 410 | if (login !== undefined) { |
| 410 | 411 | const existed = getUserByName(app.db, login) !== undefined; |
| 411 | const user = await ensureEdgeUser(app.db, login, forgeHost(app.config)); | |
| 412 | // A first sight makes an account, so it is a knock like a signup is; a | |
| 413 | // shut door is a request with no one behind it, not an error. | |
| 414 | const shut = !existed && knock(app, "edge", clientAddress(request)) !== undefined; | |
| 415 | const user = shut ? undefined : await ensureEdgeUser(app.db, login, forgeHost(app.config)); | |
| 412 | 416 | if (user) { |
| 413 | 417 | // An account the edge made is audited like one made at /signup. |
| 414 | 418 | if (!existed) { |
src/main.ts +12
| @@ -71,6 +71,15 @@ const canonicalUrl = hosted ? hostedAt : (process.env.FORGE_URL ?? "").trim(); | ||
| 71 | 71 | // identity headers sign people in; without it they are ignored. |
| 72 | 72 | const edgeToken = (process.env.FORGE_EDGE_TOKEN ?? "").trim(); |
| 73 | 73 | |
| 74 | // FORGE_TURNSTILE_SITE_KEY and FORGE_TURNSTILE_SECRET turn on the human check | |
| 75 | // at signup; one without the other is a typo, so it fails the boot. | |
| 76 | const turnstileSite = (process.env.FORGE_TURNSTILE_SITE_KEY ?? "").trim(); | |
| 77 | const turnstileSecret = (process.env.FORGE_TURNSTILE_SECRET ?? "").trim(); | |
| 78 | if ((turnstileSite === "") !== (turnstileSecret === "")) { | |
| 79 | console.error("FORGE_TURNSTILE_SITE_KEY and FORGE_TURNSTILE_SECRET go together"); | |
| 80 | process.exit(1); | |
| 81 | } | |
| 82 | ||
| 74 | 83 | const dataDir = |
| 75 | 84 | process.env.FORGE_DATA ?? |
| 76 | 85 | (hosted ? process.env.FORGE_APP_DATA : undefined) ?? |
| @@ -105,6 +114,9 @@ const app = createApp({ | ||
| 105 | 114 | : { host: process.env.FORGE_HOST }), |
| 106 | 115 | ...(canonicalUrl === "" ? {} : { url: new URL(canonicalUrl).origin }), |
| 107 | 116 | ...(edgeToken === "" ? {} : { edgeToken }), |
| 117 | ...(turnstileSite === "" | |
| 118 | ? {} | |
| 119 | : { humanCheck: { siteKey: turnstileSite, secret: turnstileSecret } }), | |
| 108 | 120 | // Hosted, the host says how this forge's terminal is reached; printed |
| 109 | 121 | // verbatim wherever the forge tells people how to connect. |
| 110 | 122 | ...(hosted && (process.env.FORGE_APP_SSH ?? "").trim() !== "" |
src/web/layout.ts +3 −1
| @@ -89,6 +89,8 @@ export interface PageOptions { | ||
| 89 | 89 | * origin" — so pages that do not ask for it keep the stricter policy. |
| 90 | 90 | */ |
| 91 | 91 | scriptAsset?: string; |
| 92 | /** The human check's widget is on this page: let Turnstile's host in. */ | |
| 93 | humanCheck?: boolean; | |
| 92 | 94 | /** Extra palette rows for this page's context (a repo's own tabs). */ |
| 93 | 95 | palette?: PaletteItem[]; |
| 94 | 96 | /** |
| @@ -658,7 +660,7 @@ export function page(options: PageOptions, status = 200): Response { | ||
| 658 | 660 | // The external stylesheet plus this page's own nonce'd <style>/<script> |
| 659 | 661 | // are the only resources allowed; connect-src 'self' lets the live |
| 660 | 662 | // event stream (EventSource) and fragment fetches reach same-origin. |
| 661 | "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'`, | |
| 663 | "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'`, | |
| 662 | 664 | "referrer-policy": "same-origin", |
| 663 | 665 | "x-content-type-options": "nosniff", |
| 664 | 666 | // Markup is revalidated every time; only the hashed assets it names are |
src/web/pages/site.ts +50 −36
| @@ -33,6 +33,8 @@ import { edgeLoginUrl } from "../../http/edge.ts"; | ||
| 33 | 33 | import { sshCommand } from "../../ssh/command.ts"; |
| 34 | 34 | import { hostOf, pageHead, signInFirst } from "../chrome.ts"; |
| 35 | 35 | import { RateLimiter } from "../../core/ratelimit.ts"; |
| 36 | import { isHuman, TURNSTILE_SCRIPT } from "../../core/humancheck.ts"; | |
| 37 | import { knock, waitSentence } from "../../http/doors.ts"; | |
| 36 | 38 | import { field, readForm } from "../form.ts"; |
| 37 | 39 | import { html, when, type Html } from "../html.ts"; |
| 38 | 40 | import { icon } from "../icons.ts"; |
| @@ -261,6 +263,7 @@ interface AuthErrors { | ||
| 261 | 263 | username?: string; |
| 262 | 264 | email?: string; |
| 263 | 265 | password?: string; |
| 266 | human?: string; | |
| 264 | 267 | } |
| 265 | 268 | |
| 266 | 269 | function authForm( |
| @@ -341,6 +344,13 @@ function authForm( | ||
| 341 | 344 | : {}), |
| 342 | 345 | ...(errors.password ? { error: errors.password } : {}), |
| 343 | 346 | })} |
| 347 | ${when( | |
| 348 | kind === "signup" ? ctx.app.config.humanCheck : undefined, | |
| 349 | (check) => | |
| 350 | html`<div class="cf-turnstile mb" data-sitekey="${check.siteKey}"></div> | |
| 351 | <script src="${TURNSTILE_SCRIPT}" async defer></script> | |
| 352 | ${errors.human ? html`<span class="error">${errors.human}</span>` : null}`, | |
| 353 | )} | |
| 344 | 354 | ${when( |
| 345 | 355 | firstAccount, |
| 346 | 356 | () => |
| @@ -388,39 +398,27 @@ export function signinPage(ctx: Ctx): Response { | ||
| 388 | 398 | } |
| 389 | 399 | |
| 390 | 400 | export function signupPage(ctx: Ctx): Response { |
| 391 | return page({ ctx, title: "Sign up", body: authForm(ctx, "signup") }); | |
| 401 | return page({ | |
| 402 | ctx, | |
| 403 | title: "Sign up", | |
| 404 | body: authForm(ctx, "signup"), | |
| 405 | humanCheck: ctx.app.config.humanCheck !== undefined, | |
| 406 | }); | |
| 392 | 407 | } |
| 393 | 408 | |
| 409 | const signinAllowed = (ctx: Ctx, username: string): number | undefined => | |
| 410 | knock(ctx.app, "signin", clientAddress(ctx.request)) ?? | |
| 411 | knock(ctx.app, "account", username.toLowerCase()); | |
| 412 | ||
| 394 | 413 | /** |
| 395 | 414 | * Sign-in attempts, throttled. The token limiter does not see a password |
| 396 | 415 | * form — a stranger has no credential yet — so guessing a password runs at |
| 397 | * line speed and each guess costs a slow hash. Two sliding windows, checked | |
| 398 | * before the hash: an account may be tried twenty times a minute, and the | |
| 399 | * forge as a whole two hundred, so neither one account nor every account at | |
| 416 | * line speed and each guess costs a slow hash. Sliding windows, checked | |
| 417 | * before the hash (`http/doors.ts`): a source, an account (twenty a minute) | |
| 418 | * and the forge as a whole, so neither one account nor every account at | |
| 400 | 419 | * once is worth the trying. A person signing in does not notice; a refused |
| 401 | * attempt is not counted, so the door reopens exactly a window later. One | |
| 402 | * limiter per forge, so a test's forge never throttles another's. | |
| 420 | * attempt is not counted, so the door reopens exactly a window later. | |
| 403 | 421 | */ |
| 404 | const signinLimits = new WeakMap<Ctx["app"], RateLimiter>(); | |
| 405 | const SIGNIN_PER_ACCOUNT = 20; | |
| 406 | const SIGNIN_PER_FORGE = 200; | |
| 407 | ||
| 408 | function signinAllowed(ctx: Ctx, username: string): number | undefined { | |
| 409 | let limiter = signinLimits.get(ctx.app); | |
| 410 | if (limiter === undefined) { | |
| 411 | limiter = new RateLimiter({ | |
| 412 | perMinute: SIGNIN_PER_ACCOUNT, | |
| 413 | adminPerMinute: SIGNIN_PER_FORGE, | |
| 414 | enabled: true, | |
| 415 | }); | |
| 416 | signinLimits.set(ctx.app, limiter); | |
| 417 | } | |
| 418 | const whole = limiter.take("forge", "admin"); | |
| 419 | if (!whole.allowed) return whole.retryAfter; | |
| 420 | const one = limiter.take(`account:${username.toLowerCase()}`, "ro"); | |
| 421 | return one.allowed ? undefined : one.retryAfter; | |
| 422 | } | |
| 423 | ||
| 424 | 422 | export async function signinSubmit(ctx: Ctx): Promise<Response> { |
| 425 | 423 | // Posted by people with no account yet: a stranger's form. |
| 426 | 424 | const form = await readForm(ctx, undefined, STRANGER_MAX); |
| @@ -435,7 +433,7 @@ export async function signinSubmit(ctx: Ctx): Promise<Response> { | ||
| 435 | 433 | body: authForm(ctx, "signin", { |
| 436 | 434 | values: { username }, |
| 437 | 435 | errors: { |
| 438 | password: `Too many attempts. Try again in ${wait === 1 ? "a second" : `${wait} seconds`}.`, | |
| 436 | password: `${waitSentence(wait)}`, | |
| 439 | 437 | }, |
| 440 | 438 | }), |
| 441 | 439 | }, |
| @@ -499,10 +497,33 @@ export async function signupSubmit(ctx: Ctx): Promise<Response> { | ||
| 499 | 497 | if (form instanceof Response) return form; |
| 500 | 498 | const username = field(form, "username"); |
| 501 | 499 | const email = field(form, "email"); |
| 500 | const address = clientAddress(ctx.request); | |
| 501 | const refuse = (errors: AuthErrors, status: number): Response => | |
| 502 | page( | |
| 503 | { | |
| 504 | ctx, | |
| 505 | title: "Sign up", | |
| 506 | body: authForm(ctx, "signup", { values: { username, email }, errors }), | |
| 507 | humanCheck: ctx.app.config.humanCheck !== undefined, | |
| 508 | }, | |
| 509 | status, | |
| 510 | ); | |
| 511 | const wait = knock(ctx.app, "signup", address); | |
| 512 | if (wait !== undefined) { | |
| 513 | const response = refuse({ username: waitSentence(wait) }, 429); | |
| 514 | response.headers.set("retry-after", String(wait)); | |
| 515 | return response; | |
| 516 | } | |
| 517 | const check = ctx.app.config.humanCheck; | |
| 518 | if ( | |
| 519 | check !== undefined && | |
| 520 | !(await isHuman(check, field(form, "cf-turnstile-response"), address)) | |
| 521 | ) | |
| 522 | return refuse({ human: "Please complete the human check and try again." }, 422); | |
| 502 | 523 | const created = await signUp( |
| 503 | 524 | ctx.app, |
| 504 | 525 | { username, email, password: field(form, "password") }, |
| 505 | { address: clientAddress(ctx.request) }, | |
| 526 | { address }, | |
| 506 | 527 | ); |
| 507 | 528 | if (!created.ok) { |
| 508 | 529 | const errors: AuthErrors = { |
| @@ -514,14 +535,7 @@ export async function signupSubmit(ctx: Ctx): Promise<Response> { | ||
| 514 | 535 | email_taken: { email: "That email already has an account." }, |
| 515 | 536 | weak_password: { password: "Passwords need at least 10 characters." }, |
| 516 | 537 | }[created.error] ?? { username: "Something went wrong." }; |
| 517 | return page( | |
| 518 | { | |
| 519 | ctx, | |
| 520 | title: "Sign up", | |
| 521 | body: authForm(ctx, "signup", { values: { username, email }, errors }), | |
| 522 | }, | |
| 523 | 422, | |
| 524 | ); | |
| 538 | return refuse(errors, 422); | |
| 525 | 539 | } |
| 526 | 540 | const session = createSession(ctx.app.db, created.value.id); |
| 527 | 541 | 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 | }); |
new above
offline