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
scout/forge:scout/2336-invites-part-2-a-forge-set-to-signup-inv → main 1 commit fork
13 files
changed +312
−38
README.md +2 −2
Diff not shown — a line 4,879 characters wide (limit 2,000). +2 −2
View filesrc/actions/users.ts +73 −10
| @@ -6,6 +6,7 @@ | ||
| 6 | 6 | import { emailChanged, welcome } from "./verify.ts"; |
| 7 | 7 | import type { App } from "../app.ts"; |
| 8 | 8 | import type { Credential } from "../auth/webauthn.ts"; |
| 9 | import { claimInvite, inviteUsable, noteInviteUser, releaseInvite } from "../core/invites.ts"; | |
| 9 | 10 | import { addPasskey, findPasskey } from "../core/passkeys.ts"; |
| 10 | 11 | import { |
| 11 | 12 | addKey, |
| @@ -44,27 +45,73 @@ export interface SignUpInput { | ||
| 44 | 45 | password: string; |
| 45 | 46 | /** The Turnstile token the browser's widget gave; read only when a secret is set. */ |
| 46 | 47 | humanToken?: string; |
| 48 | /** The invite token from the link, read only when the forge signs up by invite. */ | |
| 49 | invite?: string; | |
| 47 | 50 | } |
| 48 | 51 | |
| 49 | 52 | export type SignUpError = |
| 50 | 53 | | CreateUserError |
| 51 | 54 | | "human_check" |
| 52 | 55 | | "passkey_required" |
| 53 | | "signup_closed"; | |
| 56 | | "signup_closed" | |
| 57 | | "invite_required"; | |
| 54 | 58 | |
| 55 | 59 | /** What anyone is told when the forge makes no new accounts. */ |
| 56 | 60 | export const SIGNUP_CLOSED_MESSAGE = "Signup is closed on this forge."; |
| 57 | 61 | |
| 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 | ||
| 58 | 65 | /** |
| 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. | |
| 63 | 71 | */ |
| 64 | 72 | export function signupClosed(app: App): boolean { |
| 65 | 73 | return getSignup(app.db) !== "open" && hasAnyUser(app.db); |
| 66 | 74 | } |
| 67 | 75 | |
| 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 | ||
| 68 | 115 | /** What anyone is told at a door that still offers a password-only sign-up. */ |
| 69 | 116 | export const PASSKEY_REQUIRED_MESSAGE = |
| 70 | 117 | "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( | ||
| 102 | 149 | // when every such account has a passkey (Settings → Passkeys shows who is |
| 103 | 150 | // left) and recovery without a password exists (#1618): then delete this |
| 104 | 151 | // 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); | |
| 106 | 154 | if (app.config.passkeyOnlySignup === true) return err("passkey_required"); |
| 107 | 155 | const secret = app.config.turnstileSecret; |
| 108 | 156 | const bootstrap = from.door === "terminal" && !hasAnyUser(app.db); |
| @@ -112,9 +160,15 @@ export async function signUp( | ||
| 112 | 160 | if (!(await verify(input.humanToken ?? "", from.address))) |
| 113 | 161 | return err("human_check"); |
| 114 | 162 | } |
| 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; | |
| 116 | 166 | 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); | |
| 118 | 172 | app.bus.append({ |
| 119 | 173 | kind: "user.created", |
| 120 | 174 | actorId: created.value.id, |
| @@ -136,6 +190,7 @@ export interface PasskeySignUpInput { | ||
| 136 | 190 | passkey: Credential; |
| 137 | 191 | passkeyName: string; |
| 138 | 192 | humanToken?: string; |
| 193 | invite?: string; | |
| 139 | 194 | } |
| 140 | 195 | |
| 141 | 196 | /** |
| @@ -150,7 +205,8 @@ export async function signUpWithPasskey( | ||
| 150 | 205 | input: PasskeySignUpInput, |
| 151 | 206 | from: { address?: string | undefined } = {}, |
| 152 | 207 | ): 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); | |
| 154 | 210 | const secret = app.config.turnstileSecret; |
| 155 | 211 | if (secret !== undefined) { |
| 156 | 212 | const verify = app.config.verifyHuman ?? turnstileVerifier(secret); |
| @@ -158,17 +214,24 @@ export async function signUpWithPasskey( | ||
| 158 | 214 | return err("human_check"); |
| 159 | 215 | } |
| 160 | 216 | if (findPasskey(app.db, input.passkey.id)) return err("passkey_taken"); |
| 217 | const claimed = claim(app, input.invite); | |
| 218 | if (!claimed.ok) return claimed; | |
| 161 | 219 | const created = await createUser(app.db, { |
| 162 | 220 | username: input.username, |
| 163 | 221 | email: input.email, |
| 164 | 222 | adminIfFirst: true, |
| 165 | 223 | }); |
| 166 | if (!created.ok) return created; | |
| 224 | if (!created.ok) { | |
| 225 | if (claimed.value !== undefined) releaseInvite(app.db, claimed.value); | |
| 226 | return created; | |
| 227 | } | |
| 167 | 228 | const kept = addPasskey(app.db, created.value.id, input.passkeyName, input.passkey); |
| 168 | 229 | if (!kept.ok) { |
| 169 | 230 | discardFreshUser(app.db, created.value.id); |
| 231 | if (claimed.value !== undefined) releaseInvite(app.db, claimed.value); | |
| 170 | 232 | return err("passkey_taken"); |
| 171 | 233 | } |
| 234 | inviteUsed(app, claimed.value, created.value); | |
| 172 | 235 | app.bus.append({ |
| 173 | 236 | kind: "user.created", |
| 174 | 237 | actorId: created.value.id, |
src/core/invites.ts +33 −1
| @@ -1,7 +1,7 @@ | ||
| 1 | 1 | /** |
| 2 | 2 | * Invite links: a secret handed out once, good for one signup, gone after a |
| 3 | 3 | * 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). | |
| 5 | 5 | */ |
| 6 | 6 | |
| 7 | 7 | import type { Database } from "bun:sqlite"; |
| @@ -85,3 +85,35 @@ export function revokeInvite( | ||
| 85 | 85 | if (changed === 0) return err("not_found"); |
| 86 | 86 | return ok(view(db.query<Row, [string]>("SELECT * FROM invite WHERE id = ?1").get(inviteId)!, now)); |
| 87 | 87 | } |
| 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 { | ||
| 156 | 156 | HUMAN_CHECK_MESSAGE, |
| 157 | 157 | PASSKEY_REQUIRED_MESSAGE, |
| 158 | 158 | signUp, |
| 159 | INVITE_REQUIRED_MESSAGE, | |
| 159 | 160 | SIGNUP_CLOSED_MESSAGE, |
| 160 | 161 | updateProfile, |
| 161 | 162 | } from "../actions/users.ts"; |
| @@ -1211,9 +1212,12 @@ export function apiRoutes(router: Router<Handler>): void { | ||
| 1211 | 1212 | email: str(input.email), |
| 1212 | 1213 | password: str(input.password), |
| 1213 | 1214 | humanToken: str(input.turnstile_token), |
| 1215 | invite: str(input.invite), | |
| 1214 | 1216 | }, |
| 1215 | 1217 | { address: clientAddress(ctx.request) }, |
| 1216 | 1218 | ); |
| 1219 | if (!created.ok && created.error === "invite_required") | |
| 1220 | return apiError("invite_required", 403, INVITE_REQUIRED_MESSAGE); | |
| 1217 | 1221 | if (!created.ok && created.error === "signup_closed") |
| 1218 | 1222 | return apiError("signup_closed", 403, SIGNUP_CLOSED_MESSAGE); |
| 1219 | 1223 | if (!created.ok && created.error === "passkey_required") |
src/main.ts +3 −1
| @@ -4,7 +4,7 @@ | ||
| 4 | 4 | * environment-only — a handful of variables, all with sane defaults. |
| 5 | 5 | */ |
| 6 | 6 | |
| 7 | import { BOOT_ACTOR, setSignup, signupFromEnv } from "./settings/signup.ts"; | |
| 7 | import { BOOT_ACTOR, seedSignup, setSignup, signupFromEnv } from "./settings/signup.ts"; | |
| 8 | 8 | import { startMemorySampler } from "./boards/memory.ts"; |
| 9 | 9 | import { startSampler } from "./boards/sampler.ts"; |
| 10 | 10 | import { sweepStanding } from "./crew/standing.ts"; |
| @@ -246,6 +246,8 @@ const app = createApp({ | ||
| 246 | 246 | loadFlags(app.db); |
| 247 | 247 | // FORGE_SIGNUP (checked in configProblem) sets who may sign up; kept like any change. |
| 248 | 248 | 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); | |
| 249 | 251 | if (bootSignup.ok && bootSignup.value !== null) |
| 250 | 252 | setSignup(app.db, bootSignup.value, BOOT_ACTOR); |
| 251 | 253 | const flagTimer = setInterval(() => flushFlagUses(app.db), 10_000); |
src/settings/signup.ts +16 −2
| @@ -1,13 +1,15 @@ | ||
| 1 | 1 | /** |
| 2 | 2 | * Who may make an account: `open`, `invite` or `closed`. Stored in |
| 3 | 3 | * `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`). | |
| 5 | 6 | * `/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. | |
| 7 | 8 | */ |
| 8 | 9 | |
| 9 | 10 | import type { Database } from "bun:sqlite"; |
| 10 | 11 | import { err, ok, type Result } from "../kernel/result.ts"; |
| 12 | import { hasAnyUser } from "../core/users.ts"; | |
| 11 | 13 | import { writeSetting } from "./limits.ts"; |
| 12 | 14 | |
| 13 | 15 | export const SIGNUP_MODES = ["open", "invite", "closed"] as const; |
| @@ -42,6 +44,18 @@ export function setSignup(db: Database, value: SignupMode, actorId: string): voi | ||
| 42 | 44 | writeSetting(db, STORE_KEY, value, from, value, actorId); |
| 43 | 45 | } |
| 44 | 46 | |
| 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 | ||
| 45 | 59 | /** `FORGE_SIGNUP` from the environment: unset is no opinion, a bad value is a message. */ |
| 46 | 60 | export function signupFromEnv(raw: string | undefined): Result<SignupMode | null, string> { |
| 47 | 61 | const s = (raw ?? "").trim(); |
src/tui/screens/common.ts +2 −1
| @@ -12,7 +12,7 @@ import type { Ctx, Screen } from "../app/app.ts"; | ||
| 12 | 12 | import { binding, type Binding } from "../app/keys.ts"; |
| 13 | 13 | import type { KeyEvent } from "../term/input.ts"; |
| 14 | 14 | 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"; | |
| 16 | 16 | import type { Session } from "../session.ts"; |
| 17 | 17 | import { G, Screen as Surface, type Rect } from "../term/screen.ts"; |
| 18 | 18 | import { style } from "../term/style.ts"; |
| @@ -818,6 +818,7 @@ const MESSAGES: Record<string, string> = { | ||
| 818 | 818 | not_member: NOT_A_MEMBER, |
| 819 | 819 | not_found: "not found", |
| 820 | 820 | signup_closed: SIGNUP_CLOSED_MESSAGE, |
| 821 | invite_required: INVITE_REQUIRED_MESSAGE, | |
| 821 | 822 | human_check: "we could not tell you are a person; sign up on the web page", |
| 822 | 823 | passkey_required: "new accounts sign up with a passkey and an email address: open the sign-up page in a browser", |
| 823 | 824 | unauthorized: "sign in first", |
src/web/pages/signup-passkey.ts +11 −5
| @@ -7,7 +7,7 @@ | ||
| 7 | 7 | */ |
| 8 | 8 | |
| 9 | 9 | 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"; | |
| 11 | 11 | import { createSession } from "../../core/sessions.ts"; |
| 12 | 12 | import { getUserByName } from "../../core/users.ts"; |
| 13 | 13 | import { isSafeName } from "../../git/guard.ts"; |
| @@ -31,6 +31,7 @@ const WORDS: Record<string, string> = { | ||
| 31 | 31 | human_check: HUMAN_CHECK_MESSAGE, |
| 32 | 32 | passkey_taken: "That passkey is already registered.", |
| 33 | 33 | signup_closed: SIGNUP_CLOSED_MESSAGE, |
| 34 | invite_required: INVITE_REQUIRED_MESSAGE, | |
| 34 | 35 | }; |
| 35 | 36 | |
| 36 | 37 | /** 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 | ||
| 41 | 42 | return undefined; |
| 42 | 43 | } |
| 43 | 44 | |
| 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 | ||
| 44 | 48 | function guard(ctx: Ctx): Response | undefined { |
| 45 | 49 | if (crossOrigin(ctx.request, ctx.url, ctx.app.log)) return refuse(403, "forbidden"); |
| 46 | 50 | const wait = signinAllowed(ctx, `signup:${clientAddress(ctx.request)}`); |
| @@ -53,7 +57,8 @@ function guard(ctx: Ctx): Response | undefined { | ||
| 53 | 57 | export async function signupOptions(ctx: Ctx): Promise<Response> { |
| 54 | 58 | const denied = guard(ctx); |
| 55 | 59 | 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)); | |
| 57 | 62 | const data = await boundedBody(ctx.request, STRANGER_MAX); |
| 58 | 63 | if (data === "too_large") return refuse(413, "payload too large"); |
| 59 | 64 | const username = str(data.username).trim(); |
| @@ -73,7 +78,8 @@ export async function signupOptions(ctx: Ctx): Promise<Response> { | ||
| 73 | 78 | export async function signupPasskey(ctx: Ctx): Promise<Response> { |
| 74 | 79 | const denied = guard(ctx); |
| 75 | 80 | 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)); | |
| 77 | 83 | const data = await boundedBody(ctx.request, STRANGER_MAX); |
| 78 | 84 | if (data === "too_large") return refuse(413, "payload too large"); |
| 79 | 85 | const username = str(data.username).trim(); |
| @@ -90,11 +96,11 @@ export async function signupPasskey(ctx: Ctx): Promise<Response> { | ||
| 90 | 96 | if (!made.ok) return refuse(400, "That passkey was not accepted."); |
| 91 | 97 | const created = await signUpWithPasskey( |
| 92 | 98 | 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) }, | |
| 94 | 100 | { address: clientAddress(ctx.request) }, |
| 95 | 101 | ); |
| 96 | 102 | 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."); | |
| 98 | 104 | const session = createSession(ctx.app.db, created.value.id); |
| 99 | 105 | return json( |
| 100 | 106 | { 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"; | ||
| 16 | 16 | import { verifyEmail } from "../../actions/verify.ts"; |
| 17 | 17 | import { STRANGER_MAX } from "../../http/limits.ts"; |
| 18 | 18 | 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"; | |
| 20 | 20 | import { accessAllows, listOrgsForUser, orgAccess } from "../../core/orgs.ts"; |
| 21 | 21 | import { listPins } from "../../core/pins.ts"; |
| 22 | 22 | import { getReposByIds } from "../../core/repos.ts"; |
| @@ -233,9 +233,12 @@ function authForm( | ||
| 233 | 233 | const values = o.values ?? {}; |
| 234 | 234 | const errors = o.errors ?? {}; |
| 235 | 235 | 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}`; | |
| 239 | 242 | // "Is this the first account?" is a `LIMIT 1` existence check, not a count |
| 240 | 243 | // of the whole user table — and the sign-in screen paints on every session. |
| 241 | 244 | const firstAccount = kind === "signup" && !hasAnyUser(ctx.app.db); |
| @@ -403,20 +406,24 @@ function siteKey(ctx: Ctx): string | undefined { | ||
| 403 | 406 | return turnstileSecret === undefined ? undefined : turnstileSiteKey; |
| 404 | 407 | } |
| 405 | 408 | |
| 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 { | |
| 408 | 414 | return page( |
| 409 | 415 | { |
| 410 | 416 | ctx, |
| 411 | 417 | 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>`, | |
| 413 | 419 | }, |
| 414 | 420 | 403, |
| 415 | 421 | ); |
| 416 | 422 | } |
| 417 | 423 | |
| 418 | 424 | 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); | |
| 420 | 427 | return page({ |
| 421 | 428 | ctx, |
| 422 | 429 | title: "Sign up", |
| @@ -588,11 +595,13 @@ export async function signupSubmit(ctx: Ctx): Promise<Response> { | ||
| 588 | 595 | email, |
| 589 | 596 | password: field(form, "password"), |
| 590 | 597 | humanToken: field(form, "cf-turnstile-response"), |
| 598 | invite: inviteOf(ctx), | |
| 591 | 599 | }, |
| 592 | 600 | { address: clientAddress(ctx.request) }, |
| 593 | 601 | ); |
| 594 | 602 | 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); | |
| 596 | 605 | const errors: AuthErrors = { |
| 597 | 606 | invalid_username: { |
| 598 | 607 | username: "Usernames are letters, digits, dots, dashes.", |
src/web/passkey-client.ts +1 −1
| @@ -99,7 +99,7 @@ export const passkeyJs = /* js */ ` | ||
| 99 | 99 | wire('passkey-signup', function () { |
| 100 | 100 | function val(n) { var el = doc.querySelector('[name=' + n + ']'); return el ? el.value : ''; } |
| 101 | 101 | 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) { | |
| 103 | 103 | return navigator.credentials.create({ publicKey: { |
| 104 | 104 | challenge: bytes(o.challenge), |
| 105 | 105 | 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", () => { | ||
| 57 | 57 | mode(closed); |
| 58 | 58 | const page = await fetch(`${base}/signup`); |
| 59 | 59 | 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"); | |
| 61 | 61 | expect(html).not.toContain('name="password"'); |
| 62 | 62 | |
| 63 | 63 | const res = await post(`via-api-${closed}`); |
| 64 | 64 | expect(res.status).toBe(403); |
| 65 | 65 | 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"); | |
| 68 | 68 | expect(getUserByName(app.db, `via-api-${closed}`)).toBeUndefined(); |
| 69 | 69 | |
| 70 | 70 | expect((await me(`via-edge-${closed}`)).status).toBe(401); |
test/signup.test.ts +3 −3
| @@ -220,7 +220,7 @@ describe("signup closed (#2166)", () => { | ||
| 220 | 220 | const page = await fetch(`${servers.url}/signup`); |
| 221 | 221 | const text = await page.text(); |
| 222 | 222 | 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"); | |
| 224 | 224 | const main = text.slice(text.indexOf("<main"), text.indexOf("</main>")); |
| 225 | 225 | expect(main).not.toContain("<form"); |
| 226 | 226 | expect(main).not.toContain("<input"); |
| @@ -229,7 +229,7 @@ describe("signup closed (#2166)", () => { | ||
| 229 | 229 | const res = await post(body); |
| 230 | 230 | expect(res.status).toBe(403); |
| 231 | 231 | 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"); | |
| 233 | 233 | expect(err.message.length).toBeGreaterThan(0); |
| 234 | 234 | expect(getUserByName(app.db, body.username)).toBeUndefined(); |
| 235 | 235 | |
| @@ -246,7 +246,7 @@ describe("signup closed (#2166)", () => { | ||
| 246 | 246 | body: JSON.stringify({ username: `pk${mode}`, email: `pk${mode}@forge.local` }), |
| 247 | 247 | }); |
| 248 | 248 | expect(opts.status).toBe(403); |
| 249 | expect(await opts.text()).toContain("closed"); | |
| 249 | expect(await opts.text()).toContain(mode === "closed" ? "closed" : "invite link"); | |
| 250 | 250 | const pk = await fetch(`${servers.url}/signup/passkey`, { |
| 251 | 251 | method: "POST", |
| 252 | 252 | headers: { "content-type": "application/json", origin: servers.url }, |
new above
offline