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

An invite carries a bundle: the owner picks Use, Host or Build, each with a line saying what it allows #18473

opened this

Merged 3h 22m ago, live in production

scout/forge:scout/18453-an-invite-carries-a-bundle-the-owner-pic → main 0 commits fork 2 threads · 2 unresolved

  • Merged. scout/18453-an-invite-carries-a-bundle-the-owner-pic was merged into main as d231856.

Review

Sign in to review this change.
14 files changed +476 −45
docs/features/invite-bundle.md added +12
@@ -0,0 +1,12 @@
1 ---
2 topic: Hosting forges for others, and getting paid
3 row: Invite with a bundle: Use, Host or Build
4 ---
5 # An invite carries a bundle
6
7 Mint an invite with a bundle: `POST /api/v1/admin/invites {"bundle":"host","machine":"shop-1","containers":3,"memoryMb":2048}`, the MCP `mint_invite` with the same fields, or the bundle choice on Invite links at /admin/limits. Without one it is Use.
8 - **Use**: a guest, with what is shared with them.
9 - **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.
10 - **Build**: a member: repositories, apps and a crew.
11
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.
src/actions/invites.ts +53 −4
@@ -12,6 +12,7 @@ import {
1212 listInvites,
1313 mintInvite,
1414 mintRepoInvite,
15 MAX_DAYS,
1516 parseDays,
1617 redeemInvite,
1718 takeUpInvite,
@@ -27,10 +28,49 @@ import { canRead, canWrite, getRepoById, type Repo } from "../core/repos.ts";
2728 import { getUserByName } from "../core/users.ts";
2829 import { requireRepoAdmin, type AccessError } from "./access.ts";
2930 import { getOrg } from "../core/orgs.ts";
31 import { BUNDLES, HOST_WORDS, parseHost, type Bundle } from "../core/bundles.ts";
32 import { infraOf } from "./infra.ts";
3033 import { err, ok, type Result } from "../kernel/result.ts";
3134 import type { User } from "../core/users.ts";
3235
33 type Error = "not_found" | "invalid_days" | "unknown_org";
36 type Error = "not_found" | "invalid_days" | "unknown_org" | "invalid_bundle" | "no_machine" | "invalid_machine" | "invalid_cap";
37
38 /** What Host is given, as a door sends it: plain values, read by `parseHost`. */
39 export interface BundleInput {
40 readonly bundle?: unknown;
41 readonly machine?: unknown;
42 readonly containers?: unknown;
43 readonly memoryMb?: unknown;
44 }
45
46 /** The refusals a bundle can meet, in words. */
47 export const BUNDLE_WORDS: Record<"invalid_bundle" | "no_machine" | "invalid_machine" | "invalid_cap", string> = {
48 invalid_bundle: "A bundle is Use, Host or Build.",
49 no_machine: HOST_WORDS.noMachine,
50 invalid_machine: HOST_WORDS.badMachine,
51 invalid_cap: HOST_WORDS.badCap,
52 };
53
54 /** A refusal of `mint` in words: every door says the same. */
55 export function mintRefusal(error: Error): string {
56 switch (error) {
57 case "invalid_days":
58 return `Days is a whole number from 1 to ${MAX_DAYS}.`;
59 case "unknown_org":
60 return "No organization by that name.";
61 case "not_found":
62 return "You cannot make invite links.";
63 default:
64 return BUNDLE_WORDS[error];
65 }
66 }
67
68 /** The machines this forge can offer a Host: those running, by name; admin's to read. */
69 export function hostMachines(app: App, actor: User | undefined): string[] {
70 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);
73 }
3474
3575 const admin = (actor: User | undefined): actor is User =>
3676 actor !== undefined && actor.isAdmin && actor.kind === "user";
@@ -43,7 +83,7 @@ export const inviteLink = (origin: string, token: string): string =>
4383 * `org` names the organization the invite brings its person into; absent or empty is a plain
4484 * invite.
4585 */
46 export function mint(app: App, actor: User | undefined, days: unknown, org?: unknown): Result<{ invite: Invite; token: string }, Error> {
86 export function mint(app: App, actor: User | undefined, days: unknown, org?: unknown, choice: BundleInput = {}): Result<{ invite: Invite; token: string }, Error> {
4787 if (!admin(actor)) return err("not_found");
4888 const n = parseDays(days);
4989 if (!n.ok) return n;
@@ -51,11 +91,20 @@ export function mint(app: App, actor: User | undefined, days: unknown, org?: unk
5191 if (org !== undefined && org !== null && typeof org !== "string") return err("unknown_org");
5292 const target = name === "" ? undefined : getOrg(app.db, name);
5393 if (name !== "" && target === undefined) return err("unknown_org");
54 const made = mintInvite(app.db, actor.id, n.value, Date.now(), target?.id ?? null);
94 const wanted = choice.bundle === undefined || choice.bundle === null || choice.bundle === "" ? "use" : choice.bundle;
95 if (!BUNDLES.includes(wanted as Bundle)) return err("invalid_bundle");
96 const bundle = wanted as Bundle;
97 let host = null;
98 if (bundle === "host") {
99 const h = parseHost(choice, hostMachines(app, actor));
100 if (!h.ok) return err(h.error === "noMachine" ? "no_machine" : h.error === "badMachine" ? "invalid_machine" : "invalid_cap");
101 host = h.value;
102 }
103 const made = mintInvite(app.db, actor.id, n.value, Date.now(), target?.id ?? null, bundle, host);
55104 app.bus.append({
56105 kind: "invite.minted",
57106 actorId: actor.id,
58 payload: { id: made.invite.id, expiresAt: made.invite.expiresAt, ...(target === undefined ? {} : { org: target.username }) },
107 payload: { id: made.invite.id, expiresAt: made.invite.expiresAt, bundle, ...(target === undefined ? {} : { org: target.username }) },
59108 });
60109 return ok(made);
61110 }
src/core/bundles.ts added +77
@@ -0,0 +1,77 @@
1 /**
2 * The bundle an invite carries: Use, Host or Build. Each is one line a person can read and the
3 * grants it stands for, written once here as plain data over `may()` actions (`core/may.ts`); no
4 * check lives here. Minting stores the bundle; applying its grants is a later step's.
5 */
6
7 import type { Action } from "./may.ts";
8 import type { Role } from "./roles.ts";
9
10 export const BUNDLES = ["use", "host", "build"] as const;
11 export type Bundle = (typeof BUNDLES)[number];
12 export const DEFAULT_BUNDLE: Bundle = "use";
13
14 export interface BundleRow {
15 readonly label: string;
16 /** What it allows, in one plain line. */
17 readonly says: string;
18 /** The role the person is let in as. */
19 readonly role: Extract<Role, "guest" | "member">;
20 /** The `may()` actions it stands for. */
21 readonly grants: readonly Action[];
22 }
23
24 export const BUNDLE: Readonly<Record<Bundle, BundleRow>> = {
25 use: {
26 label: "Use",
27 says: "A guest: reads and uses what is shared with them, and changes nothing else.",
28 role: "guest",
29 grants: ["forge.read", "forge.comment", "forge.contribute"],
30 },
31 host: {
32 label: "Host",
33 says: "A guest who makes and runs their own containers on one machine, up to a cap.",
34 role: "guest",
35 grants: ["forge.read", "forge.comment", "forge.contribute", "forge.make_it_yours"],
36 },
37 build: {
38 label: "Build",
39 says: "A member: makes repositories and apps and runs a crew.",
40 role: "member",
41 grants: ["forge.read", "forge.comment", "forge.contribute", "forge.make_it_yours", "forge.run_crew", "repo.write"],
42 },
43 };
44
45 /** The one sentence a bundle says; an unknown word reads as Use (an old invite has none). */
46 export const bundleOf = (raw: unknown): Bundle => (BUNDLES.includes(raw as Bundle) ? (raw as Bundle) : DEFAULT_BUNDLE);
47
48 /** What Host is given: one machine of the offered list and a cap on containers and on memory. */
49 export interface HostChoice {
50 readonly machine: string;
51 readonly containers: number;
52 readonly memoryMb: number;
53 }
54
55 export const HOST_WORDS = {
56 noMachine: "Host needs a machine this forge can offer, and it has none: connect a cloud account and build one first.",
57 badMachine: "That machine is not one this forge offers.",
58 badCap: "Containers and memory are each a positive whole number.",
59 } as const;
60
61 const positive = (v: unknown): number | undefined => {
62 const n = typeof v === "string" && /^\d{1,7}$/.test(v.trim()) ? Number(v) : v;
63 return typeof n === "number" && Number.isInteger(n) && n > 0 && n <= 10_000_000 ? n : undefined;
64 };
65
66 /** The Host choice as sent, against the machines on offer; the refusal key otherwise. */
67 export function parseHost(
68 raw: { machine?: unknown; containers?: unknown; memoryMb?: unknown },
69 offered: readonly string[],
70 ): { ok: true; value: HostChoice } | { ok: false; error: keyof typeof HOST_WORDS } {
71 if (offered.length === 0) return { ok: false, error: "noMachine" };
72 if (typeof raw.machine !== "string" || !offered.includes(raw.machine)) return { ok: false, error: "badMachine" };
73 const containers = positive(raw.containers);
74 const memoryMb = positive(raw.memoryMb);
75 if (containers === undefined || memoryMb === undefined) return { ok: false, error: "badCap" };
76 return { ok: true, value: { machine: raw.machine, containers, memoryMb } };
77 }
src/core/invites.ts +29 −2
@@ -11,6 +11,7 @@ import type { Database } from "bun:sqlite";
1111 import { sha256 } from "../kernel/hash.ts";
1212 import { id, secret } from "../kernel/id.ts";
1313 import { err, ok, type Result } from "../kernel/result.ts";
14 import { bundleOf, type Bundle, type HostChoice } from "./bundles.ts";
1415
1516 export const DEFAULT_DAYS = 7;
1617 export const MAX_DAYS = 30;
@@ -30,6 +31,10 @@ export interface Invite {
3031 readonly usedBy: string | null;
3132 /** The organization the invite brings its person into, or null for a plain invite. */
3233 readonly org: string | null;
34 /** What it lets its person do; an invite made before bundles reads as use. */
35 readonly bundle: Bundle;
36 /** For host: the machine and caps; null otherwise. */
37 readonly host: HostChoice | null;
3338 }
3439
3540 interface Row {
@@ -45,6 +50,10 @@ interface Row {
4550 used_by: string | null;
4651 org_id: string | null;
4752 org_name: string | null;
53 bundle: string | null;
54 host_machine: string | null;
55 host_containers: number | null;
56 host_memory_mb: number | null;
4857 }
4958
5059 /** An invite with its redeemer's username, resolved in the one query. */
@@ -63,6 +72,11 @@ const view = (r: Row, now: number): Invite => ({
6372 usedAt: r.used_at,
6473 usedBy: r.used_at === null ? null : r.used_by_name,
6574 org: r.org_name,
75 bundle: bundleOf(r.bundle),
76 host:
77 r.host_machine === null || r.host_containers === null || r.host_memory_mb === null
78 ? null
79 : { machine: r.host_machine, containers: r.host_containers, memoryMb: r.host_memory_mb },
6680 });
6781
6882 /** A whole number of days from 1 to 30, or the default when absent. */
@@ -79,12 +93,25 @@ export function mintInvite(
7993 now: number = Date.now(),
8094 /** The id of the organization the invite brings its person into. */
8195 orgId: string | null = null,
96 bundle: Bundle = "use",
97 host: HostChoice | null = null,
8298 ): { invite: Invite; token: string } {
8399 const token = `invite_${secret()}`;
84100 const inviteId = id(now);
85101 db.query(
86 "INSERT INTO invite (id, token_hash, created_by, created_at, expires_at, org_id) VALUES (?1, ?2, ?3, ?4, ?5, ?6)",
87 ).run(inviteId, sha256(token), createdBy, new Date(now).toISOString(), new Date(now + days * DAY).toISOString(), orgId);
102 "INSERT INTO invite (id, token_hash, created_by, created_at, expires_at, org_id, bundle, host_machine, host_containers, host_memory_mb) VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7, ?8, ?9, ?10)",
103 ).run(
104 inviteId,
105 sha256(token),
106 createdBy,
107 new Date(now).toISOString(),
108 new Date(now + days * DAY).toISOString(),
109 orgId,
110 bundle,
111 host?.machine ?? null,
112 host?.containers ?? null,
113 host?.memoryMb ?? null,
114 );
88115 const row = db.query<Row, [string]>(`${SELECT} WHERE invite.id = ?1`).get(inviteId)!;
89116 return { invite: view(row, now), token };
90117 }
src/core/migration-pins/20261206100000-invite-bundle.pin added +1
@@ -0,0 +1,1 @@
1 2c2b7c9e9ee6792c782891bd93e536dd32d3d3d9f20aae5b94afd03b295a48ef
src/core/migrations/20261206100000-invite-bundle.ts added +8
@@ -0,0 +1,8 @@
1 // An invite carries a bundle (#18453): use, host or build, and for host the machine and caps.
2 // All nullable: an invite made before reads as use. Additive.
3 export default `
4 ALTER TABLE invite ADD COLUMN bundle TEXT;
5 ALTER TABLE invite ADD COLUMN host_machine TEXT;
6 ALTER TABLE invite ADD COLUMN host_containers INTEGER;
7 ALTER TABLE invite ADD COLUMN host_memory_mb INTEGER;
8 `;
src/http/api/admin.ts +7 −8
@@ -19,7 +19,7 @@ import { ACCESS_WORDS, accessUrl, endAllSessions, resetAccess } from "../../acti
1919 import { ADMIN_WORDS } from "../../actions/admin_words.ts";
2020 import { DERIVED_WORDS, REASON_WORDS, changeCapacity, edgeOffDryRun, listCapacity } from "../../actions/capacity.ts";
2121 import { changeShield, lastShieldChange, shieldState } from "../../actions/shield.ts";
22 import { inviteLink, list as listInviteLinks, mint as mintInviteLink, revoke as revokeInviteLink } from "../../actions/invites.ts";
22 import { inviteLink, mintRefusal, list as listInviteLinks, mint as mintInviteLink, revoke as revokeInviteLink } from "../../actions/invites.ts";
2323 import { changeLimit, listLimits } from "../../actions/limits.ts";
2424 import { changePlans, measuredPlans } from "../../actions/plans.ts";
2525 import { setAccountCeilings, setAccountGrant } from "../../actions/model_grant.ts";
@@ -569,13 +569,12 @@ 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);
573 if (!made.ok)
574 return made.error === "invalid_days"
575 ? apiError("invalid", 422, SPEND_WORDS.inviteDays)
576 : made.error === "unknown_org"
577 ? apiError("invalid", 422, "no such organization")
578 : notFound();
572 const made = mintInviteLink(ctx.app, ctx.auth.user, input.days, input.org, input);
573 if (!made.ok) {
574 if (made.error === "not_found") return notFound();
575 if (made.error === "invalid_days") return apiError("invalid", 422, SPEND_WORDS.inviteDays);
576 return apiError("invalid", 422, made.error === "unknown_org" ? "no such organization" : mintRefusal(made.error));
577 }
579578 const origin = ctx.app.config.url ?? ctx.url.origin;
580579 return json(
581580 { ...made.value.invite, token: made.value.token, link: inviteLink(origin, made.value.token) },
src/http/mcp/tools/mint_invite.ts +16 −4
@@ -1,12 +1,12 @@
11 import { SPEND_WORDS } from "../../../actions/spend_words.ts";
2 import { inviteLink, mint as mintInviteLink } from "../../../actions/invites.ts";
2 import { inviteLink, mintRefusal, mint as mintInviteLink } from "../../../actions/invites.ts";
33 import { scopeAllows } from "../../../core/tokens.ts";
44 import { good, bad, type Tool, mayBoards } from "../shared.ts";
55
66 export const tool: Tool = {
77 name: "mint_invite",
88 listedTo: "admin",
9 doc: "`{ days?, org? }`: 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; a person admin's, with an admin token",
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",
1010 description:
1111 "Mint a one-use invite link, shown once, valid `days` (1–30, default 7). Person admins.",
1212 inputSchema: {
@@ -14,6 +14,10 @@ export const tool: Tool = {
1414 properties: {
1515 days: { type: "integer", minimum: 1, maximum: 30 },
1616 org: { type: "string", description: "Organization the person joins" },
17 bundle: { type: "string", enum: ["use", "host", "build"] },
18 machine: { type: "string", description: "Host: a machine the forge offers" },
19 containers: { type: "integer", minimum: 1 },
20 memoryMb: { type: "integer", minimum: 1 },
1721 },
1822 },
1923 writes: true,
@@ -21,8 +25,16 @@ export const tool: Tool = {
2125 if (!mayBoards(user)) return bad("forbidden", "an invite is a forge admin's to mint");
2226 if (!scopeAllows(ctx.auth.scope ?? "ro", "admin"))
2327 return bad("forbidden", "an invite needs an admin token");
24 const made = mintInviteLink(ctx.app, user, args["days"], args["org"]);
25 if (!made.ok) return bad("invalid", made.error === "unknown_org" ? "no such organization" : SPEND_WORDS.inviteDays);
28 const made = mintInviteLink(ctx.app, user, args["days"], args["org"], args);
29 if (!made.ok)
30 return bad(
31 "invalid",
32 made.error === "invalid_days"
33 ? SPEND_WORDS.inviteDays
34 : made.error === "unknown_org"
35 ? "no such organization"
36 : mintRefusal(made.error),
37 );
2638 const origin = ctx.app.config.url ?? ctx.url.origin;
2739 return good({ ...made.value.invite, link: inviteLink(origin, made.value.token) });
2840 },
src/tui/screens/invites.ts +72 −22
@@ -1,29 +1,30 @@
11 /**
22 * Invite links in the terminal, a forge admin's (#2337): every link with its
33 * state, when it was made and when it expires, as Invite links on /admin/limits
4 * shows them. `m` mints one from a number of days (1 to 30, 7 by default) and
5 * prints the link once (`o` makes one for an organization: its person joins it and gets private
6 * forks of its apps), on this screen, until the next key of any kind; `x` revokes the
7 * selected open one after a confirm (`y` revokes, `n` or esc keeps it). Both go through the actions, so the gate is theirs: an
8 * admin who is a person; anyone else sees nothing and mints nothing. The top
9 * line says who may sign up now, as MCP `signup` does; `s` picks open, invite
10 * or closed, shows from → to and changes it only after a confirm; `a` does the
11 * same for who may start an agent here (open, code or off, `Agents can start here`).
4 * shows them. `m` mints one from a number of days (1 to 30, 7 by default) and a bundle (Use, Host
5 * with a machine and two caps, or Build) and prints the link once (`o` makes one for an
6 * organization: its person joins it and gets private forks of its apps), on this screen, until the
7 * next key of any kind; `x` revokes the selected open one after a confirm (`y` revokes, `n` or esc
8 * keeps it). Both go through the actions, so the gate is theirs: an admin who is a person; anyone
9 * else sees nothing and mints nothing. The top line says who may sign up now, as MCP `signup` does;
10 * `s` picks open, invite or closed, shows from → to and changes it only after a confirm; `a` does
11 * the same for who may start an agent here (open, code or off, `Agents can start here`).
1212 */
1313
14 import { inviteLink, list, mint, revoke } from "../../actions/invites.ts";
14 import { hostMachines, inviteLink, list, mint, mintRefusal, revoke, type BundleInput } from "../../actions/invites.ts";
15 import { BUNDLE, BUNDLES } from "../../core/bundles.ts";
1516 import { INVITE_NOT_OPEN } from "../../actions/sever_invite_words.ts";
1617 import { changeAgentStart, changeSignup, readAgentStart, readSignup } from "../../actions/signup.ts";
1718 import { AGENT_START_MODES, type AgentStartMode } from "../../settings/agent_start.ts";
1819 import { SIGNUP_MODES, type SignupMode } from "../../settings/signup.ts";
19 import { DEFAULT_DAYS, MAX_DAYS, type Invite } from "../../core/invites.ts";
20 import { DEFAULT_DAYS, MAX_DAYS, parseDays, type Invite } from "../../core/invites.ts";
2021 import type { Ctx, Screen } from "../app/app.ts";
2122 import { binding } from "../app/keys.ts";
2223 import { style } from "../term/style.ts";
2324 import { truncate } from "../term/width.ts";
2425 import type { Session } from "../session.ts";
2526 import { fill, len, split } from "../ui/layout.ts";
26 import { ListState, confirmScreen, drawList, pickerScreen, promptScreen, type ListRow } from "./common.ts";
27 import { ListState, confirmScreen, drawList, later, pickerScreen, promptScreen, type ListRow } from "./common.ts";
2728 import type { PaletteEntry } from "./entries.ts";
2829
2930 /** `used by ada on 2026-10-01`; the name is left out when the account is gone. */
@@ -39,22 +40,70 @@ export function invitesScreen(f: Session, ctx: Ctx): Screen {
3940 return r.ok ? r.value : [];
4041 };
4142
42 const make = (raw: string, org = ""): string | undefined => {
43 const daysOf = (raw: string): number => {
4344 const text = raw.trim();
44 const days = text === "" ? DEFAULT_DAYS : /^\d{1,3}$/.test(text) ? Number(text) : -1;
45 const made = mint(f.app, f.user, days, org);
46 if (!made.ok)
47 return made.error === "invalid_days"
48 ? `Days is a whole number from 1 to ${MAX_DAYS}.`
49 : made.error === "unknown_org"
50 ? "No organization by that name."
51 : "You cannot make invite links.";
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);
50 if (!made.ok) return mintRefusal(made.error);
5251 const origin = f.app.config.url ?? `http://localhost:${f.app.config.port}`;
5352 note = `Shown once: ${inviteLink(origin, made.value.token)}`;
5453 ctx.invalidate();
5554 return undefined;
5655 };
5756
57 /**
58 * After the days: pick the bundle; Host goes on to its machine and two caps, each refused in the
59 * words the page uses.
60 */
61 const pickBundle = (days: string): Screen =>
62 pickerScreen(ctx, screen, {
63 title: "What the invite allows",
64 items: BUNDLES.map((b) => ({ id: b, label: BUNDLE[b].label, hint: BUNDLE[b].says })),
65 onPick: ([b]) => {
66 if (b !== "host") {
67 const refused = make(days, "", { bundle: b });
68 if (refused !== undefined) note = refused;
69 return;
70 }
71 const machines = hostMachines(f.app, f.user);
72 if (machines.length === 0) {
73 note = mintRefusal("no_machine");
74 return;
75 }
76 void later(ctx, () =>
77 pickerScreen(ctx, screen, {
78 title: "Host: which machine",
79 items: machines.map((m) => ({ id: m, label: m })),
80 onPick: ([machine]) => {
81 void later(ctx, () =>
82 promptScreen(ctx, screen, {
83 title: "Host: containers",
84 label: "most containers, a positive whole number",
85 value: "3",
86 onSubmit: (containers) =>
87 later(ctx, () =>
88 promptScreen(ctx, screen, {
89 title: "Host: memory",
90 label: "most memory in MB, a positive whole number",
91 value: "2048",
92 onSubmit: (memoryMb) => {
93 const refused = make(days, "", { bundle: "host", machine, containers, memoryMb });
94 if (refused !== undefined) return refused;
95 return undefined;
96 },
97 }),
98 ),
99 }),
100 );
101 },
102 }),
103 );
104 },
105 });
106
58107 const signup = () => readSignup(f.app, f.user);
59108
60109 const plan = (to: SignupMode): void => {
@@ -110,7 +159,7 @@ export function invitesScreen(f: Session, ctx: Ctx): Screen {
110159 get keys() {
111160 return [
112161 binding(["j", "k"], "move cursor"),
113 binding(["m"], "make a link"),
162 binding(["m"], "make a link: Use, Host or Build"),
114163 binding(["o"], "make a link to an organization"),
115164 binding(["x"], "revoke"),
116165 ...(signup().ok ? [binding(["s"], "who may sign up"), binding(["a"], "agents can start here")] : []),
@@ -145,7 +194,8 @@ export function invitesScreen(f: Session, ctx: Ctx): Screen {
145194 title: "Invite link",
146195 label: `days until it expires, 1 to ${MAX_DAYS}`,
147196 value: String(DEFAULT_DAYS),
148 onSubmit: make,
197 onSubmit: (days) =>
198 !parseDays(daysOf(days)).ok ? mintRefusal("invalid_days") : later(ctx, () => pickBundle(days)),
149199 }),
150200 );
151201 } else if (e.key === "o") {
src/web/pages/admin-limits.ts +36 −4
@@ -11,7 +11,8 @@ 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 { inviteLink, list as listInviteLinks, mint as mintInviteLink, revoke as revokeInviteLink } from "../../actions/invites.ts";
14 import { BUNDLE_WORDS, hostMachines, inviteLink, list as listInviteLinks, mint as mintInviteLink, revoke as revokeInviteLink } from "../../actions/invites.ts";
15 import { BUNDLE, BUNDLES } from "../../core/bundles.ts";
1516 import { INVITE_NOT_OPEN } from "../../actions/sever_invite_words.ts";
1617 import { DEFAULT_DAYS, MAX_DAYS } from "../../core/invites.ts";
1718 import { changeAgentStart, changeBillingLinks, changeSignup, readAgentStart, readBillingLinks, readSignup } from "../../actions/signup.ts";
@@ -25,7 +26,7 @@ import { notFoundPage, settingsLayout } from "../chrome.ts";
2526 import { field, readForm } from "../form.ts";
2627 import { html, when, type Html } from "../html.ts";
2728 import { flashTo, page } from "../layout.ts";
28 import { btn, confirmAction, icon, row, time } from "../ui.ts";
29 import { btn, confirmAction, disclosure, field as inputField, icon, row, selectField, time } from "../ui.ts";
2930 import { emptyList } from "../empty_words.ts";
3031 import { plansRow } from "../settings/plans.ts";
3132 import { accountSections } from "./origins.ts";
@@ -186,13 +187,35 @@ export function limitsPage(ctx: Ctx): Response {
186187 i.usedAt === null ? "" : ` on ${i.usedAt.slice(0, 10)}`
187188 }`
188189 }</span>`,
189 meta: html`Made ${time(i.createdAt)} · expires ${time(i.expiresAt)}`,
190 meta: html`${BUNDLE[i.bundle].label}${
outdated

Principle 1: the bundle's full sentence is repeated on every listed invite, and again on the form. List the label (plus machine and caps for Host) here and keep the sentence on the form only.

191 i.host === null ? "" : ` on ${i.host.machine}, up to ${i.host.containers} containers and ${i.host.memoryMb} MB`
192 } · Made ${time(i.createdAt)} · expires ${time(i.expiresAt)}`,
190193 trail:
191194 i.state === "open"
192195 ? confirmAction({ action: `/admin/invites/${i.id}/revoke`, verb: "Revoke", size: "sm" })
193196 : html``,
194197 }),
195198 );
199 const machines = hostMachines(ctx.app, ctx.auth.user);
200 const bundleField = selectField({
201 name: "bundle",
202 label: "what it allows",
outdated

Design system: a hand-rolled fieldset with radios, <strong> and <em>, and Host fields that are always on show. Use the named form components and show the Host fields only when they apply, working with JavaScript off.

203 options: BUNDLES.filter((b) => b !== "host" || machines.length > 0).map((b) => ({
204 value: b,
205 label: `${BUNDLE[b].label}: ${BUNDLE[b].says}`,
206 selected: b === "use",
207 })),
208 ...(machines.length === 0 ? { hint: BUNDLE_WORDS.no_machine } : {}),
209 });
210 const hostFields =
211 machines.length === 0
212 ? html``
213 : disclosure(
214 "Host only: machine and caps",
215 html`${selectField({ name: "machine", label: "machine", options: machines.map((m) => ({ value: m, label: m })) })}
216 ${inputField({ name: "containers", label: "most containers", type: "number", value: "3", min: 1, step: "1", mono: true })}
217 ${inputField({ name: "memoryMb", label: "most memory (MB)", type: "number", value: "2048", min: 1, step: "1", mono: true })}`,
218 );
196219 const inviteRow = html`<div class="status-row">
197220 <dt>Invite links</dt>
198221 <dd>
@@ -209,6 +232,8 @@ export function limitsPage(ctx: Ctx): Response {
209232 /></label>
210233 <label class="small">organization (optional)
211234 <input class="input mono" type="text" name="org" maxlength="60" autocomplete="off" /></label>
235 ${bundleField}
236 ${hostFields}
212237 ${btn("Make a link", { size: "sm", variant: "primary", label: "Make an invite link" })}
213238 </form>
214239 <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>
@@ -373,10 +398,17 @@ export async function inviteMint(ctx: Ctx): Promise<Response> {
373398 const form = await readForm(ctx, "admin");
374399 if (form instanceof Response) return form;
375400 const raw = field(form, "days").trim();
376 const made = mintInviteLink(ctx.app, ctx.auth.user, /^\d{1,3}$/.test(raw) ? Number(raw) : -1, field(form, "org"));
401 const made = mintInviteLink(ctx.app, ctx.auth.user, /^\d{1,3}$/.test(raw) ? Number(raw) : -1, field(form, "org"), {
402 bundle: field(form, "bundle"),
403 machine: field(form, "machine"),
404 containers: field(form, "containers"),
405 memoryMb: field(form, "memoryMb"),
406 });
377407 if (!made.ok && made.error === "not_found") return notFoundPage(ctx);
378408 if (!made.ok && made.error === "unknown_org")
379409 return flashTo(ctx, "/admin/limits", { tone: "danger", message: "No organization by that name." });
410 if (!made.ok && made.error in BUNDLE_WORDS)
411 return flashTo(ctx, "/admin/limits", { tone: "danger", message: BUNDLE_WORDS[made.error as keyof typeof BUNDLE_WORDS] });
380412 if (!made.ok)
381413 return flashTo(ctx, "/admin/limits", {
382414 tone: "danger",
test/invite-bundles.test.ts added +142
@@ -0,0 +1,142 @@
1 /**
2 * An invite carries a bundle (#18453): Use, Host or Build, each with its line; Host names one of
3 * the forge's machines and caps. An invite made before reads as Use. Nothing here applies the
4 * grants.
5 */
6 import { afterAll, beforeAll, describe, expect, test } from "bun:test";
7 import { mkdtemp, rm } from "node:fs/promises";
8 import { tmpdir } from "node:os";
9 import { join } from "node:path";
10 import { createApp, type App } from "../src/app.ts";
11 import { list, mint } from "../src/actions/invites.ts";
12 import { BUNDLE, BUNDLES, parseHost } from "../src/core/bundles.ts";
13 import { ACTIONS } from "../src/core/may.ts";
14 import { tool as mintTool } from "../src/http/mcp/tools/mint_invite.ts";
15 import type { Ctx } from "../src/http/context.ts";
16 import { insertPinned } from "../src/core/pinned.ts";
17 import { mintInvite } from "../src/core/invites.ts";
18 import type { User } from "../src/core/users.ts";
19 import { serve, type Servers } from "../src/http/server.ts";
20 import { createSession } from "../src/core/sessions.ts";
21 import { seedAdmin } from "./helpers/admin.ts";
22 import { quietLogs } from "./helpers/globals.ts";
23
24 quietLogs();
25
26 describe("invite bundles", () => {
27 let dir = "";
28 let app: App;
29 let admin: User;
30 let servers: Servers;
31 let cookie = "";
32
33 beforeAll(async () => {
34 dir = await mkdtemp(join(tmpdir(), "forge-invite-bundles-"));
35 app = createApp({ dataDir: dir, port: 0 });
36 const made = await seedAdmin(app, { username: "olive", email: "[email protected]", password: "an-invited-passphrase" });
37 if (!made.ok) throw new Error(made.error);
38 admin = made.value;
39 servers = await serve(app);
40 cookie = `forge_session=${createSession(app.db, admin.id).token}`;
41 });
42 afterAll(async () => {
43 await servers.stop();
44 app.close();
45 await rm(dir, { recursive: true, force: true });
46 });
47
48 const page = async (): Promise<string> => (await fetch(`${servers.url}/admin/limits`, { headers: { cookie } })).text();
49 const pinMachine = (name: string): void => {
50 insertPinned(
51 app.db,
52 { name, target: "digitalocean", account: "main", app: "ada/shop", source: "", version: "v1", config: {}, host: `${name}.example.com`, claimHash: "", claimExpires: "", datacenter: "fra1", size: "s-1vcpu-1gb" },
53 "ada",
54 );
55 app.db.query("UPDATE pinned_forge SET state = 'online', remote = 'r-1' WHERE name = ?1").run(name);
56 };
57
58 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 });
60 expect(refused.ok ? "" : refused.error).toBe("no_machine");
61 const html = await page();
62 expect(html).toContain("Host needs a machine this forge can offer");
63 expect(html).toContain(BUNDLE.use.says);
64 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);
68 const bundles = (list(app, admin) as { ok: true; value: { bundle: string }[] }).value.map((i) => i.bundle);
69 expect(bundles).toEqual(["use", "build", "use"]);
70 expect(await page()).toContain(BUNDLE.build.says);
71 });
72
73 test("a bundle that is not one of three is refused", () => {
74 const r = mint(app, admin, 7, undefined, { bundle: "root" });
75 expect(r.ok ? "" : r.error).toBe("invalid_bundle");
76 });
77
78 test("Host with a machine on offer stores the machine and caps; a stranger machine or a bad cap is refused", async () => {
79 pinMachine("shop-1");
80 const bad = (c: object) => {
81 const r = mint(app, admin, 7, undefined, { bundle: "host", ...c });
82 return r.ok ? "" : r.error;
83 };
84 expect(bad({ machine: "elsewhere", containers: 2, memoryMb: 512 })).toBe("invalid_machine");
85 expect(bad({ machine: "shop-1", containers: 0, memoryMb: 512 })).toBe("invalid_cap");
86 expect(bad({ machine: "shop-1", containers: 2, memoryMb: -1 })).toBe("invalid_cap");
87 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" });
89 expect(ok.ok && ok.value.invite.host).toEqual({ machine: "shop-1", containers: 3, memoryMb: 1024 });
90 const html = await page();
91 expect(html).toContain("on shop-1, up to 3 containers and 1024 MB");
92 expect(html).not.toContain("<script>");
93 });
94
95 test("the API refuses with 422", async () => {
96 const res = await fetch(`${servers.url}/api/v1/admin/invites`, {
97 method: "POST",
98 headers: { cookie, "content-type": "application/json", origin: servers.url },
99 body: JSON.stringify({ bundle: "root" }),
100 });
101 expect(res.status).toBe(422);
102 });
103
104 test("the API mints a Host invite with its machine and caps", async () => {
105 pinMachine("api-1");
106 const res = await fetch(`${servers.url}/api/v1/admin/invites`, {
107 method: "POST",
108 headers: { cookie, "content-type": "application/json", origin: servers.url },
109 body: JSON.stringify({ bundle: "host", machine: "api-1", containers: 2, memoryMb: 512 }),
110 });
111 expect(res.status).toBe(201);
112 const made = (await res.json()) as { bundle: string; host: { machine: string; containers: number; memoryMb: number } };
113 expect(made.bundle).toBe("host");
114 expect(made.host).toEqual({ machine: "api-1", containers: 2, memoryMb: 512 });
115 });
116
117 test("MCP mint_invite takes a Host bundle and refuses a stranger machine", () => {
118 pinMachine("mcp-1");
119 const url = new URL("http://forge.test/mcp");
120 const ctx: Ctx = { app, request: new Request(url.href), url, params: {}, auth: { user: admin, scope: "admin", via: "token" }, theme: undefined };
121 const good = JSON.stringify(mintTool.run(ctx, admin, { bundle: "host", machine: "mcp-1", containers: 1, memoryMb: 256 }));
122 expect(good).toContain("mcp-1");
123 const bad = JSON.stringify(mintTool.run(ctx, admin, { bundle: "host", machine: "nowhere", containers: 1, memoryMb: 256 }));
124 expect(bad).toContain("not one this forge offers");
125 });
126
127 test("each bundle's grants are actions may() answers", () => {
128 for (const b of BUNDLES) for (const g of BUNDLE[b].grants) expect(g in ACTIONS).toBe(true);
129 });
130
131 test("an invite made before bundles reads as Use", () => {
132 const made = mintInvite(app.db, admin.id);
133 app.db.query("UPDATE invite SET bundle = NULL WHERE id = ?1").run(made.invite.id);
134 const row = (list(app, admin) as { ok: true; value: { id: string; bundle: string }[] }).value.find((i) => i.id === made.invite.id);
135 expect(row?.bundle).toBe("use");
136 });
137
138 test("every bundle has a line and grants", () => {
139 for (const b of BUNDLES) expect(BUNDLE[b].says.length).toBeGreaterThan(10);
140 expect(parseHost({ machine: "a", containers: 1, memoryMb: 1 }, []).ok).toBe(false);
141 });
142 });
test/invites-action.test.ts +1 −1
@@ -107,7 +107,7 @@ describe("invite links through the action", () => {
107107 for (const s of secrets) expect(text).not.toContain(s);
108108 }
109109 const minted = events.find((e) => e.kind === "invite.minted")!;
110 expect(minted.payload).toEqual({ id: invite.id, expiresAt: invite.expiresAt });
110 expect(minted.payload).toEqual({ id: invite.id, expiresAt: invite.expiresAt, bundle: "use" });
111111 expect(events.find((e) => e.kind === "invite.revoked")!.payload).toEqual({ id: invite.id });
112112
113113 const listing = JSON.stringify(list(app, admin));
test/invites-core.test.ts +2
@@ -7,6 +7,7 @@ import { beforeEach, describe, expect, test } from "bun:test";
77 import { Database } from "bun:sqlite";
88 import invite from "../src/core/migrations/20261016200000-invite.ts";
99 import inviteOrg from "../src/core/migrations/20261114090000-invite-org.ts";
10 import inviteBundle from "../src/core/migrations/20261206100000-invite-bundle.ts";
1011 import {
1112 DEFAULT_DAYS,
1213 MAX_DAYS,
@@ -40,6 +41,7 @@ describe("an invite's life", () => {
4041 db = new Database(":memory:");
4142 db.exec(invite);
4243 db.exec(inviteOrg);
44 db.exec(inviteBundle);
4345 db.exec("CREATE TABLE user (id TEXT PRIMARY KEY, username TEXT NOT NULL)");
4446 });
4547
test/tui-invites.test.ts +20
@@ -83,6 +83,8 @@ describe("invite links in the terminal", () => {
8383 expect(h.text()).toContain("No invite link yet");
8484 await h.press("m");
8585 await h.press("enter");
86 expect(h.text()).toContain("What the invite allows");
87 await h.press("enter");
8688 expect(forge.config.url).toBeUndefined();
8789 expect(h.text()).toMatch(/Shown once: http:\/\/localhost:\d+\/signup\?invite=invite_/);
8890 const [made] = listInvites(forge.db);
@@ -133,6 +135,7 @@ describe("invite links in the terminal", () => {
133135 await open(h);
134136 await h.press("m");
135137 await h.press("enter");
138 await h.press("enter");
136139 const made = listInvites(forge.db).find((i) => i.state === "open")!;
137140 for (const k of ["n", "esc"]) {
138141 await h.press("x");
@@ -159,6 +162,23 @@ describe("invite links in the terminal", () => {
159162 h.stop();
160163 });
161164
165 test("Build is picked in the terminal; Host with no machine says why and mints nothing", async () => {
166 const before = listInvites(forge.db).length;
167 const h = boot("alice");
168 await open(h);
169 await h.press("m");
170 await h.press("enter");
171 await h.press("down", "down", "enter");
172 expect(listInvites(forge.db).length).toBe(before + 1);
173 expect(listInvites(forge.db)[0]!.bundle).toBe("build");
174 await h.press("m");
175 await h.press("enter");
176 await h.press("down", "enter");
177 expect(h.text()).toContain("Host needs a machine this forge can offer");
178 expect(listInvites(forge.db).length).toBe(before + 1);
179 h.stop();
180 });
181
162182 test("a non-admin and an admin agent have no command and mint nothing", async () => {
163183 const before = listInvites(forge.db).length;
164184 for (const who of ["bob", "carol"]) {

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

Keyboard shortcuts

Docs