Public: anyone can read this; the crew can change it.
An invite to an organization puts the new person in it and gives them a forge whose app follows the organization's, mode proposes #12484
mason/forge:mason/12479-an-invite-to-an-organization-puts-the-ne → main 12 commits fork
20 files
changed +583
−33
- docs/MCP.md
- 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
docs/MCP.md +1 −1
| @@ -145,7 +145,7 @@ bytes in `tools/list`. After changing a tool run `bun scripts/mcp-table.ts`; | ||
| 145 | 145 | | `merge` | `land` | Land a pull, as its page's Merge button does; a person's only | 362 | |
| 146 | 146 | | `migrate` | — | Bring a repo in by public `url` (`name`, `crew`), history and all | 269 | |
| 147 | 147 | | `milestones` | — | How far each ask is | 439 | |
| 148 | | `mint_invite` | — | Mint a one-use invite link, shown once, valid `days` (1–30, default 7) | 225 | | |
| 148 | | `mint_invite` | — | Mint a one-use invite link, shown once, valid `days` (1–30, default 7) | 295 | | |
| 149 | 149 | | `mirror_now` | — | Admin: bring the snapshot mirror level now | 129 | |
| 150 | 150 | | `mirror_set` | — | Admin: set or forget the snapshot mirror | 296 | |
| 151 | 151 | | `model_ceiling` | — | Set an account's daily and per-run model spend ceilings in dollars | 422 | |
docs/features/invite-org.md added +5
| @@ -0,0 +1,5 @@ | ||
| 1 | # An invite to an organization | |
| 2 | ||
| 3 | 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. | |
| 4 | 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. | |
| 5 | 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
| @@ -5,10 +5,11 @@ | ||
| 5 | 5 | |
| 6 | 6 | import type { App } from "../app.ts"; |
| 7 | 7 | import { listInvites, mintInvite, parseDays, revokeInvite, type Invite } from "../core/invites.ts"; |
| 8 | import { getOrg } from "../core/orgs.ts"; | |
| 8 | 9 | import { err, ok, type Result } from "../kernel/result.ts"; |
| 9 | 10 | import type { User } from "../core/users.ts"; |
| 10 | 11 | |
| 11 | type Error = "not_found" | "invalid_days"; | |
| 12 | type Error = "not_found" | "invalid_days" | "unknown_org"; | |
| 12 | 13 | |
| 13 | 14 | const admin = (actor: User | undefined): actor is User => |
| 14 | 15 | actor !== undefined && actor.isAdmin && actor.kind === "user"; |
| @@ -17,15 +18,23 @@ const admin = (actor: User | undefined): actor is User => | ||
| 17 | 18 | export const inviteLink = (origin: string, token: string): string => |
| 18 | 19 | `${origin.replace(/\/$/, "")}/signup?invite=${token}`; |
| 19 | 20 | |
| 20 | export function mint(app: App, actor: User | undefined, days: unknown): Result<{ invite: Invite; token: string }, Error> { | |
| 21 | /** | |
| 22 | * `org` names the organization the invite brings its person into; absent or empty is a plain | |
| 23 | * invite. | |
| 24 | */ | |
| 25 | export function mint(app: App, actor: User | undefined, days: unknown, org?: unknown): Result<{ invite: Invite; token: string }, Error> { | |
| 21 | 26 | if (!admin(actor)) return err("not_found"); |
| 22 | 27 | const n = parseDays(days); |
| 23 | 28 | if (!n.ok) return n; |
| 24 | const made = mintInvite(app.db, actor.id, n.value); | |
| 29 | const name = typeof org === "string" ? org.trim() : ""; | |
| 30 | if (org !== undefined && org !== null && typeof org !== "string") return err("unknown_org"); | |
| 31 | const target = name === "" ? undefined : getOrg(app.db, name); | |
| 32 | if (name !== "" && target === undefined) return err("unknown_org"); | |
| 33 | const made = mintInvite(app.db, actor.id, n.value, Date.now(), target?.id ?? null); | |
| 25 | 34 | app.bus.append({ |
| 26 | 35 | kind: "invite.minted", |
| 27 | 36 | actorId: actor.id, |
| 28 | payload: { id: made.invite.id, expiresAt: made.invite.expiresAt }, | |
| 37 | payload: { id: made.invite.id, expiresAt: made.invite.expiresAt, ...(target === undefined ? {} : { org: target.username }) }, | |
| 29 | 38 | }); |
| 30 | 39 | return ok(made); |
| 31 | 40 | } |
src/actions/requests.ts +6 −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,11 @@ 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 | void welcomeInvited(app, person).catch(() => undefined); | |
| 45 | } | |
| 41 | 46 | } |
| 42 | 47 | app.bus.append({ |
| 43 | 48 | 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 { 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, |
| @@ -177,6 +178,9 @@ export async function signUp( | ||
| 177 | 178 | }, |
| 178 | 179 | }); |
| 179 | 180 | auditInvite(app, created.value.id); |
| 181 | // Until the account is let in nothing it does may create or cost: | |
| 182 | // `allowRequest` welcomes it then. | |
| 183 | if (created.value.waitingAt === null) await welcomeInvited(app, created.value); | |
| 180 | 184 | // The address is proven by the link it is sent; until then nothing it |
| 181 | 185 | // does may create or cost. A waiting account is mailed nothing yet. |
| 182 | 186 | if (email !== "" && created.value.waitingAt === null) await welcome(app, created.value); |
| @@ -240,6 +244,9 @@ export async function signUpWithPasskey( | ||
| 240 | 244 | }, |
| 241 | 245 | }); |
| 242 | 246 | auditInvite(app, created.value.id); |
| 247 | // Until the account is let in nothing it does may create or cost: | |
| 248 | // `allowRequest` welcomes it then. | |
| 249 | if (created.value.waitingAt === null) await welcomeInvited(app, created.value); | |
| 243 | 250 | // As on the password path: no address given, no link to send. |
| 244 | 251 | if (email !== "" && created.value.waitingAt === null) await welcome(app, created.value); |
| 245 | 252 | 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 { |
| @@ -38,10 +40,13 @@ interface Row { | ||
| 38 | 40 | revoked_at: string | null; |
| 39 | 41 | used_at: string | null; |
| 40 | 42 | used_by_name: string | null; |
| 43 | org_id: string | null; | |
| 44 | org_name: string | null; | |
| 41 | 45 | } |
| 42 | 46 | |
| 43 | 47 | /** An invite with its redeemer's username, resolved in the one query. */ |
| 44 | const SELECT = "SELECT invite.*, user.username AS used_by_name FROM invite LEFT JOIN user ON user.id = invite.used_by"; | |
| 48 | const SELECT = | |
| 49 | "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"; | |
| 45 | 50 | |
| 46 | 51 | const stateOf = (r: Row, now: number): InviteState => |
| 47 | 52 | r.revoked_at !== null ? "revoked" : r.used_at !== null ? "used" : Date.parse(r.expires_at) <= now ? "expired" : "open"; |
| @@ -54,6 +59,7 @@ const view = (r: Row, now: number): Invite => ({ | ||
| 54 | 59 | state: stateOf(r, now), |
| 55 | 60 | usedAt: r.used_at, |
| 56 | 61 | usedBy: r.used_at === null ? null : r.used_by_name, |
| 62 | org: r.org_name, | |
| 57 | 63 | }); |
| 58 | 64 | |
| 59 | 65 | /** A whole number of days from 1 to 30, or the default when absent. */ |
| @@ -68,12 +74,14 @@ export function mintInvite( | ||
| 68 | 74 | createdBy: string, |
| 69 | 75 | days: number = DEFAULT_DAYS, |
| 70 | 76 | now: number = Date.now(), |
| 77 | /** The id of the organization the invite brings its person into. */ | |
| 78 | orgId: string | null = null, | |
| 71 | 79 | ): { invite: Invite; token: string } { |
| 72 | 80 | const token = `invite_${secret()}`; |
| 73 | 81 | const inviteId = id(now); |
| 74 | 82 | db.query( |
| 75 | "INSERT INTO invite (id, token_hash, created_by, created_at, expires_at) VALUES (?1, ?2, ?3, ?4, ?5)", | |
| 76 | ).run(inviteId, sha256(token), createdBy, new Date(now).toISOString(), new Date(now + days * DAY).toISOString()); | |
| 83 | "INSERT INTO invite (id, token_hash, created_by, created_at, expires_at, org_id) VALUES (?1, ?2, ?3, ?4, ?5, ?6)", | |
| 84 | ).run(inviteId, sha256(token), createdBy, new Date(now).toISOString(), new Date(now + days * DAY).toISOString(), orgId); | |
| 77 | 85 | const row = db.query<Row, [string]>(`${SELECT} WHERE invite.id = ?1`).get(inviteId)!; |
| 78 | 86 | return { invite: view(row, now), token }; |
| 79 | 87 | } |
| @@ -135,3 +143,13 @@ export function revokeInvite( | ||
| 135 | 143 | export function inviteSpentBy(db: Database, userId: string): string | undefined { |
| 136 | 144 | return db.query<{ id: string }, [string]>("SELECT id FROM invite WHERE used_by = ?1").get(userId)?.id; |
| 137 | 145 | } |
| 146 | ||
| 147 | /** The organization (id and name) the invite an account spent brought it into, if it named one. */ | |
| 148 | export function inviteOrgOf(db: Database, userId: string): { id: string; name: string } | undefined { | |
| 149 | const row = db | |
| 150 | .query<{ id: string; name: string }, [string]>( | |
| 151 | "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", | |
| 152 | ) | |
| 153 | .get(userId); | |
| 154 | return row ?? undefined; | |
| 155 | } |
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
| @@ -8,6 +8,7 @@ | ||
| 8 | 8 | * back to continue); errors are `{ error, message }`. |
| 9 | 9 | */ |
| 10 | 10 | |
| 11 | import { inviteWelcome } from "../actions/invite_welcome.ts"; | |
| 11 | 12 | import { reviewWords } from "../actions/review_words.ts"; |
| 12 | 13 | import { growth, MAX_DAYS as MAX_GROWTH_DAYS } from "../core/growth.ts"; |
| 13 | 14 | import { PAUSE_REFUSAL, pausedUntil } from "../core/planner_pause.ts"; |
| @@ -1239,7 +1240,8 @@ export function apiRoutes(router: Router<Handler>): void { | ||
| 1239 | 1240 | if (!created.ok) return json({ error: created.error }, 422); |
| 1240 | 1241 | // Signup is `request`: the account waits for an admin, and acts as nothing yet. |
| 1241 | 1242 | if (created.value.waitingAt !== null) return json({ state: "waiting", username: created.value.username, message: REQUEST_IN_MESSAGE }, 202); |
| 1242 | return json(publicUser(created.value), 201); | |
| 1243 | const welcome = inviteWelcome(ctx.app, created.value); | |
| 1244 | return json(welcome === undefined ? publicUser(created.value) : { ...publicUser(created.value), welcome }, 201); | |
| 1243 | 1245 | }); |
| 1244 | 1246 | |
| 1245 | 1247 | router.add("GET", "/api/v1/users/:username", (ctx) => { |
src/http/api/admin.ts +4 −2
| @@ -445,11 +445,13 @@ export function adminRoutes(router: Router<Handler>): void { | ||
| 445 | 445 | const denied = accountAdmin(ctx, "admin"); |
| 446 | 446 | if (denied) return denied; |
| 447 | 447 | const input = await body(ctx.request); |
| 448 | const made = mintInviteLink(ctx.app, ctx.auth.user, input.days); | |
| 448 | const made = mintInviteLink(ctx.app, ctx.auth.user, input.days, input.org); | |
| 449 | 449 | if (!made.ok) |
| 450 | 450 | return made.error === "invalid_days" |
| 451 | 451 | ? apiError("invalid", 422, SPEND_WORDS.inviteDays) |
| 452 | : notFound(); | |
| 452 | : made.error === "unknown_org" | |
| 453 | ? apiError("invalid", 422, "no such organization") | |
| 454 | : notFound(); | |
| 453 | 455 | const origin = ctx.app.config.url ?? ctx.url.origin; |
| 454 | 456 | return json( |
| 455 | 457 | { ...made.value.invite, token: made.value.token, link: inviteLink(origin, made.value.token) }, |
src/http/mcp/tools/mint_invite.ts +4 −3
| @@ -5,13 +5,14 @@ import { good, bad, type Tool, mayBoards } from "../shared.ts"; | ||
| 5 | 5 | |
| 6 | 6 | export const tool: Tool = { |
| 7 | 7 | name: "mint_invite", |
| 8 | 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", | |
| 8 | doc: "`{ days?, org? }`: mint a single-use invite link that expires in `days` (1–30, default 7) and is shown once; with `org` the person joins that organization and gets private forks of its apps; a person admin's, with an admin token", | |
| 9 | 9 | description: |
| 10 | 10 | "Mint a one-use invite link, shown once, valid `days` (1–30, default 7). Person admins.", |
| 11 | 11 | inputSchema: { |
| 12 | 12 | type: "object", |
| 13 | 13 | properties: { |
| 14 | 14 | days: { type: "integer", minimum: 1, maximum: 30 }, |
| 15 | org: { type: "string", description: "Organization the person joins" }, | |
| 15 | 16 | }, |
| 16 | 17 | }, |
| 17 | 18 | writes: true, |
| @@ -19,8 +20,8 @@ export const tool: Tool = { | ||
| 19 | 20 | if (!mayBoards(user)) return bad("forbidden", "an invite is a forge admin's to mint"); |
| 20 | 21 | if (!scopeAllows(ctx.auth.scope ?? "ro", "admin")) |
| 21 | 22 | return bad("forbidden", "an invite needs an admin token"); |
| 22 | const made = mintInviteLink(ctx.app, user, args["days"]); | |
| 23 | if (!made.ok) return bad("invalid", SPEND_WORDS.inviteDays); | |
| 23 | const made = mintInviteLink(ctx.app, user, args["days"], args["org"]); | |
| 24 | if (!made.ok) return bad("invalid", made.error === "unknown_org" ? "no such organization" : SPEND_WORDS.inviteDays); | |
| 24 | 25 | const origin = ctx.app.config.url ?? ctx.url.origin; |
| 25 | 26 | return good({ ...made.value.invite, link: inviteLink(origin, made.value.token) }); |
| 26 | 27 | }, |
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 { INVITE_SPENT_MESSAGE, REQUEST_IN_MESSAGE, SIGNUP_CLOSED_MESSAGE, signUp, signupClosed } from "../../actions/users.ts"; |
| 13 | 14 | import { SignupSlot, waitText } from "../../actions/signup-window.ts"; |
| @@ -143,6 +144,8 @@ export function signInScreen(f: Session, ctx: Ctx, onDone: () => void): Screen { | ||
| 143 | 144 | } |
| 144 | 145 | } |
| 145 | 146 | ctx.toast(`signed in as ${f.user?.username ?? ""}`, "success"); |
| 147 | const welcome = mode === "create" && f.user !== undefined ? inviteWelcome(f.app, f.user) : undefined; | |
| 148 | if (welcome !== undefined) ctx.toast(welcomeWords(welcome), "success"); | |
| 146 | 149 | onDone(); |
| 147 | 150 | ctx.pop(); |
| 148 | 151 | } finally { |
src/web/pages/admin-limits.ts +6 −2
| @@ -204,9 +204,11 @@ export function limitsPage(ctx: Ctx): Response { | ||
| 204 | 204 | step="1" |
| 205 | 205 | value="${String(DEFAULT_DAYS)}" |
| 206 | 206 | /></label> |
| 207 | <label class="small">organization (optional) | |
| 208 | <input class="input mono" type="text" name="org" maxlength="60" autocomplete="off" /></label> | |
| 207 | 209 | ${btn("Make a link", { size: "sm", variant: "primary", label: "Make an invite link" })} |
| 208 | 210 | </form> |
| 209 | <span class="muted small">Shown once, when it is made; good for one signup.</span> | |
| 211 | <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> | |
| 210 | 212 | </dd> |
| 211 | 213 | <dd class="status-act"></dd> |
| 212 | 214 | </div>`; |
| @@ -366,8 +368,10 @@ export async function inviteMint(ctx: Ctx): Promise<Response> { | ||
| 366 | 368 | const form = await readForm(ctx, "admin"); |
| 367 | 369 | if (form instanceof Response) return form; |
| 368 | 370 | const raw = field(form, "days").trim(); |
| 369 | const made = mintInviteLink(ctx.app, ctx.auth.user, /^\d{1,3}$/.test(raw) ? Number(raw) : -1); | |
| 371 | const made = mintInviteLink(ctx.app, ctx.auth.user, /^\d{1,3}$/.test(raw) ? Number(raw) : -1, field(form, "org")); | |
| 370 | 372 | if (!made.ok && made.error === "not_found") return notFoundPage(ctx); |
| 373 | if (!made.ok && made.error === "unknown_org") | |
| 374 | return flashTo(ctx, "/admin/limits", { tone: "danger", message: "No organization by that name." }); | |
| 371 | 375 | if (!made.ok) |
| 372 | 376 | return flashTo(ctx, "/admin/limits", { |
| 373 | 377 | 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, signUpWithPasskey, signupClosed, HUMAN_CHECK_MESSAGE, SIGNUP_CLOSED_MESSAGE } from "../../actions/users.ts"; |
| 11 | 12 | import { createSession } from "../../core/sessions.ts"; |
| @@ -110,8 +111,9 @@ export async function signupPasskey(ctx: Ctx): Promise<Response> { | ||
| 110 | 111 | // A request that waits starts no session: it lands on the page that says so. |
| 111 | 112 | if (created.value.waitingAt !== null) return json({ ok: true, waiting: true, next: "/signup/requested" }, 202); |
| 112 | 113 | const session = createSession(ctx.app.db, created.value.id); |
| 114 | const welcome = inviteWelcome(ctx.app, created.value); | |
| 113 | 115 | return json( |
| 114 | { ok: true, next: safeNext(ctx.url.searchParams.get("next")) ?? "/" }, | |
| 116 | { ok: true, next: safeNext(ctx.url.searchParams.get("next")) ?? "/", ...(welcome === undefined ? {} : { welcome }) }, | |
| 115 | 117 | 201, |
| 116 | 118 | { "set-cookie": sessionCookie(session.token, session.expiresAt, ctx.url, ctx.app.config.url) }, |
| 117 | 119 | ); |
src/web/pages/site.ts +6 −4
| @@ -8,6 +8,7 @@ | ||
| 8 | 8 | * typed still in it. A dead end that loses input is a bug, not a message. |
| 9 | 9 | */ |
| 10 | 10 | |
| 11 | import { inviteWelcome, welcomeWords } from "../../actions/invite_welcome.ts"; | |
| 11 | 12 | import { expireCookie, setCookie } from "../../auth/cookies.ts"; |
| 12 | 13 | import { safeNext, withReturn } from "../return_to.ts"; |
| 13 | 14 | import { notePhase, takeSessionTime, timePhase } from "../../core/route_timing.ts"; |
| @@ -770,10 +771,11 @@ export async function signupSubmit(ctx: Ctx): Promise<Response> { | ||
| 770 | 771 | // A request that waits has no session to start: it lands on the page that says so. |
| 771 | 772 | if (created.value.waitingAt !== null) return redirect("/signup/requested"); |
| 772 | 773 | const session = createSession(ctx.app.db, created.value.id); |
| 773 | return redirect( | |
| 774 | safeNext(ctx.url.searchParams.get("next")) ?? "/", | |
| 775 | sessionCookie(session.token, session.expiresAt, ctx.url, ctx.app.config.url), | |
| 776 | ); | |
| 774 | const welcome = inviteWelcome(ctx.app, created.value); | |
| 775 | return redirect(safeNext(ctx.url.searchParams.get("next")) ?? "/", { | |
| 776 | cookie: sessionCookie(session.token, session.expiresAt, ctx.url, ctx.app.config.url), | |
| 777 | ...(welcome === undefined ? {} : { flash: { message: welcomeWords(welcome) }, url: ctx.url, forgeUrl: ctx.app.config.url }), | |
| 778 | }); | |
| 777 | 779 | } |
| 778 | 780 | |
| 779 | 781 | // POST /theme — persist the theme choice in a cookie. Works as a plain form |
test/invite-org.test.ts added +337
| @@ -0,0 +1,337 @@ | ||
| 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 { createApp, type App } from "../src/app.ts"; | |
| 11 | import { list as listInvites, mint } from "../src/actions/invites.ts"; | |
| 12 | import { allowRequest } from "../src/actions/requests.ts"; | |
| 13 | import { createToken } from "../src/core/tokens.ts"; | |
| 14 | import { createSession } from "../src/core/sessions.ts"; | |
| 15 | import { setQuota } from "../src/settings/quotas.ts"; | |
| 16 | import { createApp as insertApp } from "../src/core/apps.ts"; | |
| 17 | import { FORK_DEFAULT_MODE, forkFollowMode } from "../src/core/fork_follow.ts"; | |
| 18 | import { createOrg, createTeam, isOrgMember, getOrg, orgAccess } from "../src/core/orgs.ts"; | |
| 19 | import { createRepo, forkRepo, getRepo } from "../src/core/repos.ts"; | |
| 20 | import { createUser, getUserByName, type User } from "../src/core/users.ts"; | |
| 21 | import { serve, type Servers } from "../src/http/server.ts"; | |
| 22 | import { setLimit } from "../src/settings/limits.ts"; | |
| 23 | import { setSignup } from "../src/settings/signup.ts"; | |
| 24 | import { seedAdmin } from "./helpers/admin.ts"; | |
| 25 | import { device } from "./helpers/passkey.ts"; | |
| 26 | import { quietLogs } from "./helpers/globals.ts"; | |
| 27 | ||
| 28 | quietLogs(); | |
| 29 | const PASSWORD = "an-invited-passphrase"; | |
| 30 | ||
| 31 | describe("an invite to an organization", () => { | |
| 32 | let dir = ""; | |
| 33 | let app: App; | |
| 34 | let servers: Servers; | |
| 35 | let admin: User; | |
| 36 | ||
| 37 | const signup = async (username: string, invite: string) => | |
| 38 | fetch(`${servers.url}/api/v1/users`, { | |
| 39 | method: "POST", | |
| 40 | headers: { "content-type": "application/json" }, | |
| 41 | body: JSON.stringify({ username, email: `${username}@f.dev`, password: PASSWORD, invite }), | |
| 42 | }); | |
| 43 | const tokenOf = (org?: string) => { | |
| 44 | const made = mint(app, admin, undefined, org); | |
| 45 | if (!made.ok) throw new Error(made.error); | |
| 46 | return made.value; | |
| 47 | }; | |
| 48 | ||
| 49 | beforeAll(async () => { | |
| 50 | dir = await mkdtemp(join(tmpdir(), "forge-invite-org-")); | |
| 51 | app = createApp({ dataDir: dir, port: 0 }); | |
| 52 | servers = await serve(app); | |
| 53 | const made = await seedAdmin(app, { username: "olive", email: "[email protected]", password: PASSWORD }); | |
| 54 | if (!made.ok) throw new Error(made.error); | |
| 55 | admin = made.value; | |
| 56 | setSignup(app.db, "invite", admin.id); | |
| 57 | setLimit(app.db, "signup.per_source", 1000, admin.id); | |
| 58 | const org = createOrg(app.db, "acme", admin.id); | |
| 59 | if (!org.ok) throw new Error(org.error); | |
| 60 | for (const name of ["site", "api"]) { | |
| 61 | const repo = await createRepo(app.db, app.reposRoot, { ownerId: org.value.id, name, visibility: "public" }); | |
| 62 | if (!repo.ok) throw new Error(repo.error); | |
| 63 | insertApp(app.db, { repoId: repo.value.id, slug: `acme-${name}`, access: "public" }); | |
| 64 | } | |
| 65 | // A repository that is not an app is not forked. | |
| 66 | await createRepo(app.db, app.reposRoot, { ownerId: org.value.id, name: "notes", visibility: "public" }); | |
| 67 | }); | |
| 68 | afterAll(async () => { | |
| 69 | servers.stop(); | |
| 70 | app.close(); | |
| 71 | await rm(dir, { recursive: true, force: true }); | |
| 72 | }); | |
| 73 | ||
| 74 | test("the person joins the organization and gets private forks that follow its apps", async () => { | |
| 75 | const { invite, token } = tokenOf("acme"); | |
| 76 | expect(invite.org).toBe("acme"); | |
| 77 | const res = await signup("nova", token); | |
| 78 | expect(res.status).toBe(201); | |
| 79 | const body = (await res.json()) as { welcome: { org: string; team: string; forks: { repo: string; from: string; mode: string }[] } }; | |
| 80 | expect(body.welcome.org).toBe("acme"); | |
| 81 | expect(body.welcome.team).toBe("Members"); | |
| 82 | expect(body.welcome.forks.map((f) => f.repo)).toEqual(["nova/site", "nova/api"]); | |
| 83 | const nova = getUserByName(app.db, "nova")!; | |
| 84 | const org = getOrg(app.db, "acme")!; | |
| 85 | expect(isOrgMember(app.db, org.id, nova.id)).toBe(true); | |
| 86 | for (const name of ["site", "api"]) { | |
| 87 | const fork = getRepo(app.db, "nova", name)!; | |
| 88 | expect(fork.visibility).toBe("private"); | |
| 89 | expect(fork.forkParentId).toBe(getRepo(app.db, "acme", name)!.id); | |
| 90 | expect(forkFollowMode(app.db, fork.id)).toBe(FORK_DEFAULT_MODE); | |
| 91 | } | |
| 92 | expect(getRepo(app.db, "nova", "notes")).toBeUndefined(); | |
| 93 | }); | |
| 94 | ||
| 95 | test("a plain invite makes a plain account", async () => { | |
| 96 | const res = await signup("plain", tokenOf().token); | |
| 97 | expect(res.status).toBe(201); | |
| 98 | expect("welcome" in ((await res.json()) as object)).toBe(false); | |
| 99 | expect(getRepo(app.db, "plain", "site")).toBeUndefined(); | |
| 100 | }); | |
| 101 | ||
| 102 | test("an organization that does not exist mints nothing", () => { | |
| 103 | const made = mint(app, admin, undefined, "nowhere"); | |
| 104 | expect(made.ok).toBe(false); | |
| 105 | if (!made.ok) expect(made.error).toBe("unknown_org"); | |
| 106 | }); | |
| 107 | }); | |
| 108 | ||
| 109 | describe("an invite to an organization, edges", () => { | |
| 110 | let dir = ""; | |
| 111 | let app: App; | |
| 112 | let servers: Servers; | |
| 113 | let admin: User; | |
| 114 | let adminToken = ""; | |
| 115 | ||
| 116 | const signup = async (username: string, invite: string) => | |
| 117 | fetch(`${servers.url}/api/v1/users`, { | |
| 118 | method: "POST", | |
| 119 | headers: { "content-type": "application/json" }, | |
| 120 | body: JSON.stringify({ username, email: `${username}@f.dev`, password: PASSWORD, invite }), | |
| 121 | }); | |
| 122 | const tokenOf = (org: string) => { | |
| 123 | const made = mint(app, admin, undefined, org); | |
| 124 | if (!made.ok) throw new Error(made.error); | |
| 125 | return made.value.token; | |
| 126 | }; | |
| 127 | const orgWith = async (name: string, apps: { name: string; visibility: "public" | "private" }[]) => { | |
| 128 | const org = createOrg(app.db, name, admin.id); | |
| 129 | if (!org.ok) throw new Error(org.error); | |
| 130 | for (const a of apps) { | |
| 131 | const repo = await createRepo(app.db, app.reposRoot, { ownerId: org.value.id, name: a.name, visibility: a.visibility }); | |
| 132 | if (!repo.ok) throw new Error(repo.error); | |
| 133 | insertApp(app.db, { repoId: repo.value.id, slug: `${name}-${a.name}`, access: "public" }); | |
| 134 | } | |
| 135 | return org.value; | |
| 136 | }; | |
| 137 | const teamsOf = (userId: string) => | |
| 138 | app.db | |
| 139 | .query<{ name: string; permission: string }, [string]>( | |
| 140 | "SELECT t.name, t.permission FROM team t JOIN team_member m ON m.team_id = t.id WHERE m.user_id = ?1", | |
| 141 | ) | |
| 142 | .all(userId); | |
| 143 | ||
| 144 | beforeAll(async () => { | |
| 145 | dir = await mkdtemp(join(tmpdir(), "forge-invite-org-edges-")); | |
| 146 | app = createApp({ dataDir: dir, port: 0 }); | |
| 147 | servers = await serve(app); | |
| 148 | const made = await seedAdmin(app, { username: "olive", email: "[email protected]", password: PASSWORD }); | |
| 149 | if (!made.ok) throw new Error(made.error); | |
| 150 | admin = made.value; | |
| 151 | adminToken = createToken(app.db, admin.id, "t", "admin").token; | |
| 152 | setSignup(app.db, "invite", admin.id); | |
| 153 | setLimit(app.db, "signup.per_source", 1000, admin.id); | |
| 154 | }); | |
| 155 | afterAll(async () => { | |
| 156 | servers.stop(); | |
| 157 | app.close(); | |
| 158 | await rm(dir, { recursive: true, force: true }); | |
| 159 | }); | |
| 160 | ||
| 161 | test("an org with only an admin team gives the newcomer a read team, never the admin one", async () => { | |
| 162 | const org = await orgWith("adminonly", [{ name: "site", visibility: "public" }]); | |
| 163 | const team = createTeam(app.db, org.id, "Maintainers", "admin"); | |
| 164 | if (!team.ok) throw new Error(team.error); | |
| 165 | const res = await signup("rhea", tokenOf("adminonly")); | |
| 166 | expect(res.status).toBe(201); | |
| 167 | const rhea = getUserByName(app.db, "rhea")!; | |
| 168 | expect(teamsOf(rhea.id)).toEqual([{ name: "Members", permission: "read" }]); | |
| 169 | expect(orgAccess(app.db, org.id, rhea)).toBe("read"); | |
| 170 | }); | |
| 171 | ||
| 172 | test("an org with a write team and a read team joins the read one", async () => { | |
| 173 | const org = await orgWith("mixed", [{ name: "site", visibility: "public" }]); | |
| 174 | for (const [n, p] of [["Devs", "write"], ["Readers", "read"]] as const) createTeam(app.db, org.id, n, p); | |
| 175 | expect((await signup("sol", tokenOf("mixed"))).status).toBe(201); | |
| 176 | expect(teamsOf(getUserByName(app.db, "sol")!.id)).toEqual([{ name: "Readers", permission: "read" }]); | |
| 177 | }); | |
| 178 | ||
| 179 | test("a fork over the repository limit is skipped, named in the answer, and the signup stands", async () => { | |
| 180 | await orgWith("limited", [{ name: "one", visibility: "public" }, { name: "two", visibility: "public" }]); | |
| 181 | setQuota(app.db, "repositories", 1, admin.id); | |
| 182 | try { | |
| 183 | const res = await signup("tess", tokenOf("limited")); | |
| 184 | expect(res.status).toBe(201); | |
| 185 | const body = (await res.json()) as { welcome: { forks: { repo: string }[]; skipped: { from: string }[] } }; | |
| 186 | expect(body.welcome.forks.map((f) => f.repo)).toEqual(["tess/one"]); | |
| 187 | expect(body.welcome.skipped.map((s) => s.from)).toEqual(["limited/two"]); | |
| 188 | expect(getRepo(app.db, "tess", "two")).toBeUndefined(); | |
| 189 | } finally { | |
| 190 | setQuota(app.db, "repositories", null, admin.id); | |
| 191 | } | |
| 192 | }); | |
| 193 | ||
| 194 | test("a private app is forked private; a sealed repository is not forked", async () => { | |
| 195 | const org = await orgWith("closed", [{ name: "vault", visibility: "private" }]); | |
| 196 | const parent = getRepo(app.db, "closed", "vault")!; | |
| 197 | const sealed = await forkRepo(app.db, app.reposRoot, parent, org.id, "vault-sealed", { sealed: true }); | |
| 198 | if (!sealed.ok) throw new Error(sealed.error); | |
| 199 | insertApp(app.db, { repoId: sealed.value.id, slug: "closed-sealed", access: "public" }); | |
| 200 | const res = await signup("uma", tokenOf("closed")); | |
| 201 | const body = (await res.json()) as { welcome: { forks: { repo: string }[] } }; | |
| 202 | expect(body.welcome.forks.map((f) => f.repo)).toEqual(["uma/vault"]); | |
| 203 | expect(getRepo(app.db, "uma", "vault")!.visibility).toBe("private"); | |
| 204 | expect(getRepo(app.db, "uma", "vault-sealed")).toBeUndefined(); | |
| 205 | }); | |
| 206 | ||
| 207 | test("an account that waits is neither seated nor forked until it is allowed", async () => { | |
| 208 | const org = await orgWith("later", [{ name: "site", visibility: "public" }]); | |
| 209 | // An open invite vouches for its person, so a waiting account never comes by one at sign-up; | |
| 210 | // the account that waits here carries a spent org invite all the same. | |
| 211 | setSignup(app.db, "request", admin.id); | |
| 212 | const res = await fetch(`${servers.url}/api/v1/users`, { | |
| 213 | method: "POST", | |
| 214 | headers: { "content-type": "application/json" }, | |
| 215 | body: JSON.stringify({ username: "vera", email: "[email protected]", password: PASSWORD }), | |
| 216 | }); | |
| 217 | setSignup(app.db, "invite", admin.id); | |
| 218 | expect(res.status).toBe(202); | |
| 219 | const vera = getUserByName(app.db, "vera")!; | |
| 220 | const { invite } = (() => { | |
| 221 | const made = mint(app, admin, undefined, "later"); | |
| 222 | if (!made.ok) throw new Error(made.error); | |
| 223 | return made.value; | |
| 224 | })(); | |
| 225 | app.db.query("UPDATE invite SET used_by = ?1, used_at = ?2 WHERE id = ?3").run(vera.id, new Date().toISOString(), invite.id); | |
| 226 | expect(isOrgMember(app.db, org.id, vera.id)).toBe(false); | |
| 227 | expect(getRepo(app.db, "vera", "site")).toBeUndefined(); | |
| 228 | expect(allowRequest(app, admin, "vera").ok).toBe(true); | |
| 229 | for (let i = 0; i < 150 && getRepo(app.db, "vera", "site") === undefined; i++) await Bun.sleep(20); // real-timer: the welcome runs after the allow answers | |
| 230 | expect(isOrgMember(app.db, org.id, vera.id)).toBe(true); | |
| 231 | expect(getRepo(app.db, "vera", "site")).toBeDefined(); | |
| 232 | }); | |
| 233 | ||
| 234 | test("the API refuses an unknown or non-string organization and a non-admin", async () => { | |
| 235 | const post = (token: string, body: unknown) => | |
| 236 | fetch(`${servers.url}/api/v1/admin/invites`, { | |
| 237 | method: "POST", | |
| 238 | headers: { "content-type": "application/json", authorization: `Bearer ${token}` }, | |
| 239 | body: JSON.stringify(body), | |
| 240 | }); | |
| 241 | expect((await post(adminToken, { org: "nowhere" })).status).toBe(422); | |
| 242 | expect((await post(adminToken, { org: 7 })).status).toBe(422); | |
| 243 | expect((await post(adminToken, { org: { name: "acme" } })).status).toBe(422); | |
| 244 | const made = await post(adminToken, {}); | |
| 245 | expect(made.status).toBeLessThan(300); | |
| 246 | const bob = await createUser(app.db, { origin: "seed", username: "bob", email: "[email protected]", password: PASSWORD, trusted: true }); | |
| 247 | if (!bob.ok) throw new Error(bob.error); | |
| 248 | const plain = createToken(app.db, bob.value.id, "t", "admin").token; | |
| 249 | expect((await post(plain, { org: "mixed" })).status).toBeGreaterThanOrEqual(403); | |
| 250 | }); | |
| 251 | ||
| 252 | test("the MCP mint_invite refuses an unknown organization", async () => { | |
| 253 | const res = await fetch(`${servers.url}/mcp`, { | |
| 254 | method: "POST", | |
| 255 | headers: { "content-type": "application/json", accept: "application/json, text/event-stream", authorization: `Bearer ${adminToken}` }, | |
| 256 | body: JSON.stringify({ jsonrpc: "2.0", id: 1, method: "tools/call", params: { name: "mint_invite", arguments: { org: "nowhere" } } }), | |
| 257 | }); | |
| 258 | const text = JSON.stringify(await res.json()); | |
| 259 | expect(text).toContain("no such organization"); | |
| 260 | }); | |
| 261 | ||
| 262 | test("the admin page makes an invite for an organization, and says so when there is none", async () => { | |
| 263 | const cookie = `forge_session=${createSession(app.db, admin.id).token}`; | |
| 264 | const form = (org: string) => { | |
| 265 | const body = new URLSearchParams({ days: "7", org }); | |
| 266 | return fetch(`${servers.url}/admin/invites`, { | |
| 267 | method: "POST", | |
| 268 | headers: { cookie, "content-type": "application/x-www-form-urlencoded", origin: servers.url }, | |
| 269 | body, | |
| 270 | redirect: "manual", | |
| 271 | }); | |
| 272 | }; | |
| 273 | const before = listInvites(app, admin); | |
| 274 | const n = before.ok ? before.value.length : 0; | |
| 275 | expect((await form("nowhere")).status).toBe(303); | |
| 276 | expect((await form("mixed")).status).toBe(303); | |
| 277 | const after = listInvites(app, admin); | |
| 278 | expect(after.ok && after.value.length).toBe(n + 1); | |
| 279 | expect(after.ok && after.value.some((i) => i.org === "mixed")).toBe(true); | |
| 280 | }); | |
| 281 | }); | |
| 282 | ||
| 283 | describe("an invite to an organization, by passkey", () => { | |
| 284 | let dir = ""; | |
| 285 | let app: App; | |
| 286 | let servers: Servers; | |
| 287 | let admin: User; | |
| 288 | ||
| 289 | beforeAll(async () => { | |
| 290 | dir = await mkdtemp(join(tmpdir(), "forge-invite-org-passkey-")); | |
| 291 | app = createApp({ dataDir: dir, port: 0, passkeyOnlySignup: true }); | |
| 292 | servers = await serve(app); | |
| 293 | const made = await seedAdmin(app, { username: "olive", email: "[email protected]", password: "an-invited-passphrase" }); | |
| 294 | if (!made.ok) throw new Error(made.error); | |
| 295 | admin = made.value; | |
| 296 | setSignup(app.db, "invite", admin.id); | |
| 297 | setLimit(app.db, "signup.per_source", 1000, admin.id); | |
| 298 | const org = createOrg(app.db, "acme", admin.id); | |
| 299 | if (!org.ok) throw new Error(org.error); | |
| 300 | const repo = await createRepo(app.db, app.reposRoot, { ownerId: org.value.id, name: "site", visibility: "public" }); | |
| 301 | if (!repo.ok) throw new Error(repo.error); | |
| 302 | insertApp(app.db, { repoId: repo.value.id, slug: "acme-site", access: "public" }); | |
| 303 | }); | |
| 304 | afterAll(async () => { | |
| 305 | servers.stop(); | |
| 306 | app.close(); | |
| 307 | await rm(dir, { recursive: true, force: true }); | |
| 308 | }); | |
| 309 | ||
| 310 | test("a passkey sign-up with an org invite joins the org, forks its app and answers with the welcome", async () => { | |
| 311 | const made = mint(app, admin, undefined, "acme"); | |
| 312 | if (!made.ok) throw new Error(made.error); | |
| 313 | const origin = new URL(servers.url).origin; | |
| 314 | const d = await device(origin, new URL(servers.url).hostname); | |
| 315 | const post = (path: string, body: unknown) => | |
| 316 | fetch(`${servers.url}${path}?invite=${made.value.token}`, { | |
| 317 | method: "POST", | |
| 318 | headers: { "content-type": "application/json" }, | |
| 319 | body: JSON.stringify(body), | |
| 320 | }); | |
| 321 | const o = (await (await post("/signup/passkey/options", { username: "pia", email: "[email protected]", invite: made.value.token })).json()) as { challenge: string }; | |
| 322 | const res = await post("/signup/passkey", { | |
| 323 | username: "pia", | |
| 324 | email: "[email protected]", | |
| 325 | invite: made.value.token, | |
| 326 | challenge: o.challenge, | |
| 327 | ...(await d.create(o.challenge)), | |
| 328 | }); | |
| 329 | expect(res.status).toBe(201); | |
| 330 | const body = (await res.json()) as { welcome: { org: string; forks: { repo: string }[]; skipped: unknown[] } }; | |
| 331 | expect(body.welcome.org).toBe("acme"); | |
| 332 | expect(body.welcome.forks.map((f) => f.repo)).toEqual(["pia/site"]); | |
| 333 | expect(body.welcome.skipped).toEqual([]); | |
| 334 | expect(isOrgMember(app.db, getUserByName(app.db, "acme")!.id, getUserByName(app.db, "pia")!.id)).toBe(true); | |
| 335 | expect(getRepo(app.db, "pia", "site")!.visibility).toBe("private"); | |
| 336 | }); | |
| 337 | }); |
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([]); |
new above
offline