Public: anyone can read this; the crew can change it.

may() is the only permission check: every remaining helper beside it is deleted, and a test fails if one returns #18498

opened this

Merged 2h 26m ago, live in production

mason/forge:mason/18484-may-is-the-only-permission-check-every-r → main 0 commits fork 2 threads · 2 unresolved

  • Merged. mason/18484-may-is-the-only-permission-check-every-r was merged into main as ad5d09a.

Review

Sign in to review this change.
80 files changed +536 −289
docs/features/forge-size-use.md +1 −1
@@ -14,6 +14,6 @@ The parent passes the size and the cgroup directory in the child's environment (
1414
1515 **A parent** lists every finished child under "Child forges", each name a link to the child, with its size and its use against it, read the same way as on `/forges`. A hosted child reads "shared with this forge" and a stopped cell reads "not running".
1616
17 Both are visible only to the forge's owner (`canSeeMemory`, the same check as the memory block and the terminal entry). Anyone else who opens /system gets neither.
17 Both are visible only to the forge's owner (`forge.administer_person`, the same check as the memory block and the terminal entry). Anyone else who opens /system gets neither.
1818
1919 **Raising to xlarge.** A forge admin presses "Raise to xlarge" on a forge's row on /forges (16 CPUs, 32 GiB from the next start; receipted as `forge.resized`). In the terminal, `w` on "Forges you sent" does the same after a plan and a confirm; the MCP `forges` tool plans it with `{ forge, size: "xlarge" }` and makes it with `dryRun: false` and an admin token. A raise only goes up, and a forge already at xlarge shows no button.
docs/features/forges-refused.md +1 −1
@@ -9,4 +9,4 @@ row: Refused first asks
99 - **Read:** one `listRefusals` call (`core/first_ask_refusals.ts`); nothing is written by the page.
1010 - **Escaped:** the ask is a stranger's text and is escaped on output. The rows hold no email or claim code, so none is shown.
1111 - **Empty:** says "No first ask has been refused."
12 - **Door:** a link on `/system` and a terminal palette entry ("Refused first asks", `src/tui/screens/refused.ts`), both gated by `mayReadRefusals` (an admin who is a person), as the page is; `/forges` gets its own link in #11587.
12 - **Door:** a link on `/system` and a terminal palette entry ("Refused first asks", `src/tui/screens/refused.ts`), both gated by `forge.administer_person` (an admin who is a person), as the page is; `/forges` gets its own link in #11587.
docs/features/may.md +3 −1
@@ -13,7 +13,7 @@ A client asks the forge what it may do instead of reading a role. One function,
1313
1414 Actions are named in one registry (`ACTIONS`), each with one sentence: `repo.read`, `repo.write`, `repo.admin` (over a
1515 repository), `forge.read`, `forge.write` (any change at all, as your account: a session, or a token of scope `rw`), `forge.comment`, `forge.contribute`, `forge.make_it_yours`, `forge.run_crew`,
16 `forge.administer`, and `account.manage` (the account itself, never a token). Over a game box or one server of it:
16 `forge.administer`, `forge.administer_person` (the admin who is a person, never an admin agent), and `account.manage` (the account itself, never a token). Over a game box or one server of it:
1717 `game.view`, `game.operate` and `game.own`, the viewer, operator and owner of `game_grant` (forge admins own every box;
1818 nobody holds a role on the forge's own helper beside the servers).
1919
@@ -99,3 +99,5 @@ Not asked yet: the checks that only filter what a list shows (which servers, sna
9999 the tool's `list`, the terminal's Games list, the cloud's containers and the in-game chat show to whom), and the checks
100100 made again on a background job's behalf (`games/chat.ts`, `games/when_quiet.ts`, `games/shell.ts`). They still read
101101 the grant alone.
102
103 **One check, held by a test.** `test/may-only.test.ts` lists every exported `may…`, `can…` or `isAdmin…` helper under `src/`; the ones not yet folded into `may` are named in its `STILL_TO_FOLD` list (the readers of runs, sealed rows, releases and statements, `canRead`, `canWrite`, `mayOnGame` among them). That list is not empty: #18484 stays open for them, and the list only shrinks. Admin-only pages, screens and tools ask `forge.administer_person`; a repository gate asks `repo.admin`.
src/actions/abstractions.ts +3 −4
@@ -11,20 +11,19 @@ import type { App } from "../app.ts";
1111 import { readAbstractions, type AbstractionAtlas } from "../core/abstractions.ts";
1212 import type { User } from "../core/users.ts";
1313 import { err, ok, type Result } from "../kernel/result.ts";
14 import { holds } from "../core/may.ts";
15 import { principalOfUser } from "../core/principal.ts";
1416
1517 export const ATLAS_TTL_MS = 60_000;
1618
1719 const kept = new WeakMap<Database, { at: number; sized: boolean; atlas: AbstractionAtlas }>();
1820
19 /** One rule for every door to the atlas: a forge admin who is not an agent. */
20 export const mayReadAtlas = (user: User | undefined): boolean => user?.isAdmin === true && user.kind !== "agent";
21
2221 export function listAbstractions(
2322 app: App,
2423 actor: User | undefined,
2524 o: { sizes?: boolean; now?: Date; clock?: number } = {},
2625 ): Result<AbstractionAtlas, "not_found"> {
27 if (!mayReadAtlas(actor)) return err("not_found");
26 if (!holds(app.db, principalOfUser(actor), "forge.administer_person")) return err("not_found");
2827 const clock = o.clock ?? Date.now();
2928 const sized = o.sizes === true;
3029 const hit = kept.get(app.db);
src/actions/apple_crash.ts +4 −3
@@ -8,7 +8,8 @@
88 import type { App } from "../app.ts";
99 import { type CrashGroup, type CrashReport, readCrashGroups, recordCrash } from "../core/apple_crash.ts";
1010 import type { User } from "../core/users.ts";
11 import { mayReadApple } from "./apple_usage.ts";
11 import { holds } from "../core/may.ts";
12 import { principalOfUser } from "../core/principal.ts";
1213
1314 /** How long a new group is news to the notifier. */
1415 const NEWS_MS = 7 * 86_400_000;
@@ -20,7 +21,7 @@ export function keepCrash(app: App, report: CrashReport): void {
2021 }
2122
2223 export function readAppleCrashes(app: App, user: User | null | undefined): { ok: true; value: CrashGroup[] } | { ok: false; error: "not_found" } {
23 if (!mayReadApple(user)) return { ok: false, error: "not_found" };
24 if (!holds(app.db, principalOfUser(user ?? undefined), "forge.administer_person")) return { ok: false, error: "not_found" };
2425 return { ok: true, value: readCrashGroups(app.db) };
2526 }
2627
@@ -30,7 +31,7 @@ export function readAppleCrashes(app: App, user: User | null | undefined): { ok:
3031 * restart starts the notifier from a baseline, so what was already there is not told again.
3132 */
3233 export function crashLines(app: App, user: User, now: number = Date.now()): { line: string; items: readonly string[]; link: string }[] {
33 if (!mayReadApple(user) || user.kind !== "user") return [];
34 if (!holds(app.db, principalOfUser(user), "forge.administer_person") || user.kind !== "user") return [];
3435 const since = new Date(now - NEWS_MS).toISOString();
3536 const fresh = readCrashGroups(app.db).filter((g) => g.firstSeen >= since);
3637 if (fresh.length === 0) return [];
src/actions/apple_usage.ts +3 −4
@@ -7,13 +7,12 @@
77 import type { App } from "../app.ts";
88 import { type UsageRead, readUsage } from "../core/apple_usage.ts";
99 import type { User } from "../core/users.ts";
10 import { holds } from "../core/may.ts";
11 import { principalOfUser } from "../core/principal.ts";
1012
1113 export const USAGE_DAYS = 14;
1214
13 /** A forge admin who is a person: the only reader of anything the Apple app sent. */
14 export const mayReadApple = (user: User | null | undefined): user is User => user?.isAdmin === true && user.kind !== "agent";
15
1615 export function readAppleUsage(app: App, user: User | null | undefined): { ok: true; value: UsageRead } | { ok: false; error: "not_found" } {
17 if (!mayReadApple(user)) return { ok: false, error: "not_found" };
16 if (!holds(app.db, principalOfUser(user ?? undefined), "forge.administer_person")) return { ok: false, error: "not_found" };
1817 return { ok: true, value: readUsage(app.db, USAGE_DAYS) };
1918 }
src/actions/disk_readings.ts +5 −5
@@ -9,8 +9,8 @@ import type { App } from "../app.ts";
99 import type { User } from "../core/users.ts";
1010 import { err, ok, type Result } from "../kernel/result.ts";
1111 import { diskSummary, machineNames, recordReading, type Inventory, type MachineSummary } from "../machines/disk_readings.ts";
12
13 export const mayHandleDisks = (user: User | undefined): user is User => user !== undefined && user.isAdmin && user.kind !== "agent";
12 import { holds } from "../core/may.ts";
13 import { principalOfUser } from "../core/principal.ts";
1414
1515 export type FileError = { code: "not_found" } | { code: "invalid"; says: string };
1616
@@ -23,7 +23,7 @@ export function fileReading(
2323 smartJsonText: unknown,
2424 inventory?: Inventory,
2525 ): Result<{ kind: "nvme" | "behind-controller"; takenAt: number }, FileError> {
26 if (!mayHandleDisks(actor)) return err({ code: "not_found" });
26 if (!holds(app.db, principalOfUser(actor), "forge.administer_person")) return err({ code: "not_found" });
2727 const r = recordReading(app.db, machine, device, smartJsonText, Date.now(), inventory);
2828 if (!r.ok) return err({ code: "invalid", says: `Reading refused: ${r.reason}${r.field ? ` (${r.field})` : ""}.` });
2929 return ok({ kind: r.kind, takenAt: r.takenAt });
@@ -31,11 +31,11 @@ export function fileReading(
3131
3232 /** What the readings of one machine say; nothing for anyone but the owner. */
3333 export function readMachine(app: App, actor: User | undefined, machine: string): Result<MachineSummary, "not_found"> {
34 if (!mayHandleDisks(actor)) return err("not_found");
34 if (!holds(app.db, principalOfUser(actor), "forge.administer_person")) return err("not_found");
3535 return ok(diskSummary(app.db, machine));
3636 }
3737
3838 /** The machines with readings; nothing for anyone but the owner. */
3939 export function readMachines(app: App, actor: User | undefined): Result<string[], "not_found"> {
40 return mayHandleDisks(actor) ? ok(machineNames(app.db)) : err("not_found");
40 return holds(app.db, principalOfUser(actor), "forge.administer_person") ? ok(machineNames(app.db)) : err("not_found");
4141 }
src/actions/explore.ts +3 −4
@@ -42,6 +42,8 @@ import { Stamped } from "../kernel/stamped.ts";
4242 import { listChildren } from "./spawn.ts";
4343 import { parseTemplate } from "../spawn/templates.ts";
4444 import { described } from "../core/readme_description.ts";
45 import { holds } from "../core/may.ts";
46 import { principalOfUser } from "../core/principal.ts";
4547
4648 export type ExploreKind = "app" | "person" | "forge";
4749 export type ExploreSort =
@@ -1194,9 +1196,6 @@ function place(ranked: readonly ExploreRow[], forgeRows: ExploreRow[], query: Ex
11941196 /** What both doors say when an answer has no points. */
11951197 export const NO_POINTS = "No points: nothing matches this query.";
11961198
1197 /** Whether the box is offered: a site admin who is a person. */
1198 export const mayQueryMetric = (user: User | undefined): boolean => user?.isAdmin === true && user.kind !== "agent";
1199
12001199 /**
12011200 * What the box answered: 422 and the first unsupported token, or the lines a chart and a table
12021201 * draw.
@@ -1211,7 +1210,7 @@ export type ExploreMetric =
12111210 * The text is read by `parseMetric`, never evaluated.
12121211 */
12131212 export function exploreMetric(app: App, user: User | undefined, text: string): ExploreMetric | undefined {
1214 if (!mayQueryMetric(user) || text.trim() === "") return undefined;
1213 if (!holds(app.db, principalOfUser(user), "forge.administer_person") || text.trim() === "") return undefined;
12151214 const parsed = parseMetric(text);
12161215 if (!parsed.ok) return { ok: false, status: 422, error: parsed.error };
12171216 const answer = evalMetric(app.db, parsed.metric, { repoIds: "all" });
src/actions/flag_winner.ts +4 −2
@@ -7,11 +7,13 @@
77 */
88
99 import type { App } from "../app.ts";
10 import { FLAGS_ADMIN_ONLY, flagRegistry, mayManageFlags, winnerOffer } from "../core/flags.ts";
10 import { FLAGS_ADMIN_ONLY, flagRegistry, winnerOffer } from "../core/flags.ts";
1111 import type { Issue } from "../core/issues.ts";
1212 import { getRepo } from "../core/repos.ts";
1313 import type { User } from "../core/users.ts";
1414 import { openIssue } from "./issues.ts";
15 import { holds } from "../core/may.ts";
16 import { principalOfUser } from "../core/principal.ts";
1517
1618 export function makeWinnerDefault(
1719 app: App,
@@ -19,7 +21,7 @@ export function makeWinnerDefault(
1921 name: string,
2022 winner: "on" | "off",
2123 ): { ok: true; issue: Issue } | { ok: false; message: string } {
22 if (!mayManageFlags(actor)) return { ok: false, message: FLAGS_ADMIN_ONLY };
24 if (!holds(app.db, principalOfUser(actor), "forge.administer_person")) return { ok: false, message: FLAGS_ADMIN_ONLY };
2325 const registry = flagRegistry();
2426 const decl = (registry.decls as Record<string, { why: string; issue: number }>)[name];
2527 if (!Object.hasOwn(registry.decls, name) || decl === undefined)
src/actions/flags_view.ts +8 −4
@@ -1,12 +1,15 @@
11 /**
22 * The flags a forge admin sees (#7017): every declared flag as plain data —
33 * name, why, default, the issue that owns removing it, and the live value.
4 * One read for the page and the MCP to share; anyone `mayManageFlags` refuses
4 * One read for the page and the MCP to share; anyone `forge.administer_person` refuses
55 * gets the same refusal the page uses.
66 */
77
8 import { FLAGS_ADMIN_ONLY, flagRegistry, mayManageFlags, type FlagDecl, type FlagValue } from "../core/flags.ts";
8 import type { Database } from "bun:sqlite";
9 import { FLAGS_ADMIN_ONLY, flagRegistry, type FlagDecl, type FlagValue } from "../core/flags.ts";
910 import type { User } from "../core/users.ts";
11 import { holds } from "../core/may.ts";
12 import { principalOfUser } from "../core/principal.ts";
1013
1114 export type FlagRow = {
1215 name: string;
@@ -18,9 +21,10 @@ export type FlagRow = {
1821 };
1922
2023 export function readFlags(
21 user: Pick<User, "isAdmin" | "kind"> | undefined,
24 db: Database,
25 user: User | undefined,
2226 ): { ok: true; flags: FlagRow[] } | { ok: false; message: string } {
23 if (!mayManageFlags(user)) return { ok: false, message: FLAGS_ADMIN_ONLY };
27 if (!holds(db, principalOfUser(user), "forge.administer_person")) return { ok: false, message: FLAGS_ADMIN_ONLY };
2428 const registry = flagRegistry();
2529 const decls: Record<string, FlagDecl> = registry.decls;
2630 const flags = Object.entries(decls).map(([name, d]) => ({
src/boards/memory.ts −4
@@ -120,7 +120,3 @@ export function startMemorySampler(
120120 timer.unref?.();
121121 return { tick, stop: () => clearInterval(timer) };
122122 }
123
124 /** Who may read the series: a forge admin who is a person, never an agent. The page, the nav and the terminal all ask this. */
125 export const canSeeMemory = (user: { isAdmin: boolean; kind?: string } | null | undefined): boolean =>
126 user?.isAdmin === true && user.kind !== "agent";
src/core/first_ask_refusals.ts −4
@@ -14,10 +14,6 @@ export const PER_ACTOR_HOUR = 20;
1414 export const KEEP_MS = 30 * 24 * 3_600_000;
1515 const HOUR_MS = 3_600_000;
1616
17 /** Who may read the refusals: a forge admin who is a person. The page, its link on /system and the terminal all ask this. */
18 export const mayReadRefusals = (user: { isAdmin: boolean; kind?: string } | null | undefined): boolean =>
19 user?.isAdmin === true && user.kind !== "agent";
20
2117 export interface Refusal {
2218 readonly id: number;
2319 readonly at: number;
src/core/flags.ts −5
@@ -328,10 +328,5 @@ export function useFlagRegistry(next: Registry | undefined): void {
328328 active = next ?? forgeRegistry;
329329 }
330330
331 /** Whether `user` may see and set flags: an admin who is not an agent. */
332 export function mayManageFlags(user: { isAdmin: boolean; kind: string } | undefined): boolean {
333 return user !== undefined && user.isAdmin && user.kind !== "agent";
334 }
335
336331 /** What a person who may not manage flags is told, by the action, the page and the terminal alike. */
outdated

The function removed above left a double blank line behind. Remove one.

337332 export const FLAGS_ADMIN_ONLY = "Flags are set by a forge admin.";
src/core/may.ts +6
@@ -66,6 +66,11 @@ export const ACTIONS = {
6666 "forge.make_it_yours": forgeAction("make_it_yours"),
6767 "forge.run_crew": forgeAction("run_crew"),
6868 "forge.administer": forgeAction("administer"),
69 "forge.administer_person": {
70 says: "Administer the forge as a person: the admin's own account, never a crew member's, an admin agent included",
71 over: "forge",
72 scope: "rw",
73 },
6974 "visitor.make": {
7075 says: "Make something without an account: a note on an app's page",
7176 over: "forge",
@@ -143,6 +148,7 @@ function forgeRuleHolds(db: Database, action: Action, p: Principal): boolean {
143148 const user = userOf(p);
144149 if (user === undefined) return false;
145150 if (ability === "administer") return user.isAdmin;
151 if (action === "forge.administer_person") return user.isAdmin && user.kind !== "agent";
146152 // `forge.write`: any account may change what is its own to change; the scope says the rest.
147153 if (action === "forge.write") return true;
148154 if (ability !== undefined) return !lacks(db, user, ability);
src/flow/now_rows.ts −4
@@ -80,10 +80,6 @@ const SQL: Record<NowStage, string> = {
8080 /** Rows read and listed: the queue can grow, a page of it cannot. */
8181 export const NOW_LISTED = 200;
8282
83 /** Whether the viewer is shown the Now line and its lists: a site admin who is a person, as home decides it. */
84 export const mayReadNow = (user: { isAdmin: boolean; kind: string } | undefined): boolean =>
85 user !== undefined && user.isAdmin && user.kind !== "agent";
86
8783 export interface NowList {
8884 /** What home counts for the stage. */
8985 readonly total: number;
src/http/api/flags.ts +1 −1
@@ -11,7 +11,7 @@ export function flagsRoutes(router: Router<Handler>): void {
1111 router.add("GET", "/api/v1/flags", (ctx) => {
1212 notePhase(ctx.request, "session", takeSessionTime(ctx.request));
1313 if (!ctx.auth.user) return unauthorized();
14 const out = readFlags(ctx.auth.user);
14 const out = readFlags(ctx.app.db, ctx.auth.user);
1515 if (!out.ok) return apiError("forbidden", 403, out.message);
1616 // The tag is of the exact bytes sent, reached only past the access check: a flag turned on or off
1717 // changes the body, and so the tag (#9214).
src/http/api/packs.ts +6 −4
@@ -7,10 +7,12 @@
77 */
88
99 import { notePhase, takeSessionTime } from "../../core/route_timing.ts";
10 import { editPack, getPack, history, listPacks, mayCurate, resolveRepos, type CuratedPack } from "../../packs/curated.ts";
10 import { editPack, getPack, history, listPacks, resolveRepos, type CuratedPack } from "../../packs/curated.ts";
1111 import { crossOrigin, type Ctx, type Handler } from "../context.ts";
1212 import { apiError, body, forbidden, json, requireScope } from "../respond.ts";
1313 import type { Router } from "../router.ts";
14 import { holds } from "../../core/may.ts";
15 import { principalOfUser } from "../../core/principal.ts";
1416
1517 const view = (ctx: Ctx, p: CuratedPack) => ({
1618 name: p.name,
@@ -19,7 +21,7 @@ const view = (ctx: Ctx, p: CuratedPack) => ({
1921 brief: p.brief,
2022 shown: resolveRepos(ctx.app.db, p, ctx.auth.user).filter((r) => r.left === undefined).map((r) => r.full),
2123 // The list as kept, with why each left one is left out, names private and missing repos: a person admin's only.
22 ...(mayCurate(ctx.auth.user)
24 ...(holds(ctx.app.db, principalOfUser(ctx.auth.user), "forge.administer_person")
2325 ? { repos: p.repos, left_out: resolveRepos(ctx.app.db, p, ctx.auth.user).filter((r) => r.left !== undefined).map((r) => ({ repo: r.full, why: r.left })) }
2426 : {}),
2527 });
@@ -33,14 +35,14 @@ export function packRoutes(router: Router<Handler>): void {
3335 notePhase(ctx.request, "session", takeSessionTime(ctx.request));
3436 const pack = getPack(ctx.app.db, ctx.params.name ?? "");
3537 if (pack === undefined) return apiError("not_found", 404, "no such pack");
36 return json({ ...view(ctx, pack), ...(mayCurate(ctx.auth.user) ? { history: history(ctx.app.db, pack.name) } : {}) });
38 return json({ ...view(ctx, pack), ...(holds(ctx.app.db, principalOfUser(ctx.auth.user), "forge.administer_person") ? { history: history(ctx.app.db, pack.name) } : {}) });
3739 });
3840 router.add("PUT", "/api/v1/packs/:name", async (ctx) => {
3941 notePhase(ctx.request, "session", takeSessionTime(ctx.request));
4042 const denied = requireScope(ctx, "rw");
4143 if (denied) return denied;
4244 if (crossOrigin(ctx.request, ctx.url, ctx.app.log)) return forbidden();
43 if (!mayCurate(ctx.auth.user)) return forbidden();
45 if (!holds(ctx.app.db, principalOfUser(ctx.auth.user), "forge.administer_person")) return forbidden();
4446 const input = await body(ctx.request);
4547 const name = ctx.params.name ?? "";
4648 const create = getPack(ctx.app.db, name) === undefined;
src/http/mcp/shared.ts −1
@@ -608,7 +608,6 @@ export const isAnswer = (v: Repo | Answer): v is Answer => "ok" in v;
608608 * told what is there.
609609 */
610610 export const boardRefused = (): Answer => bad("forbidden", "boards are for a forge admin who is a person");
611 export const mayBoards = (user: User): boolean => user.isAdmin && user.kind !== "agent";
612611 export function boardFailed(e: BoardError): Answer {
613612 if (e === "not_found") return bad("not_found", "no such board");
614613 if (typeof e === "object") return bad("refused", e.refused);
src/http/mcp/tools/account_access.ts +4 −2
@@ -1,6 +1,8 @@
11 import { ACCESS_WORDS, accessUrl, endAllSessions, resetAccess } from "../../../actions/account_access.ts";
22 import { scopeAllows } from "../../../core/tokens.ts";
3 import { good, bad, type Tool, mayBoards } from "../shared.ts";
3 import { good, bad, type Tool } from "../shared.ts";
outdated

Leftover trailing comma and gap: type Tool, }. The same appears in a dozen MCP tools and several TUI screens. Tidy each import.

4 import { holds } from "../../../core/may.ts";
5 import { principalOfUser } from "../../../core/principal.ts";
46
57 export const tool: Tool = {
68 name: "account_access",
@@ -24,7 +26,7 @@ export const tool: Tool = {
2426 return bad("invalid", 'send a username and an action, "reset" or "end_sessions"');
2527 if (endSessions !== undefined && typeof endSessions !== "boolean")
2628 return bad("invalid", "endSessions is true or false");
27 if (!mayBoards(user)) return bad("forbidden", "a person's access is a forge admin's to reset");
29 if (!holds(ctx.app.db, principalOfUser(user), "forge.administer_person")) return bad("forbidden", "a person's access is a forge admin's to reset");
2830 const dryRun = args["dryRun"] !== false;
2931 if (!dryRun && !scopeAllows(ctx.auth.scope ?? "ro", "admin"))
3032 return bad("forbidden", "resetting access needs an admin token");
src/http/mcp/tools/account_requests.ts +4 −2
@@ -1,6 +1,8 @@
11 import { allowRequest, declineRequest, listRequests } from "../../../actions/requests.ts";
22 import { scopeAllows } from "../../../core/tokens.ts";
3 import { good, bad, type Tool, mayBoards } from "../shared.ts";
3 import { good, bad, type Tool } from "../shared.ts";
4 import { holds } from "../../../core/may.ts";
5 import { principalOfUser } from "../../../core/principal.ts";
46
57 export const tool: Tool = {
68 name: "account_requests",
@@ -13,7 +15,7 @@ export const tool: Tool = {
1315 },
1416 writes: true,
1517 run(ctx, user, args) {
16 if (!mayBoards(user)) return bad("not_found", "no such tool here");
18 if (!holds(ctx.app.db, principalOfUser(user), "forge.administer_person")) return bad("not_found", "no such tool here");
1719 const { username, answer } = args;
1820 if (username === undefined && answer === undefined) {
1921 const listed = listRequests(ctx.app, user);
src/http/mcp/tools/account_role.ts +4 −2
@@ -1,7 +1,9 @@
11 import { SPEND_WORDS } from "../../../actions/spend_words.ts";
22 import { setRole } from "../../../actions/roles.ts";
33 import { scopeAllows } from "../../../core/tokens.ts";
4 import { good, bad, type Tool, mayBoards } from "../shared.ts";
4 import { good, bad, type Tool } from "../shared.ts";
5 import { holds } from "../../../core/may.ts";
6 import { principalOfUser } from "../../../core/principal.ts";
57
68 export const tool: Tool = {
79 name: "account_role",
@@ -28,7 +30,7 @@ export const tool: Tool = {
2830 !(usdPerMonth === undefined || usdPerMonth === null || (typeof usdPerMonth === "number" && Number.isFinite(usdPerMonth)))
2931 )
3032 return bad("invalid", 'send a username and a role, "member" or "guest"');
31 if (!mayBoards(user)) return bad("forbidden", "a role is a forge admin's to set");
33 if (!holds(ctx.app.db, principalOfUser(user), "forge.administer_person")) return bad("forbidden", "a role is a forge admin's to set");
3234 const usd = typeof usdPerMonth === "number" ? usdPerMonth : null;
3335 if (args["dryRun"] !== false)
3436 return good({
src/http/mcp/tools/account_suspend.ts +4 −2
@@ -2,7 +2,9 @@ import { suspendAccount, unsuspendAccount } from "../../../actions/accounts.ts";
22 import { scopeAllows } from "../../../core/tokens.ts";
33 import { lastOwnerSays } from "../../../core/orgs.ts";
44 import { ADMIN_WORDS } from "../../../actions/admin_words.ts";
5 import { good, bad, type Tool, mayBoards } from "../shared.ts";
5 import { good, bad, type Tool } from "../shared.ts";
6 import { holds } from "../../../core/may.ts";
7 import { principalOfUser } from "../../../core/principal.ts";
68
79 export const tool: Tool = {
810 name: "account_suspend",
@@ -18,7 +20,7 @@ export const tool: Tool = {
1820 const { username, suspended } = args;
1921 if (typeof username !== "string" || typeof suspended !== "boolean")
2022 return bad("invalid", "send a username and suspended, true or false");
21 if (!mayBoards(user)) return bad("forbidden", "an account is a forge admin's to suspend");
23 if (!holds(ctx.app.db, principalOfUser(user), "forge.administer_person")) return bad("forbidden", "an account is a forge admin's to suspend");
2224 if (!scopeAllows(ctx.auth.scope ?? "ro", "admin"))
2325 return bad("forbidden", "suspending needs an admin token");
2426 const done = suspended
src/http/mcp/tools/account_verify.ts +4 −2
@@ -1,6 +1,8 @@
11 import { verifyAccount } from "../../../actions/accounts.ts";
22 import { scopeAllows } from "../../../core/tokens.ts";
3 import { good, bad, type Tool, mayBoards } from "../shared.ts";
3 import { good, bad, type Tool } from "../shared.ts";
4 import { holds } from "../../../core/may.ts";
5 import { principalOfUser } from "../../../core/principal.ts";
46
57 export const tool: Tool = {
68 name: "account_verify",
@@ -15,7 +17,7 @@ export const tool: Tool = {
1517 run(ctx, user, args) {
1618 const { username } = args;
1719 if (typeof username !== "string") return bad("invalid", "send a username");
18 if (!mayBoards(user)) return bad("forbidden", "verifying a person is a forge admin's call");
20 if (!holds(ctx.app.db, principalOfUser(user), "forge.administer_person")) return bad("forbidden", "verifying a person is a forge admin's call");
1921 if (!scopeAllows(ctx.auth.scope ?? "ro", "admin"))
2022 return bad("forbidden", "verifying a person needs an admin token");
2123 const done = verifyAccount(ctx.app, user, username);
src/http/mcp/tools/audit.ts +4 −2
@@ -1,7 +1,9 @@
11 import { audit } from "../../../contract/audit.ts";
22 import { appsOf } from "../../../web/studio/asks.ts";
33 import { advisoryView } from "../../../core/exposure.ts";
4 import { good, bad, type Tool, REPO_ARG, mayBoards, repoArg, isAnswer } from "../shared.ts";
4 import { good, bad, type Tool, REPO_ARG, repoArg, isAnswer } from "../shared.ts";
5 import { holds } from "../../../core/may.ts";
6 import { principalOfUser } from "../../../core/principal.ts";
57
68 export const tool: Tool = {
79 name: "audit",
@@ -18,7 +20,7 @@ export const tool: Tool = {
1820 writes: false,
1921 async run(ctx, user, args) {
2022 if (typeof args["advisories"] === "string") {
21 if (!mayBoards(user)) return bad("forbidden", "advisories are for a forge admin who is a person");
23 if (!holds(ctx.app.db, principalOfUser(user), "forge.administer_person")) return bad("forbidden", "advisories are for a forge admin who is a person");
2224 return good({ advisories: await advisoryView(ctx.app.db, ctx.app.reposRoot, args["advisories"].slice(0, 80)) });
2325 }
2426 const one =
src/http/mcp/tools/board_delete.ts +4 −2
@@ -1,5 +1,7 @@
11 import { deleteBoard } from "../../../actions/boards.ts";
2 import { good, type Tool, str, boardRefused, mayBoards, boardFailed } from "../shared.ts";
2 import { good, type Tool, str, boardRefused, boardFailed } from "../shared.ts";
3 import { holds } from "../../../core/may.ts";
4 import { principalOfUser } from "../../../core/principal.ts";
35
46 export const tool: Tool = {
57 name: "board_delete",
@@ -16,7 +18,7 @@ export const tool: Tool = {
1618 tier: "delete",
1719 where: "on the board's own page (/boards/<slug>), with its Delete button",
1820 async run(ctx, user, args) {
19 if (!mayBoards(user)) return boardRefused();
21 if (!holds(ctx.app.db, principalOfUser(user), "forge.administer_person")) return boardRefused();
2022 const done = await deleteBoard(ctx.app, user, str(args["slug"]));
2123 return done.ok ? good({ deleted: str(args["slug"]) }) : boardFailed(done.error);
2224 },
src/http/mcp/tools/board_pins.ts +4 −2
@@ -1,6 +1,8 @@
11 import { listPinned as listPinnedPanels, movePinned, pinPanel, unpinPanel } from "../../../actions/board-pins.ts";
2 import { good, bad, type Tool, boardRefused, mayBoards } from "../shared.ts";
2 import { good, bad, type Tool, boardRefused } from "../shared.ts";
33 import { PIN_OP_WORDS } from "../../../core/arg_words.ts";
4 import { holds } from "../../../core/may.ts";
5 import { principalOfUser } from "../../../core/principal.ts";
46
57 export const tool: Tool = {
68 name: "board_pins",
@@ -19,7 +21,7 @@ export const tool: Tool = {
1921 },
2022 writes: true,
2123 async run(ctx, user, args) {
22 if (!mayBoards(user)) return boardRefused();
24 if (!holds(ctx.app.db, principalOfUser(user), "forge.administer_person")) return boardRefused();
2325 const op = args["op"];
2426 if (op === undefined) {
2527 const listed = await listPinnedPanels(ctx.app, user);
src/http/mcp/tools/board_write.ts +4 −2
@@ -1,5 +1,7 @@
11 import { writeBoard } from "../../../actions/boards.ts";
2 import { good, type Tool, str, boardRefused, mayBoards, boardFailed } from "../shared.ts";
2 import { good, type Tool, str, boardRefused, boardFailed } from "../shared.ts";
3 import { holds } from "../../../core/may.ts";
4 import { principalOfUser } from "../../../core/principal.ts";
35
46 export const tool: Tool = {
57 name: "board_write",
@@ -17,7 +19,7 @@ export const tool: Tool = {
1719 },
1820 writes: true,
1921 async run(ctx, user, args) {
20 if (!mayBoards(user)) return boardRefused();
22 if (!holds(ctx.app.db, principalOfUser(user), "forge.administer_person")) return boardRefused();
2123 const done = await writeBoard(ctx.app, user, str(args["slug"]), args["board"]);
2224 return done.ok ? good({ slug: str(args["slug"]), ...done.value }) : boardFailed(done.error);
2325 },
src/http/mcp/tools/boards.ts +4 −2
@@ -1,7 +1,9 @@
11 import { listAllBoards, showBoard } from "../../../actions/boards.ts";
22 import { panelData, parseWindow } from "../../../boards/panel_data.ts";
33 import { panelNow } from "../../../boards/panel_now.ts";
4 import { good, bad, type Tool, str, boardRefused, mayBoards, boardFailed } from "../shared.ts";
4 import { good, bad, type Tool, str, boardRefused, boardFailed } from "../shared.ts";
5 import { holds } from "../../../core/may.ts";
6 import { principalOfUser } from "../../../core/principal.ts";
57
68 export const tool: Tool = {
79 name: "boards",
@@ -21,7 +23,7 @@ export const tool: Tool = {
2123 },
2224 writes: false,
2325 async run(ctx, user, args) {
24 if (!mayBoards(user)) return boardRefused();
26 if (!holds(ctx.app.db, principalOfUser(user), "forge.administer_person")) return boardRefused();
2527 if (args["slug"] === undefined) {
2628 const listed = await listAllBoards(ctx.app, user);
2729 return listed.ok
src/http/mcp/tools/flag_set.ts +4 −2
@@ -1,6 +1,8 @@
1 import { checkInput, flagRegistry, mayManageFlags } from "../../../core/flags.ts";
1 import { checkInput, flagRegistry } from "../../../core/flags.ts";
22 import { scopeAllows } from "../../../core/tokens.ts";
33 import { good, bad, type Tool } from "../shared.ts";
4 import { holds } from "../../../core/may.ts";
5 import { principalOfUser } from "../../../core/principal.ts";
46
57 export const tool: Tool = {
68 name: "flag_set",
@@ -18,7 +20,7 @@ export const tool: Tool = {
1820 },
1921 writes: true,
2022 run(ctx, user, args) {
21 if (!mayManageFlags(user)) return bad("forbidden", "Flags are set by a forge admin.");
23 if (!holds(ctx.app.db, principalOfUser(user), "forge.administer_person")) return bad("forbidden", "Flags are set by a forge admin.");
2224 if (!scopeAllows(ctx.auth.scope ?? "ro", "admin"))
2325 return bad("forbidden", "setting a flag needs an admin token");
2426 const { name, value, clear } = args;
src/http/mcp/tools/flag_winner.ts +3 −2
@@ -1,7 +1,8 @@
11 import { makeWinnerDefault } from "../../../actions/flag_winner.ts";
2 import { mayManageFlags } from "../../../core/flags.ts";
32 import { scopeAllows } from "../../../core/tokens.ts";
43 import { good, bad, type Tool } from "../shared.ts";
4 import { holds } from "../../../core/may.ts";
5 import { principalOfUser } from "../../../core/principal.ts";
56
67 export const tool: Tool = {
78 name: "flag_winner",
@@ -15,7 +16,7 @@ export const tool: Tool = {
1516 },
1617 writes: true,
1718 run(ctx, user, args) {
18 if (!mayManageFlags(user)) return bad("forbidden", "Flags are set by a forge admin.");
19 if (!holds(ctx.app.db, principalOfUser(user), "forge.administer_person")) return bad("forbidden", "Flags are set by a forge admin.");
1920 if (!scopeAllows(ctx.auth.scope ?? "ro", "admin"))
2021 return bad("forbidden", "a flag's default needs an admin token");
2122 const { name, winner } = args;
src/http/mcp/tools/flags.ts +2 −2
@@ -8,8 +8,8 @@ export const tool: Tool = {
88 description: "Declared flags: why, default, owner issue, live value.",
99 inputSchema: { type: "object", properties: {} },
1010 writes: false,
11 run(_ctx, user) {
12 const out = readFlags(user);
11 run(ctx, user) {
12 const out = readFlags(ctx.app.db, user);
1313 return out.ok ? good({ flags: out.flags }) : bad("forbidden", out.message);
1414 },
1515 };
src/http/mcp/tools/forges.ts +4 −2
@@ -1,6 +1,6 @@
11 import { BILLING_WORDS, grantPlan, planGrant, readPlan } from "../../../actions/billing.ts";
22 import { CODE_ERRORS, makeCode, planCode, readCodes, revoke } from "../../../actions/codes.ts";
3 import { REFUSED_SHOWN, listRefusals, mayReadRefusals } from "../../../core/first_ask_refusals.ts";
3 import { REFUSED_SHOWN, listRefusals } from "../../../core/first_ask_refusals.ts";
44 import { publicOrigin } from "../../../core/public_origin.ts";
55 import { scopeAllows } from "../../../core/tokens.ts";
66 import { clientLines, sentLines } from "../../../spawn/client_words.ts";
@@ -15,6 +15,8 @@ import { moveToCell } from "../../../spawn/move_cell.ts";
1515 import { resizeForge } from "../../../spawn/manage.ts";
1616 import { previewDoor, reissueDoor } from "../../../spawn/door.ts";
1717 import { good, bad, type Tool, str, LINK_REVEALED } from "../shared.ts";
18 import { holds } from "../../../core/may.ts";
19 import { principalOfUser } from "../../../core/principal.ts";
1820
1921 const sentSays = (n: number) => (n === 0 ? "This forge has sent no forges yet." : `${n} forge${n === 1 ? "" : "s"} sent from here.`);
2022
@@ -78,7 +80,7 @@ export const tool: Tool = {
7880 return good({ says: silent.length === 0 ? "Every machine is beating." : `Silent: ${silent.join(", ")}.`, machines: machineLines(ctx.app), silent, emptiest: emptiest(ctx.app) });
7981 }
8082 if (args["kind"] !== "refused") return bad("invalid", "kind is refused, clients or machines");
81 if (!mayReadRefusals(user)) return bad("forbidden", "only an admin of this forge sees the refused first asks");
83 if (!holds(ctx.app.db, principalOfUser(user), "forge.administer_person")) return bad("forbidden", "only an admin of this forge sees the refused first asks");
8284 const refused = listRefusals(ctx.app.db, REFUSED_SHOWN, Date.now());
8385 return good({ says: refused.length === 0 ? "No first ask has been refused." : `The last ${refused.length} refused first asks, newest first.`, refused });
8486 }
src/http/mcp/tools/invites.ts +4 −2
@@ -1,6 +1,8 @@
11 import { list as listInviteLinks, revoke as revokeInviteLink } from "../../../actions/invites.ts";
22 import { scopeAllows } from "../../../core/tokens.ts";
3 import { good, bad, type Tool, mayBoards } from "../shared.ts";
3 import { good, bad, type Tool } from "../shared.ts";
4 import { holds } from "../../../core/may.ts";
5 import { principalOfUser } from "../../../core/principal.ts";
46
57 export const tool: Tool = {
68 name: "invites",
@@ -19,7 +21,7 @@ export const tool: Tool = {
1921 // Its read (listing invite links) is never held for a Do it: only its writes are.
2022 heldNotWhen: (args) => args["action"] === "list",
2123 run(ctx, user, args) {
22 if (!mayBoards(user)) return bad("forbidden", "invites are a forge admin's");
24 if (!holds(ctx.app.db, principalOfUser(user), "forge.administer_person")) return bad("forbidden", "invites are a forge admin's");
2325 if (!scopeAllows(ctx.auth.scope ?? "ro", "admin"))
2426 return bad("forbidden", "invites need an admin token");
2527 const action = args["action"];
src/http/mcp/tools/mint_invite.ts +4 −2
@@ -1,7 +1,9 @@
11 import { SPEND_WORDS } from "../../../actions/spend_words.ts";
22 import { inviteLink, mint as mintInviteLink } from "../../../actions/invites.ts";
33 import { scopeAllows } from "../../../core/tokens.ts";
4 import { good, bad, type Tool, mayBoards } from "../shared.ts";
4 import { good, bad, type Tool } from "../shared.ts";
5 import { holds } from "../../../core/may.ts";
6 import { principalOfUser } from "../../../core/principal.ts";
57
68 export const tool: Tool = {
79 name: "mint_invite",
@@ -18,7 +20,7 @@ export const tool: Tool = {
1820 },
1921 writes: true,
2022 run(ctx, user, args) {
21 if (!mayBoards(user)) return bad("forbidden", "an invite is a forge admin's to mint");
23 if (!holds(ctx.app.db, principalOfUser(user), "forge.administer_person")) return bad("forbidden", "an invite is a forge admin's to mint");
2224 if (!scopeAllows(ctx.auth.scope ?? "ro", "admin"))
2325 return bad("forbidden", "an invite needs an admin token");
2426 const made = mintInviteLink(ctx.app, user, args["days"], args["org"]);
src/http/mcp/tools/model_ceiling.ts +4 −2
@@ -1,7 +1,9 @@
11 import { SPEND_WORDS } from "../../../actions/spend_words.ts";
22 import { setAccountCeilings } from "../../../actions/model_grant.ts";
33 import { scopeAllows } from "../../../core/tokens.ts";
4 import { good, bad, type Tool, mayBoards } from "../shared.ts";
4 import { good, bad, type Tool } from "../shared.ts";
5 import { holds } from "../../../core/may.ts";
6 import { principalOfUser } from "../../../core/principal.ts";
57
68 export const tool: Tool = {
79 name: "model_ceiling",
@@ -28,7 +30,7 @@ export const tool: Tool = {
2830 !(perRunUsd === null || (typeof perRunUsd === "number" && Number.isFinite(perRunUsd)))
2931 )
3032 return bad("invalid", "send a username, dailyUsd and perRunUsd in dollars (both null takes them back)");
31 if (!mayBoards(user)) return bad("forbidden", "a ceiling is a forge admin's to set");
33 if (!holds(ctx.app.db, principalOfUser(user), "forge.administer_person")) return bad("forbidden", "a ceiling is a forge admin's to set");
3234 if (args["dryRun"] !== false)
3335 return good({
3436 username,
src/http/mcp/tools/model_grant.ts +4 −2
@@ -1,7 +1,9 @@
11 import { SPEND_WORDS } from "../../../actions/spend_words.ts";
22 import { setAccountGrant } from "../../../actions/model_grant.ts";
33 import { scopeAllows } from "../../../core/tokens.ts";
4 import { good, bad, type Tool, mayBoards } from "../shared.ts";
4 import { good, bad, type Tool } from "../shared.ts";
5 import { holds } from "../../../core/may.ts";
6 import { principalOfUser } from "../../../core/principal.ts";
57
68 export const tool: Tool = {
79 name: "model_grant",
@@ -24,7 +26,7 @@ export const tool: Tool = {
2426 const username = args["username"];
2527 if (typeof username !== "string" || typeof usd !== "number" || !Number.isFinite(usd))
2628 return bad("invalid", "send a username and usdPerMonth in dollars");
27 if (!mayBoards(user)) return bad("forbidden", "a model grant is a forge admin's to give");
29 if (!holds(ctx.app.db, principalOfUser(user), "forge.administer_person")) return bad("forbidden", "a model grant is a forge admin's to give");
2830 const dryRun = args["dryRun"] !== false;
2931 if (dryRun)
3032 return good({
src/http/mcp/tools/restore_drill.ts +4 −2
@@ -3,7 +3,9 @@ import { costLine } from "../../../snapshot/drill_cost.ts";
33 import { lastDrill } from "../../../snapshot/drills.ts";
44 import { snapshotsOf } from "../../../snapshot/registry.ts";
55 import type { SnapshotsHandle } from "../../../snapshot/service.ts";
6 import { good, bad, type Tool, mayBoards } from "../shared.ts";
6 import { good, bad, type Tool } from "../shared.ts";
7 import { holds } from "../../../core/may.ts";
8 import { principalOfUser } from "../../../core/principal.ts";
79
810 const phaseWords = (st: ReturnType<SnapshotsHandle["startDrill"]>["state"]): Record<string, string | number> =>
911 "bytes" in st
@@ -21,7 +23,7 @@ export const tool: Tool = {
2123 heldNotWhen: (args) => args["action"] === "status",
2224 adminOnly: true,
2325 async run(ctx, user, args) {
24 if (!mayBoards(user)) return bad("forbidden", "a restore drill is a forge admin's to run");
26 if (!holds(ctx.app.db, principalOfUser(user), "forge.administer_person")) return bad("forbidden", "a restore drill is a forge admin's to run");
2527 if (!scopeAllows(ctx.auth.scope ?? "ro", "admin"))
2628 return bad("forbidden", "a drill needs an admin token");
2729 const action = args["action"] ?? "start";
src/http/mcp/tools/telemetry_grant.ts +4 −2
@@ -1,6 +1,8 @@
11 import { scopeAllows } from "../../../core/tokens.ts";
22 import { setTelemetryGrant } from "../../../actions/telemetry.ts";
3 import { good, bad, type Tool, mayBoards } from "../shared.ts";
3 import { good, bad, type Tool } from "../shared.ts";
4 import { holds } from "../../../core/may.ts";
5 import { principalOfUser } from "../../../core/principal.ts";
46
57 export const tool: Tool = {
68 name: "telemetry_grant",
@@ -18,7 +20,7 @@ export const tool: Tool = {
1820 const { agent, on } = args;
1921 if (typeof agent !== "string" || typeof on !== "boolean")
2022 return bad("invalid", "send an agent name and on, true or false");
21 if (!mayBoards(user)) return bad("forbidden", "telemetry:read is a forge admin's to grant");
23 if (!holds(ctx.app.db, principalOfUser(user), "forge.administer_person")) return bad("forbidden", "telemetry:read is a forge admin's to grant");
2224 if (!scopeAllows(ctx.auth.scope ?? "ro", "admin"))
2325 return bad("forbidden", "granting needs an admin token");
2426 const set = setTelemetryGrant(ctx.app, user, agent, on);
src/kernel/mcp_door_checks.ts +1 −7
@@ -15,13 +15,7 @@ const DOOR_FILES = ["src/http/mcp.ts", "src/http/mcp/shared.ts"] as const;
1515 const INLINE = [/\bisAdmin\b/, /\bscopeAllows\([^)]*"rw"\s*\)/] as const;
1616
1717 /** A line that may keep its check, by what it starts with, and why. Only shrinks. */
18 const MCP_INLINE_ALLOWED: readonly { readonly file: string; readonly starts: string; readonly why: string }[] = [
19 {
20 file: "src/http/mcp/shared.ts",
21 starts: "export const mayBoards",
22 why: "a tool's own rule (a forge admin who is a person), asked inside the tool, not the door",
23 },
24 ];
18 const MCP_INLINE_ALLOWED: readonly { readonly file: string; readonly starts: string; readonly why: string }[] = [];
2519
2620 /** Each inline check in the MCP door's files, as `file:line: text`; empty when there are none. */
2721 export function mcpDoorRefusalAt(root: string): string[] {
src/packs/curated.ts +6 −7
@@ -11,6 +11,8 @@ import type { Database } from "bun:sqlite";
1111 import { canRead, getRepo, repoDatesFor } from "../core/repos.ts";
1212 import type { User } from "../core/users.ts";
1313 import { isSafeName } from "../git/guard.ts";
14 import { holds } from "../core/may.ts";
15 import { principalOfUser } from "../core/principal.ts";
1416
1517 export const MAX_PACKS = 50;
1618 export const MAX_PACK_REPOS = 20;
@@ -30,9 +32,6 @@ export interface Change {
3032 readonly at: string;
3133 }
3234
33 type Admin = Pick<User, "id" | "username" | "isAdmin" | "kind">;
34 export const mayCurate = (u: Admin | undefined): u is Admin => u !== undefined && u.isAdmin && u.kind !== "agent";
35
3635 export const slugOf = (title: string): string =>
3736 title.toLowerCase().replace(/[^a-z0-9]+/g, "-").replace(/^-+|-+$/g, "").replace(/^[^a-z]+/, "").slice(0, 40).replace(/-+$/, "");
3837
@@ -96,8 +95,8 @@ function describe(from: CuratedPack | undefined, to: CuratedPack): string[] {
9695 * The one door. Creates the pack when `name` is new (`create`), else changes
9796 * the fields given; `repos` replaces the list. An admin who is not an agent.
9897 */
99 export function editPack(db: Database, user: Admin | undefined, name: string, edit: Edit, create = false): EditResult {
100 if (!mayCurate(user)) return { ok: false, error: "forbidden", says: "only a site admin edits packs" };
98 export function editPack(db: Database, user: User | undefined, name: string, edit: Edit, create = false): EditResult {
99 if (!holds(db, principalOfUser(user), "forge.administer_person") || user === undefined) return { ok: false, error: "forbidden", says: "only a site admin edits packs" };
101100 if (!NAME.test(name)) return bad("a pack name is lowercase letters, digits and dashes");
102101 const before = getPack(db, name);
103102 if (create && before !== undefined) return { ok: false, error: "exists", says: `there is already a pack named ${name}` };
@@ -144,8 +143,8 @@ export const isRepoOp = (v: unknown): v is RepoOp => v === "add" || v === "remov
144143 * One change to a pack's repo list, through `editPack`: the page and the terminal share it.
145144 * A repo to add must exist here; one to move or remove must be in the pack.
146145 */
147 export function changeRepos(db: Database, user: Admin | undefined, name: string, op: unknown, word: unknown): EditResult {
148 if (!mayCurate(user)) return { ok: false, error: "forbidden", says: "only a site admin edits packs" };
146 export function changeRepos(db: Database, user: User | undefined, name: string, op: unknown, word: unknown): EditResult {
147 if (!holds(db, principalOfUser(user), "forge.administer_person") || user === undefined) return { ok: false, error: "forbidden", says: "only a site admin edits packs" };
149148 const pack = getPack(db, name);
150149 if (pack === undefined) return { ok: false, error: "not_found", says: "no such pack" };
151150 const repo = repoWord(word);
src/tui/forge_parts.ts +13 −13
@@ -61,7 +61,6 @@ import {
6161 runAsync,
6262 } from "./screens/common.ts";
6363 import { chainScreen } from "./screens/chain.ts";
64 import { canSeeMemory } from "../boards/memory.ts";
6564 import { cockpitScreen } from "./screens/cockpit.ts";
6665 import { notesScreen } from "./screens/thoughtnotes.ts";
6766 import { deciderScreen } from "./screens/decider.ts";
@@ -72,7 +71,6 @@ import { issueScreen } from "./screens/issue.ts";
7271 import { pullScreen } from "./screens/pull.ts";
7372 import { blobScreen, repoScreen } from "./screens/repo.ts";
7473 import { dashboardScreen } from "./screens/dashboard.ts";
75 import { mayManageFlags } from "../core/flags.ts";
7674 import { mayEditTrustedHosts } from "../origins/trusted-hosts.ts";
7775 import { trustedHostsPrompt } from "./screens/trustedhosts.ts";
7876 import { flagsScreen } from "./screens/flags.ts";
@@ -92,21 +90,21 @@ import { visitorBringScreen } from "./screens/visitor_bring.ts";
9290 import { passkeysScreen } from "./screens/passkeys.ts";
9391 import { confirmsScreen } from "./screens/confirms.ts";
9492 import { receiptsScreen } from "./screens/receipts.ts";
95 import { mayTrust, trustedScreen } from "./screens/trusted.ts";
96 import { mayRunners, runnersScreen } from "./screens/runners.ts";
93 import { trustedScreen } from "./screens/trusted.ts";
94 import { runnersScreen } from "./screens/runners.ts";
9795 import { proposalTokensPrompt } from "./screens/proposal_tokens.ts";
9896 import { signInsScreen } from "./screens/signins.ts";
9997 import { oauthGrantsScreen } from "./screens/oauthgrants.ts";
10098 import { originAppsScreen } from "./screens/originapps.ts";
10199 import { addEntries } from "./screens/entries.ts";
102 import { capacityScreen, mayCapacity } from "./screens/capacity.ts";
100 import { capacityScreen } from "./screens/capacity.ts";
103101 import { crawlersScreen } from "./screens/crawlers.ts";
104102 import { wrap } from "./term/width.ts";
105103 import { flowReportFor } from "../flow/report.ts";
106104 import { forgeCeiling } from "../flow/ceiling.ts";
107105 import { flowLines, flowScreen } from "./screens/flow.ts";
108106 import { laneTimeLines } from "./screens/lane_times.ts";
109 import { askUpdate, mayDrift } from "./screens/drift.ts";
107 import { askUpdate } from "./screens/drift.ts";
110108 import { readHandoverLists } from "../flow/handover_read.ts";
111109 import { readDrifts } from "../flow/alarm_drift.ts";
112110 import { readHeld } from "../flow/held.ts";
@@ -149,6 +147,8 @@ import { newRepoScreen } from "./screens/newrepo.ts";
149147 import { signInScreen } from "./screens/signin.ts";
150148 import { tellHook } from "./screens/tell_here.ts";
151149 import { local } from "./screens/where.ts";
150 import { holds } from "../core/may.ts";
151 import { principalOfUser } from "../core/principal.ts";
152152
153153
154154 export function forgeRoot(session: Session): (ctx: Ctx) => Screen {
@@ -529,7 +529,7 @@ export function forgeCommands(session: Session): (ctx: Ctx) => Command[] {
529529 run: () => ctx.push(receiptsScreen(session, ctx)),
530530 });
531531 // Who folds in without a person's review, and the kill switch (#8937): a forge admin's.
532 if (session.signedIn && mayTrust(session))
532 if (session.signedIn && holds(session.db, principalOfUser(session.user), "forge.administer_person"))
533533 commands.push({
534534 id: "trusted",
535535 title: "Trusted sources",
@@ -538,7 +538,7 @@ export function forgeCommands(session: Session): (ctx: Ctx) => Command[] {
538538 });
539539 // The machines that take the forge's checks, as Settings → Runners lists them (#15252): an
540540 // admin's.
541 if (session.signedIn && mayRunners(session))
541 if (session.signedIn && holds(session.db, principalOfUser(session.user), "forge.administer_person"))
542542 commands.push({
543543 id: "runners",
544544 title: "Runners",
@@ -649,7 +649,7 @@ export function forgeCommands(session: Session): (ctx: Ctx) => Command[] {
649649 },
650650 );
651651 // The forge's RSS beside its JS heap, as /system gates it (#2151).
652 if (canSeeMemory(session.user))
652 if (holds(session.db, principalOfUser(session.user), "forge.administer_person"))
653653 commands.push({
654654 id: "system-memory",
655655 title: "System memory",
@@ -686,13 +686,13 @@ export function forgeCommands(session: Session): (ctx: Ctx) => Command[] {
686686 flowReader.kind === "owner" ? beatLine(lastBeat(session.db), new Date()) : undefined,
687687 publicOrigin(session.app.config.url, `http://${session.app.config.host ?? "localhost"}:${session.app.config.port ?? 3000}`),
688688 ).concat(laneTimeLines(session.db, user), flowReader.kind === "owner" ? ["", ...queueTargetLines(queueTargetsFor(session.app)).flatMap((l) => wrap(l, 58))] : [], reportLines), keeper.ask && user ? { ask: keeper.ask, answer: () => answerKeeper(session.app, keeper.ask!.id, user.id) } : undefined,
689 mayDrift(session)
689 holds(session.db, principalOfUser(session.user), "forge.administer_person")
690690 ? { read: async () => readHandoverLists(session.db, await readDrifts(session.app), Date.now()), update: (n) => askUpdate(session, n) }
691691 : undefined));
692692 },
693693 });
694694 // The forge's capacity and guards, as MCP `capacity` gates them: a forge admin who is a person.
695 if (mayCapacity(session))
695 if (holds(session.db, principalOfUser(session.user), "forge.administer_person"))
696696 commands.push({
697697 id: "capacity",
698698 title: "Capacity",
@@ -701,7 +701,7 @@ export function forgeCommands(session: Session): (ctx: Ctx) => Command[] {
701701 });
702702 // What crawlers cost and who was refused, as GET /api/v1/admin/crawlers: the capacity screen's
703703 // readers.
704 if (mayCapacity(session))
704 if (holds(session.db, principalOfUser(session.user), "forge.administer_person"))
705705 commands.push({
706706 id: "crawlers",
707707 title: "Crawlers",
@@ -763,7 +763,7 @@ export function forgeCommands(session: Session): (ctx: Ctx) => Command[] {
763763 run: () => ctx.push(fileHoldsPrompt(session, ctx, blank("Held files"))),
764764 });
765765 // Settings → Flags, as the page has it: an admin who is not an agent (#1970).
766 if (mayManageFlags(session.user))
766 if (holds(session.db, principalOfUser(session.user), "forge.administer_person"))
767767 commands.push({
768768 id: "flags",
769769 title: "Flags",
src/tui/screens/ask_data.ts +6 −7
@@ -25,9 +25,8 @@ import { truncate } from "../term/width.ts";
2525 import { ListState, drawLines, drawList, hitList, hitScroll, promptScreen, Scroll, type ListRow } from "./common.ts";
2626 import { plain } from "./boards.ts";
2727 import type { PaletteEntry } from "./entries.ts";
28
29 /** The page's gate: a site admin who is a person. */
30 export const mayExplore = (session: Session): boolean => session.user?.isAdmin === true && session.user.kind !== "agent";
28 import { holds } from "../../core/may.ts";
29 import { principalOfUser } from "../../core/principal.ts";
3130
3231 export interface ExploreRow extends ListRow {
3332 readonly params: Params;
@@ -37,7 +36,7 @@ const paramsOf = (fill: Record<string, string>): Params => readParams(new URLSea
3736
3837 /** The ready questions, then each source by its plain name on its default chart; nothing for anyone the gate refuses. */
3938 export function exploreRows(session: Session, now: number): ExploreRow[] {
40 if (!mayExplore(session)) return [];
39 if (!holds(session.db, principalOfUser(session.user), "forge.administer_person")) return [];
4140 return [
4241 ...QUESTIONS.map((q): ExploreRow => ({ title: q.label, secondary: GUIDE[q.source]?.name ?? q.source, params: paramsOf(ask(q, now)) })),
4342 ...Object.keys(SOURCES).map((s): ExploreRow => ({ title: GUIDE[s]?.name ?? s, secondary: `${s} · ${GUIDE[s]?.rows ?? ""}`, params: paramsOf({ source: s }) })),
@@ -46,7 +45,7 @@ export function exploreRows(session: Session, now: number): ExploreRow[] {
4645
4746 /** What a query shows: its sentence, then one line per row; empty for anyone the gate refuses. */
4847 export function resultLines(session: Session, p: Params, note = ""): string[] {
49 if (!mayExplore(session)) return [];
48 if (!holds(session.db, principalOfUser(session.user), "forge.administer_person")) return [];
5049 const answer = p.rows === "" ? runFor(session.app.db, p.chart, toQuery(p)) : runQuery(session.app.db, toQuery(p), { repoIds: "all" });
5150 const lines = [plain(sentence(p)), ...(note === "" ? [] : [note]), ""];
5251 if (!answer.ok) return [...lines, `refused: ${plain(answer.error)}`];
@@ -103,7 +102,7 @@ export function askDataScreen(session: Session, ctx: Ctx): Screen {
103102 if (row) open(row.params);
104103 return true;
105104 }
106 if (e.key === "/" && mayExplore(session)) {
105 if (e.key === "/" && holds(session.db, principalOfUser(session.user), "forge.administer_person")) {
107106 ctx.push(
108107 promptScreen(ctx, screen, {
109108 title: "Ask in a sentence",
@@ -125,7 +124,7 @@ export function askDataScreen(session: Session, ctx: Ctx): Screen {
125124 );
126125 return true;
127126 }
128 if (e.key === "m" && mayExplore(session)) {
127 if (e.key === "m" && holds(session.db, principalOfUser(session.user), "forge.administer_person")) {
129128 // The page's metric box (#17049): rate(x[5m]), sum by (label)(x), topk(n, x), the same
130129 // answer.
131130 ctx.push(
src/tui/screens/buildcache.ts +7 −7
@@ -9,7 +9,7 @@
99 import { clearCache } from "../../actions/build_cache.ts";
1010 import { appCacheSize } from "../../apps/build_cache.ts";
1111 import { getAppByRepo } from "../../core/apps.ts";
12 import { canAdmin, type Repo } from "../../core/repos.ts";
12 import { type Repo } from "../../core/repos.ts";
1313 import type { Ctx, Screen } from "../app/app.ts";
1414 import { binding } from "../app/keys.ts";
1515 import type { Command } from "../app/palette.ts";
@@ -17,12 +17,12 @@ import type { Session } from "../session.ts";
1717 import { style } from "../term/style.ts";
1818 import { truncate } from "../term/width.ts";
1919 import { confirmScreen, later, live } from "./common.ts";
20
21 export const mayClearCache = (f: Session, repo: Repo): boolean => f.user !== undefined && canAdmin(f.db, repo, f.user);
20 import { holds } from "../../core/may.ts";
21 import { principalOfUser } from "../../core/principal.ts";
2222
2323 /** The cache's bytes, for an admin; 0 for anyone else and for an app without one. */
2424 export function cacheBytes(f: Session, repo: Repo): number {
25 if (!mayClearCache(f, repo)) return 0;
25 if (!holds(f.db, principalOfUser(f.user), "repo.admin", { repo: repo })) return 0;
2626 const record = getAppByRepo(f.db, repo.id);
2727 return record === undefined ? 0 : appCacheSize(f.app.config.dataDir, record.id);
2828 }
@@ -41,7 +41,7 @@ export function buildCacheScreen(f: Session, ctx: Ctx, repo: Repo): Screen {
4141 render(area, s) {
4242 const c = ctx.theme.c;
4343 const bytes = cacheBytes(f, repo);
44 const said = !mayClearCache(f, repo)
44 const said = !holds(f.db, principalOfUser(f.user), "repo.admin", { repo: repo })
4545 ? "An admin of this repository manages its build cache."
4646 : bytes === 0
4747 ? "No build cache yet: the next build fills it."
@@ -50,7 +50,7 @@ export function buildCacheScreen(f: Session, ctx: Ctx, repo: Repo): Screen {
5050 },
5151 key(e) {
5252 if (e.ctrl || e.alt || e.key !== "c") return false;
53 if (!mayClearCache(f, repo)) {
53 if (!holds(f.db, principalOfUser(f.user), "repo.admin", { repo: repo })) {
5454 ctx.toast("An admin of this repository manages its build cache.", "danger");
5555 return true;
5656 }
@@ -79,7 +79,7 @@ export function buildCacheScreen(f: Session, ctx: Ctx, repo: Repo): Screen {
7979
8080 /** The palette's command while an app's repository the viewer administers is open. */
8181 export function buildCacheCommands(f: Session, ctx: Ctx, repo: Repo | undefined): Command[] {
82 if (repo === undefined || !mayClearCache(f, repo) || getAppByRepo(f.db, repo.id) === undefined) return [];
82 if (repo === undefined || !holds(f.db, principalOfUser(f.user), "repo.admin", { repo: repo }) || getAppByRepo(f.db, repo.id) === undefined) return [];
8383 return [
8484 {
8585 id: "build-cache",
src/tui/screens/capacity.ts −4
@@ -21,10 +21,6 @@ import { fill, len, split } from "../ui/layout.ts";
2121 import { egressReportedLine } from "../../system/egress_line.ts";
2222 import { ListState, confirmScreen, drawList, later, promptScreen, type ListRow } from "./common.ts";
2323
24 /** Whether the palette offers the screen: a forge admin who is a person. */
25 export const mayCapacity = (session: Session): boolean =>
26 session.user?.isAdmin === true && session.user.kind !== "agent";
27
2824 /** What a setting takes, in a few words. */
2925 export function boundsOf(key: CapacityKey): string {
3026 const kind = CAPACITY[key].kind;
src/tui/screens/crawlers.ts +3 −2
@@ -13,12 +13,13 @@ import { style } from "../term/style.ts";
1313 import { truncate } from "../term/width.ts";
1414 import { fill, len, split } from "../ui/layout.ts";
1515 import { ListState, drawList, type ListRow } from "./common.ts";
16 import { mayCapacity } from "./capacity.ts";
16 import { holds } from "../../core/may.ts";
17 import { principalOfUser } from "../../core/principal.ts";
1718
1819 export function crawlersScreen(f: Session, ctx: Ctx): Screen {
1920 const state = new ListState();
2021 const lines = (): ListRow[] => {
21 if (!mayCapacity(f)) return [];
22 if (!holds(f.db, principalOfUser(f.user), "forge.administer_person")) return [];
2223 const r = crawlReport(f.app);
2324 const b = r.refused_by_budget;
2425 return [
src/tui/screens/crewtop.ts +6 −7
@@ -20,6 +20,8 @@ import { truncate } from "../term/width.ts";
2020 import { fill, len, split } from "../ui/layout.ts";
2121 import { ListState, confirmScreen, drawList, later, type ListRow } from "./common.ts";
2222 import type { PaletteEntry } from "./entries.ts";
23 import { holds } from "../../core/may.ts";
24 import { principalOfUser } from "../../core/principal.ts";
2325
2426 const usd = (n: number): string => `$${n.toFixed(2)}`;
2527 const at = (iso: string): string => iso.slice(0, 16).replace("T", " ");
@@ -30,14 +32,11 @@ export interface TopRows {
3032 readonly accounts: ReadonlyMap<number, AccountLine>;
3133 }
3234
33 /** The page's gate: a forge admin. */
34 export const mayReadCrewTop = (f: Session): boolean => f.user?.isAdmin === true;
35
3635 /** Every section as rows: a heading row, then its lines; an empty section says so in one line. */
3736 export function crewTopRows(f: Session, now: Date = new Date()): TopRows {
3837 const rows: ListRow[] = [];
3938 const accounts = new Map<number, AccountLine>();
40 if (!mayReadCrewTop(f) || f.user === undefined) return { rows, accounts };
39 if (!holds(f.db, principalOfUser(f.user), "forge.administer") || f.user === undefined) return { rows, accounts };
4140 const head = (title: string): void => void rows.push({ title, tone: "secondary" });
4241 const none = (words: string): void => void rows.push({ title: words });
4342
@@ -103,7 +102,7 @@ export function crewTopRows(f: Session, now: Date = new Date()): TopRows {
103102 * Returns whether it went.
104103 */
105104 export function removeAccount(f: Session, a: AccountLine): boolean {
106 if (!mayReadCrewTop(f) || !a.removable) return false;
105 if (!holds(f.db, principalOfUser(f.user), "forge.administer") || !a.removable) return false;
107106 return deleteSubscription(f.db, a.id);
108107 }
109108
@@ -115,7 +114,7 @@ export function crewTopScreen(f: Session, ctx: Ctx): Screen {
115114 render(area, s) {
116115 const c = ctx.theme.c;
117116 const [top, list] = split(area, "v", [len(1), fill(1)]);
118 const said = mayReadCrewTop(f) ? "Who is on what, what waits, what it costs." : "The crew's top is read by a forge admin.";
117 const said = holds(f.db, principalOfUser(f.user), "forge.administer") ? "Who is on what, what waits, what it costs." : "The crew's top is read by a forge admin.";
119118 s.text(top!.x, top!.y, truncate(said, top!.w), style(c.mutedFg, c.bg), top!.x + top!.w);
120119 drawList(s, list!, c, state, crewTopRows(f).rows);
121120 },
@@ -124,7 +123,7 @@ export function crewTopScreen(f: Session, ctx: Ctx): Screen {
124123 if (state.key(e, rows.length)) return true;
125124 if (e.ctrl || e.alt || e.key !== "x") return false;
126125 const a = accounts.get(state.index);
127 if (!mayReadCrewTop(f)) {
126 if (!holds(f.db, principalOfUser(f.user), "forge.administer")) {
128127 ctx.toast("The crew's top is read by a forge admin.", "danger");
129128 return true;
130129 }
src/tui/screens/cutover.ts +7 −8
@@ -8,7 +8,7 @@
88 import { cutOver, cutOverMessage, undoCutOver } from "../../actions/cutover.ts";
99 import { getAppByRepo } from "../../core/apps.ts";
1010 import { listDomains, type AppDomain } from "../../core/domains.ts";
11 import { canAdmin, type Repo } from "../../core/repos.ts";
11 import { type Repo } from "../../core/repos.ts";
1212 import type { Ctx, Screen } from "../app/app.ts";
1313 import { binding } from "../app/keys.ts";
1414 import type { Command } from "../app/palette.ts";
@@ -17,13 +17,12 @@ import { style } from "../term/style.ts";
1717 import { truncate } from "../term/width.ts";
1818 import { fill, len, split } from "../ui/layout.ts";
1919 import { ListState, confirmScreen, drawList, later, type ListRow } from "./common.ts";
20
21 /** Cut over's gate: an admin of the repository. */
22 export const mayCutOver = (f: Session, repo: Repo): boolean => f.user !== undefined && canAdmin(f.db, repo, f.user);
20 import { holds } from "../../core/may.ts";
21 import { principalOfUser } from "../../core/principal.ts";
2322
2423 /** The repository's domains: none for anyone but an admin, none without an app. */
2524 export function cutOverRows(f: Session, repo: Repo): AppDomain[] {
26 if (!mayCutOver(f, repo)) return [];
25 if (!holds(f.db, principalOfUser(f.user), "repo.admin", { repo: repo })) return [];
2726 const record = getAppByRepo(f.db, repo.id);
2827 return record === undefined ? [] : listDomains(f.db, record.id);
2928 }
@@ -49,7 +48,7 @@ export function cutOverScreen(f: Session, ctx: Ctx, repo: Repo): Screen {
4948 render(area, s) {
5049 const c = ctx.theme.c;
5150 const [head, list, out] = split(area, "v", [len(1), fill(1), len(Math.min(10, Math.max(1, said.length)))]);
52 const intro = mayCutOver(f, repo)
51 const intro = holds(f.db, principalOfUser(f.user), "repo.admin", { repo: repo })
5352 ? "c checks a domain against the platform, o moves it to this app, u puts the old records back."
5453 : "An admin of this repository cuts domains over.";
5554 s.text(head!.x, head!.y, truncate(intro, head!.w), style(c.mutedFg, c.bg), head!.x + head!.w);
@@ -65,7 +64,7 @@ export function cutOverScreen(f: Session, ctx: Ctx, repo: Repo): Screen {
6564 const all = cutOverRows(f, repo);
6665 if (state.key(e, all.length)) return true;
6766 if (e.ctrl || e.alt || (e.key !== "c" && e.key !== "o" && e.key !== "u")) return false;
68 if (!mayCutOver(f, repo)) {
67 if (!holds(f.db, principalOfUser(f.user), "repo.admin", { repo: repo })) {
6968 ctx.toast("An admin of this repository cuts domains over.", "danger");
7069 return true;
7170 }
@@ -100,7 +99,7 @@ export function cutOverScreen(f: Session, ctx: Ctx, repo: Repo): Screen {
10099
101100 /** The palette's command while a repository the viewer administers is open. */
102101 export function cutOverCommands(f: Session, ctx: Ctx, repo: Repo | undefined): Command[] {
103 if (repo === undefined || !mayCutOver(f, repo)) return [];
102 if (repo === undefined || !holds(f.db, principalOfUser(f.user), "repo.admin", { repo: repo })) return [];
104103 return [
105104 {
106105 id: "cut-over",
src/tui/screens/design.ts +3 −2
@@ -14,7 +14,6 @@ import {
1414 SCALES,
1515 contrastFailures,
1616 liveTokens,
17 mayEditTheme,
1817 steerTheme,
1918 themeHistory,
2019 validateTokens,
@@ -26,6 +25,8 @@ import type { Session } from "../session.ts";
2625 import { style } from "../term/style.ts";
2726 import { Scroll, drawLines, hitScroll, live, promptScreen } from "./common.ts";
2827 import type { PaletteEntry } from "./entries.ts";
28 import { holds } from "../../core/may.ts";
29 import { principalOfUser } from "../../core/principal.ts";
2930
3031 /** One editable field: a role in a mode, or a scale. */
3132 export type Field = { kind: "role"; mode: "light" | "dark"; role: (typeof ROLES)[number] } | { kind: "scale"; key: keyof typeof SCALES };
@@ -98,7 +99,7 @@ export function designScreen(session: Session, ctx: Ctx): Screen {
9899 if (e.key === "j") return (at = Math.min(FIELDS.length - 1, at + 1)), ctx.invalidate(), true;
99100 if (e.key === "k") return (at = Math.max(0, at - 1)), ctx.invalidate(), true;
100101 if (e.ctrl || e.alt) return false;
101 if (!mayEditTheme(session.user)) {
102 if (!holds(session.db, principalOfUser(session.user), "forge.administer_person")) {
102103 if (e.key !== "e" && e.key !== "p" && e.key !== "r") return false;
103104 ctx.toast("A site admin steers the theme.", "danger");
104105 return true;
src/tui/screens/disks.ts +1 −1
@@ -3,7 +3,7 @@
33 * row a device — model, bytes written in the last 30 days, the date rated TBW
44 * is projected at that rate, and what the assessment says. Ratings are vendor
55 * figures; the date is a projection, not an alert. Read-only; the gate is
6 * `mayHandleDisks`.
6 * `forge.administer_person`.
77 */
88
99 import { readMachine, readMachines } from "../../actions/disk_readings.ts";
src/tui/screens/drift.ts −2
@@ -20,8 +20,6 @@ import { ListState, drawList, metaOf, runAsync, type ListRow } from "./common.ts
2020 import type { PaletteEntry } from "./entries.ts";
2121 import { emptyState } from "../ui/widgets.ts";
2222
23 export const mayDrift = (f: Session): boolean => f.user?.isAdmin === true && f.user.kind !== "agent";
24
2523 export function driftRows(pulls: readonly DriftingPull[]): ListRow[] {
2624 return pulls.map((p) => ({ title: `${p.repo} #${p.number}`, meta: metaOf(`${p.landings} landings`, `${p.hours} h behind`) }));
2725 }
src/tui/screens/featureswitch.ts +4 −5
@@ -21,9 +21,8 @@ import { binding } from "../app/keys.ts";
2121 import type { Session } from "../session.ts";
2222 import { ListState, drawList, promptScreen, runAsync, type ListRow } from "./common.ts";
2323 import type { PaletteEntry } from "./entries.ts";
24
25 /** Site admins who are people: what the page's `requireAdmin` lets in. */
26 export const mayFeatures = (f: Session): boolean => f.user !== undefined && f.user.isAdmin && f.user.kind !== "agent";
24 import { holds } from "../../core/may.ts";
25 import { principalOfUser } from "../../core/principal.ts";
2726
2827 const FAILS: Record<string, string> = {
2928 not_found: "no such app",
@@ -107,9 +106,9 @@ export function featureSwitchScreen(f: Session, ctx: Ctx): Screen {
107106 let features: readonly FeatureView[] = [];
108107 let ssh: SshRow | undefined;
109108 const reload = async (): Promise<void> => {
110 const listed = mayFeatures(f) ? await listFeatures(f.app, f.user) : undefined;
109 const listed = holds(f.db, principalOfUser(f.user), "forge.administer_person") ? await listFeatures(f.app, f.user) : undefined;
111110 features = listed?.ok ? listed.value : [];
112 const row = mayFeatures(f) ? sshRow(f.app, f.user) : undefined;
111 const row = holds(f.db, principalOfUser(f.user), "forge.administer_person") ? sshRow(f.app, f.user) : undefined;
113112 ssh = row?.ok ? row.value : undefined;
114113 ctx.invalidate();
115114 };
src/tui/screens/flags.ts +4 −3
@@ -14,7 +14,6 @@ import {
1414 checkInput,
1515 FLAGS_ADMIN_ONLY,
1616 flagRegistry,
17 mayManageFlags,
1817 usesLine,
1918 winnerOffer,
2019 type FlagInput,
@@ -29,6 +28,8 @@ import { truncate } from "../term/width.ts";
2928 import type { Session } from "../session.ts";
3029 import { fill, len, split } from "../ui/layout.ts";
3130 import { ListState, drawList, promptScreen, type ListRow } from "./common.ts";
31 import { holds } from "../../core/may.ts";
32 import { principalOfUser } from "../../core/principal.ts";
3233
3334 const KEYS = ["forge", "users", "roles", "percent"] as const;
3435
@@ -59,7 +60,7 @@ function show(v: FlagValue | undefined): string {
5960
6061 export function flagsScreen(f: Session, ctx: Ctx): Screen {
6162 const state = new ListState();
62 const allowed = mayManageFlags(f.user);
63 const allowed = holds(f.db, principalOfUser(f.user), "forge.administer_person");
6364 const names = (): string[] => (allowed ? Object.keys(flagRegistry().decls) : []);
6465 let note = "";
6566
@@ -89,7 +90,7 @@ export function flagsScreen(f: Session, ctx: Ctx): Screen {
8990 };
9091
9192 const rows = (): ListRow[] => {
92 const read = readFlags(f.user);
93 const read = readFlags(f.db, f.user);
9394 return (read.ok ? read.flags : []).map((flag) => ({
9495 title: flag.name,
9596 secondary: show(flag.value),
src/tui/screens/machines.ts +4 −1
@@ -40,7 +40,10 @@ export function shellStatesLine(states: ReadonlyMap<string, MachineState>): stri
4040 return parts.length === 0 ? undefined : `Your shell — ${parts.join("; ")}`;
4141 }
4242
43 /** The disk lines of each declared machine, the owner's alone (`mayHandleDisks`): nothing for any other writer. */
43 /**
44 * The disk lines of each declared machine, the owner's alone (`forge.administer_person`): nothing
45 * for any other writer.
46 */
4447 export function repoDiskLines(f: Session, list: readonly Machine[]): string[] {
4548 return list.flatMap((m) => {
4649 const r = readMachine(f.app, f.user, m.name);
src/tui/screens/nowlist.ts +6 −4
@@ -5,7 +5,7 @@
55 * web. Anyone else, and an agent, is offered nothing.
66 */
77
8 import { mayReadNow, NOW_HOLDS, NOW_LISTED, NOW_STAGES, NOW_WORDS, readNowRows } from "../../flow/now_rows.ts";
8 import { NOW_HOLDS, NOW_LISTED, NOW_STAGES, NOW_WORDS, readNowRows } from "../../flow/now_rows.ts";
99 import type { Ctx, Screen } from "../app/app.ts";
1010 import { binding } from "../app/keys.ts";
1111 import { style } from "../term/style.ts";
@@ -14,11 +14,13 @@ import type { Session } from "../session.ts";
1414 import { fill, len, split } from "../ui/layout.ts";
1515 import { ListState, drawList, openOnWeb, type ListRow } from "./common.ts";
1616 import type { PaletteEntry } from "./entries.ts";
17 import { holds } from "../../core/may.ts";
18 import { principalOfUser } from "../../core/principal.ts";
1719
1820 export function nowScreen(f: Session, ctx: Ctx, first: (typeof NOW_STAGES)[number] = "check"): Screen {
1921 const state = new ListState();
2022 let stage = first;
21 const read = () => (mayReadNow(f.user) ? readNowRows(f.db, stage) : { total: 0, rows: [] });
23 const read = () => (holds(f.db, principalOfUser(f.user), "forge.administer_person") ? readNowRows(f.db, stage) : { total: 0, rows: [] });
2224 const screen: Screen = {
2325 title: "Now",
2426 keys: [binding(["j", "k"], "move cursor"), binding(["1", "2", "3", "4"], "check, review, land, live"), binding(["enter"], "open on the web")],
@@ -28,13 +30,13 @@ export function nowScreen(f: Session, ctx: Ctx, first: (typeof NOW_STAGES)[numbe
2830 const [head, list] = split(area, "v", [len(1), fill(1)]);
2931 const words = NOW_STAGES.map((w) => (w === stage ? `[${NOW_WORDS[w]}]` : NOW_WORDS[w])).join(" ");
3032 const cut = total > rows.length ? ` Newest ${NOW_LISTED} shown.` : "";
31 const text = mayReadNow(f.user) ? `${words} ${total} · ${NOW_HOLDS[stage]}${cut}` : "Now is a site admin's.";
33 const text = holds(f.db, principalOfUser(f.user), "forge.administer_person") ? `${words} ${total} · ${NOW_HOLDS[stage]}${cut}` : "Now is a site admin's.";
3234 s.text(head!.x, head!.y, truncate(text, head!.w), style(c.mutedFg, c.bg), head!.x + head!.w);
3335 const shown: ListRow[] = rows.map((r) => ({ title: r.title, secondary: `${r.repo} · ${r.note}`, meta: r.at.slice(0, 16).replace("T", " ") }));
3436 drawList(s, list!, c, state, shown);
3537 },
3638 key(e) {
37 if (!mayReadNow(f.user)) return false;
39 if (!holds(f.db, principalOfUser(f.user), "forge.administer_person")) return false;
3840 const { rows } = read();
3941 if (state.key(e, rows.length)) return true;
4042 if (e.ctrl || e.alt) return false;
src/tui/screens/outsideagents.ts +7 −8
@@ -12,7 +12,7 @@ import { setOutsideReports } from "../../actions/reports.ts";
1212 import { revokeOutsideToken, setOutsideContributions, takesOutside } from "../../actions/contribute_token.ts";
1313 import { contributeOpen, listContribute, type ContributeTokenInfo } from "../../core/contribute_token.ts";
1414 import { reportsClosed } from "../../core/reports.ts";
15 import { canAdmin, type Repo } from "../../core/repos.ts";
15 import { type Repo } from "../../core/repos.ts";
1616 import type { Ctx, Screen } from "../app/app.ts";
1717 import { binding } from "../app/keys.ts";
1818 import type { Command } from "../app/palette.ts";
@@ -21,16 +21,15 @@ import { style } from "../term/style.ts";
2121 import { truncate } from "../term/width.ts";
2222 import { fill, len, split } from "../ui/layout.ts";
2323 import { ListState, confirmScreen, drawList, later, live, type ListRow } from "./common.ts";
24
25 /** Settings › Outside agents' gate: an admin of the repository. */
26 export const mayManageOutside = (f: Session, repo: Repo): boolean => f.user !== undefined && canAdmin(f.db, repo, f.user);
24 import { holds } from "../../core/may.ts";
25 import { principalOfUser } from "../../core/principal.ts";
2726
2827 /**
2928 * The live tokens, for an admin; none for anyone else, and none while outside
3029 * agents are not allowed.
3130 */
3231 export function outsideRows(f: Session, repo: Repo): ContributeTokenInfo[] {
33 return mayManageOutside(f, repo) && contributeOpen(f.db, repo.id) ? listContribute(f.db, repo.id, new Date()) : [];
32 return holds(f.db, principalOfUser(f.user), "repo.admin", { repo: repo }) && contributeOpen(f.db, repo.id) ? listContribute(f.db, repo.id, new Date()) : [];
3433 }
3534
3635 export function outsideAgentsScreen(f: Session, ctx: Ctx, repo: Repo): Screen {
@@ -44,7 +43,7 @@ export function outsideAgentsScreen(f: Session, ctx: Ctx, repo: Repo): Screen {
4443 },
4544 render(area, s) {
4645 const c = ctx.theme.c;
47 const may = mayManageOutside(f, repo);
46 const may = holds(f.db, principalOfUser(f.user), "repo.admin", { repo: repo });
4847 const open = contributeOpen(f.db, repo.id);
4948 const [head, list] = split(area, "v", [len(1), fill(1)]);
5049 const said = !may
@@ -67,7 +66,7 @@ export function outsideAgentsScreen(f: Session, ctx: Ctx, repo: Repo): Screen {
6766 const all = outsideRows(f, repo);
6867 if (state.key(e, all.length)) return true;
6968 if (e.ctrl || e.alt || (e.key !== "a" && e.key !== "x" && e.key !== "r")) return false;
70 if (!mayManageOutside(f, repo)) {
69 if (!holds(f.db, principalOfUser(f.user), "repo.admin", { repo: repo })) {
7170 ctx.toast("An admin of this repository manages outside agents.", "danger");
7271 return true;
7372 }
@@ -123,7 +122,7 @@ export function outsideAgentsScreen(f: Session, ctx: Ctx, repo: Repo): Screen {
123122
124123 /** The palette's command while a repository the viewer administers is open. */
125124 export function outsideAgentsCommands(f: Session, ctx: Ctx, repo: Repo | undefined): Command[] {
126 if (repo === undefined || !mayManageOutside(f, repo)) return [];
125 if (repo === undefined || !holds(f.db, principalOfUser(f.user), "repo.admin", { repo: repo })) return [];
127126 return [
128127 {
129128 id: "outside-agents",
src/tui/screens/packs.ts +10 −8
@@ -6,7 +6,7 @@
66 * database and edited through `packs/curated.ts`, the page's own door.
77 */
88
9 import { changeRepos, editPack, getPack, history, listPacks, mayCurate, resolveRepos, slugOf, type EditResult, type PackRepo } from "../../packs/curated.ts";
9 import { changeRepos, editPack, getPack, history, listPacks, resolveRepos, slugOf, type EditResult, type PackRepo } from "../../packs/curated.ts";
1010 import { MAX_DIRECTION_CHARS } from "../../spawn/plan.ts";
1111 import { newForgeScreen } from "./newforge.ts";
1212 import { promptScreen } from "./common.ts";
@@ -21,6 +21,8 @@ import { style } from "../term/style.ts";
2121 import { truncate, wrap } from "../term/width.ts";
2222 import { Scroll } from "./common.ts";
2323 import type { Session } from "../session.ts";
24 import { holds } from "../../core/may.ts";
25 import { principalOfUser } from "../../core/principal.ts";
2426
2527 /** One pack as text lines: what it brings, the commands, and the stranger's way in. */
2628 export function packLines(p: Pack, origin: string | undefined, width = 80): string[] {
@@ -87,7 +89,7 @@ export function curatedScreen(session: Session, ctx: Ctx, name: string): Screen
8789 const pack = getPack(db, name);
8890 if (pack === undefined) return undefined;
8991 const repos = resolveRepos(db, pack, user);
90 return { repos: mayCurate(user) ? repos : repos.filter((r) => r.left === undefined), shown: repos.filter((r) => r.left === undefined) };
92 return { repos: holds(db, principalOfUser(user), "forge.administer_person") ? repos : repos.filter((r) => r.left === undefined), shown: repos.filter((r) => r.left === undefined) };
9193 };
9294 const wrote = (done: EditResult): void => {
9395 note = says(done);
@@ -95,7 +97,7 @@ export function curatedScreen(session: Session, ctx: Ctx, name: string): Screen
9597 };
9698 const edit = (label: string, field: "title" | "pitch" | "brief"): void => {
9799 const pack = getPack(db, name);
98 if (pack === undefined || !mayCurate(user)) return;
100 if (pack === undefined || !holds(db, principalOfUser(user), "forge.administer_person")) return;
99101 ctx.push(promptScreen(ctx, screen, { title: `Pack ${field}`, label, value: pack[field], onSubmit: (text) => { wrote(editPack(db, user, name, { [field]: text })); } }));
100102 };
101103 const start = (): void => {
@@ -106,7 +108,7 @@ export function curatedScreen(session: Session, ctx: Ctx, name: string): Screen
106108 };
107109 const screen: Screen = {
108110 title: "Pack",
109 keys: [binding(["j", "k"], "move"), binding(["s"], "start a forge"), ...(mayCurate(user) ? [binding(["a", "x", "u", "d", "t", "p", "b"], "edit")] : []), binding(["esc"], "back")],
111 keys: [binding(["j", "k"], "move"), binding(["s"], "start a forge"), ...(holds(db, principalOfUser(user), "forge.administer_person") ? [binding(["a", "x", "u", "d", "t", "p", "b"], "edit")] : []), binding(["esc"], "back")],
110112 render(area, s) {
111113 const c = ctx.theme.c;
112114 const pack = getPack(db, name);
@@ -122,9 +124,9 @@ export function curatedScreen(session: Session, ctx: Ctx, name: string): Screen
122124 ["", "fg"],
123125 [`${v.shown.length} repo${v.shown.length === 1 ? "" : "s"}. Press s to start a forge from this.`, "muted"],
124126 ["", "fg"],
125 ...v.repos.map((r, i): [string, "fg" | "muted" | "accent"] => [`${i === at && mayCurate(user) ? "> " : " "}${r.full}${r.left === undefined ? (r.live ? " live" : "") : ` (${r.left})`}`, r.left === undefined ? (i === at ? "accent" : "fg") : "muted"]),
127 ...v.repos.map((r, i): [string, "fg" | "muted" | "accent"] => [`${i === at && holds(db, principalOfUser(user), "forge.administer_person") ? "> " : " "}${r.full}${r.left === undefined ? (r.live ? " live" : "") : ` (${r.left})`}`, r.left === undefined ? (i === at ? "accent" : "fg") : "muted"]),
126128 ...(pack.brief === "" ? [] : ([["", "fg"], ["Crew brief", "fg"], ...wrap(pack.brief, area.w - 4).map((l): [string, "muted"] => [l, "muted"])] as [string, "fg" | "muted"][])),
127 ...(mayCurate(user)
129 ...(holds(db, principalOfUser(user), "forge.administer_person")
128130 ? ([["", "fg"], ["History", "fg"], ...history(db, name, 5).map((h): [string, "muted"] => [` ${h.actor} ${h.what}`, "muted"])] as [string, "fg" | "muted"][])
129131 : []),
130132 ...(note === "" ? [] : ([["", "fg"], [note, "accent"]] as [string, "accent"][])),
@@ -134,7 +136,7 @@ export function curatedScreen(session: Session, ctx: Ctx, name: string): Screen
134136 key(e) {
135137 if (e.ctrl || e.alt) return false;
136138 const v = view();
137 const mine = mayCurate(user);
139 const mine = holds(db, principalOfUser(user), "forge.administer_person");
138140 const row = v?.repos[at];
139141 if (e.key === "esc" || e.key === "q") ctx.pop();
140142 else if (e.key === "j" || e.key === "down") at = Math.min(Math.max(0, (v?.repos.length ?? 1) - 1), at + 1);
@@ -167,7 +169,7 @@ export function packsScreen(ctx: Ctx, origin: string | undefined, app?: App, ses
167169 let note = "";
168170 const curated = () => (app === undefined ? [] : listPacks(app.db));
169171 const total = () => curated().length + catalog().packs.length;
170 const mine = () => session !== undefined && mayCurate(session.user);
172 const mine = () => session !== undefined && holds(session.db, principalOfUser(session.user), "forge.administer_person");
171173 const screen: Screen = {
172174 title: "Forge packs",
173175 keys: [binding(["j", "k"], "move"), binding(["enter"], "open"), ...(mine() ? [binding(["n"], "new pack")] : []), binding(["esc"], "close")],
src/tui/screens/refused.ts +5 −3
@@ -1,21 +1,23 @@
11 /**
22 * Refused first asks in the terminal (#11586): the last `REFUSED_SHOWN` first
33 * asks the forge turned away, newest first, as `/forges/refused` lists them.
4 * Gate is the page's (`mayReadRefusals`). One `listRefusals` call; read-only.
4 * Gate is the page's (`forge.administer_person`). One `listRefusals` call; read-only.
55 */
66
77 import type { Database } from "bun:sqlite";
8 import { REFUSED_SHOWN, listRefusals, mayReadRefusals } from "../../core/first_ask_refusals.ts";
8 import { REFUSED_SHOWN, listRefusals } from "../../core/first_ask_refusals.ts";
99 import type { Ctx, Screen } from "../app/app.ts";
1010 import { binding } from "../app/keys.ts";
1111 import type { Session } from "../session.ts";
1212 import { style } from "../term/style.ts";
1313 import { Scroll, drawLines, hitScroll } from "./common.ts";
1414 import type { PaletteEntry } from "./entries.ts";
15 import { holds } from "../../core/may.ts";
16 import { principalOfUser } from "../../core/principal.ts";
1517
1618 /** One line per refusal; empty for anyone the gate refuses. Control characters in a stranger's ask become spaces. */
1719 export function refusedLines(session: Session, db: Database = session.app.db, now = Date.now()): string[] {
18 if (!mayReadRefusals(session.user)) return [];
20 if (!holds(session.db, principalOfUser(session.user), "forge.administer_person")) return [];
1921 return listRefusals(db, REFUSED_SHOWN, now).map((r) =>
2022 `${new Date(r.at).toISOString().slice(0, 16).replace("T", " ")} ${r.actorId ?? "no one"} ${r.ask} — ${r.words}`.replace(/[\u0000-\u001f\u007f-\u009f]/g, " "),
2123 );
src/tui/screens/runners.ts +6 −7
@@ -23,9 +23,8 @@ import { truncate } from "../term/width.ts";
2323 import type { Session } from "../session.ts";
2424 import { fill, len, split } from "../ui/layout.ts";
2525 import { ListState, confirmScreen, drawList, promptScreen, type ListRow } from "./common.ts";
26
27 /** Whether the palette offers the screen: a signed-in admin who is a person. */
28 export const mayRunners = (f: Session): boolean => f.user !== undefined && f.user.isAdmin && f.user.kind === "user";
26 import { holds } from "../../core/may.ts";
27 import { principalOfUser } from "../../core/principal.ts";
2928
3029 const STATE_WORDS = { connected: "connected", quiet: "quiet", never: "never asked" } as const;
3130
@@ -188,19 +187,19 @@ export function runnersScreen(f: Session, ctx: Ctx): Screen {
188187 render(area, s) {
189188 const c = ctx.theme.c;
190189 const [head, lentRow, body] = split(area, "v", [len(1), len(1), fill(1)]);
191 const text = !mayRunners(f)
190 const text = !holds(f.db, principalOfUser(f.user), "forge.administer_person")
192191 ? "Only a forge admin sees the runners."
193192 : entries().length === 0
194193 ? "No runner is enrolled; checks run on the forge's own machine. c lends runners to another forge."
195194 : "The machines that take this forge's checks; x revokes a lent or outside one or removes a hand-made one, p pauses, u resumes. c lends runners to another forge; on an offer s stops, S stops now.";
196 const waiting = mayRunners(f) ? yieldNote(yieldState(process.env["FORGE_LEND_YIELD_LOAD"])) : "";
195 const waiting = holds(f.db, principalOfUser(f.user), "forge.administer_person") ? yieldNote(yieldState(process.env["FORGE_LEND_YIELD_LOAD"])) : "";
197196 s.text(head!.x, head!.y, truncate(waiting === "" ? text : waiting, head!.w), style(c.mutedFg, c.bg), head!.x + head!.w);
198 const lent = mayRunners(f) ? [lentLine(lentIn(f.db, Date.now())), lendingLine(f)].filter((l) => l !== "").join(" · ") : "";
197 const lent = holds(f.db, principalOfUser(f.user), "forge.administer_person") ? [lentLine(lentIn(f.db, Date.now())), lendingLine(f)].filter((l) => l !== "").join(" · ") : "";
199198 if (lent !== "") s.text(lentRow!.x, lentRow!.y, truncate(lent, lentRow!.w), style(c.mutedFg, c.bg), lentRow!.x + lentRow!.w);
200199 drawList(s, body!, c, state, rows());
201200 },
202201 key(e) {
203 if (!mayRunners(f) || e.ctrl || e.alt) return false;
202 if (!holds(f.db, principalOfUser(f.user), "forge.administer_person") || e.ctrl || e.alt) return false;
204203 const all = entries();
205204 if (state.key(e, all.length)) return true;
206205 if (e.key === "c") {
src/tui/screens/settinghistory.ts +5 −5
@@ -6,7 +6,7 @@
66 * write made on the page or here, since both are events on the bus.
77 */
88
9 import { canAdmin, getRepoById, type Repo } from "../../core/repos.ts";
9 import { getRepoById, type Repo } from "../../core/repos.ts";
1010 import { agoWords } from "../../kernel/ago.ts";
1111 import { lastChanges, SETTING_ROWS } from "../../settings/last_change.ts";
1212 import type { Ctx, Screen } from "../app/app.ts";
@@ -15,6 +15,8 @@ import type { Session } from "../session.ts";
1515 import { style } from "../term/style.ts";
1616 import { truncate } from "../term/width.ts";
1717 import { live } from "./common.ts";
18 import { holds } from "../../core/may.ts";
19 import { principalOfUser } from "../../core/principal.ts";
1820
1921 /** The lines: "Landing changed by olive, 2 hours ago", or one sentence when nothing changed. */
2022 export function historyLines(f: Session, repo: Repo, now: number = Date.now()): string[] {
@@ -26,8 +28,6 @@ export function historyLines(f: Session, repo: Repo, now: number = Date.now()):
2628 return lines.length > 0 ? lines : ["No setting has been changed yet."];
2729 }
2830
29 export const maySeeHistory = (f: Session, repo: Repo): boolean => f.user !== undefined && canAdmin(f.db, repo, f.user);
30
3131 export function settingHistoryScreen(f: Session, ctx: Ctx, repo: Repo): Screen {
3232 return {
3333 title: `${repo.ownerName}/${repo.name} — Setting history`,
@@ -38,7 +38,7 @@ export function settingHistoryScreen(f: Session, ctx: Ctx, repo: Repo): Screen {
3838 render(area, s) {
3939 const c = ctx.theme.c;
4040 const current = getRepoById(f.db, repo.id) ?? repo;
41 const lines = maySeeHistory(f, current) ? historyLines(f, current) : ["An admin of this repository reads who changed its settings."];
41 const lines = holds(f.db, principalOfUser(f.user), "repo.admin", { repo: current }) ? historyLines(f, current) : ["An admin of this repository reads who changed its settings."];
4242 lines.slice(0, area.h).forEach((line, i) => s.text(area.x, area.y + i, truncate(line, area.w), style(c.mutedFg, c.bg), area.x + area.w));
4343 },
4444 key: () => false,
@@ -47,7 +47,7 @@ export function settingHistoryScreen(f: Session, ctx: Ctx, repo: Repo): Screen {
4747
4848 /** The palette's command while a repository the viewer administers is open. */
4949 export function settingHistoryCommands(f: Session, ctx: Ctx, repo: Repo | undefined): Command[] {
50 if (repo === undefined || !maySeeHistory(f, repo)) return [];
50 if (repo === undefined || f.user === undefined || !holds(f.db, principalOfUser(f.user), "repo.admin", { repo: repo })) return [];
5151 return [
5252 {
5353 id: "setting-history",
src/tui/screens/system.ts +22 −17
@@ -13,7 +13,7 @@
1313 *
1414 * `memoryScreen` is `/system`'s other half (#2151): the forge's RSS beside
1515 * its JS heap, an hour a row for the last 24 h, read through `memoryHours`
16 * like the page. The gate is the page's (`canSeeMemory`): anyone but a forge
16 * like the page. The gate is the page's (`forge.administer_person`): anyone but a forge
1717 * admin who is a person gets no rows. Read-only.
1818 *
1919 * Under the forge line, as /system says it (#10853): a child forge in a cell
@@ -37,7 +37,7 @@ import { movedKey } from "./moved_key.ts";
3737 import type { Ctx, Screen } from "../app/app.ts";
3838 import type { SystemView } from "../../system/view.ts";
3939 import { rolloutLine, type ForgeHealth } from "../../kernel/guard.ts";
40 import { canSeeMemory, memoryHours } from "../../boards/memory.ts";
40 import { memoryHours } from "../../boards/memory.ts";
4141 import { droppedRows } from "../../boards/sampler.ts";
4242 import { askCensus, CENSUS_AGENT_REFUSED, censusReport } from "../../perf/heap_census.ts";
4343 import { askingOf } from "../../perf/asking.ts";
@@ -65,7 +65,6 @@ import { knownPatterns } from "../../http/server.ts";
6565 import type { PaletteEntry } from "./entries.ts";
6666 import { seriesScreen } from "./series.ts";
6767 import { abstractionsScreen } from "./abstractions.ts";
68 import { mayReadAtlas } from "../../actions/abstractions.ts";
6968 import { shapeWords } from "../../engine/mode.ts";
7069 import { readHealth } from "../../actions/health.ts";
7170 import { egressReportedLine } from "../../system/egress_line.ts";
@@ -82,6 +81,8 @@ import type { AdoptionRow } from "../../spawn/adopted.ts";
8281 import { withheldFindings, type WithheldFinding } from "../../crew/sentinel.ts";
8382 import { ownRepoRate, rateLine, type Rate } from "../../checks/deepsec_rate.ts";
8483 import { childrenUse, realSelf, selfUse, sizeWords, useWords, type ChildUseRow, type SelfUse } from "../../spawn/usage.ts";
84 import { holds } from "../../core/may.ts";
85 import { principalOfUser } from "../../core/principal.ts";
8586
8687 const WIDTH = 72;
8788 const GROUPS = 6;
@@ -352,7 +353,10 @@ export function dbSizeScreen(session: Session, ctx: Ctx): Screen {
352353 };
353354 }
354355
355 /** Who may grant telemetry:read: the MCP tool's gate (`mayBoards`), a forge admin who is a person. */
356 /**
357 * Who may grant telemetry:read: the MCP tool's gate (`forge.administer_person`), a forge admin who
358 * is a person.
359 */
356360 const mayGrant = (session: Session | undefined): boolean => session?.user?.isAdmin === true && session.user.kind !== "agent";
357361
358362 const READER_ROWS = 6;
@@ -443,7 +447,7 @@ export function systemScreen(ctx: Ctx, lines: readonly string[], session: Sessio
443447 };
444448 const screen: Screen = {
445449 title: "System",
446 keys: [binding(["h"], "window"), ...(reads ? [binding(["d"], "database size")] : []), ...(mayReadAtlas(session?.user) ? [binding(["a"], "tables")] : []), ...(offered ? [binding(["T"], "grant or take back telemetry")] : []), ...(canSeeMemory(session.user) ? [binding(["x"], "explore series")] : []), binding(["enter", "esc", "q"], "close")],
450 keys: [binding(["h"], "window"), ...(reads ? [binding(["d"], "database size")] : []), ...(holds(session!.db, principalOfUser(session?.user), "forge.administer_person") ? [binding(["a"], "tables")] : []), ...(offered ? [binding(["T"], "grant or take back telemetry")] : []), ...(holds(session.db, principalOfUser(session.user), "forge.administer_person") ? [binding(["x"], "explore series")] : []), binding(["enter", "esc", "q"], "close")],
447451 render(area, s) {
448452 const features = featuresLines(session);
449453 // Never waits on the walk: the last measurement, a new one started behind it when stale.
@@ -485,9 +489,9 @@ export function systemScreen(ctx: Ctx, lines: readonly string[], session: Sessio
485489 span = (span + 1) % WINDOWS.length;
486490 history = historyLines(session, WINDOWS[span]!);
487491 } else if (e.key === "T") askGrant();
488 else if (e.key === "x" && canSeeMemory(session.user)) later(ctx, () => seriesScreen(session, ctx));
492 else if (e.key === "x" && holds(session.db, principalOfUser(session.user), "forge.administer_person")) later(ctx, () => seriesScreen(session, ctx));
489493 else if (e.key === "d" && reads) later(ctx, () => dbSizeScreen(session, ctx));
490 else if (e.key === "a" && mayReadAtlas(session.user)) later(ctx, () => abstractionsScreen(session, ctx));
494 else if (e.key === "a" && holds(session.db, principalOfUser(session.user), "forge.administer_person")) later(ctx, () => abstractionsScreen(session, ctx));
491495 else if (e.key === "enter" || e.key === "esc" || e.key === "q") ctx.pop();
492496 return true;
493497 },
@@ -499,7 +503,7 @@ const mib = (n: number) => `${(n / 1_048_576).toFixed(1)}`;
499503
500504 /** The header, then an hour a row (UTC); empty for anyone the gate refuses. */
501505 export function memoryLines(session: Session, now = Date.now()): string[] {
502 if (!canSeeMemory(session.user)) return [];
506 if (!holds(session.db, principalOfUser(session.user), "forge.administer_person")) return [];
503507 const hours = memoryHours(session.db, now);
504508 const census = censusLines(session);
505509 if (hours.length === 0) return ["No samples yet; the forge samples its memory every minute.", ...census];
@@ -519,7 +523,7 @@ export function memoryLines(session: Session, now = Date.now()): string[] {
519523 * most from the first to the last. `c` on the memory screen takes one, as /system's button does.
520524 */
521525 export function censusLines(session: Session): string[] {
522 if (!canSeeMemory(session.user)) return [];
526 if (!holds(session.db, principalOfUser(session.user), "forge.administer_person")) return [];
523527 const { censuses, grew } = censusReport(session.db);
524528 if (censuses.length === 0) return ["", "No heap census yet; c takes one."];
525529 const head = `${String(censuses.length)} heap census${censuses.length === 1 ? "" : "es"}; the last at ${String(censuses[censuses.length - 1]!.uptimeMin)} min up.`;
@@ -528,11 +532,11 @@ export function censusLines(session: Session): string[] {
528532 }
529533
530534 /**
531 * "Who is asking" as /system says it, for the owner alone (`canSeeMemory`); empty for anyone
532 * else, or when nothing is heavy and nothing has waited.
535 * "Who is asking" as /system says it, for the owner alone (`forge.administer_person`); empty for
536 * anyone else, or when nothing is heavy and nothing has waited.
533537 */
534538 export function askingLines(session: Session, inner = WIDTH - 6): string[] {
535 if (!canSeeMemory(session.user)) return [];
539 if (!holds(session.db, principalOfUser(session.user), "forge.administer_person")) return [];
536540 const { waited, bounded, longestMs } = turnStatsOf(session.app);
537541 const askers = askingOf(session.app).heavy();
538542 if (askers.length === 0 && waited === 0) return [];
@@ -544,11 +548,12 @@ export function askingLines(session: Session, inner = WIDTH - 6): string[] {
544548 }
545549
546550 /**
547 * `c` on the memory screen: /system's button (#15309), under the same gate (`canSeeMemory`) and the
548 * same ten-minute limit (`askCensus`), into the same table the page reads; what it says is a toast.
551 * `c` on the memory screen: /system's button (#15309), under the same gate
552 * (`forge.administer_person`) and the same ten-minute limit (`askCensus`), into the same table the
553 * page reads; what it says is a toast.
549554 */
550555 export function takeCensus(session: Session, now = Date.now()): { text: string; tone: Tone } {
551 if (!canSeeMemory(session.user))
556 if (!holds(session.db, principalOfUser(session.user), "forge.administer_person"))
552557 return { text: session.user?.kind === "agent" ? CENSUS_AGENT_REFUSED : "A heap census is for a forge admin.", tone: "danger" };
553558 const asked = askCensus(session.db, now, process.uptime());
554559 return asked.ok
@@ -560,7 +565,7 @@ export function memoryScreen(session: Session, ctx: Ctx): Screen {
560565 const scroll = new Scroll();
561566 return {
562567 title: "System memory",
563 keys: [binding(["j", "k"], "scroll"), ...(canSeeMemory(session.user) ? [binding(["c"], "take a heap census")] : []), binding(["esc", "q"], "back")],
568 keys: [binding(["j", "k"], "scroll"), ...(holds(session.db, principalOfUser(session.user), "forge.administer_person") ? [binding(["c"], "take a heap census")] : []), binding(["esc", "q"], "back")],
564569 render(area, s) {
565570 const c = ctx.theme.c;
566571 const lines = memoryLines(session);
@@ -570,7 +575,7 @@ export function memoryScreen(session: Session, ctx: Ctx): Screen {
570575 },
571576 key(e) {
572577 if (scroll.key(e, memoryLines(session).length)) return true;
573 if (e.key === "c" && !e.ctrl && canSeeMemory(session.user)) {
578 if (e.key === "c" && !e.ctrl && holds(session.db, principalOfUser(session.user), "forge.administer_person")) {
574579 const said = takeCensus(session);
575580 ctx.toast(said.text, said.tone);
576581 return true;
src/tui/screens/template.ts +6 −7
@@ -9,7 +9,7 @@
99 import { updateRepoSettings } from "../../actions/repos.ts";
1010 import { templateTimingLine } from "../../actions/template_timing.ts";
1111 import { templateProblem } from "../../apps/template_problem.ts";
12 import { canAdmin, getRepoById, type Repo } from "../../core/repos.ts";
12 import { getRepoById, type Repo } from "../../core/repos.ts";
1313 import { templateFirstAsk } from "../../spawn/template_first_ask.ts";
1414 import { templateSaid } from "../../core/template_words.ts";
1515 import type { Ctx, Screen } from "../app/app.ts";
@@ -19,9 +19,8 @@ import type { Session } from "../session.ts";
1919 import { style } from "../term/style.ts";
2020 import { truncate } from "../term/width.ts";
2121 import { live } from "./common.ts";
22
23 /** The toggle's gate: an admin of the repository. */
24 export const mayMarkTemplate = (f: Session, repo: Repo): boolean => f.user !== undefined && canAdmin(f.db, repo, f.user);
22 import { holds } from "../../core/may.ts";
23 import { principalOfUser } from "../../core/principal.ts";
2524
2625 export function templateScreen(f: Session, ctx: Ctx, repo: Repo): Screen {
2726 const now = (): Repo => getRepoById(f.db, repo.id) ?? repo;
@@ -45,7 +44,7 @@ export function templateScreen(f: Session, ctx: Ctx, repo: Repo): Screen {
4544 render(area, s) {
4645 const c = ctx.theme.c;
4746 const on = now().template;
48 const said = !mayMarkTemplate(f, repo)
47 const said = !holds(f.db, principalOfUser(f.user), "repo.admin", { repo: repo })
4948 ? "An admin of this repository marks it a template."
5049 : on
5150 ? "New forges may start from this repository. t clears it."
@@ -61,7 +60,7 @@ export function templateScreen(f: Session, ctx: Ctx, repo: Repo): Screen {
6160 },
6261 key(e) {
6362 if (e.ctrl || e.alt || e.key !== "t") return false;
64 const set = mayMarkTemplate(f, repo)
63 const set = holds(f.db, principalOfUser(f.user), "repo.admin", { repo: repo })
6564 ? updateRepoSettings(f.app, f.user, now(), { template: !now().template })
6665 : undefined;
6766 void Promise.resolve(set).then((r) => {
@@ -76,7 +75,7 @@ export function templateScreen(f: Session, ctx: Ctx, repo: Repo): Screen {
7675
7776 /** The palette's command while a repository the viewer administers is open. */
7877 export function templateCommands(f: Session, ctx: Ctx, repo: Repo | undefined): Command[] {
79 if (repo === undefined || !mayMarkTemplate(f, repo)) return [];
78 if (repo === undefined || !holds(f.db, principalOfUser(f.user), "repo.admin", { repo: repo })) return [];
8079 return [
8180 {
8281 id: "template",
src/tui/screens/trusted.ts +5 −6
@@ -17,6 +17,8 @@ import { truncate } from "../term/width.ts";
1717 import type { Session } from "../session.ts";
1818 import { fill, len, split } from "../ui/layout.ts";
1919 import { ListState, confirmScreen, drawList, promptScreen, runAsync, type ListRow } from "./common.ts";
20 import { holds } from "../../core/may.ts";
21 import { principalOfUser } from "../../core/principal.ts";
2022
2123 const WORDS: Record<TrustError | "not_found", string> = {
2224 bad_host: "That is not a forge address.",
@@ -26,12 +28,9 @@ const WORDS: Record<TrustError | "not_found", string> = {
2628 not_found: "Only a forge admin changes who is trusted.",
2729 };
2830
29 /** Whether the palette offers the screen: a signed-in admin who is a person. */
30 export const mayTrust = (f: Session): boolean => f.user !== undefined && f.user.isAdmin && f.user.kind !== "agent";
31
3231 export function trustedScreen(f: Session, ctx: Ctx): Screen {
3332 const state = new ListState();
34 const entries = () => (mayTrust(f) ? listTrusted(f.db) : []);
33 const entries = () => (holds(f.db, principalOfUser(f.user), "forge.administer_person") ? listTrusted(f.db) : []);
3534
3635 const rows = (): ListRow[] => {
3736 const now = new Date();
@@ -51,7 +50,7 @@ export function trustedScreen(f: Session, ctx: Ctx): Screen {
5150 const c = ctx.theme.c;
5251 const [head, body] = split(area, "v", [len(1), fill(1)]);
5352 const stopped = foldInStopped(f.db);
54 const text = !mayTrust(f)
53 const text = !holds(f.db, principalOfUser(f.user), "forge.administer_person")
5554 ? "Only a forge admin changes who is trusted."
5655 : stopped !== undefined
5756 ? `Folding in is stopped (by ${stopped.by}); s resumes it.`
@@ -60,7 +59,7 @@ export function trustedScreen(f: Session, ctx: Ctx): Screen {
6059 drawList(s, body!, c, state, rows());
6160 },
6261 key(e) {
63 if (!mayTrust(f) || e.ctrl || e.alt) return false;
62 if (!holds(f.db, principalOfUser(f.user), "forge.administer_person") || e.ctrl || e.alt) return false;
6463 if (state.key(e, entries().length)) return true;
6564 const user = f.user;
6665 const at = entries()[state.index];
src/tui/screens/usage.ts +3 −2
@@ -14,7 +14,6 @@
1414 import { USAGE_ADMIN_ONLY } from "../../actions/admin_limits_words.ts";
1515 import { readForgeUsage, type ForgeUsage } from "../../actions/usage.ts";
1616 import { readReturns } from "../../actions/returns.ts";
17 import { mayManageFlags } from "../../core/flags.ts";
1817 import { ROLES, SURFACES } from "../../core/usage_count.ts";
1918 import { creditDaysLine } from "../../actions/crew_means.ts";
2019 import { COST_DAYS, costDays, dayLine } from "../../core/cost_days.ts";
@@ -32,6 +31,8 @@ import type { Session } from "../session.ts";
3231 import { fill, len, split } from "../ui/layout.ts";
3332 import { fleetGraphScreen } from "./fleetgraph.ts";
3433 import { ListState, drawList, type ListRow } from "./common.ts";
34 import { holds } from "../../core/may.ts";
35 import { principalOfUser } from "../../core/principal.ts";
3536
3637 const part = (counts: Readonly<Record<string, number>>, keys: readonly string[]) =>
3738 keys.map((k) => `${k} ${counts[k] ?? 0}`).join(" ");
@@ -76,7 +77,7 @@ export function forgeSpendLines(r: ForgeUsage): string[] {
7677
7778 export function usageScreen(f: Session, ctx: Ctx, repo?: Repo): Screen {
7879 const state = new ListState();
79 const allowed = repo === undefined && mayManageFlags(f.user);
80 const allowed = repo === undefined && holds(f.db, principalOfUser(f.user), "forge.administer_person");
8081 // Read once when the screen opens: the report scans the whole table, so a frame or a key never
8182 // re-runs it.
8283 const rows: RouteUsage[] = allowed ? routeUsage(f.db, knownPatterns(), new Date()) : [];
src/tui/screens/valves.ts +3 −2
@@ -23,7 +23,8 @@ import { truncate } from "../term/width.ts";
2323 import { fill, len, split } from "../ui/layout.ts";
2424 import type { PaletteEntry } from "./entries.ts";
2525 import { ListState, drawList, live, runAsync, type ListRow } from "./common.ts";
26 import { mayCapacity } from "./capacity.ts";
26 import { holds } from "../../core/may.ts";
27 import { principalOfUser } from "../../core/principal.ts";
2728
2829 const STEP = 10;
2930
@@ -41,7 +42,7 @@ export function valvesScreen(f: Session, ctx: Ctx): Screen {
4142 const state = new ListState();
4243 let pipes: Pipes | undefined;
4344 const reload = (): void => {
44 pipes = mayCapacity(f) && f.user !== undefined ? readPipes(f.db, f.user.id) : undefined;
45 pipes = holds(f.db, principalOfUser(f.user), "forge.administer_person") && f.user !== undefined ? readPipes(f.db, f.user.id) : undefined;
4546 ctx.invalidate();
4647 };
4748 let retrying = false;
src/tui/screens/wallet.ts +6 −7
@@ -6,7 +6,7 @@
66
77 import { readWalletMonths } from "../../actions/wallet_months.ts";
88 import { capInvalidWords, capSavedWords, saveCap } from "../../actions/wallet.ts";
9 import { canAdmin, type Repo } from "../../core/repos.ts";
9 import { type Repo } from "../../core/repos.ts";
1010 import { daysLeftLine, lastWeek } from "../../core/wallet_days_left.ts";
1111 import { capReached, lowWallet, monthCap, monthSpent, spentWords, WALLET_CAP_MAX_USD } from "../../core/wallet.ts";
1212 import type { Ctx, Screen } from "../app/app.ts";
@@ -16,13 +16,12 @@ import type { Session } from "../session.ts";
1616 import { style } from "../term/style.ts";
1717 import { truncate } from "../term/width.ts";
1818 import { live, promptScreen } from "./common.ts";
19
20 /** The wallet's gate: an admin of the repository. */
21 export const mayManageWallet = (f: Session, repo: Repo): boolean => f.user !== undefined && canAdmin(f.db, repo, f.user);
19 import { holds } from "../../core/may.ts";
20 import { principalOfUser } from "../../core/principal.ts";
2221
2322 /** The lines the screen draws: what was spent, then the paused sentence when the cap is reached. */
2423 export function walletLines(f: Session, repo: Repo, now: Date): string[] {
25 if (!mayManageWallet(f, repo)) return ["An admin of this repository manages its wallet."];
24 if (!holds(f.db, principalOfUser(f.user), "repo.admin", { repo: repo })) return ["An admin of this repository manages its wallet."];
2625 const cap = monthCap(f.db, repo.id);
2726 const spentUsd = monthSpent(f.db, repo.id, now);
2827 const spent = spentUsd.toFixed(2);
@@ -53,7 +52,7 @@ export function walletScreen(f: Session, ctx: Ctx, repo: Repo): Screen {
5352 },
5453 key(e) {
5554 if (e.ctrl || e.alt || e.key !== "c") return false;
56 if (!mayManageWallet(f, repo)) {
55 if (!holds(f.db, principalOfUser(f.user), "repo.admin", { repo: repo })) {
5756 ctx.toast("An admin of this repository manages its wallet.", "danger");
5857 return true;
5958 }
@@ -80,7 +79,7 @@ export function walletScreen(f: Session, ctx: Ctx, repo: Repo): Screen {
8079
8180 /** The palette's command while a repository the viewer administers is open. */
8281 export function walletCapCommands(f: Session, ctx: Ctx, repo: Repo | undefined): Command[] {
83 if (repo === undefined || !mayManageWallet(f, repo)) return [];
82 if (repo === undefined || !holds(f.db, principalOfUser(f.user), "repo.admin", { repo: repo })) return [];
8483 return [
8584 {
8685 id: "wallet",
src/web/pages/flags.ts +5 −3
@@ -9,7 +9,7 @@
99 import { sshOn } from "../../settings/ssh.ts";
1010 import { emptyLine } from "../empty_words.ts";
1111 import { readFlags } from "../../actions/flags_view.ts";
12 import { checkInput, FLAGS_ADMIN_ONLY, flagRegistry, usesLine, winnerOffer, mayManageFlags, useFlagRegistry, type FlagValue } from "../../core/flags.ts";
12 import { checkInput, FLAGS_ADMIN_ONLY, flagRegistry, usesLine, winnerOffer, useFlagRegistry, type FlagValue } from "../../core/flags.ts";
1313 import { makeWinnerDefault } from "../../actions/flag_winner.ts";
1414 import type { Ctx } from "../../http/context.ts";
1515 import { notePhase, takeSessionTime, timePhase } from "../../core/route_timing.ts";
@@ -20,13 +20,15 @@ import { flashTo, page } from "../layout.ts";
2020 import { btn, empty, icon, row } from "../ui.ts";
2121 import { accountSections } from "./origins.ts";
2222 import { signedInPage } from "../../http/page_may.ts";
23 import { holds } from "../../core/may.ts";
24 import { principalOfUser } from "../../core/principal.ts";
2325
2426 export { useFlagRegistry };
2527
2628 function denied(ctx: Ctx): Response | undefined {
2729 if (!signedInPage(ctx)) return signInFirst(ctx);
2830 const user = ctx.auth.user;
29 if (mayManageFlags(user)) return undefined;
31 if (holds(ctx.app.db, principalOfUser(user), "forge.administer_person")) return undefined;
3032 return page(
3133 {
3234 ctx,
@@ -69,7 +71,7 @@ export function flagsPage(ctx: Ctx): Response {
6971 if (no) return no;
7072 const registry = timePhase(ctx.request, "registry", flagRegistry);
7173 const repo = ctx.app.config.forgeRepo;
72 const read = timePhase(ctx.request, "values", () => readFlags(ctx.auth.user));
74 const read = timePhase(ctx.request, "values", () => readFlags(ctx.app.db, ctx.auth.user));
7375 const flags = read.ok ? read.flags : [];
7476 const names = flags.map((f) => f.name);
7577 // The per-flag reads are interleaved with building each row: sum each.
src/web/pages/forges-refused.ts +4 −2
@@ -7,19 +7,21 @@
77
88 import type { Ctx } from "../../http/context.ts";
99 import { notePhase, takeSessionTime } from "../../core/route_timing.ts";
10 import { REFUSED_SHOWN, listRefusals, mayReadRefusals } from "../../core/first_ask_refusals.ts";
10 import { REFUSED_SHOWN, listRefusals } from "../../core/first_ask_refusals.ts";
1111 import { notFoundPage, pageHead } from "../chrome.ts";
1212 import { html } from "../html.ts";
1313 import { page } from "../layout.ts";
1414 import { time } from "../ui.ts";
1515 import { emptyLine } from "../empty_words.ts";
16 import { holds } from "../../core/may.ts";
17 import { principalOfUser } from "../../core/principal.ts";
1618
1719 export { REFUSED_SHOWN };
1820
1921 // GET /forges/refused — an admin's only.
2022 export function forgesRefusedPage(ctx: Ctx): Response {
2123 notePhase(ctx.request, "session", takeSessionTime(ctx.request));
22 if (!mayReadRefusals(ctx.auth.user)) return notFoundPage(ctx);
24 if (!holds(ctx.app.db, principalOfUser(ctx.auth.user), "forge.administer_person")) return notFoundPage(ctx);
2325 const rendering = performance.now();
2426 const rows = listRefusals(ctx.app.db, REFUSED_SHOWN, Date.now());
2527 const res = page({
src/web/pages/forges.ts +4 −2
@@ -30,7 +30,7 @@ import { sharedForges } from "../../actions/upgrade_shared.ts";
3030 import { machinesOf } from "../../spawn/machines.ts";
3131 import { moveToCell } from "../../spawn/move_cell.ts";
3232 import { sealedAt } from "../../spawn/sealed.ts";
33 import { countRefusals, mayReadRefusals } from "../../core/first_ask_refusals.ts";
33 import { countRefusals } from "../../core/first_ask_refusals.ts";
3434 import { revokePreview } from "../../spawn/manage.ts";
3535 import { clientsCsv } from "../../spawn/clients_csv.ts";
3636 import { claimLinkBody } from "./new-forge.ts";
@@ -50,6 +50,8 @@ import { CHILD_NAME } from "../../spawn/placement.ts";
5050 import { forgesMemory, memoryOverLine } from "../../spawn/memory_fit.ts";
5151 import { NO_KEY_HELD } from "../../crew/no_key.ts";
5252 import { adminPage, signedInPage } from "../../http/page_may.ts";
53 import { holds } from "../../core/may.ts";
54 import { principalOfUser } from "../../core/principal.ts";
5355
5456
5557 /** "3 apps running", or which one is not and why. */
@@ -254,7 +256,7 @@ function sealedLine(ctx: Ctx): Html | null {
254256 * paragraph of the other link so the page gains no block.
255257 */
256258 function refusedLink(ctx: Ctx): Html | null {
257 if (!mayReadRefusals(ctx.auth.user)) return null;
259 if (!holds(ctx.app.db, principalOfUser(ctx.auth.user), "forge.administer_person")) return null;
258260 const n = countRefusals(ctx.app.db, Date.now());
259261 return n === 0 ? null : html` <a href="/forges/refused">Refused first asks (${n})</a>`;
260262 }
src/web/pages/machines.ts +1 −1
@@ -63,7 +63,7 @@ export async function machinesSettingsPage(ctx: Ctx): Promise<Response> {
6363 const sessions = timePhase(ctx.request, "sessions", () => lastSessions(ctx.app.db, repo.id));
6464 const states = machineStates(ctx.app, repo.id, ctx.auth.user!.id);
6565 // Readings are the host's, keyed by machine name alone, so they are shown
66 // to the owner (`mayHandleDisks`) and to no other writer: a name two
66 // to the owner (`forge.administer_person`) and to no other writer: a name two
6767 // repositories share must not carry one repository's disks to the other.
6868 const disks = timePhase(ctx.request, "disks", () => {
6969 const seen = new Map<string, readonly DeviceSummary[]>();
src/web/pages/now.ts +4 −2
@@ -5,7 +5,7 @@
55 * admin's, as the line is: the counts cover every repository.
66 */
77
8 import { mayReadNow, NOW_HOLDS, NOW_LISTED, NOW_STAGES, NOW_WORDS, readNowRows } from "../../flow/now_rows.ts";
8 import { NOW_HOLDS, NOW_LISTED, NOW_STAGES, NOW_WORDS, readNowRows } from "../../flow/now_rows.ts";
99 import { notePhase, takeSessionTime } from "../../core/route_timing.ts";
1010 import type { Ctx } from "../../http/context.ts";
1111 import { notFoundPage, signInFirst } from "../chrome.ts";
@@ -13,6 +13,8 @@ import { html } from "../html.ts";
1313 import { page } from "../layout.ts";
1414 import { row, time } from "../ui.ts";
1515 import { signedInPage } from "../../http/page_may.ts";
16 import { holds } from "../../core/may.ts";
17 import { principalOfUser } from "../../core/principal.ts";
1618
1719 // GET /now/:stage
1820 export function nowPage(ctx: Ctx): Response {
@@ -20,7 +22,7 @@ export function nowPage(ctx: Ctx): Response {
2022 if (!signedInPage(ctx)) return signInFirst(ctx);
2123 const user = ctx.auth.user;
2224 const stage = NOW_STAGES.find((s) => s === ctx.params["stage"]);
23 if (stage === undefined || !mayReadNow(user)) return notFoundPage(ctx);
25 if (stage === undefined || !holds(ctx.app.db, principalOfUser(user), "forge.administer_person")) return notFoundPage(ctx);
2426 const reading = performance.now();
2527 const { total, rows } = readNowRows(ctx.app.db, stage);
2628 const body =
src/web/pages/packs.ts +4 −2
@@ -18,9 +18,11 @@ import { mirrorPacks, reportWords } from "../../packs/mirror.ts";
1818 import { emptySection } from "../empty_words.ts";
1919 import { btn, copyField, field as uiField, row, timeAgo } from "../ui.ts";
2020 import { listReposVisibleTo } from "../../core/repos.ts";
21 import { changeRepos, editPack, getPack, history, listPacks, mayCurate, resolveRepos, slugOf, type CuratedPack, type PackRepo } from "../../packs/curated.ts";
21 import { changeRepos, editPack, getPack, history, listPacks, resolveRepos, slugOf, type CuratedPack, type PackRepo } from "../../packs/curated.ts";
2222 import { field, readForm } from "../form.ts";
2323 import { personAdminPage } from "../../http/page_may.ts";
24 import { holds } from "../../core/may.ts";
25 import { principalOfUser } from "../../core/principal.ts";
2426
2527 const plural = (n: number, one: string): string => `${n} ${one}${n === 1 ? "" : "s"}`;
2628
@@ -38,7 +40,7 @@ export const packsList = (packs: readonly Pack[]) =>
3840 /** A pack pushed to its repo shows within this long. */
3941 const CATALOG_FRESH_MS = 2_000;
4042
41 const admin = (ctx: Ctx): boolean => mayCurate(ctx.auth.user);
43 const admin = (ctx: Ctx): boolean => holds(ctx.app.db, principalOfUser(ctx.auth.user), "forge.administer_person");
4244
4345 /** The newest push among a pack's shown repos, as "3d ago", or a plain "no pushes yet". */
4446 const freshness = (repos: readonly PackRepo[]): string => {
src/web/pages/series.ts +5 −4
@@ -8,7 +8,6 @@
88 * `range`, `from`, `to`), so a view is a link; the only script is none.
99 */
1010 import { signedInPage } from "../../http/page_may.ts";
11 import { canSeeMemory } from "../../boards/memory.ts";
1211 import type { Ctx } from "../../http/context.ts";
1312 import { notePhase, takeSessionTime, timePhase } from "../../core/route_timing.ts";
1413 import { listSaved, removeSaved, save, NOTE_MAX, TITLE_MAX, type Saved } from "../../series/saved.ts";
@@ -20,6 +19,8 @@ import { readForm } from "../form.ts";
2019 import { html, type Html } from "../html.ts";
2120 import { flashTo, page } from "../layout.ts";
2221 import { emptyList } from "../empty_words.ts";
22 import { holds } from "../../core/may.ts";
23 import { principalOfUser } from "../../core/principal.ts";
2324
2425 const CHARTED = 6;
2526 /** A headed section, not a box: the rows and the chart inside it carry their own lines. */
@@ -93,7 +94,7 @@ function savedList(rows: readonly Saved[], minutes: number): Html {
9394 export function seriesPage(ctx: Ctx): Response {
9495 notePhase(ctx.request, "session", takeSessionTime(ctx.request));
9596 if (!signedInPage(ctx)) return signInFirst(ctx);
96 if (!canSeeMemory(ctx.auth.user)) return notFoundPage(ctx);
97 if (!holds(ctx.app.db, principalOfUser(ctx.auth.user), "forge.administer_person")) return notFoundPage(ctx);
9798 const ask = askOf(ctx.url.searchParams);
9899 const a = answer(ctx.app.db, ask, Date.now());
99100 const names = known(ctx.app.db);
@@ -119,7 +120,7 @@ export async function seriesSave(ctx: Ctx): Promise<Response> {
119120 if (!signedInPage(ctx)) return signInFirst(ctx);
120121 const form = await readForm(ctx, "admin");
121122 if (form instanceof Response) return form;
122 if (!canSeeMemory(ctx.auth.user)) return ctx.auth.user.kind === "agent" ? forbiddenPage(ctx, "Saving a query is a person's.") : notFoundPage(ctx);
123 if (!holds(ctx.app.db, principalOfUser(ctx.auth.user), "forge.administer_person")) return ctx.auth.user.kind === "agent" ? forbiddenPage(ctx, "Saving a query is a person's.") : notFoundPage(ctx);
123124 const text = (k: string) => (typeof form.get(k) === "string" ? (form.get(k) as string) : "");
124125 const saved = save(ctx.app.db, { kind: text("kind"), title: text("title"), query: text("q"), note: text("note") }, Date.now());
125126 if (!saved.ok) return flashTo(ctx, seriesHref(text("q") || "", 60), { tone: "danger", message: saved.error });
@@ -131,7 +132,7 @@ export async function seriesRemove(ctx: Ctx): Promise<Response> {
131132 if (!signedInPage(ctx)) return signInFirst(ctx);
132133 const form = await readForm(ctx, "admin");
133134 if (form instanceof Response) return form;
134 if (!canSeeMemory(ctx.auth.user)) return ctx.auth.user.kind === "agent" ? forbiddenPage(ctx, "Removing a saved query is a person's.") : notFoundPage(ctx);
135 if (!holds(ctx.app.db, principalOfUser(ctx.auth.user), "forge.administer_person")) return ctx.auth.user.kind === "agent" ? forbiddenPage(ctx, "Removing a saved query is a person's.") : notFoundPage(ctx);
135136 const id = Number(form.get("id"));
136137 if (!Number.isSafeInteger(id) || !removeSaved(ctx.app.db, id)) return flashTo(ctx, "/explore/series", { tone: "danger", message: "No such saved query." });
137138 return flashTo(ctx, "/explore/series", { message: "Removed." });
src/web/pages/series_pins.ts +4 −3
@@ -1,19 +1,20 @@
11 /**
22 * The home's pinned series (#3696): one row a pin, its latest value beside
33 * the title, a link to the query on /explore/series. Drawn for the people who
4 * may open that page (`canSeeMemory`) and only when something is pinned.
4 * may open that page (`forge.administer_person`) and only when something is pinned.
55 */
6 import { canSeeMemory } from "../../boards/memory.ts";
76 import { pinsNow } from "../../series/pins.ts";
87 import { DEFAULT_QUERY, figure } from "../../series/view.ts";
98 import type { Ctx } from "../../http/context.ts";
109 import { html, type Html } from "../html.ts";
1110 import { row } from "../ui.ts";
1211 import { seriesHref } from "./series.ts";
12 import { holds } from "../../core/may.ts";
13 import { principalOfUser } from "../../core/principal.ts";
1314
1415 export function pinnedSeries(ctx: Ctx, now: number): Html | null {
1516 const user = ctx.auth.user;
16 if (user === undefined || !canSeeMemory(user)) return null;
17 if (user === undefined || !holds(ctx.app.db, principalOfUser(user), "forge.administer_person")) return null;
1718 const pins = pinsNow(ctx.app.db, now);
1819 if (pins.length === 0) return null;
1920 return html`<section class="stack" id="pinned-series" aria-label="Pinned series">
src/web/pages/system.ts +13 −8
@@ -28,9 +28,8 @@ import { emptyNote } from "../empty_words.ts";
2828 import { sentinelRepoPath, withheldFindings, type WithheldFinding } from "../../crew/sentinel.ts";
2929 import { ownRepoRate, rateLine, RATE_MIN, type Rate } from "../../checks/deepsec_rate.ts";
3030 import { turnStatsOf } from "../../http/app_turn.ts";
31 import { mayReadRefusals } from "../../core/first_ask_refusals.ts";
3231 import { outsideDependencies } from "../../keeper/at_boot.ts";
33 import { canSeeMemory, memoryHours } from "../../boards/memory.ts";
32 import { memoryHours } from "../../boards/memory.ts";
3433 import { telemetryReader } from "../../actions/telemetry.ts";
3534 import type { Ctx } from "../../http/context.ts";
3635 import { memoryCapHolder, PROCESSES_MAX, processCapHolder, TASKS_MAX } from "../../apps/contain.ts";
@@ -84,6 +83,8 @@ import { childDirOf, listChildren } from "../../actions/spawn.ts";
8483 import { adoptionsOf } from "../../spawn/cell.ts";
8584 import type { AdoptionRow } from "../../spawn/adopted.ts";
8685 import { childrenUse, mibWords, realSelf, selfUse, shareOf, sizeWords, useWords, type ChildUseRow, type SelfUse } from "../../spawn/usage.ts";
86 import { holds } from "../../core/may.ts";
87 import { principalOfUser } from "../../core/principal.ts";
8788
8889 /** A group's memory, and a cell's beside its cap and who holds the cap. */
8990 const memoryOf = (g: { rssBytes: number; capBytes: number | null; capBy: "kernel" | "watch" | null }): Html =>
@@ -363,7 +364,7 @@ export async function heapCensusSubmit(ctx: Ctx): Promise<Response> {
363364 const form = await readForm(ctx, "admin");
364365 if (form instanceof Response) return form;
365366 // An agent hears why in one sentence; a person who is not an admin finds no such page.
366 if (!canSeeMemory(ctx.auth.user)) return ctx.auth.user.kind === "agent" ? forbiddenPage(ctx, CENSUS_AGENT_REFUSED) : notFoundPage(ctx);
367 if (!holds(ctx.app.db, principalOfUser(ctx.auth.user), "forge.administer_person")) return ctx.auth.user.kind === "agent" ? forbiddenPage(ctx, CENSUS_AGENT_REFUSED) : notFoundPage(ctx);
367368 const asked = askCensus(ctx.app.db, Date.now(), process.uptime());
368369 if (!asked.ok) {
369370 const res = prefersJson(ctx.request)
@@ -375,9 +376,12 @@ export async function heapCensusSubmit(ctx: Ctx): Promise<Response> {
375376 return flashTo(ctx, "/system#heap-census", { message: `Heap census taken: ${asked.census.objectCount.toLocaleString("en-US")} objects.` });
376377 }
377378
378 /** The forge's RSS beside its JS heap, an hour a row; empty for anyone `canSeeMemory` refuses. */
379 /**
380 * The forge's RSS beside its JS heap, an hour a row; empty for anyone `forge.administer_person`
381 * refuses.
382 */
379383 function memorySection(ctx: Ctx): Html {
380 if (!canSeeMemory(ctx.auth.user)) return html``;
384 if (!holds(ctx.app.db, principalOfUser(ctx.auth.user), "forge.administer_person")) return html``;
381385 const hours = timePhase(ctx.request, "memory", () => memoryHours(ctx.app.db, Date.now()));
382386 const series = (title: string, pick: (h: (typeof hours)[number]) => number) =>
383387 html`<div><h3 class="small">${title}</h3>${chartBox("line", hours.map((h) => ({ label: hhmm(h.at).slice(11), value: pick(h) / 1_048_576 })), title)}</div>`;
@@ -786,8 +790,9 @@ export async function systemPage(ctx: Ctx, patterns: () => readonly string[]): P
786790 const egressLine: Html | null =
787791 egressSaid === null ? null : html`<p class="small" id="egress-reported">${egressSaid} <a href="/settings/capacity">Capacity</a></p>`;
788792 const memory = memorySection(ctx);
789 // Size and children are the owner's to see, as the terminal's System command is (`canSeeMemory`).
790 const owner = canSeeMemory(ctx.auth.user);
793 // Size and children are the owner's to see, as the terminal's System command is
794 // (`forge.administer_person`).
795 const owner = holds(ctx.app.db, principalOfUser(ctx.auth.user), "forge.administer_person");
791796 const self = owner ? timePhase(ctx.request, "self", () => selfUse(realSelf(ctx.app.config.dataDir))) : null;
792797 const listed = owner ? await listChildren(ctx.app) : [];
793798 const children = childrenUse(listed, (bodyId) => childDirOf(ctx.app, bodyId));
@@ -825,7 +830,7 @@ export async function systemPage(ctx: Ctx, patterns: () => readonly string[]): P
825830 <span class="spacer"></span><a href="/system?pause">pause</a>
826831 </div>
827832 ${help}
828 ${mayReadRefusals(ctx.auth.user) ? html`<p class="small"><a href="/forges/refused">Refused first asks</a></p>` : null}
833 ${holds(ctx.app.db, principalOfUser(ctx.auth.user), "forge.administer_person") ? html`<p class="small"><a href="/forges/refused">Refused first asks</a></p>` : null}
829834 <div id="sys-dup">${at("sys-dup")}</div>
830835 <section class="settings-block"><h2>Machine</h2>
831836 <div id="summary" class="row-meta">${at("summary")}</div>
src/web/pages/usage.ts +3 −2
@@ -6,7 +6,6 @@
66 */
77
88 import { USAGE_ADMIN_ONLY } from "../../actions/admin_limits_words.ts";
9 import { mayManageFlags } from "../../core/flags.ts";
109 import { ROLES, SURFACES } from "../../core/usage_count.ts";
1110 import { notePhase, takeSessionTime, timePhase } from "../../core/route_timing.ts";
1211 import { routeUsage, WINDOW_DAYS } from "../../core/usage_report.ts";
@@ -17,6 +16,8 @@ import { page } from "../layout.ts";
1716 import { btn, empty } from "../ui.ts";
1817 import { usageShell } from "./usage-tabs.ts";
1918 import { signedInPage } from "../../http/page_may.ts";
19 import { holds } from "../../core/may.ts";
20 import { principalOfUser } from "../../core/principal.ts";
2021
2122 /** Only the keys that were used: "user 5 · agent 2", or nothing. */
2223 const part = (counts: Readonly<Record<string, number>>, keys: readonly string[]) =>
@@ -27,7 +28,7 @@ export function usagePage(ctx: Ctx, patterns: () => readonly string[]): Response
2728 notePhase(ctx.request, "session", takeSessionTime(ctx.request));
2829 if (!signedInPage(ctx)) return signInFirst(ctx);
2930 const user = ctx.auth.user;
30 if (!mayManageFlags(user))
31 if (!holds(ctx.app.db, principalOfUser(user), "forge.administer_person"))
3132 return page(
3233 {
3334 ctx,
src/web/studio/design.ts +5 −6
@@ -14,6 +14,7 @@ import type { Ctx } from "../../http/context.ts";
1414 import { eventStream } from "../../http/sse.ts";
1515 import { getUserById } from "../../core/users.ts";
1616 import type { Database } from "bun:sqlite";
17 import type { User } from "../../core/users.ts";
1718 import { THEMES } from "../../design/themes.ts";
1819 import { notePhase, takeSessionTime } from "../../core/route_timing.ts";
1920 import { notFoundPage, pageHead, signInFirst } from "../chrome.ts";
@@ -24,6 +25,8 @@ import { emptyLine, emptyList } from "../empty_words.ts";
2425 import { behaviorsJs } from "../behaviors.ts";
2526 import { badge, btn, card, dot, empty, field, kbd, listCard, meter, pill, row, stat, tabs, timeAgo } from "../ui.ts";
2627 import { homeTabs } from "./home_tabs.ts";
28 import { holds } from "../../core/may.ts";
29 import { principalOfUser } from "../../core/principal.ts";
2730
2831 // ---- the theme as data: tokens, the AA gate, versions (was design/theme.ts) ----
2932
@@ -271,18 +274,14 @@ export function revertTheme(db: Database, org: string, name: string, actorId: st
271274 return publishTheme(db, org, name, back, actorId, `Revert of v${cur.version}`);
272275 }
273276
274 /** The two writes, with one gate for the page and the terminal: a site admin who is a person. */
275 export const mayEditTheme = (user: { isAdmin?: boolean; kind?: string } | undefined): boolean =>
276 user?.isAdmin === true && user.kind !== "agent";
277
278277 /** What a publish or a revert did, and the bus event open pages follow (`theme.published`). */
279278 export function steerTheme(
280279 app: { db: Database; bus: { append(e: { kind: "theme.published"; actorId: string; payload: Record<string, unknown> }): unknown } },
281 user: { id: string; isAdmin?: boolean; kind?: string } | undefined,
280 user: User | undefined,
282281 action: "publish" | "revert",
283282 draft?: unknown,
284283 ): Published | { ok: false; error: "forbidden" } {
285 if (user === undefined || !mayEditTheme(user)) return { ok: false, error: "forbidden" };
284 if (user === undefined || !holds(app.db, principalOfUser(user), "forge.administer_person")) return { ok: false, error: "forbidden" };
286285 const { org, name } = FORGE_THEME;
287286 const done = action === "publish" ? publishTheme(app.db, org, name, draft, user.id) : revertTheme(app.db, org, name, user.id);
288287 if (done.ok) app.bus.append({ kind: "theme.published", actorId: user.id, payload: { org, name, version: done.version } });
src/web/studio/explore.ts +4 −4
@@ -18,7 +18,6 @@ import {
1818 badExploreParam,
1919 exploreParams,
2020 exploreMetric,
21 mayQueryMetric,
2221 NO_POINTS,
2322 metricCells,
2423 exploreNote,
@@ -37,7 +36,6 @@ import {
3736 type ExploreRow,
3837 } from "../../actions/explore.ts";
3938 import { drawChart } from "../../boards/chart.ts";
40 import { canSeeMemory } from "../../boards/memory.ts";
4139 import { MAX_METRIC_TEXT, MAX_TABLE } from "../../boards/query.ts";
4240 import { exploreThumbs } from "../../looks/explore_pictures.ts";
4341 import { frontWeights, type FrontWeights } from "../../core/front.ts";
@@ -51,6 +49,8 @@ import { page, redirect } from "../layout.ts";
5149 import { heldCopy, pageTag } from "../page_tag.ts";
5250 import { btn, card, chartFrame, empty, nameMark, row as rowOf, seg, tabs, time } from "../ui.ts";
5351 import { emptyList } from "../empty_words.ts";
52 import { holds } from "../../core/may.ts";
53 import { principalOfUser } from "../../core/principal.ts";
5454
5555 const href = (query: ExploreQuery, page = 1): string => {
5656 const params = new URLSearchParams(exploreParams(query));
@@ -366,8 +366,8 @@ export async function explorePage(ctx: Ctx): Promise<Response> {
366366 const body = html`<div data-explore>${pageHead("Explore", {
367367 sub: query.kind === "person" ? PEOPLE_ORDER_WORDS : "Public apps and their builders, ranked by use, forks, deployments and recency.",
368368 })}
369 ${!mayQueryMetric(ctx.auth.user) ? html`` : metricBox(metricText, metric)}
370 ${ctx.auth.user !== undefined && canSeeMemory(ctx.auth.user) ? html`<p class="small mb" data-series-link><a href="/explore/series">Series over time</a></p>` : html``}
369 ${!holds(ctx.app.db, principalOfUser(ctx.auth.user), "forge.administer_person") ? html`` : metricBox(metricText, metric)}
370 ${ctx.auth.user !== undefined && holds(ctx.app.db, principalOfUser(ctx.auth.user), "forge.administer_person") ? html`<p class="small mb" data-series-link><a href="/explore/series">Series over time</a></p>` : html``}
371371 <div class="bar mb" data-filter-line>
372372 <form method="get" action="/explore" class="bar">
373373 <input
test/flags-view.test.ts +5 −5
@@ -42,21 +42,21 @@ describe("readFlags", () => {
4242 });
4343
4444 test("an admin sees each flag with its default, and the live value once set", () => {
45 const before = readFlags(admin);
45 const before = readFlags(app.db, admin);
4646 expect(before).toEqual({
4747 ok: true,
4848 flags: [{ name: "alpha", why: "shows the new board", default: false, issue: 12, value: undefined }],
4949 });
5050 reg.set(app.db, "alpha", { forge: true }, admin.id);
51 const after = readFlags(admin);
51 const after = readFlags(app.db, admin);
5252 expect(after.ok && after.flags[0]?.value).toEqual({ forge: true });
5353 expect(after.ok && after.flags[0]?.default).toBe(false);
5454 });
5555
5656 test("a non-admin, an agent and nobody are refused", () => {
5757 const refusal = { ok: false as const, message: FLAGS_ADMIN_ONLY };
58 expect(readFlags(bob)).toEqual(refusal);
59 expect(readFlags({ ...admin, kind: "agent" })).toEqual(refusal);
60 expect(readFlags(undefined)).toEqual(refusal);
58 expect(readFlags(app.db, bob)).toEqual(refusal);
59 expect(readFlags(app.db, { ...admin, kind: "agent" })).toEqual(refusal);
60 expect(readFlags(app.db, undefined)).toEqual(refusal);
6161 });
6262 });
test/may-only.test.ts added +200
@@ -0,0 +1,200 @@
1 /**
2 * `may()` is the only permission check (#18484, Access 3 finishing). Two things are held here:
3 *
4 * - An exported permission helper (`mayX`, `canX`, `isAdmin`) beside `may` fails the test unless
5 * it is named in `STILL_TO_FOLD`, the helpers not yet folded into `may`, or in `NOT_ACCESS`,
6 * the `may…`/`can…` names that are not a question about who. `STILL_TO_FOLD` only shrinks: a
7 * helper that is deleted but still listed fails too, and a new one is never added to it.
8 * - The helpers that were folded answered what `may` answers now, on the fixtures they were
9 * deleted against (the old rule is written out below).
10 */
11 import { afterAll, beforeAll, expect, test } from "bun:test";
12 import { Glob } from "bun";
13 import { mkdtemp, rm } from "node:fs/promises";
14 import { tmpdir } from "node:os";
15 import { join } from "node:path";
16 import { createRepo } from "../src/actions/repos.ts";
17 import { createApp, type App } from "../src/app.ts";
18 import { holds } from "../src/core/may.ts";
19 import { principalOfUser } from "../src/core/principal.ts";
20 import { canAdmin, getRepo, type Repo } from "../src/core/repos.ts";
21 import { createUser, type User } from "../src/core/users.ts";
22 import { promote } from "./helpers/members.ts";
23
24 /** `may…` and `can…` names that are not a question about who may: a state, a time, a shape. */
25 const NOT_ACCESS: Readonly<Record<string, string>> = {
26 "checks/lend_pool.ts mayLend": "how much a lender offers now, by the clock",
27 "checks/lent_yield.ts mayTakeJob": "whether this machine has load to spare",
28 "crew/bets.ts mayBack": "a bet's appetite arithmetic",
29 "crew/bets.ts mayPick": "whether a bet can be picked, by its state",
30 "terminal/blocks.ts mayTakeBack": "a block's own state",
31 "machines/protocol.ts mayRole": "which message a machine role sends: protocol, not access",
32 "games/sleep.ts canSleep": "whether an image can sleep",
33 "feed/saved_filter.ts canStepBack": "whether a filter has an earlier step",
34 "billing/pay_again.ts canPayAgain": "whether a checkout can be offered again",
35 "core/error_groups.ts mayStartGroup": "a rate window on error groups",
36 "core/error_groups.ts mayFileIssue": "a rate window on error groups",
37 "actions/mail.ts mayMail": "a rate window on mail",
38 "http/contract_lazy.ts mayBeContractRoute": "whether a path could be a contract route",
39 "http/api/may.ts mayRoutes": "mounts the routes that answer `may`",
40 "actions/upstream_follow.ts mayCarryFollowCredential": "whether a URL may carry a credential: a host rule",
41 "actions/upstream_follow.ts mayCarryCredential": "whether a URL may carry a credential: a host rule",
42 "web/studio/share_receive.ts mayHold": "whether an address may be held: a shape rule",
43 "actions/order.ts mayView": "a ticket matches an order: a secret, not a role",
44 "actions/talk_act.ts mayAct": "which action a card kind offers",
45 "web/go_pages.ts mayGo": "`go` pages' own level ladder",
46 "http/addressed.ts mayShare": "whether a request is a crawler's share link",
47 "core/allocation.ts mayStart": "a budget window",
48 "apps/timer_service.ts mayCall": "a timer's path rule",
49 "apps/runtime_sleep.ts mayRun": "an app's sleep state",
50 };
51
52 /**
53 * The helpers that still decide beside `may`. Each is a pull of its own to fold; this only shrinks.
54 */
55 const STILL_TO_FOLD: readonly string[] = [
56 "actions/blocked_words.ts canAnswer",
57 "actions/crew_ceiling.ts mayRaiseCeiling",
58 "actions/destination.ts mayChangeDestination",
59 "actions/devices.ts mayManageDevices",
60 "actions/issues.ts mayEditIssue",
61 "actions/issues.ts maySetSealed",
62 "actions/planner_switch.ts maySwitch",
63 "actions/places.ts mayPin",
64 "actions/runs.ts mayReadLogOfRun",
65 "actions/runs.ts mayReadRunLog",
66 "actions/runs.ts mayReadRuns",
67 "actions/spawn.ts mayReissue",
68 "actions/statement.ts mayReadStatement",
69 "actions/verify.ts mayContribute",
70 "actions/visitor_bring.ts mayBring",
71 "apps/cloud.ts mayUse",
72 "core/fork_offer.ts mayWithdrawOffer",
73 "core/model_choice.ts mayUse",
74 "core/repos.ts canAdmin",
75 "core/repos.ts canEnterApp",
76 "core/repos.ts canRead",
77 "core/repos.ts canReadMany",
78 "core/repos.ts canSeeOwnerFacts",
79 "core/repos.ts canWrite",
80 "core/sealed.ts canSeeSealed",
81 "core/sealed.ts mayView",
82 "core/sealed.ts mayViewId",
83 "core/security_reports.ts mayReadSecurity",
84 "core/verdict.ts canVerdict",
85 "crew/direct.ts mayDirectCrew",
86 "crew/sentinel_close.ts mayClose",
87 "crew/snap.ts maySend",
88 "data/sources.ts maySeeData",
89 "flows/start.ts mayStartRadar",
90 "games/store.ts mayDo",
91 "http/mcp/tool_may.ts mayToolWrite",
92 "http/repo_may.ts mayRepo",
93 "http/api/conversation_talk.ts mayChange",
94 "http/route_marks.ts isAdminRoute",
95 "http/admin_gate.ts isAdminPath",
96 "looks/readable.ts mayFetchLook",
97 "machines/shell.ts mayOpenShell",
98 "origins/guest.ts mayApproveGuest",
99 "origins/trusted-hosts.ts mayEditTrustedHosts",
100 "release/gate.ts canRollBackTo",
101 "release/gate.ts mayRead",
102 "release/gate.ts mayReadKeeper",
103 "release/gate.ts mayRollBack",
104 "security/accept.ts mayAct",
105 "security/optin.ts mayAsk",
106 "tui/screens/accountorder.ts mayOrder",
107 "tui/screens/atlas.ts mayPlan",
108 "tui/screens/builds.ts mayPin",
109 "tui/screens/can.ts canScreen",
110 "tui/screens/crewdevices.ts mayManageDevices",
111 "tui/screens/crewswitch.ts maySwitchCrew",
112 "tui/screens/dataimport.ts mayImport",
113 "tui/screens/fleet.ts mayAct",
114 "tui/screens/prompts.ts mayManagePrompts",
115 "tui/screens/quarantine.ts mayReview",
116 "tui/screens/readgrants.ts mayGrantRead",
117 "tui/screens/returns.ts mayReadReturns",
118 "tui/screens/runlist.ts maySteer",
119 "web/pages/fleet.ts canAct",
120 "web/pages/growth_panel.ts isAdmin",
121 "web/pages/looks.ts mayFetchLook",
122 "web/studio/alarm_lines.ts mayMergeOwn",
123 "web/studio/answers.ts canSeeAnswers",
124 "web/studio/review_start.ts mayRetryReview",
125 "games/game_may.ts mayOnGame",
126 ];
127
128 const NAME = /^export (?:async )?(?:function|const) ((?:may|can)[A-Z]\w*|isAdmin\w*)\b/gm;
129
130 /** Every exported `may…`, `can…` or `isAdmin…` under src/, as `path name`, but `may` itself. */
131 async function found(): Promise<string[]> {
132 const out: string[] = [];
133 for await (const file of new Glob("**/*.ts").scan({ cwd: join(import.meta.dir, "../src") })) {
134 const text = await Bun.file(join(import.meta.dir, "../src", file)).text();
135 for (const m of text.matchAll(NAME)) out.push(`${file} ${m[1]}`);
136 }
137 return out.sort();
138 }
139
140 test("no exported permission helper stands beside may() but those still to fold", async () => {
141 const all = await found();
142 const fresh = all.filter((h) => !(h in NOT_ACCESS) && !STILL_TO_FOLD.includes(h));
143 expect(fresh, `Ask may() (src/core/may.ts) instead of a helper of your own; or, if it is not about who may, say so in NOT_ACCESS: ${fresh.join(", ")}`).toEqual([]);
144 });
145
146 test("a helper that is folded leaves the list: STILL_TO_FOLD only shrinks", async () => {
147 const all = await found();
148 const gone = [...STILL_TO_FOLD, ...Object.keys(NOT_ACCESS)].filter((h) => !all.includes(h));
149 expect(gone, `Deleted, so take them off the list: ${gone.join(", ")}`).toEqual([]);
150 });
151
152 test("the folded admin-only helpers are gone and none came back under another name", async () => {
153 const text = (await found()).join("\n");
154 for (const name of "mayReadApple mayReadAtlas mayHandleDisks mayQueryMetric mayManageFlags mayReadRefusals canSeeMemory mayReadNow mayEditTheme mayCurate mayBoards mayRunners mayTrust mayFeatures mayDrift mayExplore mayCapacity mayCutOver mayMarkTemplate mayManageWallet maySeeHistory mayClearCache mayManageOutside mayReadCrewTop".split(" "))
155 expect(text).not.toContain(` ${name}`);
156 });
157
158 let dataDir = "";
159 let app: App;
160 let repo: Repo;
161 const users: Record<string, User> = {};
162
163 beforeAll(async () => {
164 dataDir = await mkdtemp(join(tmpdir(), "forge-may-only-"));
165 app = createApp({ dataDir, port: 0 });
166 for (const [name, first] of [["boss", true], ["nina", false]] as const) {
167 const made = await createUser(app.db, { origin: "seed", trusted: true, username: name, email: `${name}@forge.local`, password: "a-good-passphrase", adminIfFirst: first });
168 if (!made.ok) throw new Error(String(made.error));
169 users[name] = made.value;
170 }
171 promote(app.db, users["boss"]!, users["nina"]!);
172 const made = await createRepo(app, users["nina"]!, { owner: "nina", name: "own", visibility: "private" });
173 if (!made.ok) throw new Error(String(made.error));
174 repo = getRepo(app.db, "nina", "own")!;
175 });
176 afterAll(async () => rm(dataDir, { recursive: true, force: true }));
177
178 test("forge.administer_person answers what the admin-only helpers did: an admin who is not an agent", () => {
179 const ada = (isAdmin: boolean, kind: User["kind"]): User => ({ ...users["boss"]!, isAdmin, kind });
180 const old = (u: User | undefined): boolean => u !== undefined && u.isAdmin && u.kind !== "agent";
181 for (const u of [ada(true, "user"), ada(true, "agent"), ada(false, "user"), ada(false, "agent"), undefined])
182 expect(holds(app.db, principalOfUser(u), "forge.administer_person"), JSON.stringify(u && [u.isAdmin, u.kind])).toBe(old(u));
183 });
184
185 test("repo.admin answers what the terminal's repository gates did: canAdmin, signed in", () => {
186 for (const u of [users["boss"], users["nina"], undefined])
187 expect(holds(app.db, principalOfUser(u), "repo.admin", { repo })).toBe(u !== undefined && canAdmin(app.db, repo, u));
188 });
189
190 test("forge.administer answers what the crew's top gate did: an admin, agent or not", () => {
191 const ada = (isAdmin: boolean, kind: User["kind"]): User => ({ ...users["boss"]!, isAdmin, kind });
192 for (const u of [ada(true, "user"), ada(true, "agent"), ada(false, "user"), undefined])
193 expect(holds(app.db, principalOfUser(u), "forge.administer")).toBe(u?.isAdmin === true);
194 });
195
196 test("an org-kind admin holds forge.administer_person, which mayRunners once refused; an org cannot sign in, so no session carries one", () => {
197 const org: User = { ...users["boss"]!, isAdmin: true, kind: "org" };
198 expect(holds(app.db, principalOfUser(org), "forge.administer_person")).toBe(true);
199 expect(holds(app.db, principalOfUser({ ...org, kind: "agent" }), "forge.administer_person")).toBe(false);
200 });
test/mcp-tools-may.test.ts +1 −1
@@ -116,6 +116,6 @@ test("the gate holds the MCP door's files: an inline isAdmin or rw scope check i
116116 await writeFile(join(root, "src/http/mcp.ts"), 'if (!user.isAdmin) return x;\nif (!scopeAllows(s, "rw")) return y;\nif (!scopeAllows(s, "admin")) return z;\n');
117117 await writeFile(join(root, "src/http/mcp/shared.ts"), "export const mayBoards = (user: User): boolean => user.isAdmin;\n");
118118 const found = mcpDoorRefusalAt(root);
119 expect(found.map((f) => f.split(": ")[0])).toEqual(["src/http/mcp.ts:1", "src/http/mcp.ts:2"]);
119 expect(found.map((f) => f.split(": ")[0])).toEqual(["src/http/mcp.ts:1", "src/http/mcp.ts:2", "src/http/mcp/shared.ts:1"]);
120120 await rm(root, { recursive: true, force: true });
121121 });

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

Keyboard shortcuts

Docs