Public: anyone can read this; the crew can change it.
Opening an invite link signs the person in, proves the account and applies the bundle, in every sign-up mode including closed #18520
Merged 2h 19m ago, live in production
mason/forge:mason/18454-opening-an-invite-link-signs-the-person → main 0 commits fork
54 files
changed +603
−234
- docs/CREW.md
- docs/features/invite-bundle.md
- docs/features/invite-link.md
- src/actions/infra.ts
- src/actions/invite_link.ts
- src/actions/invites.ts
- src/actions/spend_words.ts
- src/actions/users.ts
- src/contract/openapi/routes/postApiV1AdminInvites.ts
- src/core/account_purge.ts
- src/core/bundle_grants.ts
- src/core/bundles.ts
- src/core/grants_view.ts
- src/core/invites.ts
- src/core/migration-pins/20261206110000-invite-link-in.pin
- src/core/migrations/20261206110000-invite-link-in.ts
- src/core/users.ts
- src/core/verify.ts
- src/crew/conversation_ask.ts
- src/http/api/admin.ts
- src/http/lazy_lists.ts
- src/http/mcp/tools/mint_invite.ts
- src/http/routes/accounts.ts
- src/tui/screens/invites.ts
- src/web/pages/admin-limits.ts
- src/web/pages/invite-link.ts
- src/web/pages/signup-passkey.ts
- src/web/pages/site.ts
- src/web/pages/start_claim.ts
- test/admin-lists-paged.test.ts
- test/conversation-ask.test.ts
- test/conversation-confirm.test.ts
- test/cookie-flags.test.ts
- test/first-week.test.ts
- test/grants-view.test.ts
- test/invite-bundles.test.ts
- test/invite-expiry-words.test.ts
- test/invite-link.test.ts
- test/invite-org.test.ts
- test/invite-redeem.test.ts
- test/invites-action.test.ts
- test/invites-core.test.ts
- test/invites.test.ts
- test/mcp-forge-admin.test.ts
- test/mcp-invites.test.ts
- test/org-person-forge.test.ts
- test/perimeter-mediums.test.ts
- test/request-access-limits.test.ts
- test/signup-gate-parent.test.ts
- test/spend-words.test.ts
- test/start.test.ts
- test/tui-invites.test.ts
- test/tui-signup-invite.test.ts
- test/who-can.test.ts
docs/CREW.md +1 −1
| @@ -347,7 +347,7 @@ one the provider rests hands its runs to the other until the reset. | ||
| 347 | 347 | **Crew subscriptions in the terminal.** A forge admin presses Ctrl+K and picks **Crew subscriptions**: each Claude account with its kind, what it pays for, budget, spend and whether it rests (never a token). `w` wakes the selected resting one (an awake one is left alone and said so), `b` asks for dollars, or `none`, and sets its whole-life budget. `a` adds an account: a name, then the token typed masked (drawn as dots, handed to the core once, never shown or logged), then an optional API base; a refusal is MCP `subscription_add`'s sentence, word for word. `D` shows that the subscription and its grants go and that past runs keep it in their history, and removes it only after a confirm that defaults to Cancel. Only a forge admin who is a person is offered either key; an agent sees neither and changes nothing. Granting an added account to a repository or organization stays on the web page and in MCP. The rules are MCP `subscriptions`, `subscription_wake` and `subscription_budget`'s, from `core/subscriptions.ts`; a budget set by whoever made the forge can be lowered, never raised or cleared. |
| 348 | 348 | **Where you are signed in.** Anyone signed in sees their own browsers and tokens, never a secret, at `/settings`, over the API (`GET /api/v1/users/:username/signins`), over MCP (`sessions`), and in the terminal as the **Signed in** command (`src/tui/screens/signins.ts`; a visitor has no such command). The terminal lists this terminal's SSH key first, marked "this one", then each browser (`web browser` and the tail of its session id, so two read apart) and each token (name and scope), with when it was last seen and since when. `d` on a browser asks to confirm (Keep is the default) and signs it out through the same `endAccountSession` as Settings and MCP, so its cookie reads as signed out at once. `d` on a token asks `Revoke <name> (<scope>)?` (Keep is the default) and revokes it through the same `deleteToken` action as Settings and the API, so it stops working at once and open pages hear `token.deleted`. `d` does not end this terminal (disconnect, or remove its key in Settings → SSH keys); it says so. No browser row is marked as the current one there: the terminal holds no browser cookie. |
| 349 | 349 | |
| 350 | **Invites.** A forge admin who is a person mints a single-use invite link with `POST /api/v1/admin/invites` (`{"days": 14}`, 1 to 30, 7 by default); the response carries the link once and only its hash is kept. `GET /api/v1/admin/invites` lists them (open, used, revoked, expired) without tokens, and `DELETE /api/v1/admin/invites/:id` revokes one. Minting, revoking and using a link are events (`invite.minted`, `invite.revoked`, `invite.used`; the last names the invite and the account it let in, never the token). The same is the **Invite links** card on `/admin/limits` (a form with expiry days, 1 to 30; the new link is shown once, with a copy button; an open link has a Revoke button) and the terminal's **Invite links** command (`m` makes one and prints the link once, `x` revokes the selected open one; its top line says who may sign up, and `s`, offered only to that admin, picks open, invite or closed, shows from → to and changes it after a confirm, as MCP `signup` does). Over MCP, the `mint_invite` tool (`{days?}`, an admin token, a forge admin who is a person) answers with the same link, and the `invites` tool (`{action: "list"|"revoke", id?}`, the same person admin and admin token, for both actions) lists them without links or revokes one. While signup is `invite`, the link opens the door once: `/signup?invite=…` (the form and the passkey door) or `invite` in the `POST /api/v1/users` body. In the terminal, with signup = invite the create-account screen has a fourth, masked **Invite** field that takes the token (not the whole link); a blank one is asked for, and a bad one is refused with the same sentence as `/signup`. The account and the invite's use are one write, so two sign-ups with one link make one account; a used, revoked or expired link, or any link while signup is `closed`, makes none. While signup is `open`, a link is not spent. | |
| 350 | **Invites.** A forge admin who is a person mints a single-use invite link with `POST /api/v1/admin/invites` (every link lives 72 hours; `{"org"?, "bundle"?, …}`); the response carries the link once and only its hash is kept. `GET /api/v1/admin/invites` lists them (open, used, revoked, expired) without tokens, and `DELETE /api/v1/admin/invites/:id` revokes one. Minting, revoking and using a link are events (`invite.minted`, `invite.revoked`, `invite.used`; the last names the invite and the account it let in, never the token). The same is the **Invite links** card on `/admin/limits` (a form; the new link is shown once, with a copy button; an open link has a Revoke button) and the terminal's **Invite links** command (`m` picks the bundle, makes one and prints the link once, `x` revokes the selected open one; its top line says who may sign up, and `s`, offered only to that admin, picks open, invite or closed, shows from → to and changes it after a confirm, as MCP `signup` does). Over MCP, the `mint_invite` tool (`{org?, bundle?, …}`, an admin token, a forge admin who is a person) answers with the same link, and the `invites` tool (`{action: "list"|"revoke", id?}`, the same person admin and admin token, for both actions) lists them without links or revokes one. The link opens the door once in every signup mode, `closed` included: `/signup?invite=…` shows one button (Join) that makes the account, signs the person in, proves it with the invite as the proof and applies the bundle (`docs/features/invite-link.md`); `invite` in the `POST /api/v1/users` body and the passkey door spend it too. In the terminal, with signup = invite the create-account screen has a fourth, masked **Invite** field that takes the token (not the whole link); a blank one is asked for, and a bad one is refused with the same sentence as `/signup`. The account and the invite's use are one write, so two sign-ups with one link make one account; a used, revoked or expired link makes none. | |
| 351 | 351 | |
| 352 | 352 | **Bulk actions in the terminal.** A person (never an agent) presses Ctrl+K and picks **Bulk actions** (`src/tui/screens/bulk.ts`): their own last 30 bulk actions, newest first, as `GET /api/v1/fleet/ops` lists them, each with its action, how many rows changed, how many were refused, whether `u` still undoes it, and when. `j`/`k` move; `u` undoes the selected one while it is inside its day, through `undoFleetOp` (`undoAsksBulk` for a bulk action on asks), and toasts the outcome; an undone, expired or non-reversible receipt, or an undo itself, says why and changes nothing. Enter opens the operation's rows: each row's before → after, and each refusal's reason. Another person's operations are never listed. An agent is not offered the screen and, reached another way, sees "Not available". |
| 353 | 353 |
docs/features/invite-bundle.md +1 −1
| @@ -9,4 +9,4 @@ Mint an invite with a bundle: `POST /api/v1/admin/invites {"bundle":"host","mach | ||
| 9 | 9 | - **Host**: a guest who makes and runs their own containers on one machine, up to a cap. The machine is one of those the forge offers (running, not a game box); with none, Host is disabled and the page says why. |
| 10 | 10 | - **Build**: a member: repositories, apps and a crew. |
| 11 | 11 | |
| 12 | An unknown bundle, a machine not on the list or a cap that is not a positive whole number is refused (422). The bundle is stored with the invite and listed with its line; invites made before read as Use. The grants each stands for are in `src/core/bundles.ts`; applying them is a later step. In the terminal, `m` on Invite links asks for the days, then the bundle; Host goes on to the machine, then the two caps, and says the same refusals. | |
| 12 | An unknown bundle, a machine not on the list or a cap that is not a positive whole number is refused (422). The bundle is stored with the invite and listed with its line; invites made before read as Use. The grants each stands for are in `src/core/bundles.ts`; they are applied when the invite is spent (`docs/features/invite-link.md`). In the terminal, `m` on Invite links picks the bundle; Host goes on to the machine, then the two caps, and says the same refusals. |
docs/features/invite-link.md added +15
| @@ -0,0 +1,15 @@ | ||
| 1 | --- | |
| 2 | topic: Hosting forges for others, and getting paid | |
| 3 | row: An invite link signs its person in | |
| 4 | --- | |
| 5 | # An invite link signs its person in | |
| 6 | ||
| 7 | Open `/signup?invite=<token>` and the page says who invited you, what the link allows (Use, Host or Build) and until when, with one button, Join. Pressing it makes the account, signs you in (a session in an HttpOnly cookie), marks the account proven with the invite as the proof (who vouched and how are kept on its email connection; no mail is sent) and applies the bundle, all in the transaction that spends the invite. It works whatever the signup setting is, `closed` included: a live invite is the one way in; no invite opens a closed forge. Opening the page spends nothing, so a link preview never burns it. | |
| 8 | ||
| 9 | A link is good for one person, hashed at rest, for 72 hours (there is no longer life to choose), and can be revoked. A used, expired or revoked link answers one plain page and grants nothing. A Host invite whose machine has since gone grants nothing and says so; the invite stays open. A new person is called `friend-` and six letters; they add a passkey from their account. | |
| 10 | ||
| 11 | Try it: as an admin mint an invite (`POST /api/v1/admin/invites {"bundle":"build"}`, the MCP `mint_invite`, or Invite links at /admin/limits), open its link in a private window and press Join. | |
| 12 | ||
| 13 | The terminal (both doors): `m` on Invite links picks the bundle and makes the link (`src/tui/screens/invites.ts`); the Create account form in `src/tui/screens/signin.ts` takes the pasted token and spends it the same way, applying the same bundle. | |
| 14 | ||
| 15 | Pinned by `test/invite-link.test.ts`, `test/invites-core.test.ts` and `test/tui-signup-invite.test.ts`; the page is `src/web/pages/invite-link.ts`. |
src/actions/infra.ts +6
| @@ -200,6 +200,12 @@ export function infraOf(app: App, actor: User | undefined, now = new Date()): Re | ||
| 200 | 200 | return who.ok ? ok(reckon(app, now).view) : who; |
| 201 | 201 | } |
| 202 | 202 | |
| 203 | /** | |
| 204 | * The view with no one asking: for a check the forge makes itself (a Host invite's machine), never | |
| 205 | * shown. | |
| 206 | */ | |
| 207 | export const offeredView = (app: App, now = new Date()): InfraView => reckon(app, now).view; | |
| 208 | ||
| 203 | 209 | /** |
| 204 | 210 | * One machine by name, running, ended or a dead row, with its billing sentence: `infra show`'s |
| 205 | 211 | * answer to "does test1 still cost anything?" when it is asked by name. Undefined when no row of |
src/actions/invite_link.ts added +56
| @@ -0,0 +1,56 @@ | ||
| 1 | /** | |
| 2 | * One link and nothing else (#18454): opening an invite link, and pressing its one button, makes | |
| 3 | * the account, signs the person in, proves the account with the invite as the proof and applies the | |
| 4 | * invite's bundle, in the transaction that spends it (`createUser`, origin `invite`). It holds in | |
| 5 | * every signup mode: a live invite is the credential, a dead one opens nothing. A person is named | |
| 6 | * `friend-` and six letters until they choose another name. | |
| 7 | */ | |
| 8 | ||
| 9 | import type { App } from "../app.ts"; | |
| 10 | import { inviteByToken } from "../core/invites.ts"; | |
| 11 | import { createUser, type User } from "../core/users.ts"; | |
| 12 | import { err, ok, type Result } from "../kernel/result.ts"; | |
| 13 | import { machinesOffered } from "./invites.ts"; | |
| 14 | import { auditInvite, noEmail } from "./users.ts"; | |
| 15 | import { welcomeInvited } from "./invite_welcome.ts"; | |
| 16 | ||
| 17 | export type InviteLinkError = "spent" | "expired" | "host_gone"; | |
| 18 | ||
| 19 | const LETTERS = "abcdefghjkmnpqrstuvwxyz23456789"; | |
| 20 | const NAME_TRIES = 8; | |
| 21 | ||
| 22 | const friendName = (): string => | |
| 23 | `friend-${Array.from(crypto.getRandomValues(new Uint8Array(6)), (b) => LETTERS[b % LETTERS.length]).join("")}`; | |
| 24 | ||
| 25 | /** How an invite token stands: its state, and who made it. A token that names none is `spent`. */ | |
| 26 | export function inviteLinkState(app: App, token: string): { state: "open" | "spent" | "expired"; from: string | undefined } { | |
| 27 | const known = inviteByToken(app.db, token); | |
| 28 | if (known === undefined) return { state: "spent", from: undefined }; | |
| 29 | const state = known.invite.state === "open" ? "open" : known.invite.state === "expired" ? "expired" : "spent"; | |
| 30 | return { state, from: known.from }; | |
| 31 | } | |
| 32 | ||
| 33 | /** Spend the link `token` on a new account, signed in by the caller with the user returned. */ | |
| 34 | export async function takeInviteLink(app: App, token: string): Promise<Result<User, InviteLinkError>> { | |
| 35 | const standing = inviteLinkState(app, token); | |
| 36 | if (standing.state !== "open") return err(standing.state); | |
| 37 | for (let i = 0; i < NAME_TRIES; i++) { | |
| 38 | const username = friendName(); | |
| 39 | const made = await createUser(app.db, { | |
| 40 | username, | |
| 41 | email: noEmail(username), | |
| 42 | origin: "invite", | |
| 43 | invite: token, | |
| 44 | offeredMachines: machinesOffered(app), | |
| 45 | }); | |
| 46 | if (made.ok) { | |
| 47 | app.bus.append({ kind: "user.created", actorId: made.value.id, payload: { via: "invite_link" } }); | |
| 48 | auditInvite(app, made.value.id); | |
| 49 | await welcomeInvited(app, made.value); | |
| 50 | return ok(made.value); | |
| 51 | } | |
| 52 | if (made.error === "host_gone") return err("host_gone"); | |
| 53 | if (made.error !== "username_taken" && made.error !== "email_taken") return err("spent"); | |
| 54 | } | |
| 55 | return err("spent"); | |
| 56 | } |
src/actions/invites.ts +14 −12
| @@ -12,8 +12,6 @@ import { | ||
| 12 | 12 | listInvites, |
| 13 | 13 | mintInvite, |
| 14 | 14 | mintRepoInvite, |
| 15 | MAX_DAYS, | |
| 16 | parseDays, | |
| 17 | 15 | redeemInvite, |
| 18 | 16 | takeUpInvite, |
| 19 | 17 | removeContributor, |
| @@ -29,11 +27,11 @@ import { getUserByName } from "../core/users.ts"; | ||
| 29 | 27 | import { requireRepoAdmin, type AccessError } from "./access.ts"; |
| 30 | 28 | import { getOrg } from "../core/orgs.ts"; |
| 31 | 29 | import { BUNDLES, HOST_WORDS, parseHost, type Bundle } from "../core/bundles.ts"; |
| 32 | import { infraOf } from "./infra.ts"; | |
| 30 | import { infraOf, offeredView, type InfraView } from "./infra.ts"; | |
| 33 | 31 | import { err, ok, type Result } from "../kernel/result.ts"; |
| 34 | 32 | import type { User } from "../core/users.ts"; |
| 35 | 33 | |
| 36 | type Error = "not_found" | "invalid_days" | "unknown_org" | "invalid_bundle" | "no_machine" | "invalid_machine" | "invalid_cap"; | |
| 34 | type Error = "not_found" | "unknown_org" | "invalid_bundle" | "no_machine" | "invalid_machine" | "invalid_cap"; | |
| 37 | 35 | |
| 38 | 36 | /** What Host is given, as a door sends it: plain values, read by `parseHost`. */ |
| 39 | 37 | export interface BundleInput { |
| @@ -54,8 +52,6 @@ export const BUNDLE_WORDS: Record<"invalid_bundle" | "no_machine" | "invalid_mac | ||
| 54 | 52 | /** A refusal of `mint` in words: every door says the same. */ |
| 55 | 53 | export function mintRefusal(error: Error): string { |
| 56 | 54 | switch (error) { |
| 57 | case "invalid_days": | |
| 58 | return `Days is a whole number from 1 to ${MAX_DAYS}.`; | |
| 59 | 55 | case "unknown_org": |
| 60 | 56 | return "No organization by that name."; |
| 61 | 57 | case "not_found": |
| @@ -68,10 +64,18 @@ export function mintRefusal(error: Error): string { | ||
| 68 | 64 | /** The machines this forge can offer a Host: those running, by name; admin's to read. */ |
| 69 | 65 | export function hostMachines(app: App, actor: User | undefined): string[] { |
| 70 | 66 | const v = infraOf(app, actor); |
| 71 | if (!v.ok) return []; | |
| 72 | return v.value.groups.flatMap((g) => g.machines).filter((m) => m.state === "online" && m.game !== true).map((m) => m.name); | |
| 67 | return v.ok ? machinesIn(v.value) : []; | |
| 73 | 68 | } |
| 74 | 69 | |
| 70 | const machinesIn = (view: InfraView): string[] => | |
| 71 | view.groups.flatMap((g) => g.machines).filter((m) => m.state === "online" && m.game !== true).map((m) => m.name); | |
| 72 | ||
| 73 | /** | |
| 74 | * The same list with no one asking: for the check a redeemed Host invite makes, which reads, never | |
| 75 | * shows. | |
| 76 | */ | |
| 77 | export const machinesOffered = (app: App): string[] => machinesIn(offeredView(app)); | |
| 78 | ||
| 75 | 79 | const admin = (actor: User | undefined): actor is User => |
| 76 | 80 | actor !== undefined && actor.isAdmin && actor.kind === "user"; |
| 77 | 81 | |
| @@ -83,10 +87,8 @@ export const inviteLink = (origin: string, token: string): string => | ||
| 83 | 87 | * `org` names the organization the invite brings its person into; absent or empty is a plain |
| 84 | 88 | * invite. |
| 85 | 89 | */ |
| 86 | export function mint(app: App, actor: User | undefined, days: unknown, org?: unknown, choice: BundleInput = {}): Result<{ invite: Invite; token: string }, Error> { | |
| 90 | export function mint(app: App, actor: User | undefined, org?: unknown, choice: BundleInput = {}): Result<{ invite: Invite; token: string }, Error> { | |
| 87 | 91 | if (!admin(actor)) return err("not_found"); |
| 88 | const n = parseDays(days); | |
| 89 | if (!n.ok) return n; | |
| 90 | 92 | const name = typeof org === "string" ? org.trim() : ""; |
| 91 | 93 | if (org !== undefined && org !== null && typeof org !== "string") return err("unknown_org"); |
| 92 | 94 | const target = name === "" ? undefined : getOrg(app.db, name); |
| @@ -100,7 +102,7 @@ export function mint(app: App, actor: User | undefined, days: unknown, org?: unk | ||
| 100 | 102 | if (!h.ok) return err(h.error === "noMachine" ? "no_machine" : h.error === "badMachine" ? "invalid_machine" : "invalid_cap"); |
| 101 | 103 | host = h.value; |
| 102 | 104 | } |
| 103 | const made = mintInvite(app.db, actor.id, n.value, Date.now(), target?.id ?? null, bundle, host); | |
| 105 | const made = mintInvite(app.db, actor.id, Date.now(), target?.id ?? null, bundle, host); | |
| 104 | 106 | app.bus.append({ |
| 105 | 107 | kind: "invite.minted", |
| 106 | 108 | actorId: actor.id, |
src/actions/spend_words.ts −1
src/actions/users.ts +4 −1
| @@ -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 { machinesOffered } from "./invites.ts"; | |
| 30 | 31 | import { welcomeInvited } from "./invite_welcome.ts"; |
| 31 | 32 | import { cleanAsk, NOTE_MAX, SOURCE_MAX } from "../core/requests.ts"; |
| 32 | 33 | import { |
| @@ -176,6 +177,7 @@ export async function signUp( | ||
| 176 | 177 | origin: "signup", |
| 177 | 178 | slot: from.slot, |
| 178 | 179 | invite: from.invite, |
| 180 | ...(from.invite === undefined ? {} : { offeredMachines: machinesOffered(app) }), | |
| 179 | 181 | ask: { note: cleanAsk(input.note, NOTE_MAX), source: cleanAsk(input.source, SOURCE_MAX) }, |
| 180 | 182 | }); |
| 181 | 183 | if (!created.ok) return created; |
| @@ -237,6 +239,7 @@ export async function signUpWithPasskey( | ||
| 237 | 239 | origin: "passkey", |
| 238 | 240 | slot: from.slot, |
| 239 | 241 | invite: from.invite, |
| 242 | ...(from.invite === undefined ? {} : { offeredMachines: machinesOffered(app) }), | |
| 240 | 243 | ask: { note: cleanAsk(input.note, NOTE_MAX), source: cleanAsk(input.source, SOURCE_MAX) }, |
| 241 | 244 | }); |
| 242 | 245 | if (!created.ok) return created; |
| @@ -264,7 +267,7 @@ export async function signUpWithPasskey( | ||
| 264 | 267 | } |
| 265 | 268 | |
| 266 | 269 | /** Using an invite link is an event: the invite's id and who it let in, never its token. */ |
| 267 | function auditInvite(app: App, userId: string): void { | |
| 270 | export function auditInvite(app: App, userId: string): void { | |
| 268 | 271 | const inviteId = inviteSpentBy(app.db, userId); |
| 269 | 272 | if (inviteId === undefined) return; |
| 270 | 273 | app.bus.append({ kind: "invite.used", actorId: userId, payload: { id: inviteId } }); |
src/contract/openapi/routes/postApiV1AdminInvites.ts +2 −2
| @@ -10,7 +10,7 @@ export const route: Route = { | ||
| 10 | 10 | auth: true, |
| 11 | 11 | role: "admin", |
| 12 | 12 | status: 201, |
| 13 | body: { days: "integer" }, | |
| 14 | refusals: { invalid: "`days` is not a whole number from 1 to 30 (422)" }, | |
| 13 | body: { bundle: "string" }, | |
| 14 | refusals: { invalid: "the organization or the bundle is not one this forge offers (422)" }, | |
| 15 | 15 | refuses: [404], |
| 16 | 16 | }; |
src/core/account_purge.ts +3
| @@ -56,6 +56,9 @@ export const COVERED: Readonly<Record<string, Coverage>> = { | ||
| 56 | 56 | // A saved /traces search is private to the person who named it; it goes with them. |
| 57 | 57 | "trace_saved.user_id": DELETE, |
| 58 | 58 | "access_link.created_by": FORMER, |
| 59 | // Who vouched for an email address (the admin whose invite link proved it): the proof stays, as | |
| 60 | // the former account. | |
| 61 | "connection.proof_by": FORMER, | |
| 59 | 62 | // The admin who made an integration's lookup key: the key stays, as the former account's. |
| 60 | 63 | "connection_lookup_key.created_by": FORMER, |
| 61 | 64 | // Who asked a game box to run a command: the record keeps it, as the former account. |
src/core/bundle_grants.ts added +41
| @@ -0,0 +1,41 @@ | ||
| 1 | /** | |
| 2 | * What an invite's bundle gives the person it lets in (`core/bundles.ts` says what each bundle is). | |
| 3 | * Applied in the transaction that spends the invite and makes the account, so a person is never in | |
| 4 | * without their grants nor granted without being in. Use is a guest, which every new account | |
| 5 | * already is. Build makes a member, by the invite's maker. Host keeps one `host_grant` row: the | |
| 6 | * machine and caps picked at mint. A Host invite whose machine this forge no longer offers grants | |
| 7 | * nothing (`hostGone`, asked before anything is written). | |
| 8 | */ | |
| 9 | ||
| 10 | import type { Database } from "bun:sqlite"; | |
| 11 | import { inviteByToken } from "./invites.ts"; | |
| 12 | import { setMember } from "./roles.ts"; | |
| 13 | ||
| 14 | /** Whether the invite `token` names is a Host invite for a machine not among those offered now. */ | |
| 15 | export function hostGone(db: Database, token: string, offered: readonly string[] | undefined): boolean { | |
| 16 | const host = inviteByToken(db, token)?.invite.host ?? null; | |
| 17 | return host !== null && !(offered ?? []).includes(host.machine); | |
| 18 | } | |
| 19 | ||
| 20 | /** After `redeemInvite` and the account's insert, in their transaction: the bundle's grants. */ | |
| 21 | export function applyBundle(db: Database, token: string, userId: string, now: number = Date.now()): void { | |
| 22 | const named = inviteByToken(db, token, now); | |
| 23 | if (named === undefined) return; | |
| 24 | const { invite } = named; | |
| 25 | const at = new Date(now); | |
| 26 | if (invite.bundle === "build") setMember(db, userId, true, invite.createdBy, at); | |
| 27 | if (invite.bundle === "host" && invite.host !== null) | |
| 28 | db.query( | |
| 29 | "INSERT OR REPLACE INTO host_grant (user_id, machine, containers, memory_mb, invite_id, at) VALUES (?1, ?2, ?3, ?4, ?5, ?6)", | |
| 30 | ).run(userId, invite.host.machine, invite.host.containers, invite.host.memoryMb, invite.id, at.toISOString()); | |
| 31 | } | |
| 32 | ||
| 33 | /** The machine and caps a Host invite gave this person, or undefined when it gave none. */ | |
| 34 | export function hostGrantOf(db: Database, userId: string): { machine: string; containers: number; memoryMb: number } | undefined { | |
| 35 | const row = db | |
| 36 | .query<{ machine: string; containers: number; memory_mb: number }, [string]>( | |
| 37 | "SELECT machine, containers, memory_mb FROM host_grant WHERE user_id = ?1", | |
| 38 | ) | |
| 39 | .get(userId); | |
| 40 | return row === null ? undefined : { machine: row.machine, containers: row.containers, memoryMb: row.memory_mb }; | |
| 41 | } |
src/core/bundles.ts +1
| @@ -55,6 +55,7 @@ export interface HostChoice { | ||
| 55 | 55 | export const HOST_WORDS = { |
| 56 | 56 | noMachine: "Host needs a machine this forge can offer, and it has none: connect a cloud account and build one first.", |
| 57 | 57 | badMachine: "That machine is not one this forge offers.", |
| 58 | gone: "The machine this invite was for is no longer offered, so it grants nothing. Ask whoever sent it for a new one.", | |
| 58 | 59 | badCap: "Containers and memory are each a positive whole number.", |
| 59 | 60 | } as const; |
| 60 | 61 |
src/core/grants_view.ts +1
| @@ -85,6 +85,7 @@ const MAPPINGS: readonly Mapping[] = [ | ||
| 85 | 85 | { table: "team_member", principalKind: text("user"), principalId: "user_id", action: "role", resourceKind: text("team"), resourceId: "team_id", account: "user_id", who: OR(NAME("user_id"), "user_id"), on: OR(TEAM(`${NAME("t.org_id")} || '/' || t.name`), "team_id"), href: OR(TEAM(`'/' || ${NAME("t.org_id")} || '/-/teams/' || t.id`), text("/settings")) }, |
| 86 | 86 | { table: "app_member", principalKind: text("user"), principalId: "user_id", action: text("enter"), resourceKind: text("app"), resourceId: "app_id", by: "added_by", at: "added_at", account: "user_id", who: OR(NAME("user_id"), "user_id"), on: OR(APP("app_id"), "app_id"), href: OR(`'/' || ${APP("app_id")} || '/settings'`, text("/settings")) }, |
| 87 | 87 | { table: "game_grant", principalKind: text("user"), principalId: "user_id", action: "role", resourceKind: text("game box"), resourceId: "box_id || CASE WHEN service = '' THEN '' ELSE '/' || service END", account: "user_id", who: OR(NAME("user_id"), "user_id"), on: `COALESCE((SELECT name FROM game_box WHERE id = box_id), box_id) || CASE WHEN service = '' THEN '' ELSE '/' || service END`, href: text("/games") }, |
| 88 | { table: "host_grant", principalKind: text("user"), principalId: "user_id", action: "'host up to ' || containers || ' containers, ' || memory_mb || ' MB'", resourceKind: text("machine"), resourceId: "machine", at: "at", account: "user_id", who: OR(NAME("user_id"), "user_id"), on: "machine", href: text("/settings/people") }, | |
| 88 | 89 | { table: "model_grant", principalKind: text("user"), principalId: "user_id", action: "'use models, $' || printf('%g', usd_per_month) || ' a month'", resourceKind: text("forge"), resourceId: "''", by: "granted_by", at: "granted_at", account: "user_id", who: OR(NAME("user_id"), "user_id"), on: text("the forge''s models"), href: text("/settings/people") }, |
| 89 | 90 | { table: "subscription_grant", principalKind: "CASE WHEN agent_id = '' THEN 'scope' ELSE 'agent' END", principalId: "CASE WHEN agent_id = '' THEN scope_id ELSE agent_id END", action: text("spend"), resourceKind: text("subscription"), resourceId: "subscription_id", account: "NULLIF(agent_id, '')", who: `CASE WHEN agent_id = '' THEN COALESCE(${REPO("scope_id")}, '@' || ${NAME("scope_id")}, 'a place that is gone') ELSE COALESCE(${NAME("agent_id")}, agent_id) END`, on: OR("(SELECT name FROM subscription WHERE id = subscription_id)", "subscription_id"), href: text("/settings/subscriptions") }, |
| 90 | 91 | { table: "secret_grant", principalKind: text("repo"), principalId: "repo_id", action: text("read secret"), resourceKind: "scope || ' secret'", resourceId: "CASE WHEN scope_id = '' THEN name ELSE scope_id || '/' || name END", by: "granted_by", at: "granted_at", who: OR(REPO("repo_id"), "repo_id"), on: "name", href: text("/settings/secrets") }, |
src/core/invites.ts +13 −16
| @@ -2,9 +2,10 @@ | ||
| 2 | 2 | * Invite links: a secret handed out once, good for one signup, gone after a |
| 3 | 3 | * deadline. The database holds only the token's hash, so a list can never |
| 4 | 4 | * give a link back, and a token is found by its hash: nothing compares the |
| 5 | * secret itself. While signup is `invite`, a stranger's signup with an open | |
| 6 | * invite is let in (`newAccountsClosed` in `core/users.ts`), and the invite is | |
| 7 | * spent in the same transaction as the account (`redeemInvite`). | |
| 5 | * secret itself. In every signup mode, `invite` and `closed` included, a | |
| 6 | * stranger with an open invite is let in (`newAccountsClosed` in | |
| 7 | * `core/users.ts`), and the invite is spent in the same transaction as the | |
| 8 | * account (`redeemInvite`), which also applies its bundle (`core/bundle_grants.ts`). | |
| 8 | 9 | */ |
| 9 | 10 | |
| 10 | 11 | import type { Database } from "bun:sqlite"; |
| @@ -13,9 +14,12 @@ import { id, secret } from "../kernel/id.ts"; | ||
| 13 | 14 | import { err, ok, type Result } from "../kernel/result.ts"; |
| 14 | 15 | import { bundleOf, type Bundle, type HostChoice } from "./bundles.ts"; |
| 15 | 16 | |
| 16 | export const DEFAULT_DAYS = 7; | |
| 17 | export const MAX_DAYS = 30; | |
| 18 | const DAY = 86_400_000; | |
| 17 | /** | |
| 18 | * How long an invite link lives: 72 hours, the one life every link has. Nothing offers a longer | |
| 19 | * one. | |
| 20 | */ | |
| 21 | export const INVITE_HOURS = 72; | |
| 22 | const LIFE_MS = INVITE_HOURS * 3_600_000; | |
| 19 | 23 | |
| 20 | 24 | export type InviteState = "open" | "used" | "revoked" | "expired"; |
| 21 | 25 | |
| @@ -79,17 +83,10 @@ const view = (r: Row, now: number): Invite => ({ | ||
| 79 | 83 | : { machine: r.host_machine, containers: r.host_containers, memoryMb: r.host_memory_mb }, |
| 80 | 84 | }); |
| 81 | 85 | |
| 82 | /** A whole number of days from 1 to 30, or the default when absent. */ | |
| 83 | export function parseDays(raw: unknown): Result<number, "invalid_days"> { | |
| 84 | if (raw === undefined || raw === null) return ok(DEFAULT_DAYS); | |
| 85 | return typeof raw === "number" && Number.isInteger(raw) && raw >= 1 && raw <= MAX_DAYS ? ok(raw) : err("invalid_days"); | |
| 86 | } | |
| 87 | ||
| 88 | 86 | /** The token is returned here and nowhere else. */ |
| 89 | 87 | export function mintInvite( |
| 90 | 88 | db: Database, |
| 91 | 89 | createdBy: string, |
| 92 | days: number = DEFAULT_DAYS, | |
| 93 | 90 | now: number = Date.now(), |
| 94 | 91 | /** The id of the organization the invite brings its person into. */ |
| 95 | 92 | orgId: string | null = null, |
| @@ -105,7 +102,7 @@ export function mintInvite( | ||
| 105 | 102 | sha256(token), |
| 106 | 103 | createdBy, |
| 107 | 104 | new Date(now).toISOString(), |
| 108 | new Date(now + days * DAY).toISOString(), | |
| 105 | new Date(now + LIFE_MS).toISOString(), | |
| 109 | 106 | orgId, |
| 110 | 107 | bundle, |
| 111 | 108 | host?.machine ?? null, |
| @@ -216,7 +213,7 @@ const repoView = (r: Row, now: number): RepoInvite => { | ||
| 216 | 213 | }; |
| 217 | 214 | |
| 218 | 215 | /** |
| 219 | * A single-use link to work on one repository as a contributor, `DEFAULT_DAYS` days, the token's | |
| 216 | * A single-use link to work on one repository as a contributor, 72 hours, the token's | |
| 220 | 217 | * hash alone kept. Where the forge asks for an invite to sign up, it opens that door for its |
| 221 | 218 | * holder too. The token is returned here and nowhere else. |
| 222 | 219 | */ |
| @@ -230,7 +227,7 @@ export function mintRepoInvite( | ||
| 230 | 227 | const inviteId = id(now); |
| 231 | 228 | db.query( |
| 232 | 229 | "INSERT INTO invite (id, token_hash, created_by, created_at, expires_at, repo_id) VALUES (?1, ?2, ?3, ?4, ?5, ?6)", |
| 233 | ).run(inviteId, sha256(token), createdBy, new Date(now).toISOString(), new Date(now + DEFAULT_DAYS * DAY).toISOString(), repoId); | |
| 230 | ).run(inviteId, sha256(token), createdBy, new Date(now).toISOString(), new Date(now + LIFE_MS).toISOString(), repoId); | |
| 234 | 231 | const row = db.query<Row, [string]>(`${SELECT} WHERE invite.id = ?1`).get(inviteId)!; |
| 235 | 232 | return { invite: repoView(row, now), token }; |
| 236 | 233 | } |
src/core/migration-pins/20261206110000-invite-link-in.pin added +1
| @@ -0,0 +1,1 @@ | ||
| 1 | 7483ead1454665baeef3bb3f9e7870fe9501beead24d896c884681221d7044f4 |
src/core/migrations/20261206110000-invite-link-in.ts added +16
| @@ -0,0 +1,16 @@ | ||
| 1 | // Opening an invite link signs its person in (#18454). The proof an invite gives is recorded on the | |
| 2 | // email connection it proves: who vouched (the invite's maker) and how ('invite'; null for a link | |
| 3 | // followed). A Host invite's grant is a row of its own: the machine and caps picked at mint, and | |
| 4 | // the invite that gave them. Additive. | |
| 5 | export default ` | |
| 6 | ALTER TABLE connection ADD COLUMN proof_by TEXT; | |
| 7 | ALTER TABLE connection ADD COLUMN proof_how TEXT; | |
| 8 | CREATE TABLE host_grant ( | |
| 9 | user_id TEXT PRIMARY KEY REFERENCES user(id) ON DELETE CASCADE, | |
| 10 | machine TEXT NOT NULL, | |
| 11 | containers INTEGER NOT NULL, | |
| 12 | memory_mb INTEGER NOT NULL, | |
| 13 | invite_id TEXT NOT NULL, | |
| 14 | at TEXT NOT NULL | |
| 15 | ) WITHOUT ROWID; | |
| 16 | `; |
src/core/users.ts +39 −6
| @@ -13,7 +13,8 @@ import { err, ok, type Result } from "../kernel/result.ts"; | ||
| 13 | 13 | import { admitSignin } from "./signin-window.ts"; |
| 14 | 14 | import { waitingCount, WAITING_CAP } from "./requests.ts"; |
| 15 | 15 | import { getSignup, type SignupMode } from "../settings/signup.ts"; |
| 16 | import { inviteOpen, redeemInvite, reopenInvite, takeUpInvite } from "./invites.ts"; | |
| 16 | import { applyBundle, hostGone } from "./bundle_grants.ts"; | |
| 17 | import { inviteByToken, inviteOpen, redeemInvite, reopenInvite, takeUpInvite } from "./invites.ts"; | |
| 17 | 18 | import type { SignupSlot } from "../actions/signup-window.ts"; |
| 18 | 19 | |
| 19 | 20 | export interface User { |
| @@ -116,7 +117,12 @@ export type CreateUserError = | ||
| 116 | 117 | | "email_taken" |
| 117 | 118 | | "weak_password" |
| 118 | 119 | | "password_too_long" |
| 119 | | "signup_closed"; | |
| 120 | | "signup_closed" | |
| 121 | /** | |
| 122 | * A Host invite whose machine this forge no longer offers: nothing is granted, the invite stays | |
| 123 | * open. | |
| 124 | */ | |
| 125 | | "host_gone"; | |
| 120 | 126 | |
| 121 | 127 | /** |
| 122 | 128 | * Where a new account comes from — said by every caller, because this is the |
| @@ -160,6 +166,10 @@ export type AccountOrigin = | ||
| 160 | 166 | ask?: { note: string; source: string } | undefined; |
| 161 | 167 | } |
| 162 | 168 | | { origin: "edge" } |
| 169 | /** | |
| 170 | * The one-link sign-in: the invite's token is the whole credential (`actions/invite_link.ts`). | |
| 171 | */ | |
| 172 | | { origin: "invite"; invite: string } | |
| 163 | 173 | | { origin: Exclude<ExemptOrigin, AdminOrigin> } |
| 164 | 174 | | ({ origin: AdminOrigin } & AdminFields); |
| 165 | 175 | |
| @@ -200,9 +210,9 @@ function inviteNeeded(db: Database): boolean { | ||
| 200 | 210 | export function accountsClosedIn(db: Database, mode: SignupMode, invite?: string): boolean { |
| 201 | 211 | // In `request` the door shuts once the Waiting list is full, for anyone an open invite does not vouch for. |
| 202 | 212 | if (mode === "request") return waitingCount(db) >= WAITING_CAP && !(invite !== undefined && inviteOpen(db, invite)); |
| 203 | // Open lets anyone in; invite and closed need an invite, and only invite takes one. | |
| 213 | // Open lets anyone in; invite and closed need an invite, and a live one opens either. | |
| 204 | 214 | if (mode !== "invite" && mode !== "closed") return false; |
| 205 | return !(mode === "invite" && invite !== undefined && inviteOpen(db, invite)); | |
| 215 | return !(invite !== undefined && inviteOpen(db, invite)); | |
| 206 | 216 | } |
| 207 | 217 | |
| 208 | 218 | interface CreateUserFields { |
| @@ -244,6 +254,11 @@ interface CreateUserFields { | ||
| 244 | 254 | * Every other protected name still does. |
| 245 | 255 | */ |
| 246 | 256 | reservedSelf?: string; |
| 257 | /** | |
| 258 | * The machines this forge offers a Host now, for an invite that names one: a Host invite whose | |
| 259 | * machine is not among them grants nothing (`host_gone`). Absent, none is offered. | |
| 260 | */ | |
| 261 | offeredMachines?: readonly string[]; | |
| 247 | 262 | } |
| 248 | 263 | |
| 249 | 264 | /** |
| @@ -280,10 +295,17 @@ function admission(db: Database, input: AccountOrigin): Admission { | ||
| 280 | 295 | return { admitted: true, spend: input.invite, request: "none" }; |
| 281 | 296 | return waitingCount(db) >= WAITING_CAP ? REFUSED : { admitted: true, spend: undefined, request: "waiting" }; |
| 282 | 297 | } |
| 283 | if (!inviteNeeded(db)) return ADMITTED; | |
| 298 | // Open, a live invite is still spent: its bundle is what the person came for. | |
| 299 | if (!inviteNeeded(db)) | |
| 300 | return input.invite !== undefined && inviteOpen(db, input.invite) | |
| 301 | ? { admitted: true, spend: input.invite, request: "none" } | |
| 302 | : ADMITTED; | |
| 284 | 303 | return newAccountsClosed(db, input.invite) || input.invite === undefined |
| 285 | 304 | ? REFUSED |
| 286 | 305 | : { admitted: true, spend: input.invite, request: "none" }; |
| 306 | case "invite": | |
| 307 | // The invite link itself: a live one opens the door in every mode, a dead one in none. | |
| 308 | return inviteOpen(db, input.invite) ? { admitted: true, spend: input.invite, request: "none" } : REFUSED; | |
| 287 | 309 | case "edge": |
| 288 | 310 | return newAccountsClosed(db) ? REFUSED : ADMITTED; |
| 289 | 311 | case "claim": |
| @@ -321,6 +343,7 @@ export async function createUser( | ||
| 321 | 343 | ): Promise<Result<User, CreateUserError>> { |
| 322 | 344 | const admitted = admission(db, input); |
| 323 | 345 | if (!admitted.admitted) return err("signup_closed"); |
| 346 | if (admitted.spend !== undefined && hostGone(db, admitted.spend, input.offeredMachines)) return err("host_gone"); | |
| 324 | 347 | const admin = adminOf(input); |
| 325 | 348 | if (!isSafeName(input.username)) return err("invalid_username"); |
| 326 | 349 | const agent = input.agent === true; |
| @@ -385,7 +408,15 @@ export async function createUser( | ||
| 385 | 408 | admin.adminIfFirst ? 1 : 0, |
| 386 | 409 | agent ? 1 : 0, |
| 387 | 410 | ); |
| 388 | if (invite !== undefined) takeUpInvite(db, invite, userId); | |
| 411 | if (invite !== undefined) { | |
| 412 | takeUpInvite(db, invite, userId); | |
| 413 | applyBundle(db, invite, userId); | |
| 414 | // The one link is its own proof: the invite's maker vouched, and no mail is sent. | |
| 415 | if (input.origin === "invite") { | |
| 416 | const by = inviteByToken(db, invite)?.invite.createdBy ?? userId; | |
| 417 | markVerified(db, userId, new Date().toISOString(), { by, how: "invite" }); | |
| 418 | } | |
| 419 | } | |
| 389 | 420 | // A stranger's account keeps its ask, in the same write, waiting until allowed. |
| 390 | 421 | if (admitted.request === "waiting") { |
| 391 | 422 | const at = new Date().toISOString(); |
| @@ -411,6 +442,8 @@ export async function createUser( | ||
| 411 | 442 | } |
| 412 | 443 | // Every person gets a row: proven when the caller vouches, else not yet. |
| 413 | 444 | if (!agent) { |
| 445 | // The one link proved itself in the transaction above. | |
| 446 | if (input.origin === "invite") return ok(getUserById(db, userId)!); | |
| 414 | 447 | if (input.trusted === true) markVerified(db, userId, new Date().toISOString()); |
| 415 | 448 | else markUnproven(db, userId); |
| 416 | 449 | } |
src/core/verify.ts +12 −4
| @@ -48,7 +48,13 @@ export function markUnproven(db: Database, userId: string): void { | ||
| 48 | 48 | * proof by the account that holds the address outranks an older one another |
| 49 | 49 | * account kept as an extra connection, which is unproven. |
| 50 | 50 | */ |
| 51 | export function markVerified(db: Database, userId: string, at: string): void { | |
| 51 | export function markVerified( | |
| 52 | db: Database, | |
| 53 | userId: string, | |
| 54 | at: string, | |
| 55 | /** Who vouched and how, when it was not a link followed: an invite's maker, `invite`. */ | |
| 56 | proof?: { readonly by: string; readonly how: "invite" }, | |
| 57 | ): void { | |
| 52 | 58 | db.transaction(() => { |
| 53 | 59 | db.query( |
| 54 | 60 | `INSERT INTO email_check (user_id) VALUES (?1) |
| @@ -60,12 +66,14 @@ export function markVerified(db: Database, userId: string, at: string): void { | ||
| 60 | 66 | AND ident = (SELECT lower(email) FROM user WHERE id = ?1)`, |
| 61 | 67 | ).run(userId); |
| 62 | 68 | db.query( |
| 63 | `INSERT INTO connection (id, user_id, kind, ident, proven_at, created_at) | |
| 64 | SELECT ?2, id, 'email', lower(email), ?3, ?3 FROM user WHERE id = ?1 | |
| 69 | `INSERT INTO connection (id, user_id, kind, ident, proven_at, created_at, proof_by, proof_how) | |
| 70 | SELECT ?2, id, 'email', lower(email), ?3, ?3, ?4, ?5 FROM user WHERE id = ?1 | |
| 65 | 71 | ON CONFLICT(user_id, kind, ident) DO UPDATE SET |
| 72 | proof_by = CASE WHEN connection.proven_at IS NULL THEN excluded.proof_by ELSE connection.proof_by END, | |
| 73 | proof_how = CASE WHEN connection.proven_at IS NULL THEN excluded.proof_how ELSE connection.proof_how END, | |
| 66 | 74 | proven_at = COALESCE(connection.proven_at, excluded.proven_at), |
| 67 | 75 | code_hash = NULL, expires_at = NULL, tries = 0`, |
| 68 | ).run(userId, newId(), at); | |
| 76 | ).run(userId, newId(), at, proof?.by ?? null, proof?.how ?? null); | |
| 69 | 77 | })(); |
| 70 | 78 | } |
| 71 | 79 |
src/crew/conversation_ask.ts +1 −1
| @@ -294,7 +294,7 @@ export const ASKED_AS: Readonly<Record<string, Form>> = { | ||
| 294 | 294 | a["verb"] === "revoke" |
| 295 | 295 | ? `Revoke the child forge credential ${val(a, "id")}` |
| 296 | 296 | : `Make a propose-only credential for the child forge ${val(a, "child")}`, |
| 297 | mint_invite: (a) => `Make a single-use invite link, good for ${val(a, "days") || "7"} days`, | |
| 297 | mint_invite: (a) => "Make a single-use invite link, good for 72 hours", | |
| 298 | 298 | claim_link: (a) => |
| 299 | 299 | a["action"] === "revoke" |
| 300 | 300 | ? `End the claim link of ${val(a, "name")}` |
src/http/api/admin.ts +1 −2
| @@ -569,10 +569,9 @@ export function adminRoutes(router: Router<Handler>): void { | ||
| 569 | 569 | const denied = accountAdmin(ctx, "admin"); |
| 570 | 570 | if (denied) return denied; |
| 571 | 571 | const input = await body(ctx.request); |
| 572 | const made = mintInviteLink(ctx.app, ctx.auth.user, input.days, input.org, input); | |
| 572 | const made = mintInviteLink(ctx.app, ctx.auth.user, input.org, input); | |
| 573 | 573 | if (!made.ok) { |
| 574 | 574 | if (made.error === "not_found") return notFound(); |
| 575 | if (made.error === "invalid_days") return apiError("invalid", 422, SPEND_WORDS.inviteDays); | |
| 576 | 575 | return apiError("invalid", 422, made.error === "unknown_org" ? "no such organization" : mintRefusal(made.error)); |
| 577 | 576 | } |
| 578 | 577 | const origin = ctx.app.config.url ?? ctx.url.origin; |
src/http/lazy_lists.ts +1
| @@ -321,6 +321,7 @@ export const ACCOUNTS_ROUTES = [ | ||
| 321 | 321 | ["GET", "/signin/parent"], |
| 322 | 322 | ["GET", "/signin/parent/callback"], |
| 323 | 323 | ["GET", "/signup"], |
| 324 | ["POST", "/signup/invite"], | |
| 324 | 325 | ["GET", "/signin/access/:token"], |
| 325 | 326 | ["POST", "/signin/access/:token"], |
| 326 | 327 | ["GET", "/claim/start/:token"], |
src/http/mcp/tools/mint_invite.ts +4 −10
| @@ -1,4 +1,3 @@ | ||
| 1 | import { SPEND_WORDS } from "../../../actions/spend_words.ts"; | |
| 2 | 1 | import { inviteLink, mintRefusal, mint as mintInviteLink } from "../../../actions/invites.ts"; |
| 3 | 2 | import { scopeAllows } from "../../../core/tokens.ts"; |
| 4 | 3 | import { good, bad, type Tool, mayBoards } from "../shared.ts"; |
| @@ -6,13 +5,12 @@ import { good, bad, type Tool, mayBoards } from "../shared.ts"; | ||
| 6 | 5 | export const tool: Tool = { |
| 7 | 6 | name: "mint_invite", |
| 8 | 7 | listedTo: "admin", |
| 9 | doc: "`{ days?, org?, bundle?, machine?, containers?, memoryMb? }`: mint a single-use invite link that expires in `days` (1–30, default 7) and is shown once; with `org` the person joins that organization and gets private forks of its apps; `bundle` is use (default), host (with a `machine` of those the forge offers and positive `containers` and `memoryMb` caps) or build; a person admin's, with an admin token", | |
| 8 | doc: "`{ org?, bundle?, machine?, containers?, memoryMb? }`: mint a single-use invite link that expires in 72 hours and is shown once; with `org` the person joins that organization and gets private forks of its apps; `bundle` is use (default), host (with a `machine` of those the forge offers and positive `containers` and `memoryMb` caps) or build; a person admin's, with an admin token", | |
| 10 | 9 | description: |
| 11 | "Mint a one-use invite link, shown once, valid `days` (1–30, default 7). Person admins.", | |
| 10 | "Mint a one-use invite link, shown once, valid 72 hours. Person admins.", | |
| 12 | 11 | inputSchema: { |
| 13 | 12 | type: "object", |
| 14 | 13 | properties: { |
| 15 | days: { type: "integer", minimum: 1, maximum: 30 }, | |
| 16 | 14 | org: { type: "string", description: "Organization the person joins" }, |
| 17 | 15 | bundle: { type: "string", enum: ["use", "host", "build"] }, |
| 18 | 16 | machine: { type: "string", description: "Host: a machine the forge offers" }, |
| @@ -25,15 +23,11 @@ export const tool: Tool = { | ||
| 25 | 23 | if (!mayBoards(user)) return bad("forbidden", "an invite is a forge admin's to mint"); |
| 26 | 24 | if (!scopeAllows(ctx.auth.scope ?? "ro", "admin")) |
| 27 | 25 | return bad("forbidden", "an invite needs an admin token"); |
| 28 | const made = mintInviteLink(ctx.app, user, args["days"], args["org"], args); | |
| 26 | const made = mintInviteLink(ctx.app, user, args["org"], args); | |
| 29 | 27 | if (!made.ok) |
| 30 | 28 | return bad( |
| 31 | 29 | "invalid", |
| 32 | made.error === "invalid_days" | |
| 33 | ? SPEND_WORDS.inviteDays | |
| 34 | : made.error === "unknown_org" | |
| 35 | ? "no such organization" | |
| 36 | : mintRefusal(made.error), | |
| 30 | made.error === "unknown_org" ? "no such organization" : mintRefusal(made.error), | |
| 37 | 31 | ); |
| 38 | 32 | const origin = ctx.app.config.url ?? ctx.url.origin; |
| 39 | 33 | return good({ ...made.value.invite, link: inviteLink(origin, made.value.token) }); |
src/http/routes/accounts.ts +3 −1
| @@ -6,6 +6,7 @@ | ||
| 6 | 6 | import { claimFragmentPage, claimSubmit, claimOptions, claimRenew, welcomePage, welcomeSubmit } from "../../web/pages/claim.ts"; |
| 7 | 7 | import { firstAdminPage, firstAdminSubmit, firstAdminOptions } from "../../web/pages/first-admin.ts"; |
| 8 | 8 | import { accessPage, accessSubmit, signinOptions, signinPasskey, recoverPage, recoverRequest, recoverOptions, recoverFinish } from "../../web/pages/passkeys.ts"; |
| 9 | import { inviteLinkPage, inviteLinkSubmit } from "../../web/pages/invite-link.ts"; | |
| 9 | 10 | import { signinPage, signinSubmit, safeNext, signupPage, requestedPage, joinPage, joinSubmit, verifyPage, signupSubmit, logoutSubmit, themeSubmit } from "../../web/pages/site.ts"; |
| 10 | 11 | import { startClaimPage, startClaimSubmit, startClaimAccountSubmit } from "../../web/pages/start_claim.ts"; |
| 11 | 12 | import { type Ctx } from "../context.ts"; |
| @@ -41,7 +42,8 @@ export function accountsRoutes(router: Router<Handler>): void { | ||
| 41 | 42 | router.add("GET", "/sign-in", signinAlias); |
| 42 | 43 | router.add("GET", "/signin/parent", parentStart); |
| 43 | 44 | router.add("GET", "/signin/parent/callback", parentCallback); |
| 44 | router.add("GET", "/signup", signupPage); | |
| 45 | router.add("GET", "/signup", (ctx) => inviteLinkPage(ctx) ?? signupPage(ctx)); | |
| 46 | router.add("POST", "/signup/invite", inviteLinkSubmit); | |
| 45 | 47 | router.add("GET", "/signin/access/:token", accessPage); |
| 46 | 48 | router.add("POST", "/signin/access/:token", accessSubmit); |
| 47 | 49 | router.add("GET", "/claim/start/:token", startClaimPage); |
src/tui/screens/invites.ts +10 −23
| @@ -17,7 +17,7 @@ import { INVITE_NOT_OPEN } from "../../actions/sever_invite_words.ts"; | ||
| 17 | 17 | import { changeAgentStart, changeSignup, readAgentStart, readSignup } from "../../actions/signup.ts"; |
| 18 | 18 | import { AGENT_START_MODES, type AgentStartMode } from "../../settings/agent_start.ts"; |
| 19 | 19 | import { SIGNUP_MODES, type SignupMode } from "../../settings/signup.ts"; |
| 20 | import { DEFAULT_DAYS, MAX_DAYS, parseDays, type Invite } from "../../core/invites.ts"; | |
| 20 | import { type Invite } from "../../core/invites.ts"; | |
| 21 | 21 | import type { Ctx, Screen } from "../app/app.ts"; |
| 22 | 22 | import { binding } from "../app/keys.ts"; |
| 23 | 23 | import { style } from "../term/style.ts"; |
| @@ -40,13 +40,8 @@ export function invitesScreen(f: Session, ctx: Ctx): Screen { | ||
| 40 | 40 | return r.ok ? r.value : []; |
| 41 | 41 | }; |
| 42 | 42 | |
| 43 | const daysOf = (raw: string): number => { | |
| 44 | const text = raw.trim(); | |
| 45 | return text === "" ? DEFAULT_DAYS : /^\d{1,3}$/.test(text) ? Number(text) : -1; | |
| 46 | }; | |
| 47 | ||
| 48 | const make = (raw: string, org = "", choice: BundleInput = {}): string | undefined => { | |
| 49 | const made = mint(f.app, f.user, daysOf(raw), org, choice); | |
| 43 | const make = (org = "", choice: BundleInput = {}): string | undefined => { | |
| 44 | const made = mint(f.app, f.user, org, choice); | |
| 50 | 45 | if (!made.ok) return mintRefusal(made.error); |
| 51 | 46 | const origin = f.app.config.url ?? `http://localhost:${f.app.config.port}`; |
| 52 | 47 | note = `Shown once: ${inviteLink(origin, made.value.token)}`; |
| @@ -55,16 +50,16 @@ export function invitesScreen(f: Session, ctx: Ctx): Screen { | ||
| 55 | 50 | }; |
| 56 | 51 | |
| 57 | 52 | /** |
| 58 | * After the days: pick the bundle; Host goes on to its machine and two caps, each refused in the | |
| 53 | * Pick the bundle; Host goes on to its machine and two caps, each refused in the | |
| 59 | 54 | * words the page uses. |
| 60 | 55 | */ |
| 61 | const pickBundle = (days: string): Screen => | |
| 56 | const pickBundle = (): Screen => | |
| 62 | 57 | pickerScreen(ctx, screen, { |
| 63 | 58 | title: "What the invite allows", |
| 64 | 59 | items: BUNDLES.map((b) => ({ id: b, label: BUNDLE[b].label, hint: BUNDLE[b].says })), |
| 65 | 60 | onPick: ([b]) => { |
| 66 | 61 | if (b !== "host") { |
| 67 | const refused = make(days, "", { bundle: b }); | |
| 62 | const refused = make("", { bundle: b }); | |
| 68 | 63 | if (refused !== undefined) note = refused; |
| 69 | 64 | return; |
| 70 | 65 | } |
| @@ -90,7 +85,7 @@ export function invitesScreen(f: Session, ctx: Ctx): Screen { | ||
| 90 | 85 | label: "most memory in MB, a positive whole number", |
| 91 | 86 | value: "2048", |
| 92 | 87 | onSubmit: (memoryMb) => { |
| 93 | const refused = make(days, "", { bundle: "host", machine, containers, memoryMb }); | |
| 88 | const refused = make("", { bundle: "host", machine, containers, memoryMb }); | |
| 94 | 89 | if (refused !== undefined) return refused; |
| 95 | 90 | return undefined; |
| 96 | 91 | }, |
| @@ -179,7 +174,7 @@ export function invitesScreen(f: Session, ctx: Ctx): Screen { | ||
| 179 | 174 | ? "Invite links are made by a forge admin." |
| 180 | 175 | : r.value.length === 0 |
| 181 | 176 | ? "No invite link yet. m makes one." |
| 182 | : "Each link is good for one signup. m makes one, x revokes."; | |
| 177 | : "Each link is good for one signup, for 72 hours. m makes one, x revokes."; | |
| 183 | 178 | s.text(head!.x, head!.y, truncate(text, head!.w), style(c.mutedFg, c.bg), head!.x + head!.w); |
| 184 | 179 | drawList(s, body!, c, state, rows()); |
| 185 | 180 | }, |
| @@ -189,15 +184,7 @@ export function invitesScreen(f: Session, ctx: Ctx): Screen { | ||
| 189 | 184 | if (state.key(e, all.length)) return true; |
| 190 | 185 | if (e.ctrl || e.alt || !read().ok) return false; |
| 191 | 186 | if (e.key === "m") { |
| 192 | ctx.push( | |
| 193 | promptScreen(ctx, screen, { | |
| 194 | title: "Invite link", | |
| 195 | label: `days until it expires, 1 to ${MAX_DAYS}`, | |
| 196 | value: String(DEFAULT_DAYS), | |
| 197 | onSubmit: (days) => | |
| 198 | !parseDays(daysOf(days)).ok ? mintRefusal("invalid_days") : later(ctx, () => pickBundle(days)), | |
| 199 | }), | |
| 200 | ); | |
| 187 | ctx.push(pickBundle()); | |
| 201 | 188 | } else if (e.key === "o") { |
| 202 | 189 | ctx.push( |
| 203 | 190 | promptScreen(ctx, screen, { |
| @@ -207,7 +194,7 @@ export function invitesScreen(f: Session, ctx: Ctx): Screen { | ||
| 207 | 194 | onSubmit: (org) => |
| 208 | 195 | org.trim() === "" |
| 209 | 196 | ? "Name an organization." |
| 210 | : make(String(DEFAULT_DAYS), org), | |
| 197 | : make(org), | |
| 211 | 198 | }), |
| 212 | 199 | ); |
| 213 | 200 | } else if (e.key === "x") { |
src/web/pages/admin-limits.ts +4 −20
| @@ -11,10 +11,9 @@ import { worstCaseOf } from "../../spawn/included_credit.ts"; | ||
| 11 | 11 | import { QUOTA_INVALID } from "../../actions/admin_limits_words.ts"; |
| 12 | 12 | import { birthsWords, changeLimit, listLimits } from "../../actions/limits.ts"; |
| 13 | 13 | import { changeQuotas, readQuotas } from "../../actions/quotas.ts"; |
| 14 | import { BUNDLE_WORDS, hostMachines, inviteLink, list as listInviteLinks, mint as mintInviteLink, revoke as revokeInviteLink } from "../../actions/invites.ts"; | |
| 14 | import { BUNDLE_WORDS, hostMachines, inviteLink, mintRefusal, list as listInviteLinks, mint as mintInviteLink, revoke as revokeInviteLink } from "../../actions/invites.ts"; | |
| 15 | 15 | import { BUNDLE, BUNDLES } from "../../core/bundles.ts"; |
| 16 | 16 | import { INVITE_NOT_OPEN } from "../../actions/sever_invite_words.ts"; |
| 17 | import { DEFAULT_DAYS, MAX_DAYS } from "../../core/invites.ts"; | |
| 18 | 17 | import { changeAgentStart, changeBillingLinks, changeSignup, readAgentStart, readBillingLinks, readSignup } from "../../actions/signup.ts"; |
| 19 | 18 | import { BILLING_SIZES } from "../../settings/billing.ts"; |
| 20 | 19 | import { AGENT_START_MODES } from "../../settings/agent_start.ts"; |
| @@ -220,23 +219,13 @@ export function limitsPage(ctx: Ctx): Response { | ||
| 220 | 219 | <dt>Invite links</dt> |
| 221 | 220 | <dd> |
| 222 | 221 | <form class="row-fields" method="post" action="/admin/invites"> |
| 223 | <label class="small">expires in (days) | |
| 224 | <input | |
| 225 | class="input mono" | |
| 226 | type="number" | |
| 227 | name="days" | |
| 228 | min="1" | |
| 229 | max="${String(MAX_DAYS)}" | |
| 230 | step="1" | |
| 231 | value="${String(DEFAULT_DAYS)}" | |
| 232 | /></label> | |
| 233 | 222 | <label class="small">organization (optional) |
| 234 | 223 | <input class="input mono" type="text" name="org" maxlength="60" autocomplete="off" /></label> |
| 235 | 224 | ${bundleField} |
| 236 | 225 | ${hostFields} |
| 237 | 226 | ${btn("Make a link", { size: "sm", variant: "primary", label: "Make an invite link" })} |
| 238 | 227 | </form> |
| 239 | <span class="muted small">Shown once, when it is made; good for one signup. With an organization, the person joins it and gets private forks of its apps.</span> | |
| 228 | <span class="muted small">Shown once, when it is made; good for one signup, for 72 hours. It signs its person in on its own. With an organization, the person joins it and gets private forks of its apps.</span> | |
| 240 | 229 | </dd> |
| 241 | 230 | <dd class="status-act"></dd> |
| 242 | 231 | </div>`; |
| @@ -397,8 +386,7 @@ export async function inviteMint(ctx: Ctx): Promise<Response> { | ||
| 397 | 386 | return notFoundPage(ctx); |
| 398 | 387 | const form = await readForm(ctx, "admin"); |
| 399 | 388 | if (form instanceof Response) return form; |
| 400 | const raw = field(form, "days").trim(); | |
| 401 | const made = mintInviteLink(ctx.app, ctx.auth.user, /^\d{1,3}$/.test(raw) ? Number(raw) : -1, field(form, "org"), { | |
| 389 | const made = mintInviteLink(ctx.app, ctx.auth.user, field(form, "org"), { | |
| 402 | 390 | bundle: field(form, "bundle"), |
| 403 | 391 | machine: field(form, "machine"), |
| 404 | 392 | containers: field(form, "containers"), |
| @@ -409,11 +397,7 @@ export async function inviteMint(ctx: Ctx): Promise<Response> { | ||
| 409 | 397 | return flashTo(ctx, "/admin/limits", { tone: "danger", message: "No organization by that name." }); |
| 410 | 398 | if (!made.ok && made.error in BUNDLE_WORDS) |
| 411 | 399 | return flashTo(ctx, "/admin/limits", { tone: "danger", message: BUNDLE_WORDS[made.error as keyof typeof BUNDLE_WORDS] }); |
| 412 | if (!made.ok) | |
| 413 | return flashTo(ctx, "/admin/limits", { | |
| 414 | tone: "danger", | |
| 415 | message: `Days is a whole number from 1 to ${MAX_DAYS}.`, | |
| 416 | }); | |
| 400 | if (!made.ok) return flashTo(ctx, "/admin/limits", { tone: "danger", message: mintRefusal(made.error) }); | |
| 417 | 401 | return flashTo(ctx, "/admin/limits", { |
| 418 | 402 | message: "Invite link made. It is shown only now:", |
| 419 | 403 | code: inviteLink(ctx.app.config.url ?? ctx.url.origin, made.value.token), |
src/web/pages/invite-link.ts added +106
| @@ -0,0 +1,106 @@ | ||
| 1 | /** | |
| 2 | * An invite link is the whole credential (#18454): `/signup?invite=…` says who invited the person | |
| 3 | * and what the link allows, with one button; the press makes the account, signs them in and applies | |
| 4 | * the bundle (`actions/invite_link.ts`). Opening the page spends nothing, so a link preview or a | |
| 5 | * crawler never burns it. A used, expired or revoked link answers one plain page, whatever the | |
| 6 | * forge's signup mode. | |
| 7 | */ | |
| 8 | ||
| 9 | import { inviteExpiredLine, inviteExpiryLine, INVITE_SPENT } from "../../actions/invites.ts"; | |
| 10 | import { inviteLinkState, takeInviteLink } from "../../actions/invite_link.ts"; | |
| 11 | import { welcomeWords, inviteWelcome } from "../../actions/invite_welcome.ts"; | |
| 12 | import { rotateSession } from "../../auth/session_rotate.ts"; | |
| 13 | import { hostGrantOf } from "../../core/bundle_grants.ts"; | |
| 14 | import { BUNDLE, HOST_WORDS } from "../../core/bundles.ts"; | |
| 15 | import { inviteByToken } from "../../core/invites.ts"; | |
| 16 | import { whenWords } from "../../core/when_words.ts"; | |
| 17 | import { cookieValue, type Ctx } from "../../http/context.ts"; | |
| 18 | import { STRANGER_MAX } from "../../http/limits.ts"; | |
| 19 | import { notePhase, takeSessionTime, timePhase } from "../../core/route_timing.ts"; | |
| 20 | import { pageHead } from "../chrome.ts"; | |
| 21 | import { readForm } from "../form.ts"; | |
| 22 | import { html } from "../html.ts"; | |
| 23 | import { page, redirect } from "../layout.ts"; | |
| 24 | import { btn } from "../ui.ts"; | |
| 25 | import { inviteOf, signupSlot, sessionCookie } from "./site.ts"; | |
| 26 | ||
| 27 | /** The one plain page a link that opens nothing answers with. */ | |
| 28 | function deadPage(ctx: Ctx, said: string, status = 410) { | |
| 29 | return page( | |
| 30 | { | |
| 31 | ctx, | |
| 32 | title: "This invite opens nothing", | |
| 33 | body: html`<div class="narrow stack" id="invite-dead"> | |
| 34 | ${pageHead("This invite opens nothing")} | |
| 35 | <p>${said}</p> | |
| 36 | </div>`, | |
| 37 | }, | |
| 38 | status, | |
| 39 | ); | |
| 40 | } | |
| 41 | ||
| 42 | /** | |
| 43 | * GET /signup?invite=…; undefined when the address carries no invite, for the plain sign-up page. | |
| 44 | */ | |
| 45 | export function inviteLinkPage(ctx: Ctx): Response | undefined { | |
| 46 | const token = inviteOf(ctx); | |
| 47 | if (token === undefined) return undefined; | |
| 48 | return openLink(ctx, token); | |
| 49 | } | |
| 50 | ||
| 51 | function openLink(ctx: Ctx, token: string): Response { | |
| 52 | notePhase(ctx.request, "session", takeSessionTime(ctx.request)); | |
| 53 | const standing = timePhase(ctx.request, "invite", () => inviteLinkState(ctx.app, token)); | |
| 54 | return timePhase(ctx.request, "render", () => { | |
| 55 | if (standing.state === "expired") return deadPage(ctx, inviteExpiredLine(standing.from)); | |
| 56 | if (standing.state !== "open") return deadPage(ctx, INVITE_SPENT); | |
| 57 | const known = inviteByToken(ctx.app.db, token)!; | |
| 58 | const bundle = BUNDLE[known.invite.bundle]; | |
| 59 | const who = standing.from ?? "Someone who runs this forge"; | |
| 60 | return page({ | |
| 61 | ctx, | |
| 62 | title: "You are invited", | |
| 63 | body: html`<div class="narrow stack" id="invite-open"> | |
| 64 | ${pageHead("You are invited")} | |
| 65 | <p>${who} invited you to this forge, as <strong>${bundle.label}</strong>. ${bundle.says}</p> | |
| 66 | <p class="muted small mb" id="invite-expiry">${inviteExpiryLine(whenWords(known.invite.expiresAt))}</p> | |
| 67 | ${ctx.auth.user === undefined | |
| 68 | ? html`<form method="post" action="/signup/invite?invite=${encodeURIComponent(token)}" class="form-actions">${btn("Join", { variant: "primary" })}</form>` | |
| 69 | : html`<p>You are signed in as ${ctx.auth.user.username} already. Sign out to use this link.</p>`} | |
| 70 | </div>`, | |
| 71 | }); | |
| 72 | }); | |
| 73 | } | |
| 74 | ||
| 75 | /** For a Host invite: the machine and caps the person was given, as one sentence. */ | |
| 76 | function hostLine(ctx: Ctx, userId: string): string { | |
| 77 | const host = hostGrantOf(ctx.app.db, userId); | |
| 78 | return host === undefined ? "" : ` You may run up to ${host.containers} containers and ${host.memoryMb} MB on ${host.machine}.`; | |
| 79 | } | |
| 80 | ||
| 81 | /** POST /signup/invite?invite=… — the press: the account, the session, the bundle. */ | |
| 82 | export async function inviteLinkSubmit(ctx: Ctx): Promise<Response> { | |
| 83 | const form = await readForm(ctx, undefined, STRANGER_MAX); | |
| 84 | if (form instanceof Response) return form; | |
| 85 | const token = ctx.url.searchParams.get("invite") ?? ""; | |
| 86 | if (ctx.auth.user !== undefined) return redirect("/"); | |
| 87 | const slot = signupSlot(ctx); | |
| 88 | if (typeof slot === "number") { | |
| 89 | const response = deadPage(ctx, `Too many sign-ups from here; try again in ${slot === 1 ? "a second" : `${slot} seconds`}.`, 429); | |
| 90 | response.headers.set("retry-after", String(slot)); | |
| 91 | return response; | |
| 92 | } | |
| 93 | const made = await takeInviteLink(ctx.app, token); | |
| 94 | if (!made.ok) { | |
| 95 | if (made.error === "host_gone") return deadPage(ctx, HOST_WORDS.gone); | |
| 96 | return openLink(ctx, token); | |
| 97 | } | |
| 98 | const session = rotateSession(ctx.app.db, cookieValue(ctx.request, "forge_session"), made.value.id); | |
| 99 | const welcome = inviteWelcome(ctx.app, made.value); | |
| 100 | return redirect("/", { | |
| 101 | cookie: sessionCookie(session.token, session.expiresAt, ctx.url, ctx.app.config.url), | |
| 102 | flash: { message: `${welcome === undefined ? "You're in." : welcomeWords(welcome)}${hostLine(ctx, made.value.id)}` }, | |
| 103 | url: ctx.url, | |
| 104 | forgeUrl: ctx.app.config.url, | |
| 105 | }); | |
| 106 | } |
src/web/pages/signup-passkey.ts +2
| @@ -8,6 +8,7 @@ | ||
| 8 | 8 | |
| 9 | 9 | import { inviteWelcome } from "../../actions/invite_welcome.ts"; |
| 10 | 10 | import { newChallenge, verifyRegistration } from "../../auth/webauthn.ts"; |
| 11 | import { HOST_WORDS } from "../../core/bundles.ts"; | |
| 11 | 12 | import { givenEmail, invalidEmailMessage, signUpWithPasskey, signupClosed, HUMAN_CHECK_MESSAGE, SIGNUP_CLOSED_MESSAGE } from "../../actions/users.ts"; |
| 12 | 13 | import { rotateSession } from "../../auth/session_rotate.ts"; |
| 13 | 14 | import { getUserByName } from "../../core/users.ts"; |
| @@ -35,6 +36,7 @@ const WORDS: Record<string, string> = { | ||
| 35 | 36 | human_check: HUMAN_CHECK_MESSAGE, |
| 36 | 37 | passkey_taken: PASSKEY_TAKEN, |
| 37 | 38 | signup_closed: SIGNUP_CLOSED_MESSAGE, |
| 39 | host_gone: HOST_WORDS.gone, | |
| 38 | 40 | }; |
| 39 | 41 | |
| 40 | 42 | /** Whether the name and address are fit to sign up with; else the words. */ |
src/web/pages/site.ts +2
| @@ -29,6 +29,7 @@ import { createRepo, repositoryLimitMessage, resolveOwner } from "../../actions/ | ||
| 29 | 29 | import { REPO_DIR_IN_THE_WAY, REPO_INIT_FAILED, REPO_NAME_RULES } from "../../actions/repo_words.ts"; |
| 30 | 30 | import { NOTE_MAX, requestOf } from "../../core/requests.ts"; |
| 31 | 31 | import { invalidEmailMessage, DECLINED_MESSAGE, REQUEST_IN_MESSAGE, STILL_WAITING_MESSAGE } from "../../actions/users.ts"; |
| 32 | import { HOST_WORDS } from "../../core/bundles.ts"; | |
| 32 | 33 | import { inviteByToken } from "../../core/invites.ts"; |
| 33 | 34 | import { INVITE_SPENT, inviteExpiredLine, inviteExpiryLine, inviteRepo, joinRepo } from "../../actions/invites.ts"; |
| 34 | 35 | import { whenWords } from "../../core/when_words.ts"; |
| @@ -848,6 +849,7 @@ export async function signupSubmit(ctx: Ctx): Promise<Response> { | ||
| 848 | 849 | invalid_email: { email: invalidEmailMessage(email) }, |
| 849 | 850 | human_check: { human: HUMAN_CHECK_MESSAGE }, |
| 850 | 851 | passkey_required: { human: PASSKEY_REQUIRED_MESSAGE }, |
| 852 | host_gone: { username: HOST_WORDS.gone }, | |
| 851 | 853 | }[created.error] ?? { username: "Something went wrong." }; |
| 852 | 854 | return page( |
| 853 | 855 | { |
src/web/pages/start_claim.ts +1
| @@ -109,6 +109,7 @@ async function makeAccountAndTake(ctx: Ctx): Promise<Response> { | ||
| 109 | 109 | weak_password: { password: "Passwords need at least 12 characters." }, |
| 110 | 110 | password_too_long: { password: "That password is too long." }, |
| 111 | 111 | signup_closed: { username: "Accounts cannot be made here." }, |
| 112 | host_gone: { username: "Accounts cannot be made here." }, | |
| 112 | 113 | }[made.error]; |
| 113 | 114 | return startClaimPage(ctx, said, 422); |
| 114 | 115 | } |
test/admin-lists-paged.test.ts +1 −1
| @@ -33,7 +33,7 @@ describe("the admin's accounts, people and invites lists answer { items, next_cu | ||
| 33 | 33 | } |
| 34 | 34 | proveAll(app); |
| 35 | 35 | admin = createToken(app.db, a.value.id, "t", "admin").token; |
| 36 | for (let i = 0; i < 4; i++) mintInvite(app.db, a.value.id, 3); | |
| 36 | for (let i = 0; i < 4; i++) mintInvite(app.db, a.value.id); | |
| 37 | 37 | }); |
| 38 | 38 | afterAll(async () => { |
| 39 | 39 | servers.stop(); |
test/conversation-ask.test.ts +1 −6
| @@ -399,12 +399,7 @@ const SAID: readonly (readonly [string, Record<string, unknown>, string])[] = [ | ||
| 399 | 399 | { repo: "marin/cakes", verb: "revoke", id: "t1" }, |
| 400 | 400 | "Revoke the child forge credential t1.", |
| 401 | 401 | ], |
| 402 | [ | |
| 403 | "mint_invite", | |
| 404 | { days: 3 }, | |
| 405 | "Make a single-use invite link, good for 3 days.", | |
| 406 | ], | |
| 407 | ["mint_invite", {}, "Make a single-use invite link, good for 7 days."], | |
| 402 | ["mint_invite", {}, "Make a single-use invite link, good for 72 hours."], | |
| 408 | 403 | [ |
| 409 | 404 | "claim_link", |
| 410 | 405 | { name: "kid", reveal: true }, |
test/conversation-confirm.test.ts +1 −1
| @@ -408,7 +408,7 @@ describe("a confirm past its time", () => { | ||
| 408 | 408 | describe("a result shown once", () => { |
| 409 | 409 | test("mint_invite's link is answered to the person and never kept in the conversation", async () => { |
| 410 | 410 | const w = await world(alice); |
| 411 | const asked = JSON.parse((await call(w.token, "mint_invite", { days: 3 })).text); | |
| 411 | const asked = JSON.parse((await call(w.token, "mint_invite", {})).text); | |
| 412 | 412 | expect(asked.needs_confirm).toMatch(/^[0-9a-z]+$/); |
| 413 | 413 | const res = await yes(asked.needs_confirm, alice); |
| 414 | 414 | expect(res.status).toBe(200); |
test/cookie-flags.test.ts +1
| @@ -117,6 +117,7 @@ const WALKED: Record<string, number> = { | ||
| 117 | 117 | "src/web/pages/passkeys.ts": 5, // import, passkey sign-in, passkey add/recovery-link sign-in, access-link sign-in (+1 mention) |
| 118 | 118 | "src/web/pages/site.ts": 5, // sessionCookie() itself and its uses: password sign-in/sign-up, logout; the theme cookie; the closing flash on a sign-in (#15619) |
| 119 | 119 | "src/web/pages/first-admin.ts": 1, // the first admin made by passkey |
| 120 | "src/web/pages/invite-link.ts": 1, // the invite link signs its person in | |
| 120 | 121 | "src/web/pages/signup-passkey.ts": 2, // import, sign-up by passkey |
| 121 | 122 | "src/web/pages/map.ts": 1, // the roadmap's last-looked cookie |
| 122 | 123 | "src/web/layout.ts": 4, // the flash set on, and cleared from, a redirect |
test/first-week.test.ts +1 −1
| @@ -65,7 +65,7 @@ describe("first week", () => { | ||
| 65 | 65 | }); |
| 66 | 66 | |
| 67 | 67 | test("an invite strikes the third, and with all three done the block is gone", () => { |
| 68 | mintInvite(app.db, alice.id, 7); | |
| 68 | mintInvite(app.db, alice.id); | |
| 69 | 69 | expect(firstWeekSteps(app.db, alice)).toBeNull(); |
| 70 | 70 | expect(firstWeekBlock(app.db, alice)).toBeNull(); |
| 71 | 71 | }); |
test/grants-view.test.ts +2 −1
| @@ -30,6 +30,7 @@ function seeded(): Database { | ||
| 30 | 30 | ["INSERT INTO app_member (app_id, user_id, added_by, added_at) VALUES ('app1', 'ann', 'root', ?1)", [AT]], |
| 31 | 31 | ["INSERT INTO game_grant (box_id, user_id, role, service) VALUES ('box1', 'ann', 'player', 'web')", []], |
| 32 | 32 | ["INSERT INTO model_grant (user_id, usd_per_month, granted_by, granted_at) VALUES ('ann', 5, NULL, ?1)", [AT]], |
| 33 | ["INSERT INTO host_grant (user_id, machine, containers, memory_mb, invite_id, at) VALUES ('ann', 'shop-1', 2, 512, 'inv1', ?1)", [AT]], | |
| 33 | 34 | ["INSERT INTO subscription_grant (scope_id, agent_id, subscription_id) VALUES ('repo1', 'mason', 'sub1')", []], |
| 34 | 35 | ["INSERT INTO secret_grant (repo_id, name, scope, scope_id, granted_by, granted_at) VALUES ('repo1', 'KEY', 'org', 'org1', 'root', ?1)", [AT]], |
| 35 | 36 | ["INSERT INTO egress_grant (repo_id, destination, granted_by, granted_at) VALUES ('repo1', 'api.example.com', 'root', ?1)", [AT]], |
| @@ -72,7 +73,7 @@ describe("the grants view", () => { | ||
| 72 | 73 | test("by account: an account's own grants, and none for an account with none", () => { |
| 73 | 74 | const db = seeded(); |
| 74 | 75 | expect(everyGrant(db, "ann").map((g) => g.table).sort()).toEqual( |
| 75 | ["app_member", "client_cloud_member", "game_grant", "member", "model_grant", "share", "team_member", "telemetry_grant"], | |
| 76 | ["app_member", "client_cloud_member", "game_grant", "host_grant", "member", "model_grant", "share", "team_member", "telemetry_grant"], | |
| 76 | 77 | ); |
| 77 | 78 | expect(everyGrant(db, "mason").map((g) => g.table).sort()).toEqual(["crew_team_member", "origin_read_grant", "subscription_grant"]); |
| 78 | 79 | expect(everyGrant(db, "nobody")).toEqual([]); |
test/invite-bundles.test.ts +7 −7
| @@ -56,36 +56,36 @@ describe("invite bundles", () => { | ||
| 56 | 56 | }; |
| 57 | 57 | |
| 58 | 58 | test("with no machine Host is refused and the page says why; Use and Build mint with their line", async () => { |
| 59 | const refused = mint(app, admin, 7, undefined, { bundle: "host", machine: "m1", containers: 2, memoryMb: 512 }); | |
| 59 | const refused = mint(app, admin, undefined, { bundle: "host", machine: "m1", containers: 2, memoryMb: 512 }); | |
| 60 | 60 | expect(refused.ok ? "" : refused.error).toBe("no_machine"); |
| 61 | 61 | const html = await page(); |
| 62 | 62 | expect(html).toContain("Host needs a machine this forge can offer"); |
| 63 | 63 | expect(html).toContain(BUNDLE.use.says); |
| 64 | 64 | expect(html).toContain(BUNDLE.build.says); |
| 65 | expect(mint(app, admin, 7, undefined, { bundle: "use" }).ok).toBe(true); | |
| 66 | expect(mint(app, admin, 7, undefined, { bundle: "build" }).ok).toBe(true); | |
| 67 | expect(mint(app, admin, 7).ok).toBe(true); | |
| 65 | expect(mint(app, admin, undefined, { bundle: "use" }).ok).toBe(true); | |
| 66 | expect(mint(app, admin, undefined, { bundle: "build" }).ok).toBe(true); | |
| 67 | expect(mint(app, admin).ok).toBe(true); | |
| 68 | 68 | const bundles = (list(app, admin) as { ok: true; value: { bundle: string }[] }).value.map((i) => i.bundle); |
| 69 | 69 | expect(bundles).toEqual(["use", "build", "use"]); |
| 70 | 70 | expect(await page()).toContain(BUNDLE.build.says); |
| 71 | 71 | }); |
| 72 | 72 | |
| 73 | 73 | test("a bundle that is not one of three is refused", () => { |
| 74 | const r = mint(app, admin, 7, undefined, { bundle: "root" }); | |
| 74 | const r = mint(app, admin, undefined, { bundle: "root" }); | |
| 75 | 75 | expect(r.ok ? "" : r.error).toBe("invalid_bundle"); |
| 76 | 76 | }); |
| 77 | 77 | |
| 78 | 78 | test("Host with a machine on offer stores the machine and caps; a stranger machine or a bad cap is refused", async () => { |
| 79 | 79 | pinMachine("shop-1"); |
| 80 | 80 | const bad = (c: object) => { |
| 81 | const r = mint(app, admin, 7, undefined, { bundle: "host", ...c }); | |
| 81 | const r = mint(app, admin, undefined, { bundle: "host", ...c }); | |
| 82 | 82 | return r.ok ? "" : r.error; |
| 83 | 83 | }; |
| 84 | 84 | expect(bad({ machine: "elsewhere", containers: 2, memoryMb: 512 })).toBe("invalid_machine"); |
| 85 | 85 | expect(bad({ machine: "shop-1", containers: 0, memoryMb: 512 })).toBe("invalid_cap"); |
| 86 | 86 | expect(bad({ machine: "shop-1", containers: 2, memoryMb: -1 })).toBe("invalid_cap"); |
| 87 | 87 | expect(bad({ machine: "shop-1", containers: "2.5", memoryMb: 512 })).toBe("invalid_cap"); |
| 88 | const ok = mint(app, admin, 7, undefined, { bundle: "host", machine: "shop-1", containers: "3", memoryMb: "1024" }); | |
| 88 | const ok = mint(app, admin, undefined, { bundle: "host", machine: "shop-1", containers: "3", memoryMb: "1024" }); | |
| 89 | 89 | expect(ok.ok && ok.value.invite.host).toEqual({ machine: "shop-1", containers: 3, memoryMb: 1024 }); |
| 90 | 90 | const html = await page(); |
| 91 | 91 | expect(html).toContain("on shop-1, up to 3 containers and 1024 MB"); |
test/invite-expiry-words.test.ts +2 −2
| @@ -42,7 +42,7 @@ describe("invite expiry words", () => { | ||
| 42 | 42 | }); |
| 43 | 43 | |
| 44 | 44 | test("an open link says when it works until", async () => { |
| 45 | const { token } = mintInvite(app.db, adminId, 3); | |
| 45 | const { token } = mintInvite(app.db, adminId); | |
| 46 | 46 | const { status, text } = await get(token); |
| 47 | 47 | expect(status).toBe(200); |
| 48 | 48 | expect(text).toContain('id="invite-expiry"'); |
| @@ -53,7 +53,7 @@ describe("invite expiry words", () => { | ||
| 53 | 53 | }); |
| 54 | 54 | |
| 55 | 55 | test("an expired link says so kindly and names who sent it", async () => { |
| 56 | const { token } = mintInvite(app.db, adminId, 1, Date.now() - 3 * 86_400_000); | |
| 56 | const { token } = mintInvite(app.db, adminId, Date.now() - 4 * 86_400_000); | |
| 57 | 57 | const { text } = await get(token); |
| 58 | 58 | expect(text).toContain("This link has expired"); |
| 59 | 59 | expect(text).toContain("Ask olive for a new one"); |
test/invite-link.test.ts added +160
| @@ -0,0 +1,160 @@ | ||
| 1 | /** | |
| 2 | * Opening an invite link signs the person in, proves the account with the invite as the proof and | |
| 3 | * applies the bundle, in every signup mode including closed (#18454). One use, 72 hours, revocable; | |
| 4 | * a dead link answers one plain page and grants 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 { mint } from "../src/actions/invites.ts"; | |
| 12 | import { BUNDLES, type Bundle } from "../src/core/bundles.ts"; | |
| 13 | import { insertPinned } from "../src/core/pinned.ts"; | |
| 14 | import { mintInvite, revokeInvite } from "../src/core/invites.ts"; | |
| 15 | import { roleOf } from "../src/core/roles.ts"; | |
| 16 | import type { User } from "../src/core/users.ts"; | |
| 17 | import { emailVerified } from "../src/core/verify.ts"; | |
| 18 | import { setLimit } from "../src/settings/limits.ts"; | |
| 19 | import { SIGNUP_MODES, setSignup } from "../src/settings/signup.ts"; | |
| 20 | import { serve, type Servers } from "../src/http/server.ts"; | |
| 21 | import { seedAdmin } from "./helpers/admin.ts"; | |
| 22 | import { quietLogs } from "./helpers/globals.ts"; | |
| 23 | ||
| 24 | quietLogs(); | |
| 25 | ||
| 26 | const HOUR = 3_600_000; | |
| 27 | ||
| 28 | describe("an invite link signs its person in", () => { | |
| 29 | let dir = ""; | |
| 30 | let app: App; | |
| 31 | let admin: User; | |
| 32 | let servers: Servers; | |
| 33 | ||
| 34 | beforeAll(async () => { | |
| 35 | dir = await mkdtemp(join(tmpdir(), "forge-invite-link-")); | |
| 36 | app = createApp({ dataDir: dir, port: 0 }); | |
| 37 | const made = await seedAdmin(app, { username: "olive", email: "[email protected]", password: "an-invited-passphrase" }); | |
| 38 | if (!made.ok) throw new Error(made.error); | |
| 39 | admin = made.value; | |
| 40 | servers = await serve(app); | |
| 41 | setLimit(app.db, "signup.per_source", 1000, admin.id); | |
| 42 | }); | |
| 43 | afterAll(async () => { | |
| 44 | await servers.stop(); | |
| 45 | app.close(); | |
| 46 | await rm(dir, { recursive: true, force: true }); | |
| 47 | }); | |
| 48 | ||
| 49 | const pinMachine = (name: string): void => { | |
| 50 | insertPinned( | |
| 51 | app.db, | |
| 52 | { name, target: "digitalocean", account: "main", app: "ada/shop", source: "", version: "v1", config: {}, host: `${name}.example.com`, claimHash: "", claimExpires: "", datacenter: "fra1", size: "s-1vcpu-1gb" }, | |
| 53 | "ada", | |
| 54 | ); | |
| 55 | app.db.query("UPDATE pinned_forge SET state = 'online', remote = 'r-1' WHERE name = ?1").run(name); | |
| 56 | }; | |
| 57 | const open = (token: string) => fetch(`${servers.url}/signup?invite=${token}`); | |
| 58 | const press = (token: string) => | |
| 59 | fetch(`${servers.url}/signup/invite?invite=${token}`, { method: "POST", body: new URLSearchParams({}), redirect: "manual" }); | |
| 60 | const people = () => app.db.query<{ n: number }, []>("SELECT COUNT(*) AS n FROM user").get()!.n; | |
| 61 | const minted = (bundle: Bundle, machine = "shop-1") => { | |
| 62 | const r = mint(app, admin, undefined, bundle === "host" ? { bundle, machine, containers: 2, memoryMb: 512 } : { bundle }); | |
| 63 | if (!r.ok) throw new Error(r.error); | |
| 64 | return r.value; | |
| 65 | }; | |
| 66 | const userBy = (inviteId: string) => | |
| 67 | app.db.query<{ id: string; username: string }, [string]>("SELECT u.id, u.username FROM invite i JOIN user u ON u.id = i.used_by WHERE i.id = ?1").get(inviteId); | |
| 68 | ||
| 69 | test("each mode x each bundle: signed in, proven by the invite, with exactly the bundle's grants", async () => { | |
| 70 | pinMachine("shop-1"); | |
| 71 | for (const mode of SIGNUP_MODES) { | |
| 72 | setSignup(app.db, mode, "test"); | |
| 73 | for (const bundle of BUNDLES) { | |
| 74 | const { invite, token } = minted(bundle); | |
| 75 | const seen = await open(token); | |
| 76 | expect(seen.status).toBe(200); | |
| 77 | expect(await seen.text()).toContain("/signup/invite?invite="); | |
| 78 | // Opening spends nothing: a preview or a crawler never burns the link. | |
| 79 | expect(userBy(invite.id)).toBeNull(); | |
| 80 | ||
| 81 | const res = await press(token); | |
| 82 | expect(res.status).toBe(303); | |
| 83 | const cookie = res.headers.get("set-cookie") ?? ""; | |
| 84 | expect(cookie).toContain("forge_session="); | |
| 85 | expect(cookie).toContain("HttpOnly"); | |
| 86 | ||
| 87 | const who = userBy(invite.id)!; | |
| 88 | expect(who).not.toBeNull(); | |
| 89 | const user = app.db.query<{ id: string; is_admin: number }, [string]>("SELECT id, is_admin FROM user WHERE id = ?1").get(who.id)!; | |
| 90 | expect(user.is_admin).toBe(0); | |
| 91 | // The session in the cookie is this person's. | |
| 92 | const value = cookie.split(";")[0]!.split("=")[1]!; | |
| 93 | const me = await fetch(`${servers.url}/api/v1/user`, { headers: { cookie: `forge_session=${value}` } }); | |
| 94 | expect(((await me.json()) as { username: string }).username).toBe(who.username); | |
| 95 | // Proven with the invite as the proof, who vouched and how; no mail was asked for. | |
| 96 | expect(emailVerified(app.db, who.id)).toBe(true); | |
| 97 | const proof = app.db.query<{ proof_by: string; proof_how: string }, [string]>("SELECT proof_by, proof_how FROM connection WHERE user_id = ?1 AND kind = 'email'").get(who.id)!; | |
| 98 | expect(proof).toEqual({ proof_by: admin.id, proof_how: "invite" }); | |
| 99 | expect(app.db.query("SELECT 1 FROM email_check WHERE user_id = ?1 AND token_hash IS NOT NULL").get(who.id)).toBeNull(); | |
| 100 | // Exactly the bundle's grants. | |
| 101 | expect(roleOf(app.db, { id: who.id, isAdmin: false })).toBe(bundle === "build" ? "member" : "guest"); | |
| 102 | const host = app.db.query<{ machine: string; containers: number; memory_mb: number }, [string]>("SELECT machine, containers, memory_mb FROM host_grant WHERE user_id = ?1").get(who.id); | |
| 103 | expect(host).toEqual(bundle === "host" ? { machine: "shop-1", containers: 2, memory_mb: 512 } : null); | |
| 104 | } | |
| 105 | } | |
| 106 | }); | |
| 107 | ||
| 108 | test("a link used twice makes one account; the replay answers one plain page", async () => { | |
| 109 | setSignup(app.db, "closed", "test"); | |
| 110 | const { invite, token } = minted("use"); | |
| 111 | expect((await press(token)).status).toBe(303); | |
| 112 | const before = people(); | |
| 113 | const again = await press(token); | |
| 114 | expect(again.status).toBe(410); | |
| 115 | expect(again.headers.get("set-cookie")).toBeNull(); | |
| 116 | expect(await again.text()).toContain('id="invite-dead"'); | |
| 117 | expect((await open(token)).status).toBe(410); | |
| 118 | expect(people()).toBe(before); | |
| 119 | expect(userBy(invite.id)).not.toBeNull(); | |
| 120 | }); | |
| 121 | ||
| 122 | test("a link lives 72 hours on the clock: open just inside, dead at the mark", async () => { | |
| 123 | setSignup(app.db, "closed", "test"); | |
| 124 | const inside = mintInvite(app.db, admin.id, Date.now() - 72 * HOUR + 60_000); | |
| 125 | expect(Date.parse(inside.invite.expiresAt) - Date.parse(inside.invite.createdAt)).toBe(72 * HOUR); | |
| 126 | expect((await open(inside.token)).status).toBe(200); | |
| 127 | const dead = mintInvite(app.db, admin.id, Date.now() - 72 * HOUR - 1000); | |
| 128 | const before = people(); | |
| 129 | const page = await open(dead.token); | |
| 130 | expect(page.status).toBe(410); | |
| 131 | expect(await page.text()).toContain("This link has expired"); | |
| 132 | expect((await press(dead.token)).status).toBe(410); | |
| 133 | expect(people()).toBe(before); | |
| 134 | }); | |
| 135 | ||
| 136 | test("a revoked link grants nothing, and neither does a stranger's guess in a closed forge", async () => { | |
| 137 | setSignup(app.db, "closed", "test"); | |
| 138 | const { invite, token } = minted("build"); | |
| 139 | expect(revokeInvite(app.db, invite.id).ok).toBe(true); | |
| 140 | const before = people(); | |
| 141 | expect((await press(token)).status).toBe(410); | |
| 142 | expect((await open(token)).status).toBe(410); | |
| 143 | expect((await press("invite_not-a-real-one")).status).toBe(410); | |
| 144 | expect(people()).toBe(before); | |
| 145 | expect(userBy(invite.id)).toBeNull(); | |
| 146 | }); | |
| 147 | ||
| 148 | test("a Host invite whose machine has gone grants nothing and says so", async () => { | |
| 149 | setSignup(app.db, "invite", "test"); | |
| 150 | pinMachine("shop-2"); | |
| 151 | const { invite, token } = minted("host", "shop-2"); | |
| 152 | app.db.query("DELETE FROM pinned_forge WHERE name = 'shop-2'").run(); | |
| 153 | const before = people(); | |
| 154 | const res = await press(token); | |
| 155 | expect(await res.text()).toContain("no longer offered"); | |
| 156 | expect(res.headers.get("set-cookie")).toBeNull(); | |
| 157 | expect(people()).toBe(before); | |
| 158 | expect(app.db.query<{ n: number }, [string]>("SELECT COUNT(*) AS n FROM host_grant WHERE invite_id = ?1").get(invite.id)!.n).toBe(0); | |
| 159 | }); | |
| 160 | }); |
test/invite-org.test.ts +6 −6
| @@ -43,7 +43,7 @@ describe("an invite to an organization", () => { | ||
| 43 | 43 | body: JSON.stringify({ username, email: `${username}@f.dev`, password: PASSWORD, invite }), |
| 44 | 44 | }); |
| 45 | 45 | const tokenOf = (org?: string) => { |
| 46 | const made = mint(app, admin, undefined, org); | |
| 46 | const made = mint(app, admin, org); | |
| 47 | 47 | if (!made.ok) throw new Error(made.error); |
| 48 | 48 | return made.value; |
| 49 | 49 | }; |
| @@ -132,7 +132,7 @@ describe("an invite to an organization", () => { | ||
| 132 | 132 | }); |
| 133 | 133 | |
| 134 | 134 | test("an organization that does not exist mints nothing", () => { |
| 135 | const made = mint(app, admin, undefined, "nowhere"); | |
| 135 | const made = mint(app, admin, "nowhere"); | |
| 136 | 136 | expect(made.ok).toBe(false); |
| 137 | 137 | if (!made.ok) expect(made.error).toBe("unknown_org"); |
| 138 | 138 | }); |
| @@ -152,7 +152,7 @@ describe("an invite to an organization, edges", () => { | ||
| 152 | 152 | body: JSON.stringify({ username, email: `${username}@f.dev`, password: PASSWORD, invite }), |
| 153 | 153 | }); |
| 154 | 154 | const tokenOf = (org: string) => { |
| 155 | const made = mint(app, admin, undefined, org); | |
| 155 | const made = mint(app, admin, org); | |
| 156 | 156 | if (!made.ok) throw new Error(made.error); |
| 157 | 157 | return made.value.token; |
| 158 | 158 | }; |
| @@ -250,7 +250,7 @@ describe("an invite to an organization, edges", () => { | ||
| 250 | 250 | expect(res.status).toBe(202); |
| 251 | 251 | const vera = getUserByName(app.db, "vera")!; |
| 252 | 252 | const { invite } = (() => { |
| 253 | const made = mint(app, admin, undefined, "later"); | |
| 253 | const made = mint(app, admin, "later"); | |
| 254 | 254 | if (!made.ok) throw new Error(made.error); |
| 255 | 255 | return made.value; |
| 256 | 256 | })(); |
| @@ -273,7 +273,7 @@ describe("an invite to an organization, edges", () => { | ||
| 273 | 273 | }); |
| 274 | 274 | setSignup(app.db, "invite", admin.id); |
| 275 | 275 | const wren = getUserByName(app.db, "wren")!; |
| 276 | const made = mint(app, admin, undefined, "broken"); | |
| 276 | const made = mint(app, admin, "broken"); | |
| 277 | 277 | if (!made.ok) throw new Error(made.error); |
| 278 | 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 | 279 | app.db.exec("ALTER TABLE team_member RENAME TO team_member_away"); |
| @@ -364,7 +364,7 @@ describe("an invite to an organization, by passkey", () => { | ||
| 364 | 364 | }); |
| 365 | 365 | |
| 366 | 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"); | |
| 367 | const made = mint(app, admin, "acme"); | |
| 368 | 368 | if (!made.ok) throw new Error(made.error); |
| 369 | 369 | const origin = new URL(servers.url).origin; |
| 370 | 370 | const d = await device(origin, new URL(servers.url).hostname); |
test/invite-redeem.test.ts +10 −8
| @@ -29,7 +29,7 @@ describe("invite links redeem at signup", () => { | ||
| 29 | 29 | let servers: Servers; |
| 30 | 30 | let owner = ""; |
| 31 | 31 | |
| 32 | const mint = (days = 7, now = Date.now()) => mintInvite(app.db, owner, days, now); | |
| 32 | const mint = (now = Date.now()) => mintInvite(app.db, owner, now); | |
| 33 | 33 | const stateOf = (id: string) => listInvites(app.db).find((i) => i.id === id)?.state; |
| 34 | 34 | const form = (username: string, invite?: string) => |
| 35 | 35 | fetch(`${servers.url}/signup${invite === undefined ? "" : `?invite=${invite}`}`, { |
| @@ -119,7 +119,7 @@ describe("invite links redeem at signup", () => { | ||
| 119 | 119 | test("a revoked, an expired or an unknown link makes nothing", async () => { |
| 120 | 120 | const revoked = mint(); |
| 121 | 121 | revokeInvite(app.db, revoked.invite.id); |
| 122 | const expired = mint(1, Date.now() - 2 * 86_400_000); | |
| 122 | const expired = mint(Date.now() - 4 * 86_400_000); | |
| 123 | 123 | for (const [name, token] of [["rev", revoked.token], ["exp", expired.token], ["unknown", "invite_nothing"]] as const) { |
| 124 | 124 | expect((await apiSignup(name, token)).status).toBe(403); |
| 125 | 125 | expect(getUserByName(app.db, name)).toBeUndefined(); |
| @@ -132,14 +132,16 @@ describe("invite links redeem at signup", () => { | ||
| 132 | 132 | expect(stateOf(invite.id)).toBe("open"); |
| 133 | 133 | }); |
| 134 | 134 | |
| 135 | test("while signup is closed a link makes nothing; while open it is not spent", async () => { | |
| 136 | const { invite, token } = mint(); | |
| 135 | test("a live link opens the door while signup is closed, and is spent; so while open", async () => { | |
| 136 | const closed = mint(); | |
| 137 | 137 | setSignup(app.db, "closed", owner); |
| 138 | expect((await apiSignup("shut", token)).status).toBe(403); | |
| 139 | expect(stateOf(invite.id)).toBe("open"); | |
| 138 | expect((await apiSignup("shut", closed.token)).status).toBe(201); | |
| 139 | expect(stateOf(closed.invite.id)).toBe("used"); | |
| 140 | expect((await apiSignup("shut2")).status).toBe(403); | |
| 141 | const open = mint(); | |
| 140 | 142 | setSignup(app.db, "open", owner); |
| 141 | expect((await apiSignup("opened", token)).status).toBe(201); | |
| 142 | expect(stateOf(invite.id)).toBe("open"); | |
| 143 | expect((await apiSignup("opened", open.token)).status).toBe(201); | |
| 144 | expect(stateOf(open.invite.id)).toBe("used"); | |
| 143 | 145 | setSignup(app.db, "invite", owner); |
| 144 | 146 | // Many sign-ups from this one source: the window is not under test here. |
| 145 | 147 | setLimit(app.db, "signup.per_source", 1000, owner); |
test/invites-action.test.ts +11 −15
| @@ -11,7 +11,6 @@ import { join } from "node:path"; | ||
| 11 | 11 | import { createApp, type App } from "../src/app.ts"; |
| 12 | 12 | import { inviteLink, list, mint, revoke } from "../src/actions/invites.ts"; |
| 13 | 13 | import { signUp } from "../src/actions/users.ts"; |
| 14 | import { MAX_DAYS } from "../src/core/invites.ts"; | |
| 15 | 14 | import { listEvents } from "../src/core/events.ts"; |
| 16 | 15 | import { createUser, getUserByName, type User } from "../src/core/users.ts"; |
| 17 | 16 | import { sha256 } from "../src/kernel/hash.ts"; |
| @@ -75,7 +74,7 @@ describe("invite links through the action", () => { | ||
| 75 | 74 | |
| 76 | 75 | test("an admin's mint returns the link once; no listing, event or log line carries it", () => { |
| 77 | 76 | const since = listEvents(app.db, { limit: 1 })[0]?.id; |
| 78 | const made = logged(() => mint(app, admin, 3)); | |
| 77 | const made = logged(() => mint(app, admin)); | |
| 79 | 78 | expect(made.ok).toBe(true); |
| 80 | 79 | if (!made.ok) return; |
| 81 | 80 | const { invite, token } = made.value; |
| @@ -117,7 +116,7 @@ describe("invite links through the action", () => { | ||
| 117 | 116 | }); |
| 118 | 117 | |
| 119 | 118 | test("a revoked link signs nobody up; an open one does", async () => { |
| 120 | const made = mint(app, admin, undefined); | |
| 119 | const made = mint(app, admin); | |
| 121 | 120 | if (!made.ok) throw new Error(made.error); |
| 122 | 121 | expect(revoke(app, admin, made.value.invite.id).ok).toBe(true); |
| 123 | 122 | const refused = await signUp( |
| @@ -130,7 +129,7 @@ describe("invite links through the action", () => { | ||
| 130 | 129 | // A second revoke of the same link is not found: it is already shut. |
| 131 | 130 | expect(revoke(app, admin, made.value.invite.id)).toEqual({ ok: false, error: "not_found" }); |
| 132 | 131 | |
| 133 | const open = mint(app, admin, 1); | |
| 132 | const open = mint(app, admin); | |
| 134 | 133 | if (!open.ok) throw new Error(open.error); |
| 135 | 134 | const let_in = await signUp( |
| 136 | 135 | app, |
| @@ -141,18 +140,18 @@ describe("invite links through the action", () => { | ||
| 141 | 140 | }); |
| 142 | 141 | |
| 143 | 142 | test("a member, a guest and nobody get not_found for all three, and nothing changes", () => { |
| 144 | const made = mint(app, admin, 7); | |
| 143 | const made = mint(app, admin); | |
| 145 | 144 | if (!made.ok) throw new Error(made.error); |
| 146 | 145 | const before = list(app, admin); |
| 147 | 146 | const eventsBefore = listEvents(app.db, { limit: 500 }).length; |
| 148 | 147 | for (const actor of [member, guest, undefined]) { |
| 149 | expect(mint(app, actor, 7)).toEqual({ ok: false, error: "not_found" }); | |
| 148 | expect(mint(app, actor)).toEqual({ ok: false, error: "not_found" }); | |
| 150 | 149 | expect(list(app, actor)).toEqual({ ok: false, error: "not_found" }); |
| 151 | 150 | expect(revoke(app, actor, made.value.invite.id)).toEqual({ ok: false, error: "not_found" }); |
| 152 | 151 | } |
| 153 | 152 | // An agent account flagged admin is still not a person who may mint. |
| 154 | 153 | const agent = { ...admin, kind: "agent" as const }; |
| 155 | expect(mint(app, agent, 7)).toEqual({ ok: false, error: "not_found" }); | |
| 154 | expect(mint(app, agent)).toEqual({ ok: false, error: "not_found" }); | |
| 156 | 155 | expect(list(app, agent)).toEqual({ ok: false, error: "not_found" }); |
| 157 | 156 | expect(revoke(app, agent, made.value.invite.id)).toEqual({ ok: false, error: "not_found" }); |
| 158 | 157 | |
| @@ -160,13 +159,10 @@ describe("invite links through the action", () => { | ||
| 160 | 159 | expect(listEvents(app.db, { limit: 500 }).length).toBe(eventsBefore); |
| 161 | 160 | }); |
| 162 | 161 | |
| 163 | test("days outside 1 to 30, or not a whole number, is refused and mints nothing", () => { | |
| 164 | const before = list(app, admin); | |
| 165 | for (const days of [0, -1, MAX_DAYS + 1, 1.5, "7", Number.NaN, Infinity, {}]) { | |
| 166 | expect(mint(app, admin, days)).toEqual({ ok: false, error: "invalid_days" }); | |
| 167 | } | |
| 168 | expect(list(app, admin)).toEqual(before); | |
| 169 | expect(mint(app, admin, 1).ok).toBe(true); | |
| 170 | expect(mint(app, admin, MAX_DAYS).ok).toBe(true); | |
| 162 | test("every link lives 72 hours: the mint takes no day count", () => { | |
| 163 | const made = mint(app, admin); | |
| 164 | expect(made.ok).toBe(true); | |
| 165 | if (!made.ok) return; | |
| 166 | expect(Date.parse(made.value.invite.expiresAt) - Date.parse(made.value.invite.createdAt)).toBe(72 * 3_600_000); | |
| 171 | 167 | }); |
| 172 | 168 | }); |
test/invites-core.test.ts +15 −30
| @@ -9,13 +9,10 @@ import invite from "../src/core/migrations/20261016200000-invite.ts"; | ||
| 9 | 9 | import inviteOrg from "../src/core/migrations/20261114090000-invite-org.ts"; |
| 10 | 10 | import inviteBundle from "../src/core/migrations/20261206100000-invite-bundle.ts"; |
| 11 | 11 | import { |
| 12 | DEFAULT_DAYS, | |
| 13 | MAX_DAYS, | |
| 14 | 12 | inviteOpen, |
| 15 | 13 | inviteSpentBy, |
| 16 | 14 | listInvites, |
| 17 | 15 | mintInvite, |
| 18 | parseDays, | |
| 19 | 16 | redeemInvite, |
| 20 | 17 | reopenInvite, |
| 21 | 18 | } from "../src/core/invites.ts"; |
| @@ -23,18 +20,6 @@ import { | ||
| 23 | 20 | const DAY = 86_400_000; |
| 24 | 21 | const T0 = Date.parse("2026-10-01T00:00:00Z"); |
| 25 | 22 | |
| 26 | describe("parseDays", () => { | |
| 27 | test("the default for absent, the bounds for present", () => { | |
| 28 | expect(parseDays(undefined)).toEqual({ ok: true, value: DEFAULT_DAYS }); | |
| 29 | expect(parseDays(null)).toEqual({ ok: true, value: DEFAULT_DAYS }); | |
| 30 | expect(parseDays(1)).toEqual({ ok: true, value: 1 }); | |
| 31 | expect(parseDays(MAX_DAYS)).toEqual({ ok: true, value: MAX_DAYS }); | |
| 32 | for (const bad of [0, MAX_DAYS + 1, 1.5, "7", Number.NaN, -1, Infinity]) { | |
| 33 | expect(parseDays(bad)).toEqual({ ok: false, error: "invalid_days" }); | |
| 34 | } | |
| 35 | }); | |
| 36 | }); | |
| 37 | ||
| 38 | 23 | describe("an invite's life", () => { |
| 39 | 24 | let db: Database; |
| 40 | 25 | beforeEach(() => { |
| @@ -46,16 +31,16 @@ describe("an invite's life", () => { | ||
| 46 | 31 | }); |
| 47 | 32 | |
| 48 | 33 | test("open before its expiry, not at or after it", () => { |
| 49 | const { token } = mintInvite(db, "owner", 2, T0); | |
| 34 | const { token } = mintInvite(db, "owner", T0); | |
| 50 | 35 | expect(inviteOpen(db, token, T0)).toBe(true); |
| 51 | expect(inviteOpen(db, token, T0 + 2 * DAY - 1)).toBe(true); | |
| 52 | expect(inviteOpen(db, token, T0 + 2 * DAY)).toBe(false); | |
| 36 | expect(inviteOpen(db, token, T0 + 3 * DAY - 1)).toBe(true); | |
| 53 | 37 | expect(inviteOpen(db, token, T0 + 3 * DAY)).toBe(false); |
| 38 | expect(inviteOpen(db, token, T0 + 4 * DAY)).toBe(false); | |
| 54 | 39 | expect(inviteOpen(db, "invite_unknown", T0)).toBe(false); |
| 55 | 40 | }); |
| 56 | 41 | |
| 57 | 42 | test("redeems once; a second redeem by anyone fails", () => { |
| 58 | const { token } = mintInvite(db, "owner", 2, T0); | |
| 43 | const { token } = mintInvite(db, "owner", T0); | |
| 59 | 44 | expect(redeemInvite(db, token, "ada", T0 + 1)).toBe(true); |
| 60 | 45 | expect(inviteOpen(db, token, T0 + 2)).toBe(false); |
| 61 | 46 | expect(redeemInvite(db, token, "ada", T0 + 2)).toBe(false); |
| @@ -64,21 +49,21 @@ describe("an invite's life", () => { | ||
| 64 | 49 | }); |
| 65 | 50 | |
| 66 | 51 | test("an expired invite never redeems", () => { |
| 67 | const { token } = mintInvite(db, "owner", 1, T0); | |
| 68 | expect(redeemInvite(db, token, "ada", T0 + DAY)).toBe(false); | |
| 52 | const { token } = mintInvite(db, "owner", T0); | |
| 53 | expect(redeemInvite(db, token, "ada", T0 + 3 * DAY)).toBe(false); | |
| 69 | 54 | expect(redeemInvite(db, token, "ada", T0 + 5 * DAY)).toBe(false); |
| 70 | 55 | expect(inviteSpentBy(db, "ada")).toBeUndefined(); |
| 71 | expect(listInvites(db, T0 + DAY)[0]!.state).toBe("expired"); | |
| 56 | expect(listInvites(db, T0 + 3 * DAY)[0]!.state).toBe("expired"); | |
| 72 | 57 | }); |
| 73 | 58 | |
| 74 | 59 | test("an unknown token redeems nothing", () => { |
| 75 | mintInvite(db, "owner", 2, T0); | |
| 60 | mintInvite(db, "owner", T0); | |
| 76 | 61 | expect(redeemInvite(db, "invite_nope", "ada", T0)).toBe(false); |
| 77 | 62 | }); |
| 78 | 63 | |
| 79 | 64 | test("inviteSpentBy names the redeemer's invite", () => { |
| 80 | const a = mintInvite(db, "owner", 2, T0); | |
| 81 | const b = mintInvite(db, "owner", 2, T0); | |
| 65 | const a = mintInvite(db, "owner", T0); | |
| 66 | const b = mintInvite(db, "owner", T0); | |
| 82 | 67 | redeemInvite(db, a.token, "ada", T0); |
| 83 | 68 | expect(inviteSpentBy(db, "ada")).toBe(a.invite.id); |
| 84 | 69 | expect(inviteSpentBy(db, "bob")).toBeUndefined(); |
| @@ -87,8 +72,8 @@ describe("an invite's life", () => { | ||
| 87 | 72 | }); |
| 88 | 73 | |
| 89 | 74 | test("reopenInvite gives back only that account's invite, once more redeemable", () => { |
| 90 | const a = mintInvite(db, "owner", 2, T0); | |
| 91 | const b = mintInvite(db, "owner", 2, T0); | |
| 75 | const a = mintInvite(db, "owner", T0); | |
| 76 | const b = mintInvite(db, "owner", T0); | |
| 92 | 77 | redeemInvite(db, a.token, "ada", T0); |
| 93 | 78 | redeemInvite(db, b.token, "bob", T0); |
| 94 | 79 | reopenInvite(db, "ada"); |
| @@ -103,9 +88,9 @@ describe("an invite's life", () => { | ||
| 103 | 88 | |
| 104 | 89 | test("a redeemed invite lists who joined with it and when; null when unused or the account is gone", () => { |
| 105 | 90 | db.query("INSERT INTO user (id, username) VALUES ('u1', 'ada')").run(); |
| 106 | const used = mintInvite(db, "owner", 2, T0); | |
| 107 | const gone = mintInvite(db, "owner", 2, T0); | |
| 108 | const fresh = mintInvite(db, "owner", 2, T0); | |
| 91 | const used = mintInvite(db, "owner", T0); | |
| 92 | const gone = mintInvite(db, "owner", T0); | |
| 93 | const fresh = mintInvite(db, "owner", T0); | |
| 109 | 94 | redeemInvite(db, used.token, "u1", T0 + 1000); |
| 110 | 95 | redeemInvite(db, gone.token, "u-deleted", T0 + 2000); |
| 111 | 96 | const byId = new Map(listInvites(db, T0 + 3000).map((i) => [i.id, i])); |
test/invites.test.ts +8 −16
| @@ -49,9 +49,9 @@ describe("invites: an admin mints, lists and revokes", () => { | ||
| 49 | 49 | const made = (await res.json()) as { id: string; token: string; link: string; expiresAt: string; state: string }; |
| 50 | 50 | expect(made.link).toBe(`https://forge.example/signup?invite=${made.token}`); |
| 51 | 51 | expect(made.state).toBe("open"); |
| 52 | const days = (Date.parse(made.expiresAt) - Date.now()) / 86_400_000; | |
| 53 | expect(days).toBeGreaterThan(6.99); | |
| 54 | expect(days).toBeLessThan(7.01); | |
| 52 | const hours = (Date.parse(made.expiresAt) - Date.now()) / 3_600_000; | |
| 53 | expect(hours).toBeGreaterThan(71.99); | |
| 54 | expect(hours).toBeLessThan(72.01); | |
| 55 | 55 | |
| 56 | 56 | const rows = app.db.query("SELECT * FROM invite").all(); |
| 57 | 57 | expect(JSON.stringify(rows)).not.toContain(made.token); |
| @@ -71,11 +71,10 @@ describe("invites: an admin mints, lists and revokes", () => { | ||
| 71 | 71 | expect(JSON.stringify(listEvents(app.db, {}))).not.toContain(made.token); |
| 72 | 72 | }); |
| 73 | 73 | |
| 74 | test("days is bounded to 1..30", async () => { | |
| 75 | const post = (days: unknown) => | |
| 76 | api("/api/v1/admin/invites", admin, { method: "POST", body: JSON.stringify({ days }) }); | |
| 77 | expect((await post(30)).status).toBe(201); | |
| 78 | for (const bad of [0, 31, 1.5, "7", -1]) expect((await post(bad)).status).toBe(422); | |
| 74 | test("a longer life is not on offer: a days field changes nothing", async () => { | |
| 75 | const res = await api("/api/v1/admin/invites", admin, { method: "POST", body: JSON.stringify({ days: 30 }) }); | |
| 76 | const made = (await res.json()) as { expiresAt: string }; | |
| 77 | expect((Date.parse(made.expiresAt) - Date.now()) / 3_600_000).toBeLessThan(72.01); | |
| 79 | 78 | }); |
| 80 | 79 | |
| 81 | 80 | test("a non-admin and a stranger are refused on all three routes", async () => { |
| @@ -92,7 +91,7 @@ describe("invites: an admin mints, lists and revokes", () => { | ||
| 92 | 91 | }); |
| 93 | 92 | |
| 94 | 93 | test("an expired invite reads as expired; a used one cannot be revoked", () => { |
| 95 | const past = mintInvite(app.db, "x", 1, Date.now() - 2 * 86_400_000); | |
| 94 | const past = mintInvite(app.db, "x", Date.now() - 4 * 86_400_000); | |
| 96 | 95 | expect(listInvites(app.db).find((i) => i.id === past.invite.id)?.state).toBe("expired"); |
| 97 | 96 | const used = mintInvite(app.db, "x"); |
| 98 | 97 | app.db.query("UPDATE invite SET used_at = ?2 WHERE id = ?1").run(used.invite.id, "2026-01-01T00:00:00Z"); |
| @@ -156,13 +155,6 @@ describe("invites: the settings form", () => { | ||
| 156 | 155 | expect(listInvites(app.db)[0]!.state).toBe("revoked"); |
| 157 | 156 | }); |
| 158 | 157 | |
| 159 | test("days outside 1 to 30 mint nothing", async () => { | |
| 160 | const before = listInvites(app.db).length; | |
| 161 | await post(alice, "/admin/invites", { days: "31" }); | |
| 162 | await post(alice, "/admin/invites", { days: "abc" }); | |
| 163 | expect(listInvites(app.db).length).toBe(before); | |
| 164 | }); | |
| 165 | ||
| 166 | 158 | test("a cross-origin post is refused and a non-admin gets the not-found page", async () => { |
| 167 | 159 | const before = listInvites(app.db).length; |
| 168 | 160 | expect((await post(alice, "/admin/invites", { days: "3" }, "https://evil.example")).status).toBe(403); |
test/mcp-forge-admin.test.ts +2 −2
| @@ -272,8 +272,8 @@ describe("the forge over MCP: admin", () => { | ||
| 272 | 272 | const admin = createToken(app.db, alice.id, "admin", "admin").token; |
| 273 | 273 | expect((await tool(bobRw, "mint_invite")).error).toContain("forbidden"); |
| 274 | 274 | expect((await tool(rw, "mint_invite")).error).toContain("admin token"); |
| 275 | expect((await tool(admin, "mint_invite", { days: 0 })).error).toContain("invalid"); | |
| 276 | const made = (await tool(admin, "mint_invite", { days: 3 })).value; | |
| 275 | expect((await tool(admin, "mint_invite", { org: 5 })).error).toContain("invalid"); | |
| 276 | const made = (await tool(admin, "mint_invite", {})).value; | |
| 277 | 277 | expect(made.link).toMatch(/\/signup\?invite=[\w-]+$/); |
| 278 | 278 | const token = made.link.split("invite=")[1]; |
| 279 | 279 | expect(made.token).toBeUndefined(); |
test/mcp-invites.test.ts +1 −1
| @@ -73,7 +73,7 @@ const signup = (username: string, invite: string) => | ||
| 73 | 73 | }); |
| 74 | 74 | |
| 75 | 75 | test("an admin mints, lists and revokes; a revoked link signs no one up", async () => { |
| 76 | const kept = (await tool(admin, "mint_invite", { days: 3 })).value; | |
| 76 | const kept = (await tool(admin, "mint_invite", {})).value; | |
| 77 | 77 | const gone = (await tool(admin, "mint_invite")).value; |
| 78 | 78 | const goneToken = gone.link.split("invite=")[1]; |
| 79 | 79 |
test/org-person-forge.test.ts +1 −1
| @@ -56,7 +56,7 @@ test("an invited person gets an account, not yet a forge that follows the organi | ||
| 56 | 56 | expect(listReposOwnedBy(app.db, org.value.id).map((r) => r.name)).toEqual(["board"]); |
| 57 | 57 | |
| 58 | 58 | // An invite is accepted. |
| 59 | const invite = mint(app, admin.value, 7); | |
| 59 | const invite = mint(app, admin.value); | |
| 60 | 60 | if (!invite.ok) throw new Error(invite.error); |
| 61 | 61 | const res = await fetch(`${servers.url}/signup?invite=${invite.value.token}`, { |
| 62 | 62 | method: "POST", |
test/perimeter-mediums.test.ts +2 −2
| @@ -50,7 +50,7 @@ describe("perimeter mediums (#2922)", () => { | ||
| 50 | 50 | const made = await post("/api/v1/repos", null, { name: "hooked", visibility: "public" }); |
| 51 | 51 | expect(made.status).toBe(201); |
| 52 | 52 | |
| 53 | const inviteFirst = await post("/api/v1/admin/invites", "m6-invite", { days: 3 }); | |
| 53 | const inviteFirst = await post("/api/v1/admin/invites", "m6-invite", {}); | |
| 54 | 54 | expect(inviteFirst.status).toBe(201); |
| 55 | 55 | const invite = (await inviteFirst.json()) as { token: string; link: string }; |
| 56 | 56 | expect(invite.link).toContain(invite.token); |
| @@ -62,7 +62,7 @@ describe("perimeter mediums (#2922)", () => { | ||
| 62 | 62 | const hook = (await hookFirst.json()) as { secret: string }; |
| 63 | 63 | expect(hook.secret.length).toBeGreaterThan(8); |
| 64 | 64 | |
| 65 | const replayedInvite = await (await post("/api/v1/admin/invites", "m6-invite", { days: 3 })).text(); | |
| 65 | const replayedInvite = await (await post("/api/v1/admin/invites", "m6-invite", {})).text(); | |
| 66 | 66 | const replayedHook = await (await post(hookPath, "m6-hook", hookBody)).text(); |
| 67 | 67 | const rows = (app.db.query("SELECT body FROM idempotency").all() as { body: string }[]).map((r) => r.body); |
| 68 | 68 | expect(rows.length).toBeGreaterThanOrEqual(2); |
test/request-access-limits.test.ts +2 −2
| @@ -94,7 +94,7 @@ describe("the Waiting list is bounded", () => { | ||
| 94 | 94 | expect(refused.status).toBe(403); |
| 95 | 95 | expect(getUserByName(app.db, "onetoomany")).toBeUndefined(); |
| 96 | 96 | |
| 97 | const token = mint(app, getUserByName(app.db, "ada"), 7); | |
| 97 | const token = mint(app, getUserByName(app.db, "ada")); | |
| 98 | 98 | if (!token.ok) throw new Error("no invite"); |
| 99 | 99 | const vouched = await api("vouched", { invite: token.value.token }); |
| 100 | 100 | expect(vouched.status).toBe(201); |
| @@ -167,7 +167,7 @@ describe("what an answer rests on", () => { | ||
| 167 | 167 | |
| 168 | 168 | test("an open invite vouches in request mode: no wait, and the invite is spent", async () => { |
| 169 | 169 | expect(getSignup(app.db)).toBe("request"); |
| 170 | const token = mint(app, getUserByName(app.db, "ada"), 7); | |
| 170 | const token = mint(app, getUserByName(app.db, "ada")); | |
| 171 | 171 | if (!token.ok) throw new Error("no invite"); |
| 172 | 172 | const res = await api("guest1", { invite: token.value.token }); |
| 173 | 173 | expect(res.status).toBe(201); |
test/signup-gate-parent.test.ts +1
| @@ -113,6 +113,7 @@ test("every caller of createUser says where its account comes from", async () => | ||
| 113 | 113 | "src/actions/contribute_token.ts": ["start"], |
| 114 | 114 | "src/actions/crew.ts": ["agent"], |
| 115 | 115 | "src/actions/first_admin.ts": ["first-admin"], |
| 116 | "src/actions/invite_link.ts": ["invite"], | |
| 116 | 117 | "src/actions/offer.ts": ["start"], |
| 117 | 118 | "src/actions/spawn.ts": ["spawn", "spawn"], |
| 118 | 119 | "src/actions/start.ts": ["start", "start"], |
test/spend-words.test.ts −8
| @@ -84,14 +84,6 @@ test("a ceiling out of range answers the module's sentence from the API and name | ||
| 84 | 84 | expect(viaMcp).toMatchObject({ error: true, text: expect.stringContaining(`invalid: ${SPEND_WORDS.ceilings}`) }); |
| 85 | 85 | }); |
| 86 | 86 | |
| 87 | test("an invite's days out of range answers the module's sentence from the API and names days over MCP", async () => { | |
| 88 | const viaApi = await api("/api/v1/admin/invites", { days: 31 }); | |
| 89 | expect(viaApi).toMatchObject({ status: 422, body: { error: "invalid", message: SPEND_WORDS.inviteDays } }); | |
| 90 | const viaMcp = await tool("mint_invite", { days: 31 }); | |
| 91 | // The MCP holds `days` to its schema's 1 to 30 before the tool runs, naming the argument. | |
| 92 | expect(viaMcp).toMatchObject({ error: true, text: expect.stringContaining('invalid: argument "days" is 31; expected integer from 1 to 30') }); | |
| 93 | }); | |
| 94 | ||
| 95 | 87 | test("no file under src/ but the module types the sentences out", async () => { |
| 96 | 88 | const root = join(import.meta.dir, "..", "src"); |
| 97 | 89 | const files = (await readdir(root, { recursive: true })).filter((f) => f.endsWith(".ts")); |
test/start.test.ts +1 −1
| @@ -181,7 +181,7 @@ describe("the defenses", () => { | ||
| 181 | 181 | setAgentStart(forge.app.db, "code", admin.id); |
| 182 | 182 | expect((await post("/api/v1/start", { name: "nope" }, {}, "198.51.100.40")).status).toBe(403); |
| 183 | 183 | expect((await post("/api/v1/start", { name: "nope", code: "wrong" }, {}, "198.51.100.40")).status).toBe(403); |
| 184 | const invite = mintInvite(forge.app.db, admin.id, 7); | |
| 184 | const invite = mintInvite(forge.app.db, admin.id); | |
| 185 | 185 | const ok = await post("/api/v1/start", { name: "coded", code: invite.token }, {}, "198.51.100.40"); |
| 186 | 186 | expect(ok.status).toBe(201); |
| 187 | 187 | expect((await post("/api/v1/start", { name: "coded2", code: invite.token }, {}, "198.51.100.41")).status).toBe(403); |
test/tui-invites.test.ts −17
| @@ -82,7 +82,6 @@ describe("invite links in the terminal", () => { | ||
| 82 | 82 | await open(h); |
| 83 | 83 | expect(h.text()).toContain("No invite link yet"); |
| 84 | 84 | await h.press("m"); |
| 85 | await h.press("enter"); | |
| 86 | 85 | expect(h.text()).toContain("What the invite allows"); |
| 87 | 86 | await h.press("enter"); |
| 88 | 87 | expect(forge.config.url).toBeUndefined(); |
| @@ -135,7 +134,6 @@ describe("invite links in the terminal", () => { | ||
| 135 | 134 | await open(h); |
| 136 | 135 | await h.press("m"); |
| 137 | 136 | await h.press("enter"); |
| 138 | await h.press("enter"); | |
| 139 | 137 | const made = listInvites(forge.db).find((i) => i.state === "open")!; |
| 140 | 138 | for (const k of ["n", "esc"]) { |
| 141 | 139 | await h.press("x"); |
| @@ -149,30 +147,15 @@ describe("invite links in the terminal", () => { | ||
| 149 | 147 | h.stop(); |
| 150 | 148 | }); |
| 151 | 149 | |
| 152 | test("days outside 1 to 30 make nothing", async () => { | |
| 153 | const before = listInvites(forge.db).length; | |
| 154 | const h = boot("alice"); | |
| 155 | await open(h); | |
| 156 | await h.press("m"); | |
| 157 | await h.press("backspace"); | |
| 158 | await h.type("0"); | |
| 159 | await h.press("enter"); | |
| 160 | expect(h.text()).toContain("1 to 30"); | |
| 161 | expect(listInvites(forge.db).length).toBe(before); | |
| 162 | h.stop(); | |
| 163 | }); | |
| 164 | ||
| 165 | 150 | test("Build is picked in the terminal; Host with no machine says why and mints nothing", async () => { |
| 166 | 151 | const before = listInvites(forge.db).length; |
| 167 | 152 | const h = boot("alice"); |
| 168 | 153 | await open(h); |
| 169 | 154 | await h.press("m"); |
| 170 | await h.press("enter"); | |
| 171 | 155 | await h.press("down", "down", "enter"); |
| 172 | 156 | expect(listInvites(forge.db).length).toBe(before + 1); |
| 173 | 157 | expect(listInvites(forge.db)[0]!.bundle).toBe("build"); |
| 174 | 158 | await h.press("m"); |
| 175 | await h.press("enter"); | |
| 176 | 159 | await h.press("down", "enter"); |
| 177 | 160 | expect(h.text()).toContain("Host needs a machine this forge can offer"); |
| 178 | 161 | expect(listInvites(forge.db).length).toBe(before + 1); |
test/tui-signup-invite.test.ts +4 −4
| @@ -84,7 +84,7 @@ describe("terminal sign-up with an invite", () => { | ||
| 84 | 84 | }); |
| 85 | 85 | |
| 86 | 86 | test("an expired token says so kindly and names who sent it", async () => { |
| 87 | const { token } = mintInvite(forge.db, adminId, 1, Date.now() - 3 * 86_400_000); | |
| 87 | const { token } = mintInvite(forge.db, adminId, Date.now() - 4 * 86_400_000); | |
| 88 | 88 | const text = await attempt("tardy", token); |
| 89 | 89 | expect(text).toContain("This link has expired"); |
| 90 | 90 | expect(text).toContain("alice"); |
| @@ -93,7 +93,7 @@ describe("terminal sign-up with an invite", () => { | ||
| 93 | 93 | }); |
| 94 | 94 | |
| 95 | 95 | test("a pasted open token says when it works until, before anything is submitted", async () => { |
| 96 | const { token } = mintInvite(forge.db, adminId, 3); | |
| 96 | const { token } = mintInvite(forge.db, adminId); | |
| 97 | 97 | const text = await attempt("early", token, false); |
| 98 | 98 | expect(text).toContain("This link works until"); |
| 99 | 99 | expect(getUserByName(forge.db, "early")).toBeFalsy(); |
| @@ -101,7 +101,7 @@ describe("terminal sign-up with an invite", () => { | ||
| 101 | 101 | }); |
| 102 | 102 | |
| 103 | 103 | test("a pasted expired token says so on the invite step, before submit", async () => { |
| 104 | const { token } = mintInvite(forge.db, adminId, 1, Date.now() - 3 * 86_400_000); | |
| 104 | const { token } = mintInvite(forge.db, adminId, Date.now() - 4 * 86_400_000); | |
| 105 | 105 | const text = await attempt("early2", token, false); |
| 106 | 106 | expect(text).toContain("This link has expired"); |
| 107 | 107 | forge.db.query("DELETE FROM invite WHERE expires_at < ?1").run(new Date().toISOString()); |
| @@ -153,7 +153,7 @@ describe("terminal sign-up with an invite", () => { | ||
| 153 | 153 | const plain = await attempt("plainly", mintInvite(forge.db, adminId).token, true, KEY2); |
| 154 | 154 | expect(getUserByName(forge.db, "plainly")).toBeTruthy(); |
| 155 | 155 | expect(plain).not.toContain("Welcome to"); |
| 156 | const { token } = mintInvite(forge.db, adminId, 7, Date.now(), org.value.id); | |
| 156 | const { token } = mintInvite(forge.db, adminId, Date.now(), org.value.id); | |
| 157 | 157 | const text = await attempt("orgy", token, true, KEY3); |
| 158 | 158 | expect(getUserByName(forge.db, "orgy")).toBeTruthy(); |
| 159 | 159 | expect(text).toContain("Welcome to acme"); |
test/who-can.test.ts +2 −1
| @@ -74,6 +74,7 @@ describe("who may do what", () => { | ||
| 74 | 74 | sql("INSERT INTO origin_read_grant (repo_id, kind, grantee_id, granted_by) VALUES (?1, 'crew', ?2, ?3)", repo.value.id, dave, id("alice")); |
| 75 | 75 | sql("INSERT INTO pull_run_grant (issue_id, commit_oid, user_id) VALUES (?1, 'abcdef0123456789', ?2)", issue.value.id, dave); |
| 76 | 76 | sql("INSERT INTO telemetry_grant (user_id, granted_by) VALUES (?1, ?2)", dave, id("alice")); |
| 77 | sql("INSERT INTO host_grant (user_id, machine, containers, memory_mb, invite_id, at) VALUES (?1, 'm1', 2, 512, 'inv1', ?2)", dave, at); | |
| 77 | 78 | createClientCloud(app.db, dir, { provider: "aws", label: "client-aws", key: "k", days: 3, by: id("alice"), now: new Date(at) }); |
| 78 | 79 | sql("INSERT INTO client_cloud_member (cloud_id, user_id, granted_by, granted_at) SELECT id, ?1, ?2, ?3 FROM client_cloud", dave, id("alice"), at); |
| 79 | 80 | sql("INSERT INTO crew_team_member (team_slug, user_id) VALUES ('design', ?1)", dave); |
| @@ -90,7 +91,7 @@ describe("who may do what", () => { | ||
| 90 | 91 | test("one grant in each table, and the view lists every one", () => { |
| 91 | 92 | const seen = new Set(everyGrant(app.db).map((g) => g.table)); |
| 92 | 93 | expect([...GRANT_TABLES].filter((t) => !seen.has(t))).toEqual([]); |
| 93 | expect(GRANT_TABLES.length).toBe(16); | |
| 94 | expect(GRANT_TABLES.length).toBe(17); | |
| 94 | 95 | }); |
| 95 | 96 | |
| 96 | 97 | test("by person: everything dave can reach, with who granted it and where it is changed", () => { |
new above
offline