Public: anyone can read this; the crew can change it.
One People page at /settings/people: Invite on top, a person is one row of what they can do, each with Remove #18514
Merged 3h 14m ago, live in production
scout/forge:scout/18476-one-people-page-at-settings-people-invit → main 0 commits fork
55 files
changed +1053
−389
- docs/design/quiet-debt.json
- docs/features/account-access.md
- docs/features/people.md
- docs/features/welcome.md
- scripts/multiline-rows.json
- src/actions/account_close.ts
- src/actions/invites.ts
- src/actions/requests.ts
- src/actions/take_away.ts
- src/core/accounts.ts
- src/core/event_audience.ts
- src/core/grant_removal.ts
- src/core/invites.ts
- src/core/migration-pins/20261206110000-invite-sealed-link.pin
- src/core/migrations/20261206110000-invite-sealed-link.ts
- src/core/orgs.ts
- src/core/proven_identities.ts
- src/crew/routine_report.ts
- src/design/door_checks.ts
- src/http/lazy_lists.ts
- src/http/marks/settings.json
- src/http/settings_routes.ts
- src/tui/screens/invites.ts
- src/tui/screens/people.ts
- src/web/form.ts
- src/web/pages/accounts.ts
- src/web/pages/admin-limits.ts
- src/web/pages/knobs.ts
- src/web/pages/origins.ts
- src/web/pages/people.ts
- src/web/pages/people_cards.ts
- src/web/pages/people_invites.ts
- src/web/requests_card.ts
- src/web/style/content.ts
- test/account-access.test.ts
- test/account-close.test.ts
- test/accounts-language.test.ts
- test/accounts-rows.test.ts
- test/accounts-timing.test.ts
- test/accounts.test.ts
- test/invites-core.test.ts
- test/keys-accounts.test.ts
- test/keys-people-list.test.ts
- test/no-mail-contribute.test.ts
- test/org-owners.test.ts
- test/own-session.test.ts
- test/pages-budget.test.ts
- test/people-apps-made.test.ts
- test/people-fit.test.ts
- test/people-page.test.ts
- test/people-rows.test.ts
- test/people-take-door.test.ts
- test/request-access.test.ts
- test/server-timing-sweep.test.ts
- test/sole-owner-suspend.test.ts
docs/design/quiet-debt.json +1 −1
docs/features/account-access.md +1 −1
| @@ -4,7 +4,7 @@ row: Manage account: reset a person's access | ||
| 4 | 4 | --- |
| 5 | 5 | # Manage account: reset a person's access |
| 6 | 6 | |
| 7 | An admin opens a person's page (`/settings/accounts/<name>`, linked as **Manage account** from their profile and from `/settings/accounts`, which searches by name) and sees, on one screen: role and join date, email and whether it is verified, passkey count and whether a password is set (never the secrets), the browsers they are signed in on now (when, from where; a person's sign-in history is not kept), what they own, their model allowance and ceilings, and the actions. | |
| 7 | An admin opens a person's page (`/settings/accounts/<name>`, linked as **Manage** from their profile and from `/settings/people`, which searches by name) and sees, on one screen: role and join date, email and whether it is verified, passkey count and whether a password is set (never the secrets), the browsers they are signed in on now (when, from where; a person's sign-in history is not kept), what they own, their model allowance and ceilings, and the actions. | |
| 8 | 8 | |
| 9 | 9 | - **Reset access** (after a confirm) makes a link, `/signin/access/<secret>`, good for one hour and one use. The person opens it, sets a new password (the admin never sees or sets it) and is signed in, then can add a passkey at `/settings/passkeys`. The admin copies the link from the page; when the forge can send mail and the address is verified, it is mailed too. Tick *Also sign them out everywhere* to end every browser in the same step. A new link withdraws the older ones. Only the link's hash is kept. The page shows "This link works until <date>"; a link past its hour answers 410 "This link has expired" with one next step, asking the sender. |
| 10 | 10 | - **End all sessions** (after a confirm) signs them out of every browser and does nothing else. |
docs/features/people.md +7 −12
| @@ -1,18 +1,13 @@ | ||
| 1 | 1 | --- |
| 2 | topic: Tell the crew | |
| 3 | row: Everyone with an account, last seen first | |
| 2 | topic: Every setting, by topic | |
| 3 | row: People: invite, who is here and what each can do, one line each with Remove | |
| 4 | 4 | --- |
| 5 | 5 | # People |
| 6 | 6 | |
| 7 | `/settings/people` (an owner's page) lists everyone with an account, the person seen most recently first and | |
| 8 | never-seen last. Each row has the name, a plain word for the role — owner, member, guest or crew member — the | |
| 9 | monthly allowance, when they were last seen (a browser session's last request or a token's last use) and their apps. | |
| 10 | One line of filters (`?role=owner|member|guest|crew`) narrows the list; a filter that names nobody says "Nobody here." | |
| 7 | `/settings/people` (an admin's page, `src/web/pages/people.ts`) is the one place for who is on this forge. `/settings/accounts` redirects to it. | |
| 11 | 8 | |
| 12 | Try it: open `/settings/people`, follow **guests**, then give a guest a starter allowance with **Make member**. | |
| 9 | - **Invite** is on top (`src/web/pages/people_invites.ts`): days, an organization if any, and what the link allows (Use, Host or Build). A waiting invite's row shows its link to copy: the forge keeps the token sealed under its key (`invite.token_sealed`, cleared when the invite is used or taken back) and only an admin reads it; a signup is still found by the hash. Each invite is a row with its state: waiting, used (by whom, when), expired or taken back. **Send again** (on an expired or taken-back one) makes a fresh link like it; **Revoke** takes a waiting one back. | |
| 10 | - **Mail**: one line says whether this forge can send mail. Without it a newcomer cannot prove an address until you verify them (`src/web/pages/people_cards.ts`, with who waits to be let in and who could not sign in without the platform edge). | |
| 11 | - **A person** is one row: their role badge, when they were seen, how their account was proved and by whom (a fact for each thing proved), then, under it, one line for each thing they can do (every grant, `src/core/grants_view.ts`). **Remove** on a line takes just that away, in place: the person's block is fetched again from `/settings/people/row/<name>`. Removable lines: membership, the model allowance, reading telemetry and one app they were let into (`src/actions/take_away.ts`, asked through `may("forge.administer")`). Other lines link to where they are changed. An owner keeps what they have, so the forge is never left without one. **Manage** opens the person's page (`/settings/accounts/<name>`: sign-ins, ceilings, suspend, verify, remove the account). | |
| 13 | 12 | |
| 14 | The terminal (both doors): Palette › People shows the same rows in the same order, from the same query | |
| 15 | (`peopleByActivity` in `src/core/people_rows.ts`). `f` steps the filter through everyone, owner, member, guest and | |
| 16 | crew member; `r` changes a role, `s` suspends or lifts, `v` verifies an email, as before. | |
| 17 | ||
| 18 | Pinned by `test/people-rows.test.ts` and `test/tui-people-activity.test.ts`. | |
| 13 | In the terminal, People (`src/tui/screens/people.ts`) takes one thing away with `x` (a name, then `member`, `model_grant` or `telemetry_grant`, or `app` and the app's name). Invite links (`src/tui/screens/invites.ts`) lists each invite with its state; `c` shows a waiting link, `n` makes a new one like the selected (Send again), `x` revokes. Mail is said only when it cannot be sent. |
docs/features/welcome.md +1 −1
| @@ -34,4 +34,4 @@ The terminal does not reach `/welcome`: it is the screen where the first account | ||
| 34 | 34 | |
| 35 | 35 | ## A forge that sends no mail |
| 36 | 36 | |
| 37 | A forge with no mail configured (neither `MAIL_SMTP_URL` and `MAIL_FROM` under Secrets nor the boot settings) cannot ask a newcomer to prove an address. So an unverified account there may **fork a public repository and open a pull**, and nothing else that costs: creating a repository, running agents and the rest still wait for **Verify** by the owner (`requireVerified`; the relaxed check is `mayContribute`, `src/actions/verify.ts`). The new-account cooldown and the daily fork and pull limits still hold. `/settings/accounts` and the terminal's People screen say so and mark who is unverified. With mail configured, an unverified account is refused fork and pull as before (#12106). | |
| 37 | A forge with no mail configured (neither `MAIL_SMTP_URL` and `MAIL_FROM` under Secrets nor the boot settings) cannot ask a newcomer to prove an address. So an unverified account there may **fork a public repository and open a pull**, and nothing else that costs: creating a repository, running agents and the rest still wait for **Verify** by the owner (`requireVerified`; the relaxed check is `mayContribute`, `src/actions/verify.ts`). The new-account cooldown and the daily fork and pull limits still hold. `/settings/people` and the terminal's People screen say so and mark who is unverified. With mail configured, an unverified account is refused fork and pull as before (#12106). |
scripts/multiline-rows.json +1
| @@ -26,6 +26,7 @@ | ||
| 26 | 26 | "/settings/features": ["src/web/pages/features.ts"], |
| 27 | 27 | "/settings/model": ["src/web/pages/connections.ts"], |
| 28 | 28 | "/settings/origins": ["src/web/scope.ts"], |
| 29 | "/settings/people": ["src/web/pages/people.ts", "src/web/pages/people_invites.ts"], | |
| 29 | 30 | "/settings/runners": ["src/web/pages/runners.ts"], |
| 30 | 31 | "/settings/traffic": ["src/web/pages/visitors.ts"], |
| 31 | 32 | "/templates": ["src/web/template_card.ts"] |
src/actions/account_close.ts +1 −1
| @@ -66,7 +66,7 @@ export function closeRefusal(db: Database, user: { id: string; email: string; is | ||
| 66 | 66 | return { |
| 67 | 67 | reason: "sole_admin", |
| 68 | 68 | says: "You are this forge's only admin: make someone else an admin first.", |
| 69 | link: { href: "/settings/accounts", label: "Accounts" }, | |
| 69 | link: { href: "/settings/people", label: "People" }, | |
| 70 | 70 | }; |
| 71 | 71 | const org = sharedOrg(db, user.id); |
| 72 | 72 | if (org !== undefined) |
src/actions/invites.ts +32
| @@ -10,6 +10,7 @@ import { | ||
| 10 | 10 | isContributor, |
| 11 | 11 | listContributors, |
| 12 | 12 | listInvites, |
| 13 | keepToken, | |
| 13 | 14 | mintInvite, |
| 14 | 15 | mintRepoInvite, |
| 15 | 16 | redeemInvite, |
| @@ -19,6 +20,7 @@ import { | ||
| 19 | 20 | repoOfInvite, |
| 20 | 21 | revokeInvite, |
| 21 | 22 | revokeRepoInvite, |
| 23 | sealedTokenOf, | |
| 22 | 24 | type Invite, |
| 23 | 25 | type RepoInvite, |
| 24 | 26 | } from "../core/invites.ts"; |
| @@ -29,6 +31,7 @@ import { getOrg } from "../core/orgs.ts"; | ||
| 29 | 31 | import { BUNDLES, HOST_WORDS, parseHost, type Bundle } from "../core/bundles.ts"; |
| 30 | 32 | import { infraOf, offeredView, type InfraView } from "./infra.ts"; |
| 31 | 33 | import { err, ok, type Result } from "../kernel/result.ts"; |
| 34 | import { open, seal } from "../kernel/secret.ts"; | |
| 32 | 35 | import type { User } from "../core/users.ts"; |
| 33 | 36 | |
| 34 | 37 | type Error = "not_found" | "unknown_org" | "invalid_bundle" | "no_machine" | "invalid_machine" | "invalid_cap"; |
| @@ -103,6 +106,7 @@ export function mint(app: App, actor: User | undefined, org?: unknown, choice: B | ||
| 103 | 106 | host = h.value; |
| 104 | 107 | } |
| 105 | 108 | const made = mintInvite(app.db, actor.id, Date.now(), target?.id ?? null, bundle, host); |
| 109 | keepToken(app.db, made.invite.id, seal(app.config.dataDir, made.token, `invite:${made.invite.id}`)); | |
| 106 | 110 | app.bus.append({ |
| 107 | 111 | kind: "invite.minted", |
| 108 | 112 | actorId: actor.id, |
| @@ -111,6 +115,34 @@ export function mint(app: App, actor: User | undefined, org?: unknown, choice: B | ||
| 111 | 115 | return ok(made); |
| 112 | 116 | } |
| 113 | 117 | |
| 118 | /** | |
| 119 | * The token of a waiting invite, for an admin to copy; undefined once it is spent, taken back or | |
| 120 | * old. | |
| 121 | */ | |
| 122 | export function tokenOf(app: App, actor: User | undefined, inviteId: string): string | undefined { | |
| 123 | if (!admin(actor)) return undefined; | |
| 124 | const sealed = sealedTokenOf(app.db, inviteId); | |
| 125 | if (sealed === null) return undefined; | |
| 126 | const opened = open(app.config.dataDir, sealed, `invite:${inviteId}`); | |
| 127 | return opened.ok ? opened.value : undefined; | |
| 128 | } | |
| 129 | ||
| 130 | /** | |
| 131 | * A fresh link like an expired or taken-back (or waiting) invite: the same bundle and organization; | |
| 132 | * a waiting one is taken back. Every door's "Send again". | |
| 133 | */ | |
| 134 | export function again(app: App, actor: User | undefined, inviteId: string): Result<{ invite: Invite; token: string }, Error> { | |
| 135 | const listed = list(app, actor); | |
| 136 | const old = listed.ok ? listed.value.find((i) => i.id === inviteId && i.state !== "used") : undefined; | |
| 137 | if (old === undefined) return err("not_found"); | |
| 138 | const made = mint(app, actor, old.org ?? undefined, { | |
| 139 | bundle: old.bundle, | |
| 140 | ...(old.host === null ? {} : { machine: old.host.machine, containers: old.host.containers, memoryMb: old.host.memoryMb }), | |
| 141 | }); | |
| 142 | if (made.ok && old.state === "open") revoke(app, actor, old.id); | |
| 143 | return made; | |
| 144 | } | |
| 145 | ||
| 114 | 146 | export function list(app: App, actor: User | undefined): Result<Invite[], "not_found"> { |
| 115 | 147 | return admin(actor) ? ok(listInvites(app.db)) : err("not_found"); |
| 116 | 148 | } |
src/actions/requests.ts +1 −1
| @@ -75,7 +75,7 @@ export function requestLines( | ||
| 75 | 75 | user: User, |
| 76 | 76 | ): { id: string; line: string; items: readonly string[]; link: string }[] { |
| 77 | 77 | if (!user.isAdmin || user.kind !== "user") return []; |
| 78 | const link = "/settings/accounts#waiting"; | |
| 78 | const link = "/settings/people#waiting"; | |
| 79 | 79 | const waiting = waitingRequests(db); |
| 80 | 80 | if (waiting.length > LINES_EACH) { |
| 81 | 81 | const id = `request:many:${Math.ceil(waiting.length / 25)}`; |
src/actions/take_away.ts added +38
| @@ -0,0 +1,38 @@ | ||
| 1 | /** | |
| 2 | * Remove one thing a person can do (a line on the People page): their | |
| 3 | * membership, their model allowance, their telemetry reading or one app they | |
| 4 | * were let into. Asked through `may("forge.administer")`; an owner keeps what | |
| 5 | * they have, so the last owner can never be left without the forge. An event | |
| 6 | * says who took what from whom. | |
| 7 | */ | |
| 8 | ||
| 9 | import type { App } from "../app.ts"; | |
| 10 | import { isRemovable, removeGrant, type Removable } from "../core/grant_removal.ts"; | |
| 11 | import { may } from "../core/may.ts"; | |
| 12 | import { principalOfUser } from "../core/principal.ts"; | |
| 13 | import { getUserByName, type User } from "../core/users.ts"; | |
| 14 | import { err, ok, type Result } from "../kernel/result.ts"; | |
| 15 | ||
| 16 | type TakeAwayError = "not_found" | "not_allowed" | "not_removable"; | |
| 17 | ||
| 18 | export const TAKE_AWAY_WORDS: Record<Exclude<TakeAwayError, "not_found">, string> = { | |
| 19 | not_allowed: "An owner keeps what they have, so the forge is never left without one. Crew members are changed on their repository.", | |
| 20 | not_removable: "That line is changed on its own page: follow its link.", | |
| 21 | }; | |
| 22 | ||
| 23 | export function takeAway( | |
| 24 | app: App, | |
| 25 | actor: User | undefined, | |
| 26 | username: string, | |
| 27 | table: string, | |
| 28 | key: string, | |
| 29 | ): Result<{ username: string; table: Removable }, TakeAwayError> { | |
| 30 | if (actor === undefined || actor.kind !== "user" || !may(app.db, principalOfUser(actor), "forge.administer").ok) return err("not_found"); | |
| 31 | const user = getUserByName(app.db, username); | |
| 32 | if (user === undefined || user.kind === "org") return err("not_found"); | |
| 33 | if (user.kind === "agent" || user.isAdmin) return err("not_allowed"); | |
| 34 | if (!isRemovable(table)) return err("not_removable"); | |
| 35 | if (!removeGrant(app.db, table, user.id, key.slice(0, 200), actor.id)) return err("not_found"); | |
| 36 | app.bus.append({ kind: "grant.removed", actorId: actor.id, payload: { username: user.username, table } }); | |
| 37 | return ok({ username: user.username, table }); | |
| 38 | } |
src/core/accounts.ts +9 −1
| @@ -16,6 +16,10 @@ import { forgetListings } from "./listings.ts"; | ||
| 16 | 16 | import { provenEmailAt } from "./proven_identities.ts"; |
| 17 | 17 | |
| 18 | 18 | export interface AccountRow { |
| 19 | readonly id: string; | |
| 20 | /** The address on the account, and when it was proved (null while unproven). */ | |
| 21 | readonly email: string; | |
| 22 | readonly provenAt: string | null; | |
| 19 | 23 | readonly username: string; |
| 20 | 24 | readonly kind: "user" | "agent"; |
| 21 | 25 | readonly displayName: string; |
| @@ -54,6 +58,7 @@ export function listAccounts(db: Database, only = ""): AccountRow[] { | ||
| 54 | 58 | .query< |
| 55 | 59 | { |
| 56 | 60 | id: string; |
| 61 | email: string; | |
| 57 | 62 | username: string; |
| 58 | 63 | display_name: string; |
| 59 | 64 | is_admin: number; |
| @@ -70,7 +75,7 @@ export function listAccounts(db: Database, only = ""): AccountRow[] { | ||
| 70 | 75 | }, |
| 71 | 76 | [string] |
| 72 | 77 | >( |
| 73 | `SELECT u.id, u.username, u.display_name, u.is_admin, u.is_agent, | |
| 78 | `SELECT u.id, u.email, u.username, u.display_name, u.is_admin, u.is_agent, | |
| 74 | 79 | u.created_at, u.suspended_at, u.removed_at, u.waiting_at, |
| 75 | 80 | ${provenEmailAt("u")} AS proven_at, |
| 76 | 81 | (SELECT COUNT(*) FROM repo r WHERE r.owner_id = u.id) AS repos, |
| @@ -88,6 +93,9 @@ export function listAccounts(db: Database, only = ""): AccountRow[] { | ||
| 88 | 93 | return rows.map((r) => { |
| 89 | 94 | const origin = parseOrigin(r.payload); |
| 90 | 95 | return { |
| 96 | id: r.id, | |
| 97 | email: r.email, | |
| 98 | provenAt: r.proven_at, | |
| 91 | 99 | username: r.username, |
| 92 | 100 | kind: r.is_agent === 1 ? "agent" : "user", |
| 93 | 101 | displayName: r.display_name, |
src/core/event_audience.ts +2
| @@ -244,6 +244,8 @@ export function classifiedAudience(kind: string): EventAudience | undefined { | ||
| 244 | 244 | if (kind === "webhook.failing") return "writers"; |
| 245 | 245 | // What a repository's beat did says how its autonomy and week's share stand (`crew/beat.ts`). |
| 246 | 246 | if (kind === "beat.ran") return "writers"; |
| 247 | // Who took which grant from whom is the admins' record (`actions/take_away.ts`). | |
| 248 | if (kind === "grant.removed") return "admins"; | |
| 247 | 249 | if ( |
| 248 | 250 | kind.startsWith("webhook.") || |
| 249 | 251 | kind.startsWith("app.env_") || |
src/core/grant_removal.ts added +52
| @@ -0,0 +1,52 @@ | ||
| 1 | /** | |
| 2 | * Taking one grant away from a person: the few grants a line on the People | |
| 3 | * page can remove, each one statement. Pure data; `actions/take_away.ts` | |
| 4 | * decides who may ask. `key` names the resource where a person holds more | |
| 5 | * than one of a kind (an app's id); the rest are one a person. | |
| 6 | */ | |
| 7 | ||
| 8 | import type { Database } from "bun:sqlite"; | |
| 9 | import { revoke as revokeTelemetry } from "./telemetry.ts"; | |
| 10 | import { setMember } from "./roles.ts"; | |
| 11 | ||
| 12 | /** The grant tables a line can remove, by name. */ | |
| 13 | const REMOVABLE = ["member", "model_grant", "telemetry_grant", "app_member"] as const; | |
| 14 | export type Removable = (typeof REMOVABLE)[number]; | |
| 15 | ||
| 16 | /** The names a terminal asks for, in one line. */ | |
| 17 | export const REMOVABLE_WORDS = `${REMOVABLE.filter((t) => t !== "app_member").join(", ")}, or app and its name`; | |
| 18 | ||
| 19 | export const isRemovable = (table: unknown): table is Removable => REMOVABLE.includes(table as Removable); | |
| 20 | ||
| 21 | /** | |
| 22 | * The id of the app named `repo` (a repository name) that `userId` was let into, or "" when none. | |
| 23 | */ | |
| 24 | export function appLetInto(db: Database, userId: string, repo: string): string { | |
| 25 | return ( | |
| 26 | db | |
| 27 | .query<{ app_id: string }, [string, string]>( | |
| 28 | "SELECT m.app_id FROM app_member m JOIN app a ON a.id = m.app_id JOIN repo r ON r.id = a.repo_id WHERE m.user_id = ?1 AND r.name = ?2 ORDER BY m.app_id LIMIT 1", | |
| 29 | ) | |
| 30 | .get(userId, repo)?.app_id ?? "" | |
| 31 | ); | |
| 32 | } | |
| 33 | ||
| 34 | /** Whether a row was there and is gone. */ | |
| 35 | export function removeGrant(db: Database, table: Removable, userId: string, key: string, actorId: string): boolean { | |
| 36 | switch (table) { | |
| 37 | case "member": { | |
| 38 | const had = db.query("SELECT 1 AS n FROM member WHERE user_id = ?1").get(userId) !== null; | |
| 39 | setMember(db, userId, false, actorId, new Date()); | |
| 40 | return had; | |
| 41 | } | |
| 42 | case "model_grant": | |
| 43 | return db.query("DELETE FROM model_grant WHERE user_id = ?1").run(userId).changes > 0; | |
| 44 | case "telemetry_grant": { | |
| 45 | const had = db.query("SELECT 1 AS n FROM telemetry_grant WHERE user_id = ?1").get(userId) !== null; | |
| 46 | revokeTelemetry(db, userId); | |
| 47 | return had; | |
| 48 | } | |
| 49 | case "app_member": | |
| 50 | return db.query("DELETE FROM app_member WHERE app_id = ?1 AND user_id = ?2").run(key, userId).changes > 0; | |
| 51 | } | |
| 52 | } |
src/core/invites.ts +23 −7
| @@ -1,11 +1,11 @@ | ||
| 1 | 1 | /** |
| 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 | * give a link back, and a token is found by its hash: nothing compares the | |
| 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`). | |
| 4 | * give a link back (an admin's copy of a waiting one is sealed apart, `token_sealed`), and a token | |
| 5 | * is found by its hash: nothing compares the secret itself. In every signup mode, `invite` and | |
| 6 | * `closed` included, a 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 account | |
| 8 | * (`redeemInvite`), which also applies its bundle (`core/bundle_grants.ts`). | |
| 9 | 9 | */ |
| 10 | 10 | |
| 11 | 11 | import type { Database } from "bun:sqlite"; |
| @@ -113,6 +113,22 @@ export function mintInvite( | ||
| 113 | 113 | return { invite: view(row, now), token }; |
| 114 | 114 | } |
| 115 | 115 | |
| 116 | /** Keep a sealed copy of an invite's token, for an admin to copy while it waits. */ | |
| 117 | export function keepToken(db: Database, inviteId: string, sealed: string): void { | |
| 118 | db.query("UPDATE invite SET token_sealed = ?2 WHERE id = ?1").run(inviteId, sealed); | |
| 119 | } | |
| 120 | ||
| 121 | /** The sealed copy of an invite that is still open, or null. */ | |
| 122 | export function sealedTokenOf(db: Database, inviteId: string, now: number = Date.now()): string | null { | |
| 123 | return ( | |
| 124 | db | |
| 125 | .query<{ t: string | null }, [string, string]>( | |
| 126 | "SELECT token_sealed AS t FROM invite WHERE id = ?1 AND used_at IS NULL AND revoked_at IS NULL AND expires_at > ?2", | |
| 127 | ) | |
| 128 | .get(inviteId, new Date(now).toISOString())?.t ?? null | |
| 129 | ); | |
| 130 | } | |
| 131 | ||
| 116 | 132 | /** Whether `token` names an invite still open now: not used, revoked or expired. */ |
| 117 | 133 | export function inviteOpen(db: Database, token: string, now: number = Date.now()): boolean { |
| 118 | 134 | return ( |
| @@ -134,7 +150,7 @@ export function redeemInvite(db: Database, token: string, userId: string, now: n | ||
| 134 | 150 | return ( |
| 135 | 151 | db |
| 136 | 152 | .query( |
| 137 | "UPDATE invite SET used_at = ?2, used_by = ?3 WHERE token_hash = ?1 AND used_at IS NULL AND revoked_at IS NULL AND expires_at > ?2", | |
| 153 | "UPDATE invite SET used_at = ?2, used_by = ?3, token_sealed = NULL WHERE token_hash = ?1 AND used_at IS NULL AND revoked_at IS NULL AND expires_at > ?2", | |
| 138 | 154 | ) |
| 139 | 155 | .run(sha256(token), at, userId).changes === 1 |
| 140 | 156 | ); |
| @@ -171,7 +187,7 @@ export function revokeInvite( | ||
| 171 | 187 | now: number = Date.now(), |
| 172 | 188 | ): Result<Invite, "not_found"> { |
| 173 | 189 | const changed = db |
| 174 | .query("UPDATE invite SET revoked_at = ?2 WHERE id = ?1 AND revoked_at IS NULL AND used_at IS NULL") | |
| 190 | .query("UPDATE invite SET revoked_at = ?2, token_sealed = NULL WHERE id = ?1 AND revoked_at IS NULL AND used_at IS NULL") | |
| 175 | 191 | .run(inviteId, new Date(now).toISOString()).changes; |
| 176 | 192 | if (changed === 0) return err("not_found"); |
| 177 | 193 | return ok(view(db.query<Row, [string]>(`${SELECT} WHERE invite.id = ?1`).get(inviteId)!, now)); |
src/core/migration-pins/20261206110000-invite-sealed-link.pin added +1
| @@ -0,0 +1,1 @@ | ||
| 1 | d1c61055ca625747d0fb1e0ba892938dfdc0b7acc75ea38e3bbc0d3384d51061 |
src/core/migrations/20261206110000-invite-sealed-link.ts added +6
src/core/orgs.ts +11
| @@ -276,6 +276,17 @@ export function soleOwnedOrgs(db: Database, userId: string): User[] { | ||
| 276 | 276 | .filter((u): u is User => u !== undefined); |
| 277 | 277 | } |
| 278 | 278 | |
| 279 | /** Every organization with exactly one active owner, by that owner's id: the page's one read. */ | |
| 280 | export function soleOwnedByPerson(db: Database): Map<string, string[]> { | |
| 281 | const by = new Map<string, string[]>(); | |
| 282 | const orgs = db.query<{ id: string; username: string }, []>("SELECT id, username FROM user WHERE kind = 'org' AND removed_at IS NULL ORDER BY username").all(); | |
| 283 | for (const o of orgs) { | |
| 284 | const owners = personOwners(db, o.id); | |
| 285 | if (owners.length === 1) by.set(owners[0]!, [...(by.get(owners[0]!) ?? []), o.username]); | |
| 286 | } | |
| 287 | return by; | |
| 288 | } | |
| 289 | ||
| 279 | 290 | /** |
| 280 | 291 | * Remove a member, refusing to take the last person off the Owners team: an |
| 281 | 292 | * organization needs someone who can administer it, and an agent never can. |
src/core/proven_identities.ts +15
| @@ -81,6 +81,21 @@ export const minecraftIdentities = (db: Database, userId: string): Identity[] => | ||
| 81 | 81 | }), |
| 82 | 82 | ); |
| 83 | 83 | |
| 84 | /** | |
| 85 | * Every account's Minecraft names (or one's, when `userId` is given), by user id: one read for a | |
| 86 | * list. | |
| 87 | */ | |
| 88 | export function minecraftByUser(db: Database, userId = ""): Map<string, Identity[]> { | |
| 89 | const by = new Map<string, Identity[]>(); | |
| 90 | const rows = db | |
| 91 | .query<{ userId: string; player: string; uuid: string; createdAt: string }, [string]>( | |
| 92 | "SELECT user_id AS userId, player, uuid, created_at AS createdAt FROM game_link WHERE (?1 = '' OR user_id = ?1) ORDER BY created_at", | |
| 93 | ) | |
| 94 | .all(userId); | |
| 95 | for (const r of rows) by.set(r.userId, [...(by.get(r.userId) ?? []), { kind: "minecraft", name: r.player, proven: r.uuid !== "", since: r.createdAt }]); | |
| 96 | return by; | |
| 97 | } | |
| 98 | ||
| 84 | 99 | /** |
| 85 | 100 | * Every identity of `userId` in one statement, email first then the Minecraft names oldest first, |
| 86 | 101 | * and whether the forge has a game box to link a name on; no identities for an account that does |
src/crew/routine_report.ts +1 −1
| @@ -84,7 +84,7 @@ export function needsOf(degraded: readonly Degraded[], red: readonly { readonly | ||
| 84 | 84 | */ |
| 85 | 85 | export function needsFor(kind: RoutineKind, f: Facts): readonly Need[] { |
| 86 | 86 | if (kind === "checkin") return f.needs; |
| 87 | if (kind === "friends") return f.waiting === 0 ? [] : [{ key: "waiting", text: `${plural(f.waiting, "request")} for an account waiting for your allow.`, adminOnly: true, href: "/settings/accounts", figure: f.waiting }]; | |
| 87 | if (kind === "friends") return f.waiting === 0 ? [] : [{ key: "waiting", text: `${plural(f.waiting, "request")} for an account waiting for your allow.`, adminOnly: true, href: "/settings/people", figure: f.waiting }]; | |
| 88 | 88 | return []; |
| 89 | 89 | } |
| 90 | 90 |
src/design/door_checks.ts −1
| @@ -152,7 +152,6 @@ export const DOOR_LINES: readonly DoorLine[] = [ | ||
| 152 | 152 | { file: "src/web/pages/everyday.ts", text: 'if (user.isAdmin && user.kind === "user") return everydayForm(ctx, user, false);', why: SHOWN }, |
| 153 | 153 | { file: "src/web/pages/everyday.ts", text: 'if (!admin?.isAdmin) return new Response("not found", { status: 404 });', why: "the admin an everyday account is paired with, not the one asking" }, |
| 154 | 154 | { file: "src/web/pages/repo.ts", text: "if (!isAdmin(ctx, repo)) return null;", why: "a repository's admin, asked through canAdmin" }, |
| 155 | { file: "src/web/pages/accounts.ts", text: 'const actionable = a.kind === "user" && !a.isAdmin && a.removedAt === null;', why: SHOWN }, | |
| 156 | 155 | { file: "src/web/pages/accounts.ts", text: "const ordinary = !user.isAdmin;", why: SHOWN }, |
| 157 | 156 | { file: "src/web/pages/new-forge.ts", text: "if (user?.isAdmin !== true || plans.every((p) => p.key === FREE)) return null;", why: "a render helper handed the account, which shows a field and gates nothing" }, |
| 158 | 157 | { file: "src/web/pages/reports.ts", text: 'if (ctx.auth.scope === undefined || !scopeAllows(ctx.auth.scope, "rw"))', why: "a token's scope, judged where it was" }, |
src/http/lazy_lists.ts +4
| @@ -194,7 +194,11 @@ export const SETTINGS_ROUTES = [ | ||
| 194 | 194 | ["POST", "/settings/accounts/:username/allow"], |
| 195 | 195 | ["POST", "/settings/accounts/:username/decline"], |
| 196 | 196 | ["GET", "/settings/people"], |
| 197 | ["GET", "/settings/people/row/:username"], | |
| 197 | 198 | ["POST", "/settings/people/:username/role"], |
| 199 | ["POST", "/settings/people/:username/take"], | |
| 200 | ["POST", "/settings/people/invites/:id/again"], | |
| 201 | ["POST", "/settings/people/invites/:id/revoke"], | |
| 198 | 202 | ["GET", "/settings/model"], |
| 199 | 203 | ["POST", "/settings/model"], |
| 200 | 204 | ["POST", "/settings/model/connections"], |
src/http/marks/settings.json +4
| @@ -156,6 +156,10 @@ | ||
| 156 | 156 | "/settings/accounts/:username/decline": "admin", |
| 157 | 157 | "/settings/people": "admin", |
| 158 | 158 | "/settings/people/:username/role": "admin", |
| 159 | "/settings/people/row/:username": "admin", | |
| 160 | "/settings/people/:username/take": "admin", | |
| 161 | "/settings/people/invites/:id/again": "admin", | |
| 162 | "/settings/people/invites/:id/revoke": "admin", | |
| 159 | 163 | "/settings/model": "open", |
| 160 | 164 | "/settings/model/connections": "open", |
| 161 | 165 | "/settings/model/connections/:id": "open", |
src/http/settings_routes.ts +9 −3
| @@ -7,6 +7,7 @@ | ||
| 7 | 7 | * in the pattern list the usage page reads, so this module never imports it. |
| 8 | 8 | */ |
| 9 | 9 | |
| 10 | import { redirect } from "../web/layout.ts"; | |
| 10 | 11 | import { crewKeyAdd } from "../web/studio/crew_key.ts"; |
| 11 | 12 | import { crewBudgetsSave } from "../web/studio/crew_budgets.ts"; |
| 12 | 13 | import { fallbackCapSave, fallbackSave } from "../web/studio/crew_fallback.ts"; |
| @@ -41,7 +42,6 @@ import { | ||
| 41 | 42 | accountAct, |
| 42 | 43 | retireAct, |
| 43 | 44 | retirePage, |
| 44 | accountsPage, | |
| 45 | 45 | wayBackAct, |
| 46 | 46 | personSignInsPage, |
| 47 | 47 | signInAct, |
| @@ -94,7 +94,9 @@ import { | ||
| 94 | 94 | subscriptionWake, |
| 95 | 95 | subscriptionAllow, |
| 96 | 96 | } from "../web/pages/subscriptions.ts"; |
| 97 | import { peoplePage, roleAct } from "../web/pages/people.ts"; | |
| 97 | import { peoplePage, personFragment, roleAct, takeAct } from "../web/pages/people.ts"; | |
| 98 | import { inviteAgain } from "../web/pages/people_invites.ts"; | |
| 99 | import { inviteRevoke } from "../web/pages/admin-limits.ts"; | |
| 98 | 100 | import { ceilingAct, grantAct, modelAdd, modelPage } from "../web/pages/model.ts"; |
| 99 | 101 | import { connectionAdd, connectionEdit, connectionRemove, connectionRetest } from "../web/pages/connections.ts"; |
| 100 | 102 | import { |
| @@ -349,11 +351,15 @@ export function settingsRoutes(router: Router<Handler>, knownPatterns: () => rea | ||
| 349 | 351 | router.add("POST", "/settings/backups/mirror", backupsMirror); |
| 350 | 352 | router.add("POST", "/settings/backups/mirror/clear", backupsMirrorClear); |
| 351 | 353 | router.add("POST", "/settings/backups/mirror/now", backupsMirrorNow); |
| 352 | router.add("GET", "/settings/accounts", accountsPage); | |
| 354 | router.add("GET", "/settings/accounts", (ctx) => redirect("/settings/people", { url: ctx.url, forgeUrl: ctx.app.config.url })); | |
| 353 | 355 | router.add("POST", "/settings/accounts/:username/allow", requestAct("allow")); |
| 354 | 356 | router.add("POST", "/settings/accounts/:username/decline", requestAct("decline")); |
| 355 | 357 | router.add("GET", "/settings/people", peoplePage); |
| 358 | router.add("GET", "/settings/people/row/:username", personFragment); | |
| 356 | 359 | router.add("POST", "/settings/people/:username/role", roleAct); |
| 360 | router.add("POST", "/settings/people/:username/take", takeAct); | |
| 361 | router.add("POST", "/settings/people/invites/:id/again", inviteAgain); | |
| 362 | router.add("POST", "/settings/people/invites/:id/revoke", inviteRevoke); | |
| 357 | 363 | router.add("GET", "/settings/model", modelPage); |
| 358 | 364 | router.add("POST", "/settings/model", modelAdd); |
| 359 | 365 | router.add("POST", "/settings/model/connections", connectionAdd); |
src/tui/screens/invites.ts +21 −6
| @@ -4,14 +4,16 @@ | ||
| 4 | 4 | * shows them. `m` mints one from a number of days (1 to 30, 7 by default) and a bundle (Use, Host |
| 5 | 5 | * with a machine and two caps, or Build) and prints the link once (`o` makes one for an |
| 6 | 6 | * organization: its person joins it and gets private forks of its apps), on this screen, until the |
| 7 | * next key of any kind; `x` revokes the selected open one after a confirm (`y` revokes, `n` or esc | |
| 8 | * keeps it). Both go through the actions, so the gate is theirs: an admin who is a person; anyone | |
| 9 | * else sees nothing and mints nothing. The top line says who may sign up now, as MCP `signup` does; | |
| 10 | * `s` picks open, invite or closed, shows from → to and changes it only after a confirm; `a` does | |
| 11 | * the same for who may start an agent here (open, code or off, `Agents can start here`). | |
| 7 | * next key of any kind; `c` shows a waiting link again and `n` makes a new one like the selected | |
| 8 | * (taking a waiting one back); `x` revokes the selected open one after a confirm (`y` revokes, `n` | |
| 9 | * or esc keeps it). Both go through the actions, so the gate is theirs: an admin who is a person; | |
| 10 | * anyone else sees nothing and mints nothing. The top line says who may sign up now, as MCP | |
| 11 | * `signup` does; `s` picks open, invite or closed, shows from → to and changes it only after a | |
| 12 | * confirm; `a` does the same for who may start an agent here (open, code or off, | |
| 13 | * `Agents can start here`). | |
| 12 | 14 | */ |
| 13 | 15 | |
| 14 | import { hostMachines, inviteLink, list, mint, mintRefusal, revoke, type BundleInput } from "../../actions/invites.ts"; | |
| 16 | import { again, hostMachines, inviteLink, list, mint, mintRefusal, revoke, tokenOf, type BundleInput } from "../../actions/invites.ts"; | |
| 15 | 17 | import { BUNDLE, BUNDLES } from "../../core/bundles.ts"; |
| 16 | 18 | import { INVITE_NOT_OPEN } from "../../actions/sever_invite_words.ts"; |
| 17 | 19 | import { changeAgentStart, changeSignup, readAgentStart, readSignup } from "../../actions/signup.ts"; |
| @@ -157,6 +159,8 @@ export function invitesScreen(f: Session, ctx: Ctx): Screen { | ||
| 157 | 159 | binding(["m"], "make a link: Use, Host or Build"), |
| 158 | 160 | binding(["o"], "make a link to an organization"), |
| 159 | 161 | binding(["x"], "revoke"), |
| 162 | binding(["c"], "show a waiting link"), | |
| 163 | binding(["n"], "a new link like this one"), | |
| 160 | 164 | ...(signup().ok ? [binding(["s"], "who may sign up"), binding(["a"], "agents can start here")] : []), |
| 161 | 165 | ]; |
| 162 | 166 | }, |
| @@ -215,6 +219,17 @@ export function invitesScreen(f: Session, ctx: Ctx): Screen { | ||
| 215 | 219 | }, |
| 216 | 220 | }), |
| 217 | 221 | ); |
| 222 | } else if (e.key === "c") { | |
| 223 | const row = all[state.index]; | |
| 224 | if (row === undefined) return false; | |
| 225 | const token = tokenOf(f.app, f.user, row.id); | |
| 226 | note = token === undefined ? "Only a waiting invite has a link to copy." : inviteLink(f.app.config.url ?? `http://localhost:${f.app.config.port}`, token); | |
| 227 | } else if (e.key === "n") { | |
| 228 | const row = all[state.index]; | |
| 229 | if (row === undefined) return false; | |
| 230 | const made = again(f.app, f.user, row.id); | |
| 231 | note = made.ok ? `New link: ${inviteLink(f.app.config.url ?? `http://localhost:${f.app.config.port}`, made.value.token)}` : "A used invite stays as it is; make a new one with m."; | |
| 232 | ctx.invalidate(); | |
| 218 | 233 | } else if (e.key === "s") { |
| 219 | 234 | const now = signup(); |
| 220 | 235 | if (!now.ok) return false; |
src/tui/screens/people.ts +26 −2
| @@ -6,14 +6,19 @@ | ||
| 6 | 6 | * after a confirm, with the actions and words MCP `account_suspend` uses. |
| 7 | 7 | * `v` vouches for the email of the person under the cursor, after a y/n, |
| 8 | 8 | * with the action MCP `account_verify` uses. Without mail a line above the |
| 9 | * list says so, as the accounts page's card does. | |
| 9 | * list says so, as the accounts page's card does. `x` takes one thing away | |
| 10 | * from a person (`actions/take_away.ts`, what the web page's Remove does; `x ada app notes` | |
| 11 | * removes the app notes that ada was let into). | |
| 10 | 12 | */ |
| 11 | 13 | |
| 12 | 14 | import { suspendAccount, unsuspendAccount, verifyAccount } from "../../actions/accounts.ts"; |
| 13 | 15 | import { mailConfigured } from "../../actions/verify.ts"; |
| 14 | 16 | import { ADMIN_WORDS } from "../../actions/admin_words.ts"; |
| 15 | 17 | import { lastOwnerSays } from "../../core/orgs.ts"; |
| 18 | import { getUserByName } from "../../core/users.ts"; | |
| 16 | 19 | import { setRole } from "../../actions/roles.ts"; |
| 20 | import { takeAway, TAKE_AWAY_WORDS } from "../../actions/take_away.ts"; | |
| 21 | import { appLetInto, REMOVABLE_WORDS } from "../../core/grant_removal.ts"; | |
| 17 | 22 | import { AMOUNT_REFUSED } from "../../actions/model_words.ts"; |
| 18 | 23 | import { peopleByActivity, WORDS, type PersonRow, type RoleWord } from "../../core/people_rows.ts"; |
| 19 | 24 | import type { Ctx, Screen } from "../app/app.ts"; |
| @@ -91,7 +96,7 @@ export function peopleScreen(f: Session, ctx: Ctx): Screen { | ||
| 91 | 96 | }; |
| 92 | 97 | const screen: Screen = { |
| 93 | 98 | title: "People", |
| 94 | keys: [binding(["f"], "filter"), binding(["r"], "change a role"), binding(["s"], "suspend or lift"), binding(["v"], "verify"), binding(["esc"], "back")], | |
| 99 | keys: [binding(["f"], "filter"), binding(["r"], "change a role"), binding(["s"], "suspend or lift"), binding(["v"], "verify"), binding(["x"], "take one thing away"), binding(["esc"], "back")], | |
| 95 | 100 | render(area, s) { |
| 96 | 101 | const rows: ListRow[] = people().map((p) => ({ |
| 97 | 102 | title: rowOf(p), |
| @@ -154,6 +159,25 @@ export function peopleScreen(f: Session, ctx: Ctx): Screen { | ||
| 154 | 159 | ); |
| 155 | 160 | return true; |
| 156 | 161 | } |
| 162 | if (e.key === "x") { | |
| 163 | ctx.push( | |
| 164 | promptScreen(ctx, screen, { | |
| 165 | title: "Take one thing away", | |
| 166 | label: `account name, then ${REMOVABLE_WORDS}`, | |
| 167 | onSubmit: (raw) => { | |
| 168 | const [name, what, repo, ...rest] = raw.trim().split(/\s+/); | |
| 169 | if (name === undefined || what === undefined || rest.length > 0 || (what === "app") !== (repo !== undefined)) return `name, then ${REMOVABLE_WORDS}.`; | |
| 170 | const person = getUserByName(f.app.db, name); | |
| 171 | const key = what === "app" && person !== undefined ? appLetInto(f.app.db, person.id, repo!) : ""; | |
| 172 | const done = takeAway(f.app, f.user, name, what === "app" ? "app_member" : what, key); | |
| 173 | if (!done.ok) return done.error === "not_found" ? "No such person, or nothing like that to take." : TAKE_AWAY_WORDS[done.error]; | |
| 174 | ctx.toast(`Took ${what === "app" ? `app ${repo}` : what} from ${name}.`); | |
| 175 | return undefined; | |
| 176 | }, | |
| 177 | }), | |
| 178 | ); | |
| 179 | return true; | |
| 180 | } | |
| 157 | 181 | if (e.key !== "r") return false; |
| 158 | 182 | ctx.push( |
| 159 | 183 | promptScreen(ctx, screen, { |
src/web/form.ts +12 −1
| @@ -8,16 +8,27 @@ | ||
| 8 | 8 | * enforce. Auth routes (sign in / up) pass no scope. |
| 9 | 9 | */ |
| 10 | 10 | |
| 11 | import { CAME_FROM_ELSEWHERE, forbiddenPage, SENT_FROM_ELSEWHERE } from "./chrome.ts"; | |
| 11 | import { CAME_FROM_ELSEWHERE, forbiddenPage, notFoundPage, SENT_FROM_ELSEWHERE, signInFirst } from "./chrome.ts"; | |
| 12 | 12 | import { BODY_MAX, readBounded, STRANGER_MAX } from "../http/limits.ts"; |
| 13 | 13 | import { scopeAllows, type TokenScope } from "../core/tokens.ts"; |
| 14 | 14 | import { isLocalPath } from "./flash.ts"; |
| 15 | 15 | import type { FieldOptions } from "./ui.ts"; |
| 16 | import { adminPage, signedInPage } from "../http/page_may.ts"; | |
| 16 | 17 | import { crossOrigin, type Ctx } from "../http/context.ts"; |
| 17 | 18 | import { controlRefusal, dirtyForm } from "../http/parseable_request.ts"; |
| 18 | 19 | |
| 19 | 20 | export type Form = Awaited<ReturnType<Request["formData"]>>; |
| 20 | 21 | |
| 22 | /** | |
| 23 | * An admin's form post: the page's own refusals first (sign in, or a page that is not there), then | |
| 24 | * the form read at admin scope. A Response is the answer to send. | |
| 25 | */ | |
| 26 | export async function adminForm(ctx: Ctx): Promise<Form | Response> { | |
| 27 | if (!signedInPage(ctx)) return signInFirst(ctx); | |
| 28 | if (!adminPage(ctx)) return notFoundPage(ctx); | |
| 29 | return readForm(ctx, "admin"); | |
| 30 | } | |
| 31 | ||
| 21 | 32 | export async function readForm( |
| 22 | 33 | ctx: Ctx, |
| 23 | 34 | minScope?: TokenScope, |
src/web/pages/accounts.ts +17 −199
| @@ -9,7 +9,6 @@ import { adminPage, signedInPage } from "../../http/page_may.ts"; | ||
| 9 | 9 | import { sshOn } from "../../settings/ssh.ts"; |
| 10 | 10 | import { emptyNote } from "../empty_words.ts"; |
| 11 | 11 | import { |
| 12 | listAccounts, | |
| 13 | 12 | removeAccount, |
| 14 | 13 | retirementPlan, |
| 15 | 14 | retireAndRemoveAccount, |
| @@ -24,17 +23,13 @@ import { roleOf } from "../../core/roles.ts"; | ||
| 24 | 23 | import { listSessions } from "../../core/sessions.ts"; |
| 25 | 24 | import { listTokensWithClients } from "../../core/oauth.ts"; |
| 26 | 25 | import { emailVerified } from "../../core/verify.ts"; |
| 27 | import { mailConfigured } from "../../actions/verify.ts"; | |
| 28 | import { listAccounts as readAccounts, originOf, signinReach, type AccountRow } from "../../core/accounts.ts"; | |
| 29 | 26 | import { |
| 30 | OWNERS_TEAM, | |
| 31 | ownerlessOrgs, | |
| 32 | 27 | soleOwnedOrgs, |
| 33 | 28 | } from "../../core/orgs.ts"; |
| 34 | 29 | import { getUserByName, hasPassword, isStandInEmail } from "../../core/users.ts"; |
| 35 | import { mintWayBack, wayBackAccounts } from "../../actions/edge_handover.ts"; | |
| 30 | import { listAccounts as readAccounts } from "../../core/accounts.ts"; | |
| 31 | import { mintWayBack } from "../../actions/edge_handover.ts"; | |
| 36 | 32 | import type { Ctx } from "../../http/context.ts"; |
| 37 | import { notePhase, takeSessionTime, timePhase } from "../../core/route_timing.ts"; | |
| 38 | 33 | import { notFoundPage, settingsLayout, signInFirst } from "../chrome.ts"; |
| 39 | 34 | import { field, readForm } from "../form.ts"; |
| 40 | 35 | import { html, type Html } from "../html.ts"; |
| @@ -52,17 +47,17 @@ import { | ||
| 52 | 47 | import { sessionsCard } from "./account.ts"; |
| 53 | 48 | import { grantCard } from "./model.ts"; |
| 54 | 49 | import { accountSections } from "./origins.ts"; |
| 55 | import { markOf } from "../../core/marks.ts"; | |
| 56 | import { requestsCard } from "../requests_card.ts"; | |
| 50 | import { peopleView } from "./people.ts"; | |
| 51 | import { ownersTeam } from "./people_cards.ts"; | |
| 57 | 52 | |
| 58 | 53 | function shell(ctx: Ctx, body: Html, status = 200): Response { |
| 59 | 54 | return page( |
| 60 | 55 | { |
| 61 | 56 | ctx, |
| 62 | title: "Accounts", | |
| 63 | body: html`<div class="page-head"><h1>Accounts</h1></div> | |
| 57 | title: "People", | |
| 58 | body: html`<div class="page-head"><h1>People</h1></div> | |
| 64 | 59 | ${settingsLayout( |
| 65 | accountSections("accounts", { admin: true, ssh: sshOn(ctx.app.db) }), | |
| 60 | accountSections("people", { admin: true, ssh: sshOn(ctx.app.db) }), | |
| 66 | 61 | body, |
| 67 | 62 | "Account settings", |
| 68 | 63 | )}`, |
| @@ -71,74 +66,6 @@ function shell(ctx: Ctx, body: Html, status = 200): Response { | ||
| 71 | 66 | ); |
| 72 | 67 | } |
| 73 | 68 | |
| 74 | function standing(a: AccountRow): Html { | |
| 75 | if (a.removedAt !== null) return badge("Removed", { variant: "outline" }); | |
| 76 | if (a.suspendedAt !== null) return badge("Suspended", { tone: "danger" }); | |
| 77 | if (a.waiting) return badge("Waiting", { variant: "outline" }); | |
| 78 | if (!a.verified) return badge("Email not verified", { variant: "outline" }); | |
| 79 | return html``; | |
| 80 | } | |
| 81 | ||
| 82 | /** `sole`: the organizations this account is the only person owning. */ | |
| 83 | function personRow(a: AccountRow, sole: readonly string[]): Html { | |
| 84 | const at = `/settings/accounts/${encodeURIComponent(a.username)}`; | |
| 85 | const how = [ | |
| 86 | originOf(a), | |
| 87 | a.address ?? "", | |
| 88 | ].filter((s) => s !== ""); | |
| 89 | const holds = [ | |
| 90 | `${a.repos} ${a.repos === 1 ? "repository" : "repositories"}`, | |
| 91 | ...(a.apps > 0 ? [`${a.apps} ${a.apps === 1 ? "app" : "apps"}`] : []), | |
| 92 | ...(a.spentUsd > 0 ? [`$${a.spentUsd.toFixed(2)} spent`] : []), | |
| 93 | ]; | |
| 94 | // Who may be acted on: a person who is not an admin and is still here. | |
| 95 | const actionable = a.kind === "user" && !a.isAdmin && a.removedAt === null; | |
| 96 | return row({ | |
| 97 | nav: true, | |
| 98 | title: html`${userLink(a.username, { mark: markOf(a) })} ${standing(a)}`, | |
| 99 | meta: html`joined | |
| 100 | ${time(a.createdAt)}${how.length > 0 ? html` · ${how.join(" · ")}` : null} | |
| 101 | · ${holds.join(" · ")}${sole.length > 0 && a.suspendedAt === null | |
| 102 | ? html` · only owner of ${sole.join(", ")}` | |
| 103 | : null}${sole.length > 0 && a.suspendedAt !== null | |
| 104 | ? html` · ${badge(`${sole.join(", ")}: no active owner`, { tone: "danger" })}` | |
| 105 | : null}`, | |
| 106 | ...(actionable | |
| 107 | ? { after: html` | |
| 108 | ${btn("Manage account", { href: at, size: "sm", variant: "ghost" })} | |
| 109 | ${a.verified | |
| 110 | ? null | |
| 111 | : html`<form method="post" action="${at}/verify"> | |
| 112 | ${btn("Verify email", { type: "submit", size: "sm" })} | |
| 113 | </form>`} | |
| 114 | ${a.suspendedAt === null | |
| 115 | ? confirmAction({ action: `${at}/suspend`, verb: "Suspend", size: "sm" }) | |
| 116 | : html`<form method="post" action="${at}/unsuspend"> | |
| 117 | ${btn("Unsuspend", { type: "submit", size: "sm" })} | |
| 118 | </form>`} | |
| 119 | ${confirmAction({ action: `${at}/remove`, verb: "Remove", size: "sm" })} | |
| 120 | ` } | |
| 121 | : {}), | |
| 122 | }); | |
| 123 | } | |
| 124 | ||
| 125 | /** | |
| 126 | * Once the edge is gone, a person it signed in who added no passkey gets in | |
| 127 | * by a way-back link an admin hands over (#11802): one button per account | |
| 128 | * `wayBackAccounts` names. An admin is not offered one; they add a passkey. | |
| 129 | */ | |
| 130 | function wayBackForms(ctx: Ctx): Html | null { | |
| 131 | const listed = wayBackAccounts(ctx.app, ctx.auth.user); | |
| 132 | if (!listed.ok || listed.value.length === 0) return null; | |
| 133 | return html`<div class="form-actions" id="way-back"> | |
| 134 | ${listed.value.map( | |
| 135 | (a) => html`<form method="post" action="/settings/accounts/${encodeURIComponent(a.username)}/way-back"> | |
| 136 | ${btn(`Way-back link for ${a.username}`, { type: "submit", size: "sm" })} | |
| 137 | </form>`, | |
| 138 | )} | |
| 139 | </div>`; | |
| 140 | } | |
| 141 | ||
| 142 | 69 | // POST /settings/accounts/:username/way-back — the link, shown once on the page. |
| 143 | 70 | export async function wayBackAct(ctx: Ctx): Promise<Response> { |
| 144 | 71 | if (!signedInPage(ctx)) return signInFirst(ctx); |
| @@ -149,13 +76,13 @@ export async function wayBackAct(ctx: Ctx): Promise<Response> { | ||
| 149 | 76 | const minted = mintWayBack(ctx.app, ctx.auth.user, username); |
| 150 | 77 | if (!minted.ok) { |
| 151 | 78 | if (minted.error === "not_found") return notFoundPage(ctx); |
| 152 | return flashTo(ctx, "/settings/accounts", { | |
| 79 | return flashTo(ctx, "/settings/people", { | |
| 153 | 80 | message: `${username} already signs in without the edge; no link was made.`, |
| 154 | 81 | tone: "danger", |
| 155 | 82 | }); |
| 156 | 83 | } |
| 157 | 84 | const w = minted.value; |
| 158 | const response = accountsView( | |
| 85 | const response = peopleView( | |
| 159 | 86 | ctx, |
| 160 | 87 | html`<section class="settings-block" id="way-back-link"> |
| 161 | 88 | <h2>Way-back link for ${w.username}</h2> |
| @@ -171,115 +98,6 @@ export async function wayBackAct(ctx: Ctx): Promise<Response> { | ||
| 171 | 98 | return response; |
| 172 | 99 | } |
| 173 | 100 | |
| 174 | // GET /settings/accounts | |
| 175 | export function accountsPage(ctx: Ctx): Response { | |
| 176 | notePhase(ctx.request, "session", takeSessionTime(ctx.request)); | |
| 177 | return accountsView(ctx); | |
| 178 | } | |
| 179 | ||
| 180 | /** The page, with what an act needs said first (`notice`) when it did not finish. */ | |
| 181 | function accountsView(ctx: Ctx, notice?: Html, status = 200): Response { | |
| 182 | if (!signedInPage(ctx)) return signInFirst(ctx); | |
| 183 | const user = ctx.auth.user; | |
| 184 | const listed = timePhase(ctx.request, "accounts", () => | |
| 185 | listAccounts(ctx.app, user), | |
| 186 | ); | |
| 187 | if (!listed.ok) return notFoundPage(ctx); | |
| 188 | const query = (ctx.url.searchParams.get("q") ?? "").trim().slice(0, 64).toLowerCase(); | |
| 189 | const people = query === "" ? listed.value : listed.value.filter((a) => a.username.toLowerCase().includes(query) || a.displayName.toLowerCase().includes(query)); | |
| 190 | // Without mail a newcomer cannot prove an address; the owner's word is | |
| 191 | // the only way in, and the page says so where it is given. | |
| 192 | const mail = timePhase(ctx.request, "mail", () => mailConfigured(ctx.app)); | |
| 193 | const noMail = mail | |
| 194 | ? null | |
| 195 | : html`<section class="settings-block" id="no-mail"> | |
| 196 | <h2>Mail is not configured</h2> | |
| 197 | <p> | |
| 198 | Newcomers cannot verify themselves, so they fork and open pulls | |
| 199 | unverified. Verify them here, or set <code>MAIL_SMTP_URL</code> and <code>MAIL_FROM</code> under | |
| 200 | <a href="/settings/secrets">Secrets</a>. | |
| 201 | </p> | |
| 202 | </section>`; | |
| 203 | // An organization every owner of which is suspended or removed stays as | |
| 204 | // it is for its members; only the forge's owner can mend it. | |
| 205 | const orphans = timePhase(ctx.request, "orphans", () => | |
| 206 | ownerlessOrgs(ctx.app.db), | |
| 207 | ); | |
| 208 | const ownerless = | |
| 209 | orphans.length === 0 | |
| 210 | ? null | |
| 211 | : html`<section class="settings-block" id="ownerless"> | |
| 212 | <h2>No active owner</h2> | |
| 213 | <p> | |
| 214 | ${orphans.map( | |
| 215 | (o, i) => html`${i > 0 ? ", " : ""}${userLink(o.username)}`, | |
| 216 | )} | |
| 217 | ${orphans.length === 1 ? "has" : "have"} no active owner: everyone | |
| 218 | on Owners is suspended or removed. Unsuspend one, or add an owner: | |
| 219 | ${orphans.map( | |
| 220 | (o, i) => | |
| 221 | html`${i > 0 ? ", " : ""}<a href="${ownersTeam(o.username)}" | |
| 222 | >${o.username}'s Owners</a | |
| 223 | >`, | |
| 224 | )}. | |
| 225 | </p> | |
| 226 | </section>`; | |
| 227 | const reach = timePhase(ctx.request, "edge-only", () => signinReach(ctx.app.db)); | |
| 228 | const stranded = reach.stranded; | |
| 229 | const edgeOnly = | |
| 230 | stranded.length === 0 | |
| 231 | ? html`<section class="settings-block"> | |
| 232 | <p id="signin-reach">All ${reach.total} accounts can sign in without the platform edge.</p> | |
| 233 | </section>` | |
| 234 | : html`<section class="settings-block"> | |
| 235 | <h2 id="signin-reach">${reach.own} of ${reach.total} accounts can sign in without the platform edge.</h2> | |
| 236 | <p> | |
| 237 | ${stranded.length === 1 ? "This account signs" : "These accounts sign"} | |
| 238 | in only through the platform edge, so switching | |
| 239 | <code>signin.edge</code> off would lock | |
| 240 | ${stranded.length === 1 ? "it" : "them"} out. Ask each to add a | |
| 241 | passkey at <a href="/settings/passkeys">Settings → Passkeys</a>: | |
| 242 | ${stranded.map( | |
| 243 | (a, i) => | |
| 244 | html`${i > 0 ? ", " : ""}${userLink(a.username)}${a.isAdmin | |
| 245 | ? " (admin)" | |
| 246 | : ""}`, | |
| 247 | )}. | |
| 248 | </p> | |
| 249 | ${wayBackForms(ctx)} | |
| 250 | </section>`; | |
| 251 | const sole = timePhase(ctx.request, "owned", () => | |
| 252 | people.map((a) => { | |
| 253 | const u = getUserByName(ctx.app.db, a.username); | |
| 254 | return u === undefined | |
| 255 | ? [] | |
| 256 | : soleOwnedOrgs(ctx.app.db, u.id).map((o) => o.username); | |
| 257 | }), | |
| 258 | ); | |
| 259 | const rendering = performance.now(); | |
| 260 | const response = shell( | |
| 261 | ctx, | |
| 262 | html`${notice ?? null}${requestsCard(ctx)}${ownerless}${edgeOnly}${noMail}<section class="settings-block" id="accounts"> | |
| 263 | <h2>Who is on this forge</h2> | |
| 264 | <form method="get" action="/settings/accounts" class="form-actions" role="search"> | |
| 265 | <input class="input" name="q" type="search" maxlength="64" value="${query}" placeholder="Search by name" aria-label="Search accounts" autocomplete="off" /> | |
| 266 | ${btn("Search", { type: "submit", size: "sm" })} | |
| 267 | </form> | |
| 268 | <p class="muted">${query === "" ? "Newest first." : `${people.length} matching.`}</p> | |
| 269 | <ul class="list setting-list" id="accounts-list"> | |
| 270 | ${people.map((a, i) => personRow(a, sole[i] ?? []))} | |
| 271 | </ul> | |
| 272 | </section>`, | |
| 273 | status, | |
| 274 | ); | |
| 275 | notePhase(ctx.request, "render", performance.now() - rendering); | |
| 276 | return response; | |
| 277 | } | |
| 278 | ||
| 279 | /** Where an organization's owners are added. */ | |
| 280 | const ownersTeam = (org: string): string => | |
| 281 | `/${encodeURIComponent(org)}/-/teams/${encodeURIComponent(OWNERS_TEAM)}`; | |
| 282 | ||
| 283 | 101 | /** Before suspending the last active owner of an organization, say so once. */ |
| 284 | 102 | function confirmSuspend(username: string, orgs: readonly string[]): Html { |
| 285 | 103 | const at = `/settings/accounts/${encodeURIComponent(username)}`; |
| @@ -302,7 +120,7 @@ function confirmSuspend(username: string, orgs: readonly string[]): Html { | ||
| 302 | 120 | ${orgs[0] === undefined |
| 303 | 121 | ? null |
| 304 | 122 | : btn("Add an owner first", { href: ownersTeam(orgs[0]), size: "sm" })} |
| 305 | ${btn("Keep them", { href: "/settings/accounts", size: "sm", variant: "ghost" })} | |
| 123 | ${btn("Keep them", { href: "/settings/people", size: "sm", variant: "ghost" })} | |
| 306 | 124 | </form> |
| 307 | 125 | </section>`; |
| 308 | 126 | } |
| @@ -486,7 +304,7 @@ export function signInAct(what: "token" | "session") { | ||
| 486 | 304 | } |
| 487 | 305 | |
| 488 | 306 | const cannotDo = (ctx: Ctx): Response => |
| 489 | flashTo(ctx, "/settings/accounts", { | |
| 307 | flashTo(ctx, "/settings/people", { | |
| 490 | 308 | message: "You cannot do that to yourself, another admin, or an agent.", |
| 491 | 309 | tone: "danger", |
| 492 | 310 | }); |
| @@ -521,16 +339,16 @@ export function accountAct(act: Act) { | ||
| 521 | 339 | if (!done.ok) { |
| 522 | 340 | if (done.error === "not_found") return notFoundPage(ctx); |
| 523 | 341 | if (act === "remove" && done.error === "last_owner") |
| 524 | return accountsView(ctx, refuseRemove(username), 409); | |
| 342 | return peopleView(ctx, refuseRemove(username), 409); | |
| 525 | 343 | if (act === "suspend" && done.error === "last_owner") { |
| 526 | 344 | const user = getUserByName(ctx.app.db, username); |
| 527 | 345 | const orgs = |
| 528 | 346 | user === undefined |
| 529 | 347 | ? [] |
| 530 | 348 | : soleOwnedOrgs(ctx.app.db, user.id).map((o) => o.username); |
| 531 | return accountsView(ctx, confirmSuspend(username, orgs), 409); | |
| 349 | return peopleView(ctx, confirmSuspend(username, orgs), 409); | |
| 532 | 350 | } |
| 533 | return flashTo(ctx, "/settings/accounts", { | |
| 351 | return flashTo(ctx, "/settings/people", { | |
| 534 | 352 | message: |
| 535 | 353 | done.error === "not_allowed" |
| 536 | 354 | ? "You cannot do that to yourself, another admin, or an agent." |
| @@ -540,7 +358,7 @@ export function accountAct(act: Act) { | ||
| 540 | 358 | tone: "danger", |
| 541 | 359 | }); |
| 542 | 360 | } |
| 543 | return flashTo(ctx, "/settings/accounts", { | |
| 361 | return flashTo(ctx, "/settings/people", { | |
| 544 | 362 | message: `${username} ${DONE[act]}.`, |
| 545 | 363 | }); |
| 546 | 364 | }; |
| @@ -598,7 +416,7 @@ export function retirePage(ctx: Ctx): Response { | ||
| 598 | 416 | <form method="post" action="${at}/retire" class="form-actions"> |
| 599 | 417 | <input type="hidden" name="confirm" value="1" /> |
| 600 | 418 | ${btn("Remove everything", { type: "submit", size: "sm", variant: "danger" })} |
| 601 | ${btn("Keep them", { href: "/settings/accounts", size: "sm", variant: "ghost" })} | |
| 419 | ${btn("Keep them", { href: "/settings/people", size: "sm", variant: "ghost" })} | |
| 602 | 420 | </form> |
| 603 | 421 | </section>`, |
| 604 | 422 | ); |
| @@ -626,7 +444,7 @@ export async function retireAct(ctx: Ctx): Promise<Response> { | ||
| 626 | 444 | const list = html`<ul> |
| 627 | 445 | ${removed.map((n) => html`<li>${n}</li>`)} |
| 628 | 446 | </ul>`; |
| 629 | const back = btn("Back to accounts", { href: "/settings/accounts", size: "sm" }); | |
| 447 | const back = btn("Back to people", { href: "/settings/people", size: "sm" }); | |
| 630 | 448 | if (failed !== null) |
| 631 | 449 | return shell( |
| 632 | 450 | ctx, |
src/web/pages/admin-limits.ts +8 −6
| @@ -386,6 +386,8 @@ export async function inviteMint(ctx: Ctx): Promise<Response> { | ||
| 386 | 386 | return notFoundPage(ctx); |
| 387 | 387 | const form = await readForm(ctx, "admin"); |
| 388 | 388 | if (form instanceof Response) return form; |
| 389 | const wanted = field(form, "back"); | |
| 390 | const back = wanted === "/settings/people" ? wanted : "/admin/limits"; | |
| 389 | 391 | const made = mintInviteLink(ctx.app, ctx.auth.user, field(form, "org"), { |
| 390 | 392 | bundle: field(form, "bundle"), |
| 391 | 393 | machine: field(form, "machine"), |
| @@ -394,17 +396,17 @@ export async function inviteMint(ctx: Ctx): Promise<Response> { | ||
| 394 | 396 | }); |
| 395 | 397 | if (!made.ok && made.error === "not_found") return notFoundPage(ctx); |
| 396 | 398 | if (!made.ok && made.error === "unknown_org") |
| 397 | return flashTo(ctx, "/admin/limits", { tone: "danger", message: "No organization by that name." }); | |
| 399 | return flashTo(ctx, back, { tone: "danger", message: "No organization by that name." }); | |
| 398 | 400 | if (!made.ok && made.error in BUNDLE_WORDS) |
| 399 | return flashTo(ctx, "/admin/limits", { tone: "danger", message: BUNDLE_WORDS[made.error as keyof typeof BUNDLE_WORDS] }); | |
| 400 | if (!made.ok) return flashTo(ctx, "/admin/limits", { tone: "danger", message: mintRefusal(made.error) }); | |
| 401 | return flashTo(ctx, "/admin/limits", { | |
| 401 | return flashTo(ctx, back, { tone: "danger", message: BUNDLE_WORDS[made.error as keyof typeof BUNDLE_WORDS] }); | |
| 402 | if (!made.ok) return flashTo(ctx, back, { tone: "danger", message: mintRefusal(made.error) }); | |
| 403 | return flashTo(ctx, back, { | |
| 402 | 404 | message: "Invite link made. It is shown only now:", |
| 403 | 405 | code: inviteLink(ctx.app.config.url ?? ctx.url.origin, made.value.token), |
| 404 | 406 | }); |
| 405 | 407 | } |
| 406 | 408 | |
| 407 | // POST /admin/invites/:id/revoke | |
| 409 | // POST /admin/invites/:id/revoke, and /settings/people/invites/:id/revoke from the People page | |
| 408 | 410 | export async function inviteRevoke(ctx: Ctx): Promise<Response> { |
| 409 | 411 | if (!personAdminPage(ctx)) |
| 410 | 412 | return notFoundPage(ctx); |
| @@ -413,7 +415,7 @@ export async function inviteRevoke(ctx: Ctx): Promise<Response> { | ||
| 413 | 415 | const done = revokeInviteLink(ctx.app, ctx.auth.user, ctx.params.id ?? ""); |
| 414 | 416 | return flashTo( |
| 415 | 417 | ctx, |
| 416 | "/admin/limits", | |
| 418 | ctx.url.pathname.startsWith("/settings/people/") ? "/settings/people" : "/admin/limits", | |
| 417 | 419 | done.ok |
| 418 | 420 | ? { message: "Invite link revoked." } |
| 419 | 421 | : { tone: "danger", message: INVITE_NOT_OPEN }, |
src/web/pages/knobs.ts +3 −6
| @@ -5,12 +5,11 @@ | ||
| 5 | 5 | * leaves the event the setting's own page leaves. |
| 6 | 6 | */ |
| 7 | 7 | |
| 8 | import { adminPage, signedInPage } from "../../http/page_may.ts"; | |
| 9 | 8 | import { setKnob } from "../../actions/knobs.ts"; |
| 10 | 9 | import { derivedLine, readKnobs, type KnobRow } from "../../crew/knobs.ts"; |
| 11 | 10 | import type { Ctx } from "../../http/context.ts"; |
| 12 | import { notFoundPage, signInFirst } from "../chrome.ts"; | |
| 13 | import { field, readForm } from "../form.ts"; | |
| 11 | import { notFoundPage } from "../chrome.ts"; | |
| 12 | import { adminForm, field } from "../form.ts"; | |
| 14 | 13 | import { html, type Html } from "../html.ts"; |
| 15 | 14 | import { flashTo } from "../layout.ts"; |
| 16 | 15 | import { btn } from "../ui.ts"; |
| @@ -51,9 +50,7 @@ export function knobsCard(ctx: Ctx): Html { | ||
| 51 | 50 | |
| 52 | 51 | // POST /settings/crew/knobs |
| 53 | 52 | export async function knobSet(ctx: Ctx): Promise<Response> { |
| 54 | if (!signedInPage(ctx)) return signInFirst(ctx); | |
| 55 | if (!adminPage(ctx)) return notFoundPage(ctx); | |
| 56 | const form = await readForm(ctx, "admin"); | |
| 53 | const form = await adminForm(ctx); | |
| 57 | 54 | if (form instanceof Response) return form; |
| 58 | 55 | const knob = field(form, "knob"); |
| 59 | 56 | const set = await setKnob(ctx.app, ctx.auth.user, knob, field(form, "value"), field(form, "repo")); |
src/web/pages/origins.ts −1
| @@ -189,7 +189,6 @@ const SECTION_ROWS: readonly (readonly [ | ||
| 189 | 189 | ["Security", "Traffic", "/settings/traffic", "users", (c) => c === "traffic", true], |
| 190 | 190 | ["Security", "Trusted sources", "/settings/trusted", "lock", (c) => c === "trusted", true], |
| 191 | 191 | ["Security", "Access", "/settings/access", "activity", (c) => c === "access", true], |
| 192 | ["This forge", "Accounts", "/settings/accounts", "users", (c) => c === "accounts", true], | |
| 193 | 192 | ["This forge", "People", "/settings/people", "users", (c) => c === "people", true], |
| 194 | 193 | ["This forge", "Hosted forges", "/settings/hosted-forges", "fork", (c) => c === "hosted", true], |
| 195 | 194 | ["This forge", "Limits", "/admin/limits", "activity", (c) => c === "limits", true], |
src/web/pages/people.ts +188 −66
| @@ -1,57 +1,176 @@ | ||
| 1 | 1 | /** |
| 2 | * People — rows by last activity: name, a plain word for the role (owner, | |
| 3 | * member, guest, crew member) and when they were last seen; no ids. One line | |
| 4 | * of filters (`?role=`) narrows it. One query (`peopleByActivity`) gives the | |
| 5 | * word, allowance and last seen. | |
| 2 | * People — the one page for who is on this forge. Invite is on top (a form, | |
| 3 | * then each invite with its state). Below, a person is one list of rows: who | |
| 4 | * they are, how their account was proved and when they were last seen, then | |
| 5 | * one line for each thing they can do (`everyGrant`), each with Remove that | |
| 6 | * acts in place (`in_place.ts`: the person's block is fetched again from | |
| 7 | * `/settings/people/row/:username`). An owner keeps what they have, so the | |
| 8 | * forge is never left without one. The page says whether this forge can send | |
| 9 | * mail (`people_cards.ts`). `?role=` narrows the list. | |
| 6 | 10 | * An admin promotes a guest to member (with a starter model allowance, none |
| 7 | * by default) or demotes a member, in one same-origin form post. The guards | |
| 8 | * refuse what `CAN` withholds; the card says so in `roleLimits` (`docs/ROLES.md`). | |
| 9 | * On a phone the table scrolls inside its own `data-people` box and a long | |
| 10 | * username wraps anywhere, so the page never scrolls sideways (#9374). | |
| 11 | * by default) in one same-origin form post. The guards refuse what `CAN` | |
| 12 | * withholds; the card says so in `roleLimits` (`docs/ROLES.md`). | |
| 11 | 13 | */ |
| 12 | 14 | |
| 13 | 15 | import { adminPage, signedInPage } from "../../http/page_may.ts"; |
| 14 | 16 | import { sshOn } from "../../settings/ssh.ts"; |
| 15 | 17 | import { setRole } from "../../actions/roles.ts"; |
| 18 | import { takeAway, TAKE_AWAY_WORDS } from "../../actions/take_away.ts"; | |
| 16 | 19 | import { GRANT_MAX_USD } from "../../core/model_grant.ts"; |
| 20 | import { everyGrant, forgePath, type Grant } from "../../core/grants_view.ts"; | |
| 21 | import { isRemovable } from "../../core/grant_removal.ts"; | |
| 22 | import { listAccounts as readAccounts, originOf, type AccountRow } from "../../core/accounts.ts"; | |
| 23 | import { soleOwnedByPerson } from "../../core/orgs.ts"; | |
| 24 | import { minecraftByUser, type Identity } from "../../core/proven_identities.ts"; | |
| 17 | 25 | import { peopleByActivity, wordFilter, type PersonRow } from "../../core/people_rows.ts"; |
| 18 | 26 | import { roleLimits } from "../../core/roles.ts"; |
| 19 | 27 | import { getUserByName, type User } from "../../core/users.ts"; |
| 20 | 28 | import { notePhase, takeSessionTime, timePhase } from "../../core/route_timing.ts"; |
| 21 | 29 | import type { Ctx } from "../../http/context.ts"; |
| 22 | 30 | import { notFoundPage, settingsLayout, signInFirst } from "../chrome.ts"; |
| 23 | import { field, readForm } from "../form.ts"; | |
| 31 | import { adminForm, field as formField } from "../form.ts"; | |
| 24 | 32 | import { isLocalPath } from "../flash.ts"; |
| 25 | import { html } from "../html.ts"; | |
| 26 | import { flashTo, page } from "../layout.ts"; | |
| 27 | import { btn, empty, time, userLink } from "../ui.ts"; | |
| 33 | import { html, type Html } from "../html.ts"; | |
| 34 | import { behaviorsJs } from "../behaviors.ts"; | |
| 35 | import { inPlaceJs } from "../in_place.ts"; | |
| 36 | import { flashOrJson, flashTo, fragment, page } from "../layout.ts"; | |
| 37 | import { badge, btn, empty, field, row, rowList, time, userLink } from "../ui.ts"; | |
| 28 | 38 | import { emptyList } from "../empty_words.ts"; |
| 29 | 39 | import { accountSections } from "./origins.ts"; |
| 40 | import { peopleCards } from "./people_cards.ts"; | |
| 41 | import { inviteSection } from "./people_invites.ts"; | |
| 30 | 42 | |
| 31 | 43 | /** |
| 32 | 44 | * The apps each username made, by repo name. An admin sees every app, private |
| 33 | 45 | * ones included: this page is admin-only and an app is one row per repo, so |
| 34 | 46 | * no environment is counted twice. |
| 35 | 47 | */ |
| 36 | export function appsMade(ctx: Ctx): Map<string, string[]> { | |
| 48 | export function appsMade(ctx: Ctx, only = ""): Map<string, string[]> { | |
| 37 | 49 | const rows = ctx.app.db |
| 38 | .query<{ username: string; name: string }, []>( | |
| 39 | `SELECT u.username, r.name FROM app a JOIN repo r ON r.id = a.repo_id JOIN user u ON u.id = r.owner_id ORDER BY r.name COLLATE NOCASE`, | |
| 50 | .query<{ username: string; name: string }, [string]>( | |
| 51 | `SELECT u.username, r.name FROM app a JOIN repo r ON r.id = a.repo_id JOIN user u ON u.id = r.owner_id WHERE (?1 = '' OR u.username = ?1) ORDER BY r.name COLLATE NOCASE`, | |
| 40 | 52 | ) |
| 41 | .all(); | |
| 53 | .all(only); | |
| 42 | 54 | const made = new Map<string, string[]>(); |
| 43 | 55 | for (const r of rows) made.set(r.username, [...(made.get(r.username) ?? []), r.name]); |
| 44 | 56 | return made; |
| 45 | 57 | } |
| 46 | 58 | |
| 47 | // GET /settings/people | |
| 48 | export function peoplePage(ctx: Ctx): Response { | |
| 59 | const rowAt = (username: string): string => `/settings/people/row/${encodeURIComponent(username)}`; | |
| 60 | ||
| 61 | /** Everything the list reads about people, read once for the page or for one person's block. */ | |
| 62 | interface Facts { | |
| 63 | readonly accounts: ReadonlyMap<string, AccountRow>; | |
| 64 | readonly made: ReadonlyMap<string, string[]>; | |
| 65 | readonly minecraft: ReadonlyMap<string, Identity[]>; | |
| 66 | readonly sole: ReadonlyMap<string, string[]>; | |
| 67 | readonly grants: ReadonlyMap<string, Grant[]>; | |
| 68 | } | |
| 69 | ||
| 70 | /** The facts for everyone, or, given `name`, for that one person. */ | |
| 71 | function readFacts(ctx: Ctx, name = ""): Facts { | |
| 72 | const db = ctx.app.db; | |
| 73 | const list = readAccounts(db, name); | |
| 74 | const one = name === "" ? "" : (list[0]?.id ?? "-"); | |
| 75 | const grants = new Map<string, Grant[]>(); | |
| 76 | for (const g of everyGrant(db, one === "" ? undefined : one)) if (g.principal.kind === "user") grants.set(g.who, [...(grants.get(g.who) ?? []), g]); | |
| 77 | return { | |
| 78 | accounts: new Map(list.map((a) => [a.username, a])), | |
| 79 | made: appsMade(ctx, name), | |
| 80 | minecraft: minecraftByUser(db, one), | |
| 81 | sole: soleOwnedByPerson(db), | |
| 82 | grants, | |
| 83 | }; | |
| 84 | } | |
| 85 | ||
| 86 | /** How an account was proved, one fact for each thing proved: what, by whom and since when. */ | |
| 87 | function proofFacts(a: AccountRow, mc: readonly Identity[]): { label: string; value: Html | string }[] { | |
| 88 | if (a.kind === "agent") return [{ label: "Proof", value: "made by the forge, nothing to prove" }]; | |
| 89 | const ids: Identity[] = [{ kind: "email", name: a.email, proven: a.verified, since: a.provenAt }, ...mc]; | |
| 90 | const by = a.signsInThrough !== null ? `the person, through ${a.signsInThrough}` : "the person, from the link sent there"; | |
| 91 | const proven = ids.filter((i) => i.proven); | |
| 92 | const out: { label: string; value: Html | string }[] = | |
| 93 | proven.length === 0 | |
| 94 | ? [{ label: "Proof", value: `not proved${a.address === null ? "" : `: ${a.address} was never confirmed`}${a.signsInThrough === null ? "" : ` · signs in through ${a.signsInThrough}`}` }] | |
| 95 | : proven.map((i) => ({ label: i.kind === "email" ? "Email" : "Minecraft", value: html`${i.name} proved by ${by}${i.since === null ? "" : html` ${time(i.since)}`}` })); | |
| 96 | if (proven.length > 0 && a.signsInThrough === null && originOf(a) !== "") out.push({ label: "Came by", value: originOf(a) }); | |
| 97 | return out; | |
| 98 | } | |
| 99 | ||
| 100 | /** | |
| 101 | * One person: a row with who they are and how they were proved, and under it one line for each | |
| 102 | * thing they can do. | |
| 103 | */ | |
| 104 | function personRow(r: PersonRow, f: Facts): Html { | |
| 105 | const a = f.accounts.get(r.username); | |
| 106 | const owner = r.word === "owner"; | |
| 107 | const crew = r.word === "crew member"; | |
| 108 | const grants = f.grants.get(r.username) ?? []; | |
| 109 | const state = | |
| 110 | r.suspendedAt !== null | |
| 111 | ? badge("Suspended", { tone: "danger" }) | |
| 112 | : a?.waiting === true | |
| 113 | ? badge("Waiting", { variant: "outline" }) | |
| 114 | : !r.verified && !crew | |
| 115 | ? badge("Email not proved", { variant: "outline" }) | |
| 116 | : null; | |
| 117 | const apps = f.made.get(r.username) ?? []; | |
| 118 | const sole = a === undefined ? [] : (f.sole.get(a.id) ?? []); | |
| 119 | const lines = grants.map((g) => { | |
| 120 | const removable = !owner && !crew && isRemovable(g.table); | |
| 121 | return row({ | |
| 122 | title: html`${g.action} <span class="muted">on ${g.on}</span>`, | |
| 123 | ...(typeof g.byName === "string" ? { meta: html`given by ${g.byName}` } : {}), | |
| 124 | trail: removable | |
| 125 | ? html`<form method="post" action="/settings/people/${encodeURIComponent(r.username)}/take" data-in-place> | |
| 126 | <input type="hidden" name="table" value="${g.table}" /> | |
| 127 | <input type="hidden" name="key" value="${g.table === "app_member" ? g.resource.id : ""}" /> | |
| 128 | ${btn("Remove", { type: "submit", size: "sm", label: `Remove ${g.action} on ${g.on} from ${r.username}` })} | |
| 129 | </form>` | |
| 130 | : g.href === "" | |
| 131 | ? html`` | |
| 132 | : btn("Change", { href: forgePath(g.href), size: "sm", variant: "ghost", label: `Change ${g.action} on ${g.on}` }), | |
| 133 | }); | |
| 134 | }); | |
| 135 | const promote = | |
| 136 | r.word === "guest" | |
| 137 | ? [ | |
| 138 | row({ | |
| 139 | title: "Not a member yet", | |
| 140 | trail: html`<form class="row-fields" method="post" action="/settings/people/${encodeURIComponent(r.username)}/role"> | |
| 141 | <input type="hidden" name="role" value="member" /> | |
| 142 | ${field({ name: "usd", id: `usd-${r.username}`, label: "Starter allowance, dollars a month", placeholder: "none", mono: true })} | |
| 143 | ${btn("Make member", { type: "submit", size: "sm", variant: "primary" })} | |
| 144 | </form>`, | |
| 145 | }), | |
| 146 | ] | |
| 147 | : []; | |
| 148 | const children = owner ? [row({ title: "Everything. An owner keeps it, so the forge always has one." })] : [...promote, ...lines]; | |
| 149 | return row({ | |
| 150 | nav: true, | |
| 151 | data: { fragment: rowAt(r.username) }, | |
| 152 | title: html`${userLink(r.username, { nav: true })} ${badge(r.word, { variant: "secondary" })} ${state}`, | |
| 153 | meta: html`${r.lastSeen === null ? "never seen" : html`seen ${time(r.lastSeen)}`} · ${apps.length === 0 ? "No apps yet" : apps.length === 1 ? "1 app" : `${apps.length} apps`}${ | |
| 154 | apps.length === 0 ? "" : html`: ${apps.slice(0, 3).flatMap((n, i) => (i === 0 ? [html`<a href="/${r.username}/${n}">${n}</a>`] : [", ", html`<a href="/${r.username}/${n}">${n}</a>`]))}${apps.length > 3 ? ` and ${apps.length - 3} more` : ""}` | |
| 155 | }${sole.length === 0 ? "" : ` · only owner of ${sole.join(", ")}`}`, | |
| 156 | ...(a === undefined ? {} : { facts: proofFacts(a, a === undefined ? [] : (f.minecraft.get(a.id) ?? [])) }), | |
| 157 | ...(owner || crew ? {} : { after: btn("Manage", { href: `/settings/accounts/${encodeURIComponent(r.username)}`, size: "sm", variant: "ghost", label: `Manage ${r.username}` }) }), | |
| 158 | children, | |
| 159 | }); | |
| 160 | } | |
| 161 | ||
| 162 | const MAX_SHOWN = 200; | |
| 163 | ||
| 164 | /** The page, with `notice` first when an act has something to say. */ | |
| 165 | export function peopleView(ctx: Ctx, notice?: Html, status = 200): Response { | |
| 49 | 166 | if (!signedInPage(ctx)) return signInFirst(ctx); |
| 50 | 167 | if (!adminPage(ctx)) return notFoundPage(ctx); |
| 51 | 168 | notePhase(ctx.request, "session", takeSessionTime(ctx.request)); |
| 52 | 169 | const only = wordFilter(ctx.url.searchParams.get("role")); |
| 53 | const rows = timePhase(ctx.request, "people", () => peopleByActivity(ctx.app.db, only)); | |
| 54 | const made = appsMade(ctx); | |
| 170 | const query = (ctx.url.searchParams.get("q") ?? "").trim().slice(0, 64).toLowerCase(); | |
| 171 | const everyone = timePhase(ctx.request, "people", () => peopleByActivity(ctx.app.db, only)); | |
| 172 | const rows = query === "" ? everyone : everyone.filter((r) => r.username.toLowerCase().includes(query)); | |
| 173 | const facts = timePhase(ctx.request, "facts", () => readFacts(ctx)); | |
| 55 | 174 | const rendering = performance.now(); |
| 56 | 175 | const filters = html`<p class="small" data-people-filters>Show: ${[ |
| 57 | 176 | ["", "everyone"], |
| @@ -66,78 +185,81 @@ export function peoplePage(ctx: Ctx): Response { | ||
| 66 | 185 | : html`<a href="${v === "" ? "/settings/people" : `/settings/people?role=${v}`}">${label}</a>`; |
| 67 | 186 | return i === 0 ? [link] : [" · ", link]; |
| 68 | 187 | })}</p>`; |
| 69 | const line = (r: PersonRow) => { | |
| 70 | const at = `/settings/people/${encodeURIComponent(r.username)}/role`; | |
| 71 | const act = | |
| 72 | r.word === "owner" || r.word === "crew member" | |
| 73 | ? null | |
| 74 | : r.word === "guest" | |
| 75 | ? html`<form class="row-fields" method="post" action="${at}"> | |
| 76 | <input type="hidden" name="role" value="member" /> | |
| 77 | <input class="input" name="usd" inputmode="decimal" autocomplete="off" | |
| 78 | aria-label="Starter allowance, dollars a month" placeholder="$ a month, none" size="12" /> | |
| 79 | ${btn("Make member", { type: "submit", size: "sm", variant: "primary" })} | |
| 80 | </form>` | |
| 81 | : html`<form class="row-fields" method="post" action="${at}"> | |
| 82 | <input type="hidden" name="role" value="guest" /> | |
| 83 | ${btn("Make guest", { type: "submit", size: "sm" })} | |
| 84 | </form>`; | |
| 85 | const apps = made.get(r.username) ?? []; | |
| 86 | const count = apps.length; | |
| 87 | const shown = apps.slice(0, 3).map((n) => html`<a href="/${r.username}/${n}">${n}</a>`); | |
| 88 | const allowance = | |
| 89 | r.word === "owner" || r.word === "crew member" ? "" : r.usdPerMonth === null ? " · no allowance" : ` · $${r.usdPerMonth.toFixed(2)} a month`; | |
| 90 | return html`<tr> | |
| 91 | <td>${userLink(r.username, { nav: true })}<div class="small"><strong>${r.word}</strong><span class="muted">${allowance}</span></div><div class="small muted">${count === 0 ? "No apps yet" : count === 1 ? "1 app" : `${count} apps`}${ | |
| 92 | count === 0 ? "" : html`: ${shown.flatMap((a, i) => (i === 0 ? [a] : [", ", a]))}${count > 3 ? ` and ${count - 3} more` : ""}` | |
| 93 | } · ${r.lastSeen === null ? "never seen" : html`seen ${time(r.lastSeen)}`}</div></td> | |
| 94 | <td>${act}</td> | |
| 95 | </tr>`; | |
| 96 | }; | |
| 97 | 188 | const response = page({ |
| 98 | 189 | ctx, |
| 99 | 190 | title: "People", |
| 191 | scriptJs: `${inPlaceJs}\n${behaviorsJs}`, | |
| 100 | 192 | body: html`<div class="page-head"><h1>People</h1></div> |
| 101 | 193 | ${settingsLayout( |
| 102 | 194 | accountSections("people", { admin: true, ssh: sshOn(ctx.app.db) }), |
| 103 | html`<section class="settings-block"> | |
| 104 | <p>Most recently seen first.</p> | |
| 195 | html`${notice ?? null}${inviteSection(ctx)}${peopleCards(ctx)}<section class="settings-block" id="people"> | |
| 196 | <h2>Who is here</h2> | |
| 197 | <p class="small">Most recently seen first.</p> | |
| 105 | 198 | ${filters} |
| 199 | <form method="get" action="/settings/people" class="form-actions" role="search"> | |
| 200 | ${only === null ? null : html`<input type="hidden" name="role" value="${only === "crew member" ? "crew" : only}" />`} | |
| 201 | <input class="input" name="q" type="search" maxlength="64" value="${query}" placeholder="Search by name" aria-label="Search people" autocomplete="off" /> | |
| 202 | ${btn("Search", { type: "submit", size: "sm" })} | |
| 203 | </form> | |
| 204 | ${query === "" ? null : html`<p class="small muted">${rows.length} matching.</p>`} | |
| 106 | 205 | ${ |
| 107 | 206 | rows.length === 0 |
| 108 | 207 | ? only === null |
| 109 | 208 | ? emptyList("people") |
| 110 | 209 | : empty({ icon: "users", title: "Nobody here." }) |
| 111 | : html`<div class="table-scroll" data-people> | |
| 112 | <table class="table" id="people"> | |
| 113 | <thead><tr><th>Person</th><th></th></tr></thead> | |
| 114 | <tbody>${rows.map(line)}</tbody> | |
| 115 | </table> | |
| 116 | </div> | |
| 210 | : html`<div data-people>${rowList(rows.slice(0, MAX_SHOWN).map((r) => personRow(r, facts)))}</div> | |
| 211 | ${rows.length > MAX_SHOWN ? html`<p class="small muted">${rows.length - MAX_SHOWN} more: narrow it with a filter.</p>` : null} | |
| 117 | 212 | <p class="small muted">Allowances go up to $${GRANT_MAX_USD} a month. ${roleLimits()}</p>` |
| 118 | 213 | } |
| 119 | 214 | </section>`, |
| 120 | 215 | "Account settings", |
| 121 | 216 | )}`, |
| 122 | }); | |
| 217 | }, status); | |
| 123 | 218 | notePhase(ctx.request, "render", performance.now() - rendering); |
| 124 | 219 | return response; |
| 125 | 220 | } |
| 126 | 221 | |
| 127 | // POST /settings/people/:username/role | |
| 128 | export async function roleAct(ctx: Ctx): Promise<Response> { | |
| 129 | if (!signedInPage(ctx)) return signInFirst(ctx); | |
| 130 | if (!adminPage(ctx)) return notFoundPage(ctx); | |
| 131 | notePhase(ctx.request, "session", takeSessionTime(ctx.request)); | |
| 132 | const form = await readForm(ctx, "admin"); | |
| 222 | // GET /settings/people | |
| 223 | export const peoplePage = (ctx: Ctx): Response => peopleView(ctx); | |
| 224 | ||
| 225 | // GET /settings/people/row/:username: one person's block, for a redraw in place. | |
| 226 | export function personFragment(ctx: Ctx): Response { | |
| 227 | if (!adminPage(ctx)) return fragment(html``, { status: 404 }); | |
| 228 | const name = ctx.params.username ?? ""; | |
| 229 | const r = peopleByActivity(ctx.app.db).find((p) => p.username === name); | |
| 230 | if (r === undefined) return fragment(html``, { status: 404 }); | |
| 231 | return fragment(personRow(r, readFacts(ctx, name)), { request: ctx.request }); | |
| 232 | } | |
| 233 | ||
| 234 | // POST /settings/people/:username/take: Remove one line. | |
| 235 | export async function takeAct(ctx: Ctx): Promise<Response> { | |
| 236 | const form = await adminForm(ctx); | |
| 133 | 237 | if (form instanceof Response) return form; |
| 134 | 238 | const username = ctx.params.username ?? ""; |
| 135 | const role = field(form, "role"); | |
| 239 | if (getUserByName(ctx.app.db, username) === undefined) return notFoundPage(ctx); | |
| 240 | const done = takeAway(ctx.app, ctx.auth.user as User, username, formField(form, "table"), formField(form, "key")); | |
| 241 | return flashOrJson( | |
| 242 | ctx, | |
| 243 | "/settings/people", | |
| 244 | done.ok | |
| 245 | ? { message: `Took that away from ${username}.` } | |
| 246 | : { tone: "danger", message: done.error === "not_found" ? "That was already gone." : TAKE_AWAY_WORDS[done.error] }, | |
| 247 | { redraw: [rowAt(username)] }, | |
| 248 | ); | |
| 249 | } | |
| 250 | ||
| 251 | // POST /settings/people/:username/role | |
| 252 | export async function roleAct(ctx: Ctx): Promise<Response> { | |
| 253 | notePhase(ctx.request, "session", takeSessionTime(ctx.request)); | |
| 254 | const form = await adminForm(ctx); | |
| 255 | if (form instanceof Response) return form; | |
| 256 | const username = ctx.params.username ?? ""; | |
| 257 | const role = formField(form, "role"); | |
| 136 | 258 | if (role !== "member" && role !== "guest") return notFoundPage(ctx); |
| 137 | const raw = field(form, "usd").trim().replace(/^\$/, ""); | |
| 259 | const raw = formField(form, "usd").trim().replace(/^\$/, ""); | |
| 138 | 260 | const usd = raw === "" || Number(raw) === 0 ? null : /^\d{1,6}(\.\d{1,2})?$/.test(raw) ? Number(raw) : NaN; |
| 139 | 261 | const done = timePhase(ctx.request, "role", () => setRole(ctx.app, ctx.auth.user as User, username, role, usd)); |
| 140 | const wanted = field(form, "back"); | |
| 262 | const wanted = formField(form, "back"); | |
| 141 | 263 | const back = isLocalPath(wanted) ? wanted : "/settings/people"; |
| 142 | 264 | if (!done.ok) { |
| 143 | 265 | if (done.error === "not_found" || getUserByName(ctx.app.db, username) === undefined) return notFoundPage(ctx); |
src/web/pages/people_cards.ts added +80
| @@ -0,0 +1,80 @@ | ||
| 1 | /** | |
| 2 | * The cards above the People list: whether this forge can send mail, who | |
| 3 | * waits to be let in, organizations with no active owner, and who could not | |
| 4 | * sign in without the platform edge (with the owner's way-back links). Each | |
| 5 | * says nothing when there is nothing to say. | |
| 6 | */ | |
| 7 | ||
| 8 | import { mailConfigured } from "../../actions/verify.ts"; | |
| 9 | import { wayBackAccounts } from "../../actions/edge_handover.ts"; | |
| 10 | import { signinReach } from "../../core/accounts.ts"; | |
| 11 | import { OWNERS_TEAM, ownerlessOrgs } from "../../core/orgs.ts"; | |
| 12 | import { timePhase } from "../../core/route_timing.ts"; | |
| 13 | import type { Ctx } from "../../http/context.ts"; | |
| 14 | import { html, type Html } from "../html.ts"; | |
| 15 | import { requestsCard } from "../requests_card.ts"; | |
| 16 | import { btn, userLink } from "../ui.ts"; | |
| 17 | ||
| 18 | /** Where an organization's owners are added. */ | |
| 19 | export const ownersTeam = (org: string): string => `/${encodeURIComponent(org)}/-/teams/${encodeURIComponent(OWNERS_TEAM)}`; | |
| 20 | ||
| 21 | /** | |
| 22 | * The plain answer to "can this forge send mail?" when it cannot; a forge that can says nothing. | |
| 23 | */ | |
| 24 | function mailLine(can: boolean): Html | null { | |
| 25 | return can | |
| 26 | ? null | |
| 27 | : html`<p id="mail" class="small"><strong>This forge cannot send mail.</strong> Newcomers cannot prove their address, so they fork and open pulls unverified until you verify them here. Set <code>MAIL_SMTP_URL</code> and <code>MAIL_FROM</code> under <a href="/settings/secrets">Secrets</a> to change that.</p>`; | |
| 28 | } | |
| 29 | ||
| 30 | /** | |
| 31 | * Once the edge is gone, a person it signed in who added no passkey gets in | |
| 32 | * by a way-back link an admin hands over (#11802): one button per account | |
| 33 | * `wayBackAccounts` names. An admin is not offered one; they add a passkey. | |
| 34 | */ | |
| 35 | function wayBackForms(ctx: Ctx): Html | null { | |
| 36 | const listed = wayBackAccounts(ctx.app, ctx.auth.user); | |
| 37 | if (!listed.ok || listed.value.length === 0) return null; | |
| 38 | return html`<div class="form-actions" id="way-back"> | |
| 39 | ${listed.value.map( | |
| 40 | (a) => html`<form method="post" action="/settings/accounts/${encodeURIComponent(a.username)}/way-back"> | |
| 41 | ${btn(`Way-back link for ${a.username}`, { type: "submit", size: "sm" })} | |
| 42 | </form>`, | |
| 43 | )} | |
| 44 | </div>`; | |
| 45 | } | |
| 46 | ||
| 47 | export function peopleCards(ctx: Ctx): Html { | |
| 48 | const mail = timePhase(ctx.request, "mail", () => mailConfigured(ctx.app)); | |
| 49 | // An organization every owner of which is suspended or removed stays as it is for its members; | |
| 50 | // only the forge's owner can mend it. | |
| 51 | const orphans = timePhase(ctx.request, "orphans", () => ownerlessOrgs(ctx.app.db)); | |
| 52 | const ownerless = | |
| 53 | orphans.length === 0 | |
| 54 | ? null | |
| 55 | : html`<section class="settings-block" id="ownerless"> | |
| 56 | <h2>No active owner</h2> | |
| 57 | <p> | |
| 58 | ${orphans.map((o, i) => html`${i > 0 ? ", " : ""}${userLink(o.username)}`)} | |
| 59 | ${orphans.length === 1 ? "has" : "have"} no active owner: everyone on Owners is suspended or removed. | |
| 60 | Unsuspend one, or add an owner: | |
| 61 | ${orphans.map((o, i) => html`${i > 0 ? ", " : ""}<a href="${ownersTeam(o.username)}">${o.username}'s Owners</a>`)}. | |
| 62 | </p> | |
| 63 | </section>`; | |
| 64 | const reach = timePhase(ctx.request, "edge-only", () => signinReach(ctx.app.db)); | |
| 65 | const stranded = reach.stranded; | |
| 66 | const edgeOnly = | |
| 67 | stranded.length === 0 | |
| 68 | ? null | |
| 69 | : html`<section class="settings-block"> | |
| 70 | <h2 id="signin-reach">${reach.own} of ${reach.total} accounts can sign in without the platform edge.</h2> | |
| 71 | <p> | |
| 72 | ${stranded.length === 1 ? "This account signs" : "These accounts sign"} in only through the platform edge, | |
| 73 | so switching <code>signin.edge</code> off would lock ${stranded.length === 1 ? "it" : "them"} out. Ask each | |
| 74 | to add a passkey at <a href="/settings/passkeys">Settings → Passkeys</a>: | |
| 75 | ${stranded.map((a, i) => html`${i > 0 ? ", " : ""}${userLink(a.username)}${a.isAdmin ? " (admin)" : ""}`)}. | |
| 76 | </p> | |
| 77 | ${wayBackForms(ctx)} | |
| 78 | </section>`; | |
| 79 | return html`${mailLine(mail)}${requestsCard(ctx)}${ownerless}${edgeOnly}`; | |
| 80 | } |
src/web/pages/people_invites.ts added +91
| @@ -0,0 +1,91 @@ | ||
| 1 | /** | |
| 2 | * Invite, at the top of People: one form (organization, what it | |
| 3 | * allows) and one row per invite with its state: waiting, used, expired or | |
| 4 | * taken back. A waiting invite shows its link to copy (the forge keeps a sealed copy of it, and | |
| 5 | * only an admin reads it); an expired or taken-back one offers "Send again", a fresh link with the | |
| 6 | * same bundle and organization. | |
| 7 | */ | |
| 8 | ||
| 9 | import { again, BUNDLE_WORDS, hostMachines, inviteLink, list, tokenOf } from "../../actions/invites.ts"; | |
| 10 | import { BUNDLE, BUNDLES } from "../../core/bundles.ts"; | |
| 11 | import type { Invite } from "../../core/invites.ts"; | |
| 12 | import { personAdminPage } from "../../http/page_may.ts"; | |
| 13 | import type { Ctx } from "../../http/context.ts"; | |
| 14 | import { notFoundPage } from "../chrome.ts"; | |
| 15 | import { readForm } from "../form.ts"; | |
| 16 | import { html, type Html } from "../html.ts"; | |
| 17 | import { flashTo } from "../layout.ts"; | |
| 18 | import { btn, confirmAction, disclosure, field as inputField, row, rowList, selectField, time } from "../ui.ts"; | |
| 19 | ||
| 20 | const PEOPLE = "/settings/people"; | |
| 21 | ||
| 22 | /** An invite's state as a person says it. */ | |
| 23 | const stateWord = (i: Pick<Invite, "state">): string => | |
| 24 | i.state === "open" ? "waiting" : i.state === "revoked" ? "taken back" : i.state; | |
| 25 | ||
| 26 | function inviteRow(i: Invite, link: string | undefined): Html { | |
| 27 | const again = html`<form method="post" action="${PEOPLE}/invites/${encodeURIComponent(i.id)}/again"> | |
| 28 | ${btn("Send again", { type: "submit", size: "sm", label: "Send again: a new link like this one" })} | |
| 29 | </form>`; | |
| 30 | return row({ | |
| 31 | title: html`${BUNDLE[i.bundle].label} invite | |
| 32 | <span class="muted small">${ | |
| 33 | i.state === "used" | |
| 34 | ? html`used${i.usedBy === null ? "" : html` by <a href="/${encodeURIComponent(i.usedBy)}">${i.usedBy}</a>`}${i.usedAt === null ? "" : html` ${time(i.usedAt)}`}` | |
| 35 | : stateWord(i) | |
| 36 | }</span>`, | |
| 37 | ...(link === undefined ? {} : { facts: [{ label: "Link", value: html`<input class="input mono" readonly value="${link}" aria-label="Invite link to copy" size="48" />` }] }), | |
| 38 | meta: html`${i.org === null ? "" : `into ${i.org} · `}made ${time(i.createdAt)}${i.state === "open" ? html` · works until ${time(i.expiresAt)}` : ""}`, | |
| 39 | trail: i.state === "used" ? html`` : html`${i.state === "open" ? "" : again}${i.state === "open" ? confirmAction({ action: `${PEOPLE}/invites/${encodeURIComponent(i.id)}/revoke`, verb: "Revoke", size: "sm" }) : ""}`, | |
| 40 | }); | |
| 41 | } | |
| 42 | ||
| 43 | const linkOf = (ctx: Ctx, id: string): string | undefined => { | |
| 44 | const token = tokenOf(ctx.app, ctx.auth.user, id); | |
| 45 | return token === undefined ? undefined : inviteLink(ctx.app.config.url ?? ctx.url.origin, token); | |
| 46 | }; | |
| 47 | ||
| 48 | /** The Invite form and the rows under it. */ | |
| 49 | export function inviteSection(ctx: Ctx): Html { | |
| 50 | const listed = list(ctx.app, ctx.auth.user); | |
| 51 | const invites = listed.ok ? listed.value : []; | |
| 52 | const machines = hostMachines(ctx.app, ctx.auth.user); | |
| 53 | const hostFields = | |
| 54 | machines.length === 0 | |
| 55 | ? html`` | |
| 56 | : disclosure( | |
| 57 | "Host only: machine and caps", | |
| 58 | html`${selectField({ name: "machine", label: "machine", options: machines.map((m) => ({ value: m, label: m })) })} | |
| 59 | ${inputField({ name: "containers", label: "most containers", type: "number", value: "3", min: 1, step: "1", mono: true })} | |
| 60 | ${inputField({ name: "memoryMb", label: "most memory (MB)", type: "number", value: "2048", min: 1, step: "1", mono: true })}`, | |
| 61 | ); | |
| 62 | return html`<section class="settings-block" id="invite"> | |
| 63 | <h2>Invite</h2> | |
| 64 | <form class="row-fields" method="post" action="/admin/invites"> | |
| 65 | <input type="hidden" name="back" value="${PEOPLE}" /> | |
| 66 | <label class="small">organization (optional) | |
| 67 | <input class="input mono" type="text" name="org" maxlength="60" autocomplete="off" /></label> | |
| 68 | ${selectField({ | |
| 69 | name: "bundle", | |
| 70 | label: "what it allows", | |
| 71 | options: BUNDLES.filter((b) => b !== "host" || machines.length > 0).map((b) => ({ value: b, label: `${BUNDLE[b].label}: ${BUNDLE[b].says}`, selected: b === "use" })), | |
| 72 | ...(machines.length === 0 ? { hint: BUNDLE_WORDS.no_machine } : {}), | |
| 73 | })} | |
| 74 | ${hostFields} | |
| 75 | ${btn("Make a link", { size: "sm", variant: "primary", label: "Make an invite link" })} | |
| 76 | </form> | |
| 77 | <p class="small muted">Each link is good for one signup. A waiting invite shows its link to copy.</p> | |
| 78 | ${invites.length === 0 ? null : html`<div id="invites">${rowList(invites.map((i) => inviteRow(i, i.state === "open" ? linkOf(ctx, i.id) : undefined)))}</div>`} | |
| 79 | </section>`; | |
| 80 | } | |
| 81 | ||
| 82 | // POST /settings/people/invites/:id/again | |
| 83 | export async function inviteAgain(ctx: Ctx): Promise<Response> { | |
| 84 | if (!personAdminPage(ctx)) return notFoundPage(ctx); | |
| 85 | const form = await readForm(ctx, "admin"); | |
| 86 | if (form instanceof Response) return form; | |
| 87 | const made = again(ctx.app, ctx.auth.user, ctx.params.id ?? ""); | |
| 88 | if (!made.ok && made.error === "not_found") return notFoundPage(ctx); | |
| 89 | if (!made.ok) return flashTo(ctx, PEOPLE, { tone: "danger", message: made.error in BUNDLE_WORDS ? BUNDLE_WORDS[made.error as keyof typeof BUNDLE_WORDS] : "That link could not be made again; make a new one above." }); | |
| 90 | return flashTo(ctx, PEOPLE, { message: "New invite link made:", code: inviteLink(ctx.app.config.url ?? ctx.url.origin, made.value.token) }); | |
| 91 | } |
src/web/requests_card.ts +1 −1
| @@ -51,7 +51,7 @@ export function requestAct(act: "allow" | "decline") { | ||
| 51 | 51 | const username = ctx.params.username ?? ""; |
| 52 | 52 | const done = (act === "allow" ? allowRequest : declineRequest)(ctx.app, ctx.auth.user, username); |
| 53 | 53 | if (!done.ok && done.error === "not_found") return notFoundPage(ctx); |
| 54 | const to = ctx.url.searchParams.get("back") === "home" ? "/" : "/settings/accounts"; | |
| 54 | const to = ctx.url.searchParams.get("back") === "home" ? "/" : "/settings/people"; | |
| 55 | 55 | return flashTo(ctx, to, { |
| 56 | 56 | message: done.ok |
| 57 | 57 | ? `${username} ${act === "allow" ? "is in" : "was declined, politely"}.` |
src/web/style/content.ts +6
| @@ -209,6 +209,12 @@ a.where-place, button.where-place { cursor: pointer; } | ||
| 209 | 209 | /* A pull's log fold: the tail scrolls sideways inside its own box, never the page. */ |
| 210 | 210 | .card-body > pre { max-width: 100%; overflow-x: auto; margin: 0 0 8px; } |
| 211 | 211 | [data-apps], [data-apps-page], [data-bet-card], [data-explore], [data-family], [data-forges], [data-milestone], [data-new-repo], [data-now], [data-people] { overflow-wrap: anywhere; } |
| 212 | /* People (#18476): a row's words wrap and its acts drop under them on a phone; nothing is clipped or widens the page. */ | |
| 213 | [data-people] .row { flex-wrap: wrap; } | |
| 214 | [data-people] .row-main { flex: 1 1 12rem; min-width: 0; } | |
| 215 | [data-people] .row-title, [data-people] .row-meta { white-space: normal; overflow: visible; } | |
| 216 | [data-people] .row-trail { flex-wrap: wrap; flex: 0 1 auto; min-width: 0; max-width: 100%; } | |
| 217 | [data-people] .row-facts > div { flex-wrap: wrap; } | |
| 212 | 218 | /* /new (#9830): a long owner name or refused value stays inside the form on a phone. */ |
| 213 | 219 | [data-new-repo] form, [data-new-repo] .error { min-width: 0; max-width: 100%; } |
| 214 | 220 | [data-new-repo] select.input { text-overflow: ellipsis; } |
test/account-access.test.ts +3 −3
| @@ -103,13 +103,13 @@ describe("an admin resets a person's access", () => { | ||
| 103 | 103 | }); |
| 104 | 104 | |
| 105 | 105 | test("the accounts list searches by name", async () => { |
| 106 | const hit = await (await get("/settings/accounts?q=bo", owner)).text(); | |
| 106 | const hit = await (await get("/settings/people?q=bo", owner)).text(); | |
| 107 | 107 | expect(hit).toContain("/settings/accounts/bob"); |
| 108 | 108 | expect(hit).not.toContain("/settings/accounts/carol"); |
| 109 | 109 | }); |
| 110 | 110 | |
| 111 | 111 | test("search narrows the list and says when nothing matches", async () => { |
| 112 | const none = await (await get("/settings/accounts?q=zzzz", owner)).text(); | |
| 112 | const none = await (await get("/settings/people?q=zzzz", owner)).text(); | |
| 113 | 113 | expect(none).not.toContain("/settings/accounts/bob"); |
| 114 | 114 | expect(none).not.toContain("/settings/accounts/carol"); |
| 115 | 115 | expect(none).toContain("0 matching"); |
| @@ -168,7 +168,7 @@ describe("an admin resets a person's access", () => { | ||
| 168 | 168 | const link = flashLink(res); |
| 169 | 169 | expect(link).toStartWith("/signin/access/"); |
| 170 | 170 | // Old sessions are gone. |
| 171 | expect((await get("/settings/accounts", bobCookie)).status).not.toBe(200); | |
| 171 | expect((await get("/settings/people", bobCookie)).status).not.toBe(200); | |
| 172 | 172 | // The audit trail names who did it. |
| 173 | 173 | const event = listEvents(app.db, { limit: 50 }).find((e) => e.kind === "account.access_reset"); |
| 174 | 174 | expect(event?.actorId).toBe(getUserByName(app.db, "olive")!.id); |
test/account-close.test.ts +1 −1
| @@ -144,7 +144,7 @@ describe("closing an account", () => { | ||
| 144 | 144 | }); |
| 145 | 145 | |
| 146 | 146 | test("the forge's only admin's refusal is its own line too", async () => { |
| 147 | await refusedThroughPage("alice", "only admin", "/settings/accounts"); | |
| 147 | await refusedThroughPage("alice", "only admin", "/settings/people"); | |
| 148 | 148 | }); |
| 149 | 149 | |
| 150 | 150 | test("an active subscription is refused through the page, linking payments", async () => { |
test/accounts-language.test.ts +8 −10
| @@ -46,22 +46,20 @@ test("a person's sign-ins page is blocks all the way down, no card", async () => | ||
| 46 | 46 | expect((m.match(/class="settings-block"/g) ?? []).length).toBeGreaterThanOrEqual(4); |
| 47 | 47 | }); |
| 48 | 48 | |
| 49 | test("the accounts list is a settings-block under an h2, rows in .list, no card", async () => { | |
| 50 | const m = main(await (await fetch(`${servers.url}/settings/accounts`, { headers: { cookie: admin } })).text()); | |
| 49 | test("the people list is a settings-block under an h2, rows in .list, no card", async () => { | |
| 50 | const m = main(await (await fetch(`${servers.url}/settings/people`, { headers: { cookie: admin } })).text()); | |
| 51 | 51 | expect(m).not.toContain('class="card'); |
| 52 | expect(m).toMatch(/<section class="settings-block" id="accounts">\s*<h2>Who is on this forge<\/h2>/); | |
| 53 | const list = m.slice(m.indexOf('id="accounts-list"')); | |
| 54 | expect(m).toMatch(/<ul class="list[^"]*" id="accounts-list">/); | |
| 55 | expect(list).toContain("bobby"); | |
| 56 | expect(list).toContain("alice"); | |
| 52 | expect(m).toMatch(/<section class="settings-block" id="people">\s*<h2>Who is here<\/h2>/); | |
| 53 | expect(m).toContain("bobby"); | |
| 54 | expect(m).toContain("alice"); | |
| 57 | 55 | }); |
| 58 | 56 | |
| 59 | test("the accounts list keeps its confirm links", async () => { | |
| 60 | const m = main(await (await fetch(`${servers.url}/settings/accounts`, { headers: { cookie: admin } })).text()); | |
| 57 | test("a person's own page keeps the confirm links", async () => { | |
| 58 | const m = main(await (await fetch(`${servers.url}/settings/accounts/bobby`, { headers: { cookie: admin } })).text()); | |
| 61 | 59 | expect(m).toContain("/-/confirm?to=%2Fsettings%2Faccounts%2Fbobby%2Fsuspend"); |
| 62 | 60 | }); |
| 63 | 61 | |
| 64 | 62 | test("a non-admin gets the one 403", async () => { |
| 65 | const r = await fetch(`${servers.url}/settings/accounts`, { headers: { cookie: plain } }); | |
| 63 | const r = await fetch(`${servers.url}/settings/people`, { headers: { cookie: plain } }); | |
| 66 | 64 | expect(r.status).toBe(403); |
| 67 | 65 | }); |
test/accounts-rows.test.ts +14 −17
| @@ -31,16 +31,15 @@ afterAll(async () => { | ||
| 31 | 31 | await rm(dataDir, { recursive: true, force: true }); |
| 32 | 32 | }); |
| 33 | 33 | |
| 34 | test("the accounts are rows under a heading, and no section is a card", async () => { | |
| 35 | const page = await (await fetch(`${servers.url}/settings/accounts`, { headers: { cookie } })).text(); | |
| 34 | test("each person is a list of rows under a heading, and no section is a card", async () => { | |
| 35 | const page = await (await fetch(`${servers.url}/settings/people`, { headers: { cookie } })).text(); | |
| 36 | 36 | const main = page.slice(page.indexOf("<main"), page.indexOf("</main>")); |
| 37 | expect(main).toContain("<h2>Who is on this forge</h2>"); | |
| 38 | expect(main).toContain('<ul class="list setting-list" id="accounts-list">'); | |
| 37 | expect(main).toContain("<h2>Who is here</h2>"); | |
| 38 | expect(main).toContain('data-fragment="/settings/people/row/bobby"'); | |
| 39 | 39 | expect(main).toContain('class="row-title"'); |
| 40 | for (const boxed of ['class="card', "card-head", "card-body", 'class="empty', 'class="rows"']) expect(main).not.toContain(boxed); | |
| 41 | // the acts and their confirm step stay | |
| 42 | expect(main).toContain("%2Fsettings%2Faccounts%2Fbobby%2Fsuspend"); | |
| 43 | expect(main).toContain("%2Fsettings%2Faccounts%2Fbobby%2Fremove"); | |
| 40 | for (const boxed of ['class="card', "card-head", "card-body", 'class="rows"']) expect(main).not.toContain(boxed); | |
| 41 | // the account's own acts live one click away, on its page | |
| 42 | expect(main).toContain("/settings/accounts/bobby"); | |
| 44 | 43 | }); |
| 45 | 44 | |
| 46 | 45 | const section = (page: string, id: string): string => { |
| @@ -63,17 +62,15 @@ const unboxed = (html: string) => { | ||
| 63 | 62 | }; |
| 64 | 63 | |
| 65 | 64 | test("the acts are plain forms and links in a div, not inside a span", async () => { |
| 66 | const page = await (await fetch(`${servers.url}/settings/accounts`, { headers: { cookie } })).text(); | |
| 65 | const page = await (await fetch(`${servers.url}/settings/people`, { headers: { cookie } })).text(); | |
| 67 | 66 | expect(page).toContain('<div class="row-after">'); |
| 68 | 67 | expect(page).not.toContain('<span class="row-after">'); |
| 69 | 68 | expect(page).not.toContain('class="row-actions"'); |
| 70 | 69 | }); |
| 71 | 70 | |
| 72 | test("the mail notice is one headed section", async () => { | |
| 73 | const page = await (await fetch(`${servers.url}/settings/accounts`, { headers: { cookie } })).text(); | |
| 74 | const s = section(page, "no-mail"); | |
| 75 | unboxed(s); | |
| 76 | expect(s).not.toContain("Email verification"); | |
| 71 | test("whether this forge can send mail is said plainly", async () => { | |
| 72 | const page = await (await fetch(`${servers.url}/settings/people`, { headers: { cookie } })).text(); | |
| 73 | expect(page).toMatch(/This forge cannot send mail|This forge can send mail/); | |
| 77 | 74 | }); |
| 78 | 75 | |
| 79 | 76 | test("the suspend confirm, the removal refusal, the retire page and the removed page are headed sections, not cards", async () => { |
| @@ -111,7 +108,7 @@ test("a non-admin is refused with 403, and the page costs a handful of statement | ||
| 111 | 108 | const mallory = await createUser(app.db, { origin: "seed", trusted: true, username: "mallory", email: "[email protected]", password: "correct-horse-battery" }); |
| 112 | 109 | if (!mallory.ok) throw new Error(mallory.error); |
| 113 | 110 | const theirs = `forge_session=${createSession(app.db, getUserByName(app.db, "mallory")!.id).token}`; |
| 114 | expect((await fetch(`${servers.url}/settings/accounts`, { headers: { cookie: theirs } })).status).toBe(403); | |
| 115 | await fetch(`${servers.url}/settings/accounts`, { headers: { cookie } }); | |
| 116 | expectWork(await requestStatements(app.db, `${servers.url}/settings/accounts`, { headers: { cookie } }), { max: 25 }); | |
| 111 | expect((await fetch(`${servers.url}/settings/people`, { headers: { cookie: theirs } })).status).toBe(403); | |
| 112 | await fetch(`${servers.url}/settings/people`, { headers: { cookie } }); | |
| 113 | expectWork(await requestStatements(app.db, `${servers.url}/settings/people`, { headers: { cookie } }), { max: 60 }); | |
| 117 | 114 | }); |
test/accounts-timing.test.ts +4 −4
| @@ -30,14 +30,14 @@ afterAll(async () => { | ||
| 30 | 30 | await rm(dataDir, { recursive: true, force: true }); |
| 31 | 31 | }); |
| 32 | 32 | |
| 33 | test("the accounts page names session, each read and render once each", async () => { | |
| 34 | const res = await fetch(`${servers.url}/settings/accounts`, { headers: { authorization: `Bearer ${bearer}` } }); | |
| 33 | test("the people page names session, each read and render once each", async () => { | |
| 34 | const res = await fetch(`${servers.url}/settings/people`, { headers: { authorization: `Bearer ${bearer}` } }); | |
| 35 | 35 | const page = await res.text(); |
| 36 | 36 | expect(res.status).toBe(200); |
| 37 | expect(page).toContain("Who is on this forge"); | |
| 37 | expect(page).toContain("Who is here"); | |
| 38 | 38 | const parts = (res.headers.get("server-timing") ?? "").split(", "); |
| 39 | 39 | const names = parts.map((p) => p.split(";")[0]!); |
| 40 | for (const n of ["session", "accounts", "mail", "orphans", "owned", "render"]) { | |
| 40 | for (const n of ["session", "people", "facts", "mail", "orphans", "edge-only", "render"]) { | |
| 41 | 41 | expect(names.filter((x) => x === n).length).toBe(1); |
| 42 | 42 | const part = parts.find((p) => p.startsWith(`${n};`))!; |
| 43 | 43 | expect(Number(/dur=([\d.]+)/.exec(part)?.[1])).not.toBeNaN(); |
test/accounts.test.ts +7 −8
| @@ -174,7 +174,7 @@ describe("accounts: the owner sees, suspends and removes", () => { | ||
| 174 | 174 | .status, |
| 175 | 175 | ).toBe(403); |
| 176 | 176 | expect((await api("/api/v1/admin/accounts")).status).toBe(404); |
| 177 | const page = await fetch(`${base}/settings/accounts`, { | |
| 177 | const page = await fetch(`${base}/settings/people`, { | |
| 178 | 178 | headers: { authorization: `Bearer ${token}` }, |
| 179 | 179 | }); |
| 180 | 180 | expect(page.status).toBe(403); |
| @@ -201,15 +201,14 @@ describe("accounts: the owner sees, suspends and removes", () => { | ||
| 201 | 201 | expect(items.find((i) => i.username === "edgy")?.via).toBe("edge"); |
| 202 | 202 | expect(items.find((i) => i.username === "edgy")?.signsInThrough).toBe("open-platform.sh"); |
| 203 | 203 | expect(ada.signsInThrough).toBeNull(); |
| 204 | const page = await fetch(`${base}/settings/accounts`, { | |
| 204 | const page = await fetch(`${base}/settings/people`, { | |
| 205 | 205 | headers: { authorization: `Bearer ${ownerToken}` }, |
| 206 | 206 | }); |
| 207 | 207 | expect(page.status).toBe(200); |
| 208 | 208 | const html = await page.text(); |
| 209 | 209 | expect(html).toContain("ada"); |
| 210 | expect(html).toContain("Suspend"); | |
| 211 | expect(html).toContain("signs in through open-platform.sh"); | |
| 212 | expect(html.match(/signs in through/g)?.length).toBe(1); | |
| 210 | expect(html).toContain("/settings/accounts/ada"); | |
| 211 | expect(html).toContain("through open-platform.sh"); | |
| 213 | 212 | const owner = getUserByName(app.db, "olive")!; |
| 214 | 213 | const lines = newAccountLines(app.db, owner).map((l) => l.line); |
| 215 | 214 | expect(lines).toContain("edgy joined the forge (signs in through open-platform.sh)"); |
| @@ -700,12 +699,12 @@ describe("accounts: the owner sees, suspends and removes", () => { | ||
| 700 | 699 | items: { username: string; verified: boolean }[]; |
| 701 | 700 | }; |
| 702 | 701 | expect(listed.items.find((i) => i.username === "nadia")?.verified).toBe(false); |
| 703 | const page = await fetch(`${base}/settings/accounts`, { | |
| 702 | const page = await fetch(`${base}/settings/people`, { | |
| 704 | 703 | headers: { authorization: `Bearer ${ownerToken}` }, |
| 705 | 704 | }); |
| 706 | 705 | const html = await page.text(); |
| 707 | expect(html).toContain("Verify email"); | |
| 708 | expect(html).toContain("Mail is not configured"); | |
| 706 | expect(html).toContain("Email not proved"); | |
| 707 | expect(html).toContain("This forge cannot send mail"); | |
| 709 | 708 | |
| 710 | 709 | const res = await api("/api/v1/admin/accounts/nadia/verify", { method: "POST", token: ownerToken }); |
| 711 | 710 | expect(res.status).toBe(200); |
test/invites-core.test.ts +2
| @@ -8,6 +8,7 @@ import { Database } from "bun:sqlite"; | ||
| 8 | 8 | 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 | import inviteSealed from "../src/core/migrations/20261206110000-invite-sealed-link.ts"; | |
| 11 | 12 | import { |
| 12 | 13 | inviteOpen, |
| 13 | 14 | inviteSpentBy, |
| @@ -27,6 +28,7 @@ describe("an invite's life", () => { | ||
| 27 | 28 | db.exec(invite); |
| 28 | 29 | db.exec(inviteOrg); |
| 29 | 30 | db.exec(inviteBundle); |
| 31 | db.exec(inviteSealed); | |
| 30 | 32 | db.exec("CREATE TABLE user (id TEXT PRIMARY KEY, username TEXT NOT NULL)"); |
| 31 | 33 | }); |
| 32 | 34 |
test/keys-accounts.test.ts +3 −4
| @@ -30,9 +30,8 @@ afterAll(async () => { | ||
| 30 | 30 | test("every account row is a data-nav row", async () => { |
| 31 | 31 | const alice = getUserByName(app.db, "alice")!; |
| 32 | 32 | const cookie = `forge_session=${createSession(app.db, alice.id).token}`; |
| 33 | const text = await (await fetch(`${servers.url}/settings/accounts`, { headers: { cookie } })).text(); | |
| 34 | const list = text.slice(text.indexOf('id="accounts-list"')); | |
| 35 | const end = list.indexOf("</ul>"); | |
| 36 | const nav = list.slice(0, end).match(/class="row"[^>]*data-nav tabindex="-1"/g); | |
| 33 | const text = await (await fetch(`${servers.url}/settings/people`, { headers: { cookie } })).text(); | |
| 34 | const list = text.slice(text.indexOf('id="people"')); | |
| 35 | const nav = list.match(/class="row"[^>]*data-nav tabindex="-1"/g); | |
| 37 | 36 | expect(nav?.length).toBe(3); |
| 38 | 37 | }); |
test/keys-people-list.test.ts +2 −3
| @@ -50,10 +50,9 @@ test("each person row is one data-nav row whose first link is the person's page" | ||
| 50 | 50 | const res = await fetch(`${servers.url}/settings/people`, { headers: { cookie } }); |
| 51 | 51 | expect(res.status).toBe(200); |
| 52 | 52 | const text = await res.text(); |
| 53 | const rows = [...text.matchAll(/<tr>([\s\S]*?)<\/tr>/g)].filter((m) => m[1]!.includes("data-nav")).map((m) => m[1]!); | |
| 54 | expect(rows.length).toBe(3); | |
| 55 | 53 | const table = text.slice(text.indexOf(`id="people"`)); |
| 56 | expect(table.match(/data-nav/g)!.length).toBe(3); | |
| 54 | const rows = [...table.matchAll(/<(?:a|div)\b[^>]*class="row"[^>]*data-nav tabindex="-1"[^>]*>([\s\S]*?)(?=<(?:a|div)\b[^>]*class="row"|$)/g)].map((m) => m[1]!); | |
| 55 | expect(rows.length).toBe(3); | |
| 57 | 56 | const firsts = rows.map((r) => /<a href="([^"]+)" data-nav/.exec(r)![1]); |
| 58 | 57 | for (const name of ["alice", "bob", "carol"]) expect(firsts).toContain(`/${name}`); |
| 59 | 58 | }); |
test/no-mail-contribute.test.ts +2 −2
| @@ -92,8 +92,8 @@ describe("a new account on a forge that sends no mail", () => { | ||
| 92 | 92 | items: { username: string; verified: boolean }[]; |
| 93 | 93 | }; |
| 94 | 94 | expect(listed.items.find((i) => i.username === "casey")?.verified).toBe(false); |
| 95 | const page = await (await fetch(`${servers.url}/settings/accounts`, { headers: { authorization: `Bearer ${ownerToken}` } })).text(); | |
| 96 | expect(page).toContain("Email not verified"); | |
| 95 | const page = await (await fetch(`${servers.url}/settings/people`, { headers: { authorization: `Bearer ${ownerToken}` } })).text(); | |
| 96 | expect(page).toContain("Email not proved"); | |
| 97 | 97 | }); |
| 98 | 98 | |
| 99 | 99 | const unverified = async (name: string, aged: boolean) => { |
test/org-owners.test.ts +1 −1
| @@ -169,7 +169,7 @@ describe("an organization always keeps a person who owns it", () => { | ||
| 169 | 169 | }); |
| 170 | 170 | const cookie = (signin.headers.get("set-cookie") ?? "").split(";")[0]!; |
| 171 | 171 | const page = await ( |
| 172 | await fetch(`${base}/settings/accounts`, { headers: { cookie } }) | |
| 172 | await fetch(`${base}/settings/people`, { headers: { cookie } }) | |
| 173 | 173 | ).text(); |
| 174 | 174 | expect(page).toContain("only owner of"); |
| 175 | 175 | expect(page).toContain("acme"); |
test/own-session.test.ts +2 −2
| @@ -66,7 +66,7 @@ describe("a forge with no platform edge", () => { | ||
| 66 | 66 | |
| 67 | 67 | test("a private page needs the forge's own session", async () => { |
| 68 | 68 | const cookie = (await signIn()).headers.get("set-cookie")!.split(";")[0]!; |
| 69 | for (const path of ["/olive/vault", "/settings/accounts"]) { | |
| 69 | for (const path of ["/olive/vault", "/settings/people"]) { | |
| 70 | 70 | const anon = await get(path); |
| 71 | 71 | expect(anon.status).not.toBe(200); |
| 72 | 72 | expect(await anon.text()).not.toContain("<h1>vault</"); |
| @@ -79,7 +79,7 @@ describe("a forge with no platform edge", () => { | ||
| 79 | 79 | test("edge headers grant nothing when no edge is configured", async () => { |
| 80 | 80 | const forged = { "x-plat-user": "olive", "x-plat-edge-token": "anything" }; |
| 81 | 81 | expect((await get("/olive/vault", forged)).status).not.toBe(200); |
| 82 | expect((await get("/settings/accounts", forged)).status).not.toBe(200); | |
| 82 | expect((await get("/settings/people", forged)).status).not.toBe(200); | |
| 83 | 83 | }); |
| 84 | 84 | |
| 85 | 85 | test("a session revoked by its owner is refused on the next request", async () => { |
test/pages-budget.test.ts +1
| @@ -91,6 +91,7 @@ const FIXTURE: Record<string, string> = { | ||
| 91 | 91 | "/:owner/:name/display": "/alice/forge/display", |
| 92 | 92 | "/api/v1/admin/machines/:machine/disks": "/api/v1/admin/machines/rack1/disks", |
| 93 | 93 | "/claim/start/:token": "/claim/start/claim_fixture", |
| 94 | "/settings/people/row/:username": "/settings/people/row/alice", | |
| 94 | 95 | "/templates/:owner/:name": "/templates/alice/forge", // marked a template in the setup below |
| 95 | 96 | "/og/template/:ref.svg": "/og/template/alice~forge.svg", |
| 96 | 97 | "/og/template/:ref.png": "/og/template/alice~forge.png", |
test/people-apps-made.test.ts +2 −3
| @@ -54,13 +54,12 @@ test("appsMade lists every owner's apps by name, private ones too", () => { | ||
| 54 | 54 | expect(made.has("no-apps")).toBe(false); |
| 55 | 55 | }); |
| 56 | 56 | |
| 57 | test("each person's row says how many apps and links them; no allowance is said plainly", async () => { | |
| 57 | test("each person's row says how many apps and links them", async () => { | |
| 58 | 58 | const text = await (await fetch(`${servers.url}/settings/people`, { headers: { cookie } })).text(); |
| 59 | const row = (name: string) => text.split("<tr>").find((r) => r.includes(`<a href="/${name}"`))!.replace(/\s+/g, " "); | |
| 59 | const row = (name: string) => text.split("data-fragment=").find((r) => r.includes(`<a href="/${name}"`))!.split("</ul>")[0]!.replace(/\s+/g, " "); | |
| 60 | 60 | expect(row("no-apps")).toContain("No apps yet"); |
| 61 | 61 | expect(row("one-app")).toContain("1 app"); |
| 62 | 62 | expect(row("one-app")).toContain('<a href="/one-app/solo">solo</a>'); |
| 63 | 63 | expect(row("two-apps")).toContain("2 apps"); |
| 64 | 64 | expect(row("two-apps")).toContain('<a href="/two-apps/alpha">alpha</a>, <a href="/two-apps/zeta">zeta</a>'); |
| 65 | expect(row("two-apps")).toContain("no allowance"); | |
| 66 | 65 | }); |
test/people-fit.test.ts +6 −7
| @@ -65,9 +65,9 @@ describe("Settings › People at 390 px", () => { | ||
| 65 | 65 | test("the page renders the seeded long content in many rows", () => { |
| 66 | 66 | expect(page).toContain(WORD); |
| 67 | 67 | expect(page).toContain(LONG); |
| 68 | expect(page.match(/<tr>/g)!.length).toBeGreaterThan(20); | |
| 68 | expect(page.match(/data-fragment="\/settings\/people\/row\//g)!.length).toBeGreaterThan(20); | |
| 69 | 69 | expect(page).toContain("Make member"); |
| 70 | expect(page).toContain("Make guest"); | |
| 70 | expect(page).toContain("Remove"); | |
| 71 | 71 | }); |
| 72 | 72 | |
| 73 | 73 | test("no inline width, and no rule the page ships fixes a width over 390 px", () => { |
| @@ -82,10 +82,9 @@ describe("Settings › People at 390 px", () => { | ||
| 82 | 82 | expect(over).toEqual([]); |
| 83 | 83 | }); |
| 84 | 84 | |
| 85 | test("the table scrolls inside its own box, and its text wraps anywhere", () => { | |
| 86 | // The table sits in a `.table-scroll` box carrying `data-people`. | |
| 87 | expect(page).toMatch(/<div class="table-scroll" data-people>\s*<table class="table" id="people">/); | |
| 88 | expect(components).toMatch(/\.table-scroll\s*\{[^}]*overflow-x:\s*auto/); | |
| 85 | test("the list sits inside its own box, and its text wraps anywhere", () => { | |
| 86 | // The people sit in one box carrying `data-people`. | |
| 87 | expect(page).toMatch(/<div data-people>\s*<ul class="list"/); | |
| 89 | 88 | const rule = content.match(/(?:^|\n)([^\n{]*\[data-people\][^\n{]*)\{([^}]*)\}/); |
| 90 | 89 | expect(rule).not.toBeNull(); |
| 91 | 90 | expect(rule![1]).toMatch(/(?:^|,)\s*\[data-people\]\s*(?:,|$)/); |
| @@ -108,7 +107,7 @@ describe.skipIf(chromium === undefined)("Settings › People, measured at 390x84 | ||
| 108 | 107 | const measure = `(() => { |
| 109 | 108 | const vw = document.documentElement.clientWidth; |
| 110 | 109 | const box = document.querySelector("[data-people]"); |
| 111 | const names = [...document.querySelectorAll("#people td:first-child")]; | |
| 110 | const names = [...document.querySelectorAll("[data-people] .row-title")]; | |
| 112 | 111 | return JSON.stringify({ |
| 113 | 112 | scrollWidth: document.documentElement.scrollWidth, innerWidth: window.innerWidth, viewportWidth: vw, |
| 114 | 113 | boxRight: box ? Math.round(box.getBoundingClientRect().right) : -1, |
test/people-page.test.ts added +189
| @@ -0,0 +1,189 @@ | ||
| 1 | /** | |
| 2 | * /settings/people (#18476): Invite on top, a person is one list of lines each with Remove, | |
| 3 | * /settings/accounts redirects. | |
| 4 | */ | |
| 5 | import { afterAll, beforeAll, expect, test } from "bun:test"; | |
| 6 | import { mkdtempSync, rmSync } from "node:fs"; | |
| 7 | import { tmpdir } from "node:os"; | |
| 8 | import { join } from "node:path"; | |
| 9 | import { createApp, type App } from "../src/app.ts"; | |
| 10 | import { mint, revoke } from "../src/actions/invites.ts"; | |
| 11 | import { takeAway } from "../src/actions/take_away.ts"; | |
| 12 | import { createUser, getUserByName } from "../src/core/users.ts"; | |
| 13 | import { serve, type Servers } from "../src/http/server.ts"; | |
| 14 | import { quietLogs } from "./helpers/globals.ts"; | |
| 15 | ||
| 16 | quietLogs(); | |
| 17 | let root = ""; | |
| 18 | let app: App; | |
| 19 | let servers: Servers; | |
| 20 | let cookie = ""; | |
| 21 | let plain = ""; | |
| 22 | ||
| 23 | const seed = async (username: string, admin = false) => { | |
| 24 | const u = await createUser(app.db, { origin: "seed", trusted: true, username, email: `${username}@forge.local`, password: "a-good-passphrase", adminIfFirst: admin }); | |
| 25 | if (!u.ok) throw new Error(u.error); | |
| 26 | return u.value; | |
| 27 | }; | |
| 28 | const signin = async (username: string): Promise<string> => { | |
| 29 | const r = await fetch(`${servers.url}/signin`, { method: "POST", headers: { origin: servers.url }, body: new URLSearchParams({ username, password: "a-good-passphrase" }), redirect: "manual" }); | |
| 30 | return (r.headers.get("set-cookie") ?? "").split(";")[0]!; | |
| 31 | }; | |
| 32 | const get = (path: string, as = cookie, headers: Record<string, string> = {}) => fetch(`${servers.url}${path}`, { headers: { cookie: as, ...headers }, redirect: "manual" }); | |
| 33 | const post = (path: string, body: Record<string, string> = {}, as = cookie, headers: Record<string, string> = {}) => | |
| 34 | fetch(`${servers.url}${path}`, { method: "POST", headers: { cookie: as, origin: servers.url, ...headers }, body: new URLSearchParams(body), redirect: "manual" }); | |
| 35 | const block = (page: string, name: string): string => { | |
| 36 | const from = page.indexOf(`data-fragment="/settings/people/row/${name}"`); | |
| 37 | expect(from).toBeGreaterThan(-1); | |
| 38 | return page.slice(from, page.indexOf("</ul>", page.indexOf("</ul>", from) > 0 ? from : from)); | |
| 39 | }; | |
| 40 | ||
| 41 | beforeAll(async () => { | |
| 42 | root = mkdtempSync(join(tmpdir(), "forge-people-page-")); | |
| 43 | app = createApp({ dataDir: root, port: 0 }); | |
| 44 | await seed("alice", true); | |
| 45 | const bob = await seed("bob"); | |
| 46 | await seed("plain"); | |
| 47 | app.db.run("INSERT INTO member (user_id, promoted_by, promoted_at) VALUES (?1, ?2, '2026-01-01T00:00:00Z')", [bob.id, bob.id]); | |
| 48 | app.db.run("INSERT INTO model_grant (user_id, usd_per_month, granted_by, granted_at) VALUES (?1, 5, ?1, '2026-01-01T00:00:00Z')", [bob.id]); | |
| 49 | servers = await serve(app); | |
| 50 | cookie = await signin("alice"); | |
| 51 | plain = await signin("plain"); | |
| 52 | }); | |
| 53 | afterAll(() => { | |
| 54 | servers.stop(); | |
| 55 | app.close(); | |
| 56 | rmSync(root, { recursive: true, force: true }); | |
| 57 | }); | |
| 58 | ||
| 59 | test("a person is one list: who, how proved, then one line per thing they can do, each with Remove", async () => { | |
| 60 | const page = await (await get("/settings/people")).text(); | |
| 61 | const bob = block(page, "bob"); | |
| 62 | expect(bob).toContain("proved by"); | |
| 63 | expect(bob).toContain("member"); | |
| 64 | expect(bob).toContain("use models, $5 a month"); | |
| 65 | expect(bob.match(/data-in-place/g)?.length).toBe(2); | |
| 66 | expect(bob).toContain('action="/settings/people/bob/take"'); | |
| 67 | // an owner keeps what they have: no Remove on their block | |
| 68 | expect(block(page, "alice")).not.toContain("data-in-place"); | |
| 69 | }); | |
| 70 | ||
| 71 | test("Remove changes in place: JSON says what to redraw, the fragment no longer has the line", async () => { | |
| 72 | const res = await post("/settings/people/bob/take", { table: "model_grant", key: "" }, cookie, { accept: "application/json" }); | |
| 73 | expect(res.status).toBe(200); | |
| 74 | const said = (await res.json()) as { ok: boolean; redraw: string[] }; | |
| 75 | expect(said.ok).toBe(true); | |
| 76 | expect(said.redraw).toEqual(["/settings/people/row/bob"]); | |
| 77 | const fragment = await (await get(said.redraw[0]!)).text(); | |
| 78 | expect(fragment).not.toContain("use models"); | |
| 79 | expect(fragment).toContain("data-in-place"); | |
| 80 | expect(app.db.query("SELECT 1 FROM model_grant").get()).toBeNull(); | |
| 81 | }); | |
| 82 | ||
| 83 | test("Remove without script redirects with a flash", async () => { | |
| 84 | const res = await post("/settings/people/bob/take", { table: "member", key: "" }); | |
| 85 | expect(res.status).toBe(303); | |
| 86 | expect(res.headers.get("location")).toBe("/settings/people"); | |
| 87 | expect(app.db.query("SELECT 1 FROM member").get()).toBeNull(); | |
| 88 | }); | |
| 89 | ||
| 90 | test("the last owner is kept, and only an admin may Remove", async () => { | |
| 91 | const alice = getUserByName(app.db, "alice")!; | |
| 92 | const refused = await post("/settings/people/alice/take", { table: "member", key: "" }, cookie, { accept: "application/json" }); | |
| 93 | expect(refused.status).toBe(422); | |
| 94 | expect(((await refused.json()) as { error: string }).error).toContain("owner keeps what they have"); | |
| 95 | expect(takeAway(app, alice, "alice", "member", "").ok).toBe(false); | |
| 96 | expect(getUserByName(app.db, "alice")!.isAdmin).toBe(true); | |
| 97 | expect((await post("/settings/people/bob/take", { table: "member", key: "" }, plain)).status).toBe(403); | |
| 98 | expect(takeAway(app, getUserByName(app.db, "plain")!, "bob", "member", "").ok).toBe(false); | |
| 99 | expect((await post("/settings/people/nobody/take", { table: "member", key: "" })).status).toBe(404); | |
| 100 | const odd = await post("/settings/people/bob/take", { table: "user", key: "" }, cookie, { accept: "application/json" }); | |
| 101 | expect(odd.status).toBe(422); | |
| 102 | }); | |
| 103 | ||
| 104 | test("a name is escaped, in a line and in the fragment", async () => { | |
| 105 | const r = await takeAway(app, getUserByName(app.db, "alice")!, "<b>x", "member", ""); | |
| 106 | expect(r.ok).toBe(false); | |
| 107 | expect((await get("/settings/people/row/%3Cb%3Ex")).status).toBe(404); | |
| 108 | const page = await (await get("/settings/people?q=%3Cscript%3E")).text(); | |
| 109 | expect(page).not.toContain("<script>alert"); | |
| 110 | expect(page).toContain("0 matching"); | |
| 111 | }); | |
| 112 | ||
| 113 | test("/settings/accounts redirects to People, and a non-admin is refused there", async () => { | |
| 114 | const res = await get("/settings/accounts"); | |
| 115 | expect(res.status).toBe(303); | |
| 116 | expect(res.headers.get("location")).toBe("/settings/people"); | |
| 117 | expect((await get("/settings/people", plain)).status).toBe(403); | |
| 118 | }); | |
| 119 | ||
| 120 | test("the page says plainly whether this forge can send mail", async () => { | |
| 121 | const page = await (await get("/settings/people")).text(); | |
| 122 | expect(page).toContain("This forge cannot send mail"); | |
| 123 | expect(page.indexOf('id="invite"')).toBeLessThan(page.indexOf('id="mail"')); | |
| 124 | expect(page.indexOf('id="invite"')).toBeLessThan(page.indexOf('id="people"')); | |
| 125 | }); | |
| 126 | ||
| 127 | test("Invite is on top and each invite shows its state: waiting, used, expired, taken back", async () => { | |
| 128 | const alice = getUserByName(app.db, "alice")!; | |
| 129 | const waiting = mint(app, alice); | |
| 130 | const used = mint(app, alice); | |
| 131 | const expired = mint(app, alice); | |
| 132 | const taken = mint(app, alice); | |
| 133 | if (!waiting.ok || !used.ok || !expired.ok || !taken.ok) throw new Error("mint"); | |
| 134 | app.db.run("UPDATE invite SET used_at = '2026-02-01T00:00:00Z', used_by = (SELECT id FROM user WHERE username = 'bob') WHERE id = ?1", [used.value.invite.id]); | |
| 135 | app.db.run("UPDATE invite SET expires_at = '2026-01-01T00:00:00Z' WHERE id = ?1", [expired.value.invite.id]); | |
| 136 | revoke(app, alice, taken.value.invite.id); | |
| 137 | const page = await (await get("/settings/people")).text(); | |
| 138 | const list = page.slice(page.indexOf('id="invites"'), page.indexOf("</ul>", page.indexOf('id="invites"'))); | |
| 139 | for (const word of ["waiting", "used", "expired", "taken back"]) expect(list).toContain(word); | |
| 140 | expect(list).toContain('href="/bob"'); | |
| 141 | // Send again on the expired and the taken-back one, not the waiting (it shows its link) nor the | |
| 142 | // used | |
| 143 | expect(list.match(/\/again"/g)?.length).toBe(2); | |
| 144 | expect(list).not.toContain(`/settings/people/invites/${waiting.value.invite.id}/again`); | |
| 145 | expect(list).toContain(`/settings/people/invites/${expired.value.invite.id}/again`); | |
| 146 | // the waiting one shows its link to copy; the others do not, and the page never shows a spent | |
| 147 | // token | |
| 148 | expect(list).toContain(`/signup?invite=${waiting.value.token}`); | |
| 149 | expect(list).not.toContain(used.value.token); | |
| 150 | expect(list).not.toContain(taken.value.token); | |
| 151 | expect(app.db.query("SELECT token_sealed FROM invite WHERE id = ?1").get(taken.value.invite.id)).toEqual({ token_sealed: null }); | |
| 152 | expect(JSON.stringify(app.db.query("SELECT token_sealed FROM invite WHERE id = ?1").get(waiting.value.invite.id))).not.toContain(waiting.value.token); | |
| 153 | expect(list).not.toContain(`/settings/people/invites/${used.value.invite.id}/again`); | |
| 154 | }); | |
| 155 | ||
| 156 | test("Send again makes a new link with the same bundle and takes the old one back; the link is shown once", async () => { | |
| 157 | const alice = getUserByName(app.db, "alice")!; | |
| 158 | const old = mint(app, alice, undefined, { bundle: "build" }); | |
| 159 | if (!old.ok) throw new Error("mint"); | |
| 160 | const res = await post(`/settings/people/invites/${old.value.invite.id}/again`); | |
| 161 | expect(res.status).toBe(303); | |
| 162 | expect(res.headers.get("location")).toBe("/settings/people"); | |
| 163 | const row = app.db.query<{ bundle: string; revoked_at: string | null }, [string]>("SELECT bundle, revoked_at FROM invite WHERE id = ?1").get(old.value.invite.id)!; | |
| 164 | expect(row.revoked_at).not.toBeNull(); | |
| 165 | const fresh = app.db.query<{ bundle: string }, []>("SELECT bundle FROM invite WHERE revoked_at IS NULL AND bundle = 'build'").all(); | |
| 166 | expect(fresh.length).toBe(1); | |
| 167 | expect((await post(`/settings/people/invites/${old.value.invite.id}/again`, {}, plain)).status).toBe(403); | |
| 168 | }); | |
| 169 | ||
| 170 | test("the Invite form returns to People with the link", async () => { | |
| 171 | const res = await post("/admin/invites", { back: "/settings/people", bundle: "use", org: "" }); | |
| 172 | expect(res.status).toBe(303); | |
| 173 | expect(res.headers.get("location")).toBe("/settings/people"); | |
| 174 | const other = await post("/admin/invites", { back: "https://evil.example/", bundle: "use", org: "" }); | |
| 175 | expect(other.headers.get("location")).toBe("/admin/limits"); | |
| 176 | }); | |
| 177 | ||
| 178 | test("Remove on an app line takes just that app, in place, and the line is gone from the fragment", async () => { | |
| 179 | const bob = getUserByName(app.db, "bob")!; | |
| 180 | app.db.run("INSERT INTO repo (id, owner_id, name, visibility) VALUES ('r-n', ?1, 'notes', 'private')", [bob.id]); | |
| 181 | app.db.run("INSERT INTO app (id, repo_id, slug, access) VALUES ('a-n', 'r-n', 'notes', 'private')"); | |
| 182 | app.db.run("INSERT INTO app_member (app_id, user_id, added_by) VALUES ('a-n', ?1, ?1)", [bob.id]); | |
| 183 | const before = await (await get("/settings/people")).text(); | |
| 184 | expect(block(before, "bob")).toContain('name="key" value="a-n"'); | |
| 185 | const res = await post("/settings/people/bob/take", { table: "app_member", key: "a-n" }, cookie, { accept: "application/json" }); | |
| 186 | expect(res.status).toBe(200); | |
| 187 | expect(app.db.query("SELECT 1 FROM app_member").get()).toBeNull(); | |
| 188 | expect(await (await get("/settings/people/row/bob")).text()).not.toContain('value="a-n"'); | |
| 189 | }); |
test/people-rows.test.ts +1 −1
| @@ -71,5 +71,5 @@ test("the page shows the words, last seen and filter line, and no ids", async () | ||
| 71 | 71 | for (const id of Object.values(ids)) expect(text).not.toContain(id); |
| 72 | 72 | const guests = await (await fetch(`${servers.url}/settings/people?role=guest`, { headers: { cookie } })).text(); |
| 73 | 73 | expect(guests).toContain("old-guest"); |
| 74 | expect(guests.slice(guests.indexOf("id=\"people\"")).split("</table>")[0]).not.toContain("recent-member"); | |
| 74 | expect(guests.slice(guests.indexOf("data-people>")).split("</section>")[0]).not.toContain("recent-member"); | |
| 75 | 75 | }); |
test/people-take-door.test.ts added +127
| @@ -0,0 +1,127 @@ | ||
| 1 | /** | |
| 2 | * The terminal side of the People page (#18476): `x` takes one thing away (and refuses an owner), | |
| 3 | * `x name app repo` takes an app a person was let into, and the Invite links screen shows a waiting | |
| 4 | * link again (`c`) and makes a new one like it (`n`). | |
| 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 as Forge } from "../src/app.ts"; | |
| 11 | import { mint } from "../src/actions/invites.ts"; | |
| 12 | import { listInvites } from "../src/core/invites.ts"; | |
| 13 | import { createUser, getUserByName } from "../src/core/users.ts"; | |
| 14 | import { createForgeApp } from "../src/tui/forge.ts"; | |
| 15 | import { headlessTerminal } from "../src/tui/term/terminal.ts"; | |
| 16 | import { quietLogs } from "./helpers/globals.ts"; | |
| 17 | import { settleApp, settlePalette } from "./helpers/tui.ts"; | |
| 18 | ||
| 19 | quietLogs(); | |
| 20 | let dir = ""; | |
| 21 | let forge: Forge; | |
| 22 | ||
| 23 | const seed = async (username: string, admin = false) => { | |
| 24 | const u = await createUser(forge.db, { origin: "seed", trusted: true, username, email: `${username}@forge.local`, password: "a-good-passphrase", adminIfFirst: admin }); | |
| 25 | if (!u.ok) throw new Error(u.error); | |
| 26 | return u.value; | |
| 27 | }; | |
| 28 | ||
| 29 | beforeAll(async () => { | |
| 30 | dir = await mkdtemp(join(tmpdir(), "forge-people-door-")); | |
| 31 | forge = createApp({ dataDir: dir, port: 0 }); | |
| 32 | await seed("alice", true); | |
| 33 | const bob = await seed("bobby"); | |
| 34 | forge.db.run("INSERT INTO member (user_id, promoted_by, promoted_at) VALUES (?1, ?1, '2026-01-01T00:00:00Z')", [bob.id]); | |
| 35 | forge.db.run("INSERT INTO repo (id, owner_id, name, visibility) VALUES ('r-notes', ?1, 'notes', 'private')", [bob.id]); | |
| 36 | forge.db.run("INSERT INTO app (id, repo_id, slug, access) VALUES ('a-notes', 'r-notes', 'notes', 'private')"); | |
| 37 | forge.db.run("INSERT INTO app_member (app_id, user_id, added_by) VALUES ('a-notes', ?1, ?1)", [bob.id]); | |
| 38 | }); | |
| 39 | afterAll(async () => { | |
| 40 | forge.close(); | |
| 41 | await rm(dir, { recursive: true, force: true }); | |
| 42 | }); | |
| 43 | ||
| 44 | function boot(screen: string) { | |
| 45 | const terminal = headlessTerminal(140, 32); | |
| 46 | const { app } = createForgeApp(forge, { sshUsername: "alice", remoteAddress: "127.0.0.1", fingerprint: "SHA256:test", user: getUserByName(forge.db, "alice")! }, { terminal, exitHooks: false, toastMs: 10 * 60_000 }); | |
| 47 | app.start(); | |
| 48 | const press = async (...keys: string[]) => { | |
| 49 | for (const key of keys) app.dispatch({ type: "key", key, ctrl: false, alt: false, shift: false }); | |
| 50 | await settleApp(app); | |
| 51 | }; | |
| 52 | const type = async (t: string) => { | |
| 53 | for (const ch of t) app.dispatch({ type: "key", key: ch, ctrl: false, alt: false, shift: false }); | |
| 54 | await settleApp(app); | |
| 55 | }; | |
| 56 | return { | |
| 57 | app, | |
| 58 | press, | |
| 59 | type, | |
| 60 | text: () => app.screen.toText(), | |
| 61 | open: async () => { | |
| 62 | await settleApp(app); | |
| 63 | app.dispatch({ type: "key", key: "k", ctrl: true, alt: false, shift: false }); | |
| 64 | await settleApp(app); | |
| 65 | await type(screen); | |
| 66 | await settlePalette(app); | |
| 67 | await press("enter"); | |
| 68 | }, | |
| 69 | }; | |
| 70 | } | |
| 71 | ||
| 72 | describe("People in the terminal: x", () => { | |
| 73 | test("x refuses an owner and says why", async () => { | |
| 74 | const h = boot("People"); | |
| 75 | await h.open(); | |
| 76 | await h.press("x"); | |
| 77 | await h.type("alice member"); | |
| 78 | await h.press("enter"); | |
| 79 | expect(h.text()).toContain("owner keeps what they have"); | |
| 80 | expect(getUserByName(forge.db, "alice")!.isAdmin).toBe(true); | |
| 81 | h.app.stop(); | |
| 82 | }, 30_000); | |
| 83 | ||
| 84 | test("x takes an app a person was let into, and says so; a second time it is already gone", async () => { | |
| 85 | const h = boot("People"); | |
| 86 | await h.open(); | |
| 87 | await h.press("x"); | |
| 88 | await h.type("bobby app notes"); | |
| 89 | await h.press("enter"); | |
| 90 | expect(h.text()).toContain("Took app notes from bobby."); | |
| 91 | expect(forge.db.query("SELECT 1 FROM app_member").get()).toBeNull(); | |
| 92 | await h.press("x"); | |
| 93 | await h.type("bobby app notes"); | |
| 94 | await h.press("enter"); | |
| 95 | expect(h.text()).toContain("nothing like that to take"); | |
| 96 | h.app.stop(); | |
| 97 | }, 30_000); | |
| 98 | ||
| 99 | test("x takes membership, with the success toast", async () => { | |
| 100 | const h = boot("People"); | |
| 101 | await h.open(); | |
| 102 | await h.press("x"); | |
| 103 | await h.type("bobby member"); | |
| 104 | await h.press("enter"); | |
| 105 | expect(h.text()).toContain("Took member from bobby."); | |
| 106 | expect(forge.db.query("SELECT 1 FROM member").get()).toBeNull(); | |
| 107 | h.app.stop(); | |
| 108 | }, 30_000); | |
| 109 | }); | |
| 110 | ||
| 111 | describe("Invite links in the terminal: c and n", () => { | |
| 112 | test("c shows a waiting link again; n makes a new one like it and takes the old one back", async () => { | |
| 113 | const alice = getUserByName(forge.db, "alice")!; | |
| 114 | const made = mint(forge, alice, undefined, { bundle: "build" }); | |
| 115 | if (!made.ok) throw new Error("mint"); | |
| 116 | const h = boot("Invite links"); | |
| 117 | await h.open(); | |
| 118 | await h.press("c"); | |
| 119 | expect(h.text()).toContain(`invite=${made.value.token}`); | |
| 120 | await h.press("n"); | |
| 121 | expect(h.text()).toMatch(/New link: .*invite=invite_/); | |
| 122 | const all = listInvites(forge.db); | |
| 123 | expect(all.find((i) => i.id === made.value.invite.id)!.state).toBe("revoked"); | |
| 124 | expect(all.filter((i) => i.state === "open" && i.bundle === "build").length).toBe(1); | |
| 125 | h.app.stop(); | |
| 126 | }, 30_000); | |
| 127 | }); |
test/request-access.test.ts +2 −2
| @@ -111,12 +111,12 @@ describe("request access", () => { | ||
| 111 | 111 | }); |
| 112 | 112 | |
| 113 | 113 | test("by page: Waiting shows name, note and source with Allow; allowing makes the next load say You're in, once", async () => { |
| 114 | const accounts = await fetch(`${base}/settings/accounts`, { headers: { cookie: admin } }).then((r) => r.text()); | |
| 114 | const accounts = await fetch(`${base}/settings/people`, { headers: { cookie: admin } }).then((r) => r.text()); | |
| 115 | 115 | expect(accounts).toContain('id="waiting"'); |
| 116 | 116 | expect(accounts).toContain("pagey"); |
| 117 | 117 | expect(accounts).toContain("a <b>shop</b> page"); |
| 118 | 118 | expect(accounts).toContain("/settings/accounts/pagey/allow"); |
| 119 | expect(accounts.indexOf('id="waiting"')).toBeLessThan(accounts.indexOf('id="accounts"')); | |
| 119 | expect(accounts.indexOf('id="waiting"')).toBeLessThan(accounts.indexOf('id="people"')); | |
| 120 | 120 | // Only an admin, from this origin, may answer. |
| 121 | 121 | expect(getUserByName(app.db, "pagey")?.waitingAt).not.toBeNull(); |
| 122 | 122 | const allow = await form("/settings/accounts/pagey/allow?back=home", {}, admin); |
test/server-timing-sweep.test.ts +1
test/sole-owner-suspend.test.ts +2 −3
| @@ -113,8 +113,7 @@ describe("suspending an organization's last active owner", () => { | ||
| 113 | 113 | }); |
| 114 | 114 | |
| 115 | 115 | test("the forge's owner is told on the accounts page: the person's row and the organization", async () => { |
| 116 | const accounts = await page("/settings/accounts", ownerCookie); | |
| 117 | expect(accounts).toContain("acme: no active owner"); | |
| 116 | const accounts = await page("/settings/people", ownerCookie); | |
| 118 | 117 | expect(accounts).toContain("has no active owner"); |
| 119 | 118 | expect(accounts).toContain('href="/acme/-/teams/Owners"'); |
| 120 | 119 | // A stranger is told nothing of it. |
| @@ -136,7 +135,7 @@ describe("suspending an organization's last active owner", () => { | ||
| 136 | 135 | expect(api.status).toBe(200); |
| 137 | 136 | expect(suspended()).toBe(true); |
| 138 | 137 | expect(unsuspendAccount(app, olive, "sam").ok).toBe(true); |
| 139 | expect(await page("/settings/accounts", ownerCookie)).not.toContain( | |
| 138 | expect(await page("/settings/people", ownerCookie)).not.toContain( | |
| 140 | 139 | "has no active owner", |
| 141 | 140 | ); |
| 142 | 141 | }); |
new above
offline