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

may() is the only permission check: every helper in STILL_TO_FOLD is deleted #18631

opened this

The crew's run on it is queued

mason/forge:mason/18605-may-is-the-only-permission-check-every-h → main 2 commits fork

  • Ready to merge — no conflicts with main. 2 commits will land on main.

    Check queued 1m, place 6 of 6Check of b468ab5fast tier: queued · full gate runs on land

    You need write access to merge.

Review

Sign in to review this change.
18 files changed +114 −113
src/actions/crew_ceiling.ts −5
@@ -20,11 +20,6 @@ export function applyStoredCeiling(app: App): void {
2020 holdRaisedCeiling(app.config, typeof stored === "number" && stored > 0 && stored <= MAX_CEILING ? stored : null);
2121 }
2222
23 /** Whether `actor` may raise the ceiling: a forge admin, and a cap is set. */
24 export function mayRaiseCeiling(app: App, actor: User | undefined): boolean {
25 return actor?.isAdmin === true && forgeCeiling(app.config) !== null;
26 }
27
2823 /**
2924 * Raise to `to`, the figure the caller showed. Refused unless it is what one Raise from the
3025 * current cap gives, so a repeated or stale Raise does not compound.
src/actions/planner_switch.ts +6 −9
@@ -4,9 +4,11 @@
44 * rule (what a pause stops) lives in `core/planner_pause.ts`.
55 */
66
7 import { holds } from "../core/may.ts";
8 import { principalOfUser } from "../core/principal.ts";
79 import { forgetGrowthPanel } from "../core/growth_panel.ts";
810 import type { App } from "../app.ts";
9 import { canAdmin, type Repo } from "../core/repos.ts";
11 import type { Repo } from "../core/repos.ts";
1012 import type { User } from "../core/users.ts";
1113 import { err, ok, type Result } from "../kernel/result.ts";
1214 import { FOREVER, liftCeilingOnce, nextWeek, pauseForChapter, parseCeiling, pausePlanner, pausedUntil, resumePlanner, setOpenCeiling } from "../core/planner_pause.ts";
@@ -30,11 +32,6 @@ export const SWITCH_REFUSED: Record<SwitchError, string> = {
3032 no_chapter: "There is no open chapter to wait for.",
3133 };
3234
33 /** A person who administers the repository may switch the planner; an agent never. */
34 export function maySwitch(app: App, actor: User | undefined, repo: Repo): boolean {
35 return actor !== undefined && actor.kind !== "agent" && canAdmin(app.db, repo, actor);
36 }
37
3835 /** Whether `at` (UTC) is a time in the future within a year. */
3936 export function validUntil(at: string, now = new Date()): boolean {
4037 const t = Date.parse(at);
@@ -50,7 +47,7 @@ export function setPlannerSwitch(
5047 now = new Date(),
5148 ): Result<string | null, SwitchError> {
5249 if (actor === undefined) return err("not_found");
53 if (!maySwitch(app, actor, repo)) return err("forbidden");
50 if (!holds(app.db, principalOfUser(actor), "repo.admin_person", { repo })) return err("forbidden");
5451 if (input.mode === "on") resumePlanner(app.db, repo.id);
5552 else if (input.mode === "chapter") {
5653 if (!pauseForChapter(app.db, repo.id, actor.id)) return err("no_chapter");
@@ -104,7 +101,7 @@ export function setCeiling(
104101 input: { readonly mode: "set"; readonly value: string } | { readonly mode: "resume" },
105102 ): Result<number, SwitchError> {
106103 if (actor === undefined) return err("not_found");
107 if (actor.kind === "agent" || !canAdmin(app.db, repo, actor)) return err("forbidden");
104 if (!holds(app.db, principalOfUser(actor), "repo.admin_person", { repo })) return err("forbidden");
108105 let value: number;
109106 if (input.mode === "resume") value = liftCeilingOnce(app.db, repo.id, actor.id);
110107 else {
@@ -123,7 +120,7 @@ export function setCeiling(
123120 */
124121 export function setPullsCeiling(app: App, actor: User | undefined, repo: Repo, raw: string): Result<number, SwitchError> {
125122 if (actor === undefined) return err("not_found");
126 if (actor.kind === "agent" || !canAdmin(app.db, repo, actor)) return err("forbidden");
123 if (!holds(app.db, principalOfUser(actor), "repo.admin_person", { repo })) return err("forbidden");
127124 const n = parsePullsCeiling(raw);
128125 if (n === undefined) return err("invalid");
129126 setOpenPullsCeiling(app.db, repo.id, n, actor.id);
src/core/may.ts +4
@@ -59,6 +59,8 @@ export const ACTIONS = {
5959 "repo.read": { says: "Read a repository: its code, issues and pulls", over: "repo", scope: "ro" },
6060 "repo.write": { says: "Change a repository: push, merge, label, close", over: "repo", scope: "rw" },
6161 "repo.admin": { says: "Administer a repository: its settings, webhooks, protection and deletion", over: "repo", scope: "rw" },
62 "repo.write_person": { says: "Change a repository as a person: one who writes to it, never a crew member", over: "repo", scope: "rw" },
63 "repo.admin_person": { says: "Administer a repository as a person: one who administers it, never a crew member", over: "repo", scope: "rw" },
6264 "forge.read": forgeAction("read"),
6365 "forge.write": { says: "Change something as your account: any write, by a session or a token of scope rw", over: "forge", scope: "rw" },
6466 "forge.comment": forgeAction("comment"),
@@ -116,6 +118,8 @@ const ABILITY_OF: Readonly<Partial<Record<Action, Ability>>> = {
116118 function repoRuleHolds(db: Database, action: Action, repo: Repo, user: User | undefined): boolean {
117119 if (action === "repo.read") return readsRepo(db, repo, user);
118120 if (action === "repo.write") return writesRepo(db, repo, user);
121 if (action === "repo.write_person") return user?.kind !== "agent" && writesRepo(db, repo, user);
122 if (action === "repo.admin_person") return user?.kind !== "agent" && adminsRepo(db, repo, user);
119123 return adminsRepo(db, repo, user);
120124 }
121125
src/http/mcp/tools/system.ts +5 −3
@@ -1,4 +1,6 @@
11 import { noteRead, telemetryReader } from "../../../actions/telemetry.ts";
2 import { holds } from "../../../core/may.ts";
3 import { principalOfUser } from "../../../core/principal.ts";
24 import { badBlocked } from "../shared.ts";
35 import { noTelemetryBlocked } from "../../../actions/blocked_words.ts";
46 import { systemWithReaders } from "../../../system/telemetry.ts";
@@ -22,7 +24,7 @@ import { largestDirs } from "../../../system/largest_dirs.ts";
2224 import { dbSize } from "../../../system/db_size.ts";
2325 import { resultWords, weekRows } from "../../../maintain/week_line.ts";
2426 import { duties } from "../../../maintain/registry.ts";
25 import { maySwitch, setPlannerSwitch, setPullsCeiling, SWITCH_REFUSED, utcAt, validUntil, type SwitchInput } from "../../../actions/planner_switch.ts";
27 import { setPlannerSwitch, setPullsCeiling, SWITCH_REFUSED, utcAt, validUntil, type SwitchInput } from "../../../actions/planner_switch.ts";
2628 import { pauseSentence, pausedUntil } from "../../../core/planner_pause.ts";
2729 import { openPullsCeiling, parsePullsCeiling, pullsCeilingHold } from "../../../core/pulls_ceiling.ts";
2830 import { growthCounts } from "../../../core/growth.ts";
@@ -67,7 +69,7 @@ export const tool: Tool = {
6769 const n = args["pulls"];
6870 if (typeof n !== "number" || !Number.isInteger(n)) return bad("invalid", "pulls is a whole number, 0 for off");
6971 if (args["confirm"] !== undefined && typeof args["confirm"] !== "boolean") return bad("invalid", "confirm is true or false");
70 if (!maySwitch(ctx.app, user, repo)) return bad("forbidden", SWITCH_REFUSED.forbidden);
72 if (!holds(ctx.app.db, principalOfUser(user), "repo.admin_person", { repo })) return bad("forbidden", SWITCH_REFUSED.forbidden);
7173 if (parsePullsCeiling(String(n)) === undefined) return bad("invalid", "pulls is a whole number from 0 to 100000");
7274 if (args["confirm"] !== true)
7375 return good({ done: false, says: `The open-pull ceiling would be ${n === 0 ? "off" : n} (now ${openPullsCeiling(ctx.app.db, repo.id) || "off"}). Nothing changed; call again with confirm:true to do it.` });
@@ -80,7 +82,7 @@ export const tool: Tool = {
8082 if (args["chapter"] !== undefined && (args["chapter"] !== true || a === "resume" || args["until"] !== undefined)) return bad("invalid", "chapter is true, for pause without until");
8183 if (args["confirm"] !== undefined && typeof args["confirm"] !== "boolean") return bad("invalid", "confirm is true or false");
8284 if (args["until"] !== undefined && (typeof args["until"] !== "string" || a === "resume")) return bad("invalid", "until is a UTC time, for pause");
83 if (!maySwitch(ctx.app, user, repo)) return bad("forbidden", SWITCH_REFUSED.forbidden);
85 if (!holds(ctx.app.db, principalOfUser(user), "repo.admin_person", { repo })) return bad("forbidden", SWITCH_REFUSED.forbidden);
8486 const input: SwitchInput =
8587 a === "resume" ? { mode: "on" } : args["chapter"] === true ? { mode: "chapter" } : typeof args["until"] === "string" ? { mode: "until", at: utcAt(args["until"]) } : { mode: "owner" };
8688 if (input.mode === "until" && !validUntil(input.at)) return bad("invalid", SWITCH_REFUSED.invalid);
src/tui/screens/accountorder.ts +6 −7
@@ -6,8 +6,10 @@
66 * a write made there.
77 */
88
9 import { holds } from "../../core/may.ts";
10 import { principalOfUser } from "../../core/principal.ts";
911 import { ORDER_WORDS, parseOrder, repoOrderNames, setRepoOrder } from "../../actions/repo_account_order.ts";
10 import { canWrite, type Repo } from "../../core/repos.ts";
12 import type { Repo } from "../../core/repos.ts";
1113 import type { Ctx, Screen } from "../app/app.ts";
1214 import { binding } from "../app/keys.ts";
1315 import type { Command } from "../app/palette.ts";
@@ -17,9 +19,6 @@ import { truncate } from "../term/width.ts";
1719 import { fill, len, split } from "../ui/layout.ts";
1820 import { ListState, drawList, later, live, promptScreen, type ListRow } from "./common.ts";
1921
20 /** Who sets the order: a person who can write to the repository. */
21 export const mayOrder = (f: Session, repo: Repo): boolean => f.user !== undefined && f.user.kind !== "agent" && canWrite(f.db, repo, f.user);
22
2322 /** Say what a save did, as a toast would. */
2423 export function saveOrder(f: Session, repo: Repo, names: readonly string[]): { text: string; bad: boolean } {
2524 const set = setRepoOrder(f.app, f.user, repo, names);
@@ -39,7 +38,7 @@ export function accountOrderScreen(f: Session, ctx: Ctx, repo: Repo): Screen {
3938 const c = ctx.theme.c;
4039 const names = repoOrderNames(f.app, repo);
4140 const [head, list] = split(area, "v", [len(1), fill(1)]);
42 const said = !mayOrder(f, repo)
41 const said = !holds(f.db, principalOfUser(f.user), "repo.write_person", { repo })
4342 ? "A writer of this repository sets its account order."
4443 : names.length === 0
4544 ? "The forge's order. e names accounts to try first here."
@@ -51,7 +50,7 @@ export function accountOrderScreen(f: Session, ctx: Ctx, repo: Repo): Screen {
5150 key(e) {
5251 if (state.key(e, repoOrderNames(f.app, repo).length)) return true;
5352 if (e.ctrl || e.alt || (e.key !== "e" && e.key !== "c")) return false;
54 if (!mayOrder(f, repo)) {
53 if (!holds(f.db, principalOfUser(f.user), "repo.write_person", { repo })) {
5554 ctx.toast("A writer of this repository sets its account order.", "danger");
5655 return true;
5756 }
@@ -86,7 +85,7 @@ export function accountOrderScreen(f: Session, ctx: Ctx, repo: Repo): Screen {
8685
8786 /** The palette's command while a repository the viewer can write to is open. */
8887 export function accountOrderCommands(f: Session, ctx: Ctx, repo: Repo | undefined): Command[] {
89 if (repo === undefined || !mayOrder(f, repo)) return [];
88 if (repo === undefined || !holds(f.db, principalOfUser(f.user), "repo.write_person", { repo })) return [];
9089 return [
9190 {
9291 id: "account-order",
src/tui/screens/atlas.ts +10 −9
@@ -7,6 +7,8 @@
77 * viewers live are one code path. Offered to whoever may plan here.
88 */
99
10 import { holds } from "../../core/may.ts";
11 import { principalOfUser } from "../../core/principal.ts";
1012 import {
1113 ATLAS_BODY_MAX,
1214 businessItems,
@@ -18,7 +20,7 @@ import {
1820 } from "../../actions/business_plan.ts";
1921 import type { PlanItem } from "../../actions/plan.ts";
2022 import { isCrew } from "../../core/agents.ts";
21 import { canRead, canWrite, type Repo } from "../../core/repos.ts";
23 import type { Repo } from "../../core/repos.ts";
2224 import type { Ctx, Screen } from "../app/app.ts";
2325 import { binding } from "../app/keys.ts";
2426 import type { Command } from "../app/palette.ts";
@@ -29,12 +31,11 @@ import { fill, len, split } from "../ui/layout.ts";
2931 import { Textarea } from "../ui/textarea.ts";
3032 import { card } from "../ui/widgets.ts";
3133
32 /** Who may plan here: as the API's confirm decides it. */
33 export function mayPlan(f: Session, repo: Repo): boolean {
34 const u = f.user;
35 if (u === undefined || !canRead(f.db, repo, u)) return false;
36 return canWrite(f.db, repo, u) || isCrew(f.db, repo.id, u.id);
37 }
34 /** Who may plan here, as the API's confirm decides it: a reader who writes, or sits on the crew. */
35 const plans = (f: Session, repo: Repo): boolean => {
36 const p = principalOfUser(f.user);
37 return holds(f.db, p, "repo.read", { repo }) && (holds(f.db, p, "repo.write", { repo }) || (f.user !== undefined && isCrew(f.db, repo.id, f.user.id)));
38 };
3839
3940 export type AtlasStep =
4041 | { readonly kind: "error"; readonly message: string }
@@ -46,7 +47,7 @@ export type AtlasStep =
4647 * or, when it is the plan just previewed (`previewed` is its stamp), confirmed.
4748 */
4849 export function atlasStep(f: Session, repo: Repo, text: string, previewed?: string): AtlasStep {
49 if (!mayPlan(f, repo)) return { kind: "error", message: "you need write access to plan here" };
50 if (!plans(f, repo)) return { kind: "error", message: "you need write access to plan here" };
5051 if (new TextEncoder().encode(text).length > ATLAS_BODY_MAX)
5152 return { kind: "error", message: `a plan is at most ${ATLAS_BODY_MAX} bytes` };
5253 let input: unknown;
@@ -155,7 +156,7 @@ export function atlasScreen(f: Session, ctx: Ctx, repo: Repo): Screen {
155156
156157 /** The per-repository command: offered to whoever may plan here. */
157158 export function atlasCommands(f: Session, ctx: Ctx, repo: Repo | undefined): Command[] {
158 if (repo === undefined || !mayPlan(f, repo)) return [];
159 if (repo === undefined || !plans(f, repo)) return [];
159160 return [
160161 {
161162 id: "atlas-plan",
src/tui/screens/autonomy.ts +7 −4
@@ -14,8 +14,11 @@
1414 * Anyone else gets no palette entry and, if the screen is reached, no values.
1515 */
1616
17 import { holds } from "../../core/may.ts";
18 import { principalOfUser } from "../../core/principal.ts";
19 import { forgeCeiling } from "../../flow/ceiling.ts";
1720 import { movedKey } from "./moved_key.ts";
18 import { mayRaiseCeiling, raiseCrewCeiling } from "../../actions/crew_ceiling.ts";
21 import { raiseCrewCeiling } from "../../actions/crew_ceiling.ts";
1922 import { checkPool, setCheckSlots } from "../../actions/check_slots.ts";
2023 import { pullChecksOf } from "../../checks/check_slots.ts";
2124 import { updateRepoSettings } from "../../actions/repos.ts";
@@ -80,7 +83,7 @@ export function autonomyCommands(f: Session, ctx: Ctx, repo: Repo | undefined):
8083 /** The header's crew line, as the web prints it, with its fix. */
8184 function stopLineOf(f: Session, r: Repo): string {
8285 const w = stopWords(autonomyStatus(f.app, r));
83 if (w.raiseTo !== undefined && mayRaiseCeiling(f.app, f.user)) return `${w.words} Raise to $${w.raiseTo} (c).`;
86 if (w.raiseTo !== undefined && (holds(f.app.db, principalOfUser(f.user), "forge.administer") && forgeCeiling(f.app.config) !== null)) return `${w.words} Raise to $${w.raiseTo} (c).`;
8487 return w.fix === null ? w.words : `${w.words} ${w.fix} (m).`;
8588 }
8689
@@ -128,7 +131,7 @@ export function autonomyScreen(f: Session, ctx: Ctx, repo: Repo): Screen {
128131 title: "Autonomy",
129132 get keys() {
130133 return mayChange()
131 ? [binding(["m"], "mode"), binding(["p"], "planner"), binding(["s"], "builder"), binding(["r"], "reviewer"), binding(["o"], "polish share"), binding(["C"], "check slots"), ...(mayRaiseCeiling(f.app, f.user) ? [binding(["c"], "raise ceiling")] : [])]
134 ? [binding(["m"], "mode"), binding(["p"], "planner"), binding(["s"], "builder"), binding(["r"], "reviewer"), binding(["o"], "polish share"), binding(["C"], "check slots"), ...((holds(f.app.db, principalOfUser(f.user), "forge.administer") && forgeCeiling(f.app.config) !== null) ? [binding(["c"], "raise ceiling")] : [])]
132135 : [];
133136 },
134137 render(area, s) {
@@ -194,7 +197,7 @@ export function autonomyScreen(f: Session, ctx: Ctx, repo: Repo): Screen {
194197 });
195198 return true;
196199 }
197 if (e.key === "c" && mayRaiseCeiling(f.app, f.user)) {
200 if (e.key === "c" && (holds(f.app.db, principalOfUser(f.user), "forge.administer") && forgeCeiling(f.app.config) !== null)) {
198201 const to = stopWords(autonomyStatus(f.app, current())).raiseTo;
199202 if (to === undefined) {
200203 ctx.toast("The crew is not paused at the forge's ceiling.", "danger");
src/tui/screens/crewswitch.ts +5 −7
@@ -5,9 +5,11 @@
55 * open settings page redraws, and this screen follows a change made there.
66 */
77
8 import { holds } from "../../core/may.ts";
9 import { principalOfUser } from "../../core/principal.ts";
810 import { crewHereSaid, setCrewHere } from "../../actions/crew_switch.ts";
911 import { CREW_OFF_LINE, crewBuildsHere } from "../../core/crew_switch.ts";
10 import { canAdmin, type Repo } from "../../core/repos.ts";
12 import type { Repo } from "../../core/repos.ts";
1113 import type { Ctx, Screen } from "../app/app.ts";
1214 import { binding } from "../app/keys.ts";
1315 import type { Command } from "../app/palette.ts";
@@ -17,13 +19,9 @@ import { drawLines, live, Scroll } from "./common.ts";
1719
1820 const NOT_YOURS = "An admin of this repository switches its crew.";
1921
20 /** The settings page's gate: an admin of the repository, never an agent. */
21 export const maySwitchCrew = (f: Session, repo: Repo): boolean =>
22 f.user !== undefined && f.user.kind !== "agent" && canAdmin(f.db, repo, f.user);
23
2422 /** What the screen says: the switch's state, and the key that flips it for whoever may. */
2523 export function crewSwitchLines(f: Session, repo: Repo): string[] {
26 if (!maySwitchCrew(f, repo)) return [NOT_YOURS];
24 if (!holds(f.db, principalOfUser(f.user), "repo.admin_person", { repo })) return [NOT_YOURS];
2725 return crewBuildsHere(f.db, repo.id)
2826 ? ["Crew builds here: on. Its builders and planner pick its ready issues.", "Space turns it off."]
2927 : [CREW_OFF_LINE, "Space turns it on."];
@@ -56,7 +54,7 @@ export function crewSwitchScreen(f: Session, ctx: Ctx, repo: Repo): Screen {
5654
5755 /** The palette's command while a repository the viewer administers is open. */
5856 export function crewSwitchCommands(f: Session, ctx: Ctx, repo: Repo | undefined): Command[] {
59 if (repo === undefined || !maySwitchCrew(f, repo)) return [];
57 if (repo === undefined || !holds(f.db, principalOfUser(f.user), "repo.admin_person", { repo })) return [];
6058 return [
6159 {
6260 id: "crew-builds-here",
src/tui/screens/dataimport.ts +7 −15
@@ -9,12 +9,14 @@
99 * dump's rows and checksum, the store's, and whether they match.
1010 */
1111
12 import { holds } from "../../core/may.ts";
13 import { principalOfUser } from "../../core/principal.ts";
1214 import { importAppData, importDataMessage } from "../../actions/migrate.ts";
1315 import { envDataDir } from "../../apps/data.ts";
1416 import { DUMP_FILE_WORDS, readStagedDump } from "../../apps/dump_file.ts";
1517 import type { ImportReport } from "../../apps/dump_import.ts";
1618 import { getAppByRepo } from "../../core/apps.ts";
17 import { canAdmin, type Repo } from "../../core/repos.ts";
19 import type { Repo } from "../../core/repos.ts";
1820 import type { Ctx, Screen } from "../app/app.ts";
1921 import { binding } from "../app/keys.ts";
2022 import type { Command } from "../app/palette.ts";
@@ -24,16 +26,6 @@ import { truncate } from "../term/width.ts";
2426 import { fill, len, split } from "../ui/layout.ts";
2527 import { ListState, drawList, promptScreen, type ListRow } from "./common.ts";
2628
27 /** Whether this viewer may import: the repository's admin, and it is an app. */
28 export function mayImport(f: Session, repo: Repo | undefined): repo is Repo {
29 return (
30 repo !== undefined &&
31 f.user !== undefined &&
32 getAppByRepo(f.app.db, repo.id) !== undefined &&
33 canAdmin(f.app.db, repo, f.user)
34 );
35 }
36
3729 /** What an import's report says, a row per table. */
3830 export function reportRows(report: ImportReport): ListRow[] {
3931 return report.tables.map((t) => ({
@@ -52,7 +44,7 @@ export function importStaged(
5244 replace: boolean,
5345 ): { ok: true; report: ImportReport } | { ok: false; words: string } {
5446 const record = getAppByRepo(f.app.db, repo.id);
55 if (record === undefined || !canAdmin(f.app.db, repo, f.user)) return { ok: false, words: "No such repository, or you are not its admin." };
47 if (record === undefined || f.user === undefined || !holds(f.app.db, principalOfUser(f.user), "repo.admin", { repo })) return { ok: false, words: "No such repository, or you are not its admin." };
5648 const read = readStagedDump(envDataDir(f.app.config.dataDir, record.id, "production"), name);
5749 if (!read.ok) return { ok: false, words: DUMP_FILE_WORDS[read.error] };
5850 const done = importAppData(f.app, f.user, repo, { dump: read.sql, replace });
@@ -84,13 +76,13 @@ export function dataImportScreen(f: Session, ctx: Ctx, repo: Repo): Screen {
8476 render(area, s) {
8577 const c = ctx.theme.c;
8678 const [head, list] = split(area, "v", [len(1), fill(1)]);
87 s.text(head!.x, head!.y, truncate(mayImport(f, repo) ? note : "Only the app's admin imports a database.", head!.w), style(c.mutedFg, c.bg), head!.x + head!.w);
79 s.text(head!.x, head!.y, truncate((repo !== undefined && getAppByRepo(f.app.db, repo.id) !== undefined && holds(f.app.db, principalOfUser(f.user), "repo.admin", { repo })) ? note : "Only the app's admin imports a database.", head!.w), style(c.mutedFg, c.bg), head!.x + head!.w);
8880 drawList(s, list!, c, state, rows);
8981 },
9082 key(e) {
9183 if (state.key(e, rows.length)) return true;
9284 if (e.ctrl || e.alt || !["i", "r"].includes(e.key)) return false;
93 if (!mayImport(f, repo)) {
85 if (!(repo !== undefined && getAppByRepo(f.app.db, repo.id) !== undefined && holds(f.app.db, principalOfUser(f.user), "repo.admin", { repo }))) {
9486 ctx.toast("Only the app's admin imports a database.", "danger");
9587 return true;
9688 }
@@ -103,7 +95,7 @@ export function dataImportScreen(f: Session, ctx: Ctx, repo: Repo): Screen {
10395
10496 /** The palette's command: an admin of a repository that is an app. */
10597 export function dataImportCommands(f: Session, ctx: Ctx, repo: Repo | undefined): Command[] {
106 if (!mayImport(f, repo)) return [];
98 if (!(repo !== undefined && getAppByRepo(f.app.db, repo.id) !== undefined && holds(f.app.db, principalOfUser(f.user), "repo.admin", { repo }))) return [];
10799 return [
108100 {
109101 id: "data-import",
src/tui/screens/datamove.ts +7 −5
@@ -8,9 +8,11 @@
88 * store; the result line says whether it was.
99 */
1010
11 import { holds } from "../../core/may.ts";
12 import { principalOfUser } from "../../core/principal.ts";
1113 import { afterMoveWords, dataMoveState, moveData, moveMessage, undoMove, type MoveReceipt } from "../../actions/migrate_data.ts";
1214 import { lostKeys, skippedWords } from "../../apps/pg_dump.ts";
13 import { canAdmin, type Repo } from "../../core/repos.ts";
15 import type { Repo } from "../../core/repos.ts";
1416 import type { Ctx, Screen } from "../app/app.ts";
1517 import { binding } from "../app/keys.ts";
1618 import type { Command } from "../app/palette.ts";
@@ -19,7 +21,7 @@ import { style } from "../term/style.ts";
1921 import { truncate } from "../term/width.ts";
2022 import { fill, len, split } from "../ui/layout.ts";
2123 import { ListState, confirmScreen, drawList, promptScreen, type ListRow } from "./common.ts";
22 import { mayImport } from "./dataimport.ts";
24 import { getAppByRepo } from "../../core/apps.ts";
2325
2426 /** A move's receipt, a row per table. */
2527 export function moveRows(receipt: MoveReceipt): ListRow[] {
@@ -83,13 +85,13 @@ export function dataMoveScreen(f: Session, ctx: Ctx, repo: Repo): Screen {
8385 render(area, s) {
8486 const c = ctx.theme.c;
8587 const [head, list] = split(area, "v", [len(1), fill(1)]);
86 s.text(head!.x, head!.y, truncate(mayImport(f, repo) ? note : "Only the app's admin moves the data.", head!.w), style(c.mutedFg, c.bg), head!.x + head!.w);
88 s.text(head!.x, head!.y, truncate((repo !== undefined && getAppByRepo(f.app.db, repo.id) !== undefined && holds(f.app.db, principalOfUser(f.user), "repo.admin", { repo })) ? note : "Only the app's admin moves the data.", head!.w), style(c.mutedFg, c.bg), head!.x + head!.w);
8789 drawList(s, list!, c, state, rows);
8890 },
8991 key(e) {
9092 if (state.key(e, rows.length)) return true;
9193 if (e.ctrl || e.alt || !["m", "a", "u"].includes(e.key)) return false;
92 if (!mayImport(f, repo)) {
94 if (!(repo !== undefined && getAppByRepo(f.app.db, repo.id) !== undefined && holds(f.app.db, principalOfUser(f.user), "repo.admin", { repo }))) {
9395 ctx.toast("Only the app's admin moves the data.", "danger");
9496 return true;
9597 }
@@ -108,7 +110,7 @@ export function dataMoveScreen(f: Session, ctx: Ctx, repo: Repo): Screen {
108110
109111 /** The palette's command: an admin of a repository that is an app. */
110112 export function dataMoveCommands(f: Session, ctx: Ctx, repo: Repo | undefined): Command[] {
111 if (!mayImport(f, repo) || f.user === undefined || !canAdmin(f.app.db, repo, f.user)) return [];
113 if (!(repo !== undefined && getAppByRepo(f.app.db, repo.id) !== undefined && holds(f.app.db, principalOfUser(f.user), "repo.admin", { repo }))) return [];
112114 return [
113115 {
114116 id: "data-move",
src/tui/screens/pull.ts +4 −2
@@ -26,11 +26,13 @@
2626 * `n`/`p` walk the unsettled ones while the cursor is inside a thread.
2727 */
2828
29 import { holds } from "../../core/may.ts";
30 import { principalOfUser } from "../../core/principal.ts";
2931 import { OFFER_PULL_WORDS, offerPull, previewOfferPull } from "../../actions/offer_pull.ts";
3032 import { keyOf } from "../../web/keymap.ts";
3133 import { offerStatusLinkFor } from "../../core/outsider_status.ts";
3234 import { outsideClause } from "../../web/outside.ts";
33 import { mayRetryReview, RETRY_WORDS, reviewFailedToStart } from "../../web/studio/review_start.ts";
35 import { RETRY_WORDS, reviewFailedToStart } from "../../web/studio/review_start.ts";
3436 import { retryFailedStart } from "../../crew/review.ts";
3537 import { teamHoldRefusal, waitingOnTeams } from "../../core/teams_words.ts";
3638 import { crewFilters, guardedRefusal, isStrangerPull, strangerGuard, strangerNext } from "../../crew/stranger.ts";
@@ -385,7 +387,7 @@ export function pullScreen(
385387 /** This open agent pull's review failed to start twice (#16178); `F` sends it again. */
386388 let reviewFailed = false;
387389 /** `F` is the page's "Re-run review", gated as the page gates it (`mayRetryReview`). */
388 const mayRerunReview = (): boolean => reviewFailed && repo !== undefined && mayRetryReview(f.db, repo, f.user);
390 const mayRerunReview = (): boolean => reviewFailed && repo !== undefined && holds(f.db, principalOfUser(f.user), "repo.write_person", { repo });
389391 /** A writer, on a pull that is one of several variants. */
390392 const mayVote = (): boolean =>
391393 mayWrite() &&
src/tui/screens/readgrants.ts +7 −9
@@ -6,8 +6,10 @@
66 * read.
77 */
88
9 import { holds } from "../../core/may.ts";
10 import { principalOfUser } from "../../core/principal.ts";
911 import { GRANT_ERRORS, grantRead, isReadOnlyMirror, listGrants, revokeRead } from "../../actions/origin_read_grant.ts";
10 import { canAdmin, type Repo } from "../../core/repos.ts";
12 import type { Repo } from "../../core/repos.ts";
1113 import type { Ctx, Screen } from "../app/app.ts";
1214 import { binding } from "../app/keys.ts";
1315 import type { Command } from "../app/palette.ts";
@@ -17,21 +19,17 @@ import { truncate } from "../term/width.ts";
1719 import { fill, len, split } from "../ui/layout.ts";
1820 import { ListState, confirmScreen, drawList, later, promptScreen, type ListRow } from "./common.ts";
1921
20 /** An admin of a mirror of a read-only origin, the only one who grants. */
21 export const mayGrantRead = (f: Session, repo: Repo): boolean =>
22 f.user !== undefined && canAdmin(f.db, repo, f.user) && isReadOnlyMirror(f.app, repo);
23
2422 export function readGrantsScreen(f: Session, ctx: Ctx, repo: Repo): Screen {
2523 const state = new ListState();
2624 const where = `${repo.ownerName}/${repo.name}`;
27 const rows = () => (mayGrantRead(f, repo) ? listGrants(f.db, repo.id) : []);
25 const rows = () => ((holds(f.db, principalOfUser(f.user), "repo.admin", { repo }) && isReadOnlyMirror(f.app, repo)) ? listGrants(f.db, repo.id) : []);
2826 const screen: Screen = {
2927 title: `${where} — Who may read this`,
3028 keys: [binding(["j", "k"], "move cursor"), binding(["a"], "grant an app"), binding(["c"], "grant a crew member"), binding(["x"], "revoke")],
3129 render(area, s) {
3230 const c = ctx.theme.c;
3331 const [head, list] = split(area, "v", [len(1), fill(1)]);
34 const said = mayGrantRead(f, repo)
32 const said = (holds(f.db, principalOfUser(f.user), "repo.admin", { repo }) && isReadOnlyMirror(f.app, repo))
3533 ? "Grants are reads only. a grants one of your apps, c a crew member, x revokes."
3634 : "Only the admin of a mirror of a read-only origin grants reads.";
3735 s.text(head!.x, head!.y, truncate(said, head!.w), style(c.mutedFg, c.bg), head!.x + head!.w);
@@ -42,7 +40,7 @@ export function readGrantsScreen(f: Session, ctx: Ctx, repo: Repo): Screen {
4240 const all = rows();
4341 if (state.key(e, all.length)) return true;
4442 if (e.ctrl || e.alt || (e.key !== "a" && e.key !== "c" && e.key !== "x")) return false;
45 if (!mayGrantRead(f, repo)) {
43 if (!(holds(f.db, principalOfUser(f.user), "repo.admin", { repo }) && isReadOnlyMirror(f.app, repo))) {
4644 ctx.toast(GRANT_ERRORS.not_read_only, "danger");
4745 return true;
4846 }
@@ -87,7 +85,7 @@ export function readGrantsScreen(f: Session, ctx: Ctx, repo: Repo): Screen {
8785
8886 /** The palette's command while a mirror the viewer administers is open. */
8987 export function readGrantsCommands(f: Session, ctx: Ctx, repo: Repo | undefined): Command[] {
90 if (repo === undefined || !mayGrantRead(f, repo)) return [];
88 if (repo === undefined || !(holds(f.db, principalOfUser(f.user), "repo.admin", { repo }) && isReadOnlyMirror(f.app, repo))) return [];
9189 return [
9290 {
9391 id: "read-grants",
src/web/chrome.ts +4 −2
@@ -8,6 +8,9 @@
88 * `ui.ts` may not. That is the line between the two files.
99 */
1010
11 import { holds } from "../core/may.ts";
12 import { principalOfUser } from "../core/principal.ts";
13 import { forgeCeiling } from "../flow/ceiling.ts";
1114 import { togetherHtml } from "./together.ts";
1215 import { repoOnRequest } from "../http/request_repo.ts";
1316 import { hereAddress, returnTo, safeNext, withReturn } from "./return_to.ts";
@@ -33,7 +36,6 @@ import { keptBehind, MINE_ANCHOR, ownsInTree } from "../core/following.ts";
3336 import { html, raw, when, type Html } from "./html.ts";
3437 import { clamp } from "./clamp.ts";
3538 import { autonomyStatus } from "../crew/autonomy_status.ts";
36 import { mayRaiseCeiling } from "../actions/crew_ceiling.ts";
3739 import { stopWords } from "../crew/stop_words.ts";
3840 import { icon } from "./icons.ts";
3941 import { seesAnyBox } from "../games/store.ts";
@@ -401,7 +403,7 @@ export function scopeHeader(
401403 export function crewStopLine(ctx: Ctx, repo: Repo, base: string): Html {
402404 const w = stopWords(autonomyStatus(ctx.app, repo));
403405 const raise =
404 w.raiseTo !== undefined && mayRaiseCeiling(ctx.app, ctx.auth.user)
406 w.raiseTo !== undefined && (holds(ctx.app.db, principalOfUser(ctx.auth.user), "forge.administer") && forgeCeiling(ctx.app.config) !== null)
405407 ? html` <form method="post" action="${base}/settings/autonomy/raise" class="inline" data-in-place><input type="hidden" name="to" value="${w.raiseTo}"><button type="submit">Raise to $${w.raiseTo}</button></form>`
406408 : null;
407409 return html`<p class="${w.stopped ? "small" : "muted small"}" data-crew-line data-fragment="${base}/settings/crew/line" role="status">${w.words}${w.fix === null ? null : html` <a href="${base}/settings/autonomy">${w.fix}</a>`}${raise}</p>`;
src/web/pages/boards-view.ts +18 −2
@@ -7,6 +7,12 @@
77 * No client framework. Every form posts to `boards-edit.ts`. Anyone but a
88 * person who is an admin gets the not-found page.
99 */
10 import type { Database } from "bun:sqlite";
11 import { getRepo } from "../../core/repos.ts";
12 import type { User } from "../../core/users.ts";
13 import { ownRepoPath } from "../../kernel/own_repo.ts";
14 import { holds } from "../../core/may.ts";
15 import { principalOfUser } from "../../core/principal.ts";
1016 import { checkSlotsFold } from "./boards-slots.ts";
1117 import { CHART_NAMES } from "../../boards/chart.ts";
1218 import { isSlug, MAX_H, MAX_PANELS, MAX_TITLE, MAX_W, RANGES, type Board, type Panel } from "../../boards/store.ts";
@@ -31,7 +37,7 @@ import { formatValue } from "../../boards/chart.ts";
3137 import { boardsIndexLiveJs } from "../boards-index-live.ts";
3238 import { flowPanel, outAsked } from "./flow-panel.ts";
3339 import { boardsHoldsCard } from "./boards-holds.ts";
34 import { alarmLines, mayMergeOwn } from "../studio/alarm_lines.ts";
40 import { alarmLines } from "../studio/alarm_lines.ts";
3541 import { boardPicture, boardsPicture, isFailed, LONG_WAIT_MS, waitAnswer } from "../../flow/pages.ts";
3642 import { isPinned, listPins } from "../../boards/pins.ts";
3743 import { boardMarks } from "../../boards/marks.ts";
@@ -90,6 +96,16 @@ function grid(app: App, slug: string, board: Board, panels: readonly PanelDrawn[
9096 </section>`;
9197 }
9298
99 /**
100 * Merging into the forge's own repository is a person's act: an agent proposes and is shown no
101 * Merge button.
102 */
103 function mergesOwn(db: Database, user: User): boolean {
104 const [owner, name] = ownRepoPath().split("/");
105 const repo = owner && name ? getRepo(db, owner, name) : undefined;
106 return repo !== undefined && holds(db, principalOfUser(user), "repo.write_person", { repo });
107 }
108
93109 const denied = (ctx: Ctx) => !personAdminPage(ctx);
94110
95111 /**
@@ -161,7 +177,7 @@ export async function boardsList(ctx: Ctx): Promise<Response> {
161177 </section>`;
162178 const drift = driftSection(picture.drifting ?? []);
163179 const flow = timePhase(ctx.request, "flow", () =>
164 flowPanel(ctx.app, { kind: "owner" }, ctx.url, "/boards", { picture, refetch: false, now: html`${liveLine(ctx.url.searchParams.has("pause"))}${alarmLines(picture.alarms, mayMergeOwn(ctx.app.db, user))}`, between: boards, first: drift, last: html`${checkSlotsFold(ctx.app)}${boardsHoldsCard(ctx.app.db, user, true)}` }));
180 flowPanel(ctx.app, { kind: "owner" }, ctx.url, "/boards", { picture, refetch: false, now: html`${liveLine(ctx.url.searchParams.has("pause"))}${alarmLines(picture.alarms, mergesOwn(ctx.app.db, user))}`, between: boards, first: drift, last: html`${checkSlotsFold(ctx.app)}${boardsHoldsCard(ctx.app.db, user, true)}` }));
165181 const rendering = performance.now();
166182 const response = page({
167183 ctx,
src/web/studio/alarm_lines.ts −13
@@ -8,10 +8,7 @@ import type { Database } from "bun:sqlite";
88 import { alarmBackup } from "../../flow/alarm_backup.ts";
99 import type { Waiting } from "../../flow/alarm_lane.ts";
1010 import { firedAlarms, type FiredAlarm } from "../../flow/alarms.ts";
11 import { canWrite, getRepo } from "../../core/repos.ts";
12 import type { User } from "../../core/users.ts";
1311 import { writeStamp } from "../../core/write_clock.ts";
14 import { ownRepoPath } from "../../kernel/own_repo.ts";
1512 import { Stamped } from "../../kernel/stamped.ts";
1613 import { html, type Html } from "../html.ts";
1714 import { btn, row, rowList } from "../ui.ts";
@@ -83,13 +80,3 @@ export function alarmLines(alarms: readonly FiredAlarm[], mayMerge = false): Htm
8380 </div>`;
8481 }
8582
86 /**
87 * Whether `user` may merge into the forge's own repository: the lane alarm's Merge buttons are
88 * theirs. Merging is a person's act; an agent proposes and is never shown one.
89 */
90 export function mayMergeOwn(db: Database, user: User): boolean {
91 if (user.kind === "agent") return false;
92 const [owner, name] = ownRepoPath().split("/");
93 const repo = owner && name ? getRepo(db, owner, name) : undefined;
94 return repo !== undefined && canWrite(db, repo, user);
95 }
src/web/studio/review_start.ts +4 −9
@@ -6,11 +6,12 @@
66 * again (`retryFailedStart`), posted under `/pulls/:number/review-retry`.
77 */
88
9 import { holds } from "../../core/may.ts";
10 import { principalOfUser } from "../../core/principal.ts";
911 import type { Database } from "bun:sqlite";
1012 import { mayView } from "../../core/sealed.ts";
1113 import { getPull, type Pull } from "../../core/pulls.ts";
12 import { canWrite, type Repo } from "../../core/repos.ts";
13 import type { User } from "../../core/users.ts";
14 import type { Repo } from "../../core/repos.ts";
1415 import { retryFailedStart, waitsForPerson, type RetryOutcome } from "../../crew/review.ts";
1516 import { reviewSays } from "../../crew/review_says.ts";
1617 import type { Ctx } from "../../http/context.ts";
@@ -28,13 +29,7 @@ export const RETRY_WORDS: Record<RetryOutcome, string> = {
2829 wait: "Review could not be sent just now: a review is out, or the crew cannot run. Try again shortly.",
2930 };
3031
31 /**
32 * The people the re-run lets through, on the page and in the terminal: a person who writes here.
33 */
34 export const mayRetryReview = (db: Database, repo: Repo, user: User | undefined): boolean =>
35 user !== undefined && user.kind === "user" && canWrite(db, repo, user);
36
37 const mayRetry = (ctx: Ctx, repo: Repo): boolean => mayRetryReview(ctx.app.db, repo, ctx.auth.user);
32 const mayRetry = (ctx: Ctx, repo: Repo): boolean => holds(ctx.app.db, principalOfUser(ctx.auth.user), "repo.write_person", { repo });
3833
3934 /**
4035 * Whether this pull reads "review failed to start": an open agent pull whose two review runs never
test/flow-alarm-lane.test.ts +4 −2
@@ -1,4 +1,6 @@
11 /** The lane has stopped (#11507): ten open pulls, 91 minutes without a merge and one repeated failure line raise exactly one alarm; a merge clears it. */
2 import { holds } from "../src/core/may.ts";
3 import { principalOfUser } from "../src/core/principal.ts";
24 import { afterAll, beforeAll, describe, expect, test } from "bun:test";
35 import { mkdtempSync, rmSync } from "node:fs";
46 import { tmpdir } from "node:os";
@@ -13,7 +15,7 @@ import { laneStopped } from "../src/crew/sentinel_lane.ts";
1315 import { firedAlarms } from "../src/flow/alarms.ts";
1416 import { forgeFailed, laneAlarm, laneMinutes, maskLine } from "../src/flow/alarm_lane.ts";
1517 import { id } from "../src/kernel/id.ts";
16 import { alarmLines, mayMergeOwn } from "../src/web/studio/alarm_lines.ts";
18 import { alarmLines } from "../src/web/studio/alarm_lines.ts";
1719 import { waitingLines } from "../src/tui/screens/flow.ts";
1820
1921 const NOW = new Date("2026-11-12T17:11:00.000Z");
@@ -413,7 +415,7 @@ describe("the lane alarm's green pulls carry a Merge action (#18339)", () => {
413415 ]);
414416 const fired = lane();
415417 expect(fired[0]!.waiting).toEqual(alarm.waiting!);
416 expect(mayMergeOwn(app.db, owner())).toBe(true);
418 expect(holds(app.db, principalOfUser(owner()), "repo.write_person", { repo: getRepo(app.db, "trevato", "forge")! })).toBe(true);
417419 const out = String(alarmLines(fired, true));
418420 for (const n of [na, nb]) {
419421 expect(out).toContain(`<a href="/trevato/forge/pulls/${n}" class="row"`);
test/may-only.test.ts +16 −10
@@ -17,7 +17,7 @@ import { createRepo } from "../src/actions/repos.ts";
1717 import { createApp, type App } from "../src/app.ts";
1818 import { holds } from "../src/core/may.ts";
1919 import { principalOfUser } from "../src/core/principal.ts";
20 import { canAdmin, getRepo, type Repo } from "../src/core/repos.ts";
20 import { canAdmin, canWrite, getRepo, type Repo } from "../src/core/repos.ts";
2121 import { createUser, type User } from "../src/core/users.ts";
2222 import { promote } from "./helpers/members.ts";
2323
@@ -54,12 +54,10 @@ const NOT_ACCESS: Readonly<Record<string, string>> = {
5454 */
5555 const STILL_TO_FOLD: readonly string[] = [
5656 "actions/blocked_words.ts canAnswer",
57 "actions/crew_ceiling.ts mayRaiseCeiling",
5857 "actions/destination.ts mayChangeDestination",
5958 "actions/devices.ts mayManageDevices",
6059 "actions/issues.ts mayEditIssue",
6160 "actions/issues.ts maySetSealed",
62 "actions/planner_switch.ts maySwitch",
6361 "actions/places.ts mayPin",
6462 "actions/runs.ts mayReadLogOfRun",
6563 "actions/runs.ts mayReadRunLog",
@@ -103,25 +101,18 @@ const STILL_TO_FOLD: readonly string[] = [
103101 "release/gate.ts mayRollBack",
104102 "security/accept.ts mayAct",
105103 "security/optin.ts mayAsk",
106 "tui/screens/accountorder.ts mayOrder",
107 "tui/screens/atlas.ts mayPlan",
108104 "tui/screens/builds.ts mayPin",
109105 "tui/screens/can.ts canScreen",
110106 "tui/screens/crewdevices.ts mayManageDevices",
111 "tui/screens/crewswitch.ts maySwitchCrew",
112 "tui/screens/dataimport.ts mayImport",
113107 "tui/screens/fleet.ts mayAct",
114108 "tui/screens/prompts.ts mayManagePrompts",
115109 "tui/screens/quarantine.ts mayReview",
116 "tui/screens/readgrants.ts mayGrantRead",
117110 "tui/screens/returns.ts mayReadReturns",
118111 "tui/screens/runlist.ts maySteer",
119112 "web/pages/fleet.ts canAct",
120113 "web/pages/growth_panel.ts isAdmin",
121114 "web/pages/looks.ts mayFetchLook",
122 "web/studio/alarm_lines.ts mayMergeOwn",
123115 "web/studio/answers.ts canSeeAnswers",
124 "web/studio/review_start.ts mayRetryReview",
125116 "games/game_may.ts mayOnGame",
126117 ];
127118
@@ -198,3 +189,18 @@ test("an org-kind admin holds forge.administer_person, which mayRunners once ref
198189 expect(holds(app.db, principalOfUser(org), "forge.administer_person")).toBe(true);
199190 expect(holds(app.db, principalOfUser({ ...org, kind: "agent" }), "forge.administer_person")).toBe(false);
200191 });
192
193 test("repo.admin_person and repo.write_person answer what the person-only wrappers did: the rule, and never an agent", () => {
194 const as = (u: User, kind: User["kind"]): User => ({ ...u, kind });
195 for (const base of [users["boss"]!, users["nina"]!])
196 for (const kind of ["user", "agent"] as const) {
197 const u = as(base, kind);
198 const p = principalOfUser(u);
199 // maySwitch, maySwitchCrew, mayImport: `kind !== "agent" && canAdmin`.
200 expect(holds(app.db, p, "repo.admin_person", { repo }), `${u.username} ${kind} admin`).toBe(kind !== "agent" && canAdmin(app.db, repo, u));
201 // mayOrder, mayMergeOwn: `kind !== "agent" && canWrite`.
202 expect(holds(app.db, p, "repo.write_person", { repo }), `${u.username} ${kind} write`).toBe(kind !== "agent" && canWrite(app.db, repo, u));
203 }
204 expect(holds(app.db, principalOfUser(undefined), "repo.admin_person", { repo })).toBe(false);
205 expect(holds(app.db, principalOfUser(undefined), "repo.write_person", { repo })).toBe(false);
206 });

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

Keyboard shortcuts

Docs