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

Signup carries a Turnstile check verified on the server, landed from pull #1204 on today's main #1631

Closed opened this
Closed without merging

scout/forge:scout/1457-signup-carries-a-turnstile-check-verifie → main 6 commits fork

  • Closed without merging. Nothing was applied to main.

Review

Sign in to review this change.
13 files changed +371 −7
README.md +9 −1
@@ -115,7 +115,15 @@ signed in by the platform, with an account made on first sight. Mail out
115115 configured by the forge-level secrets `MAIL_SMTP_URL`
116116 (`smtps://user:pass@host:465`) and `MAIL_FROM`, set live under Settings →
117117 Secrets, or at boot by `FORGE_SMTP_URL` / `FORGE_MAIL_FROM`. With neither, no
118 mail is sent and a newcomer waits for the owner to verify them. Behind a
118 mail is sent and a newcomer waits for the owner to verify them. To put a
119 Cloudflare Turnstile check on signup, create a widget in Cloudflare and set
120 `FORGE_TURNSTILE_SITE_KEY` and `FORGE_TURNSTILE_SECRET` (both, in the
121 environment, never in the repository): `/signup` then shows the widget, the
122 server verifies the token before it hashes a password or makes an account,
123 and only that page's CSP admits `https://challenges.cloudflare.com`. With
124 either missing the check is off, and Settings → Capacity says so. Terminal
125 signup is refused while it is on; claim links and admin-made accounts are not
126 checked. Behind a
119127 proxy, `FORGE_TRUSTED_PROXIES` (comma-separated CIDR ranges, e.g.
120128 `10.42.0.0/16` for a k3s ingress) names the proxies allowed to say who the
121129 client is; limits for strangers and the signup audit then see each outside
scripts/gate.ts +1
@@ -79,6 +79,7 @@ export const GATE: readonly string[] = [
7979 "test/settings.test.ts",
8080 "test/signin-throttle.test.ts",
8181 "test/signins.test.ts",
82 "test/human-check.test.ts",
8283 "test/sole-owner-suspend.test.ts",
8384 "test/standing-every-process.test.ts",
8485 "test/steer.test.ts",
src/actions/users.ts +9 −2
@@ -11,6 +11,7 @@ import {
1111 parseAuthorizedKey,
1212 type UserKey,
1313 } from "../core/keys.ts";
14 import { passesHumanCheck } from "../core/human-check.ts";
1415 import { reservedName } from "../core/reserved.ts";
1516 import { setUserSetting } from "../core/settings.ts";
1617 import {
@@ -36,9 +37,11 @@ export interface SignUpInput {
3637 username: string;
3738 email: string;
3839 password: string;
40 /** The Turnstile token the form carried; unread when the check is off. */
41 humanToken?: string | undefined;
3942 }
4043
41 export type SignUpError = CreateUserError;
44 export type SignUpError = CreateUserError | "human_check";
4245
4346 /**
4447 * The first account on a fresh forge is the admin — no setup wizard. A name
@@ -51,7 +54,11 @@ export async function signUp(
5154 /** Where the request came from, for the owner's audit of who joined. */
5255 from: { address?: string | undefined } = {},
5356 ): Promise<Result<User, SignUpError>> {
54 const created = await createUser(app.db, { ...input, adminIfFirst: true });
57 // Before a password is hashed or a row made: a bot costs one fetch.
58 if (!(await passesHumanCheck(app.config, input.humanToken, from.address)))
59 return err("human_check");
60 const { humanToken: _token, ...account } = input;
61 const created = await createUser(app.db, { ...account, adminIfFirst: true });
5562 if (!created.ok) return created;
5663 app.bus.append({
5764 kind: "user.created",
src/app.ts +7
@@ -17,6 +17,7 @@ import { follow } from "./core/following.ts";
1717 import { enqueueForEvent } from "./core/webhooks.ts";
1818 import { openDb } from "./kernel/db.ts";
1919 import { id } from "./kernel/id.ts";
20 import type { HumanCheckConfig } from "./core/human-check.ts";
2021 import { createLog, type Log } from "./kernel/log.ts";
2122 import { closeReadersUnder } from "./git/read.ts";
2223
@@ -125,6 +126,12 @@ export interface ForgeConfig {
125126 * parent's updates. Unset, children are spawned without the fork.
126127 */
127128 forgeRepo?: string;
129 /**
130 * The Turnstile check on signup (`core/human-check.ts`): site key and
131 * secret from `FORGE_TURNSTILE_*`, and a `verify` a test injects.
132 * Undefined is no check.
133 */
134 humanCheck?: HumanCheckConfig;
128135 }
129136
130137 export interface App {
src/core/human-check.ts added +76
@@ -0,0 +1,76 @@
1 /**
2 * The human check on signup: Cloudflare Turnstile, verified here.
3 *
4 * On only when a site key and a secret are both configured
5 * (`FORGE_TURNSTILE_SITE_KEY`, `FORGE_TURNSTILE_SECRET`); either missing and
6 * the check is off. The secret goes to Cloudflare's siteverify and nowhere
7 * else — never into a page, a log or an error. `verify` is the seam a test
8 * replaces so no test reaches the network.
9 */
10
11 export const TURNSTILE_ORIGIN = "https://challenges.cloudflare.com";
12 const SITEVERIFY = `${TURNSTILE_ORIGIN}/turnstile/v0/siteverify`;
13 /** A token longer than this is not one Turnstile issued (it documents 2048). */
14 const TOKEN_MAX = 2048;
15
16 export type HumanVerifier = (
17 token: string,
18 address: string | undefined,
19 ) => Promise<boolean>;
20
21 export interface HumanCheckConfig {
22 siteKey: string;
23 secret: string;
24 /** Stand-in for Cloudflare in tests. Default: `turnstileVerifier(secret)`. */
25 verify?: HumanVerifier;
26 }
27
28 export function humanCheckOn(
29 config: { humanCheck?: HumanCheckConfig },
30 ): config is { humanCheck: HumanCheckConfig } {
31 const c = config.humanCheck;
32 return c !== undefined && c.siteKey !== "" && c.secret !== "";
33 }
34
35 /** The one line the admin's settings show. */
36 export function humanCheckLine(config: {
37 humanCheck?: HumanCheckConfig;
38 }): string {
39 return humanCheckOn(config)
40 ? "Human check on signup: on (Cloudflare Turnstile)."
41 : "Human check on signup: off. Set FORGE_TURNSTILE_SITE_KEY and FORGE_TURNSTILE_SECRET to turn it on.";
42 }
43
44 export function turnstileVerifier(secret: string): HumanVerifier {
45 return async (token, address) => {
46 try {
47 const body = new URLSearchParams({ secret, response: token });
48 if (address !== undefined) body.set("remoteip", address);
49 const res = await fetch(SITEVERIFY, {
50 method: "POST",
51 body,
52 signal: AbortSignal.timeout(5000),
53 });
54 if (!res.ok) return false;
55 const answer = (await res.json()) as { success?: unknown };
56 return answer.success === true;
57 } catch {
58 // A check that cannot be made is a refusal, not a pass.
59 return false;
60 }
61 };
62 }
63
64 /** True when the check is off, or the token is one Cloudflare vouches for. */
65 export async function passesHumanCheck(
66 config: { humanCheck?: HumanCheckConfig },
67 token: string | undefined,
68 address: string | undefined,
69 ): Promise<boolean> {
70 if (!humanCheckOn(config)) return true;
71 if (token === undefined || token === "" || token.length > TOKEN_MAX)
72 return false;
73 const verify =
74 config.humanCheck.verify ?? turnstileVerifier(config.humanCheck.secret);
75 return verify(token, address);
76 }
src/http/api.ts +6 −1
@@ -1112,10 +1112,15 @@ export function apiRoutes(router: Router<Handler>): void {
11121112 username: str(input.username),
11131113 email: str(input.email),
11141114 password: str(input.password),
1115 humanToken: str(input.human_token),
11151116 },
11161117 { address: clientAddress(ctx.request) },
11171118 );
1118 if (!created.ok) return json({ error: created.error }, 422);
1119 if (!created.ok)
1120 return json(
1121 { error: created.error },
1122 created.error === "human_check" ? 403 : 422,
1123 );
11191124 return json(publicUser(created.value), 201);
11201125 });
11211126
src/main.ts +10
@@ -132,6 +132,16 @@ const app = createApp({
132132 Number(process.env.FORGE_MAIL_DAILY) > 0
133133 ? { mailDailyCap: Number(process.env.FORGE_MAIL_DAILY) }
134134 : {}),
135 // The Turnstile check on signup: both keys, or no check (`core/human-check.ts`).
136 ...((process.env.FORGE_TURNSTILE_SITE_KEY ?? "").trim() !== "" &&
137 (process.env.FORGE_TURNSTILE_SECRET ?? "").trim() !== ""
138 ? {
139 humanCheck: {
140 siteKey: process.env.FORGE_TURNSTILE_SITE_KEY!.trim(),
141 secret: process.env.FORGE_TURNSTILE_SECRET!.trim(),
142 },
143 }
144 : {}),
135145 // Who may say who the client is: the ingress in front of a hosted forge.
136146 ...(trustedProxies.length > 0 ? { trustedProxies } : {}),
137147 ...((process.env.FORGE_CLIENT_IP_HEADER ?? "").trim() !== ""
src/tui/screens/signin.ts +6
@@ -8,6 +8,7 @@
88 * which is the admin — the terminal equivalent of the web's first-run signup.
99 */
1010
11 import { humanCheckOn } from "../../core/human-check.ts";
1112 import { signUp } from "../../actions/users.ts";
1213 import { hasAnyUser } from "../../core/users.ts";
1314 import type { Ctx, Screen } from "../app/app.ts";
@@ -60,6 +61,11 @@ export function signInScreen(f: Session, ctx: Ctx, onDone: () => void): Screen {
6061 string,
6162 string,
6263 ];
64 // A terminal has no widget to show: the web page is the way in.
65 if (humanCheckOn(f.app.config)) {
66 error = "Sign up on the web page: it carries a human check.";
67 return;
68 }
6369 const created = await signUp(
6470 f.app,
6571 { username, email, password },
src/web/layout.ts +7 −1
@@ -91,6 +91,11 @@ export interface PageOptions {
9191 * origin" — so pages that do not ask for it keep the stricter policy.
9292 */
9393 scriptAsset?: string;
94 /**
95 * The one third-party origin a page may load script, frame and talk to
96 * (Turnstile on /signup). Only the page that asks widens its policy.
97 */
98 humanCheckOrigin?: string;
9499 /** Extra palette rows for this page's context (a repo's own tabs). */
95100 palette?: PaletteItem[];
96101 /**
@@ -650,12 +655,13 @@ export function page(options: PageOptions, status = 200): Response {
650655 </body>
651656 </html>`;
652657
658 const third = options.humanCheckOrigin;
653659 const headers = new Headers({
654660 "content-type": "text/html; charset=utf-8",
655661 // The external stylesheet plus this page's own nonce'd <style>/<script>
656662 // are the only resources allowed; connect-src 'self' lets the live
657663 // event stream (EventSource) and fragment fetches reach same-origin.
658 "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'`,
664 "content-security-policy": `default-src 'none'; style-src 'self' 'nonce-${nonce}'; script-src 'nonce-${nonce}'${options.scriptAsset === undefined ? "" : " 'self'"}${third ? ` ${third}` : ""}; connect-src 'self'${third ? ` ${third}` : ""}; ${third ? `frame-src ${third}; ` : ""}worker-src 'self'; manifest-src 'self'; img-src 'self' data:; form-action 'self'; base-uri 'none'; frame-ancestors 'none'`,
659665 "referrer-policy": "same-origin",
660666 "x-content-type-options": "nosniff",
661667 // Markup is revalidated every time; only the hashed assets it names are
src/web/pages/capacity.ts +2
@@ -7,6 +7,7 @@
77 */
88
99 import { changeCapacity, listCapacity } from "../../actions/capacity.ts";
10 import { humanCheckLine } from "../../core/human-check.ts";
1011 import { CAPACITY, type CapacityKey } from "../../core/capacity.ts";
1112 import type { Ctx } from "../../http/context.ts";
1213 import { notFoundPage, settingsLayout, signInFirst } from "../chrome.ts";
@@ -113,6 +114,7 @@ export function capacityPage(ctx: Ctx): Response {
113114 )}
114115 ${card(
115116 html`<div class="card-body">
117 <p class="muted small" id="human-check">${humanCheckLine(ctx.app.config)}</p>
116118 <p class="muted small">
117119 How much the forge does at once. A change here takes effect on the
118120 next crew run, check or app start — running work is left to finish —
src/web/pages/site.ts +40 −2
@@ -8,6 +8,7 @@
88 * typed still in it. A dead end that loses input is a bug, not a message.
99 */
1010
11 import { humanCheckOn, TURNSTILE_ORIGIN } from "../../core/human-check.ts";
1112 import { limitValue } from "../../settings/limits.ts";
1213 import { mayView } from "../../core/sealed.ts";
1314 import { signOutHere } from "../../actions/signins.ts";
@@ -323,6 +324,7 @@ interface AuthErrors {
323324 username?: string;
324325 email?: string;
325326 password?: string;
327 humanCheck?: string;
326328 }
327329
328330 function authForm(
@@ -403,6 +405,24 @@ function authForm(
403405 : {}),
404406 ...(errors.password ? { error: errors.password } : {}),
405407 })}
408 ${when(humanCheckOn(ctx.app.config) && kind === "signup", () => {
409 const check = ctx.app.config.humanCheck!;
410 return html`<div class="mb">
411 <div
412 class="cf-turnstile"
413 data-sitekey="${check.siteKey}"
414 data-response-field-name="human_token"
415 ></div>
416 ${errors.humanCheck
417 ? html`<span class="error" role="alert">${errors.humanCheck}</span>`
418 : null}
419 <script
420 src="${TURNSTILE_ORIGIN}/turnstile/v0/api.js"
421 async
422 defer
423 ></script>
424 </div>`;
425 })}
406426 ${when(
407427 firstAccount,
408428 () =>
@@ -449,8 +469,17 @@ export function signinPage(ctx: Ctx): Response {
449469 return page({ ctx, title: "Sign in", body: authForm(ctx, "signin") });
450470 }
451471
472 /** Only the signup page, and only with the check on, admits Cloudflare. */
473 const signupOrigin = (ctx: Ctx) =>
474 humanCheckOn(ctx.app.config) ? { humanCheckOrigin: TURNSTILE_ORIGIN } : {};
475
452476 export function signupPage(ctx: Ctx): Response {
453 return page({ ctx, title: "Sign up", body: authForm(ctx, "signup") });
477 return page({
478 ctx,
479 title: "Sign up",
480 body: authForm(ctx, "signup"),
481 ...signupOrigin(ctx),
482 });
454483 }
455484
456485 /**
@@ -563,7 +592,12 @@ export async function signupSubmit(ctx: Ctx): Promise<Response> {
563592 const email = field(form, "email");
564593 const created = await signUp(
565594 ctx.app,
566 { username, email, password: field(form, "password") },
595 {
596 username,
597 email,
598 password: field(form, "password"),
599 humanToken: field(form, "human_token"),
600 },
567601 { address: clientAddress(ctx.request) },
568602 );
569603 if (!created.ok) {
@@ -575,12 +609,16 @@ export async function signupSubmit(ctx: Ctx): Promise<Response> {
575609 username_reserved: { username: "That name is reserved." },
576610 email_taken: { email: "That email already has an account." },
577611 weak_password: { password: "Passwords need at least 10 characters." },
612 human_check: {
613 humanCheck: "Please complete the human check and try again.",
614 },
578615 }[created.error] ?? { username: "Something went wrong." };
579616 return page(
580617 {
581618 ctx,
582619 title: "Sign up",
583620 body: authForm(ctx, "signup", { values: { username, email }, errors }),
621 ...signupOrigin(ctx),
584622 },
585623 422,
586624 );
test/asks.test.ts +6
@@ -17,6 +17,8 @@ import type { Repo } from "../src/core/repos.ts";
1717 import { claimRun, createRun, finishRun } from "../src/core/runs.ts";
1818 import { getUserByName } from "../src/core/users.ts";
1919 import { serve, type Servers } from "../src/http/server.ts";
20 import { resetRefusedInternal } from "../src/kernel/internal_refused.ts";
21 import { clearErrors } from "../src/kernel/log.ts";
2022 import { quietLogs } from "./helpers/globals.ts";
2123
2224 quietLogs();
@@ -87,6 +89,10 @@ describe("the asks page", () => {
8789 });
8890
8991 test("when nothing asks, it says All fine, and so does the header", async () => {
92 // The forge's own needs read process-wide counters (errors, refused
93 // internal calls) that an earlier suite in this process may have left.
94 clearErrors();
95 resetRefusedInternal();
9096 const page = await get(alice, "/");
9197 expect(sentence(page)).toBe("All fine");
9298 expect(headerCount(page)).toBe(0);
test/human-check.test.ts added +192
@@ -0,0 +1,192 @@
1 import { afterEach, describe, expect, test } from "bun:test";
2 import { mkdtemp, rm } from "node:fs/promises";
3 import { tmpdir } from "node:os";
4 import { join } from "node:path";
5 import { createApp, type App } from "../src/app.ts";
6 import { createSession } from "../src/core/sessions.ts";
7 import { createUser, getUserByName } from "../src/core/users.ts";
8 import { serve, type Servers } from "../src/http/server.ts";
9 import { createForgeApp } from "../src/tui/forge.ts";
10 import { headlessTerminal } from "../src/tui/term/terminal.ts";
11 import { settleApp } from "./helpers/tui.ts";
12
13 // Signup's Turnstile check: on only with both keys, verified by the server
14 // before an account is made, widening the CSP of /signup alone.
15 describe("signup human check", () => {
16 let dir = "";
17 let app: App;
18 let servers: Servers;
19 let base = "";
20 let seen: (string | undefined)[] = [];
21
22 const boot = async (on: boolean) => {
23 dir = await mkdtemp(join(tmpdir(), "forge-human-"));
24 app = createApp({
25 dataDir: dir,
26 port: 0,
27 ...(on
28 ? {
29 humanCheck: {
30 siteKey: "site-key-123",
31 secret: "very-secret-value",
32 verify: async (token: string) => {
33 seen.push(token);
34 return token === "good";
35 },
36 },
37 }
38 : {}),
39 });
40 servers = await serve(app);
41 base = servers.url;
42 };
43 afterEach(async () => {
44 servers?.stop();
45 app?.close();
46 seen = [];
47 await rm(dir, { recursive: true, force: true });
48 });
49
50 const form = (fields: Record<string, string>) =>
51 fetch(`${base}/signup`, {
52 method: "POST",
53 headers: { origin: base, "content-type": "application/x-www-form-urlencoded" },
54 body: new URLSearchParams({
55 username: "newbie",
56 email: "[email protected]",
57 password: "a-good-passphrase",
58 ...fields,
59 }),
60 redirect: "manual",
61 });
62
63 test("the page renders the widget, with the origin in its CSP alone", async () => {
64 await boot(true);
65 const res = await fetch(`${base}/signup`);
66 const body = await res.text();
67 const csp = res.headers.get("content-security-policy") ?? "";
68 expect(body).toContain('data-sitekey="site-key-123"');
69 expect(body).not.toContain("very-secret-value");
70 expect(csp).toContain("https://challenges.cloudflare.com");
71 const other = await fetch(`${base}/signin`);
72 expect(other.headers.get("content-security-policy")).not.toContain(
73 "cloudflare",
74 );
75 expect(await other.text()).not.toContain("cf-turnstile");
76 });
77
78 test("a missing or bad token makes no account", async () => {
79 await boot(true);
80 for (const fields of [{}, { human_token: "bad" }]) {
81 const res = await form(fields);
82 expect(res.status).toBe(422);
83 expect(await res.text()).toContain(
84 "Please complete the human check and try again.",
85 );
86 }
87 expect(getUserByName(app.db, "newbie")).toBeUndefined();
88 expect(seen).toEqual(["bad"]);
89 });
90
91 test("a good token makes the account", async () => {
92 await boot(true);
93 const res = await form({ human_token: "good" });
94 expect(res.status).toBe(303);
95 expect(getUserByName(app.db, "newbie")).toBeDefined();
96 });
97
98 test("the API refuses without a token and takes human_token", async () => {
99 await boot(true);
100 const post = (extra: object) =>
101 fetch(`${base}/api/v1/users`, {
102 method: "POST",
103 headers: { "content-type": "application/json", origin: base },
104 body: JSON.stringify({
105 username: "apiuser",
106 email: "[email protected]",
107 password: "a-good-passphrase",
108 ...extra,
109 }),
110 });
111 const refused = await post({});
112 expect(refused.status).toBe(403);
113 expect(((await refused.json()) as { error: string }).error).toBe("human_check");
114 expect((await post({ human_token: "good" })).status).toBe(201);
115 });
116
117 test("with no key the check is off and the admin's settings say so", async () => {
118 await boot(false);
119 const page = await (await fetch(`${base}/signup`)).text();
120 expect(page).not.toContain("cf-turnstile");
121 expect((await form({})).status).toBe(303);
122 const admin = getUserByName(app.db, "newbie")!;
123 const res = await fetch(`${base}/settings/capacity`, {
124 headers: { cookie: `forge_session=${createSession(app.db, admin.id).token}` },
125 });
126 expect(await res.text()).toContain("Human check on signup: off.");
127 });
128
129 test("the settings line says on when the keys are set", async () => {
130 await boot(true);
131 const made = await createUser(app.db, {
132 username: "boss",
133 email: "[email protected]",
134 password: "a-good-passphrase",
135 adminIfFirst: true,
136 trusted: true,
137 });
138 if (!made.ok) throw new Error(made.error);
139 const res = await fetch(`${base}/settings/capacity`, {
140 headers: { cookie: `forge_session=${createSession(app.db, made.value.id).token}` },
141 });
142 expect(await res.text()).toContain("Human check on signup: on");
143 });
144
145 // The terminal has no widget to show, so with the check on its signup is
146 // refused; with it off the same keystrokes make the account.
147 const terminalSignup = async () => {
148 const { app: tui } = createForgeApp(
149 app,
150 {
151 sshUsername: "git",
152 remoteAddress: "127.0.0.1",
153 fingerprint: "SHA256:unknown",
154 },
155 { terminal: headlessTerminal(120, 32), exitHooks: false },
156 );
157 tui.start();
158 const type = async (text: string) => {
159 for (const key of text)
160 tui.dispatch({ type: "key", key, ctrl: false, alt: false, shift: false });
161 await settleApp(tui);
162 };
163 try {
164 await settleApp(tui);
165 await type("s"); // an empty forge opens the screen in create mode
166 await type("newbie");
167 tui.dispatch({ type: "key", key: "tab", ctrl: false, alt: false, shift: false });
168 await type("[email protected]");
169 tui.dispatch({ type: "key", key: "tab", ctrl: false, alt: false, shift: false });
170 await type("a-good-passphrase");
171 tui.dispatch({ type: "key", key: "enter", ctrl: false, alt: false, shift: false });
172 await settleApp(tui);
173 return tui.screen.toText();
174 } finally {
175 tui.stop();
176 }
177 };
178
179 test("the terminal refuses signup while the check is on", async () => {
180 await boot(true);
181 const screen = await terminalSignup();
182 expect(getUserByName(app.db, "newbie")).toBeUndefined();
183 expect(screen).toContain("Sign up on the web page");
184 });
185
186 test("the terminal signs up when the check is off", async () => {
187 await boot(false);
188 const screen = await terminalSignup();
189 expect(getUserByName(app.db, "newbie")).toBeDefined();
190 expect(screen).not.toContain("Sign up on the web page");
191 });
192 });

↑↓ navigate ↵ open ⌘↵ its app esc close

Keyboard shortcuts

Docs