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

An invite to an organization lands from the closed pull #12484's branch, with the signup welcome tested #16764

Merged opened this

Check · Review · Land · Live done — Landed and live in production.

Merged

scout/forge:scout/12561-an-invite-to-an-organization-lands-from → main 0 commits fork 3 threads · 3 unresolved

  • Merged. scout/12561-an-invite-to-an-organization-lands-from was merged into main as 518ce94.

Review

Sign in to review this change.
21 files changed +691 −34
docs/features/invite-org.md added +9
@@ -0,0 +1,9 @@
1 ---
2 topic: Hosting forges for others, and getting paid
3 row: Invite someone to an organization
4 ---
5 # An invite to an organization
6
7 Mint an invite with an organization: `POST /api/v1/admin/invites {"org":"acme"}` the MCP `mint_invite` with `org`, the organization field of Invite links on /admin/limits, or `o` on the terminal's Invite links screen.
8 Whoever signs up with the link joins the organization's read team (the first one that is not Owners; a team called `Members`, read, is made when it has none, and a team that writes or administers is never joined) and gets a private fork of each of the organization's apps in their own forge, following it by the default mode (proposes). The signup says so: the API answer and the passkey signup carry `welcome: { org, team, forks, skipped }`, the page flashes it and the terminal toasts it. An account that waits for an admin (`request`) is welcomed when it is allowed, not before.
9 A fork that cannot be made (a repository limit, a repository they cannot read) is skipped, named in `skipped`, and the signup still succeeds. A plain invite is unchanged.
src/actions/invite_welcome.ts added +130
@@ -0,0 +1,130 @@
1 /**
2 * What an invite to an organization gives the person who redeems it (#12479, VISION P4): a seat on
3 * the organization's read team and, for each of its apps, a fork in their own forge that follows
4 * it by `FORK_DEFAULT_MODE` (proposes), private to them. The admin's invite vouches for the person,
5 * so the forks skip the email proof a stranger's fork needs; the limits on repositories still hold.
6 * A fork that cannot be made is said, never silent, and never fails the signup.
7 */
8
9 import type { App } from "../app.ts";
10 import { getAppByRepo } from "../core/apps.ts";
11 import { FORK_DEFAULT_MODE, setForkFollowMode } from "../core/fork_follow.ts";
12 import { inviteOrgOf } from "../core/invites.ts";
13 import { addTeamMember, createTeam, listTeams, OWNERS_TEAM } from "../core/orgs.ts";
14 import { canRead, forkRepo as cloneRepo, getRepoById, type Repo } from "../core/repos.ts";
15 import type { User } from "../core/users.ts";
16 import { repositoryLimitRefusal } from "./repos.ts";
17
18 export const MEMBERS_TEAM = "Members";
19 /** Tried in turn when the org already has a team of the first name that is not a read team. */
20 const TEAM_NAMES = [MEMBERS_TEAM, "Invited members"];
21
22 export interface Welcome {
23 readonly org: string;
24 readonly team: string;
25 /** `owner/name` of each fork made, with the one it follows. */
26 readonly forks: readonly { readonly repo: string; readonly from: string; readonly mode: string }[];
27 /** `owner/name` of each org app that could not be forked, and why. */
28 readonly skipped: readonly { readonly from: string; readonly why: string }[];
29 }
30
31 /**
32 * The org's team a newcomer joins: only ever a read team, so an invite never hands out more
33 * than reading. The first read team that is not Owners; when there is none, one is made
34 * (`Members`). An org whose only teams write or admin gets a new read team beside them.
35 */
36 function teamFor(app: App, orgId: string) {
37 const read = listTeams(app.db, orgId).find((t) => t.name !== OWNERS_TEAM && t.permission === "read");
38 if (read !== undefined) return read;
39 for (const name of TEAM_NAMES) {
40 const made = createTeam(app.db, orgId, name, "read");
41 if (made.ok) return made.value;
42 }
43 return undefined;
44 }
45
46 /** The org's apps' repositories, oldest first. */
47 function orgApps(app: App, orgId: string): Repo[] {
48 return app.db
49 .query<{ id: string }, [string]>(
50 "SELECT repo.id FROM repo JOIN app ON app.repo_id = repo.id WHERE repo.owner_id = ?1 AND repo.sealed_for IS NULL ORDER BY repo.id",
51 )
52 .all(orgId)
53 .map((r) => getRepoById(app.db, r.id))
54 .filter((r): r is Repo => r !== undefined && getAppByRepo(app.db, r.id) !== undefined);
55 }
56
57 /**
58 * Put the person the invite let in into its organization and fork the org's apps for them;
59 * undefined for a plain invite.
60 */
61 export async function welcomeInvited(app: App, user: User): Promise<Welcome | undefined> {
62 const org = inviteOrgOf(app.db, user.id);
63 if (org === undefined) return undefined;
64 const team = teamFor(app, org.id);
65 if (team === undefined) return undefined;
66 addTeamMember(app.db, team, user.id);
67 const forks: { repo: string; from: string; mode: string }[] = [];
68 const skipped: { from: string; why: string }[] = [];
69 for (const parent of orgApps(app, org.id)) {
70 const from = `${parent.ownerName}/${parent.name}`;
71 if (!canRead(app.db, parent, user)) {
72 skipped.push({ from, why: "you cannot read it" });
73 continue;
74 }
75 const limit = repositoryLimitRefusal(app, user);
76 if (limit !== undefined) {
77 skipped.push({ from, why: limit });
78 continue;
79 }
80 const made = await cloneRepo(app.db, app.reposRoot, parent, user.id, undefined, { visibility: "private" });
81 if (!made.ok) {
82 skipped.push({ from, why: made.error });
83 continue;
84 }
85 setForkFollowMode(app.db, made.value.id, FORK_DEFAULT_MODE);
86 app.bus.append({
87 kind: "repo.forked",
88 repoId: made.value.id,
89 actorId: user.id,
90 payload: { parent: from, via: "invite" },
91 });
92 forks.push({ repo: `${made.value.ownerName}/${made.value.name}`, from, mode: FORK_DEFAULT_MODE });
93 }
94 return { org: org.name, team: team.name, forks, skipped };
95 }
96
97 /**
98 * What `welcomeInvited` did for this account, read back from the rows: for the answer a signup
99 * gives. An org app with no fork of theirs is `skipped`, whatever the reason.
100 */
101 export function inviteWelcome(app: App, user: User): Welcome | undefined {
102 const org = inviteOrgOf(app.db, user.id);
103 if (org === undefined) return undefined;
104 const team = listTeams(app.db, org.id).find(
105 (t) => app.db.query("SELECT 1 FROM team_member WHERE team_id = ?1 AND user_id = ?2").get(t.id, user.id) !== null,
106 );
107 const forks = app.db
108 .query<{ own: string; name: string; parent_id: string; parent_owner: string; parent_name: string }, [string, string]>(
109 `SELECT f.name AS name, u.username AS own, p.id AS parent_id, p.name AS parent_name, pu.username AS parent_owner
110 FROM repo f JOIN user u ON u.id = f.owner_id JOIN repo p ON p.id = f.fork_parent_id JOIN user pu ON pu.id = p.owner_id
111 WHERE f.owner_id = ?1 AND p.owner_id = ?2 ORDER BY f.id`,
112 )
113 .all(user.id, org.id);
114 const forked = new Set(forks.map((r) => r.parent_id));
115 return {
116 org: org.name,
117 team: team?.name ?? "",
118 forks: forks.map((r) => ({ repo: `${r.own}/${r.name}`, from: `${r.parent_owner}/${r.parent_name}`, mode: FORK_DEFAULT_MODE as string })),
119 skipped: orgApps(app, org.id)
120 .filter((r) => !forked.has(r.id))
121 .map((r) => ({ from: `${r.ownerName}/${r.name}`, why: "could not be forked" })),
122 };
123 }
124
125 /** One sentence for the person: where they landed, what they were given, what was left out. */
126 export function welcomeWords(w: Welcome): string {
127 const forks = w.forks.length === 0 ? "no apps to fork yet" : `${w.forks.length} private fork${w.forks.length === 1 ? "" : "s"} that follow${w.forks.length === 1 ? "s" : ""} ${w.org}`;
128 const left = w.skipped.length === 0 ? "" : ` ${w.skipped.length} could not be forked: ${w.skipped.map((k) => k.from).join(", ")}.`;
129 return `Welcome to ${w.org}: you are in ${w.team}, with ${forks}.${left}`;
130 }
src/actions/invites.ts +13 −4
@@ -26,10 +26,11 @@ import {
2626 import { canRead, canWrite, getRepoById, type Repo } from "../core/repos.ts";
2727 import { getUserByName } from "../core/users.ts";
2828 import { requireRepoAdmin, type AccessError } from "./access.ts";
29 import { getOrg } from "../core/orgs.ts";
2930 import { err, ok, type Result } from "../kernel/result.ts";
3031 import type { User } from "../core/users.ts";
3132
32 type Error = "not_found" | "invalid_days";
33 type Error = "not_found" | "invalid_days" | "unknown_org";
3334
3435 const admin = (actor: User | undefined): actor is User =>
3536 actor !== undefined && actor.isAdmin && actor.kind === "user";
@@ -38,15 +39,23 @@ const admin = (actor: User | undefined): actor is User =>
3839 export const inviteLink = (origin: string, token: string): string =>
3940 `${origin.replace(/\/$/, "")}/signup?invite=${token}`;
4041
41 export function mint(app: App, actor: User | undefined, days: unknown): Result<{ invite: Invite; token: string }, Error> {
42 /**
43 * `org` names the organization the invite brings its person into; absent or empty is a plain
44 * invite.
45 */
46 export function mint(app: App, actor: User | undefined, days: unknown, org?: unknown): Result<{ invite: Invite; token: string }, Error> {
4247 if (!admin(actor)) return err("not_found");
4348 const n = parseDays(days);
4449 if (!n.ok) return n;
45 const made = mintInvite(app.db, actor.id, n.value);
50 const name = typeof org === "string" ? org.trim() : "";
51 if (org !== undefined && org !== null && typeof org !== "string") return err("unknown_org");
52 const target = name === "" ? undefined : getOrg(app.db, name);
53 if (name !== "" && target === undefined) return err("unknown_org");
54 const made = mintInvite(app.db, actor.id, n.value, Date.now(), target?.id ?? null);
4655 app.bus.append({
4756 kind: "invite.minted",
4857 actorId: actor.id,
49 payload: { id: made.invite.id, expiresAt: made.invite.expiresAt },
58 payload: { id: made.invite.id, expiresAt: made.invite.expiresAt, ...(target === undefined ? {} : { org: target.username }) },
5059 });
5160 return ok(made);
5261 }
src/actions/requests.ts +9 −1
@@ -4,6 +4,7 @@
44 * these: the page's buttons, the API and MCP.
55 */
66
7 import { welcomeInvited } from "./invite_welcome.ts";
78 import type { Database } from "bun:sqlite";
89 import type { App } from "../app.ts";
910 import { answerRequest, waitingRequests, type AccountRequest } from "../core/requests.ts";
@@ -37,7 +38,14 @@ function answer(
3738 // an admin gives credits.
3839 if (state === "allowed") {
3940 const person = getUserByName(app.db, username);
40 if (person !== undefined) setMember(app.db, person.id, true, who.value.id, new Date());
41 if (person !== undefined) {
42 setMember(app.db, person.id, true, who.value.id, new Date());
43 // An invite to an organization waited with the account: its seat and forks are made now.
44 // A failure leaves them without a seat or forks: the error log names who.
outdated

Failure is swallowed silently. Log it or record an event so an allowed person who got no seat or forks can be found.

45 void welcomeInvited(app, person).catch((e: unknown) =>
46 app.log.error("invite welcome failed", { user: person.username, error: String(e) }),
47 );
48 }
4149 }
4250 app.bus.append({
4351 kind: state === "allowed" ? "account.allowed" : "account.declined",
src/actions/users.ts +7
@@ -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 { welcomeInvited } from "./invite_welcome.ts";
3031 import { cleanAsk, NOTE_MAX, SOURCE_MAX } from "../core/requests.ts";
3132 import {
3233 changePassword as rehash,
@@ -188,6 +189,9 @@ export async function signUp(
188189 },
189190 });
190191 auditInvite(app, created.value.id);
192 // Until the account is let in nothing it does may create or cost:
193 // `allowRequest` welcomes it then.
194 if (created.value.waitingAt === null) await welcomeInvited(app, created.value);
191195 // The address is proven by the link it is sent; until then nothing it
192196 // does may create or cost. A waiting account is mailed nothing yet.
193197 if (email !== "" && created.value.waitingAt === null) await welcome(app, created.value);
@@ -251,6 +255,9 @@ export async function signUpWithPasskey(
251255 },
252256 });
253257 auditInvite(app, created.value.id);
258 // Until the account is let in nothing it does may create or cost:
259 // `allowRequest` welcomes it then.
260 if (created.value.waitingAt === null) await welcomeInvited(app, created.value);
254261 // As on the password path: no address given, no link to send.
255262 if (email !== "" && created.value.waitingAt === null) await welcome(app, created.value);
256263 return created;
src/core/invites.ts +21 −3
@@ -28,6 +28,8 @@ export interface Invite {
2828 readonly usedAt: string | null;
2929 /** The username it let in; null when unused or the account is gone. */
3030 readonly usedBy: string | null;
31 /** The organization the invite brings its person into, or null for a plain invite. */
32 readonly org: string | null;
3133 }
3234
3335 interface Row {
@@ -41,10 +43,13 @@ interface Row {
4143 /** The repository a link to work on it names; null for an invite to the forge. */
4244 repo_id: string | null;
4345 used_by: string | null;
46 org_id: string | null;
47 org_name: string | null;
4448 }
4549
4650 /** An invite with its redeemer's username, resolved in the one query. */
47 const SELECT = "SELECT invite.*, user.username AS used_by_name FROM invite LEFT JOIN user ON user.id = invite.used_by";
51 const SELECT =
52 "SELECT invite.*, user.username AS used_by_name, o.username AS org_name FROM invite LEFT JOIN user ON user.id = invite.used_by LEFT JOIN user o ON o.id = invite.org_id";
4853
4954 const stateOf = (r: Row, now: number): InviteState =>
5055 r.revoked_at !== null ? "revoked" : r.used_at !== null ? "used" : Date.parse(r.expires_at) <= now ? "expired" : "open";
@@ -57,6 +62,7 @@ const view = (r: Row, now: number): Invite => ({
5762 state: stateOf(r, now),
5863 usedAt: r.used_at,
5964 usedBy: r.used_at === null ? null : r.used_by_name,
65 org: r.org_name,
6066 });
6167
6268 /** A whole number of days from 1 to 30, or the default when absent. */
@@ -71,12 +77,14 @@ export function mintInvite(
7177 createdBy: string,
7278 days: number = DEFAULT_DAYS,
7379 now: number = Date.now(),
80 /** The id of the organization the invite brings its person into. */
81 orgId: string | null = null,
7482 ): { invite: Invite; token: string } {
7583 const token = `invite_${secret()}`;
7684 const inviteId = id(now);
7785 db.query(
78 "INSERT INTO invite (id, token_hash, created_by, created_at, expires_at) VALUES (?1, ?2, ?3, ?4, ?5)",
79 ).run(inviteId, sha256(token), createdBy, new Date(now).toISOString(), new Date(now + days * DAY).toISOString());
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);
8088 const row = db.query<Row, [string]>(`${SELECT} WHERE invite.id = ?1`).get(inviteId)!;
8189 return { invite: view(row, now), token };
8290 }
@@ -281,3 +289,13 @@ export function contributedSince(
281289 )
282290 .all(userId, since);
283291 }
292
293 /** The organization (id and name) the invite an account spent brought it into, if it named one. */
294 export function inviteOrgOf(db: Database, userId: string): { id: string; name: string } | undefined {
295 const row = db
296 .query<{ id: string; name: string }, [string]>(
297 "SELECT o.id AS id, o.username AS name FROM invite JOIN user o ON o.id = invite.org_id WHERE invite.used_by = ?1",
298 )
299 .get(userId);
300 return row ?? undefined;
301 }
src/core/migration-pins/20261114090000-invite-org.pin added +1
@@ -0,0 +1,1 @@
1 254ad886c075aeed4a7fcc6b7adfc7b734f34257df8b1467bb2dac014ec2c307
src/core/migrations/20261114090000-invite-org.ts added +5
@@ -0,0 +1,5 @@
1 // An invite may name an organization (#12479): whoever redeems it joins that organization and is
2 // given a forge that follows its apps. NULL is the plain invite it always was. Additive.
3 export default `
4 ALTER TABLE invite ADD COLUMN org_id TEXT;
5 `;
src/http/api.ts +3 −1
@@ -17,6 +17,7 @@ import { listAppReleases } from "../core/app_releases.ts";
1717 import { openapiHandler } from "../contract/served.ts";
1818 import { CHECK_ASKED } from "../actions/pull_ask_words.ts";
1919 import { liveOf } from "../perf/live.ts";
20 import { inviteWelcome } from "../actions/invite_welcome.ts";
2021 import { growth, MAX_DAYS as MAX_GROWTH_DAYS } from "../core/growth.ts";
2122 import { CEILING_REFUSAL, PAUSE_REFUSAL, pausedUntil } from "../core/planner_pause.ts";
2223 import { homeTruth } from "../system/home_truth.ts";
@@ -1216,7 +1217,8 @@ export function apiRoutes(router: Router<Handler>, isPage: (path: string) => boo
12161217 if (!created.ok) return json({ error: created.error }, 422);
12171218 // Signup is `request`: the account waits for an admin, and acts as nothing yet.
12181219 if (created.value.waitingAt !== null) return json({ state: "waiting", username: created.value.username, message: REQUEST_IN_MESSAGE }, 202);
1219 return json(publicUser(created.value), 201);
1220 const welcome = inviteWelcome(ctx.app, created.value);
1221 return json(welcome === undefined ? publicUser(created.value) : { ...publicUser(created.value), welcome }, 201);
12201222 });
12211223
12221224 router.add("GET", "/api/v1/users/:username", (ctx) => {
src/http/api/admin.ts +4 −2
@@ -537,11 +537,13 @@ export function adminRoutes(router: Router<Handler>): void {
537537 const denied = accountAdmin(ctx, "admin");
538538 if (denied) return denied;
539539 const input = await body(ctx.request);
540 const made = mintInviteLink(ctx.app, ctx.auth.user, input.days);
540 const made = mintInviteLink(ctx.app, ctx.auth.user, input.days, input.org);
541541 if (!made.ok)
542542 return made.error === "invalid_days"
543543 ? apiError("invalid", 422, SPEND_WORDS.inviteDays)
544 : notFound();
544 : made.error === "unknown_org"
545 ? apiError("invalid", 422, "no such organization")
546 : notFound();
545547 const origin = ctx.app.config.url ?? ctx.url.origin;
546548 return json(
547549 { ...made.value.invite, token: made.value.token, link: inviteLink(origin, made.value.token) },
src/http/mcp/tools/mint_invite.ts +4 −3
@@ -6,13 +6,14 @@ import { good, bad, type Tool, mayBoards } from "../shared.ts";
66 export const tool: Tool = {
77 name: "mint_invite",
88 listedTo: "admin",
9 doc: "`{ days? }`: mint a single-use invite link that expires in `days` (1–30, default 7) and is shown once; a person admin's, with an admin token",
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",
1010 description:
1111 "Mint a one-use invite link, shown once, valid `days` (1–30, default 7). Person admins.",
1212 inputSchema: {
1313 type: "object",
1414 properties: {
1515 days: { type: "integer", minimum: 1, maximum: 30 },
16 org: { type: "string", description: "Organization the person joins" },
1617 },
1718 },
1819 writes: true,
@@ -20,8 +21,8 @@ export const tool: Tool = {
2021 if (!mayBoards(user)) return bad("forbidden", "an invite is a forge admin's to mint");
2122 if (!scopeAllows(ctx.auth.scope ?? "ro", "admin"))
2223 return bad("forbidden", "an invite needs an admin token");
23 const made = mintInviteLink(ctx.app, user, args["days"]);
24 if (!made.ok) return bad("invalid", SPEND_WORDS.inviteDays);
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);
2526 const origin = ctx.app.config.url ?? ctx.url.origin;
2627 return good({ ...made.value.invite, link: inviteLink(origin, made.value.token) });
2728 },
src/tui/screens/invites.ts +20 −4
@@ -2,7 +2,8 @@
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
44 * shows them. `m` mints one from a number of days (1 to 30, 7 by default) and
5 * prints the link once, on this screen, until the next key of any kind; `x` revokes the
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
67 * selected open one after a confirm (`y` revokes, `n` or esc keeps it). Both go through the actions, so the gate is theirs: an
78 * admin who is a person; anyone else sees nothing and mints nothing. The top
89 * line says who may sign up now, as MCP `signup` does; `s` picks open, invite
@@ -38,14 +39,16 @@ export function invitesScreen(f: Session, ctx: Ctx): Screen {
3839 return r.ok ? r.value : [];
3940 };
4041
41 const make = (raw: string): string | undefined => {
42 const make = (raw: string, org = ""): string | undefined => {
4243 const text = raw.trim();
4344 const days = text === "" ? DEFAULT_DAYS : /^\d{1,3}$/.test(text) ? Number(text) : -1;
44 const made = mint(f.app, f.user, days);
45 const made = mint(f.app, f.user, days, org);
4546 if (!made.ok)
4647 return made.error === "invalid_days"
4748 ? `Days is a whole number from 1 to ${MAX_DAYS}.`
48 : "You cannot make invite links.";
49 : made.error === "unknown_org"
50 ? "No organization by that name."
51 : "You cannot make invite links.";
4952 const origin = f.app.config.url ?? `http://localhost:${f.app.config.port}`;
5053 note = `Shown once: ${inviteLink(origin, made.value.token)}`;
5154 ctx.invalidate();
@@ -108,6 +111,7 @@ export function invitesScreen(f: Session, ctx: Ctx): Screen {
108111 return [
109112 binding(["j", "k"], "move cursor"),
110113 binding(["m"], "make a link"),
114 binding(["o"], "make a link to an organization"),
111115 binding(["x"], "revoke"),
112116 ...(signup().ok ? [binding(["s"], "who may sign up"), binding(["a"], "agents can start here")] : []),
113117 ];
@@ -144,6 +148,18 @@ export function invitesScreen(f: Session, ctx: Ctx): Screen {
144148 onSubmit: make,
145149 }),
146150 );
151 } else if (e.key === "o") {

The o key (and its unknown-org message) has no test. Add a TUI test that fails without this branch.

152 ctx.push(
153 promptScreen(ctx, screen, {
154 title: "Invite link to an organization",
155 label: "organization name; its person joins it and gets forks of its apps",
156 value: "",
157 onSubmit: (org) =>
158 org.trim() === ""
159 ? "Name an organization."
160 : make(String(DEFAULT_DAYS), org),
161 }),
162 );
147163 } else if (e.key === "x") {
148164 const row = all[state.index];
149165 if (row === undefined) return false;
src/tui/screens/signin.ts +3
@@ -8,6 +8,7 @@
88 * account while signup allows — not an admin; the operator makes the admin.
99 */
1010
11 import { inviteWelcome, welcomeWords } from "../../actions/invite_welcome.ts";
1112 import { activeEdgeToken } from "../../http/edge.ts";
1213 import { inviteByToken } from "../../core/invites.ts";
1314 import { whenWords } from "../../core/when_words.ts";
@@ -158,6 +159,8 @@ export function signInScreen(f: Session, ctx: Ctx, onDone: () => void): Screen {
158159 }
159160 }
160161 ctx.toast(`signed in as ${f.user?.username ?? ""}`, "success");
162 const welcome = mode === "create" && f.user !== undefined ? inviteWelcome(f.app, f.user) : undefined;

The welcome toast on terminal signup has no test. Add one that fails when these lines are removed.

163 if (welcome !== undefined) ctx.toast(welcomeWords(welcome), "success");
161164 onDone();
162165 ctx.pop();
163166 } finally {
src/web/pages/admin-limits.ts +6 −2
@@ -206,9 +206,11 @@ export function limitsPage(ctx: Ctx): Response {
206206 step="1"
207207 value="${String(DEFAULT_DAYS)}"
208208 /></label>
209 <label class="small">organization (optional)
210 <input class="input mono" type="text" name="org" maxlength="60" autocomplete="off" /></label>
209211 ${btn("Make a link", { size: "sm", variant: "primary", label: "Make an invite link" })}
210212 </form>
211 <span class="muted small">Shown once, when it is made; good for one signup.</span>
213 <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>
212214 </dd>
213215 <dd class="status-act"></dd>
214216 </div>`;
@@ -369,8 +371,10 @@ export async function inviteMint(ctx: Ctx): Promise<Response> {
369371 const form = await readForm(ctx, "admin");
370372 if (form instanceof Response) return form;
371373 const raw = field(form, "days").trim();
372 const made = mintInviteLink(ctx.app, ctx.auth.user, /^\d{1,3}$/.test(raw) ? Number(raw) : -1);
374 const made = mintInviteLink(ctx.app, ctx.auth.user, /^\d{1,3}$/.test(raw) ? Number(raw) : -1, field(form, "org"));
373375 if (!made.ok && made.error === "not_found") return notFoundPage(ctx);
376 if (!made.ok && made.error === "unknown_org")
377 return flashTo(ctx, "/admin/limits", { tone: "danger", message: "No organization by that name." });
374378 if (!made.ok)
375379 return flashTo(ctx, "/admin/limits", {
376380 tone: "danger",
src/web/pages/signup-passkey.ts +3 −1
@@ -6,6 +6,7 @@
66 * per address; a challenge answers once.
77 */
88
9 import { inviteWelcome } from "../../actions/invite_welcome.ts";
910 import { newChallenge, verifyRegistration } from "../../auth/webauthn.ts";
1011 import { givenEmail, invalidEmailMessage, signUpWithPasskey, signupClosed, HUMAN_CHECK_MESSAGE, SIGNUP_CLOSED_MESSAGE } from "../../actions/users.ts";
1112 import { rotateSession } from "../../auth/session_rotate.ts";
@@ -109,8 +110,9 @@ export async function signupPasskey(ctx: Ctx): Promise<Response> {
109110 // A request that waits starts no session: it lands on the page that says so.
110111 if (created.value.waitingAt !== null) return json({ ok: true, waiting: true, next: "/signup/requested" }, 202);
111112 const session = rotateSession(ctx.app.db, cookieValue(ctx.request, "forge_session"), created.value.id);
113 const welcome = inviteWelcome(ctx.app, created.value);
112114 return json(
113 { ok: true, next: safeNext(ctx.url.searchParams.get("next")) ?? "/" },
115 { ok: true, next: safeNext(ctx.url.searchParams.get("next")) ?? "/", ...(welcome === undefined ? {} : { welcome }) },
114116 201,
115117 { "set-cookie": sessionCookie(session.token, session.expiresAt, ctx.url, ctx.app.config.url) },
116118 );
src/web/pages/site.ts +6 −4
@@ -11,6 +11,7 @@
1111 import { contributorMay } from "../../text/contributor.ts";
1212 import { closeState, closingSays } from "../../actions/account_close.ts";
1313 import { USERNAME_PATTERN } from "../username_pattern.ts";
14 import { inviteWelcome, welcomeWords } from "../../actions/invite_welcome.ts";
1415 import { expireCookie, setCookie } from "../../auth/cookies.ts";
1516 import { safeNext, withReturn } from "../return_to.ts";
1617 import { armPendingReturn, pendingReturn } from "../../core/pending_return.ts";
@@ -861,13 +862,14 @@ export async function signupSubmit(ctx: Ctx): Promise<Response> {
861862 // A request that waits has no session to start: it lands on the page that says so.
862863 if (created.value.waitingAt !== null) return redirect("/signup/requested");
863864 const session = rotateSession(ctx.app.db, cookieValue(ctx.request, "forge_session"), created.value.id);
865 const welcome = inviteWelcome(ctx.app, created.value);
864866 const next = safeNext(ctx.url.searchParams.get("next"));
865867 // Signed up from Make it yours: arm that one copy for the new account (`core/pending_return.ts`).
866868 armPendingReturn(ctx.app.db, created.value.id, next);
867 return redirect(
868 next ?? "/",
869 sessionCookie(session.token, session.expiresAt, ctx.url, ctx.app.config.url),
870 );
869 return redirect(next ?? "/", {
870 cookie: sessionCookie(session.token, session.expiresAt, ctx.url, ctx.app.config.url),
871 ...(welcome === undefined ? {} : { flash: { message: welcomeWords(welcome) }, url: ctx.url, forgeUrl: ctx.app.config.url }),
872 });
871873 }
872874
873875 // POST /theme — persist the theme choice in a cookie. Works as a plain form
test/invite-org.test.ts added +395
@@ -0,0 +1,395 @@
1 /**
2 * An invite naming an organization (#12479): its person joins the organization and is given a
3 * private fork of each of its apps that follows it by the default mode (proposes); a plain
4 * invite makes a plain account; an unknown organization mints nothing.
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 { pollUntil } from "./helpers/poll.ts";
11 import { createApp, type App } from "../src/app.ts";
12 import { list as listInvites, mint } from "../src/actions/invites.ts";
13 import { welcomeWords, type Welcome } from "../src/actions/invite_welcome.ts";
14 import { allowRequest } from "../src/actions/requests.ts";
15 import { createToken } from "../src/core/tokens.ts";
16 import { createSession } from "../src/core/sessions.ts";
17 import { setQuota } from "../src/settings/quotas.ts";
18 import { createApp as insertApp } from "../src/core/apps.ts";
19 import { FORK_DEFAULT_MODE, forkFollowMode } from "../src/core/fork_follow.ts";
20 import { createOrg, createTeam, isOrgMember, getOrg, orgAccess } from "../src/core/orgs.ts";
21 import { createRepo, forkRepo, getRepo } from "../src/core/repos.ts";
22 import { createUser, getUserByName, type User } from "../src/core/users.ts";
23 import { serve, type Servers } from "../src/http/server.ts";
24 import { setLimit } from "../src/settings/limits.ts";
25 import { setSignup } from "../src/settings/signup.ts";
26 import { seedAdmin } from "./helpers/admin.ts";
27 import { device } from "./helpers/passkey.ts";
28 import { quietLogs } from "./helpers/globals.ts";
29
30 quietLogs();
31 const PASSWORD = "an-invited-passphrase";
32
33 describe("an invite to an organization", () => {
34 let dir = "";
35 let app: App;
36 let servers: Servers;
37 let admin: User;
38
39 const signup = async (username: string, invite: string) =>
40 fetch(`${servers.url}/api/v1/users`, {
41 method: "POST",
42 headers: { "content-type": "application/json" },
43 body: JSON.stringify({ username, email: `${username}@f.dev`, password: PASSWORD, invite }),
44 });
45 const tokenOf = (org?: string) => {
46 const made = mint(app, admin, undefined, org);
47 if (!made.ok) throw new Error(made.error);
48 return made.value;
49 };
50
51 beforeAll(async () => {
52 dir = await mkdtemp(join(tmpdir(), "forge-invite-org-"));
53 app = createApp({ dataDir: dir, port: 0 });
54 servers = await serve(app);
55 const made = await seedAdmin(app, { username: "olive", email: "[email protected]", password: PASSWORD });
56 if (!made.ok) throw new Error(made.error);
57 admin = made.value;
58 setSignup(app.db, "invite", admin.id);
59 setLimit(app.db, "signup.per_source", 1000, admin.id);
60 const org = createOrg(app.db, "acme", admin.id);
61 if (!org.ok) throw new Error(org.error);
62 for (const name of ["site", "api"]) {
63 const repo = await createRepo(app.db, app.reposRoot, { ownerId: org.value.id, name, visibility: "public" });
64 if (!repo.ok) throw new Error(repo.error);
65 insertApp(app.db, { repoId: repo.value.id, slug: `acme-${name}`, access: "public" });
66 }
67 // A repository that is not an app is not forked.
68 await createRepo(app.db, app.reposRoot, { ownerId: org.value.id, name: "notes", visibility: "public" });
69 });
70 afterAll(async () => {
71 servers.stop();
72 app.close();
73 await rm(dir, { recursive: true, force: true });
74 });
75
76 test("the person joins the organization and gets private forks that follow its apps", async () => {
77 const { invite, token } = tokenOf("acme");
78 expect(invite.org).toBe("acme");
79 const res = await signup("nova", token);
80 expect(res.status).toBe(201);
81 const body = (await res.json()) as { welcome: { org: string; team: string; forks: { repo: string; from: string; mode: string }[] } };
82 expect(body.welcome.org).toBe("acme");
83 expect(body.welcome.team).toBe("Members");
84 expect(body.welcome.forks.map((f) => f.repo)).toEqual(["nova/site", "nova/api"]);
85 const nova = getUserByName(app.db, "nova")!;
86 const org = getOrg(app.db, "acme")!;
87 expect(isOrgMember(app.db, org.id, nova.id)).toBe(true);
88 for (const name of ["site", "api"]) {
89 const fork = getRepo(app.db, "nova", name)!;
90 expect(fork.visibility).toBe("private");
91 expect(fork.forkParentId).toBe(getRepo(app.db, "acme", name)!.id);
92 expect(forkFollowMode(app.db, fork.id)).toBe(FORK_DEFAULT_MODE);
93 }
94 expect(getRepo(app.db, "nova", "notes")).toBeUndefined();
95 });
96
97 test("the sign-up page's redirect flash carries the welcome: org, team and forks", async () => {
98 const { token } = tokenOf("acme");
99 const res = await fetch(`${servers.url}/signup?invite=${token}`, {
100 method: "POST",
101 redirect: "manual",
102 headers: { "content-type": "application/x-www-form-urlencoded", origin: servers.url },
103 body: new URLSearchParams({ username: "wren", email: "[email protected]", password: PASSWORD }),
104 });
105 expect(res.status).toBe(303);
106 const cookies = res.headers.getSetCookie();
107 const flash = cookies.find((c) => c.startsWith("forge_flash="));
108 expect(flash).toBeDefined();
109 const said = JSON.parse(decodeURIComponent(flash!.split(";")[0]!.slice("forge_flash=".length))) as { message: string };
110 expect(said.message).toContain("Welcome to acme");
111 expect(said.message).toContain("you are in Members");
112 expect(said.message).toContain("2 private forks that follow acme");
113 expect(getRepo(app.db, "wren", "site")).toBeDefined();
114 });
115
116 test("a plain invite's sign-up page redirect carries no welcome", async () => {
117 const res = await fetch(`${servers.url}/signup?invite=${tokenOf().token}`, {
118 method: "POST",
119 redirect: "manual",
120 headers: { "content-type": "application/x-www-form-urlencoded", origin: servers.url },
121 body: new URLSearchParams({ username: "plainweb", email: "[email protected]", password: PASSWORD }),
122 });
123 expect(res.status).toBe(303);
124 expect(res.headers.getSetCookie().some((c) => c.startsWith("forge_flash="))).toBe(false);
125 });
126
127 test("a plain invite makes a plain account", async () => {
128 const res = await signup("plain", tokenOf().token);
129 expect(res.status).toBe(201);
130 expect("welcome" in ((await res.json()) as object)).toBe(false);
131 expect(getRepo(app.db, "plain", "site")).toBeUndefined();
132 });
133
134 test("an organization that does not exist mints nothing", () => {
135 const made = mint(app, admin, undefined, "nowhere");
136 expect(made.ok).toBe(false);
137 if (!made.ok) expect(made.error).toBe("unknown_org");
138 });
139 });
140
141 describe("an invite to an organization, edges", () => {
142 let dir = "";
143 let app: App;
144 let servers: Servers;
145 let admin: User;
146 let adminToken = "";
147
148 const signup = async (username: string, invite: string) =>
149 fetch(`${servers.url}/api/v1/users`, {
150 method: "POST",
151 headers: { "content-type": "application/json" },
152 body: JSON.stringify({ username, email: `${username}@f.dev`, password: PASSWORD, invite }),
153 });
154 const tokenOf = (org: string) => {
155 const made = mint(app, admin, undefined, org);
156 if (!made.ok) throw new Error(made.error);
157 return made.value.token;
158 };
159 const orgWith = async (name: string, apps: { name: string; visibility: "public" | "private" }[]) => {
160 const org = createOrg(app.db, name, admin.id);
161 if (!org.ok) throw new Error(org.error);
162 for (const a of apps) {
163 const repo = await createRepo(app.db, app.reposRoot, { ownerId: org.value.id, name: a.name, visibility: a.visibility });
164 if (!repo.ok) throw new Error(repo.error);
165 insertApp(app.db, { repoId: repo.value.id, slug: `${name}-${a.name}`, access: "public" });
166 }
167 return org.value;
168 };
169 const teamsOf = (userId: string) =>
170 app.db
171 .query<{ name: string; permission: string }, [string]>(
172 "SELECT t.name, t.permission FROM team t JOIN team_member m ON m.team_id = t.id WHERE m.user_id = ?1",
173 )
174 .all(userId);
175
176 beforeAll(async () => {
177 dir = await mkdtemp(join(tmpdir(), "forge-invite-org-edges-"));
178 app = createApp({ dataDir: dir, port: 0 });
179 servers = await serve(app);
180 const made = await seedAdmin(app, { username: "olive", email: "[email protected]", password: PASSWORD });
181 if (!made.ok) throw new Error(made.error);
182 admin = made.value;
183 adminToken = createToken(app.db, admin.id, "t", "admin").token;
184 setSignup(app.db, "invite", admin.id);
185 setLimit(app.db, "signup.per_source", 1000, admin.id);
186 });
187 afterAll(async () => {
188 servers.stop();
189 app.close();
190 await rm(dir, { recursive: true, force: true });
191 });
192
193 test("an org with only an admin team gives the newcomer a read team, never the admin one", async () => {
194 const org = await orgWith("adminonly", [{ name: "site", visibility: "public" }]);
195 const team = createTeam(app.db, org.id, "Maintainers", "admin");
196 if (!team.ok) throw new Error(team.error);
197 const res = await signup("rhea", tokenOf("adminonly"));
198 expect(res.status).toBe(201);
199 const rhea = getUserByName(app.db, "rhea")!;
200 expect(teamsOf(rhea.id)).toEqual([{ name: "Members", permission: "read" }]);
201 expect(orgAccess(app.db, org.id, rhea)).toBe("read");
202 });
203
204 test("an org with a write team and a read team joins the read one", async () => {
205 const org = await orgWith("mixed", [{ name: "site", visibility: "public" }]);
206 for (const [n, p] of [["Devs", "write"], ["Readers", "read"]] as const) createTeam(app.db, org.id, n, p);
207 expect((await signup("sol", tokenOf("mixed"))).status).toBe(201);
208 expect(teamsOf(getUserByName(app.db, "sol")!.id)).toEqual([{ name: "Readers", permission: "read" }]);
209 });
210
211 test("a fork over the repository limit is skipped, named in the answer, and the signup stands", async () => {
212 await orgWith("limited", [{ name: "one", visibility: "public" }, { name: "two", visibility: "public" }]);
213 setQuota(app.db, "repositories", 1, admin.id);
214 try {
215 const res = await signup("tess", tokenOf("limited"));
216 expect(res.status).toBe(201);
217 const body = (await res.json()) as { welcome: { forks: { repo: string }[]; skipped: { from: string }[] } };
218 expect(body.welcome.forks.map((f) => f.repo)).toEqual(["tess/one"]);
219 expect(body.welcome.skipped.map((s) => s.from)).toEqual(["limited/two"]);
220 expect(getRepo(app.db, "tess", "two")).toBeUndefined();
221 } finally {
222 setQuota(app.db, "repositories", null, admin.id);
223 }
224 });
225
226 test("a private app is forked private; a sealed repository is not forked", async () => {
227 const org = await orgWith("closed", [{ name: "vault", visibility: "private" }]);
228 const parent = getRepo(app.db, "closed", "vault")!;
229 const sealed = await forkRepo(app.db, app.reposRoot, parent, org.id, "vault-sealed", { sealed: true });
230 if (!sealed.ok) throw new Error(sealed.error);
231 insertApp(app.db, { repoId: sealed.value.id, slug: "closed-sealed", access: "public" });
232 const res = await signup("uma", tokenOf("closed"));
233 const body = (await res.json()) as { welcome: { forks: { repo: string }[] } };
234 expect(body.welcome.forks.map((f) => f.repo)).toEqual(["uma/vault"]);
235 expect(getRepo(app.db, "uma", "vault")!.visibility).toBe("private");
236 expect(getRepo(app.db, "uma", "vault-sealed")).toBeUndefined();
237 });
238
239 test("an account that waits is neither seated nor forked until it is allowed", async () => {
240 const org = await orgWith("later", [{ name: "site", visibility: "public" }]);
241 // An open invite vouches for its person, so a waiting account never comes by one at sign-up;
242 // the account that waits here carries a spent org invite all the same.
243 setSignup(app.db, "request", admin.id);
244 const res = await fetch(`${servers.url}/api/v1/users`, {
245 method: "POST",
246 headers: { "content-type": "application/json" },
247 body: JSON.stringify({ username: "vera", email: "[email protected]", password: PASSWORD }),
248 });
249 setSignup(app.db, "invite", admin.id);
250 expect(res.status).toBe(202);
251 const vera = getUserByName(app.db, "vera")!;
252 const { invite } = (() => {
253 const made = mint(app, admin, undefined, "later");
254 if (!made.ok) throw new Error(made.error);
255 return made.value;
256 })();
257 app.db.query("UPDATE invite SET used_by = ?1, used_at = ?2 WHERE id = ?3").run(vera.id, new Date().toISOString(), invite.id);
258 expect(isOrgMember(app.db, org.id, vera.id)).toBe(false);
259 expect(getRepo(app.db, "vera", "site")).toBeUndefined();
260 expect(allowRequest(app, admin, "vera").ok).toBe(true);
261 await pollUntil(() => getRepo(app.db, "vera", "site") !== undefined, "the welcome after the allow");
262 expect(isOrgMember(app.db, org.id, vera.id)).toBe(true);
263 expect(getRepo(app.db, "vera", "site")).toBeDefined();
264 });
265
266 test("a welcome that fails after an allow is logged, naming the person", async () => {
267 await orgWith("broken", [{ name: "site", visibility: "public" }]);
268 setSignup(app.db, "request", admin.id);
269 await fetch(`${servers.url}/api/v1/users`, {
270 method: "POST",
271 headers: { "content-type": "application/json" },
272 body: JSON.stringify({ username: "wren", email: "[email protected]", password: PASSWORD }),
273 });
274 setSignup(app.db, "invite", admin.id);
275 const wren = getUserByName(app.db, "wren")!;
276 const made = mint(app, admin, undefined, "broken");
277 if (!made.ok) throw new Error(made.error);
278 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);
279 app.db.exec("ALTER TABLE team_member RENAME TO team_member_away");
280 try {
281 expect(allowRequest(app, admin, "wren").ok).toBe(true);
282 await pollUntil(() => app.signals.errors.recent(20).latest.some((l) => l.message.includes("invite welcome failed")), "the failure in the error log");
283 } finally {
284 app.db.exec("ALTER TABLE team_member_away RENAME TO team_member");
285 }
286 const line = app.signals.errors.recent(20).latest.find((l) => l.message.includes("invite welcome failed"))!;
287 expect(line.message).toContain("wren");
288 });
289
290 test("the API refuses an unknown or non-string organization and a non-admin", async () => {
291 const post = (token: string, body: unknown) =>
292 fetch(`${servers.url}/api/v1/admin/invites`, {
293 method: "POST",
294 headers: { "content-type": "application/json", authorization: `Bearer ${token}` },
295 body: JSON.stringify(body),
296 });
297 expect((await post(adminToken, { org: "nowhere" })).status).toBe(422);
298 expect((await post(adminToken, { org: 7 })).status).toBe(422);
299 expect((await post(adminToken, { org: { name: "acme" } })).status).toBe(422);
300 const made = await post(adminToken, {});
301 expect(made.status).toBeLessThan(300);
302 const bob = await createUser(app.db, { origin: "seed", username: "bob", email: "[email protected]", password: PASSWORD, trusted: true });
303 if (!bob.ok) throw new Error(bob.error);
304 const plain = createToken(app.db, bob.value.id, "t", "admin").token;
305 expect((await post(plain, { org: "mixed" })).status).toBeGreaterThanOrEqual(403);
306 });
307
308 test("the MCP mint_invite refuses an unknown organization", async () => {
309 const res = await fetch(`${servers.url}/mcp`, {
310 method: "POST",
311 headers: { "content-type": "application/json", accept: "application/json, text/event-stream", authorization: `Bearer ${adminToken}` },
312 body: JSON.stringify({ jsonrpc: "2.0", id: 1, method: "tools/call", params: { name: "mint_invite", arguments: { org: "nowhere" } } }),
313 });
314 const text = JSON.stringify(await res.json());
315 expect(text).toContain("no such organization");
316 });
317
318 test("the admin page makes an invite for an organization, and says so when there is none", async () => {
319 const cookie = `forge_session=${createSession(app.db, admin.id).token}`;
320 const form = (org: string) => {
321 const body = new URLSearchParams({ days: "7", org });
322 return fetch(`${servers.url}/admin/invites`, {
323 method: "POST",
324 headers: { cookie, "content-type": "application/x-www-form-urlencoded", origin: servers.url },
325 body,
326 redirect: "manual",
327 });
328 };
329 const before = listInvites(app, admin);
330 const n = before.ok ? before.value.length : 0;
331 expect((await form("nowhere")).status).toBe(303);
332 expect((await form("mixed")).status).toBe(303);
333 const after = listInvites(app, admin);
334 expect(after.ok && after.value.length).toBe(n + 1);
335 expect(after.ok && after.value.some((i) => i.org === "mixed")).toBe(true);
336 });
337 });
338
339 describe("an invite to an organization, by passkey", () => {
340 let dir = "";
341 let app: App;
342 let servers: Servers;
343 let admin: User;
344
345 beforeAll(async () => {
346 dir = await mkdtemp(join(tmpdir(), "forge-invite-org-passkey-"));
347 app = createApp({ dataDir: dir, port: 0, passkeyOnlySignup: true });
348 servers = await serve(app);
349 const made = await seedAdmin(app, { username: "olive", email: "[email protected]", password: "an-invited-passphrase" });
350 if (!made.ok) throw new Error(made.error);
351 admin = made.value;
352 setSignup(app.db, "invite", admin.id);
353 setLimit(app.db, "signup.per_source", 1000, admin.id);
354 const org = createOrg(app.db, "acme", admin.id);
355 if (!org.ok) throw new Error(org.error);
356 const repo = await createRepo(app.db, app.reposRoot, { ownerId: org.value.id, name: "site", visibility: "public" });
357 if (!repo.ok) throw new Error(repo.error);
358 insertApp(app.db, { repoId: repo.value.id, slug: "acme-site", access: "public" });
359 });
360 afterAll(async () => {
361 servers.stop();
362 app.close();
363 await rm(dir, { recursive: true, force: true });
364 });
365
366 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");
368 if (!made.ok) throw new Error(made.error);
369 const origin = new URL(servers.url).origin;
370 const d = await device(origin, new URL(servers.url).hostname);
371 const post = (path: string, body: unknown) =>
372 fetch(`${servers.url}${path}?invite=${made.value.token}`, {
373 method: "POST",
374 headers: { "content-type": "application/json" },
375 body: JSON.stringify(body),
376 });
377 const o = (await (await post("/signup/passkey/options", { username: "pia", email: "[email protected]", invite: made.value.token })).json()) as { challenge: string };
378 const res = await post("/signup/passkey", {
379 username: "pia",
380 email: "[email protected]",
381 invite: made.value.token,
382 challenge: o.challenge,
383 ...(await d.create(o.challenge)),
384 });
385 expect(res.status).toBe(201);
386 const body = (await res.json()) as { welcome: Welcome };
387 expect(body.welcome.org).toBe("acme");
388 expect(body.welcome.forks.map((f) => f.repo)).toEqual(["pia/site"]);
389 expect(body.welcome.skipped).toEqual([]);
390 expect(body.welcome.team).toBe("Members");
391 expect(welcomeWords(body.welcome)).toContain("1 private fork that follows acme");
392 expect(isOrgMember(app.db, getUserByName(app.db, "acme")!.id, getUserByName(app.db, "pia")!.id)).toBe(true);
393 expect(getRepo(app.db, "pia", "site")!.visibility).toBe("private");
394 });
395 });
test/invites-core.test.ts +2
@@ -6,6 +6,7 @@
66 import { beforeEach, describe, expect, test } from "bun:test";
77 import { Database } from "bun:sqlite";
88 import invite from "../src/core/migrations/20261016200000-invite.ts";
9 import inviteOrg from "../src/core/migrations/20261114090000-invite-org.ts";
910 import {
1011 DEFAULT_DAYS,
1112 MAX_DAYS,
@@ -38,6 +39,7 @@ describe("an invite's life", () => {
3839 beforeEach(() => {
3940 db = new Database(":memory:");
4041 db.exec(invite);
42 db.exec(inviteOrg);
4143 db.exec("CREATE TABLE user (id TEXT PRIMARY KEY, username TEXT NOT NULL)");
4244 });
4345
test/org-person-forge.test.ts +6 −7
@@ -1,12 +1,10 @@
11 /**
22 * VISION P4: "they add their people; each new person gets their own forge
3 * that follows the organization's." This pins what exists TODAY (#12475):
4 * an accepted invite makes a plain account, and nothing more. The invite
3 * that follows the organization's." This pins what a PLAIN invite does
4 * (#12475): an accepted invite makes a plain account, and nothing more. The invite
55 * names no organization, so the person is in no team, owns no repository,
66 * and nothing forks the organization's app for them, so nothing follows it.
7 * The gap is filed as its own issue; when it is built these assertions are
8 * the ones to turn into the proof that the person's app follows the
9 * organization's in the `proposes` mode (FORK_DEFAULT_MODE, `tell-me`).
7 * An invite that names an organization is proven in test/invite-org.test.ts.
108 */
119 import { afterAll, beforeAll, expect, test } from "bun:test";
1210 import { mkdtemp, rm } from "node:fs/promises";
@@ -69,8 +67,9 @@ test("an invited person gets an account, not yet a forge that follows the organi
6967 const ivy = getUserByName(app.db, "ivy");
7068 expect(ivy).toBeDefined();
7169
72 // Today: the invite carries no organization, so the person is not in it...
73 expect(Object.keys(invite.value.invite)).not.toContain("org");
70 // A plain invite (no `org`, see test/invite-org.test.ts for the one that names it)
71 // carries no organization, so the person is not in it...
72 expect(invite.value.invite.org ?? null).toBeNull();
7473 expect(isOrgMember(app.db, org.value.id, ivy!.id)).toBe(false);
7574 // ...owns no repository (no forge of their own with an app in it)...
7675 expect(listReposOwnedBy(app.db, ivy!.id)).toEqual([]);
test/tui-invites.test.ts +24
@@ -9,6 +9,7 @@ import { tmpdir } from "node:os";
99 import { join } from "node:path";
1010 import { createApp, type App as Forge } from "../src/app.ts";
1111 import { listInvites, mintInvite, redeemInvite } from "../src/core/invites.ts";
12 import { createOrg } from "../src/core/orgs.ts";
1213 import { createUser, getUserByName } from "../src/core/users.ts";
1314 import { createForgeApp } from "../src/tui/forge.ts";
1415 import { invitesScreen } from "../src/tui/screens/invites.ts";
@@ -104,6 +105,29 @@ describe("invite links in the terminal", () => {
104105 h.stop();
105106 });
106107
108 test("o makes a link to an organization; an unknown name says so and makes nothing", async () => {
109 const org = createOrg(forge.db, "acme", getUserByName(forge.db, "alice")!.id);
110 if (!org.ok) throw new Error(org.error);
111 const before = listInvites(forge.db).length;
112 const h = boot("alice");
113 await open(h);
114 await h.press("o");
115 expect(h.text()).toContain("Invite link to an organization");
116 await h.press("enter");
117 expect(h.text()).toContain("Name an organization.");
118 await h.type("nowhere");
119 await h.press("enter");
120 expect(h.text()).toContain("No organization by that name.");
121 expect(listInvites(forge.db).length).toBe(before);
122 await h.press("backspace", "backspace", "backspace", "backspace", "backspace", "backspace", "backspace");
123 await h.type("acme");
124 await h.press("enter");
125 expect(h.text()).toMatch(/Shown once: .*invite=invite_/);
126 expect(listInvites(forge.db).length).toBe(before + 1);
127 expect(listInvites(forge.db).some((i) => i.org === "acme")).toBe(true);
128 h.stop();
129 });
130
107131 test("n or esc on the revoke confirm keeps the link open", async () => {
108132 const h = boot("alice");
109133 await open(h);
test/tui-signup-invite.test.ts +20 −2
@@ -10,7 +10,9 @@ import { join } from "node:path";
1010 import { signUp } from "../src/actions/users.ts";
1111 import { createApp, type App as Forge } from "../src/app.ts";
1212 import { listInvites, mintInvite } from "../src/core/invites.ts";
13 import { createOrg } from "../src/core/orgs.ts";
1314 import { getUserByName } from "../src/core/users.ts";
15 import { setLimit } from "../src/settings/limits.ts";
1416 import { setSignup } from "../src/settings/signup.ts";
1517 import { createForgeApp } from "../src/tui/forge.ts";
1618 import type { TuiIdentity } from "../src/tui/session.ts";
@@ -24,6 +26,9 @@ quietLogs();
2426 const KEY =
2527 "ssh-ed25519 AAAAC3NzaC1lZDI1NTE5AAAAIB2S7bF0R4NmuTUvVJXPPjdI1AF8XHXeYSNfr8DJ5eDo terminal-test";
2628
29 const KEY2 = "ssh-ed25519 AAAAC3NzaC1lZDI1NTE5AAAAIOMqqnkVzrm0SdG6UOoqKLsabgH5C9okWi0dh2l9GKJl plain";
30 const KEY3 = "ssh-ed25519 AAAAC3NzaC1lZDI1NTE5AAAAIB2S7bF0R4NmuTUvVJXPPjdI1AF8XHXeYSNfr8DJ5eDp org";
31
2732 describe("terminal sign-up with an invite", () => {
2833 let dir: string;
2934 let forge: Forge;
@@ -42,8 +47,8 @@ describe("terminal sign-up with an invite", () => {
4247 await rm(dir, { recursive: true, force: true });
4348 });
4449
45 const attempt = async (name: string, token: string, submit = true): Promise<string> => {
46 const identity: TuiIdentity = { sshUsername: "git", remoteAddress: "198.51.100.7", fingerprint: "SHA256:x", publicKey: KEY };
50 const attempt = async (name: string, token: string, submit = true, publicKey = KEY): Promise<string> => {
51 const identity: TuiIdentity = { sshUsername: "git", remoteAddress: "198.51.100.7", fingerprint: "SHA256:x", publicKey };
4752 const { app } = createForgeApp(forge, identity, { terminal: headlessTerminal(120, 32), exitHooks: false });
4853 app.start();
4954 const key = (k: string, ctrl = false): void =>
@@ -140,4 +145,17 @@ describe("terminal sign-up with an invite", () => {
140145 await attempt("eve", token);
141146 expect(getUserByName(forge.db, "eve")).toBeFalsy();
142147 });
148
149 test("an invite to an organization toasts the welcome on the terminal signup; a plain one does not", async () => {
150 setLimit(forge.db, "signup.per_source", 1000, adminId);
151 const org = createOrg(forge.db, "acme", adminId);
152 if (!org.ok) throw new Error(org.error);
153 const plain = await attempt("plainly", mintInvite(forge.db, adminId).token, true, KEY2);
154 expect(getUserByName(forge.db, "plainly")).toBeTruthy();
155 expect(plain).not.toContain("Welcome to");
156 const { token } = mintInvite(forge.db, adminId, 7, Date.now(), org.value.id);
157 const text = await attempt("orgy", token, true, KEY3);
158 expect(getUserByName(forge.db, "orgy")).toBeTruthy();
159 expect(text).toContain("Welcome to acme");
160 });
143161 });

↑↓ navigate ↵ open ⌘↵ its app esc close

Keyboard shortcuts

Docs