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

Opening an invite link signs the person in, proves the account and applies the bundle, in every sign-up mode including closed #18520

opened this

Merged 2h 19m ago, live in production

mason/forge:mason/18454-opening-an-invite-link-signs-the-person → main 0 commits fork

  • Merged. mason/18454-opening-an-invite-link-signs-the-person was merged into main as f42bd09.

Review

Sign in to review this change.
54 files changed +603 −234
docs/CREW.md +1 −1
@@ -347,7 +347,7 @@ one the provider rests hands its runs to the other until the reset.
347347 **Crew subscriptions in the terminal.** A forge admin presses Ctrl+K and picks **Crew subscriptions**: each Claude account with its kind, what it pays for, budget, spend and whether it rests (never a token). `w` wakes the selected resting one (an awake one is left alone and said so), `b` asks for dollars, or `none`, and sets its whole-life budget. `a` adds an account: a name, then the token typed masked (drawn as dots, handed to the core once, never shown or logged), then an optional API base; a refusal is MCP `subscription_add`'s sentence, word for word. `D` shows that the subscription and its grants go and that past runs keep it in their history, and removes it only after a confirm that defaults to Cancel. Only a forge admin who is a person is offered either key; an agent sees neither and changes nothing. Granting an added account to a repository or organization stays on the web page and in MCP. The rules are MCP `subscriptions`, `subscription_wake` and `subscription_budget`'s, from `core/subscriptions.ts`; a budget set by whoever made the forge can be lowered, never raised or cleared.
348348 **Where you are signed in.** Anyone signed in sees their own browsers and tokens, never a secret, at `/settings`, over the API (`GET /api/v1/users/:username/signins`), over MCP (`sessions`), and in the terminal as the **Signed in** command (`src/tui/screens/signins.ts`; a visitor has no such command). The terminal lists this terminal's SSH key first, marked "this one", then each browser (`web browser` and the tail of its session id, so two read apart) and each token (name and scope), with when it was last seen and since when. `d` on a browser asks to confirm (Keep is the default) and signs it out through the same `endAccountSession` as Settings and MCP, so its cookie reads as signed out at once. `d` on a token asks `Revoke <name> (<scope>)?` (Keep is the default) and revokes it through the same `deleteToken` action as Settings and the API, so it stops working at once and open pages hear `token.deleted`. `d` does not end this terminal (disconnect, or remove its key in Settings → SSH keys); it says so. No browser row is marked as the current one there: the terminal holds no browser cookie.
349349
350 **Invites.** A forge admin who is a person mints a single-use invite link with `POST /api/v1/admin/invites` (`{"days": 14}`, 1 to 30, 7 by default); the response carries the link once and only its hash is kept. `GET /api/v1/admin/invites` lists them (open, used, revoked, expired) without tokens, and `DELETE /api/v1/admin/invites/:id` revokes one. Minting, revoking and using a link are events (`invite.minted`, `invite.revoked`, `invite.used`; the last names the invite and the account it let in, never the token). The same is the **Invite links** card on `/admin/limits` (a form with expiry days, 1 to 30; the new link is shown once, with a copy button; an open link has a Revoke button) and the terminal's **Invite links** command (`m` makes one and prints the link once, `x` revokes the selected open one; its top line says who may sign up, and `s`, offered only to that admin, picks open, invite or closed, shows from → to and changes it after a confirm, as MCP `signup` does). Over MCP, the `mint_invite` tool (`{days?}`, an admin token, a forge admin who is a person) answers with the same link, and the `invites` tool (`{action: "list"|"revoke", id?}`, the same person admin and admin token, for both actions) lists them without links or revokes one. While signup is `invite`, the link opens the door once: `/signup?invite=…` (the form and the passkey door) or `invite` in the `POST /api/v1/users` body. In the terminal, with signup = invite the create-account screen has a fourth, masked **Invite** field that takes the token (not the whole link); a blank one is asked for, and a bad one is refused with the same sentence as `/signup`. The account and the invite's use are one write, so two sign-ups with one link make one account; a used, revoked or expired link, or any link while signup is `closed`, makes none. While signup is `open`, a link is not spent.
350 **Invites.** A forge admin who is a person mints a single-use invite link with `POST /api/v1/admin/invites` (every link lives 72 hours; `{"org"?, "bundle"?, …}`); the response carries the link once and only its hash is kept. `GET /api/v1/admin/invites` lists them (open, used, revoked, expired) without tokens, and `DELETE /api/v1/admin/invites/:id` revokes one. Minting, revoking and using a link are events (`invite.minted`, `invite.revoked`, `invite.used`; the last names the invite and the account it let in, never the token). The same is the **Invite links** card on `/admin/limits` (a form; the new link is shown once, with a copy button; an open link has a Revoke button) and the terminal's **Invite links** command (`m` picks the bundle, makes one and prints the link once, `x` revokes the selected open one; its top line says who may sign up, and `s`, offered only to that admin, picks open, invite or closed, shows from → to and changes it after a confirm, as MCP `signup` does). Over MCP, the `mint_invite` tool (`{org?, bundle?, …}`, an admin token, a forge admin who is a person) answers with the same link, and the `invites` tool (`{action: "list"|"revoke", id?}`, the same person admin and admin token, for both actions) lists them without links or revokes one. The link opens the door once in every signup mode, `closed` included: `/signup?invite=…` shows one button (Join) that makes the account, signs the person in, proves it with the invite as the proof and applies the bundle (`docs/features/invite-link.md`); `invite` in the `POST /api/v1/users` body and the passkey door spend it too. In the terminal, with signup = invite the create-account screen has a fourth, masked **Invite** field that takes the token (not the whole link); a blank one is asked for, and a bad one is refused with the same sentence as `/signup`. The account and the invite's use are one write, so two sign-ups with one link make one account; a used, revoked or expired link makes none.
351351
352352 **Bulk actions in the terminal.** A person (never an agent) presses Ctrl+K and picks **Bulk actions** (`src/tui/screens/bulk.ts`): their own last 30 bulk actions, newest first, as `GET /api/v1/fleet/ops` lists them, each with its action, how many rows changed, how many were refused, whether `u` still undoes it, and when. `j`/`k` move; `u` undoes the selected one while it is inside its day, through `undoFleetOp` (`undoAsksBulk` for a bulk action on asks), and toasts the outcome; an undone, expired or non-reversible receipt, or an undo itself, says why and changes nothing. Enter opens the operation's rows: each row's before → after, and each refusal's reason. Another person's operations are never listed. An agent is not offered the screen and, reached another way, sees "Not available".
353353
docs/features/invite-bundle.md +1 −1
@@ -9,4 +9,4 @@ Mint an invite with a bundle: `POST /api/v1/admin/invites {"bundle":"host","mach
99 - **Host**: a guest who makes and runs their own containers on one machine, up to a cap. The machine is one of those the forge offers (running, not a game box); with none, Host is disabled and the page says why.
1010 - **Build**: a member: repositories, apps and a crew.
1111
12 An unknown bundle, a machine not on the list or a cap that is not a positive whole number is refused (422). The bundle is stored with the invite and listed with its line; invites made before read as Use. The grants each stands for are in `src/core/bundles.ts`; applying them is a later step. In the terminal, `m` on Invite links asks for the days, then the bundle; Host goes on to the machine, then the two caps, and says the same refusals.
12 An unknown bundle, a machine not on the list or a cap that is not a positive whole number is refused (422). The bundle is stored with the invite and listed with its line; invites made before read as Use. The grants each stands for are in `src/core/bundles.ts`; they are applied when the invite is spent (`docs/features/invite-link.md`). In the terminal, `m` on Invite links picks the bundle; Host goes on to the machine, then the two caps, and says the same refusals.
src/actions/infra.ts +6
@@ -200,6 +200,12 @@ export function infraOf(app: App, actor: User | undefined, now = new Date()): Re
200200 return who.ok ? ok(reckon(app, now).view) : who;
201201 }
202202
203 /**
204 * The view with no one asking: for a check the forge makes itself (a Host invite's machine), never
205 * shown.
206 */
207 export const offeredView = (app: App, now = new Date()): InfraView => reckon(app, now).view;
208
203209 /**
204210 * One machine by name, running, ended or a dead row, with its billing sentence: `infra show`'s
205211 * answer to "does test1 still cost anything?" when it is asked by name. Undefined when no row of
src/actions/invites.ts +14 −12
@@ -12,8 +12,6 @@ import {
1212 listInvites,
1313 mintInvite,
1414 mintRepoInvite,
15 MAX_DAYS,
16 parseDays,
1715 redeemInvite,
1816 takeUpInvite,
1917 removeContributor,
@@ -29,11 +27,11 @@ import { getUserByName } from "../core/users.ts";
2927 import { requireRepoAdmin, type AccessError } from "./access.ts";
3028 import { getOrg } from "../core/orgs.ts";
3129 import { BUNDLES, HOST_WORDS, parseHost, type Bundle } from "../core/bundles.ts";
32 import { infraOf } from "./infra.ts";
30 import { infraOf, offeredView, type InfraView } from "./infra.ts";
3331 import { err, ok, type Result } from "../kernel/result.ts";
3432 import type { User } from "../core/users.ts";
3533
36 type Error = "not_found" | "invalid_days" | "unknown_org" | "invalid_bundle" | "no_machine" | "invalid_machine" | "invalid_cap";
34 type Error = "not_found" | "unknown_org" | "invalid_bundle" | "no_machine" | "invalid_machine" | "invalid_cap";
3735
3836 /** What Host is given, as a door sends it: plain values, read by `parseHost`. */
3937 export interface BundleInput {
@@ -54,8 +52,6 @@ export const BUNDLE_WORDS: Record<"invalid_bundle" | "no_machine" | "invalid_mac
5452 /** A refusal of `mint` in words: every door says the same. */
5553 export function mintRefusal(error: Error): string {
5654 switch (error) {
57 case "invalid_days":
58 return `Days is a whole number from 1 to ${MAX_DAYS}.`;
5955 case "unknown_org":
6056 return "No organization by that name.";
6157 case "not_found":
@@ -68,10 +64,18 @@ export function mintRefusal(error: Error): string {
6864 /** The machines this forge can offer a Host: those running, by name; admin's to read. */
6965 export function hostMachines(app: App, actor: User | undefined): string[] {
7066 const v = infraOf(app, actor);
71 if (!v.ok) return [];
72 return v.value.groups.flatMap((g) => g.machines).filter((m) => m.state === "online" && m.game !== true).map((m) => m.name);
67 return v.ok ? machinesIn(v.value) : [];
7368 }
7469
70 const machinesIn = (view: InfraView): string[] =>
71 view.groups.flatMap((g) => g.machines).filter((m) => m.state === "online" && m.game !== true).map((m) => m.name);
72
73 /**
74 * The same list with no one asking: for the check a redeemed Host invite makes, which reads, never
75 * shows.
76 */
77 export const machinesOffered = (app: App): string[] => machinesIn(offeredView(app));
78
7579 const admin = (actor: User | undefined): actor is User =>
7680 actor !== undefined && actor.isAdmin && actor.kind === "user";
7781
@@ -83,10 +87,8 @@ export const inviteLink = (origin: string, token: string): string =>
8387 * `org` names the organization the invite brings its person into; absent or empty is a plain
8488 * invite.
8589 */
86 export function mint(app: App, actor: User | undefined, days: unknown, org?: unknown, choice: BundleInput = {}): Result<{ invite: Invite; token: string }, Error> {
90 export function mint(app: App, actor: User | undefined, org?: unknown, choice: BundleInput = {}): Result<{ invite: Invite; token: string }, Error> {
8791 if (!admin(actor)) return err("not_found");
88 const n = parseDays(days);
89 if (!n.ok) return n;
9092 const name = typeof org === "string" ? org.trim() : "";
9193 if (org !== undefined && org !== null && typeof org !== "string") return err("unknown_org");
9294 const target = name === "" ? undefined : getOrg(app.db, name);
@@ -100,7 +102,7 @@ export function mint(app: App, actor: User | undefined, days: unknown, org?: unk
100102 if (!h.ok) return err(h.error === "noMachine" ? "no_machine" : h.error === "badMachine" ? "invalid_machine" : "invalid_cap");
101103 host = h.value;
102104 }
103 const made = mintInvite(app.db, actor.id, n.value, Date.now(), target?.id ?? null, bundle, host);
105 const made = mintInvite(app.db, actor.id, Date.now(), target?.id ?? null, bundle, host);
104106 app.bus.append({
105107 kind: "invite.minted",
106108 actorId: actor.id,
src/actions/spend_words.ts −1
@@ -5,5 +5,4 @@
55 export const SPEND_WORDS = {
66 usdPerMonth: "usdPerMonth is from 0.01 to 10000 dollars",
77 ceilings: "dailyUsd and perRunUsd are each from 0.01 to 10000 dollars, or both null",
8 inviteDays: "days is a whole number from 1 to 30",
98 } as const;
src/actions/users.ts +4 −1
@@ -27,6 +27,7 @@ import {
2727 import { mintViaToken, VIA_TOKEN_MAX_MS } from "../core/via_token.ts";
2828 import { id } from "../kernel/id.ts";
2929 import { contributedSince, inviteSpentBy } from "../core/invites.ts";
30 import { machinesOffered } from "./invites.ts";
3031 import { welcomeInvited } from "./invite_welcome.ts";
3132 import { cleanAsk, NOTE_MAX, SOURCE_MAX } from "../core/requests.ts";
3233 import {
@@ -176,6 +177,7 @@ export async function signUp(
176177 origin: "signup",
177178 slot: from.slot,
178179 invite: from.invite,
180 ...(from.invite === undefined ? {} : { offeredMachines: machinesOffered(app) }),
179181 ask: { note: cleanAsk(input.note, NOTE_MAX), source: cleanAsk(input.source, SOURCE_MAX) },
180182 });
181183 if (!created.ok) return created;
@@ -237,6 +239,7 @@ export async function signUpWithPasskey(
237239 origin: "passkey",
238240 slot: from.slot,
239241 invite: from.invite,
242 ...(from.invite === undefined ? {} : { offeredMachines: machinesOffered(app) }),
240243 ask: { note: cleanAsk(input.note, NOTE_MAX), source: cleanAsk(input.source, SOURCE_MAX) },
241244 });
242245 if (!created.ok) return created;
@@ -264,7 +267,7 @@ export async function signUpWithPasskey(
264267 }
265268
266269 /** Using an invite link is an event: the invite's id and who it let in, never its token. */
267 function auditInvite(app: App, userId: string): void {
270 export function auditInvite(app: App, userId: string): void {
268271 const inviteId = inviteSpentBy(app.db, userId);
269272 if (inviteId === undefined) return;
270273 app.bus.append({ kind: "invite.used", actorId: userId, payload: { id: inviteId } });
src/contract/openapi/routes/postApiV1AdminInvites.ts +2 −2
@@ -10,7 +10,7 @@ export const route: Route = {
1010 auth: true,
1111 role: "admin",
1212 status: 201,
13 body: { days: "integer" },
14 refusals: { invalid: "`days` is not a whole number from 1 to 30 (422)" },
13 body: { bundle: "string" },
14 refusals: { invalid: "the organization or the bundle is not one this forge offers (422)" },
1515 refuses: [404],
1616 };
src/core/account_purge.ts +3
@@ -56,6 +56,9 @@ export const COVERED: Readonly<Record<string, Coverage>> = {
5656 // A saved /traces search is private to the person who named it; it goes with them.
5757 "trace_saved.user_id": DELETE,
5858 "access_link.created_by": FORMER,
59 // Who vouched for an email address (the admin whose invite link proved it): the proof stays, as
60 // the former account.
61 "connection.proof_by": FORMER,
5962 // The admin who made an integration's lookup key: the key stays, as the former account's.
6063 "connection_lookup_key.created_by": FORMER,
6164 // Who asked a game box to run a command: the record keeps it, as the former account.
src/core/bundle_grants.ts added +41
@@ -0,0 +1,41 @@
1 /**
2 * What an invite's bundle gives the person it lets in (`core/bundles.ts` says what each bundle is).
3 * Applied in the transaction that spends the invite and makes the account, so a person is never in
4 * without their grants nor granted without being in. Use is a guest, which every new account
5 * already is. Build makes a member, by the invite's maker. Host keeps one `host_grant` row: the
6 * machine and caps picked at mint. A Host invite whose machine this forge no longer offers grants
7 * nothing (`hostGone`, asked before anything is written).
8 */
9
10 import type { Database } from "bun:sqlite";
11 import { inviteByToken } from "./invites.ts";
12 import { setMember } from "./roles.ts";
13
14 /** Whether the invite `token` names is a Host invite for a machine not among those offered now. */
15 export function hostGone(db: Database, token: string, offered: readonly string[] | undefined): boolean {
16 const host = inviteByToken(db, token)?.invite.host ?? null;
17 return host !== null && !(offered ?? []).includes(host.machine);
18 }
19
20 /** After `redeemInvite` and the account's insert, in their transaction: the bundle's grants. */
21 export function applyBundle(db: Database, token: string, userId: string, now: number = Date.now()): void {
22 const named = inviteByToken(db, token, now);
23 if (named === undefined) return;
24 const { invite } = named;
25 const at = new Date(now);
26 if (invite.bundle === "build") setMember(db, userId, true, invite.createdBy, at);
27 if (invite.bundle === "host" && invite.host !== null)
28 db.query(
29 "INSERT OR REPLACE INTO host_grant (user_id, machine, containers, memory_mb, invite_id, at) VALUES (?1, ?2, ?3, ?4, ?5, ?6)",
30 ).run(userId, invite.host.machine, invite.host.containers, invite.host.memoryMb, invite.id, at.toISOString());
31 }
32
33 /** The machine and caps a Host invite gave this person, or undefined when it gave none. */
34 export function hostGrantOf(db: Database, userId: string): { machine: string; containers: number; memoryMb: number } | undefined {
35 const row = db
36 .query<{ machine: string; containers: number; memory_mb: number }, [string]>(
37 "SELECT machine, containers, memory_mb FROM host_grant WHERE user_id = ?1",
38 )
39 .get(userId);
40 return row === null ? undefined : { machine: row.machine, containers: row.containers, memoryMb: row.memory_mb };
41 }
src/core/bundles.ts +1
@@ -55,6 +55,7 @@ export interface HostChoice {
5555 export const HOST_WORDS = {
5656 noMachine: "Host needs a machine this forge can offer, and it has none: connect a cloud account and build one first.",
5757 badMachine: "That machine is not one this forge offers.",
58 gone: "The machine this invite was for is no longer offered, so it grants nothing. Ask whoever sent it for a new one.",
5859 badCap: "Containers and memory are each a positive whole number.",
5960 } as const;
6061
src/core/grants_view.ts +1
@@ -85,6 +85,7 @@ const MAPPINGS: readonly Mapping[] = [
8585 { table: "team_member", principalKind: text("user"), principalId: "user_id", action: "role", resourceKind: text("team"), resourceId: "team_id", account: "user_id", who: OR(NAME("user_id"), "user_id"), on: OR(TEAM(`${NAME("t.org_id")} || '/' || t.name`), "team_id"), href: OR(TEAM(`'/' || ${NAME("t.org_id")} || '/-/teams/' || t.id`), text("/settings")) },
8686 { table: "app_member", principalKind: text("user"), principalId: "user_id", action: text("enter"), resourceKind: text("app"), resourceId: "app_id", by: "added_by", at: "added_at", account: "user_id", who: OR(NAME("user_id"), "user_id"), on: OR(APP("app_id"), "app_id"), href: OR(`'/' || ${APP("app_id")} || '/settings'`, text("/settings")) },
8787 { table: "game_grant", principalKind: text("user"), principalId: "user_id", action: "role", resourceKind: text("game box"), resourceId: "box_id || CASE WHEN service = '' THEN '' ELSE '/' || service END", account: "user_id", who: OR(NAME("user_id"), "user_id"), on: `COALESCE((SELECT name FROM game_box WHERE id = box_id), box_id) || CASE WHEN service = '' THEN '' ELSE '/' || service END`, href: text("/games") },
88 { table: "host_grant", principalKind: text("user"), principalId: "user_id", action: "'host up to ' || containers || ' containers, ' || memory_mb || ' MB'", resourceKind: text("machine"), resourceId: "machine", at: "at", account: "user_id", who: OR(NAME("user_id"), "user_id"), on: "machine", href: text("/settings/people") },
8889 { table: "model_grant", principalKind: text("user"), principalId: "user_id", action: "'use models, $' || printf('%g', usd_per_month) || ' a month'", resourceKind: text("forge"), resourceId: "''", by: "granted_by", at: "granted_at", account: "user_id", who: OR(NAME("user_id"), "user_id"), on: text("the forge''s models"), href: text("/settings/people") },
8990 { table: "subscription_grant", principalKind: "CASE WHEN agent_id = '' THEN 'scope' ELSE 'agent' END", principalId: "CASE WHEN agent_id = '' THEN scope_id ELSE agent_id END", action: text("spend"), resourceKind: text("subscription"), resourceId: "subscription_id", account: "NULLIF(agent_id, '')", who: `CASE WHEN agent_id = '' THEN COALESCE(${REPO("scope_id")}, '@' || ${NAME("scope_id")}, 'a place that is gone') ELSE COALESCE(${NAME("agent_id")}, agent_id) END`, on: OR("(SELECT name FROM subscription WHERE id = subscription_id)", "subscription_id"), href: text("/settings/subscriptions") },
9091 { table: "secret_grant", principalKind: text("repo"), principalId: "repo_id", action: text("read secret"), resourceKind: "scope || ' secret'", resourceId: "CASE WHEN scope_id = '' THEN name ELSE scope_id || '/' || name END", by: "granted_by", at: "granted_at", who: OR(REPO("repo_id"), "repo_id"), on: "name", href: text("/settings/secrets") },
src/core/invites.ts +13 −16
@@ -2,9 +2,10 @@
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
44 * give a link back, and a token is found by its hash: nothing compares the
5 * secret itself. While signup is `invite`, a stranger's signup with an open
6 * invite is let in (`newAccountsClosed` in `core/users.ts`), and the invite is
7 * spent in the same transaction as the account (`redeemInvite`).
5 * secret itself. In every signup mode, `invite` and `closed` included, a
6 * stranger with an open invite is let in (`newAccountsClosed` in
7 * `core/users.ts`), and the invite is spent in the same transaction as the
8 * account (`redeemInvite`), which also applies its bundle (`core/bundle_grants.ts`).
89 */
910
1011 import type { Database } from "bun:sqlite";
@@ -13,9 +14,12 @@ import { id, secret } from "../kernel/id.ts";
1314 import { err, ok, type Result } from "../kernel/result.ts";
1415 import { bundleOf, type Bundle, type HostChoice } from "./bundles.ts";
1516
16 export const DEFAULT_DAYS = 7;
17 export const MAX_DAYS = 30;
18 const DAY = 86_400_000;
17 /**
18 * How long an invite link lives: 72 hours, the one life every link has. Nothing offers a longer
19 * one.
20 */
21 export const INVITE_HOURS = 72;
22 const LIFE_MS = INVITE_HOURS * 3_600_000;
1923
2024 export type InviteState = "open" | "used" | "revoked" | "expired";
2125
@@ -79,17 +83,10 @@ const view = (r: Row, now: number): Invite => ({
7983 : { machine: r.host_machine, containers: r.host_containers, memoryMb: r.host_memory_mb },
8084 });
8185
82 /** A whole number of days from 1 to 30, or the default when absent. */
83 export function parseDays(raw: unknown): Result<number, "invalid_days"> {
84 if (raw === undefined || raw === null) return ok(DEFAULT_DAYS);
85 return typeof raw === "number" && Number.isInteger(raw) && raw >= 1 && raw <= MAX_DAYS ? ok(raw) : err("invalid_days");
86 }
87
8886 /** The token is returned here and nowhere else. */
8987 export function mintInvite(
9088 db: Database,
9189 createdBy: string,
92 days: number = DEFAULT_DAYS,
9390 now: number = Date.now(),
9491 /** The id of the organization the invite brings its person into. */
9592 orgId: string | null = null,
@@ -105,7 +102,7 @@ export function mintInvite(
105102 sha256(token),
106103 createdBy,
107104 new Date(now).toISOString(),
108 new Date(now + days * DAY).toISOString(),
105 new Date(now + LIFE_MS).toISOString(),
109106 orgId,
110107 bundle,
111108 host?.machine ?? null,
@@ -216,7 +213,7 @@ const repoView = (r: Row, now: number): RepoInvite => {
216213 };
217214
218215 /**
219 * A single-use link to work on one repository as a contributor, `DEFAULT_DAYS` days, the token's
216 * A single-use link to work on one repository as a contributor, 72 hours, the token's
220217 * hash alone kept. Where the forge asks for an invite to sign up, it opens that door for its
221218 * holder too. The token is returned here and nowhere else.
222219 */
@@ -230,7 +227,7 @@ export function mintRepoInvite(
230227 const inviteId = id(now);
231228 db.query(
232229 "INSERT INTO invite (id, token_hash, created_by, created_at, expires_at, repo_id) VALUES (?1, ?2, ?3, ?4, ?5, ?6)",
233 ).run(inviteId, sha256(token), createdBy, new Date(now).toISOString(), new Date(now + DEFAULT_DAYS * DAY).toISOString(), repoId);
230 ).run(inviteId, sha256(token), createdBy, new Date(now).toISOString(), new Date(now + LIFE_MS).toISOString(), repoId);
234231 const row = db.query<Row, [string]>(`${SELECT} WHERE invite.id = ?1`).get(inviteId)!;
235232 return { invite: repoView(row, now), token };
236233 }
src/core/users.ts +39 −6
@@ -13,7 +13,8 @@ import { err, ok, type Result } from "../kernel/result.ts";
1313 import { admitSignin } from "./signin-window.ts";
1414 import { waitingCount, WAITING_CAP } from "./requests.ts";
1515 import { getSignup, type SignupMode } from "../settings/signup.ts";
16 import { inviteOpen, redeemInvite, reopenInvite, takeUpInvite } from "./invites.ts";
16 import { applyBundle, hostGone } from "./bundle_grants.ts";
17 import { inviteByToken, inviteOpen, redeemInvite, reopenInvite, takeUpInvite } from "./invites.ts";
1718 import type { SignupSlot } from "../actions/signup-window.ts";
1819
1920 export interface User {
@@ -116,7 +117,12 @@ export type CreateUserError =
116117 | "email_taken"
117118 | "weak_password"
118119 | "password_too_long"
119 | "signup_closed";
120 | "signup_closed"
121 /**
122 * A Host invite whose machine this forge no longer offers: nothing is granted, the invite stays
123 * open.
124 */
125 | "host_gone";
120126
121127 /**
122128 * Where a new account comes from — said by every caller, because this is the
@@ -160,6 +166,10 @@ export type AccountOrigin =
160166 ask?: { note: string; source: string } | undefined;
161167 }
162168 | { origin: "edge" }
169 /**
170 * The one-link sign-in: the invite's token is the whole credential (`actions/invite_link.ts`).
171 */
172 | { origin: "invite"; invite: string }
163173 | { origin: Exclude<ExemptOrigin, AdminOrigin> }
164174 | ({ origin: AdminOrigin } & AdminFields);
165175
@@ -200,9 +210,9 @@ function inviteNeeded(db: Database): boolean {
200210 export function accountsClosedIn(db: Database, mode: SignupMode, invite?: string): boolean {
201211 // In `request` the door shuts once the Waiting list is full, for anyone an open invite does not vouch for.
202212 if (mode === "request") return waitingCount(db) >= WAITING_CAP && !(invite !== undefined && inviteOpen(db, invite));
203 // Open lets anyone in; invite and closed need an invite, and only invite takes one.
213 // Open lets anyone in; invite and closed need an invite, and a live one opens either.
204214 if (mode !== "invite" && mode !== "closed") return false;
205 return !(mode === "invite" && invite !== undefined && inviteOpen(db, invite));
215 return !(invite !== undefined && inviteOpen(db, invite));
206216 }
207217
208218 interface CreateUserFields {
@@ -244,6 +254,11 @@ interface CreateUserFields {
244254 * Every other protected name still does.
245255 */
246256 reservedSelf?: string;
257 /**
258 * The machines this forge offers a Host now, for an invite that names one: a Host invite whose
259 * machine is not among them grants nothing (`host_gone`). Absent, none is offered.
260 */
261 offeredMachines?: readonly string[];
247262 }
248263
249264 /**
@@ -280,10 +295,17 @@ function admission(db: Database, input: AccountOrigin): Admission {
280295 return { admitted: true, spend: input.invite, request: "none" };
281296 return waitingCount(db) >= WAITING_CAP ? REFUSED : { admitted: true, spend: undefined, request: "waiting" };
282297 }
283 if (!inviteNeeded(db)) return ADMITTED;
298 // Open, a live invite is still spent: its bundle is what the person came for.
299 if (!inviteNeeded(db))
300 return input.invite !== undefined && inviteOpen(db, input.invite)
301 ? { admitted: true, spend: input.invite, request: "none" }
302 : ADMITTED;
284303 return newAccountsClosed(db, input.invite) || input.invite === undefined
285304 ? REFUSED
286305 : { admitted: true, spend: input.invite, request: "none" };
306 case "invite":
307 // The invite link itself: a live one opens the door in every mode, a dead one in none.
308 return inviteOpen(db, input.invite) ? { admitted: true, spend: input.invite, request: "none" } : REFUSED;
287309 case "edge":
288310 return newAccountsClosed(db) ? REFUSED : ADMITTED;
289311 case "claim":
@@ -321,6 +343,7 @@ export async function createUser(
321343 ): Promise<Result<User, CreateUserError>> {
322344 const admitted = admission(db, input);
323345 if (!admitted.admitted) return err("signup_closed");
346 if (admitted.spend !== undefined && hostGone(db, admitted.spend, input.offeredMachines)) return err("host_gone");
324347 const admin = adminOf(input);
325348 if (!isSafeName(input.username)) return err("invalid_username");
326349 const agent = input.agent === true;
@@ -385,7 +408,15 @@ export async function createUser(
385408 admin.adminIfFirst ? 1 : 0,
386409 agent ? 1 : 0,
387410 );
388 if (invite !== undefined) takeUpInvite(db, invite, userId);
411 if (invite !== undefined) {
412 takeUpInvite(db, invite, userId);
413 applyBundle(db, invite, userId);
414 // The one link is its own proof: the invite's maker vouched, and no mail is sent.
415 if (input.origin === "invite") {
416 const by = inviteByToken(db, invite)?.invite.createdBy ?? userId;
417 markVerified(db, userId, new Date().toISOString(), { by, how: "invite" });
418 }
419 }
389420 // A stranger's account keeps its ask, in the same write, waiting until allowed.
390421 if (admitted.request === "waiting") {
391422 const at = new Date().toISOString();
@@ -411,6 +442,8 @@ export async function createUser(
411442 }
412443 // Every person gets a row: proven when the caller vouches, else not yet.
413444 if (!agent) {
445 // The one link proved itself in the transaction above.
446 if (input.origin === "invite") return ok(getUserById(db, userId)!);
414447 if (input.trusted === true) markVerified(db, userId, new Date().toISOString());
415448 else markUnproven(db, userId);
416449 }
src/core/verify.ts +12 −4
@@ -48,7 +48,13 @@ export function markUnproven(db: Database, userId: string): void {
4848 * proof by the account that holds the address outranks an older one another
4949 * account kept as an extra connection, which is unproven.
5050 */
51 export function markVerified(db: Database, userId: string, at: string): void {
51 export function markVerified(
52 db: Database,
53 userId: string,
54 at: string,
55 /** Who vouched and how, when it was not a link followed: an invite's maker, `invite`. */
56 proof?: { readonly by: string; readonly how: "invite" },
57 ): void {
5258 db.transaction(() => {
5359 db.query(
5460 `INSERT INTO email_check (user_id) VALUES (?1)
@@ -60,12 +66,14 @@ export function markVerified(db: Database, userId: string, at: string): void {
6066 AND ident = (SELECT lower(email) FROM user WHERE id = ?1)`,
6167 ).run(userId);
6268 db.query(
63 `INSERT INTO connection (id, user_id, kind, ident, proven_at, created_at)
64 SELECT ?2, id, 'email', lower(email), ?3, ?3 FROM user WHERE id = ?1
69 `INSERT INTO connection (id, user_id, kind, ident, proven_at, created_at, proof_by, proof_how)
70 SELECT ?2, id, 'email', lower(email), ?3, ?3, ?4, ?5 FROM user WHERE id = ?1
6571 ON CONFLICT(user_id, kind, ident) DO UPDATE SET
72 proof_by = CASE WHEN connection.proven_at IS NULL THEN excluded.proof_by ELSE connection.proof_by END,
73 proof_how = CASE WHEN connection.proven_at IS NULL THEN excluded.proof_how ELSE connection.proof_how END,
6674 proven_at = COALESCE(connection.proven_at, excluded.proven_at),
6775 code_hash = NULL, expires_at = NULL, tries = 0`,
68 ).run(userId, newId(), at);
76 ).run(userId, newId(), at, proof?.by ?? null, proof?.how ?? null);
6977 })();
7078 }
7179
src/crew/conversation_ask.ts +1 −1
@@ -294,7 +294,7 @@ export const ASKED_AS: Readonly<Record<string, Form>> = {
294294 a["verb"] === "revoke"
295295 ? `Revoke the child forge credential ${val(a, "id")}`
296296 : `Make a propose-only credential for the child forge ${val(a, "child")}`,
297 mint_invite: (a) => `Make a single-use invite link, good for ${val(a, "days") || "7"} days`,
297 mint_invite: (a) => "Make a single-use invite link, good for 72 hours",
298298 claim_link: (a) =>
299299 a["action"] === "revoke"
300300 ? `End the claim link of ${val(a, "name")}`
src/http/api/admin.ts +1 −2
@@ -569,10 +569,9 @@ export function adminRoutes(router: Router<Handler>): void {
569569 const denied = accountAdmin(ctx, "admin");
570570 if (denied) return denied;
571571 const input = await body(ctx.request);
572 const made = mintInviteLink(ctx.app, ctx.auth.user, input.days, input.org, input);
572 const made = mintInviteLink(ctx.app, ctx.auth.user, input.org, input);
573573 if (!made.ok) {
574574 if (made.error === "not_found") return notFound();
575 if (made.error === "invalid_days") return apiError("invalid", 422, SPEND_WORDS.inviteDays);
576575 return apiError("invalid", 422, made.error === "unknown_org" ? "no such organization" : mintRefusal(made.error));
577576 }
578577 const origin = ctx.app.config.url ?? ctx.url.origin;
src/http/lazy_lists.ts +1
@@ -321,6 +321,7 @@ export const ACCOUNTS_ROUTES = [
321321 ["GET", "/signin/parent"],
322322 ["GET", "/signin/parent/callback"],
323323 ["GET", "/signup"],
324 ["POST", "/signup/invite"],
324325 ["GET", "/signin/access/:token"],
325326 ["POST", "/signin/access/:token"],
326327 ["GET", "/claim/start/:token"],
src/http/mcp/tools/mint_invite.ts +4 −10
@@ -1,4 +1,3 @@
1 import { SPEND_WORDS } from "../../../actions/spend_words.ts";
21 import { inviteLink, mintRefusal, mint as mintInviteLink } from "../../../actions/invites.ts";
32 import { scopeAllows } from "../../../core/tokens.ts";
43 import { good, bad, type Tool, mayBoards } from "../shared.ts";
@@ -6,13 +5,12 @@ import { good, bad, type Tool, mayBoards } from "../shared.ts";
65 export const tool: Tool = {
76 name: "mint_invite",
87 listedTo: "admin",
9 doc: "`{ days?, org?, bundle?, machine?, containers?, memoryMb? }`: mint a single-use invite link that expires in `days` (1–30, default 7) and is shown once; with `org` the person joins that organization and gets private forks of its apps; `bundle` is use (default), host (with a `machine` of those the forge offers and positive `containers` and `memoryMb` caps) or build; a person admin's, with an admin token",
8 doc: "`{ org?, bundle?, machine?, containers?, memoryMb? }`: mint a single-use invite link that expires in 72 hours and is shown once; with `org` the person joins that organization and gets private forks of its apps; `bundle` is use (default), host (with a `machine` of those the forge offers and positive `containers` and `memoryMb` caps) or build; a person admin's, with an admin token",
109 description:
11 "Mint a one-use invite link, shown once, valid `days` (1–30, default 7). Person admins.",
10 "Mint a one-use invite link, shown once, valid 72 hours. Person admins.",
1211 inputSchema: {
1312 type: "object",
1413 properties: {
15 days: { type: "integer", minimum: 1, maximum: 30 },
1614 org: { type: "string", description: "Organization the person joins" },
1715 bundle: { type: "string", enum: ["use", "host", "build"] },
1816 machine: { type: "string", description: "Host: a machine the forge offers" },
@@ -25,15 +23,11 @@ export const tool: Tool = {
2523 if (!mayBoards(user)) return bad("forbidden", "an invite is a forge admin's to mint");
2624 if (!scopeAllows(ctx.auth.scope ?? "ro", "admin"))
2725 return bad("forbidden", "an invite needs an admin token");
28 const made = mintInviteLink(ctx.app, user, args["days"], args["org"], args);
26 const made = mintInviteLink(ctx.app, user, args["org"], args);
2927 if (!made.ok)
3028 return bad(
3129 "invalid",
32 made.error === "invalid_days"
33 ? SPEND_WORDS.inviteDays
34 : made.error === "unknown_org"
35 ? "no such organization"
36 : mintRefusal(made.error),
30 made.error === "unknown_org" ? "no such organization" : mintRefusal(made.error),
3731 );
3832 const origin = ctx.app.config.url ?? ctx.url.origin;
3933 return good({ ...made.value.invite, link: inviteLink(origin, made.value.token) });
src/http/routes/accounts.ts +3 −1
@@ -6,6 +6,7 @@
66 import { claimFragmentPage, claimSubmit, claimOptions, claimRenew, welcomePage, welcomeSubmit } from "../../web/pages/claim.ts";
77 import { firstAdminPage, firstAdminSubmit, firstAdminOptions } from "../../web/pages/first-admin.ts";
88 import { accessPage, accessSubmit, signinOptions, signinPasskey, recoverPage, recoverRequest, recoverOptions, recoverFinish } from "../../web/pages/passkeys.ts";
9 import { inviteLinkPage, inviteLinkSubmit } from "../../web/pages/invite-link.ts";
910 import { signinPage, signinSubmit, safeNext, signupPage, requestedPage, joinPage, joinSubmit, verifyPage, signupSubmit, logoutSubmit, themeSubmit } from "../../web/pages/site.ts";
1011 import { startClaimPage, startClaimSubmit, startClaimAccountSubmit } from "../../web/pages/start_claim.ts";
1112 import { type Ctx } from "../context.ts";
@@ -41,7 +42,8 @@ export function accountsRoutes(router: Router<Handler>): void {
4142 router.add("GET", "/sign-in", signinAlias);
4243 router.add("GET", "/signin/parent", parentStart);
4344 router.add("GET", "/signin/parent/callback", parentCallback);
44 router.add("GET", "/signup", signupPage);
45 router.add("GET", "/signup", (ctx) => inviteLinkPage(ctx) ?? signupPage(ctx));
46 router.add("POST", "/signup/invite", inviteLinkSubmit);
4547 router.add("GET", "/signin/access/:token", accessPage);
4648 router.add("POST", "/signin/access/:token", accessSubmit);
4749 router.add("GET", "/claim/start/:token", startClaimPage);
src/tui/screens/invites.ts +10 −23
@@ -17,7 +17,7 @@ import { INVITE_NOT_OPEN } from "../../actions/sever_invite_words.ts";
1717 import { changeAgentStart, changeSignup, readAgentStart, readSignup } from "../../actions/signup.ts";
1818 import { AGENT_START_MODES, type AgentStartMode } from "../../settings/agent_start.ts";
1919 import { SIGNUP_MODES, type SignupMode } from "../../settings/signup.ts";
20 import { DEFAULT_DAYS, MAX_DAYS, parseDays, type Invite } from "../../core/invites.ts";
20 import { type Invite } from "../../core/invites.ts";
2121 import type { Ctx, Screen } from "../app/app.ts";
2222 import { binding } from "../app/keys.ts";
2323 import { style } from "../term/style.ts";
@@ -40,13 +40,8 @@ export function invitesScreen(f: Session, ctx: Ctx): Screen {
4040 return r.ok ? r.value : [];
4141 };
4242
43 const daysOf = (raw: string): number => {
44 const text = raw.trim();
45 return text === "" ? DEFAULT_DAYS : /^\d{1,3}$/.test(text) ? Number(text) : -1;
46 };
47
48 const make = (raw: string, org = "", choice: BundleInput = {}): string | undefined => {
49 const made = mint(f.app, f.user, daysOf(raw), org, choice);
43 const make = (org = "", choice: BundleInput = {}): string | undefined => {
44 const made = mint(f.app, f.user, org, choice);
5045 if (!made.ok) return mintRefusal(made.error);
5146 const origin = f.app.config.url ?? `http://localhost:${f.app.config.port}`;
5247 note = `Shown once: ${inviteLink(origin, made.value.token)}`;
@@ -55,16 +50,16 @@ export function invitesScreen(f: Session, ctx: Ctx): Screen {
5550 };
5651
5752 /**
58 * After the days: pick the bundle; Host goes on to its machine and two caps, each refused in the
53 * Pick the bundle; Host goes on to its machine and two caps, each refused in the
5954 * words the page uses.
6055 */
61 const pickBundle = (days: string): Screen =>
56 const pickBundle = (): Screen =>
6257 pickerScreen(ctx, screen, {
6358 title: "What the invite allows",
6459 items: BUNDLES.map((b) => ({ id: b, label: BUNDLE[b].label, hint: BUNDLE[b].says })),
6560 onPick: ([b]) => {
6661 if (b !== "host") {
67 const refused = make(days, "", { bundle: b });
62 const refused = make("", { bundle: b });
6863 if (refused !== undefined) note = refused;
6964 return;
7065 }
@@ -90,7 +85,7 @@ export function invitesScreen(f: Session, ctx: Ctx): Screen {
9085 label: "most memory in MB, a positive whole number",
9186 value: "2048",
9287 onSubmit: (memoryMb) => {
93 const refused = make(days, "", { bundle: "host", machine, containers, memoryMb });
88 const refused = make("", { bundle: "host", machine, containers, memoryMb });
9489 if (refused !== undefined) return refused;
9590 return undefined;
9691 },
@@ -179,7 +174,7 @@ export function invitesScreen(f: Session, ctx: Ctx): Screen {
179174 ? "Invite links are made by a forge admin."
180175 : r.value.length === 0
181176 ? "No invite link yet. m makes one."
182 : "Each link is good for one signup. m makes one, x revokes.";
177 : "Each link is good for one signup, for 72 hours. m makes one, x revokes.";
183178 s.text(head!.x, head!.y, truncate(text, head!.w), style(c.mutedFg, c.bg), head!.x + head!.w);
184179 drawList(s, body!, c, state, rows());
185180 },
@@ -189,15 +184,7 @@ export function invitesScreen(f: Session, ctx: Ctx): Screen {
189184 if (state.key(e, all.length)) return true;
190185 if (e.ctrl || e.alt || !read().ok) return false;
191186 if (e.key === "m") {
192 ctx.push(
193 promptScreen(ctx, screen, {
194 title: "Invite link",
195 label: `days until it expires, 1 to ${MAX_DAYS}`,
196 value: String(DEFAULT_DAYS),
197 onSubmit: (days) =>
198 !parseDays(daysOf(days)).ok ? mintRefusal("invalid_days") : later(ctx, () => pickBundle(days)),
199 }),
200 );
187 ctx.push(pickBundle());
201188 } else if (e.key === "o") {
202189 ctx.push(
203190 promptScreen(ctx, screen, {
@@ -207,7 +194,7 @@ export function invitesScreen(f: Session, ctx: Ctx): Screen {
207194 onSubmit: (org) =>
208195 org.trim() === ""
209196 ? "Name an organization."
210 : make(String(DEFAULT_DAYS), org),
197 : make(org),
211198 }),
212199 );
213200 } else if (e.key === "x") {
src/web/pages/admin-limits.ts +4 −20
@@ -11,10 +11,9 @@ import { worstCaseOf } from "../../spawn/included_credit.ts";
1111 import { QUOTA_INVALID } from "../../actions/admin_limits_words.ts";
1212 import { birthsWords, changeLimit, listLimits } from "../../actions/limits.ts";
1313 import { changeQuotas, readQuotas } from "../../actions/quotas.ts";
14 import { BUNDLE_WORDS, hostMachines, inviteLink, list as listInviteLinks, mint as mintInviteLink, revoke as revokeInviteLink } from "../../actions/invites.ts";
14 import { BUNDLE_WORDS, hostMachines, inviteLink, mintRefusal, list as listInviteLinks, mint as mintInviteLink, revoke as revokeInviteLink } from "../../actions/invites.ts";
1515 import { BUNDLE, BUNDLES } from "../../core/bundles.ts";
1616 import { INVITE_NOT_OPEN } from "../../actions/sever_invite_words.ts";
17 import { DEFAULT_DAYS, MAX_DAYS } from "../../core/invites.ts";
1817 import { changeAgentStart, changeBillingLinks, changeSignup, readAgentStart, readBillingLinks, readSignup } from "../../actions/signup.ts";
1918 import { BILLING_SIZES } from "../../settings/billing.ts";
2019 import { AGENT_START_MODES } from "../../settings/agent_start.ts";
@@ -220,23 +219,13 @@ export function limitsPage(ctx: Ctx): Response {
220219 <dt>Invite links</dt>
221220 <dd>
222221 <form class="row-fields" method="post" action="/admin/invites">
223 <label class="small">expires in (days)
224 <input
225 class="input mono"
226 type="number"
227 name="days"
228 min="1"
229 max="${String(MAX_DAYS)}"
230 step="1"
231 value="${String(DEFAULT_DAYS)}"
232 /></label>
233222 <label class="small">organization (optional)
234223 <input class="input mono" type="text" name="org" maxlength="60" autocomplete="off" /></label>
235224 ${bundleField}
236225 ${hostFields}
237226 ${btn("Make a link", { size: "sm", variant: "primary", label: "Make an invite link" })}
238227 </form>
239 <span class="muted small">Shown once, when it is made; good for one signup. With an organization, the person joins it and gets private forks of its apps.</span>
228 <span class="muted small">Shown once, when it is made; good for one signup, for 72 hours. It signs its person in on its own. With an organization, the person joins it and gets private forks of its apps.</span>
240229 </dd>
241230 <dd class="status-act"></dd>
242231 </div>`;
@@ -397,8 +386,7 @@ export async function inviteMint(ctx: Ctx): Promise<Response> {
397386 return notFoundPage(ctx);
398387 const form = await readForm(ctx, "admin");
399388 if (form instanceof Response) return form;
400 const raw = field(form, "days").trim();
401 const made = mintInviteLink(ctx.app, ctx.auth.user, /^\d{1,3}$/.test(raw) ? Number(raw) : -1, field(form, "org"), {
389 const made = mintInviteLink(ctx.app, ctx.auth.user, field(form, "org"), {
402390 bundle: field(form, "bundle"),
403391 machine: field(form, "machine"),
404392 containers: field(form, "containers"),
@@ -409,11 +397,7 @@ export async function inviteMint(ctx: Ctx): Promise<Response> {
409397 return flashTo(ctx, "/admin/limits", { tone: "danger", message: "No organization by that name." });
410398 if (!made.ok && made.error in BUNDLE_WORDS)
411399 return flashTo(ctx, "/admin/limits", { tone: "danger", message: BUNDLE_WORDS[made.error as keyof typeof BUNDLE_WORDS] });
412 if (!made.ok)
413 return flashTo(ctx, "/admin/limits", {
414 tone: "danger",
415 message: `Days is a whole number from 1 to ${MAX_DAYS}.`,
416 });
400 if (!made.ok) return flashTo(ctx, "/admin/limits", { tone: "danger", message: mintRefusal(made.error) });
417401 return flashTo(ctx, "/admin/limits", {
418402 message: "Invite link made. It is shown only now:",
419403 code: inviteLink(ctx.app.config.url ?? ctx.url.origin, made.value.token),
src/web/pages/signup-passkey.ts +2
@@ -8,6 +8,7 @@
88
99 import { inviteWelcome } from "../../actions/invite_welcome.ts";
1010 import { newChallenge, verifyRegistration } from "../../auth/webauthn.ts";
11 import { HOST_WORDS } from "../../core/bundles.ts";
1112 import { givenEmail, invalidEmailMessage, signUpWithPasskey, signupClosed, HUMAN_CHECK_MESSAGE, SIGNUP_CLOSED_MESSAGE } from "../../actions/users.ts";
1213 import { rotateSession } from "../../auth/session_rotate.ts";
1314 import { getUserByName } from "../../core/users.ts";
@@ -35,6 +36,7 @@ const WORDS: Record<string, string> = {
3536 human_check: HUMAN_CHECK_MESSAGE,
3637 passkey_taken: PASSKEY_TAKEN,
3738 signup_closed: SIGNUP_CLOSED_MESSAGE,
39 host_gone: HOST_WORDS.gone,
3840 };
3941
4042 /** Whether the name and address are fit to sign up with; else the words. */
src/web/pages/site.ts +2
@@ -29,6 +29,7 @@ import { createRepo, repositoryLimitMessage, resolveOwner } from "../../actions/
2929 import { REPO_DIR_IN_THE_WAY, REPO_INIT_FAILED, REPO_NAME_RULES } from "../../actions/repo_words.ts";
3030 import { NOTE_MAX, requestOf } from "../../core/requests.ts";
3131 import { invalidEmailMessage, DECLINED_MESSAGE, REQUEST_IN_MESSAGE, STILL_WAITING_MESSAGE } from "../../actions/users.ts";
32 import { HOST_WORDS } from "../../core/bundles.ts";
3233 import { inviteByToken } from "../../core/invites.ts";
3334 import { INVITE_SPENT, inviteExpiredLine, inviteExpiryLine, inviteRepo, joinRepo } from "../../actions/invites.ts";
3435 import { whenWords } from "../../core/when_words.ts";
@@ -848,6 +849,7 @@ export async function signupSubmit(ctx: Ctx): Promise<Response> {
848849 invalid_email: { email: invalidEmailMessage(email) },
849850 human_check: { human: HUMAN_CHECK_MESSAGE },
850851 passkey_required: { human: PASSKEY_REQUIRED_MESSAGE },
852 host_gone: { username: HOST_WORDS.gone },
851853 }[created.error] ?? { username: "Something went wrong." };
852854 return page(
853855 {
src/web/pages/start_claim.ts +1
@@ -109,6 +109,7 @@ async function makeAccountAndTake(ctx: Ctx): Promise<Response> {
109109 weak_password: { password: "Passwords need at least 12 characters." },
110110 password_too_long: { password: "That password is too long." },
111111 signup_closed: { username: "Accounts cannot be made here." },
112 host_gone: { username: "Accounts cannot be made here." },
112113 }[made.error];
113114 return startClaimPage(ctx, said, 422);
114115 }
test/admin-lists-paged.test.ts +1 −1
@@ -33,7 +33,7 @@ describe("the admin's accounts, people and invites lists answer { items, next_cu
3333 }
3434 proveAll(app);
3535 admin = createToken(app.db, a.value.id, "t", "admin").token;
36 for (let i = 0; i < 4; i++) mintInvite(app.db, a.value.id, 3);
36 for (let i = 0; i < 4; i++) mintInvite(app.db, a.value.id);
3737 });
3838 afterAll(async () => {
3939 servers.stop();
test/conversation-ask.test.ts +1 −6
@@ -399,12 +399,7 @@ const SAID: readonly (readonly [string, Record<string, unknown>, string])[] = [
399399 { repo: "marin/cakes", verb: "revoke", id: "t1" },
400400 "Revoke the child forge credential t1.",
401401 ],
402 [
403 "mint_invite",
404 { days: 3 },
405 "Make a single-use invite link, good for 3 days.",
406 ],
407 ["mint_invite", {}, "Make a single-use invite link, good for 7 days."],
402 ["mint_invite", {}, "Make a single-use invite link, good for 72 hours."],
408403 [
409404 "claim_link",
410405 { name: "kid", reveal: true },
test/conversation-confirm.test.ts +1 −1
@@ -408,7 +408,7 @@ describe("a confirm past its time", () => {
408408 describe("a result shown once", () => {
409409 test("mint_invite's link is answered to the person and never kept in the conversation", async () => {
410410 const w = await world(alice);
411 const asked = JSON.parse((await call(w.token, "mint_invite", { days: 3 })).text);
411 const asked = JSON.parse((await call(w.token, "mint_invite", {})).text);
412412 expect(asked.needs_confirm).toMatch(/^[0-9a-z]+$/);
413413 const res = await yes(asked.needs_confirm, alice);
414414 expect(res.status).toBe(200);
test/first-week.test.ts +1 −1
@@ -65,7 +65,7 @@ describe("first week", () => {
6565 });
6666
6767 test("an invite strikes the third, and with all three done the block is gone", () => {
68 mintInvite(app.db, alice.id, 7);
68 mintInvite(app.db, alice.id);
6969 expect(firstWeekSteps(app.db, alice)).toBeNull();
7070 expect(firstWeekBlock(app.db, alice)).toBeNull();
7171 });
test/grants-view.test.ts +2 −1
@@ -30,6 +30,7 @@ function seeded(): Database {
3030 ["INSERT INTO app_member (app_id, user_id, added_by, added_at) VALUES ('app1', 'ann', 'root', ?1)", [AT]],
3131 ["INSERT INTO game_grant (box_id, user_id, role, service) VALUES ('box1', 'ann', 'player', 'web')", []],
3232 ["INSERT INTO model_grant (user_id, usd_per_month, granted_by, granted_at) VALUES ('ann', 5, NULL, ?1)", [AT]],
33 ["INSERT INTO host_grant (user_id, machine, containers, memory_mb, invite_id, at) VALUES ('ann', 'shop-1', 2, 512, 'inv1', ?1)", [AT]],
3334 ["INSERT INTO subscription_grant (scope_id, agent_id, subscription_id) VALUES ('repo1', 'mason', 'sub1')", []],
3435 ["INSERT INTO secret_grant (repo_id, name, scope, scope_id, granted_by, granted_at) VALUES ('repo1', 'KEY', 'org', 'org1', 'root', ?1)", [AT]],
3536 ["INSERT INTO egress_grant (repo_id, destination, granted_by, granted_at) VALUES ('repo1', 'api.example.com', 'root', ?1)", [AT]],
@@ -72,7 +73,7 @@ describe("the grants view", () => {
7273 test("by account: an account's own grants, and none for an account with none", () => {
7374 const db = seeded();
7475 expect(everyGrant(db, "ann").map((g) => g.table).sort()).toEqual(
75 ["app_member", "client_cloud_member", "game_grant", "member", "model_grant", "share", "team_member", "telemetry_grant"],
76 ["app_member", "client_cloud_member", "game_grant", "host_grant", "member", "model_grant", "share", "team_member", "telemetry_grant"],
7677 );
7778 expect(everyGrant(db, "mason").map((g) => g.table).sort()).toEqual(["crew_team_member", "origin_read_grant", "subscription_grant"]);
7879 expect(everyGrant(db, "nobody")).toEqual([]);
test/invite-bundles.test.ts +7 −7
@@ -56,36 +56,36 @@ describe("invite bundles", () => {
5656 };
5757
5858 test("with no machine Host is refused and the page says why; Use and Build mint with their line", async () => {
59 const refused = mint(app, admin, 7, undefined, { bundle: "host", machine: "m1", containers: 2, memoryMb: 512 });
59 const refused = mint(app, admin, undefined, { bundle: "host", machine: "m1", containers: 2, memoryMb: 512 });
6060 expect(refused.ok ? "" : refused.error).toBe("no_machine");
6161 const html = await page();
6262 expect(html).toContain("Host needs a machine this forge can offer");
6363 expect(html).toContain(BUNDLE.use.says);
6464 expect(html).toContain(BUNDLE.build.says);
65 expect(mint(app, admin, 7, undefined, { bundle: "use" }).ok).toBe(true);
66 expect(mint(app, admin, 7, undefined, { bundle: "build" }).ok).toBe(true);
67 expect(mint(app, admin, 7).ok).toBe(true);
65 expect(mint(app, admin, undefined, { bundle: "use" }).ok).toBe(true);
66 expect(mint(app, admin, undefined, { bundle: "build" }).ok).toBe(true);
67 expect(mint(app, admin).ok).toBe(true);
6868 const bundles = (list(app, admin) as { ok: true; value: { bundle: string }[] }).value.map((i) => i.bundle);
6969 expect(bundles).toEqual(["use", "build", "use"]);
7070 expect(await page()).toContain(BUNDLE.build.says);
7171 });
7272
7373 test("a bundle that is not one of three is refused", () => {
74 const r = mint(app, admin, 7, undefined, { bundle: "root" });
74 const r = mint(app, admin, undefined, { bundle: "root" });
7575 expect(r.ok ? "" : r.error).toBe("invalid_bundle");
7676 });
7777
7878 test("Host with a machine on offer stores the machine and caps; a stranger machine or a bad cap is refused", async () => {
7979 pinMachine("shop-1");
8080 const bad = (c: object) => {
81 const r = mint(app, admin, 7, undefined, { bundle: "host", ...c });
81 const r = mint(app, admin, undefined, { bundle: "host", ...c });
8282 return r.ok ? "" : r.error;
8383 };
8484 expect(bad({ machine: "elsewhere", containers: 2, memoryMb: 512 })).toBe("invalid_machine");
8585 expect(bad({ machine: "shop-1", containers: 0, memoryMb: 512 })).toBe("invalid_cap");
8686 expect(bad({ machine: "shop-1", containers: 2, memoryMb: -1 })).toBe("invalid_cap");
8787 expect(bad({ machine: "shop-1", containers: "2.5", memoryMb: 512 })).toBe("invalid_cap");
88 const ok = mint(app, admin, 7, undefined, { bundle: "host", machine: "shop-1", containers: "3", memoryMb: "1024" });
88 const ok = mint(app, admin, undefined, { bundle: "host", machine: "shop-1", containers: "3", memoryMb: "1024" });
8989 expect(ok.ok && ok.value.invite.host).toEqual({ machine: "shop-1", containers: 3, memoryMb: 1024 });
9090 const html = await page();
9191 expect(html).toContain("on shop-1, up to 3 containers and 1024 MB");
test/invite-expiry-words.test.ts +2 −2
@@ -42,7 +42,7 @@ describe("invite expiry words", () => {
4242 });
4343
4444 test("an open link says when it works until", async () => {
45 const { token } = mintInvite(app.db, adminId, 3);
45 const { token } = mintInvite(app.db, adminId);
4646 const { status, text } = await get(token);
4747 expect(status).toBe(200);
4848 expect(text).toContain('id="invite-expiry"');
@@ -53,7 +53,7 @@ describe("invite expiry words", () => {
5353 });
5454
5555 test("an expired link says so kindly and names who sent it", async () => {
56 const { token } = mintInvite(app.db, adminId, 1, Date.now() - 3 * 86_400_000);
56 const { token } = mintInvite(app.db, adminId, Date.now() - 4 * 86_400_000);
5757 const { text } = await get(token);
5858 expect(text).toContain("This link has expired");
5959 expect(text).toContain("Ask olive for a new one");
test/invite-org.test.ts +6 −6
@@ -43,7 +43,7 @@ describe("an invite to an organization", () => {
4343 body: JSON.stringify({ username, email: `${username}@f.dev`, password: PASSWORD, invite }),
4444 });
4545 const tokenOf = (org?: string) => {
46 const made = mint(app, admin, undefined, org);
46 const made = mint(app, admin, org);
4747 if (!made.ok) throw new Error(made.error);
4848 return made.value;
4949 };
@@ -132,7 +132,7 @@ describe("an invite to an organization", () => {
132132 });
133133
134134 test("an organization that does not exist mints nothing", () => {
135 const made = mint(app, admin, undefined, "nowhere");
135 const made = mint(app, admin, "nowhere");
136136 expect(made.ok).toBe(false);
137137 if (!made.ok) expect(made.error).toBe("unknown_org");
138138 });
@@ -152,7 +152,7 @@ describe("an invite to an organization, edges", () => {
152152 body: JSON.stringify({ username, email: `${username}@f.dev`, password: PASSWORD, invite }),
153153 });
154154 const tokenOf = (org: string) => {
155 const made = mint(app, admin, undefined, org);
155 const made = mint(app, admin, org);
156156 if (!made.ok) throw new Error(made.error);
157157 return made.value.token;
158158 };
@@ -250,7 +250,7 @@ describe("an invite to an organization, edges", () => {
250250 expect(res.status).toBe(202);
251251 const vera = getUserByName(app.db, "vera")!;
252252 const { invite } = (() => {
253 const made = mint(app, admin, undefined, "later");
253 const made = mint(app, admin, "later");
254254 if (!made.ok) throw new Error(made.error);
255255 return made.value;
256256 })();
@@ -273,7 +273,7 @@ describe("an invite to an organization, edges", () => {
273273 });
274274 setSignup(app.db, "invite", admin.id);
275275 const wren = getUserByName(app.db, "wren")!;
276 const made = mint(app, admin, undefined, "broken");
276 const made = mint(app, admin, "broken");
277277 if (!made.ok) throw new Error(made.error);
278278 app.db.query("UPDATE invite SET used_by = ?1, used_at = ?2 WHERE id = ?3").run(wren.id, new Date().toISOString(), made.value.invite.id);
279279 app.db.exec("ALTER TABLE team_member RENAME TO team_member_away");
@@ -364,7 +364,7 @@ describe("an invite to an organization, by passkey", () => {
364364 });
365365
366366 test("a passkey sign-up with an org invite joins the org, forks its app and answers with the welcome", async () => {
367 const made = mint(app, admin, undefined, "acme");
367 const made = mint(app, admin, "acme");
368368 if (!made.ok) throw new Error(made.error);
369369 const origin = new URL(servers.url).origin;
370370 const d = await device(origin, new URL(servers.url).hostname);
test/invite-redeem.test.ts +10 −8
@@ -29,7 +29,7 @@ describe("invite links redeem at signup", () => {
2929 let servers: Servers;
3030 let owner = "";
3131
32 const mint = (days = 7, now = Date.now()) => mintInvite(app.db, owner, days, now);
32 const mint = (now = Date.now()) => mintInvite(app.db, owner, now);
3333 const stateOf = (id: string) => listInvites(app.db).find((i) => i.id === id)?.state;
3434 const form = (username: string, invite?: string) =>
3535 fetch(`${servers.url}/signup${invite === undefined ? "" : `?invite=${invite}`}`, {
@@ -119,7 +119,7 @@ describe("invite links redeem at signup", () => {
119119 test("a revoked, an expired or an unknown link makes nothing", async () => {
120120 const revoked = mint();
121121 revokeInvite(app.db, revoked.invite.id);
122 const expired = mint(1, Date.now() - 2 * 86_400_000);
122 const expired = mint(Date.now() - 4 * 86_400_000);
123123 for (const [name, token] of [["rev", revoked.token], ["exp", expired.token], ["unknown", "invite_nothing"]] as const) {
124124 expect((await apiSignup(name, token)).status).toBe(403);
125125 expect(getUserByName(app.db, name)).toBeUndefined();
@@ -132,14 +132,16 @@ describe("invite links redeem at signup", () => {
132132 expect(stateOf(invite.id)).toBe("open");
133133 });
134134
135 test("while signup is closed a link makes nothing; while open it is not spent", async () => {
136 const { invite, token } = mint();
135 test("a live link opens the door while signup is closed, and is spent; so while open", async () => {
136 const closed = mint();
137137 setSignup(app.db, "closed", owner);
138 expect((await apiSignup("shut", token)).status).toBe(403);
139 expect(stateOf(invite.id)).toBe("open");
138 expect((await apiSignup("shut", closed.token)).status).toBe(201);
139 expect(stateOf(closed.invite.id)).toBe("used");
140 expect((await apiSignup("shut2")).status).toBe(403);
141 const open = mint();
140142 setSignup(app.db, "open", owner);
141 expect((await apiSignup("opened", token)).status).toBe(201);
142 expect(stateOf(invite.id)).toBe("open");
143 expect((await apiSignup("opened", open.token)).status).toBe(201);
144 expect(stateOf(open.invite.id)).toBe("used");
143145 setSignup(app.db, "invite", owner);
144146 // Many sign-ups from this one source: the window is not under test here.
145147 setLimit(app.db, "signup.per_source", 1000, owner);
test/invites-action.test.ts +11 −15
@@ -11,7 +11,6 @@ import { join } from "node:path";
1111 import { createApp, type App } from "../src/app.ts";
1212 import { inviteLink, list, mint, revoke } from "../src/actions/invites.ts";
1313 import { signUp } from "../src/actions/users.ts";
14 import { MAX_DAYS } from "../src/core/invites.ts";
1514 import { listEvents } from "../src/core/events.ts";
1615 import { createUser, getUserByName, type User } from "../src/core/users.ts";
1716 import { sha256 } from "../src/kernel/hash.ts";
@@ -75,7 +74,7 @@ describe("invite links through the action", () => {
7574
7675 test("an admin's mint returns the link once; no listing, event or log line carries it", () => {
7776 const since = listEvents(app.db, { limit: 1 })[0]?.id;
78 const made = logged(() => mint(app, admin, 3));
77 const made = logged(() => mint(app, admin));
7978 expect(made.ok).toBe(true);
8079 if (!made.ok) return;
8180 const { invite, token } = made.value;
@@ -117,7 +116,7 @@ describe("invite links through the action", () => {
117116 });
118117
119118 test("a revoked link signs nobody up; an open one does", async () => {
120 const made = mint(app, admin, undefined);
119 const made = mint(app, admin);
121120 if (!made.ok) throw new Error(made.error);
122121 expect(revoke(app, admin, made.value.invite.id).ok).toBe(true);
123122 const refused = await signUp(
@@ -130,7 +129,7 @@ describe("invite links through the action", () => {
130129 // A second revoke of the same link is not found: it is already shut.
131130 expect(revoke(app, admin, made.value.invite.id)).toEqual({ ok: false, error: "not_found" });
132131
133 const open = mint(app, admin, 1);
132 const open = mint(app, admin);
134133 if (!open.ok) throw new Error(open.error);
135134 const let_in = await signUp(
136135 app,
@@ -141,18 +140,18 @@ describe("invite links through the action", () => {
141140 });
142141
143142 test("a member, a guest and nobody get not_found for all three, and nothing changes", () => {
144 const made = mint(app, admin, 7);
143 const made = mint(app, admin);
145144 if (!made.ok) throw new Error(made.error);
146145 const before = list(app, admin);
147146 const eventsBefore = listEvents(app.db, { limit: 500 }).length;
148147 for (const actor of [member, guest, undefined]) {
149 expect(mint(app, actor, 7)).toEqual({ ok: false, error: "not_found" });
148 expect(mint(app, actor)).toEqual({ ok: false, error: "not_found" });
150149 expect(list(app, actor)).toEqual({ ok: false, error: "not_found" });
151150 expect(revoke(app, actor, made.value.invite.id)).toEqual({ ok: false, error: "not_found" });
152151 }
153152 // An agent account flagged admin is still not a person who may mint.
154153 const agent = { ...admin, kind: "agent" as const };
155 expect(mint(app, agent, 7)).toEqual({ ok: false, error: "not_found" });
154 expect(mint(app, agent)).toEqual({ ok: false, error: "not_found" });
156155 expect(list(app, agent)).toEqual({ ok: false, error: "not_found" });
157156 expect(revoke(app, agent, made.value.invite.id)).toEqual({ ok: false, error: "not_found" });
158157
@@ -160,13 +159,10 @@ describe("invite links through the action", () => {
160159 expect(listEvents(app.db, { limit: 500 }).length).toBe(eventsBefore);
161160 });
162161
163 test("days outside 1 to 30, or not a whole number, is refused and mints nothing", () => {
164 const before = list(app, admin);
165 for (const days of [0, -1, MAX_DAYS + 1, 1.5, "7", Number.NaN, Infinity, {}]) {
166 expect(mint(app, admin, days)).toEqual({ ok: false, error: "invalid_days" });
167 }
168 expect(list(app, admin)).toEqual(before);
169 expect(mint(app, admin, 1).ok).toBe(true);
170 expect(mint(app, admin, MAX_DAYS).ok).toBe(true);
162 test("every link lives 72 hours: the mint takes no day count", () => {
163 const made = mint(app, admin);
164 expect(made.ok).toBe(true);
165 if (!made.ok) return;
166 expect(Date.parse(made.value.invite.expiresAt) - Date.parse(made.value.invite.createdAt)).toBe(72 * 3_600_000);
171167 });
172168 });
test/invites-core.test.ts +15 −30
@@ -9,13 +9,10 @@ import invite from "../src/core/migrations/20261016200000-invite.ts";
99 import inviteOrg from "../src/core/migrations/20261114090000-invite-org.ts";
1010 import inviteBundle from "../src/core/migrations/20261206100000-invite-bundle.ts";
1111 import {
12 DEFAULT_DAYS,
13 MAX_DAYS,
1412 inviteOpen,
1513 inviteSpentBy,
1614 listInvites,
1715 mintInvite,
18 parseDays,
1916 redeemInvite,
2017 reopenInvite,
2118 } from "../src/core/invites.ts";
@@ -23,18 +20,6 @@ import {
2320 const DAY = 86_400_000;
2421 const T0 = Date.parse("2026-10-01T00:00:00Z");
2522
26 describe("parseDays", () => {
27 test("the default for absent, the bounds for present", () => {
28 expect(parseDays(undefined)).toEqual({ ok: true, value: DEFAULT_DAYS });
29 expect(parseDays(null)).toEqual({ ok: true, value: DEFAULT_DAYS });
30 expect(parseDays(1)).toEqual({ ok: true, value: 1 });
31 expect(parseDays(MAX_DAYS)).toEqual({ ok: true, value: MAX_DAYS });
32 for (const bad of [0, MAX_DAYS + 1, 1.5, "7", Number.NaN, -1, Infinity]) {
33 expect(parseDays(bad)).toEqual({ ok: false, error: "invalid_days" });
34 }
35 });
36 });
37
3823 describe("an invite's life", () => {
3924 let db: Database;
4025 beforeEach(() => {
@@ -46,16 +31,16 @@ describe("an invite's life", () => {
4631 });
4732
4833 test("open before its expiry, not at or after it", () => {
49 const { token } = mintInvite(db, "owner", 2, T0);
34 const { token } = mintInvite(db, "owner", T0);
5035 expect(inviteOpen(db, token, T0)).toBe(true);
51 expect(inviteOpen(db, token, T0 + 2 * DAY - 1)).toBe(true);
52 expect(inviteOpen(db, token, T0 + 2 * DAY)).toBe(false);
36 expect(inviteOpen(db, token, T0 + 3 * DAY - 1)).toBe(true);
5337 expect(inviteOpen(db, token, T0 + 3 * DAY)).toBe(false);
38 expect(inviteOpen(db, token, T0 + 4 * DAY)).toBe(false);
5439 expect(inviteOpen(db, "invite_unknown", T0)).toBe(false);
5540 });
5641
5742 test("redeems once; a second redeem by anyone fails", () => {
58 const { token } = mintInvite(db, "owner", 2, T0);
43 const { token } = mintInvite(db, "owner", T0);
5944 expect(redeemInvite(db, token, "ada", T0 + 1)).toBe(true);
6045 expect(inviteOpen(db, token, T0 + 2)).toBe(false);
6146 expect(redeemInvite(db, token, "ada", T0 + 2)).toBe(false);
@@ -64,21 +49,21 @@ describe("an invite's life", () => {
6449 });
6550
6651 test("an expired invite never redeems", () => {
67 const { token } = mintInvite(db, "owner", 1, T0);
68 expect(redeemInvite(db, token, "ada", T0 + DAY)).toBe(false);
52 const { token } = mintInvite(db, "owner", T0);
53 expect(redeemInvite(db, token, "ada", T0 + 3 * DAY)).toBe(false);
6954 expect(redeemInvite(db, token, "ada", T0 + 5 * DAY)).toBe(false);
7055 expect(inviteSpentBy(db, "ada")).toBeUndefined();
71 expect(listInvites(db, T0 + DAY)[0]!.state).toBe("expired");
56 expect(listInvites(db, T0 + 3 * DAY)[0]!.state).toBe("expired");
7257 });
7358
7459 test("an unknown token redeems nothing", () => {
75 mintInvite(db, "owner", 2, T0);
60 mintInvite(db, "owner", T0);
7661 expect(redeemInvite(db, "invite_nope", "ada", T0)).toBe(false);
7762 });
7863
7964 test("inviteSpentBy names the redeemer's invite", () => {
80 const a = mintInvite(db, "owner", 2, T0);
81 const b = mintInvite(db, "owner", 2, T0);
65 const a = mintInvite(db, "owner", T0);
66 const b = mintInvite(db, "owner", T0);
8267 redeemInvite(db, a.token, "ada", T0);
8368 expect(inviteSpentBy(db, "ada")).toBe(a.invite.id);
8469 expect(inviteSpentBy(db, "bob")).toBeUndefined();
@@ -87,8 +72,8 @@ describe("an invite's life", () => {
8772 });
8873
8974 test("reopenInvite gives back only that account's invite, once more redeemable", () => {
90 const a = mintInvite(db, "owner", 2, T0);
91 const b = mintInvite(db, "owner", 2, T0);
75 const a = mintInvite(db, "owner", T0);
76 const b = mintInvite(db, "owner", T0);
9277 redeemInvite(db, a.token, "ada", T0);
9378 redeemInvite(db, b.token, "bob", T0);
9479 reopenInvite(db, "ada");
@@ -103,9 +88,9 @@ describe("an invite's life", () => {
10388
10489 test("a redeemed invite lists who joined with it and when; null when unused or the account is gone", () => {
10590 db.query("INSERT INTO user (id, username) VALUES ('u1', 'ada')").run();
106 const used = mintInvite(db, "owner", 2, T0);
107 const gone = mintInvite(db, "owner", 2, T0);
108 const fresh = mintInvite(db, "owner", 2, T0);
91 const used = mintInvite(db, "owner", T0);
92 const gone = mintInvite(db, "owner", T0);
93 const fresh = mintInvite(db, "owner", T0);
10994 redeemInvite(db, used.token, "u1", T0 + 1000);
11095 redeemInvite(db, gone.token, "u-deleted", T0 + 2000);
11196 const byId = new Map(listInvites(db, T0 + 3000).map((i) => [i.id, i]));
test/invites.test.ts +8 −16
@@ -49,9 +49,9 @@ describe("invites: an admin mints, lists and revokes", () => {
4949 const made = (await res.json()) as { id: string; token: string; link: string; expiresAt: string; state: string };
5050 expect(made.link).toBe(`https://forge.example/signup?invite=${made.token}`);
5151 expect(made.state).toBe("open");
52 const days = (Date.parse(made.expiresAt) - Date.now()) / 86_400_000;
53 expect(days).toBeGreaterThan(6.99);
54 expect(days).toBeLessThan(7.01);
52 const hours = (Date.parse(made.expiresAt) - Date.now()) / 3_600_000;
53 expect(hours).toBeGreaterThan(71.99);
54 expect(hours).toBeLessThan(72.01);
5555
5656 const rows = app.db.query("SELECT * FROM invite").all();
5757 expect(JSON.stringify(rows)).not.toContain(made.token);
@@ -71,11 +71,10 @@ describe("invites: an admin mints, lists and revokes", () => {
7171 expect(JSON.stringify(listEvents(app.db, {}))).not.toContain(made.token);
7272 });
7373
74 test("days is bounded to 1..30", async () => {
75 const post = (days: unknown) =>
76 api("/api/v1/admin/invites", admin, { method: "POST", body: JSON.stringify({ days }) });
77 expect((await post(30)).status).toBe(201);
78 for (const bad of [0, 31, 1.5, "7", -1]) expect((await post(bad)).status).toBe(422);
74 test("a longer life is not on offer: a days field changes nothing", async () => {
75 const res = await api("/api/v1/admin/invites", admin, { method: "POST", body: JSON.stringify({ days: 30 }) });
76 const made = (await res.json()) as { expiresAt: string };
77 expect((Date.parse(made.expiresAt) - Date.now()) / 3_600_000).toBeLessThan(72.01);
7978 });
8079
8180 test("a non-admin and a stranger are refused on all three routes", async () => {
@@ -92,7 +91,7 @@ describe("invites: an admin mints, lists and revokes", () => {
9291 });
9392
9493 test("an expired invite reads as expired; a used one cannot be revoked", () => {
95 const past = mintInvite(app.db, "x", 1, Date.now() - 2 * 86_400_000);
94 const past = mintInvite(app.db, "x", Date.now() - 4 * 86_400_000);
9695 expect(listInvites(app.db).find((i) => i.id === past.invite.id)?.state).toBe("expired");
9796 const used = mintInvite(app.db, "x");
9897 app.db.query("UPDATE invite SET used_at = ?2 WHERE id = ?1").run(used.invite.id, "2026-01-01T00:00:00Z");
@@ -156,13 +155,6 @@ describe("invites: the settings form", () => {
156155 expect(listInvites(app.db)[0]!.state).toBe("revoked");
157156 });
158157
159 test("days outside 1 to 30 mint nothing", async () => {
160 const before = listInvites(app.db).length;
161 await post(alice, "/admin/invites", { days: "31" });
162 await post(alice, "/admin/invites", { days: "abc" });
163 expect(listInvites(app.db).length).toBe(before);
164 });
165
166158 test("a cross-origin post is refused and a non-admin gets the not-found page", async () => {
167159 const before = listInvites(app.db).length;
168160 expect((await post(alice, "/admin/invites", { days: "3" }, "https://evil.example")).status).toBe(403);
test/mcp-forge-admin.test.ts +2 −2
@@ -272,8 +272,8 @@ describe("the forge over MCP: admin", () => {
272272 const admin = createToken(app.db, alice.id, "admin", "admin").token;
273273 expect((await tool(bobRw, "mint_invite")).error).toContain("forbidden");
274274 expect((await tool(rw, "mint_invite")).error).toContain("admin token");
275 expect((await tool(admin, "mint_invite", { days: 0 })).error).toContain("invalid");
276 const made = (await tool(admin, "mint_invite", { days: 3 })).value;
275 expect((await tool(admin, "mint_invite", { org: 5 })).error).toContain("invalid");
276 const made = (await tool(admin, "mint_invite", {})).value;
277277 expect(made.link).toMatch(/\/signup\?invite=[\w-]+$/);
278278 const token = made.link.split("invite=")[1];
279279 expect(made.token).toBeUndefined();
test/mcp-invites.test.ts +1 −1
@@ -73,7 +73,7 @@ const signup = (username: string, invite: string) =>
7373 });
7474
7575 test("an admin mints, lists and revokes; a revoked link signs no one up", async () => {
76 const kept = (await tool(admin, "mint_invite", { days: 3 })).value;
76 const kept = (await tool(admin, "mint_invite", {})).value;
7777 const gone = (await tool(admin, "mint_invite")).value;
7878 const goneToken = gone.link.split("invite=")[1];
7979
test/org-person-forge.test.ts +1 −1
@@ -56,7 +56,7 @@ test("an invited person gets an account, not yet a forge that follows the organi
5656 expect(listReposOwnedBy(app.db, org.value.id).map((r) => r.name)).toEqual(["board"]);
5757
5858 // An invite is accepted.
59 const invite = mint(app, admin.value, 7);
59 const invite = mint(app, admin.value);
6060 if (!invite.ok) throw new Error(invite.error);
6161 const res = await fetch(`${servers.url}/signup?invite=${invite.value.token}`, {
6262 method: "POST",
test/perimeter-mediums.test.ts +2 −2
@@ -50,7 +50,7 @@ describe("perimeter mediums (#2922)", () => {
5050 const made = await post("/api/v1/repos", null, { name: "hooked", visibility: "public" });
5151 expect(made.status).toBe(201);
5252
53 const inviteFirst = await post("/api/v1/admin/invites", "m6-invite", { days: 3 });
53 const inviteFirst = await post("/api/v1/admin/invites", "m6-invite", {});
5454 expect(inviteFirst.status).toBe(201);
5555 const invite = (await inviteFirst.json()) as { token: string; link: string };
5656 expect(invite.link).toContain(invite.token);
@@ -62,7 +62,7 @@ describe("perimeter mediums (#2922)", () => {
6262 const hook = (await hookFirst.json()) as { secret: string };
6363 expect(hook.secret.length).toBeGreaterThan(8);
6464
65 const replayedInvite = await (await post("/api/v1/admin/invites", "m6-invite", { days: 3 })).text();
65 const replayedInvite = await (await post("/api/v1/admin/invites", "m6-invite", {})).text();
6666 const replayedHook = await (await post(hookPath, "m6-hook", hookBody)).text();
6767 const rows = (app.db.query("SELECT body FROM idempotency").all() as { body: string }[]).map((r) => r.body);
6868 expect(rows.length).toBeGreaterThanOrEqual(2);
test/request-access-limits.test.ts +2 −2
@@ -94,7 +94,7 @@ describe("the Waiting list is bounded", () => {
9494 expect(refused.status).toBe(403);
9595 expect(getUserByName(app.db, "onetoomany")).toBeUndefined();
9696
97 const token = mint(app, getUserByName(app.db, "ada"), 7);
97 const token = mint(app, getUserByName(app.db, "ada"));
9898 if (!token.ok) throw new Error("no invite");
9999 const vouched = await api("vouched", { invite: token.value.token });
100100 expect(vouched.status).toBe(201);
@@ -167,7 +167,7 @@ describe("what an answer rests on", () => {
167167
168168 test("an open invite vouches in request mode: no wait, and the invite is spent", async () => {
169169 expect(getSignup(app.db)).toBe("request");
170 const token = mint(app, getUserByName(app.db, "ada"), 7);
170 const token = mint(app, getUserByName(app.db, "ada"));
171171 if (!token.ok) throw new Error("no invite");
172172 const res = await api("guest1", { invite: token.value.token });
173173 expect(res.status).toBe(201);
test/signup-gate-parent.test.ts +1
@@ -113,6 +113,7 @@ test("every caller of createUser says where its account comes from", async () =>
113113 "src/actions/contribute_token.ts": ["start"],
114114 "src/actions/crew.ts": ["agent"],
115115 "src/actions/first_admin.ts": ["first-admin"],
116 "src/actions/invite_link.ts": ["invite"],
116117 "src/actions/offer.ts": ["start"],
117118 "src/actions/spawn.ts": ["spawn", "spawn"],
118119 "src/actions/start.ts": ["start", "start"],
test/spend-words.test.ts −8
@@ -84,14 +84,6 @@ test("a ceiling out of range answers the module's sentence from the API and name
8484 expect(viaMcp).toMatchObject({ error: true, text: expect.stringContaining(`invalid: ${SPEND_WORDS.ceilings}`) });
8585 });
8686
87 test("an invite's days out of range answers the module's sentence from the API and names days over MCP", async () => {
88 const viaApi = await api("/api/v1/admin/invites", { days: 31 });
89 expect(viaApi).toMatchObject({ status: 422, body: { error: "invalid", message: SPEND_WORDS.inviteDays } });
90 const viaMcp = await tool("mint_invite", { days: 31 });
91 // The MCP holds `days` to its schema's 1 to 30 before the tool runs, naming the argument.
92 expect(viaMcp).toMatchObject({ error: true, text: expect.stringContaining('invalid: argument "days" is 31; expected integer from 1 to 30') });
93 });
94
9587 test("no file under src/ but the module types the sentences out", async () => {
9688 const root = join(import.meta.dir, "..", "src");
9789 const files = (await readdir(root, { recursive: true })).filter((f) => f.endsWith(".ts"));
test/start.test.ts +1 −1
@@ -181,7 +181,7 @@ describe("the defenses", () => {
181181 setAgentStart(forge.app.db, "code", admin.id);
182182 expect((await post("/api/v1/start", { name: "nope" }, {}, "198.51.100.40")).status).toBe(403);
183183 expect((await post("/api/v1/start", { name: "nope", code: "wrong" }, {}, "198.51.100.40")).status).toBe(403);
184 const invite = mintInvite(forge.app.db, admin.id, 7);
184 const invite = mintInvite(forge.app.db, admin.id);
185185 const ok = await post("/api/v1/start", { name: "coded", code: invite.token }, {}, "198.51.100.40");
186186 expect(ok.status).toBe(201);
187187 expect((await post("/api/v1/start", { name: "coded2", code: invite.token }, {}, "198.51.100.41")).status).toBe(403);
test/tui-invites.test.ts −17
@@ -82,7 +82,6 @@ describe("invite links in the terminal", () => {
8282 await open(h);
8383 expect(h.text()).toContain("No invite link yet");
8484 await h.press("m");
85 await h.press("enter");
8685 expect(h.text()).toContain("What the invite allows");
8786 await h.press("enter");
8887 expect(forge.config.url).toBeUndefined();
@@ -135,7 +134,6 @@ describe("invite links in the terminal", () => {
135134 await open(h);
136135 await h.press("m");
137136 await h.press("enter");
138 await h.press("enter");
139137 const made = listInvites(forge.db).find((i) => i.state === "open")!;
140138 for (const k of ["n", "esc"]) {
141139 await h.press("x");
@@ -149,30 +147,15 @@ describe("invite links in the terminal", () => {
149147 h.stop();
150148 });
151149
152 test("days outside 1 to 30 make nothing", async () => {
153 const before = listInvites(forge.db).length;
154 const h = boot("alice");
155 await open(h);
156 await h.press("m");
157 await h.press("backspace");
158 await h.type("0");
159 await h.press("enter");
160 expect(h.text()).toContain("1 to 30");
161 expect(listInvites(forge.db).length).toBe(before);
162 h.stop();
163 });
164
165150 test("Build is picked in the terminal; Host with no machine says why and mints nothing", async () => {
166151 const before = listInvites(forge.db).length;
167152 const h = boot("alice");
168153 await open(h);
169154 await h.press("m");
170 await h.press("enter");
171155 await h.press("down", "down", "enter");
172156 expect(listInvites(forge.db).length).toBe(before + 1);
173157 expect(listInvites(forge.db)[0]!.bundle).toBe("build");
174158 await h.press("m");
175 await h.press("enter");
176159 await h.press("down", "enter");
177160 expect(h.text()).toContain("Host needs a machine this forge can offer");
178161 expect(listInvites(forge.db).length).toBe(before + 1);
test/tui-signup-invite.test.ts +4 −4
@@ -84,7 +84,7 @@ describe("terminal sign-up with an invite", () => {
8484 });
8585
8686 test("an expired token says so kindly and names who sent it", async () => {
87 const { token } = mintInvite(forge.db, adminId, 1, Date.now() - 3 * 86_400_000);
87 const { token } = mintInvite(forge.db, adminId, Date.now() - 4 * 86_400_000);
8888 const text = await attempt("tardy", token);
8989 expect(text).toContain("This link has expired");
9090 expect(text).toContain("alice");
@@ -93,7 +93,7 @@ describe("terminal sign-up with an invite", () => {
9393 });
9494
9595 test("a pasted open token says when it works until, before anything is submitted", async () => {
96 const { token } = mintInvite(forge.db, adminId, 3);
96 const { token } = mintInvite(forge.db, adminId);
9797 const text = await attempt("early", token, false);
9898 expect(text).toContain("This link works until");
9999 expect(getUserByName(forge.db, "early")).toBeFalsy();
@@ -101,7 +101,7 @@ describe("terminal sign-up with an invite", () => {
101101 });
102102
103103 test("a pasted expired token says so on the invite step, before submit", async () => {
104 const { token } = mintInvite(forge.db, adminId, 1, Date.now() - 3 * 86_400_000);
104 const { token } = mintInvite(forge.db, adminId, Date.now() - 4 * 86_400_000);
105105 const text = await attempt("early2", token, false);
106106 expect(text).toContain("This link has expired");
107107 forge.db.query("DELETE FROM invite WHERE expires_at < ?1").run(new Date().toISOString());
@@ -153,7 +153,7 @@ describe("terminal sign-up with an invite", () => {
153153 const plain = await attempt("plainly", mintInvite(forge.db, adminId).token, true, KEY2);
154154 expect(getUserByName(forge.db, "plainly")).toBeTruthy();
155155 expect(plain).not.toContain("Welcome to");
156 const { token } = mintInvite(forge.db, adminId, 7, Date.now(), org.value.id);
156 const { token } = mintInvite(forge.db, adminId, Date.now(), org.value.id);
157157 const text = await attempt("orgy", token, true, KEY3);
158158 expect(getUserByName(forge.db, "orgy")).toBeTruthy();
159159 expect(text).toContain("Welcome to acme");
test/who-can.test.ts +2 −1
@@ -74,6 +74,7 @@ describe("who may do what", () => {
7474 sql("INSERT INTO origin_read_grant (repo_id, kind, grantee_id, granted_by) VALUES (?1, 'crew', ?2, ?3)", repo.value.id, dave, id("alice"));
7575 sql("INSERT INTO pull_run_grant (issue_id, commit_oid, user_id) VALUES (?1, 'abcdef0123456789', ?2)", issue.value.id, dave);
7676 sql("INSERT INTO telemetry_grant (user_id, granted_by) VALUES (?1, ?2)", dave, id("alice"));
77 sql("INSERT INTO host_grant (user_id, machine, containers, memory_mb, invite_id, at) VALUES (?1, 'm1', 2, 512, 'inv1', ?2)", dave, at);
7778 createClientCloud(app.db, dir, { provider: "aws", label: "client-aws", key: "k", days: 3, by: id("alice"), now: new Date(at) });
7879 sql("INSERT INTO client_cloud_member (cloud_id, user_id, granted_by, granted_at) SELECT id, ?1, ?2, ?3 FROM client_cloud", dave, id("alice"), at);
7980 sql("INSERT INTO crew_team_member (team_slug, user_id) VALUES ('design', ?1)", dave);
@@ -90,7 +91,7 @@ describe("who may do what", () => {
9091 test("one grant in each table, and the view lists every one", () => {
9192 const seen = new Set(everyGrant(app.db).map((g) => g.table));
9293 expect([...GRANT_TABLES].filter((t) => !seen.has(t))).toEqual([]);
93 expect(GRANT_TABLES.length).toBe(16);
94 expect(GRANT_TABLES.length).toBe(17);
9495 });
9596
9697 test("by person: everything dave can reach, with who granted it and where it is changed", () => {

Search
↑↓ navigate ↵ open ⌘↵ its app esc close

Keyboard shortcuts

Docs