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

Invite links: an admin mints a single-use, expiring link, and a forge set to invite signs people up only through one #2320

Parked opened this
Closed without merging

scout/forge:scout/1143-invite-links-an-admin-mints-a-single-use → main 1 commit fork

  • Closed without merging. Nothing was applied to main.

Review

Sign in to review this change.
18 files changed +794 −35
README.md +3 −1

Diff not shown — a line 4,879 characters wide (limit 2,000). +3 −1

View file
src/actions/invites.ts added +63
@@ -0,0 +1,63 @@
1 /**
2 * Invite links (`core/invites.ts`), for a forge admin who is a person.
3 * Everyone else, an agent included, is told `not_found`. Minting and
4 * revoking go to the event outbox; using one is recorded by `signUp`.
5 */
6
7 import type { App } from "../app.ts";
8 import {
9 listInvites,
10 mintInvite,
11 parseDays,
12 revokeInvite,
13 type Invite,
14 } from "../core/invites.ts";
15 import type { User } from "../core/users.ts";
16 import { err, ok, type Result } from "../kernel/result.ts";
17
18 export type InviteError = "not_found" | "invalid_days";
19
20 function admin(actor: User | undefined): Result<User, "not_found"> {
21 return actor?.isAdmin === true && actor.kind !== "agent" ? ok(actor) : err("not_found");
22 }
23
24 export function readInvites(app: App, actor: User | undefined): Result<Invite[], "not_found"> {
25 const who = admin(actor);
26 return who.ok ? ok(listInvites(app.db)) : who;
27 }
28
29 /** Mint a link; the token is in the result and nowhere else. */
30 export function createInvite(
31 app: App,
32 actor: User | undefined,
33 rawDays: unknown,
34 ): Result<{ invite: Invite; token: string; path: string }, InviteError> {
35 const who = admin(actor);
36 if (!who.ok) return who;
37 const days = parseDays(rawDays);
38 if (!days.ok) return days;
39 const minted = mintInvite(app.db, who.value.id, days.value);
40 app.bus.append({
41 kind: "invite.created",
42 actorId: who.value.id,
43 payload: { inviteId: minted.invite.id, expiresAt: minted.invite.expiresAt },
44 });
45 return ok({ ...minted, path: invitePath(minted.token) });
46 }
47
48 export function removeInvite(
49 app: App,
50 actor: User | undefined,
51 inviteId: string,
52 ): Result<void, "not_found"> {
53 const who = admin(actor);
54 if (!who.ok) return who;
55 if (!revokeInvite(app.db, inviteId)) return err("not_found");
56 app.bus.append({ kind: "invite.revoked", actorId: who.value.id, payload: { inviteId } });
57 return ok();
58 }
59
60 /** Where the link lands; the page there posts the token, so it leaves the URL. */
61 export function invitePath(token: string): string {
62 return `/invite/${token}`;
63 }
src/actions/users.ts +68 −12
@@ -35,7 +35,8 @@ import {
3535 type User,
3636 } from "../core/users.ts";
3737 import { err, ok, type Result } from "../kernel/result.ts";
38 import { getSignup } from "../settings/signup.ts";
38 import { claimInvite, markInviteUsed, releaseInvite } from "../core/invites.ts";
39 import { getSignup, type SignupMode } from "../settings/signup.ts";
3940 import { requireUser } from "./access.ts";
4041
4142 export interface SignUpInput {
@@ -44,25 +45,62 @@ export interface SignUpInput {
4445 password: string;
4546 /** The Turnstile token the browser's widget gave; read only when a secret is set. */
4647 humanToken?: string;
48 /** The invite token, read only when the forge signs people up by invitation. */
49 invite?: string;
4750 }
4851
4952 export type SignUpError =
5053 | CreateUserError
5154 | "human_check"
5255 | "passkey_required"
53 | "signup_closed";
56 | "signup_closed"
57 | "invite_required";
58
59 /** What anyone is told when an invite is missing, used, expired, revoked or never was. */
60 export const INVITE_REQUIRED_MESSAGE =
61 "Signing up on this forge needs a valid invite link.";
5462
5563 /** What anyone is told when the forge makes no new accounts. */
5664 export const SIGNUP_CLOSED_MESSAGE = "Signup is closed on this forge.";
5765
5866 /**
59 * Whether no new account may be made now. Read from the store on every call,
60 * so a change takes effect on the next request. `invite` acts as closed until
61 * invitations exist (#1143). The forge's first account is never refused: the
62 * owner cannot be locked out of a fresh forge by a setting.
67 * Who may make an account now. Read from the store on every call, so a change
68 * takes effect on the next request. The forge's first account is never
69 * refused: the owner cannot be locked out of a fresh forge by a setting.
70 */
71 export function signupMode(app: App): SignupMode {
72 return hasAnyUser(app.db) ? getSignup(app.db) : "open";
73 }
74
75 /**
76 * Whether the doors that cannot take an invite (the platform edge) make no
77 * account now: closed, and `invite` too, since the edge carries no link.
6378 */
6479 export function signupClosed(app: App): boolean {
65 return getSignup(app.db) !== "open" && hasAnyUser(app.db);
80 return signupMode(app) !== "open";
81 }
82
83 /**
84 * Let a sign-up through its gate: `closed` refuses; `invite` claims the link
85 * (once, atomically) or refuses with one sentence; `open` needs nothing.
86 * `claimed` is the link to give back if the account is not made.
87 */
88 function gate(
89 app: App,
90 invite: string | undefined,
91 ): Result<{ claimed: string | undefined }, "signup_closed" | "invite_required"> {
92 const mode = signupMode(app);
93 if (mode === "closed") return err("signup_closed");
94 if (mode === "open") return ok({ claimed: undefined });
95 const claimed = claimInvite(app.db, invite ?? "");
96 return claimed.ok ? ok({ claimed: claimed.value }) : err("invite_required");
97 }
98
99 /** Record the link's use once the account exists. */
100 function usedInvite(app: App, claimed: string | undefined, user: User): void {
101 if (claimed === undefined) return;
102 markInviteUsed(app.db, claimed, user.id);
103 app.bus.append({ kind: "invite.used", actorId: user.id, payload: { inviteId: claimed } });
66104 }
67105
68106 /** What anyone is told at a door that still offers a password-only sign-up. */
@@ -102,7 +140,7 @@ export async function signUp(
102140 // when every such account has a passkey (Settings → Passkeys shows who is
103141 // left) and recovery without a password exists (#1618): then delete this
104142 // action's password path, `verifyPassword`'s doors and the password column.
105 if (signupClosed(app)) return err("signup_closed");
143 if (signupMode(app) === "closed") return err("signup_closed");
106144 if (app.config.passkeyOnlySignup === true) return err("passkey_required");
107145 const secret = app.config.turnstileSecret;
108146 const bootstrap = from.door === "terminal" && !hasAnyUser(app.db);
@@ -112,9 +150,15 @@ export async function signUp(
112150 if (!(await verify(input.humanToken ?? "", from.address)))
113151 return err("human_check");
114152 }
115 const { humanToken: _token, ...account } = input;
153 const passed = gate(app, input.invite);
154 if (!passed.ok) return passed;
155 const { humanToken: _token, invite: _invite, ...account } = input;
116156 const created = await createUser(app.db, { ...account, adminIfFirst: true });
117 if (!created.ok) return created;
157 if (!created.ok) {
158 if (passed.value.claimed !== undefined) releaseInvite(app.db, passed.value.claimed);
159 return created;
160 }
161 usedInvite(app, passed.value.claimed, created.value);
118162 app.bus.append({
119163 kind: "user.created",
120164 actorId: created.value.id,
@@ -136,6 +180,7 @@ export interface PasskeySignUpInput {
136180 passkey: Credential;
137181 passkeyName: string;
138182 humanToken?: string;
183 invite?: string;
139184 }
140185
141186 /**
@@ -150,7 +195,7 @@ export async function signUpWithPasskey(
150195 input: PasskeySignUpInput,
151196 from: { address?: string | undefined } = {},
152197 ): Promise<Result<User, SignUpError | "passkey_taken">> {
153 if (signupClosed(app)) return err("signup_closed");
198 if (signupMode(app) === "closed") return err("signup_closed");
154199 const secret = app.config.turnstileSecret;
155200 if (secret !== undefined) {
156201 const verify = app.config.verifyHuman ?? turnstileVerifier(secret);
@@ -158,17 +203,28 @@ export async function signUpWithPasskey(
158203 return err("human_check");
159204 }
160205 if (findPasskey(app.db, input.passkey.id)) return err("passkey_taken");
206 const passed = gate(app, input.invite);
207 if (!passed.ok) return passed;
208 const { claimed } = passed.value;
209 const giveBack = () => {
210 if (claimed !== undefined) releaseInvite(app.db, claimed);
211 };
161212 const created = await createUser(app.db, {
162213 username: input.username,
163214 email: input.email,
164215 adminIfFirst: true,
165216 });
166 if (!created.ok) return created;
217 if (!created.ok) {
218 giveBack();
219 return created;
220 }
167221 const kept = addPasskey(app.db, created.value.id, input.passkeyName, input.passkey);
168222 if (!kept.ok) {
169223 discardFreshUser(app.db, created.value.id);
224 giveBack();
170225 return err("passkey_taken");
171226 }
227 usedInvite(app, claimed, created.value);
172228 app.bus.append({
173229 kind: "user.created",
174230 actorId: created.value.id,
src/core/invites.ts added +146
@@ -0,0 +1,146 @@
1 /**
2 * Invite links (#1143): a forge admin mints one, it makes one account, and it
3 * stops working after `days` or when revoked. The token is shown once; only
4 * its hash is stored. Every way a token can fail is the same `invalid_invite`,
5 * so a refusal never says whether the token ever existed.
6 */
7
8 import type { Database } from "bun:sqlite";
9 import { sha256 } from "../kernel/hash.ts";
10 import { id, secret } from "../kernel/id.ts";
11 import { err, ok, type Result } from "../kernel/result.ts";
12
13 export const INVITE_DEFAULT_DAYS = 7;
14 export const INVITE_MAX_DAYS = 30;
15 const DAY_MS = 86_400_000;
16
17 export interface Invite {
18 readonly id: string;
19 readonly createdBy: string;
20 readonly createdAt: string;
21 readonly expiresAt: string;
22 readonly usedAt: string | null;
23 readonly usedBy: string | null;
24 readonly revokedAt: string | null;
25 readonly status: "open" | "used" | "revoked" | "expired";
26 }
27
28 interface Row {
29 id: string;
30 created_by: string;
31 created_at: string;
32 expires_at: string;
33 used_at: string | null;
34 used_by: string | null;
35 revoked_at: string | null;
36 }
37
38 /** Days from untrusted input: unset is the default, else a whole number 1 to 30. */
39 export function parseDays(raw: unknown): Result<number, "invalid_days"> {
40 if (raw === undefined || raw === null || raw === "") return ok(INVITE_DEFAULT_DAYS);
41 const n = typeof raw === "string" && /^\d{1,3}$/.test(raw) ? Number(raw) : raw;
42 return typeof n === "number" && Number.isInteger(n) && n >= 1 && n <= INVITE_MAX_DAYS
43 ? ok(n)
44 : err("invalid_days");
45 }
46
47 function shape(r: Row, now: string): Invite {
48 const status =
49 r.used_at !== null ? "used" : r.revoked_at !== null ? "revoked" : r.expires_at <= now ? "expired" : "open";
50 return {
51 id: r.id,
52 createdBy: r.created_by,
53 createdAt: r.created_at,
54 expiresAt: r.expires_at,
55 usedAt: r.used_at,
56 usedBy: r.used_by,
57 revokedAt: r.revoked_at,
58 status,
59 };
60 }
61
62 /** Mint a link; the token comes back this once. */
63 export function mintInvite(
64 db: Database,
65 createdBy: string,
66 days: number,
67 now: Date = new Date(),
68 ): { invite: Invite; token: string } {
69 const token = secret();
70 const inviteId = id();
71 const row: Row = {
72 id: inviteId,
73 created_by: createdBy,
74 created_at: now.toISOString(),
75 expires_at: new Date(now.getTime() + days * DAY_MS).toISOString(),
76 used_at: null,
77 used_by: null,
78 revoked_at: null,
79 };
80 db.query(
81 `INSERT INTO invite (id, token_hash, created_by, created_at, expires_at) VALUES (?1, ?2, ?3, ?4, ?5)`,
82 ).run(row.id, sha256(token), row.created_by, row.created_at, row.expires_at);
83 return { invite: shape(row, row.created_at), token };
84 }
85
86 /**
87 * Use up a link: true for exactly one caller, once, while it is unused,
88 * unrevoked and unexpired. One statement, so two requests cannot both win.
89 */
90 export function claimInvite(
91 db: Database,
92 token: string,
93 now: Date = new Date(),
94 ): Result<string, "invalid_invite"> {
95 if (token === "" || token.length > 200) return err("invalid_invite");
96 const at = now.toISOString();
97 const row = db
98 .query<{ id: string }, [string, string]>(
99 `UPDATE invite SET used_at = ?2
100 WHERE token_hash = ?1 AND used_at IS NULL AND revoked_at IS NULL AND expires_at > ?2
101 RETURNING id`,
102 )
103 .get(sha256(token), at);
104 return row === null ? err("invalid_invite") : ok(row.id);
105 }
106
107 /** Whether a link would be accepted now, without using it. */
108 export function inviteValid(db: Database, token: string, now: Date = new Date()): boolean {
109 if (token === "" || token.length > 200) return false;
110 return (
111 db
112 .query<{ n: number }, [string, string]>(
113 `SELECT 1 AS n FROM invite
114 WHERE token_hash = ?1 AND used_at IS NULL AND revoked_at IS NULL AND expires_at > ?2`,
115 )
116 .get(sha256(token), now.toISOString()) !== null
117 );
118 }
119
120 /** Give a claimed link back: the account it was for was not made. */
121 export function releaseInvite(db: Database, inviteId: string): void {
122 db.query("UPDATE invite SET used_at = NULL WHERE id = ?1 AND used_by IS NULL").run(inviteId);
123 }
124
125 /** Record which account a claimed link made. */
126 export function markInviteUsed(db: Database, inviteId: string, userId: string): void {
127 db.query("UPDATE invite SET used_by = ?2 WHERE id = ?1").run(inviteId, userId);
128 }
129
130 /** Revoke an unused link; false when there is no such open link. */
131 export function revokeInvite(db: Database, inviteId: string, now: Date = new Date()): boolean {
132 return (
133 db
134 .query("UPDATE invite SET revoked_at = ?2 WHERE id = ?1 AND used_at IS NULL AND revoked_at IS NULL")
135 .run(inviteId, now.toISOString()).changes > 0
136 );
137 }
138
139 /** The most recent links, newest first. */
140 export function listInvites(db: Database, limit = 50, now: Date = new Date()): Invite[] {
141 const at = now.toISOString();
142 return db
143 .query<Row, [number]>("SELECT * FROM invite ORDER BY id DESC LIMIT ?1")
144 .all(Math.trunc(limit))
145 .map((r) => shape(r, at));
146 }
src/core/migrations/20261017090000-invites.ts added +15
@@ -0,0 +1,15 @@
1 // An invite link (#1143): one row per link a forge admin minted. Only the
2 // hash of the token is kept. A link works once (`used_at`), until it expires
3 // (`expires_at`), unless revoked (`revoked_at`). `used_by` is the account it made.
4 export default `
5 CREATE TABLE invite (
6 id TEXT PRIMARY KEY,
7 token_hash TEXT NOT NULL UNIQUE,
8 created_by TEXT NOT NULL,
9 created_at TEXT NOT NULL,
10 expires_at TEXT NOT NULL,
11 used_at TEXT,
12 used_by TEXT,
13 revoked_at TEXT
14 ) WITHOUT ROWID;
15 `;
src/http/api.ts +38
@@ -25,6 +25,7 @@ import { mayView, mayViewId, sealedScope } from "../core/sealed.ts";
2525 import { changeCapacity, listCapacity } from "../actions/capacity.ts";
2626 import { changeLimit, listLimits } from "../actions/limits.ts";
2727 import { changeQuotas, readQuotas } from "../actions/quotas.ts";
28 import { createInvite, readInvites, removeInvite } from "../actions/invites.ts";
2829 import { changeSignup, readSignup } from "../actions/signup.ts";
2930 import {
3031 accountSignIns,
@@ -154,6 +155,7 @@ import {
154155 HUMAN_CHECK_MESSAGE,
155156 PASSKEY_REQUIRED_MESSAGE,
156157 signUp,
158 INVITE_REQUIRED_MESSAGE,
157159 SIGNUP_CLOSED_MESSAGE,
158160 updateProfile,
159161 } from "../actions/users.ts";
@@ -1201,9 +1203,12 @@ export function apiRoutes(router: Router<Handler>): void {
12011203 email: str(input.email),
12021204 password: str(input.password),
12031205 humanToken: str(input.turnstile_token),
1206 invite: str(input.invite),
12041207 },
12051208 { address: clientAddress(ctx.request) },
12061209 );
1210 if (!created.ok && created.error === "invite_required")
1211 return apiError("invite_required", 403, INVITE_REQUIRED_MESSAGE);
12071212 if (!created.ok && created.error === "signup_closed")
12081213 return apiError("signup_closed", 403, SIGNUP_CLOSED_MESSAGE);
12091214 if (!created.ok && created.error === "passkey_required")
@@ -1526,6 +1531,39 @@ export function apiRoutes(router: Router<Handler>): void {
15261531 );
15271532 });
15281533
1534 // Invite links (`core/invites.ts`): a forge admin who is a person. The token
1535 // is in the answer to the POST and nowhere else.
1536 router.add("GET", "/api/v1/admin/invites", (ctx) => {
1537 const denied = accountAdmin(ctx, "ro");
1538 if (denied) return denied;
1539 const read = readInvites(ctx.app, ctx.auth.user);
1540 return read.ok ? json({ invites: read.value }) : notFound();
1541 });
1542
1543 router.add("POST", "/api/v1/admin/invites", async (ctx) => {
1544 const denied = accountAdmin(ctx, "admin");
1545 if (denied) return denied;
1546 const input = await body(ctx.request);
1547 const made = createInvite(ctx.app, ctx.auth.user, input.days);
1548 if (!made.ok)
1549 return made.error === "not_found"
1550 ? notFound()
1551 : apiError("invalid_days", 422, "days is a whole number from 1 to 30");
1552 const base = (ctx.app.config.url ?? ctx.url.origin).replace(/\/$/, "");
1553 return json(
1554 { ...made.value.invite, token: made.value.token, url: `${base}${made.value.path}` },
1555 201,
1556 { "cache-control": "no-store" },
1557 );
1558 });
1559
1560 router.add("DELETE", "/api/v1/admin/invites/:id", (ctx) => {
1561 const denied = accountAdmin(ctx, "admin");
1562 if (denied) return denied;
1563 const removed = removeInvite(ctx.app, ctx.auth.user, ctx.params.id!);
1564 return removed.ok ? json({ revoked: ctx.params.id }) : notFound();
1565 });
1566
15291567 // Per-account quotas (`core/quotas.ts`): null is no limit. Nothing
15301568 // enforces them yet.
15311569 router.add("GET", "/api/v1/admin/settings", (ctx) => {
src/http/mcp.ts +41 −1
@@ -27,6 +27,7 @@ import { usesByVendor, type VendorUse } from "../cloud/declared.ts";
2727 import { cloudOverview } from "../cloud/overview.ts";
2828 import { PROVIDERS } from "../cloud/providers.ts";
2929 import { changeQuotas, readQuotas } from "../actions/quotas.ts";
30 import { createInvite, readInvites, removeInvite } from "../actions/invites.ts";
3031 import { changeSignup, readSignup } from "../actions/signup.ts";
3132 import { SIGNUP_MODES } from "../settings/signup.ts";
3233 import { QUOTA_KEYS } from "../settings/quotas.ts";
@@ -2496,7 +2497,7 @@ const TOOLS: readonly Tool[] = [
24962497 {
24972498 name: "signup",
24982499 description:
2499 "Who may sign up: open, invite or closed (default open). Nothing reads it yet. Without `mode`, the setting and the recent changes. With `mode`, the change it would make; with dryRun false, made, by a forge admin with an admin-scope token, never an agent. The same as /admin/limits (Signup) and PATCH /api/v1/admin/settings.",
2500 "Who may sign up: open, invite or closed (a new forge starts on invite). Without `mode`, the setting and the recent changes. With `mode`, the change it would make; with dryRun false, made, by a forge admin with an admin-scope token, never an agent. The same as /admin/limits (Signup) and PATCH /api/v1/admin/settings.",
25002501 inputSchema: {
25012502 type: "object",
25022503 properties: {
@@ -2526,6 +2527,45 @@ const TOOLS: readonly Tool[] = [
25262527 });
25272528 },
25282529 },
2530 {
2531 name: "invites",
2532 description:
2533 "Invite links, for a forge admin who is a person (an agent is refused). Without `action`, the links and their status. `action: \"mint\"` makes a single-use link that expires in `days` (1 to 30, default 7); `action: \"revoke\"` with `id` revokes an open one. Changes need dryRun false and an admin-scope token. A minted token is shown once. The same as /admin/limits (Invite links) and /api/v1/admin/invites.",
2534 inputSchema: {
2535 type: "object",
2536 properties: {
2537 action: { type: "string", enum: ["mint", "revoke"] },
2538 days: { type: "integer", minimum: 1, maximum: 30 },
2539 id: { type: "string", maxLength: 40 },
2540 dryRun: { type: "boolean", description: "Plan only (the default). Send false to change it." },
2541 },
2542 },
2543 writes: true,
2544 dryByDefault: true,
2545 run(ctx, user, args) {
2546 const read = readInvites(ctx.app, user);
2547 if (!read.ok) return bad("not_found", "no such tool here");
2548 const action = args["action"];
2549 if (action === undefined) return good({ invites: read.value });
2550 if (action !== "mint" && action !== "revoke") return bad("invalid_action", "action is mint or revoke");
2551 if (args["dryRun"] !== false)
2552 return good({ says: `Would ${action} an invite. Send dryRun: false to do it.` });
2553 if (!scopeAllows(ctx.auth.scope ?? "ro", "admin"))
2554 return bad("forbidden", "invite links need an admin-scope token");
2555 if (action === "mint") {
2556 const made = createInvite(ctx.app, user, args["days"]);
2557 if (!made.ok) return bad(made.error, "days is a whole number from 1 to 30");
2558 const base = (ctx.app.config.url ?? ctx.url.origin).replace(/\/$/, "");
2559 return good({
2560 says: `Invite ${made.value.invite.id} expires ${made.value.invite.expiresAt}. The link is shown once.`,
2561 url: `${base}${made.value.path}`,
2562 invite: made.value.invite,
2563 });
2564 }
2565 const removed = removeInvite(ctx.app, user, typeof args["id"] === "string" ? args["id"] : "");
2566 return removed.ok ? good({ says: "Invite revoked." }) : bad("not_found", "no such open invite");
2567 },
2568 },
25292569 {
25302570 name: "boards",
25312571 description:
src/http/server.ts +6 −1
@@ -5,6 +5,7 @@
55 * verdict. Auth is resolved once per request and handed to handlers as data.
66 */
77
8 import { inviteAccept, invitePage } from "../web/pages/invite.ts";
89 import { signupOptions, signupPasskey } from "../web/pages/signup-passkey.ts";
910 import { toolbarComment, toolbarPage } from "../web/studio/toolbar.ts";
1011 import { TOOLBAR_NAME, toolbarResponse } from "../apps/toolbar.ts";
@@ -20,7 +21,7 @@ import { flagsPage, flagsSet } from "../web/pages/flags.ts";
2021 import { usagePage } from "../web/pages/usage.ts";
2122 import { domainsPage } from "../web/pages/domains.ts";
2223 import { resiliencePage } from "../web/pages/resilience.ts";
23 import { limitsPage, limitsSet, quotasSet, signupSet } from "../web/pages/admin-limits.ts";
24 import { inviteMake, inviteRevoke, limitsPage, limitsSet, quotasSet, signupSet } from "../web/pages/admin-limits.ts";
2425 import { boardsPage } from "../web/pages/boards.ts";
2526 import { boardNew, boardPin, boardPost } from "../web/pages/boards-edit.ts";
2627 import { boardLive, boardShow, boardsList } from "../web/pages/boards-view.ts";
@@ -644,6 +645,8 @@ export function buildRouter(): Router<Handler> {
644645 router.add("GET", "/signin/parent", parentStart);
645646 router.add("GET", "/signin/parent/callback", parentCallback);
646647 router.add("GET", "/signup", signupPage);
648 router.add("GET", "/invite/:token", invitePage);
649 router.add("POST", "/invite", inviteAccept);
647650 router.add("GET", "/verify", verifyPage);
648651 router.add("POST", "/signup", signupSubmit);
649652 router.add("POST", "/logout", logoutSubmit);
@@ -795,6 +798,8 @@ export function buildRouter(): Router<Handler> {
795798 router.add("POST", "/admin/limits", limitsSet);
796799 router.add("POST", "/admin/quotas", quotasSet);
797800 router.add("POST", "/admin/signup", signupSet);
801 router.add("POST", "/admin/invites", inviteMake);
802 router.add("POST", "/admin/invites/revoke", inviteRevoke);
798803 router.add("GET", "/settings/backups", backupsPage);
799804 router.add("POST", "/settings/backups/now", backupsNow);
800805 router.add("POST", "/settings/backups/drill", backupsDrill);
src/main.ts +3 −1
@@ -4,7 +4,7 @@
44 * environment-only — a handful of variables, all with sane defaults.
55 */
66
7 import { BOOT_ACTOR, setSignup, signupFromEnv } from "./settings/signup.ts";
7 import { BOOT_ACTOR, setSignup, signupDefaultForNewForge, signupFromEnv } from "./settings/signup.ts";
88 import { startMemorySampler } from "./boards/memory.ts";
99 import { startSampler } from "./boards/sampler.ts";
1010 import { sweepStanding } from "./crew/standing.ts";
@@ -244,6 +244,8 @@ const app = createApp({
244244 });
245245
246246 loadFlags(app.db);
247 // A forge with no accounts and no choice yet starts on invite; one that has either keeps it.
248 signupDefaultForNewForge(app.db);
247249 // FORGE_SIGNUP (checked in configProblem) sets who may sign up; kept like any change.
248250 const bootSignup = signupFromEnv(process.env.FORGE_SIGNUP);
249251 if (bootSignup.ok && bootSignup.value !== null)
src/settings/signup.ts +13 −1
@@ -3,7 +3,9 @@
33 * `forge_setting` under `signup`, and every change is kept in
44 * `forge_setting_change` (who, when, from what to what). Default `open`.
55 * `/signup`, `POST /api/v1/users`, passkey signup and a first edge sign-in ask
6 * it (`signupClosed` in `actions/users.ts`); `invite` acts as closed until #1143.
6 * it (`signupMode` in `actions/users.ts`); `invite` needs a link (`core/invites.ts`).
7 * The stored default is `open`, which a forge older than invites keeps; a new
8 * forge is written `invite` at its first boot (`signupDefaultForNewForge`).
79 */
810
911 import type { Database } from "bun:sqlite";
@@ -42,6 +44,16 @@ export function setSignup(db: Database, value: SignupMode, actorId: string): voi
4244 writeSetting(db, STORE_KEY, value, from, value, actorId);
4345 }
4446
47 /**
48 * A forge with no accounts and no stored choice starts on `invite`; a forge
49 * that has accounts or has chosen keeps what it has. Call at boot.
50 */
51 export function signupDefaultForNewForge(db: Database): void {
52 const chosen = db.query("SELECT 1 FROM forge_setting WHERE key = ?1").get(STORE_KEY) !== null;
53 const anyone = db.query("SELECT 1 FROM user LIMIT 1").get() !== null;
54 if (!chosen && !anyone) writeSetting(db, STORE_KEY, "invite", SIGNUP_DEFAULT, "invite", BOOT_ACTOR);
55 }
56
4557 /** `FORGE_SIGNUP` from the environment: unset is no opinion, a bad value is a message. */
4658 export function signupFromEnv(raw: string | undefined): Result<SignupMode | null, string> {
4759 const s = (raw ?? "").trim();
src/tui/screens/common.ts +1
@@ -816,6 +816,7 @@ export function slug(path: string): string {
816816 const MESSAGES: Record<string, string> = {
817817 not_found: "not found",
818818 signup_closed: SIGNUP_CLOSED_MESSAGE,
819 invite_required: "signing up here needs an invite link: open it in a browser",
819820 human_check: "we could not tell you are a person; sign up on the web page",
820821 passkey_required: "new accounts sign up with a passkey and an email address: open the sign-up page in a browser",
821822 unauthorized: "sign in first",
src/web/pages/admin-limits.ts +79 −3
@@ -7,7 +7,9 @@
77
88 import { changeLimit, listLimits } from "../../actions/limits.ts";
99 import { changeQuotas, readQuotas } from "../../actions/quotas.ts";
10 import { createInvite, readInvites, removeInvite } from "../../actions/invites.ts";
1011 import { changeSignup, readSignup } from "../../actions/signup.ts";
12 import { INVITE_DEFAULT_DAYS, INVITE_MAX_DAYS } from "../../core/invites.ts";
1113 import { SIGNUP_MODES } from "../../settings/signup.ts";
1214 import { QUOTA_KEYS } from "../../settings/quotas.ts";
1315 import type { Ctx } from "../../http/context.ts";
@@ -19,7 +21,7 @@ import { btn, card, icon, row, time } from "../ui.ts";
1921 import { accountSections } from "./origins.ts";
2022
2123 // GET /admin/limits
22 export function limitsPage(ctx: Ctx): Response {
24 export function limitsPage(ctx: Ctx, minted?: string): Response {
2325 const listed = listLimits(ctx.app, ctx.auth.user);
2426 if (!listed.ok) return notFoundPage(ctx);
2527 const { limits, changes } = listed.value;
@@ -128,7 +130,8 @@ export function limitsPage(ctx: Ctx): Response {
128130 const signupCard = card(
129131 html`<div class="card-body">
130132 <p class="muted small">
131 Who may sign up: open, invite or closed. Nothing reads this yet.
133 Who may sign up: open, invite (only with a link from below) or closed.
134 A new forge starts on invite.
132135 </p>
133136 <form class="row-actions" method="post" action="/admin/signup">
134137 <label class="small">signup
@@ -150,7 +153,46 @@ export function limitsPage(ctx: Ctx): Response {
150153 pad: false,
151154 },
152155 );
153 const body = html`${signupCard}${quotaCard}${card(
156 const invites = readInvites(ctx.app, ctx.auth.user);
157 const inviteRows = (invites.ok ? invites.value : []).map((i) =>
158 row({
159 lead: icon("history"),
160 title: html`<span class="mono">${i.id}</span> · ${i.status}`,
161 meta: html`Expires ${time(i.expiresAt)}`,
162 trail:
163 i.status === "open"
164 ? html`<form class="row-actions" method="post" action="/admin/invites/revoke">
165 <input type="hidden" name="id" value="${i.id}" />
166 ${btn("Revoke", { size: "sm", label: `Revoke invite ${i.id}` })}
167 </form>`
168 : html``,
169 }),
170 );
171 const inviteCard = card(
172 html`<div class="card-body">
173 <p class="muted small">
174 An invite link makes one account, once, and stops working after
175 the days you choose. Only a hash of it is kept, so it is shown
176 here just once.
177 </p>
178 ${when(
179 minted,
180 (link) => html`<p class="mb">Copy it now: <input class="input mono" readonly size="60" value="${link}" aria-label="Invite link" /></p>`,
181 )}
182 <form class="row-actions" method="post" action="/admin/invites">
183 <label class="small">days
184 <input class="input mono" type="number" name="days" min="1" max="${String(INVITE_MAX_DAYS)}" step="1" value="${String(INVITE_DEFAULT_DAYS)}" /></label>
185 ${btn("Make a link", { size: "sm", variant: "primary", label: "Make an invite link" })}
186 </form>
187 </div>
188 ${when(inviteRows.length > 0, () => html`<ul class="list">${inviteRows}</ul>`)}`,
189 {
190 head: html`${icon("activity")}
191 <h2>Invite links</h2>`,
192 pad: false,
193 },
194 );
195 const body = html`${signupCard}${inviteCard}${quotaCard}${card(
154196 html`<div class="card-body">
155197 <p class="muted small">
156198 Every limit you can hit, and why it is there. A change governs
@@ -266,3 +308,37 @@ export async function signupSet(ctx: Ctx): Promise<Response> {
266308 : { tone: "danger", message: "Signup is open, invite or closed." },
267309 );
268310 }
311
312 // POST /admin/invites — the link is shown on the page this answers, never stored.
313 export async function inviteMake(ctx: Ctx): Promise<Response> {
314 if (ctx.auth.user?.isAdmin !== true || ctx.auth.user.kind === "agent")
315 return notFoundPage(ctx);
316 const form = await readForm(ctx, "admin");
317 if (form instanceof Response) return form;
318 const made = createInvite(ctx.app, ctx.auth.user, field(form, "days"));
319 if (!made.ok && made.error === "not_found") return notFoundPage(ctx);
320 if (!made.ok)
321 return flashTo(ctx, "/admin/limits", {
322 tone: "danger",
323 message: `Days are a whole number from 1 to ${INVITE_MAX_DAYS}.`,
324 });
325 const res = limitsPage(ctx, `${(ctx.app.config.url ?? ctx.url.origin).replace(/\/$/, "")}${made.value.path}`);
326 res.headers.set("cache-control", "no-store");
327 return res;
328 }
329
330 // POST /admin/invites/revoke
331 export async function inviteRevoke(ctx: Ctx): Promise<Response> {
332 if (ctx.auth.user?.isAdmin !== true || ctx.auth.user.kind === "agent")
333 return notFoundPage(ctx);
334 const form = await readForm(ctx, "admin");
335 if (form instanceof Response) return form;
336 const removed = removeInvite(ctx.app, ctx.auth.user, field(form, "id"));
337 return flashTo(
338 ctx,
339 "/admin/limits",
340 removed.ok
341 ? { message: "Invite revoked." }
342 : { tone: "danger", message: "There is no such open invite." },
343 );
344 }
src/web/pages/invite.ts added +62
@@ -0,0 +1,62 @@
1 /**
2 * Landing on an invite link (#1143). The token is in the URL only once: the
3 * page at `/invite/:token` shows a button, and the POST behind it moves the
4 * token into a short-lived HttpOnly cookie scoped to `/signup` and sends the
5 * person on to sign up. So the token is not in the address they sign up from,
6 * not in a Referer, and the page never says whether the token is any good —
7 * the refusal comes at sign-up, in one sentence, the same for every failure.
8 */
9
10 import { cookieValue, type Ctx } from "../../http/context.ts";
11 import { field, readForm } from "../form.ts";
12 import { html } from "../html.ts";
13 import { page, redirect } from "../layout.ts";
14 import { btn } from "../ui.ts";
15
16 const COOKIE = "forge_invite";
17 const KEPT_SECONDS = 3600;
18
19 function cookie(ctx: Ctx, value: string, seconds: number): string {
20 const secure =
21 ctx.url.protocol === "https:" || ctx.app.config.url?.startsWith("https://") ? "; Secure" : "";
22 return `${COOKIE}=${value}; Path=/signup; HttpOnly; SameSite=Lax; Max-Age=${seconds}${secure}`;
23 }
24
25 /** The invite token this browser holds, or "" — never validated here. */
26 export function inviteHeld(ctx: Ctx): string {
27 const held = cookieValue(ctx.request, COOKIE) ?? "";
28 return /^[A-Za-z0-9_-]{1,200}$/.test(held) ? held : "";
29 }
30
31 /** The Set-Cookie that forgets the token, once it is used. */
32 export function inviteForgotten(ctx: Ctx): string {
33 return cookie(ctx, "", 0);
34 }
35
36 // GET /invite/:token — a button; nothing here depends on the token.
37 export function invitePage(ctx: Ctx): Response {
38 const token = ctx.params.token ?? "";
39 const res = page({
40 ctx,
41 title: "You are invited",
42 body: html`<div class="stack">
43 <h1>You are invited</h1>
44 <p>Continue to make your account on this forge.</p>
45 <form method="post" action="/invite">
46 <input type="hidden" name="token" value="${token}" />
47 ${btn("Continue", { variant: "primary", size: "lg" })}
48 </form>
49 </div>`,
50 });
51 res.headers.set("cache-control", "no-store");
52 return res;
53 }
54
55 // POST /invite — keep the token in a cookie and go to sign up.
56 export async function inviteAccept(ctx: Ctx): Promise<Response> {
57 const form = await readForm(ctx, undefined);
58 if (form instanceof Response) return form;
59 const token = field(form, "token");
60 if (!/^[A-Za-z0-9_-]{1,200}$/.test(token)) return redirect("/signup");
61 return redirect("/signup", cookie(ctx, token, KEPT_SECONDS));
62 }
src/web/pages/signup-passkey.ts +17 −6
@@ -7,7 +7,7 @@
77 */
88
99 import { newChallenge, verifyRegistration } from "../../auth/webauthn.ts";
10 import { plausibleEmail, signUpWithPasskey, signupClosed, HUMAN_CHECK_MESSAGE, SIGNUP_CLOSED_MESSAGE } from "../../actions/users.ts";
10 import { plausibleEmail, signUpWithPasskey, signupMode, HUMAN_CHECK_MESSAGE, INVITE_REQUIRED_MESSAGE, SIGNUP_CLOSED_MESSAGE } from "../../actions/users.ts";
1111 import { createSession } from "../../core/sessions.ts";
1212 import { getUserByName } from "../../core/users.ts";
1313 import { isSafeName } from "../../git/guard.ts";
@@ -15,6 +15,8 @@ import { crossOrigin, type Ctx } from "../../http/context.ts";
1515 import { STRANGER_MAX } from "../../http/limits.ts";
1616 import { clientAddress } from "../../http/peer.ts";
1717 import { boundedBody, json, str } from "../../http/respond.ts";
18 import { inviteForgotten, inviteHeld } from "./invite.ts";
19 import { inviteValid } from "../../core/invites.ts";
1820 import { relying, store } from "./passkeys.ts";
1921 import { safeNext, sessionCookie, signinAllowed } from "./site.ts";
2022
@@ -31,6 +33,7 @@ const WORDS: Record<string, string> = {
3133 human_check: HUMAN_CHECK_MESSAGE,
3234 passkey_taken: "That passkey is already registered.",
3335 signup_closed: SIGNUP_CLOSED_MESSAGE,
36 invite_required: INVITE_REQUIRED_MESSAGE,
3437 };
3538
3639 /** Whether the name and address are fit to sign up with; else the words. */
@@ -53,7 +56,10 @@ function guard(ctx: Ctx): Response | undefined {
5356 export async function signupOptions(ctx: Ctx): Promise<Response> {
5457 const denied = guard(ctx);
5558 if (denied) return denied;
56 if (signupClosed(ctx.app)) return refuse(403, SIGNUP_CLOSED_MESSAGE);
59 const mode = signupMode(ctx.app);
60 if (mode === "closed") return refuse(403, SIGNUP_CLOSED_MESSAGE);
61 if (mode === "invite" && !inviteValid(ctx.app.db, inviteHeld(ctx)))
62 return refuse(403, INVITE_REQUIRED_MESSAGE);
5763 const data = await boundedBody(ctx.request, STRANGER_MAX);
5864 if (data === "too_large") return refuse(413, "payload too large");
5965 const username = str(data.username).trim();
@@ -73,7 +79,10 @@ export async function signupOptions(ctx: Ctx): Promise<Response> {
7379 export async function signupPasskey(ctx: Ctx): Promise<Response> {
7480 const denied = guard(ctx);
7581 if (denied) return denied;
76 if (signupClosed(ctx.app)) return refuse(403, SIGNUP_CLOSED_MESSAGE);
82 const mode = signupMode(ctx.app);
83 if (mode === "closed") return refuse(403, SIGNUP_CLOSED_MESSAGE);
84 if (mode === "invite" && !inviteValid(ctx.app.db, inviteHeld(ctx)))
85 return refuse(403, INVITE_REQUIRED_MESSAGE);
7786 const data = await boundedBody(ctx.request, STRANGER_MAX);
7887 if (data === "too_large") return refuse(413, "payload too large");
7988 const username = str(data.username).trim();
@@ -90,15 +99,17 @@ export async function signupPasskey(ctx: Ctx): Promise<Response> {
9099 if (!made.ok) return refuse(400, "That passkey was not accepted.");
91100 const created = await signUpWithPasskey(
92101 ctx.app,
93 { username, email, passkey: made, passkeyName: "Passkey", humanToken: str(data.humanToken) },
102 { username, email, passkey: made, passkeyName: "Passkey", humanToken: str(data.humanToken), invite: inviteHeld(ctx) },
94103 { address: clientAddress(ctx.request) },
95104 );
96105 if (!created.ok)
97 return refuse(created.error === "human_check" ? 422 : created.error === "signup_closed" ? 403 : 409, WORDS[created.error] ?? "Sign-up did not work. Try again.");
106 return refuse(created.error === "human_check" ? 422 : created.error === "signup_closed" || created.error === "invite_required" ? 403 : 409, WORDS[created.error] ?? "Sign-up did not work. Try again.");
98107 const session = createSession(ctx.app.db, created.value.id);
99 return json(
108 const res = json(
100109 { ok: true, next: safeNext(ctx.url.searchParams.get("next")) ?? "/" },
101110 201,
102111 { "set-cookie": sessionCookie(session.token, session.expiresAt, ctx.url, ctx.app.config.url) },
103112 );
113 res.headers.append("set-cookie", inviteForgotten(ctx));
114 return res;
104115 }
src/web/pages/site.ts +23 −3
@@ -15,7 +15,7 @@ import { clientAddress } from "../../http/peer.ts";
1515 import { verifyEmail } from "../../actions/verify.ts";
1616 import { STRANGER_MAX } from "../../http/limits.ts";
1717 import { createRepo, repositoryLimitMessage, resolveOwner } from "../../actions/repos.ts";
18 import { HUMAN_CHECK_MESSAGE, PASSKEY_REQUIRED_MESSAGE, SIGNUP_CLOSED_MESSAGE, signUp, signupClosed } from "../../actions/users.ts";
18 import { HUMAN_CHECK_MESSAGE, PASSKEY_REQUIRED_MESSAGE, INVITE_REQUIRED_MESSAGE, SIGNUP_CLOSED_MESSAGE, signUp, signupMode } from "../../actions/users.ts";
1919 import { accessAllows, listOrgsForUser, orgAccess } from "../../core/orgs.ts";
2020 import { listPins } from "../../core/pins.ts";
2121 import { getReposByIds } from "../../core/repos.ts";
@@ -30,6 +30,8 @@ import { sshCommand } from "../../ssh/command.ts";
3030 import { hostOf, pageHead, signInFirst } from "../chrome.ts";
3131 import { RateLimiter } from "../../core/ratelimit.ts";
3232 import { field, readForm } from "../form.ts";
33 import { inviteForgotten, inviteHeld } from "./invite.ts";
34 import { inviteValid } from "../../core/invites.ts";
3335 import { passkeyJs } from "../passkey-client.ts";
3436 import { html, when, type Html } from "../html.ts";
3537 import { icon } from "../icons.ts";
@@ -414,8 +416,22 @@ function signupClosedPage(ctx: Ctx): Response {
414416 );
415417 }
416418
419 /** The whole of `/signup` by invitation without a good link: one sentence, the same for every failure. */
420 function inviteRequiredPage(ctx: Ctx): Response {
421 return page(
422 {
423 ctx,
424 title: "Sign up",
425 body: html`<div class="stack"><h1>Sign up</h1><p>${INVITE_REQUIRED_MESSAGE}</p><p><a href="/signin">Sign in</a></p></div>`,
426 },
427 403,
428 );
429 }
430
417431 export function signupPage(ctx: Ctx): Response {
418 if (signupClosed(ctx.app)) return signupClosedPage(ctx);
432 const mode = signupMode(ctx.app);
433 if (mode === "closed") return signupClosedPage(ctx);
434 if (mode === "invite" && !inviteValid(ctx.app.db, inviteHeld(ctx))) return inviteRequiredPage(ctx);
419435 return page({
420436 ctx,
421437 title: "Sign up",
@@ -541,11 +557,13 @@ export async function signupSubmit(ctx: Ctx): Promise<Response> {
541557 email,
542558 password: field(form, "password"),
543559 humanToken: field(form, "cf-turnstile-response"),
560 invite: inviteHeld(ctx),
544561 },
545562 { address: clientAddress(ctx.request) },
546563 );
547564 if (!created.ok) {
548565 if (created.error === "signup_closed") return signupClosedPage(ctx);
566 if (created.error === "invite_required") return inviteRequiredPage(ctx);
549567 const errors: AuthErrors = {
550568 invalid_username: {
551569 username: "Usernames are letters, digits, dots, dashes.",
@@ -569,10 +587,12 @@ export async function signupSubmit(ctx: Ctx): Promise<Response> {
569587 );
570588 }
571589 const session = createSession(ctx.app.db, created.value.id);
572 return redirect(
590 const done = redirect(
573591 safeNext(ctx.url.searchParams.get("next")) ?? "/",
574592 sessionCookie(session.token, session.expiresAt, ctx.url, ctx.app.config.url),
575593 );
594 done.headers.append("set-cookie", inviteForgotten(ctx));
595 return done;
576596 }
577597
578598 // POST /theme — persist the theme choice in a cookie. Works as a plain form
test/invites.test.ts added +207
@@ -0,0 +1,207 @@
1 /**
2 * Invite links (#1143): minted by an admin, single use, expiring, revocable;
3 * with `signup = invite` they are the only way to an account, and every
4 * failure reads the same.
5 */
6
7 import { afterAll, beforeAll, describe, expect, test } from "bun:test";
8 import { mkdtemp, rm } from "node:fs/promises";
9 import { tmpdir } from "node:os";
10 import { join } from "node:path";
11 import { createApp, type App } from "../src/app.ts";
12 import { INVITE_REQUIRED_MESSAGE } from "../src/actions/users.ts";
13 import { claimInvite, mintInvite, parseDays, revokeInvite } from "../src/core/invites.ts";
14 import { createToken } from "../src/core/tokens.ts";
15 import { createUser, getUserByName } from "../src/core/users.ts";
16 import { listEvents } from "../src/core/events.ts";
17 import { serve, type Servers } from "../src/http/server.ts";
18 import { getSignup, setSignup, signupDefaultForNewForge } from "../src/settings/signup.ts";
19
20 const ORIGIN = "https://forge.example";
21
22 describe("invite links", () => {
23 let dataDir: string;
24 let app: App;
25 let servers: Servers;
26 let base: string;
27 let adminId: string;
28 let adminToken: string;
29
30 beforeAll(async () => {
31 dataDir = await mkdtemp(join(tmpdir(), "forge-invites-"));
32 app = createApp({ dataDir, port: 0, url: ORIGIN });
33 const admin = await createUser(app.db, {
34 trusted: true,
35 username: "boss",
36 email: "[email protected]",
37 password: "a-good-passphrase",
38 adminIfFirst: true,
39 });
40 if (!admin.ok) throw new Error(admin.error);
41 adminId = admin.value.id;
42 adminToken = createToken(app.db, adminId, "t", "admin").token;
43 setSignup(app.db, "invite", adminId);
44 servers = await serve(app);
45 base = servers.url;
46 });
47 afterAll(async () => {
48 await servers.stop();
49 app.close();
50 await rm(dataDir, { recursive: true, force: true });
51 });
52
53 const mint = async (days?: number) => {
54 const res = await fetch(`${base}/api/v1/admin/invites`, {
55 method: "POST",
56 headers: { authorization: `Bearer ${adminToken}`, "content-type": "application/json" },
57 body: JSON.stringify(days === undefined ? {} : { days }),
58 });
59 return { res, body: (await res.json()) as { id: string; token: string; url: string; expiresAt: string } };
60 };
61 const signup = (username: string, invite?: string) =>
62 fetch(`${base}/api/v1/users`, {
63 method: "POST",
64 headers: { "content-type": "application/json", origin: ORIGIN },
65 body: JSON.stringify({
66 username,
67 email: `${username}@example.com`,
68 password: "a-good-passphrase",
69 ...(invite === undefined ? {} : { invite }),
70 }),
71 });
72 const kinds = () => listEvents(app.db, {}).map((e) => e.kind);
73
74 test("an admin mints a link: 7 days by default, only a hash stored, audited", async () => {
75 const { res, body } = await mint();
76 expect(res.status).toBe(201);
77 expect(body.url).toBe(`${ORIGIN}/invite/${body.token}`);
78 const days = (Date.parse(body.expiresAt) - Date.now()) / 86_400_000;
79 expect(days).toBeGreaterThan(6.99);
80 expect(days).toBeLessThan(7.01);
81 const stored = app.db.query<{ token_hash: string }, [string]>("SELECT token_hash FROM invite WHERE id = ?1").get(body.id);
82 expect(stored?.token_hash).not.toContain(body.token);
83 expect(kinds()).toContain("invite.created");
84 });
85
86 test("days: up to 30, nothing else", async () => {
87 expect((await mint(30)).res.status).toBe(201);
88 expect((await mint(31)).res.status).toBe(422);
89 expect((await mint(0)).res.status).toBe(422);
90 expect(parseDays("12")).toEqual({ ok: true, value: 12 });
91 expect(parseDays("1e1").ok).toBe(false);
92 });
93
94 test("a non-admin cannot mint", async () => {
95 const bob = await createUser(app.db, { username: "bob", email: "[email protected]", trusted: true, password: "a-good-passphrase" });
96 if (!bob.ok) throw new Error("no bob");
97 const t = createToken(app.db, bob.value.id, "t", "admin").token;
98 const res = await fetch(`${base}/api/v1/admin/invites`, {
99 method: "POST",
100 headers: { authorization: `Bearer ${t}`, "content-type": "application/json" },
101 body: "{}",
102 });
103 expect(res.status).toBe(404);
104 });
105
106 test("a valid link makes one account, once", async () => {
107 const { body } = await mint();
108 const ok = await signup("alice", body.token);
109 expect(ok.status).toBe(201);
110 expect(getUserByName(app.db, "alice")).toBeDefined();
111 expect(kinds()).toContain("invite.used");
112 const again = await signup("alice2", body.token);
113 expect(again.status).toBe(403);
114 expect(getUserByName(app.db, "alice2")).toBeUndefined();
115 });
116
117 test("a refused sign-up gives the link back", async () => {
118 const { body } = await mint();
119 expect((await signup("alice", body.token)).status).toBe(422); // name taken
120 expect((await signup("carol", body.token)).status).toBe(201);
121 });
122
123 test("missing, unknown, used, expired and revoked read the same", async () => {
124 const used = await mint();
125 await signup("dave", used.body.token);
126 const revoked = await mint();
127 const del = await fetch(`${base}/api/v1/admin/invites/${revoked.body.id}`, {
128 method: "DELETE",
129 headers: { authorization: `Bearer ${adminToken}` },
130 });
131 expect(del.status).toBe(200);
132 expect(kinds()).toContain("invite.revoked");
133 const old = mintInvite(app.db, adminId, 1, new Date(Date.now() - 2 * 86_400_000));
134 const bodies = new Set<string>();
135 for (const token of [undefined, "never-existed", used.body.token, revoked.body.token, old.token]) {
136 const res = await signup("eve", token);
137 expect(res.status).toBe(403);
138 bodies.add(await res.text());
139 }
140 expect(bodies.size).toBe(1);
141 expect([...bodies][0]).toContain(INVITE_REQUIRED_MESSAGE);
142 expect(getUserByName(app.db, "eve")).toBeUndefined();
143 });
144
145 test("two claims of one link: one wins", () => {
146 const m = mintInvite(app.db, adminId, 7);
147 expect(claimInvite(app.db, m.token).ok).toBe(true);
148 expect(claimInvite(app.db, m.token).ok).toBe(false);
149 expect(revokeInvite(app.db, m.invite.id)).toBe(false);
150 });
151
152 test("the web: landing posts the token into a cookie, then /signup takes it", async () => {
153 const { body } = await mint();
154 const bare = await fetch(`${base}/signup`);
155 expect(bare.status).toBe(403);
156 expect(await bare.text()).toContain(INVITE_REQUIRED_MESSAGE);
157
158 const landing = await fetch(`${base}/invite/${body.token}`);
159 expect(landing.status).toBe(200);
160 expect(landing.headers.get("referrer-policy")).not.toBeNull();
161 const accept = await fetch(`${base}/invite`, {
162 method: "POST",
163 redirect: "manual",
164 headers: { "content-type": "application/x-www-form-urlencoded", origin: ORIGIN },
165 body: new URLSearchParams({ token: body.token }),
166 });
167 expect(accept.status).toBe(303);
168 expect(accept.headers.get("location")).toBe("/signup");
169 const set = accept.headers.get("set-cookie") ?? "";
170 expect(set).toContain("HttpOnly");
171 expect(set).not.toContain("location");
172 const cookie = set.split(";")[0]!;
173
174 const form = await fetch(`${base}/signup`, { headers: { cookie } });
175 expect(form.status).toBe(200);
176 expect(await form.text()).toContain('name="password"');
177 const made = await fetch(`${base}/signup`, {
178 method: "POST",
179 redirect: "manual",
180 headers: { "content-type": "application/x-www-form-urlencoded", origin: ORIGIN, cookie },
181 body: new URLSearchParams({ username: "frank", email: "[email protected]", password: "a-good-passphrase" }),
182 });
183 expect(made.status).toBe(303);
184 expect(getUserByName(app.db, "frank")).toBeDefined();
185 expect((await fetch(`${base}/signup`, { headers: { cookie } })).status).toBe(403);
186 });
187
188 test("a new forge defaults to invite; one with accounts or a choice keeps its value", async () => {
189 const fresh = createApp({ dataDir: await mkdtemp(join(tmpdir(), "forge-invites-new-")), port: 0, url: ORIGIN });
190 expect(getSignup(fresh.db)).toBe("open");
191 signupDefaultForNewForge(fresh.db);
192 expect(getSignup(fresh.db)).toBe("invite");
193 fresh.close();
194
195 const old = createApp({ dataDir: await mkdtemp(join(tmpdir(), "forge-invites-old-")), port: 0, url: ORIGIN });
196 await createUser(old.db, { username: "elder", email: "[email protected]", trusted: true, password: "a-good-passphrase", adminIfFirst: true });
197 signupDefaultForNewForge(old.db);
198 expect(getSignup(old.db)).toBe("open");
199 old.close();
200
201 const chose = createApp({ dataDir: await mkdtemp(join(tmpdir(), "forge-invites-chose-")), port: 0, url: ORIGIN });
202 setSignup(chose.db, "closed", "boot");
203 signupDefaultForNewForge(chose.db);
204 expect(getSignup(chose.db)).toBe("closed");
205 chose.close();
206 });
207 });
test/signup-closed.test.ts +5 −3
@@ -50,19 +50,21 @@ describe("closed signup", () => {
5050 expect(((await first.json()) as { isAdmin: boolean }).isAdmin).toBe(true);
5151 });
5252
53 // `invite` is not closed to a link (test/invites.test.ts); the edge carries none.
5354 for (const closed of ["closed", "invite"] as const) {
5455 test(`${closed}: page, API and edge make no account`, async () => {
56 const said = closed === "closed" ? "Signup is closed on this forge." : "needs a valid invite link";
5557 mode(closed);
5658 const page = await fetch(`${base}/signup`);
5759 const html = await page.text();
58 expect(html).toContain("Signup is closed on this forge.");
60 expect(html).toContain(said);
5961 expect(html).not.toContain('name="password"');
6062
6163 const res = await post(`via-api-${closed}`);
6264 expect(res.status).toBe(403);
6365 const body = (await res.json()) as { error: string; message: string };
64 expect(body.error).toBe("signup_closed");
65 expect(body.message).toContain("closed");
66 expect(body.error).toBe(closed === "closed" ? "signup_closed" : "invite_required");
67 expect(body.message).toContain(closed === "closed" ? "closed" : "invite link");
6668 expect(getUserByName(app.db, `via-api-${closed}`)).toBeUndefined();
6769
6870 expect((await me(`via-edge-${closed}`)).status).toBe(401);
test/signup.test.ts +4 −3
@@ -218,7 +218,8 @@ describe("signup closed (#2166)", () => {
218218 const page = await fetch(`${servers.url}/signup`);
219219 const text = await page.text();
220220 expect(page.status).toBe(403);
221 expect(text).toContain("Signup is closed on this forge.");
221 // `invite` has its own sentence now (test/invites.test.ts).
222 expect(text).toContain(mode === "closed" ? "Signup is closed on this forge." : "needs a valid invite link");
222223 const main = text.slice(text.indexOf("<main"), text.indexOf("</main>"));
223224 expect(main).not.toContain("<form");
224225 expect(main).not.toContain("<input");
@@ -227,7 +228,7 @@ describe("signup closed (#2166)", () => {
227228 const res = await post(body);
228229 expect(res.status).toBe(403);
229230 const err = (await res.json()) as { error: string; message: string };
230 expect(err.error).toBe("signup_closed");
231 expect(err.error).toBe(mode === "closed" ? "signup_closed" : "invite_required");
231232 expect(err.message.length).toBeGreaterThan(0);
232233 expect(getUserByName(app.db, body.username)).toBeUndefined();
233234
@@ -244,7 +245,7 @@ describe("signup closed (#2166)", () => {
244245 body: JSON.stringify({ username: `pk${mode}`, email: `pk${mode}@forge.local` }),
245246 });
246247 expect(opts.status).toBe(403);
247 expect(await opts.text()).toContain("closed");
248 expect(await opts.text()).toContain(mode === "closed" ? "closed" : "invite link");
248249 const pk = await fetch(`${servers.url}/signup/passkey`, {
249250 method: "POST",
250251 headers: { "content-type": "application/json", origin: servers.url },

↑↓ navigate ↵ open ⌘↵ its app esc close

Keyboard shortcuts

Docs