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 #1669

Closed opened this
Closed without merging

scout/forge:scout/1665-signup-verifies-a-turnstile-token-on-the → main 1 commit fork

  • Closed without merging. Nothing was applied to main.

Review

Sign in to review this change.
8 files changed +139 −3
scripts/gate.ts +1
@@ -159,6 +159,7 @@ export const GATE: readonly string[] = [
159159 "test/branch_tell.test.ts",
160160 "test/usage.test.ts",
161161 "test/tokens.test.ts",
162 "test/turnstile.test.ts",
162163 "test/credentials.test.ts",
163164 "test/standing.test.ts",
164165 "test/board.test.ts",
src/actions/users.ts +13 −2
@@ -36,9 +36,11 @@ export interface SignUpInput {
3636 username: string;
3737 email: string;
3838 password: string;
39 /** The Turnstile token the form carried; asked for only when the forge has a verifier. */
40 humanToken?: string;
3941 }
4042
41 export type SignUpError = CreateUserError;
43 export type SignUpError = CreateUserError | "human_check_failed";
4244
4345 /**
4446 * The first account on a fresh forge is the admin — no setup wizard. A name
@@ -51,7 +53,16 @@ export async function signUp(
5153 /** Where the request came from, for the owner's audit of who joined. */
5254 from: { address?: string | undefined } = {},
5355 ): 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 });
5566 if (!created.ok) return created;
5667 app.bus.append({
5768 kind: "user.created",
src/app.ts +7
@@ -7,6 +7,7 @@
77 import type { MailConfig, Mailer } from "./kernel/mail.ts";
88 import type { Database } from "bun:sqlite";
99 import type { Decider } from "./crew/decide.ts";
10 import type { VerifyHuman } from "./turnstile.ts";
1011 import { randomBytes } from "node:crypto";
1112 import { mkdirSync } from "node:fs";
1213 import { join, resolve } from "node:path";
@@ -95,6 +96,12 @@ export interface ForgeConfig {
9596 * (`actions/mail.ts`). Undefined is `FORGE_DAILY`.
9697 */
9798 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;
98105 /** Stand-in for `mail` in tests: receives each message instead of SMTP. */
99106 mailer?: Mailer;
100107 /**
src/http/api.ts +1
@@ -1113,6 +1113,7 @@ export function apiRoutes(router: Router<Handler>): void {
11131113 username: str(input.username),
11141114 email: str(input.email),
11151115 password: str(input.password),
1116 humanToken: str(input["cf-turnstile-response"]),
11161117 },
11171118 { address: clientAddress(ctx.request) },
11181119 );
src/main.ts +6
@@ -6,6 +6,7 @@
66
77 import { parseCidrs } from "./kernel/cidr.ts";
88 import { createApp } from "./app.ts";
9 import { turnstile } from "./turnstile.ts";
910 import { reconcile } from "./core/reconcile.ts";
1011 import { syncAllPillars } from "./actions/pillars.ts";
1112 import { firstBoot } from "./spawn/first-boot.ts";
@@ -132,6 +133,11 @@ const app = createApp({
132133 Number(process.env.FORGE_MAIL_DAILY) > 0
133134 ? { mailDailyCap: Number(process.env.FORGE_MAIL_DAILY) }
134135 : {}),
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 : {}),
135141 // Who may say who the client is: the ingress in front of a hosted forge.
136142 ...(trustedProxies.length > 0 ? { trustedProxies } : {}),
137143 ...((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> {
563563 const email = field(form, "email");
564564 const created = await signUp(
565565 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 },
567572 { address: clientAddress(ctx.request) },
568573 );
569574 if (!created.ok) {
@@ -575,6 +580,9 @@ export async function signupSubmit(ctx: Ctx): Promise<Response> {
575580 username_reserved: { username: "That name is reserved." },
576581 email_taken: { email: "That email already has an account." },
577582 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 },
578586 }[created.error] ?? { username: "Something went wrong." };
579587 return page(
580588 {
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 });

↑↓ navigate ↵ open ⌘↵ its app esc close

Keyboard shortcuts

Docs