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

Signup carries a human check verified on the server before an account is made #1160

Closed opened this
Closed without merging

scout/forge:scout/975-signup-carries-a-human-check-verified-on → main 6 commits fork

  • Closed without merging. Nothing was applied to main.

Review

Sign in to review this change.
35 files changed +311 −10
.bash_profile added
No content changes.
.bashrc added
No content changes.
.claude/agents added
No content changes.
.claude/commands added
No content changes.
.claude/hooks added
No content changes.
.claude/launch.json added
No content changes.
.claude/loop.md added
No content changes.
.claude/output-styles added
No content changes.
.claude/routines added
No content changes.
.claude/scheduled_tasks.json added
No content changes.
.claude/settings.json added
No content changes.
.claude/settings.local.json added
No content changes.
.claude/skills added
No content changes.
.claude/workflows added
No content changes.
.gitconfig added
No content changes.
.gitmodules added
No content changes.
.idea added
No content changes.
.mcp.json added
No content changes.
.profile added
No content changes.
.ripgreprc added
No content changes.
.vscode added
No content changes.
.zprofile added
No content changes.
.zshrc added
No content changes.
README.md +7 −1
@@ -95,7 +95,13 @@ 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. The signup human check is Cloudflare Turnstile: set
99 `FORGE_TURNSTILE_SITE_KEY` and `FORGE_TURNSTILE_SECRET` (the deployment's
100 settings, never the repository) and `/signup`, the API's `POST /api/v1/users`
101 (field `human_token`) verify the token on the
102 server before an account is made (the terminal's sign-up is refused while it is on); the signup page's CSP then admits
103 `challenges.cloudflare.com` and nothing else. With either missing the check is
104 off, and Settings → Capacity says so. No dependency: the verifier is one `fetch`. Mail out
99105 (the link that proves a newcomer's email) is SMTP submission over TLS,
100106 configured by the forge-level secrets `MAIL_SMTP_URL`
101107 (`smtps://user:pass@host:465`) and `MAIL_FROM`, set live under Settings →
scripts/gate.ts +1
@@ -212,6 +212,7 @@ export const GATE: readonly string[] = [
212212 "test/report-discovery.test.ts",
213213 "test/apps-report.test.ts",
214214 "test/private-app.test.ts",
215 "test/human-check.test.ts",
215216 "test/actions.test.ts",
216217 "test/app-env.test.ts",
217218 "test/apps-ssh.test.ts",
src/actions/users.ts +6 −2
@@ -11,6 +11,7 @@ import {
1111 parseAuthorizedKey,
1212 type UserKey,
1313 } from "../core/keys.ts";
14 import { passesHumanCheck } from "../core/humancheck.ts";
1415 import { reservedName } from "../core/reserved.ts";
1516 import { setUserSetting } from "../core/settings.ts";
1617 import {
@@ -38,7 +39,7 @@ export interface SignUpInput {
3839 password: string;
3940 }
4041
41 export type SignUpError = CreateUserError;
42 export type SignUpError = CreateUserError | "human_check";
4243
4344 /**
4445 * The first account on a fresh forge is the admin — no setup wizard. A name
@@ -49,8 +50,11 @@ export async function signUp(
4950 app: App,
5051 input: SignUpInput,
5152 /** Where the request came from, for the owner's audit of who joined. */
52 from: { address?: string | undefined } = {},
53 from: { address?: string | undefined; humanToken?: string | undefined } = {},
5354 ): Promise<Result<User, SignUpError>> {
55 // Before the hash and before the row: a refused check costs nothing.
56 if (!(await passesHumanCheck(app.config, from.humanToken, from.address)))
57 return err("human_check");
5458 const created = await createUser(app.db, { ...input, adminIfFirst: true });
5559 if (!created.ok) return created;
5660 app.bus.append({
src/app.ts +12
@@ -20,6 +20,16 @@ import { id } from "./kernel/id.ts";
2020 import { createLog, type Log } from "./kernel/log.ts";
2121 import { closeReadersUnder } from "./git/read.ts";
2222
23 /** The signup human check (`core/humancheck.ts`); absent, it is off. */
24 export interface HumanCheckConfig {
25 /** Public: rendered into the signup page. */
26 siteKey: string;
27 /** Private: sent only to the verifier. */
28 secret: string;
29 /** Stand-in for Turnstile's siteverify in tests. */
30 verify?: (token: string, address?: string) => Promise<boolean>;
31 }
32
2333 export interface ForgeConfig {
2434 /** Everything lives here: index db, bare repos, the internal socket. */
2535 dataDir: string;
@@ -88,6 +98,8 @@ export interface ForgeConfig {
8898 * (`actions/mail.ts`). Undefined is `FORGE_DAILY`.
8999 */
90100 mailDailyCap?: number;
101 /** Turnstile on signup (`FORGE_TURNSTILE_SITE_KEY`, `FORGE_TURNSTILE_SECRET`). */
102 humanCheck?: HumanCheckConfig;
91103 /** Stand-in for `mail` in tests: receives each message instead of SMTP. */
92104 mailer?: Mailer;
93105 /**
src/core/humancheck.ts added +69
@@ -0,0 +1,69 @@
1 /**
2 * The human check on signup: Cloudflare Turnstile, when a site key and a
3 * secret are configured (`FORGE_TURNSTILE_SITE_KEY`, `FORGE_TURNSTILE_SECRET`
4 * — the deployment's settings, never the repository). Without both, the
5 * check is off. The verifier is a seam: tests hand `createApp` a fake, so
6 * nothing here needs the network to be proven.
7 */
8
9 import type { HumanCheckConfig } from "../app.ts";
10
11 export const TURNSTILE_ORIGIN = "https://challenges.cloudflare.com";
12 const VERIFY_URL = `${TURNSTILE_ORIGIN}/turnstile/v0/siteverify`;
13 /** The form field the widget fills. */
14 export const TURNSTILE_FIELD = "cf-turnstile-response";
15 const MAX_TOKEN = 2048;
16
17 export const HUMAN_CHECK_MESSAGE =
18 "Please complete the human check and try again.";
19
20 /** Whether signups are checked: a configured key pair. */
21 export function humanCheckOn(
22 config: { humanCheck?: HumanCheckConfig | undefined },
23 ): config is { humanCheck: HumanCheckConfig } {
24 return config.humanCheck !== undefined;
25 }
26
27 /** Ask Turnstile whether `token` passed. A network failure is a refusal. */
28 export async function verifyTurnstile(
29 secret: string,
30 token: string,
31 address?: string,
32 ): Promise<boolean> {
33 try {
34 const body = new URLSearchParams({ secret, response: token });
35 if (address) body.set("remoteip", address);
36 const res = await fetch(VERIFY_URL, {
37 method: "POST",
38 body,
39 signal: AbortSignal.timeout(5000),
40 });
41 if (!res.ok) return false;
42 const answer: unknown = await res.json();
43 return (
44 typeof answer === "object" &&
45 answer !== null &&
46 (answer as { success?: unknown }).success === true
47 );
48 } catch {
49 return false;
50 }
51 }
52
53 /**
54 * Whether this request may make an account. Off, always. On, only a
55 * non-empty, bounded token the verifier accepts.
56 */
57 export async function passesHumanCheck(
58 config: { humanCheck?: HumanCheckConfig | undefined },
59 token: string | undefined,
60 address?: string,
61 ): Promise<boolean> {
62 if (!humanCheckOn(config)) return true;
63 if (token === undefined || token === "" || token.length > MAX_TOKEN)
64 return false;
65 const { verify, secret } = config.humanCheck;
66 return verify
67 ? verify(token, address)
68 : verifyTurnstile(secret, token, address);
69 }
src/http/api.ts +9 −2
@@ -124,6 +124,7 @@ import {
124124 updateProfile,
125125 } from "../actions/users.ts";
126126 import { listEvents } from "../core/events.ts";
127 import { HUMAN_CHECK_MESSAGE } from "../core/humancheck.ts";
127128 import { audienceFilter } from "../core/event_audience.ts";
128129 import {
129130 forkParentFor,
@@ -1101,9 +1102,15 @@ export function apiRoutes(router: Router<Handler>): void {
11011102 email: str(input.email),
11021103 password: str(input.password),
11031104 },
1104 { address: clientAddress(ctx.request) },
1105 {
1106 address: clientAddress(ctx.request),
1107 humanToken: str(input.human_token),
1108 },
11051109 );
1106 if (!created.ok) return json({ error: created.error }, 422);
1110 if (!created.ok)
1111 return created.error === "human_check"
1112 ? json({ error: created.error, message: HUMAN_CHECK_MESSAGE }, 403)
1113 : json({ error: created.error }, 422);
11071114 return json(publicUser(created.value), 201);
11081115 });
11091116
src/main.ts +9
@@ -72,6 +72,10 @@ const canonicalUrl = hosted ? hostedAt : (process.env.FORGE_URL ?? "").trim();
7272 // identity headers sign people in; without it they are ignored.
7373 const edgeToken = (process.env.FORGE_EDGE_TOKEN ?? "").trim();
7474
75 // The human check on signup: both halves or it is off.
76 const turnstileSiteKey = (process.env.FORGE_TURNSTILE_SITE_KEY ?? "").trim();
77 const turnstileSecret = (process.env.FORGE_TURNSTILE_SECRET ?? "").trim();
78
7579 const dataDir =
7680 process.env.FORGE_DATA ??
7781 (hosted ? process.env.FORGE_APP_DATA : undefined) ??
@@ -106,6 +110,11 @@ const app = createApp({
106110 : { host: process.env.FORGE_HOST }),
107111 ...(canonicalUrl === "" ? {} : { url: new URL(canonicalUrl).origin }),
108112 ...(edgeToken === "" ? {} : { edgeToken }),
113 ...(turnstileSiteKey === "" || turnstileSecret === ""
114 ? {}
115 : {
116 humanCheck: { siteKey: turnstileSiteKey, secret: turnstileSecret },
117 }),
109118 // Hosted, the host says how this forge's terminal is reached; printed
110119 // verbatim wherever the forge tells people how to connect.
111120 ...(hosted && (process.env.FORGE_APP_SSH ?? "").trim() !== ""
src/tui/screens/common.ts +2
@@ -813,6 +813,8 @@ export function slug(path: string): string {
813813 // ---- errors and time ----
814814
815815 const MESSAGES: Record<string, string> = {
816 human_check:
817 "the human check runs on the web signup page; sign up there first",
816818 not_found: "not found",
817819 unauthorized: "sign in first",
818820 forbidden: "you do not have permission",
src/web/layout.ts +7 −1
@@ -7,6 +7,7 @@
77 * `/search`), and every dialog (a link to a real page).
88 */
99
10 import { TURNSTILE_ORIGIN } from "../core/humancheck.ts";
1011 import { askCountFor } from "./studio/asks.ts";
1112 import { appsForRepos } from "../core/apps.ts";
1213 import { listReposVisibleTo } from "../core/repos.ts";
@@ -91,6 +92,11 @@ export interface PageOptions {
9192 * origin" — so pages that do not ask for it keep the stricter policy.
9293 */
9394 scriptAsset?: string;
95 /**
96 * The signup page carries Turnstile: its one origin is admitted for the
97 * script and the widget's frame, and nothing else is relaxed.
98 */
99 humanCheck?: boolean;
94100 /** Extra palette rows for this page's context (a repo's own tabs). */
95101 palette?: PaletteItem[];
96102 /**
@@ -641,7 +647,7 @@ export function page(options: PageOptions, status = 200): Response {
641647 // The external stylesheet plus this page's own nonce'd <style>/<script>
642648 // are the only resources allowed; connect-src 'self' lets the live
643649 // event stream (EventSource) and fragment fetches reach same-origin.
644 "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'`,
650 "content-security-policy": `default-src 'none'; style-src 'self' 'nonce-${nonce}'; script-src 'nonce-${nonce}'${options.scriptAsset === undefined ? "" : " 'self'"}${options.humanCheck ? ` ${TURNSTILE_ORIGIN}` : ""}; ${options.humanCheck ? `frame-src ${TURNSTILE_ORIGIN}; ` : ""}connect-src 'self'; worker-src 'self'; manifest-src 'self'; img-src 'self' data:; form-action 'self'; base-uri 'none'; frame-ancestors 'none'`,
645651 "referrer-policy": "same-origin",
646652 "x-content-type-options": "nosniff",
647653 // Markup is revalidated every time; only the hashed assets it names are
src/web/pages/capacity.ts +13 −1
@@ -8,6 +8,8 @@
88
99 import { changeCapacity, listCapacity } from "../../actions/capacity.ts";
1010 import { CAPACITY, type CapacityKey } from "../../core/capacity.ts";
11 import type { ForgeConfig } from "../../app.ts";
12 import { humanCheckOn } from "../../core/humancheck.ts";
1113 import type { Ctx } from "../../http/context.ts";
1214 import { notFoundPage, settingsLayout, signInFirst } from "../chrome.ts";
1315 import { field, readForm } from "../form.ts";
@@ -48,6 +50,13 @@ function input(key: CapacityKey, value: string) {
4850 />`;
4951 }
5052
53 /** The signup human check, in one line: on or off, and how to change it. */
54 export function humanCheckLine(config: ForgeConfig): string {
55 return humanCheckOn(config)
56 ? "Signup human check: on (Cloudflare Turnstile)."
57 : "Signup human check: off. Set FORGE_TURNSTILE_SITE_KEY and FORGE_TURNSTILE_SECRET to turn it on.";
58 }
59
5160 // GET /settings/capacity
5261 export function capacityPage(ctx: Ctx): Response {
5362 const denied = requireAdmin(ctx);
@@ -101,7 +110,10 @@ export function capacityPage(ctx: Ctx): Response {
101110 const reported = settings.some(
102111 (s) => s.key === "cells.egress" && s.value === "report",
103112 );
104 const body = html`${when(
113 const body = html`<p class="muted small mb" id="human-check">
114 ${icon("shield")} ${humanCheckLine(ctx.app.config)}
115 </p>
116 ${when(
105117 reported,
106118 () => html`<p class="muted small mb" id="egress-reported">
107119 ${icon("activity")} Egress is reported, not enforced: every new app,
src/web/pages/site.ts +32 −3
@@ -35,7 +35,13 @@ import { sshCommand } from "../../ssh/command.ts";
3535 import { hostOf, pageHead, signInFirst } from "../chrome.ts";
3636 import { RateLimiter } from "../../core/ratelimit.ts";
3737 import { field, readForm } from "../form.ts";
38 import { html, when, type Html } from "../html.ts";
38 import { html, raw, when, type Html } from "../html.ts";
39 import {
40 HUMAN_CHECK_MESSAGE,
41 TURNSTILE_FIELD,
42 TURNSTILE_ORIGIN,
43 humanCheckOn,
44 } from "../../core/humancheck.ts";
3945 import { icon } from "../icons.ts";
4046 import { flashTo, page, redirect } from "../layout.ts";
4147 import {
@@ -260,6 +266,7 @@ interface AuthValues {
260266 }
261267
262268 interface AuthErrors {
269 human?: string;
263270 username?: string;
264271 email?: string;
265272 password?: string;
@@ -343,6 +350,18 @@ function authForm(
343350 : {}),
344351 ...(errors.password ? { error: errors.password } : {}),
345352 })}
353 ${when(
354 kind === "signup" ? ctx.app.config.humanCheck : undefined,
355 (check) =>
356 html`<div class="mb">
357 <div class="cf-turnstile" data-sitekey="${check.siteKey}"></div>
358 ${raw(`<script src="${TURNSTILE_ORIGIN}/turnstile/v0/api.js" async defer></script>`)}
359 ${when(
360 errors.human,
361 (m) => html`<p class="error" role="alert">${m}</p>`,
362 )}
363 </div>`,
364 )}
346365 ${when(
347366 firstAccount,
348367 () =>
@@ -390,7 +409,12 @@ export function signinPage(ctx: Ctx): Response {
390409 }
391410
392411 export function signupPage(ctx: Ctx): Response {
393 return page({ ctx, title: "Sign up", body: authForm(ctx, "signup") });
412 return page({
413 ctx,
414 title: "Sign up",
415 body: authForm(ctx, "signup"),
416 humanCheck: humanCheckOn(ctx.app.config),
417 });
394418 }
395419
396420 /**
@@ -504,10 +528,14 @@ export async function signupSubmit(ctx: Ctx): Promise<Response> {
504528 const created = await signUp(
505529 ctx.app,
506530 { username, email, password: field(form, "password") },
507 { address: clientAddress(ctx.request) },
531 {
532 address: clientAddress(ctx.request),
533 humanToken: field(form, TURNSTILE_FIELD),
534 },
508535 );
509536 if (!created.ok) {
510537 const errors: AuthErrors = {
538 human_check: { human: HUMAN_CHECK_MESSAGE },
511539 invalid_username: {
512540 username: "Usernames are letters, digits, dots, dashes.",
513541 },
@@ -521,6 +549,7 @@ export async function signupSubmit(ctx: Ctx): Promise<Response> {
521549 ctx,
522550 title: "Sign up",
523551 body: authForm(ctx, "signup", { values: { username, email }, errors }),
552 humanCheck: humanCheckOn(ctx.app.config),
524553 },
525554 422,
526555 );
test/human-check.test.ts added +144
@@ -0,0 +1,144 @@
1 import { afterAll, beforeAll, 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 { serve, type Servers } from "../src/http/server.ts";
7 import { getUserByName } from "../src/core/users.ts";
8
9 const asked: string[] = [];
10
11 describe("the signup human check", () => {
12 let dataDir: string;
13 let app: App;
14 let servers: Servers;
15 let base: string;
16
17 beforeAll(async () => {
18 dataDir = await mkdtemp(join(tmpdir(), "forge-human-"));
19 app = createApp({
20 dataDir,
21 port: 0,
22 humanCheck: {
23 siteKey: "site-key-public",
24 secret: "secret-never-shown",
25 verify: async (token) => {
26 asked.push(token);
27 return token === "good";
28 },
29 },
30 });
31 servers = await serve(app);
32 base = servers.url;
33 });
34
35 afterAll(async () => {
36 servers.stop();
37 app.close();
38 await rm(dataDir, { recursive: true, force: true });
39 });
40
41 const post = (name: string, token?: string) =>
42 fetch(`${base}/signup`, {
43 method: "POST",
44 redirect: "manual",
45 headers: { origin: base },
46 body: new URLSearchParams({
47 username: name,
48 email: `${name}@example.com`,
49 password: "correct horse battery",
50 ...(token === undefined ? {} : { "cf-turnstile-response": token }),
51 }),
52 });
53
54 test("the page carries the widget and admits only Turnstile's origin", async () => {
55 const res = await fetch(`${base}/signup`);
56 const html = await res.text();
57 const csp = res.headers.get("content-security-policy") ?? "";
58 expect(html).toContain('data-sitekey="site-key-public"');
59 expect(html).not.toContain("secret-never-shown");
60 expect(csp).toContain("script-src 'nonce-");
61 expect(csp).toContain("https://challenges.cloudflare.com");
62 expect(csp).toContain("frame-src https://challenges.cloudflare.com;");
63 const signin = await fetch(`${base}/signin`);
64 expect(signin.headers.get("content-security-policy")).not.toContain(
65 "cloudflare",
66 );
67 });
68
69 test("a missing or bad token makes no account", async () => {
70 const missing = await post("nomissing");
71 expect(missing.status).toBe(422);
72 expect(await missing.text()).toContain("complete the human check");
73 const bad = await post("nobad", "bad");
74 expect(bad.status).toBe(422);
75 expect(getUserByName(app.db, "nomissing")).toBeUndefined();
76 expect(getUserByName(app.db, "nobad")).toBeUndefined();
77 expect(asked).toEqual(["bad"]);
78 });
79
80 test("a good token makes the account", async () => {
81 const res = await post("ada", "good");
82 expect(res.status).toBe(303);
83 expect(getUserByName(app.db, "ada")).toBeDefined();
84 });
85
86 test("the API refuses the same way", async () => {
87 const send = (extra: object) =>
88 fetch(`${base}/api/v1/users`, {
89 method: "POST",
90 headers: { "content-type": "application/json" },
91 body: JSON.stringify({
92 username: "bob",
93 email: "[email protected]",
94 password: "correct horse battery",
95 ...extra,
96 }),
97 });
98 const refused = await send({});
99 expect(refused.status).toBe(403);
100 expect(((await refused.json()) as { error: string }).error).toBe("human_check");
101 expect(getUserByName(app.db, "bob")).toBeUndefined();
102 expect((await send({ human_token: "good" })).status).toBe(201);
103 });
104 });
105
106 describe("with no key configured", () => {
107 test("the check is off: no widget, no Turnstile origin, signup unchanged", async () => {
108 const dir = await mkdtemp(join(tmpdir(), "forge-human-off-"));
109 const app = createApp({ dataDir: dir, port: 0 });
110 const servers = await serve(app);
111 try {
112 const res = await fetch(`${servers.url}/signup`);
113 expect(await res.text()).not.toContain("cf-turnstile");
114 expect(res.headers.get("content-security-policy")).not.toContain(
115 "cloudflare",
116 );
117 const made = await fetch(`${servers.url}/api/v1/users`, {
118 method: "POST",
119 headers: { "content-type": "application/json" },
120 body: JSON.stringify({
121 username: "eve",
122 email: "[email protected]",
123 password: "correct horse battery",
124 }),
125 });
126 expect(made.status).toBe(201);
127 } finally {
128 servers.stop();
129 app.close();
130 await rm(dir, { recursive: true, force: true });
131 }
132 });
133 });
134
135 describe("the admin's settings line", () => {
136 test("says on or off in one line", async () => {
137 const { humanCheckLine } = await import("../src/web/pages/capacity.ts");
138 const base = { dataDir: "x", port: 0 };
139 expect(humanCheckLine(base)).toContain("off");
140 expect(
141 humanCheckLine({ ...base, humanCheck: { siteKey: "a", secret: "b" } }),
142 ).toContain("on");
143 });
144 });

↑↓ navigate ↵ open ⌘↵ its app esc close

Keyboard shortcuts

Docs