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

The owner can close signup: one live setting, open or closed, kept on every way an account is made #1154

Parked opened this
Closed without merging

scout/forge:scout/1142-the-owner-can-close-signup-one-live-sett → main 3 commits fork

  • Closed without merging. Nothing was applied to main.

Review

Sign in to review this change.
9 files changed +253 −5
README.md +1 −1
@@ -169,7 +169,7 @@ adds `FORGE_URL` (the canonical public base URL, needed for OAuth callbacks),
169169 `FORGE_ORIGIN_ALLOW` (hosts an operator vouches for on a LAN). Behind a
170170 platform edge that signs people in for every app it serves, `FORGE_EDGE_TOKEN`
171171 is the edge's secret: a request carrying it and `X-Plat-User` is that person,
172 signed in by the platform, with an account made on first sight. Mail out
172 signed in by the platform, with an account made on first sight. `FORGE_SIGNUP` (`open`, `invite` or `closed`; a wrong word fails the boot) says who may make an account; an admin changes it live under Settings → Capacity, `PATCH /api/v1/admin/settings` or the `capacity` MCP tool, and closed also stops the edge's first-sight accounts (the forge's first account is always let in; `invite` acts as closed for now). Mail out
173173 (the link that proves a newcomer's email) is SMTP submission over TLS,
174174 configured by the forge-level secrets `MAIL_SMTP_URL`
175175 (`smtps://user:pass@host:465`) and `MAIL_FROM`, set live under Settings →
src/actions/users.ts +3 −1
@@ -34,6 +34,7 @@ import {
3434 type UpdateProfileError,
3535 type User,
3636 } from "../core/users.ts";
37 import { signupOpen } from "../core/capacity.ts";
3738 import { err, ok, type Result } from "../kernel/result.ts";
3839 import { requireUser } from "./access.ts";
3940
@@ -45,7 +46,7 @@ export interface SignUpInput {
4546 humanToken?: string;
4647 }
4748
48 export type SignUpError = CreateUserError | "human_check" | "passkey_required";
49 export type SignUpError = CreateUserError | "human_check" | "passkey_required" | "signup_closed";
4950
5051 /** What anyone is told at a door that still offers a password-only sign-up. */
5152 export const PASSKEY_REQUIRED_MESSAGE =
@@ -84,6 +85,7 @@ export async function signUp(
8485 // when every such account has a passkey (Settings → Passkeys shows who is
8586 // left) and recovery without a password exists (#1618): then delete this
8687 // action's password path, `verifyPassword`'s doors and the password column.
88 if (!signupOpen(app.db)) return err("signup_closed");
8789 if (app.config.passkeyOnlySignup === true) return err("passkey_required");
8890 const secret = app.config.turnstileSecret;
8991 const bootstrap = from.door === "terminal" && !hasAnyUser(app.db);
src/core/capacity.ts +24 −1
@@ -21,7 +21,8 @@ export type CapacityKey =
2121 | "checks.shards"
2222 | "children.max"
2323 | "cells.egress"
24 | "guard_new_accounts";
24 | "guard_new_accounts"
25 | "signup";
2526
2627 interface Definition {
2728 /** What the settings page and the API call it. */
@@ -80,6 +81,13 @@ export const CAPACITY: Record<CapacityKey, Definition> = {
8081 fallback: "off",
8182 help: "on refuses repository creation and forks for accounts younger than 7 days (agents and admins are exempt); off leaves it to the usual permissions. Takes effect immediately. Replaces the hand-installed database trigger that used to do this with no toggle.",
8283 },
84 signup: {
85 label: "Who can sign up",
86 env: "FORGE_SIGNUP",
87 kind: { type: "choice", values: ["open", "invite", "closed"] },
88 fallback: "open",
89 help: "open lets anyone make an account; closed makes none, at /signup, in the API or through the platform edge. invite is kept and acts like closed for now. The forge's first account can always be made, and no one already signed in is affected. Takes effect immediately.",
90 },
8391 };
8492
8593 export const CAPACITY_KEYS = Object.keys(CAPACITY) as CapacityKey[];
@@ -191,6 +199,21 @@ export function capacityCount(
191199 return Number.isInteger(n) && n > 0 ? n : fallback;
192200 }
193201
202 /**
203 * Whether a new account may be made now: the forge says open, or has no
204 * account yet (the first one is always let in). `invite` acts as `closed`.
205 * Read on every attempt, so a change needs no restart.
206 */
207 export function signupOpen(db: Database): boolean {
208 return (
209 capacityValue(db, "signup") === "open" ||
210 db.query("SELECT 1 FROM user LIMIT 1").get() === null
211 );
212 }
213
214 /** The one sentence a refused sign-up carries, on every path. */
215 export const SIGNUP_CLOSED_MESSAGE = "Signup is closed on this forge.";
216
194217 /** How many hosted children this forge may hold now; read on every use. */
195218 export function maxChildren(db: Database): number {
196219 return Number(capacityValue(db, "children.max"));
src/core/users.ts +3
@@ -7,6 +7,7 @@ import { markUnproven, markVerified } from "./verify.ts";
77 import type { Database } from "bun:sqlite";
88 import { isSafeName } from "../git/guard.ts";
99 import { noreplyAddress } from "./commit_identity.ts";
10 import { signupOpen } from "./capacity.ts";
1011 import { reservedName } from "./reserved.ts";
1112 import { id } from "../kernel/id.ts";
1213 import { err, ok, type Result } from "../kernel/result.ts";
@@ -333,6 +334,8 @@ export async function ensureEdgeUser(
333334 const existing = getUserByName(db, login);
334335 if (existing)
335336 return existing.kind === "user" && isActive(existing) ? existing : undefined;
337 // A closed forge makes no account on sight; the first one is still let in.
338 if (!signupOpen(db)) return undefined;
336339 // The edge vouches for a login, not for its right to a name: createUser
337340 // refuses a reserved one, so a platform account called after the crew or
338341 // the owner is not let in under it.
src/http/api.ts +33
@@ -22,6 +22,11 @@ import { askCheck } from "../checks/again.ts";
2222 import { mayView, mayViewId, sealedScope } from "../core/sealed.ts";
2323 import { changeCapacity, listCapacity } from "../actions/capacity.ts";
2424 import { changeLimit, listLimits } from "../actions/limits.ts";
25 import {
26 isCapacityKey,
27 SIGNUP_CLOSED_MESSAGE,
28 validCapacity,
29 } from "../core/capacity.ts";
2530 import {
2631 accountSignIns,
2732 endAccountSession,
@@ -1136,6 +1141,8 @@ export function apiRoutes(router: Router<Handler>): void {
11361141 },
11371142 { address: clientAddress(ctx.request) },
11381143 );
1144 if (!created.ok && created.error === "signup_closed")
1145 return apiError("signup_closed", 403, SIGNUP_CLOSED_MESSAGE);
11391146 if (!created.ok && created.error === "passkey_required")
11401147 return apiError("passkey_required", 422, PASSKEY_REQUIRED_MESSAGE);
11411148 if (!created.ok && created.error === "human_check")
@@ -1406,6 +1413,32 @@ export function apiRoutes(router: Router<Handler>): void {
14061413 );
14071414 });
14081415
1416 // Settings by name, several at once: `{"signup": "closed"}`. Every value is
1417 // checked before any is applied, so a bad one changes nothing.
1418 router.add("PATCH", "/api/v1/admin/settings", async (ctx) => {
1419 const denied = accountAdmin(ctx, "admin");
1420 if (denied) return denied;
1421 const input = await body(ctx.request);
1422 const entries = Object.entries(input);
1423 if (entries.length === 0)
1424 return apiError("invalid_value", 422, "no setting named");
1425 for (const [key, value] of entries) {
1426 if (!isCapacityKey(key))
1427 return apiError("no_such_setting", 422, `no such setting: ${key}`);
1428 if (typeof value !== "string" || !validCapacity(key, value.trim()))
1429 return apiError(
1430 "invalid_value",
1431 422,
1432 `that value is outside what ${key} takes`,
1433 );
1434 }
1435 const changed = entries.map(([key, value]) => {
1436 const done = changeCapacity(ctx.app, ctx.auth.user, key, str(value));
1437 return done.ok ? done.value : undefined;
1438 });
1439 return json({ changed: changed.filter((c) => c !== undefined) });
1440 });
1441
14091442 // The forge's limits (`settings/limits.ts`): the same door as capacity.
14101443 router.add("GET", "/api/v1/admin/limits", (ctx) => {
14111444 const denied = accountAdmin(ctx, "ro");
src/http/mcp.ts +2 −2
@@ -2009,13 +2009,13 @@ const TOOLS: readonly Tool[] = [
20092009 {
20102010 name: "capacity",
20112011 description:
2012 "The forge's capacity and guards, live: crew runs at once (crew.concurrency), checks at once (checks.concurrency), test shards per check (checks.shards), whether a cell's undeclared egress is refused or reported (cells.egress), and whether new accounts may create repositories and forks (guard_new_accounts: on refuses accounts younger than 7 days, off is the default). Without `key`, each setting, its value and where it comes from, and the recent changes. With `key` and `value` (\"\" goes back to the boot default), the change it would make; with dryRun false, made, by a forge admin with an admin-scope token, never an agent. A change is honoured by the next run, check or cell, never by a restart. The same as Settings → Capacity and /api/v1/admin/capacity.",
2012 "The forge's capacity and guards, live: crew runs at once (crew.concurrency), checks at once (checks.concurrency), test shards per check (checks.shards), whether a cell's undeclared egress is refused or reported (cells.egress), and whether new accounts may create repositories and forks (guard_new_accounts: on refuses accounts younger than 7 days, off is the default), and who can sign up (signup: open, invite or closed; invite acts as closed for now, the first account is always let in). Without `key`, each setting, its value and where it comes from, and the recent changes. With `key` and `value` (\"\" goes back to the boot default), the change it would make; with dryRun false, made, by a forge admin with an admin-scope token, never an agent. A change is honoured by the next run, check or cell, never by a restart. The same as Settings → Capacity and /api/v1/admin/capacity.",
20132013 inputSchema: {
20142014 type: "object",
20152015 properties: {
20162016 key: {
20172017 type: "string",
2018 enum: ["crew.concurrency", "checks.concurrency", "checks.shards", "cells.egress", "guard_new_accounts"],
2018 enum: ["crew.concurrency", "checks.concurrency", "checks.shards", "cells.egress", "guard_new_accounts", "signup"],
20192019 },
20202020 value: { type: "string", maxLength: 16 },
20212021 dryRun: { type: "boolean", description: "Plan only (the default). Send false to change it." },
src/main.ts +10
@@ -137,6 +137,16 @@ if (lingerMs === null) {
137137 process.exit(1);
138138 }
139139
140 // FORGE_SIGNUP is who may make an account; a wrong word fails the boot rather
141 // than leaving a forge open that was meant to be closed.
142 {
143 const signup = (process.env.FORGE_SIGNUP ?? "").trim();
144 if (signup !== "" && !["open", "invite", "closed"].includes(signup)) {
145 console.error(`FORGE_SIGNUP: "${signup}" is not open, invite or closed`);
146 process.exit(1);
147 }
148 }
149
140150 const trustedProxies = (process.env.FORGE_TRUSTED_PROXIES ?? "")
141151 .split(",")
142152 .map((s) => s.trim())
src/web/pages/site.ts +17
@@ -14,6 +14,7 @@ import { clientAddress } from "../../http/peer.ts";
1414 import { verifyEmail } from "../../actions/verify.ts";
1515 import { STRANGER_MAX } from "../../http/limits.ts";
1616 import { createRepo } from "../../actions/repos.ts";
17 import { SIGNUP_CLOSED_MESSAGE, signupOpen } from "../../core/capacity.ts";
1718 import { HUMAN_CHECK_MESSAGE, PASSKEY_REQUIRED_MESSAGE, signUp } from "../../actions/users.ts";
1819 import { accessAllows, listOrgsForUser, orgAccess } from "../../core/orgs.ts";
1920 import { listPins } from "../../core/pins.ts";
@@ -391,7 +392,21 @@ function siteKey(ctx: Ctx): string | undefined {
391392 return turnstileSecret === undefined ? undefined : turnstileSiteKey;
392393 }
393394
395 function signupClosed(ctx: Ctx): Response {
396 return page(
397 {
398 ctx,
399 title: "Sign up",
400 body: html`<div class="page-head"><h1>Sign up</h1></div>
401 <p id="signup-closed">${SIGNUP_CLOSED_MESSAGE}</p>
402 <p><a href="/signin">Sign in</a></p>`,
403 },
404 403,
405 );
406 }
407
394408 export function signupPage(ctx: Ctx): Response {
409 if (!signupOpen(ctx.app.db)) return signupClosed(ctx);
395410 return page({
396411 ctx,
397412 title: "Sign up",
@@ -507,6 +522,7 @@ export async function signupSubmit(ctx: Ctx): Promise<Response> {
507522 // Posted by people with no account yet: a stranger's form.
508523 const form = await readForm(ctx, undefined, STRANGER_MAX);
509524 if (form instanceof Response) return form;
525 if (!signupOpen(ctx.app.db)) return signupClosed(ctx);
510526 const username = field(form, "username");
511527 const email = field(form, "email");
512528 const created = await signUp(
@@ -530,6 +546,7 @@ export async function signupSubmit(ctx: Ctx): Promise<Response> {
530546 weak_password: { password: "Passwords need at least 10 characters." },
531547 human_check: { human: HUMAN_CHECK_MESSAGE },
532548 passkey_required: { human: PASSKEY_REQUIRED_MESSAGE },
549 signup_closed: { human: SIGNUP_CLOSED_MESSAGE },
533550 }[created.error] ?? { username: "Something went wrong." };
534551 return page(
535552 {
test/signup-closed.test.ts added +160
@@ -0,0 +1,160 @@
1 /**
2 * Who can sign up is one live setting (#1142): open, invite or closed. Closed
3 * (and invite, for now) makes no account on any path — the page, the API, the
4 * platform edge — yet the forge's first account can always be made, and an
5 * admin's existing session never depends on it. A change is live, audited.
6 */
7
8 import { afterAll, beforeAll, describe, expect, test } from "bun:test";
9 import { mkdtemp, rm } from "node:fs/promises";
10 import { tmpdir } from "node:os";
11 import { join } from "node:path";
12 import { changeCapacity } from "../src/actions/capacity.ts";
13 import { createApp, type App } from "../src/app.ts";
14 import { capacityChanges, signupOpen } from "../src/core/capacity.ts";
15 import { createToken } from "../src/core/tokens.ts";
16 import { createUser, getUserByName, type User } from "../src/core/users.ts";
17 import { serve, type Servers } from "../src/http/server.ts";
18
19 const EDGE = "edge-secret-0123456789";
20
21 describe("signup setting", () => {
22 let dir: string;
23 let app: App;
24 let servers: Servers;
25 let owner: User;
26 let adminToken: string;
27
28 const setSignup = (value: string) => changeCapacity(app, owner, "signup", value);
29 const post = (username: string) =>
30 fetch(`${servers.url}/api/v1/users`, {
31 method: "POST",
32 headers: { "content-type": "application/json" },
33 body: JSON.stringify({
34 username,
35 email: `${username}@example.test`,
36 password: "a-good-passphrase",
37 }),
38 });
39 const edge = (login: string) =>
40 fetch(`${servers.url}/api/v1/user`, {
41 headers: { "x-plat-user": login, "x-plat-edge-token": EDGE },
42 });
43
44 beforeAll(async () => {
45 dir = await mkdtemp(join(tmpdir(), "forge-signup-"));
46 app = createApp({ dataDir: dir, port: 0, edgeToken: EDGE });
47 servers = await serve(app);
48 });
49 afterAll(async () => {
50 servers.stop();
51 app.close();
52 await rm(dir, { recursive: true, force: true });
53 });
54
55 test("a fresh forge makes its first account, closed or not", async () => {
56 // Closing needs an admin, so close the store directly on the empty forge.
57 app.db
58 .query(
59 "INSERT INTO forge_setting (key, value, updated_by, updated_at) VALUES ('signup','closed','boot','now')",
60 )
61 .run();
62 expect(signupOpen(app.db)).toBe(true);
63 const res = await post("ada");
64 expect(res.status).toBe(201);
65 owner = getUserByName(app.db, "ada")!;
66 expect(owner.isAdmin).toBe(true);
67 expect(signupOpen(app.db)).toBe(false);
68 adminToken = createToken(app.db, owner.id, "t", "admin").token;
69 });
70
71 test("closed: page, API and edge make no account; sign-in still works", async () => {
72 const page = await fetch(`${servers.url}/signup`);
73 expect(page.status).toBe(403);
74 expect(await page.text()).toContain("Signup is closed on this forge.");
75
76 const api = await post("bob");
77 expect(api.status).toBe(403);
78 expect(((await api.json()) as { message?: string }).message ?? "").toContain("closed");
79
80 const form = await fetch(`${servers.url}/signup`, {
81 method: "POST",
82 headers: {
83 "content-type": "application/x-www-form-urlencoded",
84 origin: servers.url,
85 },
86 body: new URLSearchParams({
87 username: "bob",
88 email: "[email protected]",
89 password: "a-good-passphrase",
90 }),
91 });
92 expect(form.status).toBe(403);
93
94 await edge("carol");
95 expect(getUserByName(app.db, "carol")).toBeUndefined();
96 expect(getUserByName(app.db, "bob")).toBeUndefined();
97
98 // The admin's own edge identity and password session are untouched.
99 const me = await edge("ada");
100 expect(me.status).toBe(200);
101 });
102
103 test("invite acts like closed for now", async () => {
104 expect(setSignup("invite").ok).toBe(true);
105 expect((await post("bob")).status).toBe(403);
106 expect((await fetch(`${servers.url}/signup`)).status).toBe(403);
107 });
108
109 test("a live change by PATCH, with no restart, opens every path", async () => {
110 const res = await fetch(`${servers.url}/api/v1/admin/settings`, {
111 method: "PATCH",
112 headers: {
113 authorization: `Bearer ${adminToken}`,
114 "content-type": "application/json",
115 },
116 body: JSON.stringify({ signup: "open" }),
117 });
118 expect(res.status).toBe(200);
119 expect((await fetch(`${servers.url}/signup`)).status).toBe(200);
120 expect((await post("bob")).status).toBe(201);
121 await edge("carol");
122 expect(getUserByName(app.db, "carol")).toBeDefined();
123 });
124
125 test("a wrong value or key is refused and changes nothing; others are not admin", async () => {
126 const patch = (token: string, body: unknown) =>
127 fetch(`${servers.url}/api/v1/admin/settings`, {
128 method: "PATCH",
129 headers: {
130 authorization: `Bearer ${token}`,
131 "content-type": "application/json",
132 },
133 body: JSON.stringify(body),
134 });
135 expect((await patch(adminToken, { signup: "sometimes" })).status).toBe(422);
136 expect((await patch(adminToken, { nope: "x" })).status).toBe(422);
137 expect(changeCapacity(app, owner, "signup", "sometimes").ok).toBe(false);
138 const bob = getUserByName(app.db, "bob")!;
139 const bobToken = createToken(app.db, bob.id, "t", "admin").token;
140 expect((await patch(bobToken, { signup: "closed" })).status).toBe(404);
141 expect(signupOpen(app.db)).toBe(true);
142 });
143
144 test("every change is kept with who and when", () => {
145 setSignup("closed");
146 const last = capacityChanges(app.db).find((c) => c.key === "signup")!;
147 expect(last.to).toBe("closed");
148 expect(last.actorName).toBe("ada");
149 expect(last.at).toMatch(/^\d{4}-/);
150 });
151
152 test("createUser still makes accounts directly (the owner's own paths)", async () => {
153 const made = await createUser(app.db, {
154 username: "dan",
155 email: "[email protected]",
156 password: "a-good-passphrase",
157 });
158 expect(made.ok).toBe(true);
159 });
160 });

↑↓ navigate ↵ open ⌘↵ its app esc close

Keyboard shortcuts

Docs