Public: anyone can read this; the crew can change it.
Signup verifies a Turnstile token on the server before it makes an account, through a verifier injected on createApp #1673
scout/forge:scout/1665-signup-verifies-a-turnstile-token-on-the → main 1 commit fork
8 files
changed +139
−3
scripts/gate.ts +1
| @@ -159,6 +159,7 @@ export const GATE: readonly string[] = [ | ||
| 159 | 159 | "test/branch_tell.test.ts", |
| 160 | 160 | "test/usage.test.ts", |
| 161 | 161 | "test/tokens.test.ts", |
| 162 | "test/turnstile.test.ts", | |
| 162 | 163 | "test/credentials.test.ts", |
| 163 | 164 | "test/standing.test.ts", |
| 164 | 165 | "test/board.test.ts", |
src/actions/users.ts +13 −2
| @@ -36,9 +36,11 @@ export interface SignUpInput { | ||
| 36 | 36 | username: string; |
| 37 | 37 | email: string; |
| 38 | 38 | password: string; |
| 39 | /** The Turnstile token the form carried; asked for only when the forge has a verifier. */ | |
| 40 | humanToken?: string; | |
| 39 | 41 | } |
| 40 | 42 | |
| 41 | export type SignUpError = CreateUserError; | |
| 43 | export type SignUpError = CreateUserError | "human_check_failed"; | |
| 42 | 44 | |
| 43 | 45 | /** |
| 44 | 46 | * The first account on a fresh forge is the admin — no setup wizard. A name |
| @@ -51,7 +53,16 @@ export async function signUp( | ||
| 51 | 53 | /** Where the request came from, for the owner's audit of who joined. */ |
| 52 | 54 | from: { address?: string | undefined } = {}, |
| 53 | 55 | ): Promise<Result<User, SignUpError>> { |
| 54 | const created = await createUser(app.db, { ...input, adminIfFirst: true }); | |
| 56 | // Before a password is hashed or a row made. | |
| 57 | if (app.config.verifyHuman !== undefined) { | |
| 58 | const human = await app.config.verifyHuman( | |
| 59 | input.humanToken ?? "", | |
| 60 | from.address, | |
| 61 | ); | |
| 62 | if (!human) return err("human_check_failed"); | |
| 63 | } | |
| 64 | const { humanToken: _token, ...account } = input; | |
| 65 | const created = await createUser(app.db, { ...account, adminIfFirst: true }); | |
| 55 | 66 | if (!created.ok) return created; |
| 56 | 67 | app.bus.append({ |
| 57 | 68 | kind: "user.created", |
src/app.ts +7
| @@ -7,6 +7,7 @@ | ||
| 7 | 7 | import type { MailConfig, Mailer } from "./kernel/mail.ts"; |
| 8 | 8 | import type { Database } from "bun:sqlite"; |
| 9 | 9 | import type { Decider } from "./crew/decide.ts"; |
| 10 | import type { VerifyHuman } from "./turnstile.ts"; | |
| 10 | 11 | import { randomBytes } from "node:crypto"; |
| 11 | 12 | import { mkdirSync } from "node:fs"; |
| 12 | 13 | import { join, resolve } from "node:path"; |
| @@ -95,6 +96,12 @@ export interface ForgeConfig { | ||
| 95 | 96 | * (`actions/mail.ts`). Undefined is `FORGE_DAILY`. |
| 96 | 97 | */ |
| 97 | 98 | mailDailyCap?: number; |
| 99 | /** | |
| 100 | * Whether a signup's Turnstile token is good (`turnstile.ts`). Set, a | |
| 101 | * signup without a good token is refused; unset, signup asks nothing. | |
| 102 | * `FORGE_TURNSTILE_SECRET` builds it in `main.ts`; tests inject a fake. | |
| 103 | */ | |
| 104 | verifyHuman?: VerifyHuman; | |
| 98 | 105 | /** Stand-in for `mail` in tests: receives each message instead of SMTP. */ |
| 99 | 106 | mailer?: Mailer; |
| 100 | 107 | /** |
src/http/api.ts +1
| @@ -1113,6 +1113,7 @@ export function apiRoutes(router: Router<Handler>): void { | ||
| 1113 | 1113 | username: str(input.username), |
| 1114 | 1114 | email: str(input.email), |
| 1115 | 1115 | password: str(input.password), |
| 1116 | humanToken: str(input["cf-turnstile-response"]), | |
| 1116 | 1117 | }, |
| 1117 | 1118 | { address: clientAddress(ctx.request) }, |
| 1118 | 1119 | ); |
src/main.ts +6
| @@ -6,6 +6,7 @@ | ||
| 6 | 6 | |
| 7 | 7 | import { parseCidrs } from "./kernel/cidr.ts"; |
| 8 | 8 | import { createApp } from "./app.ts"; |
| 9 | import { turnstile } from "./turnstile.ts"; | |
| 9 | 10 | import { reconcile } from "./core/reconcile.ts"; |
| 10 | 11 | import { syncAllPillars } from "./actions/pillars.ts"; |
| 11 | 12 | import { firstBoot } from "./spawn/first-boot.ts"; |
| @@ -132,6 +133,11 @@ const app = createApp({ | ||
| 132 | 133 | Number(process.env.FORGE_MAIL_DAILY) > 0 |
| 133 | 134 | ? { mailDailyCap: Number(process.env.FORGE_MAIL_DAILY) } |
| 134 | 135 | : {}), |
| 136 | // FORGE_TURNSTILE_SECRET: signup asks for a Turnstile token and checks it | |
| 137 | // with Cloudflare (`turnstile.ts`). Unset, signup asks nothing. | |
| 138 | ...((process.env.FORGE_TURNSTILE_SECRET ?? "").trim() !== "" | |
| 139 | ? { verifyHuman: turnstile(process.env.FORGE_TURNSTILE_SECRET!.trim()) } | |
| 140 | : {}), | |
| 135 | 141 | // Who may say who the client is: the ingress in front of a hosted forge. |
| 136 | 142 | ...(trustedProxies.length > 0 ? { trustedProxies } : {}), |
| 137 | 143 | ...((process.env.FORGE_CLIENT_IP_HEADER ?? "").trim() !== "" |
src/turnstile.ts added +35
| @@ -0,0 +1,35 @@ | ||
| 1 | /** | |
| 2 | * Cloudflare Turnstile: is the one signing up a person? `turnstile(secret)` | |
| 3 | * is the verifier `createApp` takes as `verifyHuman`; tests hand in a fake. | |
| 4 | */ | |
| 5 | ||
| 6 | const SITEVERIFY = "https://challenges.cloudflare.com/turnstile/v0/siteverify"; | |
| 7 | ||
| 8 | /** Answers yes only when the token is a good one. Never throws. */ | |
| 9 | export type VerifyHuman = ( | |
| 10 | token: string, | |
| 11 | address?: string, | |
| 12 | ) => Promise<boolean>; | |
| 13 | ||
| 14 | export function turnstile( | |
| 15 | secret: string, | |
| 16 | fetcher: typeof fetch = fetch, | |
| 17 | ): VerifyHuman { | |
| 18 | return async (token, address) => { | |
| 19 | if (token === "" || token.length > 2048) return false; | |
| 20 | const body = new URLSearchParams({ secret, response: token }); | |
| 21 | if (address) body.set("remoteip", address); | |
| 22 | try { | |
| 23 | const res = await fetcher(SITEVERIFY, { | |
| 24 | method: "POST", | |
| 25 | body, | |
| 26 | signal: AbortSignal.timeout(5000), | |
| 27 | }); | |
| 28 | if (!res.ok) return false; | |
| 29 | const answer = (await res.json()) as { success?: unknown }; | |
| 30 | return answer.success === true; | |
| 31 | } catch { | |
| 32 | return false; | |
| 33 | } | |
| 34 | }; | |
| 35 | } |
src/web/pages/site.ts +9 −1
| @@ -563,7 +563,12 @@ export async function signupSubmit(ctx: Ctx): Promise<Response> { | ||
| 563 | 563 | const email = field(form, "email"); |
| 564 | 564 | const created = await signUp( |
| 565 | 565 | ctx.app, |
| 566 | { username, email, password: field(form, "password") }, | |
| 566 | { | |
| 567 | username, | |
| 568 | email, | |
| 569 | password: field(form, "password"), | |
| 570 | humanToken: field(form, "cf-turnstile-response"), | |
| 571 | }, | |
| 567 | 572 | { address: clientAddress(ctx.request) }, |
| 568 | 573 | ); |
| 569 | 574 | if (!created.ok) { |
| @@ -575,6 +580,9 @@ export async function signupSubmit(ctx: Ctx): Promise<Response> { | ||
| 575 | 580 | username_reserved: { username: "That name is reserved." }, |
| 576 | 581 | email_taken: { email: "That email already has an account." }, |
| 577 | 582 | weak_password: { password: "Passwords need at least 10 characters." }, |
| 583 | human_check_failed: { | |
| 584 | username: "We could not tell you are a person. Try again.", | |
| 585 | }, | |
| 578 | 586 | }[created.error] ?? { username: "Something went wrong." }; |
| 579 | 587 | return page( |
| 580 | 588 | { |
test/turnstile.test.ts added +67
| @@ -0,0 +1,67 @@ | ||
| 1 | import { afterEach, describe, expect, test } from "bun:test"; | |
| 2 | import { mkdtempSync, rmSync } from "node:fs"; | |
| 3 | import { tmpdir } from "node:os"; | |
| 4 | import { join } from "node:path"; | |
| 5 | import { signUp } from "../src/actions/users.ts"; | |
| 6 | import { createApp, type App } from "../src/app.ts"; | |
| 7 | import { turnstile } from "../src/turnstile.ts"; | |
| 8 | ||
| 9 | const dirs: string[] = []; | |
| 10 | const apps: App[] = []; | |
| 11 | afterEach(() => { | |
| 12 | for (const a of apps.splice(0)) a.close(); | |
| 13 | for (const d of dirs.splice(0)) rmSync(d, { recursive: true, force: true }); | |
| 14 | }); | |
| 15 | ||
| 16 | function boot(verifyHuman?: (t: string) => Promise<boolean>): App { | |
| 17 | const dir = mkdtempSync(join(process.env.TMPDIR ?? tmpdir(), "turnstile-")); | |
| 18 | dirs.push(dir); | |
| 19 | const app = createApp({ dataDir: dir, ...(verifyHuman ? { verifyHuman } : {}) }); | |
| 20 | apps.push(app); | |
| 21 | return app; | |
| 22 | } | |
| 23 | ||
| 24 | const who = { username: "ada", email: "[email protected]", password: "long-enough-pass" }; | |
| 25 | const users = (app: App): number => | |
| 26 | (app.db.query("SELECT COUNT(*) AS n FROM user").get() as { n: number }).n; | |
| 27 | ||
| 28 | describe("signup and Turnstile", () => { | |
| 29 | test("off: signup works with no token", async () => { | |
| 30 | const app = boot(); | |
| 31 | expect((await signUp(app, who)).ok).toBe(true); | |
| 32 | expect(users(app)).toBe(1); | |
| 33 | }); | |
| 34 | ||
| 35 | test("on with a good token: the account is made", async () => { | |
| 36 | const app = boot(async (t) => t === "good"); | |
| 37 | const made = await signUp(app, { ...who, humanToken: "good" }); | |
| 38 | expect(made.ok).toBe(true); | |
| 39 | expect(users(app)).toBe(1); | |
| 40 | }); | |
| 41 | ||
| 42 | test("on with no or a bad token: refused, no account row", async () => { | |
| 43 | const app = boot(async (t) => t === "good"); | |
| 44 | for (const humanToken of [undefined, "", "bad"]) { | |
| 45 | const r = await signUp(app, { ...who, ...(humanToken === undefined ? {} : { humanToken }) }); | |
| 46 | expect(r).toEqual({ ok: false, error: "human_check_failed" }); | |
| 47 | } | |
| 48 | expect(users(app)).toBe(0); | |
| 49 | }); | |
| 50 | ||
| 51 | test("the verifier posts secret and token, and says yes only to success", async () => { | |
| 52 | const seen: string[] = []; | |
| 53 | const answer = (success: unknown, status = 200): typeof fetch => | |
| 54 | (async (_url: unknown, init?: RequestInit) => { | |
| 55 | seen.push(String(init?.body)); | |
| 56 | return new Response(JSON.stringify({ success }), { status }); | |
| 57 | }) as unknown as typeof fetch; | |
| 58 | expect(await turnstile("sek", answer(true))("tok", "1.2.3.4")).toBe(true); | |
| 59 | expect(seen[0]).toContain("secret=sek"); | |
| 60 | expect(seen[0]).toContain("response=tok"); | |
| 61 | expect(await turnstile("sek", answer(false))("tok")).toBe(false); | |
| 62 | expect(await turnstile("sek", answer(true, 500))("tok")).toBe(false); | |
| 63 | expect(await turnstile("sek", answer(true))("")).toBe(false); | |
| 64 | const down = (async () => { throw new Error("down"); }) as unknown as typeof fetch; | |
| 65 | expect(await turnstile("sek", down)("tok")).toBe(false); | |
| 66 | }); | |
| 67 | }); |
new above
offline