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

opened this

Merged 3h 14m ago, live in production

scout/forge:scout/18476-one-people-page-at-settings-people-invit → main 0 commits fork

  • Merged. scout/18476-one-people-page-at-settings-people-invit was merged into main as d9f5ff1.

Review

Sign in to review this change.
55 files changed +1053 −389
docs/design/quiet-debt.json +1 −1
@@ -29,7 +29,7 @@
2929 },
3030 "src/web/pages/accounts.ts": {
3131 "pagehead": 1,
32 "bare-list": 6
32 "bare-list": 5
3333 },
3434 "src/web/pages/admin-limits.ts": {
3535 "row-primary": 1,
docs/features/account-access.md +1 −1
@@ -4,7 +4,7 @@ row: Manage account: reset a person's access
44 ---
55 # Manage account: reset a person's access
66
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.
88
99 - **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.
1010 - **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 @@
11 ---
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
44 ---
55 # People
66
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.
118
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).
1312
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
3434
3535 ## A forge that sends no mail
3636
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 @@
2626 "/settings/features": ["src/web/pages/features.ts"],
2727 "/settings/model": ["src/web/pages/connections.ts"],
2828 "/settings/origins": ["src/web/scope.ts"],
29 "/settings/people": ["src/web/pages/people.ts", "src/web/pages/people_invites.ts"],
2930 "/settings/runners": ["src/web/pages/runners.ts"],
3031 "/settings/traffic": ["src/web/pages/visitors.ts"],
3132 "/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
6666 return {
6767 reason: "sole_admin",
6868 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" },
7070 };
7171 const org = sharedOrg(db, user.id);
7272 if (org !== undefined)
src/actions/invites.ts +32
@@ -10,6 +10,7 @@ import {
1010 isContributor,
1111 listContributors,
1212 listInvites,
13 keepToken,
1314 mintInvite,
1415 mintRepoInvite,
1516 redeemInvite,
@@ -19,6 +20,7 @@ import {
1920 repoOfInvite,
2021 revokeInvite,
2122 revokeRepoInvite,
23 sealedTokenOf,
2224 type Invite,
2325 type RepoInvite,
2426 } from "../core/invites.ts";
@@ -29,6 +31,7 @@ import { getOrg } from "../core/orgs.ts";
2931 import { BUNDLES, HOST_WORDS, parseHost, type Bundle } from "../core/bundles.ts";
3032 import { infraOf, offeredView, type InfraView } from "./infra.ts";
3133 import { err, ok, type Result } from "../kernel/result.ts";
34 import { open, seal } from "../kernel/secret.ts";
3235 import type { User } from "../core/users.ts";
3336
3437 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
103106 host = h.value;
104107 }
105108 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}`));
106110 app.bus.append({
107111 kind: "invite.minted",
108112 actorId: actor.id,
@@ -111,6 +115,34 @@ export function mint(app: App, actor: User | undefined, org?: unknown, choice: B
111115 return ok(made);
112116 }
113117
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
114146 export function list(app: App, actor: User | undefined): Result<Invite[], "not_found"> {
115147 return admin(actor) ? ok(listInvites(app.db)) : err("not_found");
116148 }
src/actions/requests.ts +1 −1
@@ -75,7 +75,7 @@ export function requestLines(
7575 user: User,
7676 ): { id: string; line: string; items: readonly string[]; link: string }[] {
7777 if (!user.isAdmin || user.kind !== "user") return [];
78 const link = "/settings/accounts#waiting";
78 const link = "/settings/people#waiting";
7979 const waiting = waitingRequests(db);
8080 if (waiting.length > LINES_EACH) {
8181 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";
1616 import { provenEmailAt } from "./proven_identities.ts";
1717
1818 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;
1923 readonly username: string;
2024 readonly kind: "user" | "agent";
2125 readonly displayName: string;
@@ -54,6 +58,7 @@ export function listAccounts(db: Database, only = ""): AccountRow[] {
5458 .query<
5559 {
5660 id: string;
61 email: string;
5762 username: string;
5863 display_name: string;
5964 is_admin: number;
@@ -70,7 +75,7 @@ export function listAccounts(db: Database, only = ""): AccountRow[] {
7075 },
7176 [string]
7277 >(
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,
7479 u.created_at, u.suspended_at, u.removed_at, u.waiting_at,
7580 ${provenEmailAt("u")} AS proven_at,
7681 (SELECT COUNT(*) FROM repo r WHERE r.owner_id = u.id) AS repos,
@@ -88,6 +93,9 @@ export function listAccounts(db: Database, only = ""): AccountRow[] {
8893 return rows.map((r) => {
8994 const origin = parseOrigin(r.payload);
9095 return {
96 id: r.id,
97 email: r.email,
98 provenAt: r.proven_at,
9199 username: r.username,
92100 kind: r.is_agent === 1 ? "agent" : "user",
93101 displayName: r.display_name,
src/core/event_audience.ts +2
@@ -244,6 +244,8 @@ export function classifiedAudience(kind: string): EventAudience | undefined {
244244 if (kind === "webhook.failing") return "writers";
245245 // What a repository's beat did says how its autonomy and week's share stand (`crew/beat.ts`).
246246 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";
247249 if (
248250 kind.startsWith("webhook.") ||
249251 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 @@
11 /**
22 * Invite links: a secret handed out once, good for one signup, gone after a
33 * 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`).
99 */
1010
1111 import type { Database } from "bun:sqlite";
@@ -113,6 +113,22 @@ export function mintInvite(
113113 return { invite: view(row, now), token };
114114 }
115115
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
116132 /** Whether `token` names an invite still open now: not used, revoked or expired. */
117133 export function inviteOpen(db: Database, token: string, now: number = Date.now()): boolean {
118134 return (
@@ -134,7 +150,7 @@ export function redeemInvite(db: Database, token: string, userId: string, now: n
134150 return (
135151 db
136152 .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",
138154 )
139155 .run(sha256(token), at, userId).changes === 1
140156 );
@@ -171,7 +187,7 @@ export function revokeInvite(
171187 now: number = Date.now(),
172188 ): Result<Invite, "not_found"> {
173189 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")
175191 .run(inviteId, new Date(now).toISOString()).changes;
176192 if (changed === 0) return err("not_found");
177193 return ok(view(db.query<Row, [string]>(`${SELECT} WHERE invite.id = ?1`).get(inviteId)!, now));
src/core/orgs.ts +11
@@ -276,6 +276,17 @@ export function soleOwnedOrgs(db: Database, userId: string): User[] {
276276 .filter((u): u is User => u !== undefined);
277277 }
278278
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
279290 /**
280291 * Remove a member, refusing to take the last person off the Owners team: an
281292 * 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[] =>
8181 }),
8282 );
8383
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
8499 /**
85100 * Every identity of `userId` in one statement, email first then the Minecraft names oldest first,
86101 * 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
8484 */
8585 export function needsFor(kind: RoutineKind, f: Facts): readonly Need[] {
8686 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 }];
8888 return [];
8989 }
9090
src/design/door_checks.ts −1
@@ -152,7 +152,6 @@ export const DOOR_LINES: readonly DoorLine[] = [
152152 { file: "src/web/pages/everyday.ts", text: 'if (user.isAdmin && user.kind === "user") return everydayForm(ctx, user, false);', why: SHOWN },
153153 { 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" },
154154 { 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 },
156155 { file: "src/web/pages/accounts.ts", text: "const ordinary = !user.isAdmin;", why: SHOWN },
157156 { 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" },
158157 { 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 = [
194194 ["POST", "/settings/accounts/:username/allow"],
195195 ["POST", "/settings/accounts/:username/decline"],
196196 ["GET", "/settings/people"],
197 ["GET", "/settings/people/row/:username"],
197198 ["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"],
198202 ["GET", "/settings/model"],
199203 ["POST", "/settings/model"],
200204 ["POST", "/settings/model/connections"],
src/http/marks/settings.json +4
@@ -156,6 +156,10 @@
156156 "/settings/accounts/:username/decline": "admin",
157157 "/settings/people": "admin",
158158 "/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",
159163 "/settings/model": "open",
160164 "/settings/model/connections": "open",
161165 "/settings/model/connections/:id": "open",
src/http/settings_routes.ts +9 −3
@@ -7,6 +7,7 @@
77 * in the pattern list the usage page reads, so this module never imports it.
88 */
99
10 import { redirect } from "../web/layout.ts";
1011 import { crewKeyAdd } from "../web/studio/crew_key.ts";
1112 import { crewBudgetsSave } from "../web/studio/crew_budgets.ts";
1213 import { fallbackCapSave, fallbackSave } from "../web/studio/crew_fallback.ts";
@@ -41,7 +42,6 @@ import {
4142 accountAct,
4243 retireAct,
4344 retirePage,
44 accountsPage,
4545 wayBackAct,
4646 personSignInsPage,
4747 signInAct,
@@ -94,7 +94,9 @@ import {
9494 subscriptionWake,
9595 subscriptionAllow,
9696 } 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";
98100 import { ceilingAct, grantAct, modelAdd, modelPage } from "../web/pages/model.ts";
99101 import { connectionAdd, connectionEdit, connectionRemove, connectionRetest } from "../web/pages/connections.ts";
100102 import {
@@ -349,11 +351,15 @@ export function settingsRoutes(router: Router<Handler>, knownPatterns: () => rea
349351 router.add("POST", "/settings/backups/mirror", backupsMirror);
350352 router.add("POST", "/settings/backups/mirror/clear", backupsMirrorClear);
351353 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 }));
353355 router.add("POST", "/settings/accounts/:username/allow", requestAct("allow"));
354356 router.add("POST", "/settings/accounts/:username/decline", requestAct("decline"));
355357 router.add("GET", "/settings/people", peoplePage);
358 router.add("GET", "/settings/people/row/:username", personFragment);
356359 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);
357363 router.add("GET", "/settings/model", modelPage);
358364 router.add("POST", "/settings/model", modelAdd);
359365 router.add("POST", "/settings/model/connections", connectionAdd);
src/tui/screens/invites.ts +21 −6
@@ -4,14 +4,16 @@
44 * shows them. `m` mints one from a number of days (1 to 30, 7 by default) and a bundle (Use, Host
55 * with a machine and two caps, or Build) and prints the link once (`o` makes one for an
66 * 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`).
1214 */
1315
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";
1517 import { BUNDLE, BUNDLES } from "../../core/bundles.ts";
1618 import { INVITE_NOT_OPEN } from "../../actions/sever_invite_words.ts";
1719 import { changeAgentStart, changeSignup, readAgentStart, readSignup } from "../../actions/signup.ts";
@@ -157,6 +159,8 @@ export function invitesScreen(f: Session, ctx: Ctx): Screen {
157159 binding(["m"], "make a link: Use, Host or Build"),
158160 binding(["o"], "make a link to an organization"),
159161 binding(["x"], "revoke"),
162 binding(["c"], "show a waiting link"),
163 binding(["n"], "a new link like this one"),
160164 ...(signup().ok ? [binding(["s"], "who may sign up"), binding(["a"], "agents can start here")] : []),
161165 ];
162166 },
@@ -215,6 +219,17 @@ export function invitesScreen(f: Session, ctx: Ctx): Screen {
215219 },
216220 }),
217221 );
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();
218233 } else if (e.key === "s") {
219234 const now = signup();
220235 if (!now.ok) return false;
src/tui/screens/people.ts +26 −2
@@ -6,14 +6,19 @@
66 * after a confirm, with the actions and words MCP `account_suspend` uses.
77 * `v` vouches for the email of the person under the cursor, after a y/n,
88 * 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).
1012 */
1113
1214 import { suspendAccount, unsuspendAccount, verifyAccount } from "../../actions/accounts.ts";
1315 import { mailConfigured } from "../../actions/verify.ts";
1416 import { ADMIN_WORDS } from "../../actions/admin_words.ts";
1517 import { lastOwnerSays } from "../../core/orgs.ts";
18 import { getUserByName } from "../../core/users.ts";
1619 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";
1722 import { AMOUNT_REFUSED } from "../../actions/model_words.ts";
1823 import { peopleByActivity, WORDS, type PersonRow, type RoleWord } from "../../core/people_rows.ts";
1924 import type { Ctx, Screen } from "../app/app.ts";
@@ -91,7 +96,7 @@ export function peopleScreen(f: Session, ctx: Ctx): Screen {
9196 };
9297 const screen: Screen = {
9398 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")],
95100 render(area, s) {
96101 const rows: ListRow[] = people().map((p) => ({
97102 title: rowOf(p),
@@ -154,6 +159,25 @@ export function peopleScreen(f: Session, ctx: Ctx): Screen {
154159 );
155160 return true;
156161 }
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 }
157181 if (e.key !== "r") return false;
158182 ctx.push(
159183 promptScreen(ctx, screen, {
src/web/form.ts +12 −1
@@ -8,16 +8,27 @@
88 * enforce. Auth routes (sign in / up) pass no scope.
99 */
1010
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";
1212 import { BODY_MAX, readBounded, STRANGER_MAX } from "../http/limits.ts";
1313 import { scopeAllows, type TokenScope } from "../core/tokens.ts";
1414 import { isLocalPath } from "./flash.ts";
1515 import type { FieldOptions } from "./ui.ts";
16 import { adminPage, signedInPage } from "../http/page_may.ts";
1617 import { crossOrigin, type Ctx } from "../http/context.ts";
1718 import { controlRefusal, dirtyForm } from "../http/parseable_request.ts";
1819
1920 export type Form = Awaited<ReturnType<Request["formData"]>>;
2021
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
2132 export async function readForm(
2233 ctx: Ctx,
2334 minScope?: TokenScope,
src/web/pages/accounts.ts +17 −199
@@ -9,7 +9,6 @@ import { adminPage, signedInPage } from "../../http/page_may.ts";
99 import { sshOn } from "../../settings/ssh.ts";
1010 import { emptyNote } from "../empty_words.ts";
1111 import {
12 listAccounts,
1312 removeAccount,
1413 retirementPlan,
1514 retireAndRemoveAccount,
@@ -24,17 +23,13 @@ import { roleOf } from "../../core/roles.ts";
2423 import { listSessions } from "../../core/sessions.ts";
2524 import { listTokensWithClients } from "../../core/oauth.ts";
2625 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";
2926 import {
30 OWNERS_TEAM,
31 ownerlessOrgs,
3227 soleOwnedOrgs,
3328 } from "../../core/orgs.ts";
3429 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";
3632 import type { Ctx } from "../../http/context.ts";
37 import { notePhase, takeSessionTime, timePhase } from "../../core/route_timing.ts";
3833 import { notFoundPage, settingsLayout, signInFirst } from "../chrome.ts";
3934 import { field, readForm } from "../form.ts";
4035 import { html, type Html } from "../html.ts";
@@ -52,17 +47,17 @@ import {
5247 import { sessionsCard } from "./account.ts";
5348 import { grantCard } from "./model.ts";
5449 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";
5752
5853 function shell(ctx: Ctx, body: Html, status = 200): Response {
5954 return page(
6055 {
6156 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>
6459 ${settingsLayout(
65 accountSections("accounts", { admin: true, ssh: sshOn(ctx.app.db) }),
60 accountSections("people", { admin: true, ssh: sshOn(ctx.app.db) }),
6661 body,
6762 "Account settings",
6863 )}`,
@@ -71,74 +66,6 @@ function shell(ctx: Ctx, body: Html, status = 200): Response {
7166 );
7267 }
7368
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
14269 // POST /settings/accounts/:username/way-back — the link, shown once on the page.
14370 export async function wayBackAct(ctx: Ctx): Promise<Response> {
14471 if (!signedInPage(ctx)) return signInFirst(ctx);
@@ -149,13 +76,13 @@ export async function wayBackAct(ctx: Ctx): Promise<Response> {
14976 const minted = mintWayBack(ctx.app, ctx.auth.user, username);
15077 if (!minted.ok) {
15178 if (minted.error === "not_found") return notFoundPage(ctx);
152 return flashTo(ctx, "/settings/accounts", {
79 return flashTo(ctx, "/settings/people", {
15380 message: `${username} already signs in without the edge; no link was made.`,
15481 tone: "danger",
15582 });
15683 }
15784 const w = minted.value;
158 const response = accountsView(
85 const response = peopleView(
15986 ctx,
16087 html`<section class="settings-block" id="way-back-link">
16188 <h2>Way-back link for ${w.username}</h2>
@@ -171,115 +98,6 @@ export async function wayBackAct(ctx: Ctx): Promise<Response> {
17198 return response;
17299 }
173100
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
283101 /** Before suspending the last active owner of an organization, say so once. */
284102 function confirmSuspend(username: string, orgs: readonly string[]): Html {
285103 const at = `/settings/accounts/${encodeURIComponent(username)}`;
@@ -302,7 +120,7 @@ function confirmSuspend(username: string, orgs: readonly string[]): Html {
302120 ${orgs[0] === undefined
303121 ? null
304122 : 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" })}
306124 </form>
307125 </section>`;
308126 }
@@ -486,7 +304,7 @@ export function signInAct(what: "token" | "session") {
486304 }
487305
488306 const cannotDo = (ctx: Ctx): Response =>
489 flashTo(ctx, "/settings/accounts", {
307 flashTo(ctx, "/settings/people", {
490308 message: "You cannot do that to yourself, another admin, or an agent.",
491309 tone: "danger",
492310 });
@@ -521,16 +339,16 @@ export function accountAct(act: Act) {
521339 if (!done.ok) {
522340 if (done.error === "not_found") return notFoundPage(ctx);
523341 if (act === "remove" && done.error === "last_owner")
524 return accountsView(ctx, refuseRemove(username), 409);
342 return peopleView(ctx, refuseRemove(username), 409);
525343 if (act === "suspend" && done.error === "last_owner") {
526344 const user = getUserByName(ctx.app.db, username);
527345 const orgs =
528346 user === undefined
529347 ? []
530348 : 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);
532350 }
533 return flashTo(ctx, "/settings/accounts", {
351 return flashTo(ctx, "/settings/people", {
534352 message:
535353 done.error === "not_allowed"
536354 ? "You cannot do that to yourself, another admin, or an agent."
@@ -540,7 +358,7 @@ export function accountAct(act: Act) {
540358 tone: "danger",
541359 });
542360 }
543 return flashTo(ctx, "/settings/accounts", {
361 return flashTo(ctx, "/settings/people", {
544362 message: `${username} ${DONE[act]}.`,
545363 });
546364 };
@@ -598,7 +416,7 @@ export function retirePage(ctx: Ctx): Response {
598416 <form method="post" action="${at}/retire" class="form-actions">
599417 <input type="hidden" name="confirm" value="1" />
600418 ${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" })}
602420 </form>
603421 </section>`,
604422 );
@@ -626,7 +444,7 @@ export async function retireAct(ctx: Ctx): Promise<Response> {
626444 const list = html`<ul>
627445 ${removed.map((n) => html`<li>${n}</li>`)}
628446 </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" });
630448 if (failed !== null)
631449 return shell(
632450 ctx,
src/web/pages/admin-limits.ts +8 −6
@@ -386,6 +386,8 @@ export async function inviteMint(ctx: Ctx): Promise<Response> {
386386 return notFoundPage(ctx);
387387 const form = await readForm(ctx, "admin");
388388 if (form instanceof Response) return form;
389 const wanted = field(form, "back");
390 const back = wanted === "/settings/people" ? wanted : "/admin/limits";
389391 const made = mintInviteLink(ctx.app, ctx.auth.user, field(form, "org"), {
390392 bundle: field(form, "bundle"),
391393 machine: field(form, "machine"),
@@ -394,17 +396,17 @@ export async function inviteMint(ctx: Ctx): Promise<Response> {
394396 });
395397 if (!made.ok && made.error === "not_found") return notFoundPage(ctx);
396398 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." });
398400 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, {
402404 message: "Invite link made. It is shown only now:",
403405 code: inviteLink(ctx.app.config.url ?? ctx.url.origin, made.value.token),
404406 });
405407 }
406408
407 // POST /admin/invites/:id/revoke
409 // POST /admin/invites/:id/revoke, and /settings/people/invites/:id/revoke from the People page
408410 export async function inviteRevoke(ctx: Ctx): Promise<Response> {
409411 if (!personAdminPage(ctx))
410412 return notFoundPage(ctx);
@@ -413,7 +415,7 @@ export async function inviteRevoke(ctx: Ctx): Promise<Response> {
413415 const done = revokeInviteLink(ctx.app, ctx.auth.user, ctx.params.id ?? "");
414416 return flashTo(
415417 ctx,
416 "/admin/limits",
418 ctx.url.pathname.startsWith("/settings/people/") ? "/settings/people" : "/admin/limits",
417419 done.ok
418420 ? { message: "Invite link revoked." }
419421 : { tone: "danger", message: INVITE_NOT_OPEN },
src/web/pages/knobs.ts +3 −6
@@ -5,12 +5,11 @@
55 * leaves the event the setting's own page leaves.
66 */
77
8 import { adminPage, signedInPage } from "../../http/page_may.ts";
98 import { setKnob } from "../../actions/knobs.ts";
109 import { derivedLine, readKnobs, type KnobRow } from "../../crew/knobs.ts";
1110 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";
1413 import { html, type Html } from "../html.ts";
1514 import { flashTo } from "../layout.ts";
1615 import { btn } from "../ui.ts";
@@ -51,9 +50,7 @@ export function knobsCard(ctx: Ctx): Html {
5150
5251 // POST /settings/crew/knobs
5352 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);
5754 if (form instanceof Response) return form;
5855 const knob = field(form, "knob");
5956 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 [
189189 ["Security", "Traffic", "/settings/traffic", "users", (c) => c === "traffic", true],
190190 ["Security", "Trusted sources", "/settings/trusted", "lock", (c) => c === "trusted", true],
191191 ["Security", "Access", "/settings/access", "activity", (c) => c === "access", true],
192 ["This forge", "Accounts", "/settings/accounts", "users", (c) => c === "accounts", true],
193192 ["This forge", "People", "/settings/people", "users", (c) => c === "people", true],
194193 ["This forge", "Hosted forges", "/settings/hosted-forges", "fork", (c) => c === "hosted", true],
195194 ["This forge", "Limits", "/admin/limits", "activity", (c) => c === "limits", true],
src/web/pages/people.ts +188 −66
@@ -1,57 +1,176 @@
11 /**
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.
610 * 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`).
1113 */
1214
1315 import { adminPage, signedInPage } from "../../http/page_may.ts";
1416 import { sshOn } from "../../settings/ssh.ts";
1517 import { setRole } from "../../actions/roles.ts";
18 import { takeAway, TAKE_AWAY_WORDS } from "../../actions/take_away.ts";
1619 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";
1725 import { peopleByActivity, wordFilter, type PersonRow } from "../../core/people_rows.ts";
1826 import { roleLimits } from "../../core/roles.ts";
1927 import { getUserByName, type User } from "../../core/users.ts";
2028 import { notePhase, takeSessionTime, timePhase } from "../../core/route_timing.ts";
2129 import type { Ctx } from "../../http/context.ts";
2230 import { notFoundPage, settingsLayout, signInFirst } from "../chrome.ts";
23 import { field, readForm } from "../form.ts";
31 import { adminForm, field as formField } from "../form.ts";
2432 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";
2838 import { emptyList } from "../empty_words.ts";
2939 import { accountSections } from "./origins.ts";
40 import { peopleCards } from "./people_cards.ts";
41 import { inviteSection } from "./people_invites.ts";
3042
3143 /**
3244 * The apps each username made, by repo name. An admin sees every app, private
3345 * ones included: this page is admin-only and an app is one row per repo, so
3446 * no environment is counted twice.
3547 */
36 export function appsMade(ctx: Ctx): Map<string, string[]> {
48 export function appsMade(ctx: Ctx, only = ""): Map<string, string[]> {
3749 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`,
4052 )
41 .all();
53 .all(only);
4254 const made = new Map<string, string[]>();
4355 for (const r of rows) made.set(r.username, [...(made.get(r.username) ?? []), r.name]);
4456 return made;
4557 }
4658
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 {
49166 if (!signedInPage(ctx)) return signInFirst(ctx);
50167 if (!adminPage(ctx)) return notFoundPage(ctx);
51168 notePhase(ctx.request, "session", takeSessionTime(ctx.request));
52169 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));
55174 const rendering = performance.now();
56175 const filters = html`<p class="small" data-people-filters>Show: ${[
57176 ["", "everyone"],
@@ -66,78 +185,81 @@ export function peoplePage(ctx: Ctx): Response {
66185 : html`<a href="${v === "" ? "/settings/people" : `/settings/people?role=${v}`}">${label}</a>`;
67186 return i === 0 ? [link] : [" · ", link];
68187 })}</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 };
97188 const response = page({
98189 ctx,
99190 title: "People",
191 scriptJs: `${inPlaceJs}\n${behaviorsJs}`,
100192 body: html`<div class="page-head"><h1>People</h1></div>
101193 ${settingsLayout(
102194 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>
105198 ${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>`}
106205 ${
107206 rows.length === 0
108207 ? only === null
109208 ? emptyList("people")
110209 : 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}
117212 <p class="small muted">Allowances go up to $${GRANT_MAX_USD} a month. ${roleLimits()}</p>`
118213 }
119214 </section>`,
120215 "Account settings",
121216 )}`,
122 });
217 }, status);
123218 notePhase(ctx.request, "render", performance.now() - rendering);
124219 return response;
125220 }
126221
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);
133237 if (form instanceof Response) return form;
134238 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");
136258 if (role !== "member" && role !== "guest") return notFoundPage(ctx);
137 const raw = field(form, "usd").trim().replace(/^\$/, "");
259 const raw = formField(form, "usd").trim().replace(/^\$/, "");
138260 const usd = raw === "" || Number(raw) === 0 ? null : /^\d{1,6}(\.\d{1,2})?$/.test(raw) ? Number(raw) : NaN;
139261 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");
141263 const back = isLocalPath(wanted) ? wanted : "/settings/people";
142264 if (!done.ok) {
143265 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") {
5151 const username = ctx.params.username ?? "";
5252 const done = (act === "allow" ? allowRequest : declineRequest)(ctx.app, ctx.auth.user, username);
5353 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";
5555 return flashTo(ctx, to, {
5656 message: done.ok
5757 ? `${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; }
209209 /* A pull's log fold: the tail scrolls sideways inside its own box, never the page. */
210210 .card-body > pre { max-width: 100%; overflow-x: auto; margin: 0 0 8px; }
211211 [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; }
212218 /* /new (#9830): a long owner name or refused value stays inside the form on a phone. */
213219 [data-new-repo] form, [data-new-repo] .error { min-width: 0; max-width: 100%; }
214220 [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", () => {
103103 });
104104
105105 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();
107107 expect(hit).toContain("/settings/accounts/bob");
108108 expect(hit).not.toContain("/settings/accounts/carol");
109109 });
110110
111111 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();
113113 expect(none).not.toContain("/settings/accounts/bob");
114114 expect(none).not.toContain("/settings/accounts/carol");
115115 expect(none).toContain("0 matching");
@@ -168,7 +168,7 @@ describe("an admin resets a person's access", () => {
168168 const link = flashLink(res);
169169 expect(link).toStartWith("/signin/access/");
170170 // 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);
172172 // The audit trail names who did it.
173173 const event = listEvents(app.db, { limit: 50 }).find((e) => e.kind === "account.access_reset");
174174 expect(event?.actorId).toBe(getUserByName(app.db, "olive")!.id);
test/account-close.test.ts +1 −1
@@ -144,7 +144,7 @@ describe("closing an account", () => {
144144 });
145145
146146 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");
148148 });
149149
150150 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 () =>
4646 expect((m.match(/class="settings-block"/g) ?? []).length).toBeGreaterThanOrEqual(4);
4747 });
4848
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());
5151 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");
5755 });
5856
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());
6159 expect(m).toContain("/-/confirm?to=%2Fsettings%2Faccounts%2Fbobby%2Fsuspend");
6260 });
6361
6462 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 } });
6664 expect(r.status).toBe(403);
6765 });
test/accounts-rows.test.ts +14 −17
@@ -31,16 +31,15 @@ afterAll(async () => {
3131 await rm(dataDir, { recursive: true, force: true });
3232 });
3333
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();
3636 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"');
3939 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");
4443 });
4544
4645 const section = (page: string, id: string): string => {
@@ -63,17 +62,15 @@ const unboxed = (html: string) => {
6362 };
6463
6564 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();
6766 expect(page).toContain('<div class="row-after">');
6867 expect(page).not.toContain('<span class="row-after">');
6968 expect(page).not.toContain('class="row-actions"');
7069 });
7170
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/);
7774 });
7875
7976 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
111108 const mallory = await createUser(app.db, { origin: "seed", trusted: true, username: "mallory", email: "[email protected]", password: "correct-horse-battery" });
112109 if (!mallory.ok) throw new Error(mallory.error);
113110 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 });
117114 });
test/accounts-timing.test.ts +4 −4
@@ -30,14 +30,14 @@ afterAll(async () => {
3030 await rm(dataDir, { recursive: true, force: true });
3131 });
3232
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}` } });
3535 const page = await res.text();
3636 expect(res.status).toBe(200);
37 expect(page).toContain("Who is on this forge");
37 expect(page).toContain("Who is here");
3838 const parts = (res.headers.get("server-timing") ?? "").split(", ");
3939 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"]) {
4141 expect(names.filter((x) => x === n).length).toBe(1);
4242 const part = parts.find((p) => p.startsWith(`${n};`))!;
4343 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", () => {
174174 .status,
175175 ).toBe(403);
176176 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`, {
178178 headers: { authorization: `Bearer ${token}` },
179179 });
180180 expect(page.status).toBe(403);
@@ -201,15 +201,14 @@ describe("accounts: the owner sees, suspends and removes", () => {
201201 expect(items.find((i) => i.username === "edgy")?.via).toBe("edge");
202202 expect(items.find((i) => i.username === "edgy")?.signsInThrough).toBe("open-platform.sh");
203203 expect(ada.signsInThrough).toBeNull();
204 const page = await fetch(`${base}/settings/accounts`, {
204 const page = await fetch(`${base}/settings/people`, {
205205 headers: { authorization: `Bearer ${ownerToken}` },
206206 });
207207 expect(page.status).toBe(200);
208208 const html = await page.text();
209209 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");
213212 const owner = getUserByName(app.db, "olive")!;
214213 const lines = newAccountLines(app.db, owner).map((l) => l.line);
215214 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", () => {
700699 items: { username: string; verified: boolean }[];
701700 };
702701 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`, {
704703 headers: { authorization: `Bearer ${ownerToken}` },
705704 });
706705 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");
709708
710709 const res = await api("/api/v1/admin/accounts/nadia/verify", { method: "POST", token: ownerToken });
711710 expect(res.status).toBe(200);
test/invites-core.test.ts +2
@@ -8,6 +8,7 @@ import { Database } from "bun:sqlite";
88 import invite from "../src/core/migrations/20261016200000-invite.ts";
99 import inviteOrg from "../src/core/migrations/20261114090000-invite-org.ts";
1010 import inviteBundle from "../src/core/migrations/20261206100000-invite-bundle.ts";
11 import inviteSealed from "../src/core/migrations/20261206110000-invite-sealed-link.ts";
1112 import {
1213 inviteOpen,
1314 inviteSpentBy,
@@ -27,6 +28,7 @@ describe("an invite's life", () => {
2728 db.exec(invite);
2829 db.exec(inviteOrg);
2930 db.exec(inviteBundle);
31 db.exec(inviteSealed);
3032 db.exec("CREATE TABLE user (id TEXT PRIMARY KEY, username TEXT NOT NULL)");
3133 });
3234
test/keys-accounts.test.ts +3 −4
@@ -30,9 +30,8 @@ afterAll(async () => {
3030 test("every account row is a data-nav row", async () => {
3131 const alice = getUserByName(app.db, "alice")!;
3232 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);
3736 expect(nav?.length).toBe(3);
3837 });
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"
5050 const res = await fetch(`${servers.url}/settings/people`, { headers: { cookie } });
5151 expect(res.status).toBe(200);
5252 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);
5553 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);
5756 const firsts = rows.map((r) => /<a href="([^"]+)" data-nav/.exec(r)![1]);
5857 for (const name of ["alice", "bob", "carol"]) expect(firsts).toContain(`/${name}`);
5958 });
test/no-mail-contribute.test.ts +2 −2
@@ -92,8 +92,8 @@ describe("a new account on a forge that sends no mail", () => {
9292 items: { username: string; verified: boolean }[];
9393 };
9494 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");
9797 });
9898
9999 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", () => {
169169 });
170170 const cookie = (signin.headers.get("set-cookie") ?? "").split(";")[0]!;
171171 const page = await (
172 await fetch(`${base}/settings/accounts`, { headers: { cookie } })
172 await fetch(`${base}/settings/people`, { headers: { cookie } })
173173 ).text();
174174 expect(page).toContain("only owner of");
175175 expect(page).toContain("acme");
test/own-session.test.ts +2 −2
@@ -66,7 +66,7 @@ describe("a forge with no platform edge", () => {
6666
6767 test("a private page needs the forge's own session", async () => {
6868 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"]) {
7070 const anon = await get(path);
7171 expect(anon.status).not.toBe(200);
7272 expect(await anon.text()).not.toContain("<h1>vault</");
@@ -79,7 +79,7 @@ describe("a forge with no platform edge", () => {
7979 test("edge headers grant nothing when no edge is configured", async () => {
8080 const forged = { "x-plat-user": "olive", "x-plat-edge-token": "anything" };
8181 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);
8383 });
8484
8585 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> = {
9191 "/:owner/:name/display": "/alice/forge/display",
9292 "/api/v1/admin/machines/:machine/disks": "/api/v1/admin/machines/rack1/disks",
9393 "/claim/start/:token": "/claim/start/claim_fixture",
94 "/settings/people/row/:username": "/settings/people/row/alice",
9495 "/templates/:owner/:name": "/templates/alice/forge", // marked a template in the setup below
9596 "/og/template/:ref.svg": "/og/template/alice~forge.svg",
9697 "/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", () => {
5454 expect(made.has("no-apps")).toBe(false);
5555 });
5656
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 () => {
5858 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, " ");
6060 expect(row("no-apps")).toContain("No apps yet");
6161 expect(row("one-app")).toContain("1 app");
6262 expect(row("one-app")).toContain('<a href="/one-app/solo">solo</a>');
6363 expect(row("two-apps")).toContain("2 apps");
6464 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");
6665 });
test/people-fit.test.ts +6 −7
@@ -65,9 +65,9 @@ describe("Settings › People at 390 px", () => {
6565 test("the page renders the seeded long content in many rows", () => {
6666 expect(page).toContain(WORD);
6767 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);
6969 expect(page).toContain("Make member");
70 expect(page).toContain("Make guest");
70 expect(page).toContain("Remove");
7171 });
7272
7373 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", () => {
8282 expect(over).toEqual([]);
8383 });
8484
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"/);
8988 const rule = content.match(/(?:^|\n)([^\n{]*\[data-people\][^\n{]*)\{([^}]*)\}/);
9089 expect(rule).not.toBeNull();
9190 expect(rule![1]).toMatch(/(?:^|,)\s*\[data-people\]\s*(?:,|$)/);
@@ -108,7 +107,7 @@ describe.skipIf(chromium === undefined)("Settings › People, measured at 390x84
108107 const measure = `(() => {
109108 const vw = document.documentElement.clientWidth;
110109 const box = document.querySelector("[data-people]");
111 const names = [...document.querySelectorAll("#people td:first-child")];
110 const names = [...document.querySelectorAll("[data-people] .row-title")];
112111 return JSON.stringify({
113112 scrollWidth: document.documentElement.scrollWidth, innerWidth: window.innerWidth, viewportWidth: vw,
114113 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 ()
7171 for (const id of Object.values(ids)) expect(text).not.toContain(id);
7272 const guests = await (await fetch(`${servers.url}/settings/people?role=guest`, { headers: { cookie } })).text();
7373 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");
7575 });
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", () => {
111111 });
112112
113113 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());
115115 expect(accounts).toContain('id="waiting"');
116116 expect(accounts).toContain("pagey");
117117 expect(accounts).toContain("a &lt;b&gt;shop&lt;/b&gt; page");
118118 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"'));
120120 // Only an admin, from this origin, may answer.
121121 expect(getUserByName(app.db, "pagey")?.waitingAt).not.toBeNull();
122122 const allow = await form("/settings/accounts/pagey/allow?back=home", {}, admin);
test/server-timing-sweep.test.ts +1
@@ -45,6 +45,7 @@ const NOT_PAGES = new Set([
4545 * by redirecting.
4646 */
4747 const REDIRECTS = new Set([
48 "/settings/accounts",
4849 "/asked",
4950 "/asks",
5051 "/.well-known/change-password",
test/sole-owner-suspend.test.ts +2 −3
@@ -113,8 +113,7 @@ describe("suspending an organization's last active owner", () => {
113113 });
114114
115115 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);
118117 expect(accounts).toContain("has no active owner");
119118 expect(accounts).toContain('href="/acme/-/teams/Owners"');
120119 // A stranger is told nothing of it.
@@ -136,7 +135,7 @@ describe("suspending an organization's last active owner", () => {
136135 expect(api.status).toBe(200);
137136 expect(suspended()).toBe(true);
138137 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(
140139 "has no active owner",
141140 );
142141 });

Search
↑↓ navigate ↵ open ⌘↵ its app esc close

Keyboard shortcuts

Docs