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
Check · Review · Land · Live done — Landed and live in production.
scout/forge:scout/12561-an-invite-to-an-organization-lands-from → main 0 commits fork 3 threads · 3 unresolved
21 files
changed +691
−34
- docs/features/invite-org.md
- src/actions/invite_welcome.ts
- src/actions/invites.ts
- src/actions/requests.ts
- src/actions/users.ts
- src/core/invites.ts
- src/core/migration-pins/20261114090000-invite-org.pin
- src/core/migrations/20261114090000-invite-org.ts
- src/http/api.ts
- src/http/api/admin.ts
- src/http/mcp/tools/mint_invite.ts
- src/tui/screens/invites.ts
- src/tui/screens/signin.ts
- src/web/pages/admin-limits.ts
- src/web/pages/signup-passkey.ts
- src/web/pages/site.ts
- test/invite-org.test.ts
- test/invites-core.test.ts
- test/org-person-forge.test.ts
- test/tui-invites.test.ts
- test/tui-signup-invite.test.ts
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 { | ||
| 26 | 26 | import { canRead, canWrite, getRepoById, type Repo } from "../core/repos.ts"; |
| 27 | 27 | import { getUserByName } from "../core/users.ts"; |
| 28 | 28 | import { requireRepoAdmin, type AccessError } from "./access.ts"; |
| 29 | import { getOrg } from "../core/orgs.ts"; | |
| 29 | 30 | import { err, ok, type Result } from "../kernel/result.ts"; |
| 30 | 31 | import type { User } from "../core/users.ts"; |
| 31 | 32 | |
| 32 | type Error = "not_found" | "invalid_days"; | |
| 33 | type Error = "not_found" | "invalid_days" | "unknown_org"; | |
| 33 | 34 | |
| 34 | 35 | const admin = (actor: User | undefined): actor is User => |
| 35 | 36 | actor !== undefined && actor.isAdmin && actor.kind === "user"; |
| @@ -38,15 +39,23 @@ const admin = (actor: User | undefined): actor is User => | ||
| 38 | 39 | export const inviteLink = (origin: string, token: string): string => |
| 39 | 40 | `${origin.replace(/\/$/, "")}/signup?invite=${token}`; |
| 40 | 41 | |
| 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> { | |
| 42 | 47 | if (!admin(actor)) return err("not_found"); |
| 43 | 48 | const n = parseDays(days); |
| 44 | 49 | 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); | |
| 46 | 55 | app.bus.append({ |
| 47 | 56 | kind: "invite.minted", |
| 48 | 57 | 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 }) }, | |
| 50 | 59 | }); |
| 51 | 60 | return ok(made); |
| 52 | 61 | } |
src/actions/requests.ts +9 −1
| @@ -4,6 +4,7 @@ | ||
| 4 | 4 | * these: the page's buttons, the API and MCP. |
| 5 | 5 | */ |
| 6 | 6 | |
| 7 | import { welcomeInvited } from "./invite_welcome.ts"; | |
| 7 | 8 | import type { Database } from "bun:sqlite"; |
| 8 | 9 | import type { App } from "../app.ts"; |
| 9 | 10 | import { answerRequest, waitingRequests, type AccountRequest } from "../core/requests.ts"; |
| @@ -37,7 +38,14 @@ function answer( | ||
| 37 | 38 | // an admin gives credits. |
| 38 | 39 | if (state === "allowed") { |
| 39 | 40 | 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. | |
| 45 | void welcomeInvited(app, person).catch((e: unknown) => | |
| 46 | app.log.error("invite welcome failed", { user: person.username, error: String(e) }), | |
| 47 | ); | |
| 48 | } | |
| 41 | 49 | } |
| 42 | 50 | app.bus.append({ |
| 43 | 51 | kind: state === "allowed" ? "account.allowed" : "account.declined", |
src/actions/users.ts +7
| @@ -27,6 +27,7 @@ import { | ||
| 27 | 27 | import { mintViaToken, VIA_TOKEN_MAX_MS } from "../core/via_token.ts"; |
| 28 | 28 | import { id } from "../kernel/id.ts"; |
| 29 | 29 | import { contributedSince, inviteSpentBy } from "../core/invites.ts"; |
| 30 | import { welcomeInvited } from "./invite_welcome.ts"; | |
| 30 | 31 | import { cleanAsk, NOTE_MAX, SOURCE_MAX } from "../core/requests.ts"; |
| 31 | 32 | import { |
| 32 | 33 | changePassword as rehash, |
| @@ -188,6 +189,9 @@ export async function signUp( | ||
| 188 | 189 | }, |
| 189 | 190 | }); |
| 190 | 191 | 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); | |
| 191 | 195 | // The address is proven by the link it is sent; until then nothing it |
| 192 | 196 | // does may create or cost. A waiting account is mailed nothing yet. |
| 193 | 197 | if (email !== "" && created.value.waitingAt === null) await welcome(app, created.value); |
| @@ -251,6 +255,9 @@ export async function signUpWithPasskey( | ||
| 251 | 255 | }, |
| 252 | 256 | }); |
| 253 | 257 | 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); | |
| 254 | 261 | // As on the password path: no address given, no link to send. |
| 255 | 262 | if (email !== "" && created.value.waitingAt === null) await welcome(app, created.value); |
| 256 | 263 | return created; |
src/core/invites.ts +21 −3
| @@ -28,6 +28,8 @@ export interface Invite { | ||
| 28 | 28 | readonly usedAt: string | null; |
| 29 | 29 | /** The username it let in; null when unused or the account is gone. */ |
| 30 | 30 | readonly usedBy: string | null; |
| 31 | /** The organization the invite brings its person into, or null for a plain invite. */ | |
| 32 | readonly org: string | null; | |
| 31 | 33 | } |
| 32 | 34 | |
| 33 | 35 | interface Row { |
| @@ -41,10 +43,13 @@ interface Row { | ||
| 41 | 43 | /** The repository a link to work on it names; null for an invite to the forge. */ |
| 42 | 44 | repo_id: string | null; |
| 43 | 45 | used_by: string | null; |
| 46 | org_id: string | null; | |
| 47 | org_name: string | null; | |
| 44 | 48 | } |
| 45 | 49 | |
| 46 | 50 | /** 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"; | |
| 48 | 53 | |
| 49 | 54 | const stateOf = (r: Row, now: number): InviteState => |
| 50 | 55 | 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 => ({ | ||
| 57 | 62 | state: stateOf(r, now), |
| 58 | 63 | usedAt: r.used_at, |
| 59 | 64 | usedBy: r.used_at === null ? null : r.used_by_name, |
| 65 | org: r.org_name, | |
| 60 | 66 | }); |
| 61 | 67 | |
| 62 | 68 | /** A whole number of days from 1 to 30, or the default when absent. */ |
| @@ -71,12 +77,14 @@ export function mintInvite( | ||
| 71 | 77 | createdBy: string, |
| 72 | 78 | days: number = DEFAULT_DAYS, |
| 73 | 79 | now: number = Date.now(), |
| 80 | /** The id of the organization the invite brings its person into. */ | |
| 81 | orgId: string | null = null, | |
| 74 | 82 | ): { invite: Invite; token: string } { |
| 75 | 83 | const token = `invite_${secret()}`; |
| 76 | 84 | const inviteId = id(now); |
| 77 | 85 | 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); | |
| 80 | 88 | const row = db.query<Row, [string]>(`${SELECT} WHERE invite.id = ?1`).get(inviteId)!; |
| 81 | 89 | return { invite: view(row, now), token }; |
| 82 | 90 | } |
| @@ -281,3 +289,13 @@ export function contributedSince( | ||
| 281 | 289 | ) |
| 282 | 290 | .all(userId, since); |
| 283 | 291 | } |
| 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
src/http/api.ts +3 −1
| @@ -17,6 +17,7 @@ import { listAppReleases } from "../core/app_releases.ts"; | ||
| 17 | 17 | import { openapiHandler } from "../contract/served.ts"; |
| 18 | 18 | import { CHECK_ASKED } from "../actions/pull_ask_words.ts"; |
| 19 | 19 | import { liveOf } from "../perf/live.ts"; |
| 20 | import { inviteWelcome } from "../actions/invite_welcome.ts"; | |
| 20 | 21 | import { growth, MAX_DAYS as MAX_GROWTH_DAYS } from "../core/growth.ts"; |
| 21 | 22 | import { CEILING_REFUSAL, PAUSE_REFUSAL, pausedUntil } from "../core/planner_pause.ts"; |
| 22 | 23 | import { homeTruth } from "../system/home_truth.ts"; |
| @@ -1216,7 +1217,8 @@ export function apiRoutes(router: Router<Handler>, isPage: (path: string) => boo | ||
| 1216 | 1217 | if (!created.ok) return json({ error: created.error }, 422); |
| 1217 | 1218 | // Signup is `request`: the account waits for an admin, and acts as nothing yet. |
| 1218 | 1219 | 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); | |
| 1220 | 1222 | }); |
| 1221 | 1223 | |
| 1222 | 1224 | 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 { | ||
| 537 | 537 | const denied = accountAdmin(ctx, "admin"); |
| 538 | 538 | if (denied) return denied; |
| 539 | 539 | 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); | |
| 541 | 541 | if (!made.ok) |
| 542 | 542 | return made.error === "invalid_days" |
| 543 | 543 | ? apiError("invalid", 422, SPEND_WORDS.inviteDays) |
| 544 | : notFound(); | |
| 544 | : made.error === "unknown_org" | |
| 545 | ? apiError("invalid", 422, "no such organization") | |
| 546 | : notFound(); | |
| 545 | 547 | const origin = ctx.app.config.url ?? ctx.url.origin; |
| 546 | 548 | return json( |
| 547 | 549 | { ...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"; | ||
| 6 | 6 | export const tool: Tool = { |
| 7 | 7 | name: "mint_invite", |
| 8 | 8 | 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", | |
| 10 | 10 | description: |
| 11 | 11 | "Mint a one-use invite link, shown once, valid `days` (1–30, default 7). Person admins.", |
| 12 | 12 | inputSchema: { |
| 13 | 13 | type: "object", |
| 14 | 14 | properties: { |
| 15 | 15 | days: { type: "integer", minimum: 1, maximum: 30 }, |
| 16 | org: { type: "string", description: "Organization the person joins" }, | |
| 16 | 17 | }, |
| 17 | 18 | }, |
| 18 | 19 | writes: true, |
| @@ -20,8 +21,8 @@ export const tool: Tool = { | ||
| 20 | 21 | if (!mayBoards(user)) return bad("forbidden", "an invite is a forge admin's to mint"); |
| 21 | 22 | if (!scopeAllows(ctx.auth.scope ?? "ro", "admin")) |
| 22 | 23 | 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); | |
| 25 | 26 | const origin = ctx.app.config.url ?? ctx.url.origin; |
| 26 | 27 | return good({ ...made.value.invite, link: inviteLink(origin, made.value.token) }); |
| 27 | 28 | }, |
src/tui/screens/invites.ts +20 −4
| @@ -2,7 +2,8 @@ | ||
| 2 | 2 | * Invite links in the terminal, a forge admin's (#2337): every link with its |
| 3 | 3 | * state, when it was made and when it expires, as Invite links on /admin/limits |
| 4 | 4 | * 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 | |
| 6 | 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 |
| 7 | 8 | * admin who is a person; anyone else sees nothing and mints nothing. The top |
| 8 | 9 | * 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 { | ||
| 38 | 39 | return r.ok ? r.value : []; |
| 39 | 40 | }; |
| 40 | 41 | |
| 41 | const make = (raw: string): string | undefined => { | |
| 42 | const make = (raw: string, org = ""): string | undefined => { | |
| 42 | 43 | const text = raw.trim(); |
| 43 | 44 | 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); | |
| 45 | 46 | if (!made.ok) |
| 46 | 47 | return made.error === "invalid_days" |
| 47 | 48 | ? `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."; | |
| 49 | 52 | const origin = f.app.config.url ?? `http://localhost:${f.app.config.port}`; |
| 50 | 53 | note = `Shown once: ${inviteLink(origin, made.value.token)}`; |
| 51 | 54 | ctx.invalidate(); |
| @@ -108,6 +111,7 @@ export function invitesScreen(f: Session, ctx: Ctx): Screen { | ||
| 108 | 111 | return [ |
| 109 | 112 | binding(["j", "k"], "move cursor"), |
| 110 | 113 | binding(["m"], "make a link"), |
| 114 | binding(["o"], "make a link to an organization"), | |
| 111 | 115 | binding(["x"], "revoke"), |
| 112 | 116 | ...(signup().ok ? [binding(["s"], "who may sign up"), binding(["a"], "agents can start here")] : []), |
| 113 | 117 | ]; |
| @@ -144,6 +148,18 @@ export function invitesScreen(f: Session, ctx: Ctx): Screen { | ||
| 144 | 148 | onSubmit: make, |
| 145 | 149 | }), |
| 146 | 150 | ); |
| 151 | } else if (e.key === "o") { | |
| 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 | ); | |
| 147 | 163 | } else if (e.key === "x") { |
| 148 | 164 | const row = all[state.index]; |
| 149 | 165 | if (row === undefined) return false; |
src/tui/screens/signin.ts +3
| @@ -8,6 +8,7 @@ | ||
| 8 | 8 | * account while signup allows — not an admin; the operator makes the admin. |
| 9 | 9 | */ |
| 10 | 10 | |
| 11 | import { inviteWelcome, welcomeWords } from "../../actions/invite_welcome.ts"; | |
| 11 | 12 | import { activeEdgeToken } from "../../http/edge.ts"; |
| 12 | 13 | import { inviteByToken } from "../../core/invites.ts"; |
| 13 | 14 | import { whenWords } from "../../core/when_words.ts"; |
| @@ -158,6 +159,8 @@ export function signInScreen(f: Session, ctx: Ctx, onDone: () => void): Screen { | ||
| 158 | 159 | } |
| 159 | 160 | } |
| 160 | 161 | ctx.toast(`signed in as ${f.user?.username ?? ""}`, "success"); |
| 162 | const welcome = mode === "create" && f.user !== undefined ? inviteWelcome(f.app, f.user) : undefined; | |
| 163 | if (welcome !== undefined) ctx.toast(welcomeWords(welcome), "success"); | |
| 161 | 164 | onDone(); |
| 162 | 165 | ctx.pop(); |
| 163 | 166 | } finally { |
src/web/pages/admin-limits.ts +6 −2
| @@ -206,9 +206,11 @@ export function limitsPage(ctx: Ctx): Response { | ||
| 206 | 206 | step="1" |
| 207 | 207 | value="${String(DEFAULT_DAYS)}" |
| 208 | 208 | /></label> |
| 209 | <label class="small">organization (optional) | |
| 210 | <input class="input mono" type="text" name="org" maxlength="60" autocomplete="off" /></label> | |
| 209 | 211 | ${btn("Make a link", { size: "sm", variant: "primary", label: "Make an invite link" })} |
| 210 | 212 | </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> | |
| 212 | 214 | </dd> |
| 213 | 215 | <dd class="status-act"></dd> |
| 214 | 216 | </div>`; |
| @@ -369,8 +371,10 @@ export async function inviteMint(ctx: Ctx): Promise<Response> { | ||
| 369 | 371 | const form = await readForm(ctx, "admin"); |
| 370 | 372 | if (form instanceof Response) return form; |
| 371 | 373 | 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")); | |
| 373 | 375 | 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." }); | |
| 374 | 378 | if (!made.ok) |
| 375 | 379 | return flashTo(ctx, "/admin/limits", { |
| 376 | 380 | tone: "danger", |
src/web/pages/signup-passkey.ts +3 −1
| @@ -6,6 +6,7 @@ | ||
| 6 | 6 | * per address; a challenge answers once. |
| 7 | 7 | */ |
| 8 | 8 | |
| 9 | import { inviteWelcome } from "../../actions/invite_welcome.ts"; | |
| 9 | 10 | import { newChallenge, verifyRegistration } from "../../auth/webauthn.ts"; |
| 10 | 11 | import { givenEmail, invalidEmailMessage, signUpWithPasskey, signupClosed, HUMAN_CHECK_MESSAGE, SIGNUP_CLOSED_MESSAGE } from "../../actions/users.ts"; |
| 11 | 12 | import { rotateSession } from "../../auth/session_rotate.ts"; |
| @@ -109,8 +110,9 @@ export async function signupPasskey(ctx: Ctx): Promise<Response> { | ||
| 109 | 110 | // A request that waits starts no session: it lands on the page that says so. |
| 110 | 111 | if (created.value.waitingAt !== null) return json({ ok: true, waiting: true, next: "/signup/requested" }, 202); |
| 111 | 112 | const session = rotateSession(ctx.app.db, cookieValue(ctx.request, "forge_session"), created.value.id); |
| 113 | const welcome = inviteWelcome(ctx.app, created.value); | |
| 112 | 114 | 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 }) }, | |
| 114 | 116 | 201, |
| 115 | 117 | { "set-cookie": sessionCookie(session.token, session.expiresAt, ctx.url, ctx.app.config.url) }, |
| 116 | 118 | ); |
src/web/pages/site.ts +6 −4
| @@ -11,6 +11,7 @@ | ||
| 11 | 11 | import { contributorMay } from "../../text/contributor.ts"; |
| 12 | 12 | import { closeState, closingSays } from "../../actions/account_close.ts"; |
| 13 | 13 | import { USERNAME_PATTERN } from "../username_pattern.ts"; |
| 14 | import { inviteWelcome, welcomeWords } from "../../actions/invite_welcome.ts"; | |
| 14 | 15 | import { expireCookie, setCookie } from "../../auth/cookies.ts"; |
| 15 | 16 | import { safeNext, withReturn } from "../return_to.ts"; |
| 16 | 17 | import { armPendingReturn, pendingReturn } from "../../core/pending_return.ts"; |
| @@ -861,13 +862,14 @@ export async function signupSubmit(ctx: Ctx): Promise<Response> { | ||
| 861 | 862 | // A request that waits has no session to start: it lands on the page that says so. |
| 862 | 863 | if (created.value.waitingAt !== null) return redirect("/signup/requested"); |
| 863 | 864 | const session = rotateSession(ctx.app.db, cookieValue(ctx.request, "forge_session"), created.value.id); |
| 865 | const welcome = inviteWelcome(ctx.app, created.value); | |
| 864 | 866 | const next = safeNext(ctx.url.searchParams.get("next")); |
| 865 | 867 | // Signed up from Make it yours: arm that one copy for the new account (`core/pending_return.ts`). |
| 866 | 868 | 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 | }); | |
| 871 | 873 | } |
| 872 | 874 | |
| 873 | 875 | // 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 @@ | ||
| 6 | 6 | import { beforeEach, describe, expect, test } from "bun:test"; |
| 7 | 7 | import { Database } from "bun:sqlite"; |
| 8 | 8 | import invite from "../src/core/migrations/20261016200000-invite.ts"; |
| 9 | import inviteOrg from "../src/core/migrations/20261114090000-invite-org.ts"; | |
| 9 | 10 | import { |
| 10 | 11 | DEFAULT_DAYS, |
| 11 | 12 | MAX_DAYS, |
| @@ -38,6 +39,7 @@ describe("an invite's life", () => { | ||
| 38 | 39 | beforeEach(() => { |
| 39 | 40 | db = new Database(":memory:"); |
| 40 | 41 | db.exec(invite); |
| 42 | db.exec(inviteOrg); | |
| 41 | 43 | db.exec("CREATE TABLE user (id TEXT PRIMARY KEY, username TEXT NOT NULL)"); |
| 42 | 44 | }); |
| 43 | 45 |
test/org-person-forge.test.ts +6 −7
| @@ -1,12 +1,10 @@ | ||
| 1 | 1 | /** |
| 2 | 2 | * 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 | |
| 5 | 5 | * names no organization, so the person is in no team, owns no repository, |
| 6 | 6 | * 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. | |
| 10 | 8 | */ |
| 11 | 9 | import { afterAll, beforeAll, expect, test } from "bun:test"; |
| 12 | 10 | 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 | ||
| 69 | 67 | const ivy = getUserByName(app.db, "ivy"); |
| 70 | 68 | expect(ivy).toBeDefined(); |
| 71 | 69 | |
| 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(); | |
| 74 | 73 | expect(isOrgMember(app.db, org.value.id, ivy!.id)).toBe(false); |
| 75 | 74 | // ...owns no repository (no forge of their own with an app in it)... |
| 76 | 75 | expect(listReposOwnedBy(app.db, ivy!.id)).toEqual([]); |
test/tui-invites.test.ts +24
| @@ -9,6 +9,7 @@ import { tmpdir } from "node:os"; | ||
| 9 | 9 | import { join } from "node:path"; |
| 10 | 10 | import { createApp, type App as Forge } from "../src/app.ts"; |
| 11 | 11 | import { listInvites, mintInvite, redeemInvite } from "../src/core/invites.ts"; |
| 12 | import { createOrg } from "../src/core/orgs.ts"; | |
| 12 | 13 | import { createUser, getUserByName } from "../src/core/users.ts"; |
| 13 | 14 | import { createForgeApp } from "../src/tui/forge.ts"; |
| 14 | 15 | import { invitesScreen } from "../src/tui/screens/invites.ts"; |
| @@ -104,6 +105,29 @@ describe("invite links in the terminal", () => { | ||
| 104 | 105 | h.stop(); |
| 105 | 106 | }); |
| 106 | 107 | |
| 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 | ||
| 107 | 131 | test("n or esc on the revoke confirm keeps the link open", async () => { |
| 108 | 132 | const h = boot("alice"); |
| 109 | 133 | await open(h); |
test/tui-signup-invite.test.ts +20 −2
| @@ -10,7 +10,9 @@ import { join } from "node:path"; | ||
| 10 | 10 | import { signUp } from "../src/actions/users.ts"; |
| 11 | 11 | import { createApp, type App as Forge } from "../src/app.ts"; |
| 12 | 12 | import { listInvites, mintInvite } from "../src/core/invites.ts"; |
| 13 | import { createOrg } from "../src/core/orgs.ts"; | |
| 13 | 14 | import { getUserByName } from "../src/core/users.ts"; |
| 15 | import { setLimit } from "../src/settings/limits.ts"; | |
| 14 | 16 | import { setSignup } from "../src/settings/signup.ts"; |
| 15 | 17 | import { createForgeApp } from "../src/tui/forge.ts"; |
| 16 | 18 | import type { TuiIdentity } from "../src/tui/session.ts"; |
| @@ -24,6 +26,9 @@ quietLogs(); | ||
| 24 | 26 | const KEY = |
| 25 | 27 | "ssh-ed25519 AAAAC3NzaC1lZDI1NTE5AAAAIB2S7bF0R4NmuTUvVJXPPjdI1AF8XHXeYSNfr8DJ5eDo terminal-test"; |
| 26 | 28 | |
| 29 | const KEY2 = "ssh-ed25519 AAAAC3NzaC1lZDI1NTE5AAAAIOMqqnkVzrm0SdG6UOoqKLsabgH5C9okWi0dh2l9GKJl plain"; | |
| 30 | const KEY3 = "ssh-ed25519 AAAAC3NzaC1lZDI1NTE5AAAAIB2S7bF0R4NmuTUvVJXPPjdI1AF8XHXeYSNfr8DJ5eDp org"; | |
| 31 | ||
| 27 | 32 | describe("terminal sign-up with an invite", () => { |
| 28 | 33 | let dir: string; |
| 29 | 34 | let forge: Forge; |
| @@ -42,8 +47,8 @@ describe("terminal sign-up with an invite", () => { | ||
| 42 | 47 | await rm(dir, { recursive: true, force: true }); |
| 43 | 48 | }); |
| 44 | 49 | |
| 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 }; | |
| 47 | 52 | const { app } = createForgeApp(forge, identity, { terminal: headlessTerminal(120, 32), exitHooks: false }); |
| 48 | 53 | app.start(); |
| 49 | 54 | const key = (k: string, ctrl = false): void => |
| @@ -140,4 +145,17 @@ describe("terminal sign-up with an invite", () => { | ||
| 140 | 145 | await attempt("eve", token); |
| 141 | 146 | expect(getUserByName(forge.db, "eve")).toBeFalsy(); |
| 142 | 147 | }); |
| 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 | }); | |
| 143 | 161 | }); |
new above
offline
Failure is swallowed silently. Log it or record an event so an allowed person who got no seat or forks can be found.