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

Invites, part 2: a forge set to signup = invite makes an account only through a valid link, and new forges default to invite #2408

Parked opened this
Closed without merging

scout/forge:scout/2336-invites-part-2-a-forge-set-to-signup-inv → main 1 commit fork

  • Closed without merging. Nothing was applied to main.

Review

Sign in to review this change.
13 files changed +312 −38
README.md +2 −2

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

View file
src/actions/users.ts +73 −10
@@ -6,6 +6,7 @@
66 import { emailChanged, welcome } from "./verify.ts";
77 import type { App } from "../app.ts";
88 import type { Credential } from "../auth/webauthn.ts";
9 import { claimInvite, inviteUsable, noteInviteUser, releaseInvite } from "../core/invites.ts";
910 import { addPasskey, findPasskey } from "../core/passkeys.ts";
1011 import {
1112 addKey,
@@ -44,27 +45,73 @@ 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 from the link, read only when the forge signs up by invite. */
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";
5458
5559 /** What anyone is told when the forge makes no new accounts. */
5660 export const SIGNUP_CLOSED_MESSAGE = "Signup is closed on this forge.";
5761
62 /** What anyone is told without a link that works: the same for every cause. */
63 export const INVITE_REQUIRED_MESSAGE = "Signing up here needs a valid invite link.";
64
5865 /**
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.
66 * Whether no new account may be made now, whatever the visitor holds. Read
67 * from the store on every call, so a change takes effect on the next request.
68 * `invite` is refused here: only a door that carries a link asks
69 * `signupRefusal`. The forge's first account is never refused: the owner
70 * cannot be locked out of a fresh forge by a setting.
6371 */
6472 export function signupClosed(app: App): boolean {
6573 return getSignup(app.db) !== "open" && hasAnyUser(app.db);
6674 }
6775
76 type Refusal = "signup_closed" | "invite_required";
77
78 /**
79 * Why this visitor may not sign up, if they may not: `signup_closed` when
80 * closed, `invite_required` when the forge wants a link and this one is
81 * missing, unknown, used, revoked or expired (the visitor cannot tell which).
82 */
83 export function signupRefusal(app: App, invite: string | undefined): Refusal | undefined {
84 if (!hasAnyUser(app.db)) return undefined;
85 const mode = getSignup(app.db);
86 if (mode === "open") return undefined;
87 if (mode === "closed") return "signup_closed";
88 return invite !== undefined && inviteUsable(app.db, invite) ? undefined : "invite_required";
89 }
90
91 /** The sentence for a refusal. */
92 export const refusalMessage = (why: Refusal): string =>
93 why === "signup_closed" ? SIGNUP_CLOSED_MESSAGE : INVITE_REQUIRED_MESSAGE;
94
95 /**
96 * Use the link up for an account about to be made. `undefined` when none is
97 * needed (open forge, or the first account); a refusal when the link fails.
98 * The claim is atomic, so two sign-ups with one link cannot both win.
99 */
100 function claim(app: App, invite: string | undefined): Result<string | undefined, Refusal> {
101 const why = signupRefusal(app, invite);
102 if (why !== undefined) return err(why);
103 if (getSignup(app.db) !== "invite" || !hasAnyUser(app.db)) return ok(undefined);
104 const claimed = claimInvite(app.db, invite ?? "");
105 return claimed === undefined ? err("invite_required") : ok(claimed);
106 }
107
108 /** Audit a used link, once the account exists. */
109 function inviteUsed(app: App, inviteId: string | undefined, user: User): void {
110 if (inviteId === undefined) return;
111 noteInviteUser(app.db, inviteId, user.id);
112 app.bus.append({ kind: "invite.used", actorId: user.id, payload: { id: inviteId } });
113 }
114
68115 /** What anyone is told at a door that still offers a password-only sign-up. */
69116 export const PASSKEY_REQUIRED_MESSAGE =
70117 "New accounts sign up with a passkey and an email address. Open the sign-up page in a browser and choose \u201cCreate account with a passkey\u201d.";
@@ -102,7 +149,8 @@ export async function signUp(
102149 // when every such account has a passkey (Settings → Passkeys shows who is
103150 // left) and recovery without a password exists (#1618): then delete this
104151 // action's password path, `verifyPassword`'s doors and the password column.
105 if (signupClosed(app)) return err("signup_closed");
152 const refusal = signupRefusal(app, input.invite);
153 if (refusal !== undefined) return err(refusal);
106154 if (app.config.passkeyOnlySignup === true) return err("passkey_required");
107155 const secret = app.config.turnstileSecret;
108156 const bootstrap = from.door === "terminal" && !hasAnyUser(app.db);
@@ -112,9 +160,15 @@ export async function signUp(
112160 if (!(await verify(input.humanToken ?? "", from.address)))
113161 return err("human_check");
114162 }
115 const { humanToken: _token, ...account } = input;
163 const { humanToken: _token, invite, ...account } = input;
164 const claimed = claim(app, invite);
165 if (!claimed.ok) return claimed;
116166 const created = await createUser(app.db, { ...account, adminIfFirst: true });
117 if (!created.ok) return created;
167 if (!created.ok) {
168 if (claimed.value !== undefined) releaseInvite(app.db, claimed.value);
169 return created;
170 }
171 inviteUsed(app, claimed.value, created.value);
118172 app.bus.append({
119173 kind: "user.created",
120174 actorId: created.value.id,
@@ -136,6 +190,7 @@ export interface PasskeySignUpInput {
136190 passkey: Credential;
137191 passkeyName: string;
138192 humanToken?: string;
193 invite?: string;
139194 }
140195
141196 /**
@@ -150,7 +205,8 @@ export async function signUpWithPasskey(
150205 input: PasskeySignUpInput,
151206 from: { address?: string | undefined } = {},
152207 ): Promise<Result<User, SignUpError | "passkey_taken">> {
153 if (signupClosed(app)) return err("signup_closed");
208 const refusal = signupRefusal(app, input.invite);
209 if (refusal !== undefined) return err(refusal);
154210 const secret = app.config.turnstileSecret;
155211 if (secret !== undefined) {
156212 const verify = app.config.verifyHuman ?? turnstileVerifier(secret);
@@ -158,17 +214,24 @@ export async function signUpWithPasskey(
158214 return err("human_check");
159215 }
160216 if (findPasskey(app.db, input.passkey.id)) return err("passkey_taken");
217 const claimed = claim(app, input.invite);
218 if (!claimed.ok) return claimed;
161219 const created = await createUser(app.db, {
162220 username: input.username,
163221 email: input.email,
164222 adminIfFirst: true,
165223 });
166 if (!created.ok) return created;
224 if (!created.ok) {
225 if (claimed.value !== undefined) releaseInvite(app.db, claimed.value);
226 return created;
227 }
167228 const kept = addPasskey(app.db, created.value.id, input.passkeyName, input.passkey);
168229 if (!kept.ok) {
169230 discardFreshUser(app.db, created.value.id);
231 if (claimed.value !== undefined) releaseInvite(app.db, claimed.value);
170232 return err("passkey_taken");
171233 }
234 inviteUsed(app, claimed.value, created.value);
172235 app.bus.append({
173236 kind: "user.created",
174237 actorId: created.value.id,
src/core/invites.ts +33 −1
@@ -1,7 +1,7 @@
11 /**
22 * Invite links: a secret handed out once, good for one signup, gone after a
33 * deadline. The database holds only the token's hash, so a list can never
4 * give a link back. Signup does not read these yet (#2335).
4 * give a link back. Signup claims one (#2336).
55 */
66
77 import type { Database } from "bun:sqlite";
@@ -85,3 +85,35 @@ export function revokeInvite(
8585 if (changed === 0) return err("not_found");
8686 return ok(view(db.query<Row, [string]>("SELECT * FROM invite WHERE id = ?1").get(inviteId)!, now));
8787 }
88
89 /** Whether this token is a link that could still be used now. Changes nothing. */
90 export function inviteUsable(db: Database, token: string, now: number = Date.now()): boolean {
91 if (!token.startsWith("invite_") || token.length > 200) return false;
92 return db
93 .query<Row, [string]>("SELECT * FROM invite WHERE token_hash = ?1")
94 .all(sha256(token))
95 .some((r) => stateOf(r, now) === "open");
96 }
97
98 /** Use the link up, once: the id when this call won it, else undefined. */
99 export function claimInvite(db: Database, token: string, now: number = Date.now()): string | undefined {
100 if (!token.startsWith("invite_") || token.length > 200) return undefined;
101 const row = db
102 .query<{ id: string }, [string, string]>(
103 `UPDATE invite SET used_at = ?2
104 WHERE token_hash = ?1 AND used_at IS NULL AND revoked_at IS NULL AND expires_at > ?2
105 RETURNING id`,
106 )
107 .get(sha256(token), new Date(now).toISOString());
108 return row?.id;
109 }
110
111 /** Give a claimed link back when the account it was for was not made. */
112 export function releaseInvite(db: Database, inviteId: string): void {
113 db.query("UPDATE invite SET used_at = NULL, used_by = NULL WHERE id = ?1").run(inviteId);
114 }
115
116 /** Note who the link made. */
117 export function noteInviteUser(db: Database, inviteId: string, userId: string): void {
118 db.query("UPDATE invite SET used_by = ?2 WHERE id = ?1").run(inviteId, userId);
119 }
src/http/api.ts +4
@@ -156,6 +156,7 @@ import {
156156 HUMAN_CHECK_MESSAGE,
157157 PASSKEY_REQUIRED_MESSAGE,
158158 signUp,
159 INVITE_REQUIRED_MESSAGE,
159160 SIGNUP_CLOSED_MESSAGE,
160161 updateProfile,
161162 } from "../actions/users.ts";
@@ -1211,9 +1212,12 @@ export function apiRoutes(router: Router<Handler>): void {
12111212 email: str(input.email),
12121213 password: str(input.password),
12131214 humanToken: str(input.turnstile_token),
1215 invite: str(input.invite),
12141216 },
12151217 { address: clientAddress(ctx.request) },
12161218 );
1219 if (!created.ok && created.error === "invite_required")
1220 return apiError("invite_required", 403, INVITE_REQUIRED_MESSAGE);
12171221 if (!created.ok && created.error === "signup_closed")
12181222 return apiError("signup_closed", 403, SIGNUP_CLOSED_MESSAGE);
12191223 if (!created.ok && created.error === "passkey_required")
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, seedSignup, setSignup, 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";
@@ -246,6 +246,8 @@ const app = createApp({
246246 loadFlags(app.db);
247247 // FORGE_SIGNUP (checked in configProblem) sets who may sign up; kept like any change.
248248 const bootSignup = signupFromEnv(process.env.FORGE_SIGNUP);
249 // A new forge signs up by invite unless told otherwise; an existing one keeps its value.
250 if (!(bootSignup.ok && bootSignup.value !== null)) seedSignup(app.db);
249251 if (bootSignup.ok && bootSignup.value !== null)
250252 setSignup(app.db, bootSignup.value, BOOT_ACTOR);
251253 const flagTimer = setInterval(() => flushFlagUses(app.db), 10_000);
src/settings/signup.ts +16 −2
@@ -1,13 +1,15 @@
11 /**
22 * Who may make an account: `open`, `invite` or `closed`. Stored in
33 * `forge_setting` under `signup`, and every change is kept in
4 * `forge_setting_change` (who, when, from what to what). Default `open`.
4 * `forge_setting_change` (who, when, from what to what). A store with no row reads `open`, so a forge that already has accounts keeps it;
5 * a new forge is given `invite` at its first boot (`seedSignup`).
56 * `/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.
7 * it (`signupClosed` in `actions/users.ts`); `invite` also takes a valid link.
78 */
89
910 import type { Database } from "bun:sqlite";
1011 import { err, ok, type Result } from "../kernel/result.ts";
12 import { hasAnyUser } from "../core/users.ts";
1113 import { writeSetting } from "./limits.ts";
1214
1315 export const SIGNUP_MODES = ["open", "invite", "closed"] as const;
@@ -42,6 +44,18 @@ export function setSignup(db: Database, value: SignupMode, actorId: string): voi
4244 writeSetting(db, STORE_KEY, value, from, value, actorId);
4345 }
4446
47 /**
48 * A new forge (no accounts, nothing chosen) signs people up by invite. A forge
49 * with accounts, or one whose admin or `FORGE_SIGNUP` already chose, is left
50 * as it is. Returns whether it wrote.
51 */
52 export function seedSignup(db: Database): boolean {
53 const chosen = db.query("SELECT 1 FROM forge_setting WHERE key = ?1").get(STORE_KEY) !== null;
54 if (chosen || hasAnyUser(db)) return false;
55 writeSetting(db, STORE_KEY, "invite", SIGNUP_DEFAULT, "invite", BOOT_ACTOR);
56 return true;
57 }
58
4559 /** `FORGE_SIGNUP` from the environment: unset is no opinion, a bad value is a message. */
4660 export function signupFromEnv(raw: string | undefined): Result<SignupMode | null, string> {
4761 const s = (raw ?? "").trim();
src/tui/screens/common.ts +2 −1
@@ -12,7 +12,7 @@ import type { Ctx, Screen } from "../app/app.ts";
1212 import { binding, type Binding } from "../app/keys.ts";
1313 import type { KeyEvent } from "../term/input.ts";
1414 import type { RepoCounts } from "../../core/repos.ts";
15 import { SIGNUP_CLOSED_MESSAGE } from "../../actions/users.ts";
15 import { INVITE_REQUIRED_MESSAGE, SIGNUP_CLOSED_MESSAGE } from "../../actions/users.ts";
1616 import type { Session } from "../session.ts";
1717 import { G, Screen as Surface, type Rect } from "../term/screen.ts";
1818 import { style } from "../term/style.ts";
@@ -818,6 +818,7 @@ const MESSAGES: Record<string, string> = {
818818 not_member: NOT_A_MEMBER,
819819 not_found: "not found",
820820 signup_closed: SIGNUP_CLOSED_MESSAGE,
821 invite_required: INVITE_REQUIRED_MESSAGE,
821822 human_check: "we could not tell you are a person; sign up on the web page",
822823 passkey_required: "new accounts sign up with a passkey and an email address: open the sign-up page in a browser",
823824 unauthorized: "sign in first",
src/web/pages/signup-passkey.ts +11 −5
@@ -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, signupRefusal, refusalMessage, HUMAN_CHECK_MESSAGE, SIGNUP_CLOSED_MESSAGE, INVITE_REQUIRED_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";
@@ -31,6 +31,7 @@ const WORDS: Record<string, string> = {
3131 human_check: HUMAN_CHECK_MESSAGE,
3232 passkey_taken: "That passkey is already registered.",
3333 signup_closed: SIGNUP_CLOSED_MESSAGE,
34 invite_required: INVITE_REQUIRED_MESSAGE,
3435 };
3536
3637 /** Whether the name and address are fit to sign up with; else the words. */
@@ -41,6 +42,9 @@ function problem(ctx: Ctx, username: string, email: string): string | undefined
4142 return undefined;
4243 }
4344
45 /** The link token the page was opened with, carried in the query. */
46 const invite = (ctx: Ctx): string => (ctx.url.searchParams.get("invite") ?? "").slice(0, 200);
47
4448 function guard(ctx: Ctx): Response | undefined {
4549 if (crossOrigin(ctx.request, ctx.url, ctx.app.log)) return refuse(403, "forbidden");
4650 const wait = signinAllowed(ctx, `signup:${clientAddress(ctx.request)}`);
@@ -53,7 +57,8 @@ function guard(ctx: Ctx): Response | undefined {
5357 export async function signupOptions(ctx: Ctx): Promise<Response> {
5458 const denied = guard(ctx);
5559 if (denied) return denied;
56 if (signupClosed(ctx.app)) return refuse(403, SIGNUP_CLOSED_MESSAGE);
60 const why = signupRefusal(ctx.app, invite(ctx));
61 if (why !== undefined) return refuse(403, refusalMessage(why));
5762 const data = await boundedBody(ctx.request, STRANGER_MAX);
5863 if (data === "too_large") return refuse(413, "payload too large");
5964 const username = str(data.username).trim();
@@ -73,7 +78,8 @@ export async function signupOptions(ctx: Ctx): Promise<Response> {
7378 export async function signupPasskey(ctx: Ctx): Promise<Response> {
7479 const denied = guard(ctx);
7580 if (denied) return denied;
76 if (signupClosed(ctx.app)) return refuse(403, SIGNUP_CLOSED_MESSAGE);
81 const why = signupRefusal(ctx.app, invite(ctx));
82 if (why !== undefined) return refuse(403, refusalMessage(why));
7783 const data = await boundedBody(ctx.request, STRANGER_MAX);
7884 if (data === "too_large") return refuse(413, "payload too large");
7985 const username = str(data.username).trim();
@@ -90,11 +96,11 @@ export async function signupPasskey(ctx: Ctx): Promise<Response> {
9096 if (!made.ok) return refuse(400, "That passkey was not accepted.");
9197 const created = await signUpWithPasskey(
9298 ctx.app,
93 { username, email, passkey: made, passkeyName: "Passkey", humanToken: str(data.humanToken) },
99 { username, email, passkey: made, passkeyName: "Passkey", humanToken: str(data.humanToken), invite: invite(ctx) },
94100 { address: clientAddress(ctx.request) },
95101 );
96102 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.");
103 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.");
98104 const session = createSession(ctx.app.db, created.value.id);
99105 return json(
100106 { ok: true, next: safeNext(ctx.url.searchParams.get("next")) ?? "/" },
src/web/pages/site.ts +18 −9
@@ -16,7 +16,7 @@ import { bucketOf, clientAddress } from "../../http/peer.ts";
1616 import { verifyEmail } from "../../actions/verify.ts";
1717 import { STRANGER_MAX } from "../../http/limits.ts";
1818 import { createRepo, repositoryLimitMessage, resolveOwner } from "../../actions/repos.ts";
19 import { HUMAN_CHECK_MESSAGE, PASSKEY_REQUIRED_MESSAGE, SIGNUP_CLOSED_MESSAGE, signUp, signupClosed } from "../../actions/users.ts";
19 import { HUMAN_CHECK_MESSAGE, PASSKEY_REQUIRED_MESSAGE, refusalMessage, signUp, signupRefusal } from "../../actions/users.ts";
2020 import { accessAllows, listOrgsForUser, orgAccess } from "../../core/orgs.ts";
2121 import { listPins } from "../../core/pins.ts";
2222 import { getReposByIds } from "../../core/repos.ts";
@@ -233,9 +233,12 @@ function authForm(
233233 const values = o.values ?? {};
234234 const errors = o.errors ?? {};
235235 const next = safeNext(ctx.url.searchParams.get("next"));
236 const action = next
237 ? `/${kind}?next=${encodeURIComponent(next)}`
238 : `/${kind}`;
236 const invite = kind === "signup" ? inviteOf(ctx) : "";
237 const query = [
238 ...(next ? [`next=${encodeURIComponent(next)}`] : []),
239 ...(invite ? [`invite=${encodeURIComponent(invite)}`] : []),
240 ].join("&");
241 const action = query ? `/${kind}?${query}` : `/${kind}`;
239242 // "Is this the first account?" is a `LIMIT 1` existence check, not a count
240243 // of the whole user table — and the sign-in screen paints on every session.
241244 const firstAccount = kind === "signup" && !hasAnyUser(ctx.app.db);
@@ -403,20 +406,24 @@ function siteKey(ctx: Ctx): string | undefined {
403406 return turnstileSecret === undefined ? undefined : turnstileSiteKey;
404407 }
405408
406 /** The whole of `/signup` while the forge makes no new accounts: a sentence, no form. */
407 function signupClosedPage(ctx: Ctx): Response {
409 /** The link token a sign-up request carries, if any: a bounded string. */
410 const inviteOf = (ctx: Ctx): string => (ctx.url.searchParams.get("invite") ?? "").slice(0, 200);
411
412 /** The whole of `/signup` while this visitor may not sign up: a sentence, no form. */
413 function signupClosedPage(ctx: Ctx, why: "signup_closed" | "invite_required"): Response {
408414 return page(
409415 {
410416 ctx,
411417 title: "Sign up",
412 body: html`<div class="stack"><h1>Sign up</h1><p>${SIGNUP_CLOSED_MESSAGE}</p><p><a href="/signin">Sign in</a></p></div>`,
418 body: html`<div class="stack"><h1>Sign up</h1><p>${refusalMessage(why)}</p><p><a href="/signin">Sign in</a></p></div>`,
413419 },
414420 403,
415421 );
416422 }
417423
418424 export function signupPage(ctx: Ctx): Response {
419 if (signupClosed(ctx.app)) return signupClosedPage(ctx);
425 const why = signupRefusal(ctx.app, inviteOf(ctx));
426 if (why !== undefined) return signupClosedPage(ctx, why);
420427 return page({
421428 ctx,
422429 title: "Sign up",
@@ -588,11 +595,13 @@ export async function signupSubmit(ctx: Ctx): Promise<Response> {
588595 email,
589596 password: field(form, "password"),
590597 humanToken: field(form, "cf-turnstile-response"),
598 invite: inviteOf(ctx),
591599 },
592600 { address: clientAddress(ctx.request) },
593601 );
594602 if (!created.ok) {
595 if (created.error === "signup_closed") return signupClosedPage(ctx);
603 if (created.error === "signup_closed" || created.error === "invite_required")
604 return signupClosedPage(ctx, created.error);
596605 const errors: AuthErrors = {
597606 invalid_username: {
598607 username: "Usernames are letters, digits, dots, dashes.",
src/web/passkey-client.ts +1 −1
@@ -99,7 +99,7 @@ export const passkeyJs = /* js */ `
9999 wire('passkey-signup', function () {
100100 function val(n) { var el = doc.querySelector('[name=' + n + ']'); return el ? el.value : ''; }
101101 var who = { username: val('username'), email: val('email') };
102 return post('/signup/passkey/options', who).then(function (o) {
102 return post('/signup/passkey/options' + location.search, who).then(function (o) {
103103 return navigator.credentials.create({ publicKey: {
104104 challenge: bytes(o.challenge),
105105 rp: { id: o.rpId, name: o.rpName },
test/invite-signup.test.ts added +143
@@ -0,0 +1,143 @@
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 { signUp } from "../src/actions/users.ts";
7 import { listEvents } from "../src/core/events.ts";
8 import { mintInvite, revokeInvite } from "../src/core/invites.ts";
9 import { getUserByName } from "../src/core/users.ts";
10 import { serve, type Servers } from "../src/http/server.ts";
11 import { setLimit } from "../src/settings/limits.ts";
12 import { getSignup, seedSignup, setSignup } from "../src/settings/signup.ts";
13
14 const SENTENCE = "Signing up here needs a valid invite link.";
15
16 describe("signup = invite", () => {
17 let dir: string;
18 let app: App;
19 let servers: Servers;
20 let admin: string;
21 let n = 0;
22
23 const mint = () => mintInvite(app.db, admin).token;
24 const post = (invite: string | undefined, username = `guest${++n}`) =>
25 fetch(`${servers.url}/api/v1/users`, {
26 method: "POST",
27 headers: { "content-type": "application/json", origin: servers.url },
28 body: JSON.stringify({ username, email: `${username}@example.com`, password: "a-good-passphrase", invite }),
29 }).then(async (res) => ({ res, name: username, body: (await res.json()) as { message?: string; error?: string } }));
30
31 beforeAll(async () => {
32 dir = await mkdtemp(join(tmpdir(), "forge-invite-signup-"));
33 app = createApp({ dataDir: dir, port: 0, url: "https://forge.example" });
34 servers = await serve(app);
35 const first = await signUp(app, { username: "olive", email: "[email protected]", password: "owner-passphrase" });
36 if (!first.ok) throw new Error("signup");
37 admin = first.value.id;
38 setSignup(app.db, "invite", "boot");
39 setLimit(app.db, "signup.per_source", 1000, "setup");
40 setLimit(app.db, "signup.per_forge", 1000, "setup");
41 });
42 afterAll(async () => {
43 servers.stop();
44 app.close();
45 await rm(dir, { recursive: true, force: true });
46 });
47
48 test("a valid link makes the account, uses the link up, and is audited", async () => {
49 const token = mint();
50 const page = await fetch(`${servers.url}/signup?invite=${token}`);
51 const html = await page.text();
52 expect(page.status).toBe(200);
53 expect(html).toContain('name="password"');
54 expect(html).toContain(`action="/signup?invite=${token}"`);
55
56 const { res, name } = await post(token);
57 expect(res.status).toBe(201);
58 const user = getUserByName(app.db, name)!;
59 expect(user).toBeDefined();
60 const used = listEvents(app.db, { limit: 50 }).filter((e) => e.kind === "invite.used");
61 expect(used.length).toBe(1);
62 expect(used[0]!.actorId).toBe(user.id);
63 expect(JSON.stringify(used)).not.toContain(token);
64 });
65
66 test("the same link twice is refused, with one plain sentence", async () => {
67 const token = mint();
68 expect((await post(token)).res.status).toBe(201);
69 const again = await post(token);
70 expect(again.res.status).toBe(403);
71 expect(again.body.message).toBe(SENTENCE);
72 expect(getUserByName(app.db, again.name)).toBeUndefined();
73 expect(await (await fetch(`${servers.url}/signup?invite=${token}`)).text()).toContain(SENTENCE);
74 });
75
76 test("expired and revoked links are refused", async () => {
77 const old = mintInvite(app.db, admin);
78 app.db.query("UPDATE invite SET expires_at = ?2 WHERE id = ?1").run(old.invite.id, new Date(Date.now() - 1000).toISOString());
79 const expired = await post(old.token);
80 expect(expired.res.status).toBe(403);
81 expect(expired.body.message).toBe(SENTENCE);
82
83 const gone = mintInvite(app.db, admin);
84 expect(revokeInvite(app.db, gone.invite.id).ok).toBe(true);
85 const revoked = await post(gone.token);
86 expect(revoked.res.status).toBe(403);
87 expect(revoked.body.message).toBe(SENTENCE);
88 });
89
90 test("no link, a made-up link and a malformed one all get the same answer", async () => {
91 for (const a of [await post(undefined), await post("invite_neverminted"), await post("not shaped like one")]) {
92 expect(a.res.status).toBe(403);
93 expect(a.body).toEqual({ error: "invite_required", message: SENTENCE });
94 }
95 const bare = await fetch(`${servers.url}/signup`);
96 expect(bare.status).toBe(403);
97 expect(await bare.text()).toContain(SENTENCE);
98 });
99
100 test("a link is not spent by a refused account (taken name)", async () => {
101 const token = mint();
102 expect((await post(token, "olive")).res.status).toBe(422);
103 expect((await post(token)).res.status).toBe(201);
104 });
105
106 test("open and closed forges ignore the link", async () => {
107 setSignup(app.db, "open", "boot");
108 expect((await post(undefined)).res.status).toBe(201);
109 setSignup(app.db, "closed", "boot");
110 const closed = await post(mint());
111 expect(closed.res.status).toBe(403);
112 expect(closed.body.error).toBe("signup_closed");
113 setSignup(app.db, "invite", "boot");
114 });
115 });
116
117 describe("a new forge defaults to invite", () => {
118 test("seedSignup gives a fresh store invite, and leaves chosen or populated ones alone", async () => {
119 const mk = async () => {
120 const dir = await mkdtemp(join(tmpdir(), "forge-seed-"));
121 return { dir, app: createApp({ dataDir: dir, port: 0, url: "https://forge.example" }) };
122 };
123 const fresh = await mk();
124 expect(seedSignup(fresh.app.db)).toBe(true);
125 expect(getSignup(fresh.app.db)).toBe("invite");
126 expect(seedSignup(fresh.app.db)).toBe(false);
127 fresh.app.close();
128
129 const chosen = await mk();
130 setSignup(chosen.app.db, "closed", "boot");
131 expect(seedSignup(chosen.app.db)).toBe(false);
132 expect(getSignup(chosen.app.db)).toBe("closed");
133 chosen.app.close();
134
135 const existing = await mk();
136 await signUp(existing.app, { username: "old", email: "[email protected]", password: "owner-passphrase" });
137 expect(seedSignup(existing.app.db)).toBe(false);
138 expect(getSignup(existing.app.db)).toBe("open");
139 existing.app.close();
140
141 await Promise.all([fresh, chosen, existing].map((x) => rm(x.dir, { recursive: true, force: true })));
142 });
143 });
test/signup-closed.test.ts +3 −3
@@ -57,14 +57,14 @@ describe("closed signup", () => {
5757 mode(closed);
5858 const page = await fetch(`${base}/signup`);
5959 const html = await page.text();
60 expect(html).toContain("Signup is closed on this forge.");
60 expect(html).toContain(closed === "closed" ? "Signup is closed on this forge." : "needs a valid invite link");
6161 expect(html).not.toContain('name="password"');
6262
6363 const res = await post(`via-api-${closed}`);
6464 expect(res.status).toBe(403);
6565 const body = (await res.json()) as { error: string; message: string };
66 expect(body.error).toBe("signup_closed");
67 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");
6868 expect(getUserByName(app.db, `via-api-${closed}`)).toBeUndefined();
6969
7070 expect((await me(`via-edge-${closed}`)).status).toBe(401);
test/signup.test.ts +3 −3
@@ -220,7 +220,7 @@ describe("signup closed (#2166)", () => {
220220 const page = await fetch(`${servers.url}/signup`);
221221 const text = await page.text();
222222 expect(page.status).toBe(403);
223 expect(text).toContain("Signup is closed on this forge.");
223 expect(text).toContain(mode === "closed" ? "Signup is closed on this forge." : "needs a valid invite link");
224224 const main = text.slice(text.indexOf("<main"), text.indexOf("</main>"));
225225 expect(main).not.toContain("<form");
226226 expect(main).not.toContain("<input");
@@ -229,7 +229,7 @@ describe("signup closed (#2166)", () => {
229229 const res = await post(body);
230230 expect(res.status).toBe(403);
231231 const err = (await res.json()) as { error: string; message: string };
232 expect(err.error).toBe("signup_closed");
232 expect(err.error).toBe(mode === "closed" ? "signup_closed" : "invite_required");
233233 expect(err.message.length).toBeGreaterThan(0);
234234 expect(getUserByName(app.db, body.username)).toBeUndefined();
235235
@@ -246,7 +246,7 @@ describe("signup closed (#2166)", () => {
246246 body: JSON.stringify({ username: `pk${mode}`, email: `pk${mode}@forge.local` }),
247247 });
248248 expect(opts.status).toBe(403);
249 expect(await opts.text()).toContain("closed");
249 expect(await opts.text()).toContain(mode === "closed" ? "closed" : "invite link");
250250 const pk = await fetch(`${servers.url}/signup/passkey`, {
251251 method: "POST",
252252 headers: { "content-type": "application/json", origin: servers.url },

↑↓ navigate ↵ open ⌘↵ its app esc close

Keyboard shortcuts

Docs