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

Feature flags, part 2: Settings → Flags lets an admin see every flag and set its value per forge, user, role or percentage #1912

Parked opened this
Closed without merging

scout/forge:scout/1828-feature-flags-part-2-settings-flags-lets → main 5 commits fork 3 threads · 3 unresolved

  • Closed without merging. Nothing was applied to main.

Review

Sign in to review this change.
14 files changed +807 −1
README.md +2
@@ -966,6 +966,8 @@ While the default branch's own last check is red, the forge holds its pulls' che
966966
967967 Every limit the owner can hit is declared in `src/settings/limits.ts` with its default, bounds and reason, and changed live by a forge admin at `/admin/limits`, `PUT /api/v1/admin/limits/:key` or the `limits` MCP tool (never by an agent). Each change is kept with who made it.
968968
969 Feature flags (`src/core/flags.ts`) are set or cleared live by a forge admin at `/settings/flags`, `GET /api/v1/admin/flags` and `PUT /api/v1/admin/flags/:name` (a body naming no field is refused, never a clear; `clear: true` clears), the `flags` MCP tool, or `Flags` in the terminal palette; an agent can't change a flag. A no-op change writes no audit row.
970
969971 ## Choosing among variants
970972
971973 A tell with `variants: n` starts n builders whose pulls share a variant group.
scripts/gate.ts +1
@@ -309,6 +309,7 @@ export const GATE: readonly string[] = [
309309 "test/holds.test.ts",
310310 "test/hollow.test.ts",
311311 "test/flags.test.ts",
312 "test/flags-settings.test.ts",
312313 "test/home-feed.test.ts",
313314 "test/home-walk.test.ts",
314315 "test/oauth-discovery.test.ts",
src/actions/flags.ts added +105
@@ -0,0 +1,105 @@
1 /**
2 * The forge's feature flags (`core/flags.ts`), for a forge admin: listed with
3 * their why, default and live value, and set or cleared. Never by an agent,
4 * whatever it was granted — the crew does not decide which version of a thing
5 * it is shown. Everyone else is told `not_found`. The settings page, the API
6 * and the `flags` MCP tool all come through here.
7 */
8
9 import type { App } from "../app.ts";
10 import { checkValue, forgeFlags, type FlagValue } from "../core/flags.ts";
11 import type { User } from "../core/users.ts";
12 import { err, ok, type Result } from "../kernel/result.ts";
13
14 export interface FlagRow {
15 readonly name: string;
16 readonly why: string;
17 readonly default: boolean;
18 readonly issue: number;
19 readonly value: FlagValue | undefined;
20 }
21
22 /** What a form or JSON body says about one flag, as text; `null` clears it. */
23 export type FlagInput = {
24 readonly forge: string;
25 readonly users: string;
26 readonly roles: string;
27 readonly percent: string;
28 } | null;
29
30 function admin(actor: User | undefined): Result<User, "not_found"> {
31 return actor?.isAdmin === true && actor.kind !== "agent"
32 ? ok(actor)
33 : err("not_found");
34 }
35
36 export function listFlags(
37 actor: User | undefined,
38 ): Result<FlagRow[], "not_found"> {
39 const who = admin(actor);
40 if (!who.ok) return who;
41 return ok(
42 forgeFlags.list().map(({ name, decl, value }) => ({
43 name,
44 why: decl.why,
45 default: decl.default,
46 issue: decl.issue,
47 value,
48 })),
49 );
50 }
51
52 /**
53 * A JSON body as `FlagInput`: `{clear:true}` clears; else forge (true/false/null), users/roles (arrays), percent (number/null).
outdated

An empty or malformed body comes out as all-empty strings, which checkValue reads as "clear". Clearing should take an explicit clear: true. A body that names none of the fields should be invalid.

54 * A body that names none of those is `undefined`, never a clear: an empty,
55 * broken or oversized body must not remove a live value.
56 */
57 export function flagInputOf(raw: Record<string, unknown>): FlagInput | undefined {
58 if (raw["clear"] === true) return null;
59 if (!["forge", "users", "roles", "percent"].some((k) => k in raw)) return undefined;
60 const join = (v: unknown): string =>
61 Array.isArray(v) ? v.filter((x) => typeof x === "string").join(",") : typeof v === "string" ? v : "";
62 return {
63 forge: raw["forge"] === true ? "on" : raw["forge"] === false ? "off" : typeof raw["forge"] === "string" ? raw["forge"] : "",
64 users: join(raw["users"]),
65 roles: join(raw["roles"]),
66 percent: typeof raw["percent"] === "number" ? String(raw["percent"]) : typeof raw["percent"] === "string" ? raw["percent"] : "",
67 };
68 }
69
70 export type ChangeFlagError =
71 | { readonly kind: "not_found" }
72 | { readonly kind: "no_such_flag" }
73 | { readonly kind: "invalid"; readonly message: string };
74
75 /** Set `name` to `input`, or clear it with `null`; live in this request. */
76 export function changeFlag(
77 app: App,
78 actor: User | undefined,
79 name: string,
80 input: FlagInput,
81 ): Result<{ name: string; value: FlagValue | undefined }, ChangeFlagError> {
82 const who = admin(actor);
83 if (!who.ok) return err({ kind: "not_found" });
84 const checked = input === null ? ok<FlagValue>({}) : checkValue(input);
85 if (!checked.ok) return err({ kind: "invalid", message: checked.error });
86 const set = forgeFlags.set(app.db, name, checked.value, who.value.id);
87 if (!set.ok) return err({ kind: "no_such_flag" });
88 return ok({
89 name,
90 value: Object.keys(checked.value).length === 0 ? undefined : checked.value,
91 });
92 }
93
94 /** What a terminal line says: `on`, `off`, `25%`, `users a,b`, `roles r`, or `clear`; `undefined` when it says none. */
95 export function flagInputOfLine(line: string): FlagInput | undefined {
96 const t = line.trim().toLowerCase();
97 if (t === "clear") return null;
98 if (t === "on" || t === "off") return { forge: t, users: "", roles: "", percent: "" };
99 const pct = /^(\d{1,3})%$/.exec(t);
100 if (pct) return { forge: "", users: "", roles: "", percent: pct[1]! };
101 const list = /^(users|roles)\s+(\S.*)$/.exec(t);
102 if (list)
103 return { forge: "", users: list[1] === "users" ? list[2]! : "", roles: list[1] === "roles" ? list[2]! : "", percent: "" };
104 return undefined;
105 }
src/core/flags.ts +96 −1
@@ -17,6 +17,7 @@
1717 */
1818
1919 import type { Database } from "bun:sqlite";
20 import { err, ok, type Result } from "../kernel/result.ts";
2021
2122 export type FlagDecl = {
2223 /** One line: what the flag switches and why it exists. */
@@ -121,6 +122,51 @@ export function unreadFlags(
121122 });
122123 }
123124
125 const NAME = /^[A-Za-z0-9_.@-]{1,64}$/;
126 const ROLE = /^[a-z][a-z0-9_-]{0,31}$/;
127 const MAX_LIST = 200;
128
129 function list(text: string, ok1: RegExp, what: string): Result<string[], string> {
130 const items = text.split(/[\s,]+/).filter((t) => t !== "");
131 if (items.length > MAX_LIST) return err(`At most ${MAX_LIST} ${what}.`);
132 const seen = new Set<string>();
133 for (const item of items) {
134 if (!ok1.test(item)) return err(`"${item.slice(0, 40)}" is not a valid ${what.replace(/s$/, "")}.`);
135 seen.add(item);
136 }
137 return ok([...seen]);
138 }
139
140 /**
141 * The admin's form as a value, checked against the declared type (a boolean
142 * flag: `forge` on/off, user ids, role names, a whole percentage 0–100).
143 * An empty form is `{}`, meaning "clear".
144 */
145 export function checkValue(input: {
146 forge: string;
147 users: string;
148 roles: string;
149 percent: string;
150 }): Result<FlagValue, string> {
151 const out: FlagValue = {};
152 if (input.forge === "on") out.forge = true;
153 else if (input.forge === "off") out.forge = false;
154 else if (input.forge !== "") return err("The forge value is on, off or unset.");
155 const users = list(input.users, NAME, "users");
156 if (!users.ok) return users;
157 if (users.value.length > 0) out.users = users.value;
158 const roles = list(input.roles, ROLE, "roles");
159 if (!roles.ok) return roles;
160 if (roles.value.length > 0) out.roles = roles.value;
161 const pct = input.percent.trim();
162 if (pct !== "") {
163 if (!/^\d{1,3}$/.test(pct) || Number(pct) > 100)
164 return err("Percent is a whole number from 0 to 100.");
165 out.percent = Number(pct);
166 }
167 return ok(out);
168 }
169
124170 /** A flag registry over `decls`; the forge's own is `flag`/`loadFlags` below. */
125171 export function makeFlags<const D extends Record<string, FlagDecl>>(decls: D) {
126172 let values = new Map<string, FlagValue>();
@@ -145,13 +191,62 @@ export function makeFlags<const D extends Record<string, FlagDecl>>(decls: D) {
145191 values = new Map();
146192 }
147193 },
194 /** Every declared flag with its live value, in declaration order. */
195 list(): { name: string; decl: FlagDecl; value: FlagValue | undefined }[] {
196 return Object.entries(decls).map(([name, decl]) => ({
197 name,
198 decl,
199 value: values.get(name),
200 }));
201 },
202 /**
203 * Store (or, with `undefined`/empty, clear) a declared flag's value and
204 * take effect at once: the in-memory copy is reloaded in this process.
205 */
206 set(
207 db: Database,
208 name: string,
209 value: FlagValue | undefined,
210 actorId: string,
211 ): Result<void, "no_such_flag"> {
212 if (!Object.hasOwn(decls, name)) return err("no_such_flag");
213 const key = KEY_PREFIX + name;
214 const at = new Date().toISOString();
215 const next =
216 value === undefined || Object.keys(value).length === 0
217 ? undefined
218 : JSON.stringify(value);
219 db.transaction(() => {
220 const from =
221 db
222 .query<{ value: string }, [string]>(
223 "SELECT value FROM forge_setting WHERE key = ?1",
224 )
225 .get(key)?.value ?? "unset";
226 if (from === (next ?? "unset")) return;
227 if (next === undefined)
228 db.query("DELETE FROM forge_setting WHERE key = ?1").run(key);
229 else
230 db.query(
231 `INSERT INTO forge_setting (key, value, updated_by, updated_at) VALUES (?1, ?2, ?3, ?4)
232 ON CONFLICT (key) DO UPDATE SET value = excluded.value,
233 updated_by = excluded.updated_by, updated_at = excluded.updated_at`,
234 ).run(key, next, actorId, at);
235 db.query(
236 `INSERT INTO forge_setting_change (key, from_value, to_value, actor_id, at)
237 VALUES (?1, ?2, ?3, ?4, ?5)`,
238 ).run(key, from, next ?? "unset", actorId, at);
239 })();
240 this.load(db);
241 return ok(undefined);
242 },
148243 flag(name: keyof D & string, viewer?: Viewer): boolean {
149244 return evaluate(name, decls[name]!.default, values.get(name), viewer);
150245 },
151246 };
152247 }
153248
154 const forgeFlags = makeFlags(FLAGS);
249 export const forgeFlags = makeFlags(FLAGS);
155250
156251 /** Read the stored flag values into memory; never throws. */
157252 export const loadFlags = forgeFlags.load;
src/http/api.ts +28
@@ -21,6 +21,7 @@ import { bodyCapFor, readBounded } from "./limits.ts";
2121 import { askCheck } from "../checks/again.ts";
2222 import { mayView, mayViewId, sealedScope } from "../core/sealed.ts";
2323 import { changeCapacity, listCapacity } from "../actions/capacity.ts";
24 import { changeFlag, flagInputOf, listFlags } from "../actions/flags.ts";
2425 import { changeLimit, listLimits } from "../actions/limits.ts";
2526 import {
2627 accountSignIns,
@@ -1433,6 +1434,33 @@ export function apiRoutes(router: Router<Handler>): void {
14331434 );
14341435 });
14351436
1437 // The forge's feature flags (`core/flags.ts`): the same door as limits.
1438 router.add("GET", "/api/v1/admin/flags", (ctx) => {
1439 const denied = accountAdmin(ctx, "ro");
1440 if (denied) return denied;
1441 const listed = listFlags(ctx.auth.user);
1442 return listed.ok ? json({ flags: listed.value }) : notFound();
1443 });
1444
1445 router.add("PUT", "/api/v1/admin/flags/:name", async (ctx) => {
1446 const denied = accountAdmin(ctx, "admin");
1447 if (denied) return denied;
1448 const raw = await boundedBody(ctx.request, REQUEST_MAX);
1449 if (raw === "too_large")
1450 return apiError("too_large", 413, `at most ${REQUEST_MAX} bytes`);
1451 const input = flagInputOf(raw);
1452 if (input === undefined)
1453 return apiError("invalid", 422, "name forge, users, roles, percent, or clear: true");
1454 const changed = changeFlag(ctx.app, ctx.auth.user, ctx.params.name!, input);
1455 if (changed.ok) return json(changed.value);
1456 if (changed.error.kind === "not_found") return notFound();
1457 return apiError(
1458 changed.error.kind,
1459 422,
1460 changed.error.kind === "no_such_flag" ? "no such flag" : changed.error.message,
1461 );
1462 });
1463
14361464 router.add("GET", "/api/v1/admin/accounts", (ctx) => {
14371465 const denied = accountAdmin(ctx, "ro");
14381466 if (denied) return denied;
src/http/mcp.ts +40
@@ -23,6 +23,7 @@ import { listAccess } from "../actions/access_log.ts";
2323 import { changeCapacity, listCapacity } from "../actions/capacity.ts";
2424 import { readPipeline, verdict } from "../flow/pipeline.ts";
2525 import { readThroughput, stageOut, throughputSays } from "../flow/throughput.ts";
26 import { changeFlag, flagInputOf, listFlags } from "../actions/flags.ts";
2627 import { changeLimit, listLimits } from "../actions/limits.ts";
2728 import { LIMIT_KEYS } from "../settings/limits.ts";
2829 import { relationOf, takeUpdates } from "../actions/forks.ts";
@@ -2077,6 +2078,45 @@ const TOOLS: readonly Tool[] = [
20772078 });
20782079 },
20792080 },
2081 {
2082 name: "flags",
2083 description:
2084 "The forge's feature flags, for a forge admin: each with its why, default, owner issue and live value. Without `name`, every flag. With `name` and one of `forge` (\"on\"/\"off\"), `users`, `roles` (comma lists), `percent` (0-100), or `clear` true, the change it would make; with dryRun false, made, live at once. Never by an agent.",
2085 inputSchema: {
2086 type: "object",
2087 properties: {
2088 name: { type: "string", maxLength: 64 },
2089 forge: { type: "string", enum: ["", "on", "off"] },
2090 users: { type: "string", maxLength: 512 },
2091 roles: { type: "string", maxLength: 512 },
2092 percent: { type: "number", minimum: 0, maximum: 100 },
2093 clear: { type: "boolean" },
2094 dryRun: { type: "boolean", description: "Plan only (the default). Send false to change it." },
2095 },
2096 },
2097 writes: true,
2098 dryByDefault: true,
2099 run(ctx, user, args) {
2100 const listed = listFlags(user);
2101 if (!listed.ok) return bad("not_found", "no such tool here");
2102 const name = typeof args["name"] === "string" ? args["name"] : undefined;
outdated

{name, dryRun:false} with no fields clears the flag, and the dry run calls it a "set". Refuse a write that names no field.

2103 if (name === undefined) return good({ flags: listed.value });
2104 const now = listed.value.find((f) => f.name === name);
2105 if (now === undefined) return bad("no_such_flag", `no flag ${name}`);
2106 const input = flagInputOf(args);
2107 if (input === undefined)
2108 return bad("invalid", "name forge, users, roles, percent, or clear: true");
2109 if (args["dryRun"] !== false)
2110 return good({
2111 says: `Would ${input === null ? "clear" : "set"} ${name}${input === null ? "" : ` to ${JSON.stringify(input)}`}. Send dryRun: false to change it.`,
2112 });
2113 if (!scopeAllows(ctx.auth.scope ?? "ro", "admin"))
2114 return bad("forbidden", "changing the forge's flags needs an admin-scope token");
2115 const changed = changeFlag(ctx.app, user, name, input);
2116 if (!changed.ok) return bad(changed.error.kind, changed.error.kind === "invalid" ? changed.error.message : "no such flag");
2117 return good({ says: `${name} ${changed.value.value === undefined ? "cleared" : "saved"}, live now.`, ...changed.value });
2118 },
2119 },
20802120 ];
20812121
20822122 /**
src/http/server.ts +3
@@ -10,6 +10,7 @@ import { unsealReleased } from "../actions/sealed.ts";
1010 import { accessPage } from "../web/pages/access.ts";
1111 import { capacityPage, capacitySet } from "../web/pages/capacity.ts";
1212 import { flowPage } from "../web/pages/flow.ts";
13 import { flagsPage, flagsSet } from "../web/pages/flags.ts";
1314 import { limitsPage, limitsSet } from "../web/pages/admin-limits.ts";
1415 import { boardsPage } from "../web/pages/boards.ts";
1516 import { boardNew, boardPin, boardPost } from "../web/pages/boards-edit.ts";
@@ -715,6 +716,8 @@ export function buildRouter(): Router<Handler> {
715716 router.add("GET", "/boards/:slug", boardShow);
716717 router.add("GET", "/boards/:slug/live", boardLive);
717718 router.add("POST", "/boards/:slug/:op", boardPost);
719 router.add("GET", "/settings/flags", flagsPage);
720 router.add("POST", "/settings/flags", flagsSet);
718721 router.add("GET", "/admin/limits", limitsPage);
719722 router.add("POST", "/admin/limits", limitsSet);
720723 router.add("GET", "/settings/backups", backupsPage);
src/main.ts +2
@@ -11,6 +11,7 @@ import { parentUrlProblem } from "./core/parent_releases.ts";
1111 import { releaseEnv } from "./release/env.ts";
1212 import { createApp } from "./app.ts";
1313 import { backfillCarried } from "./core/carried.ts";
14 import { loadFlags } from "./core/flags.ts";
1415 import { reconcile } from "./core/reconcile.ts";
1516 import { syncAllPillars } from "./actions/pillars.ts";
1617 import { bootHostedChildren } from "./spawn/host.ts";
@@ -230,6 +231,7 @@ const app = createApp({
230231 }),
231232 });
232233
234 loadFlags(app.db);
233235 await reconcile(app);
234236 // Issues linked under a pillar's umbrella before pillars had labels.
235237 const labelled = syncAllPillars(app);
src/tui/forge.ts +9
@@ -28,6 +28,7 @@ import {
2828 openOnWeb,
2929 runAsync,
3030 } from "./screens/common.ts";
31 import { flagsScreen } from "./screens/flags.ts";
3132 import { askedScreen } from "./screens/asked.ts";
3233 import { familyScreen } from "./screens/family.ts";
3334 import { familyLines, familyView } from "../spawn/family.ts";
@@ -206,6 +207,14 @@ export function forgeCommands(session: Session): (ctx: Ctx) => Command[] {
206207 hint: "the pipeline's bottleneck and throughput",
207208 run: () => ctx.push(flowScreen(ctx, flowLines(session.db))),
208209 });
210 // The forge's feature flags: a forge admin's, never an agent's (#1828).
211 if (session.user?.isAdmin === true && session.user.kind !== "agent")
212 commands.push({
213 id: "flags",
214 title: "Flags",
215 hint: "set or clear a feature flag",
216 run: () => ctx.push(flagsScreen(session, ctx)),
217 });
209218 // Stalled flow steps the viewer can unblock, as the home's cards show them (#1807).
210219 if (session.signedIn)
211220 commands.push({
src/tui/screens/flags.ts added +106
@@ -0,0 +1,106 @@
1 /**
2 * The forge's feature flags in the terminal, for a forge admin (#1828): the
3 * settings page's door, not a second implementation. Listing and changing go
4 * through `actions/flags.ts`, which decides who may: anyone else, an agent
5 * included, sees an empty screen and no keys.
6 *
7 * `enter` asks for a value in one line: `on`, `off`, `25%`, `users a,b`,
8 * `roles r`, or `clear`. A line that says none of those changes nothing.
9 */
10
11 import { changeFlag, flagInputOfLine, listFlags, type FlagRow } from "../../actions/flags.ts";
12 import type { FlagValue } from "../../core/flags.ts";
13 import type { Ctx, Screen } from "../app/app.ts";
14 import { binding } from "../app/keys.ts";
15 import { style } from "../term/style.ts";
16 import { truncate } from "../term/width.ts";
17 import type { Session } from "../session.ts";
18 import { ListState, drawList, hitList, plural, promptScreen, type ListRow } from "./common.ts";
19 import { fill, len, split } from "../ui/layout.ts";
20
21 /** A live value in one short phrase; `default` when none is set. */
22 export function sayValue(v: FlagValue | undefined): string {
23 if (v === undefined) return "default";
24 const parts: string[] = [];
25 if (v.forge !== undefined) parts.push(v.forge ? "on" : "off");
26 if (v.users !== undefined) parts.push(`users ${v.users.join(",")}`);
27 if (v.roles !== undefined) parts.push(`roles ${v.roles.join(",")}`);
28 if (v.percent !== undefined) parts.push(`${v.percent}%`);
29 return parts.join(" · ");
30 }
31
32 export function flagsScreen(f: Session, ctx: Ctx): Screen {
33 const state = new ListState();
34 const read = (): FlagRow[] => {
35 const listed = listFlags(f.user);
36 return listed.ok ? listed.value : [];
37 };
38 let flags = read();
39
40 const reload = (): void => {
41 flags = read();
42 state.clamp(flags.length);
43 ctx.invalidate();
44 };
45
46 const edit = (): void => {
47 const row = flags[state.index];
48 if (row === undefined) return;
49 ctx.push(
50 promptScreen(ctx, screen, {
51 title: row.name,
52 label: "Value",
53 placeholder: "on, off, 25%, users a,b, roles r, clear",
54 value: row.value === undefined ? "" : sayValue(row.value),
55 hint: row.why,
56 onSubmit: (text) => {
57 const input = flagInputOfLine(text);
58 if (input === undefined) return "say on, off, 25%, users a,b, roles r, or clear";
59 const done = changeFlag(f.app, f.user, row.name, input);
60 if (!done.ok)
61 return done.error.kind === "invalid" ? done.error.message : "not allowed";
62 reload();
63 ctx.toast(`${row.name} ${done.value.value === undefined ? "cleared" : "saved"}, live now`, "success");
64 return undefined;
65 },
66 }),
67 );
68 };
69
70 const rows = (): ListRow[] =>
71 flags.map((r) => ({
72 title: r.name,
73 secondary: r.why,
74 meta: `${sayValue(r.value)} · default ${r.default ? "on" : "off"} · #${r.issue}`,
75 }));
76
77 const screen: Screen = {
78 title: "Flags",
79 get keys() {
80 return [
81 binding(["j", "k"], "move cursor"),
82 binding(["enter"], "set or clear", { disabled: flags.length === 0 }),
83 ];
84 },
85 load() {
86 reload();
87 return Promise.resolve();
88 },
89 render(area, s) {
90 const c = ctx.theme.c;
91 const [head, list] = split(area, "v", [len(1), fill(1)]);
92 const note = flags.length === 0 ? "No flags to show." : plural(flags.length, "flag");
93 s.text(head!.x, head!.y, truncate(note, head!.w), style(c.mutedFg, c.bg), head!.x + head!.w);
94 drawList(s, list!, c, state, rows());
95 hitList(ctx, list!, state, flags.length, { open: edit });
96 },
97 key(e) {
98 if (state.key(e, flags.length)) return true;
99 if (e.ctrl || e.alt) return false;
100 if (e.key === "enter") edit();
101 else return false;
102 return true;
103 },
104 };
105 return screen;
106 }
src/web/pages/flags.ts added +143
@@ -0,0 +1,143 @@
1 /**
2 * Settings → Flags, for a forge admin: every declared flag (`core/flags.ts`)
3 * with its why, default, owner issue and live value, and a form to set or
4 * clear it. A change is stored and loaded into memory in the same request, so
5 * it governs the next page, restart or not. Anyone else gets a 403, an agent
6 * included: the crew does not decide which version of a thing it is shown.
7 */
8
9 import { changeFlag, listFlags } from "../../actions/flags.ts";
10 import type { FlagValue } from "../../core/flags.ts";
11 import type { Ctx } from "../../http/context.ts";
12 import { settingsLayout } from "../chrome.ts";
13 import { field, readForm } from "../form.ts";
14 import { html, when } from "../html.ts";
15 import { flashTo, page } from "../layout.ts";
16 import { btn, card, empty, icon, row } from "../ui.ts";
17 import { accountSections } from "./origins.ts";
18
19 const forbidden = () => new Response("forbidden", { status: 403 });
20
21 const isAdmin = (ctx: Ctx): boolean =>
22 ctx.auth.user?.isAdmin === true && ctx.auth.user.kind !== "agent";
23
24 const forgeWord = (v: FlagValue | undefined): string =>
25 v?.forge === undefined ? "" : v.forge ? "on" : "off";
26
27 // GET /settings/flags
28 export function flagsPage(ctx: Ctx): Response {
29 if (!isAdmin(ctx)) return forbidden();
30 const listed = listFlags(ctx.auth.user);
31 if (!listed.ok) return forbidden();
32 const rows = listed.value.map(({ name, why, default: def, issue, value }) =>
33 row({
34 lead: icon("activity"),
35 title: html`<span class="mono">${name}</span>`,
36 meta: html`${why}<br />Default
37 <strong>${def ? "on" : "off"}</strong> · owner
38 <a href="/issues/${String(issue)}">#${String(issue)}</a> ·
39 ${value === undefined
40 ? "no value set"
41 : html`live <span class="mono">${JSON.stringify(value)}</span>`}`,
42 trail: html`<form class="row-actions" method="post" action="/settings/flags">
43 <input type="hidden" name="name" value="${name}" />
44 <select class="input" name="forge" aria-label="${name}: forge-wide">
45 ${["", "on", "off"].map(
46 (o) =>
47 html`<option value="${o}" ${forgeWord(value) === o ? "selected" : ""}>
48 ${o === "" ? "forge: default" : `forge: ${o}`}
49 </option>`,
50 )}
51 </select>
52 <input class="input mono" name="users" placeholder="user ids"
53 aria-label="${name}: user ids" value="${(value?.users ?? []).join(", ")}" />
54 <input class="input mono" name="roles" placeholder="roles"
55 aria-label="${name}: roles" value="${(value?.roles ?? []).join(", ")}" />
56 <input class="input mono" type="number" name="percent" min="0" max="100"
57 step="1" placeholder="%" aria-label="${name}: percent"
58 value="${value?.percent === undefined ? "" : String(value.percent)}" />
59 ${btn("Save", { size: "sm", variant: "primary", label: `Save ${name}` })}
60 ${when(
61 value !== undefined,
62 () =>
63 html`${btn("Clear", {
64 size: "sm",
65 name: "clear",
66 value: "1",
67 label: `Clear the value of ${name}`,
68 })}`,
69 )}
70 </form>`,
71 }),
72 );
73 const body = card(
74 rows.length === 0
75 ? empty({
76 icon: "activity",
77 title: "No flags declared",
78 note: "A flag is declared in src/core/flags.ts, with the change it guards.",
79 })
80 : html`<div class="card-body">
81 <p class="muted small">
82 A viewer is on when listed in user ids, or their role is listed,
83 or their stable bucket falls under the percentage; otherwise the
84 forge value answers, otherwise the default. A change applies
85 within the request; nothing needs a restart.
86 </p>
87 </div>
88 <ul class="list">
89 ${rows}
90 </ul>`,
91 {
92 head: html`${icon("activity")}
93 <h2>Flags</h2>`,
94 pad: false,
95 },
96 );
97 return page({
98 ctx,
99 title: "Flags",
100 body: html`<div class="page-head"><h1>Flags</h1></div>
101 ${settingsLayout(
102 accountSections("flags", { admin: true }),
103 body,
104 "Account settings",
105 )}`,
106 });
107 }
108
109 // POST /settings/flags
110 export async function flagsSet(ctx: Ctx): Promise<Response> {
111 // Before the body is read: a non-admin's form is not even parsed.
112 if (!isAdmin(ctx)) return forbidden();
113 const form = await readForm(ctx, "admin");
114 if (form instanceof Response) return form;
115 const name = field(form, "name");
116 const clear = field(form, "clear") === "1";
117 const changed = changeFlag(
118 ctx.app,
119 ctx.auth.user,
120 name,
121 clear
122 ? null
123 : {
124 forge: field(form, "forge"),
125 users: field(form, "users"),
126 roles: field(form, "roles"),
127 percent: field(form, "percent"),
128 },
129 );
130 if (!changed.ok) {
131 if (changed.error.kind === "not_found") return forbidden();
132 return flashTo(ctx, "/settings/flags", {
133 tone: "danger",
134 message:
135 changed.error.kind === "invalid"
136 ? changed.error.message
137 : "There is no such flag.",
138 });
139 }
140 return flashTo(ctx, "/settings/flags", {
141 message: changed.value.value === undefined ? `${name} cleared.` : `${name} saved.`,
142 });
143 }
src/web/pages/origins.ts +7
@@ -83,6 +83,7 @@ export type AccountSection =
8383 | "capacity"
8484 | "access"
8585 | "limits"
86 | "flags"
8687 | "cloud";
8788
8889 /**
@@ -146,6 +147,12 @@ export function accountSections(
146147 icon: "activity" as const,
147148 current: current === "limits",
148149 },
150 {
151 label: "Flags",
152 href: "/settings/flags",
153 icon: "activity" as const,
154 current: current === "flags",
155 },
149156 {
150157 label: "Backups",
151158 href: "/settings/backups",
test/flags-settings.test.ts added +264
@@ -0,0 +1,264 @@
1 /**
2 * Settings → Flags (#1828): an admin sees every declared flag and sets or
3 * clears its value; the POST is same-origin checked and validated; a
4 * non-admin gets a 403; a change is live on the next evaluation.
5 */
6
7 import { afterAll, beforeAll, describe, expect, test } from "bun:test";
8 import { mkdtemp, rm } from "node:fs/promises";
9 import { tmpdir } from "node:os";
10 import { join } from "node:path";
11 import { createApp, type App } from "../src/app.ts";
12 import { checkValue, FLAGS, flag, forgeFlags } from "../src/core/flags.ts";
13 import { createToken } from "../src/core/tokens.ts";
14 import { createUser } from "../src/core/users.ts";
15 import { serve, type Servers } from "../src/http/server.ts";
16 import { createForgeApp } from "../src/tui/forge.ts";
17 import { headlessTerminal } from "../src/tui/term/terminal.ts";
18 import { getUserByName } from "../src/core/users.ts";
19 import { settleApp } from "./helpers/tui.ts";
20
21 describe("checkValue", () => {
22 const blank = { forge: "", users: "", roles: "", percent: "" };
23 test("accepts a typed value and refuses the rest", () => {
24 expect(checkValue({ ...blank, forge: "on", users: "a, b", percent: "30" })).toEqual({
25 ok: true,
26 value: { forge: true, users: ["a", "b"], percent: 30 },
27 });
28 expect(checkValue(blank)).toEqual({ ok: true, value: {} });
29 for (const bad of [
30 { forge: "maybe" },
31 { percent: "101" },
32 { percent: "-1" },
33 { percent: "1.5" },
34 { users: "<script>" },
35 { roles: "Admin!" },
36 ])
37 expect(checkValue({ ...blank, ...bad }).ok).toBe(false);
38 });
39 });
40
41 describe("Settings → Flags", () => {
42 let dataDir: string;
43 let app: App;
44 let servers: Servers;
45 const decls = FLAGS as Record<string, unknown>;
46
47 const login = async (username: string) => {
48 const res = await fetch(`${servers.url}/signin`, {
49 method: "POST",
50 redirect: "manual",
51 headers: { "content-type": "application/x-www-form-urlencoded", origin: servers.url },
52 body: new URLSearchParams({ username, password: "a-good-passphrase" }),
53 });
54 return (res.headers.get("set-cookie") ?? "").split(";")[0] ?? "";
55 };
56 const post = (cookie: string, body: Record<string, string>, origin = servers.url) =>
57 fetch(`${servers.url}/settings/flags`, {
58 method: "POST",
59 redirect: "manual",
60 headers: { cookie, "content-type": "application/x-www-form-urlencoded", origin },
61 body: new URLSearchParams(body),
62 });
63
64 beforeAll(async () => {
65 decls["probe"] = { why: "A <probe> flag for the test.", default: false, issue: 1828 };
66 dataDir = await mkdtemp(join(tmpdir(), "forge-flags-"));
67 app = createApp({ dataDir, port: 0 });
68 servers = await serve(app);
69 for (const [username, first] of [["alice", true], ["bob", false]] as const) {
70 const made = await createUser(app.db, {
71 trusted: true,
72 username,
73 email: `${username}@forge.local`,
74 password: "a-good-passphrase",
75 adminIfFirst: first,
76 });
77 if (!made.ok) throw new Error(made.error);
78 }
79 });
80 afterAll(async () => {
81 delete decls["probe"];
82 forgeFlags.load(app.db);
83 await servers.stop();
84 await rm(dataDir, { recursive: true, force: true });
85 });
86
87 test("a non-admin, signed in or not, gets a 403 and changes nothing", async () => {
88 const bob = await login("bob");
89 for (const cookie of [bob, ""]) {
90 const got = await fetch(`${servers.url}/settings/flags`, { headers: { cookie } });
91 expect(got.status).toBe(403);
92 expect((await post(cookie, { name: "probe", forge: "on" })).status).toBe(403);
93 }
94 expect((flag as (n: string) => boolean)("probe")).toBe(false);
95 expect(app.db.query("SELECT 1 FROM forge_setting WHERE key = 'flag.probe'").get()).toBeNull();
96 });
97
98 test("the admin sees the flag, its why (escaped), default and owner", async () => {
99 const cookie = await login("alice");
100 const text = await (await fetch(`${servers.url}/settings/flags`, { headers: { cookie } })).text();
101 expect(text).toContain("probe");
102 expect(text).toContain("A &lt;probe&gt; flag for the test.");
103 expect(text).toContain("#1828");
104 });
105
106 test("a cross-origin or invalid post is refused; a valid one is live at once, and clears", async () => {
107 const cookie = await login("alice");
108 const read = (n: string, id = "u1") => (flag as (n: string, v: { id: string }) => boolean)(n, { id });
109 expect((await post(cookie, { name: "probe", forge: "on" }, "https://evil.example")).status).toBe(403);
110 expect(read("probe")).toBe(false);
111 for (const bad of [{ forge: "maybe" }, { percent: "500" }, { name: "nope", forge: "on" }]) {
112 const res = await post(cookie, { name: "probe", ...bad });
113 expect(res.status).toBe(303);
114 }
115 expect(read("probe")).toBe(false);
116 expect(app.db.query("SELECT 1 FROM forge_setting WHERE key = 'flag.probe'").get()).toBeNull();
117
118 expect((await post(cookie, { name: "probe", forge: "on" })).status).toBe(303);
119 expect(read("probe")).toBe(true);
120 const page = await (await fetch(`${servers.url}/settings/flags`, { headers: { cookie } })).text();
121 expect(page).toContain("live");
122 expect(app.db.query("SELECT COUNT(*) n FROM forge_setting_change WHERE key = 'flag.probe'").get()).toEqual({ n: 1 });
123
124 expect((await post(cookie, { name: "probe", clear: "1" })).status).toBe(303);
125 expect(read("probe")).toBe(false);
126 });
127
128 test("clearing a flag that has no value leaves no audit row", async () => {
129 const cookie = await login("alice");
130 const rows = () => app.db.query("SELECT COUNT(*) n FROM forge_setting_change WHERE key = 'flag.probe'").get();
131 const before = rows();
132 expect((await post(cookie, { name: "probe", clear: "1" })).status).toBe(303);
133 expect(rows()).toEqual(before);
134 });
135
136 test("the API door: a non-admin is refused; an admin's change is live", async () => {
137 const read = (id = "u1") => (flag as (n: string, v: { id: string }) => boolean)("probe", { id });
138 const alice = createToken(app.db, (app.db.query("SELECT id FROM user WHERE username='alice'").get() as { id: string }).id, "t", "admin").token;
139 const bob = createToken(app.db, (app.db.query("SELECT id FROM user WHERE username='bob'").get() as { id: string }).id, "t", "admin").token;
140 const api = (token: string, method: string, path: string, body?: unknown) =>
141 fetch(`${servers.url}/api/v1/admin/flags${path}`, {
142 method,
143 headers: { authorization: `Bearer ${token}`, "content-type": "application/json" },
144 ...(body === undefined ? {} : { body: JSON.stringify(body) }),
145 });
146 expect((await api(bob, "GET", "")).status).toBe(404);
147 expect((await api(bob, "PUT", "/probe", { forge: true })).status).toBe(404);
148 expect(read()).toBe(false);
149 const listed = (await (await api(alice, "GET", "")).json()) as { flags: { name: string }[] };
150 expect(listed.flags.map((f) => f.name)).toContain("probe");
151 expect((await api(alice, "PUT", "/nope", { forge: true })).status).toBe(422);
152 expect((await api(alice, "PUT", "/probe", { percent: 500 })).status).toBe(422);
153 expect((await api(alice, "PUT", "/probe", { forge: true })).status).toBe(200);
154 expect(read()).toBe(true);
155 expect((await api(alice, "PUT", "/probe", { clear: true })).status).toBe(200);
156 expect(read()).toBe(false);
157 });
158
159 test("the MCP door: a non-admin is refused; an admin's change is live", async () => {
160 const read = () => (flag as (n: string, v: { id: string }) => boolean)("probe", { id: "u1" });
161 const id = (n: string) => (app.db.query("SELECT id FROM user WHERE username=?1").get(n) as { id: string }).id;
162 const call = async (token: string, args: Record<string, unknown>) => {
163 const res = await fetch(`${servers.url}/mcp`, {
164 method: "POST",
165 headers: { "content-type": "application/json", accept: "application/json, text/event-stream", authorization: `Bearer ${token}` },
166 body: JSON.stringify({ jsonrpc: "2.0", id: 1, method: "tools/call", params: { name: "flags", arguments: args } }),
167 });
168 const b = (await res.json()) as any;
169 return { error: b.result.isError === true, text: b.result.content[0].text as string };
170 };
171 const bob = createToken(app.db, id("bob"), "t", "admin").token;
172 const alice = createToken(app.db, id("alice"), "t", "admin").token;
173 expect((await call(bob, { name: "probe", forge: "on", dryRun: false })).error).toBe(true);
174 expect(read()).toBe(false);
175 expect((await call(alice, { name: "probe", forge: "on" })).text).toContain("Would set");
176 expect(read()).toBe(false);
177 expect((await call(alice, { name: "probe", forge: "on", dryRun: false })).error).toBe(false);
178 expect(read()).toBe(true);
179 await call(alice, { name: "probe", clear: true, dryRun: false });
180 expect(read()).toBe(false);
181 });
182 test("an empty, broken or oversized body never clears a set value", async () => {
183 const read = () => (flag as (n: string, v: { id: string }) => boolean)("probe", { id: "u1" });
184 const aliceId = (app.db.query("SELECT id FROM user WHERE username='alice'").get() as { id: string }).id;
185 const alice = createToken(app.db, aliceId, "t", "admin").token;
186 const put = (body: string) =>
187 fetch(`${servers.url}/api/v1/admin/flags/probe`, {
188 method: "PUT",
189 headers: { authorization: `Bearer ${alice}`, "content-type": "application/json" },
190 body,
191 });
192 expect((await put(JSON.stringify({ forge: true }))).status).toBe(200);
193 expect(read()).toBe(true);
194 expect((await put("{}")).status).toBe(422);
195 expect((await put("not json")).status).toBe(422);
196 expect((await put("")).status).toBe(422);
197 expect((await put(JSON.stringify({ pad: "x".repeat(2_000_000) }))).status).toBe(413);
198 expect(read()).toBe(true);
199 const res = await fetch(`${servers.url}/mcp`, {
200 method: "POST",
201 headers: { "content-type": "application/json", accept: "application/json, text/event-stream", authorization: `Bearer ${alice}` },
202 body: JSON.stringify({ jsonrpc: "2.0", id: 1, method: "tools/call", params: { name: "flags", arguments: { name: "probe", dryRun: false } } }),
203 });
204 expect(((await res.json()) as any).result.isError).toBe(true);
205 expect(read()).toBe(true);
206 expect((await put(JSON.stringify({ clear: true }))).status).toBe(200);
207 expect(read()).toBe(false);
208 });
209
210 test("the terminal door: an admin lists and sets a flag; others have no such command", async () => {
211 const read = () => (flag as (n: string, v: { id: string }) => boolean)("probe", { id: "u1" });
212 const boot = (name: string) => {
213 const terminal = headlessTerminal(120, 32);
214 const { app: tui } = createForgeApp(
215 app,
216 { sshUsername: "t", remoteAddress: "127.0.0.1", user: getUserByName(app.db, name)! },
217 { terminal, exitHooks: false },
218 );
219 tui.start();
220 const press = async (...keys: string[]) => {
221 for (const key of keys) {
222 const ctrl = key.startsWith("ctrl+");
223 tui.dispatch({ type: "key", key: ctrl ? key.slice(5) : key, ctrl, alt: false, shift: false });
224 }
225 await settleApp(tui);
226 };
227 const type = async (text: string) => {
228 for (const ch of text) tui.dispatch({ type: "key", key: ch, ctrl: false, alt: false, shift: false });
229 await settleApp(tui);
230 };
231 return { tui, press, type };
232 };
233 const admin = boot("alice");
234 await settleApp(admin.tui);
235 await admin.press("ctrl+k");
236 await admin.type("Flags");
237 await admin.press("enter");
238 const text = admin.tui.screen.toText();
239 expect(text).toContain("probe");
240 expect(text).toContain("default off");
241 await admin.press("enter");
242 await admin.type("on");
243 await admin.press("enter");
244 expect(read()).toBe(true);
245 await admin.press("enter");
246 await admin.type("nonsense");
247 await admin.press("enter");
248 expect(read()).toBe(true);
249 await admin.press("esc");
250 await admin.press("enter");
251 await admin.press("backspace", "backspace");
252 await admin.type("clear");
253 await admin.press("enter");
254 expect(read()).toBe(false);
255 admin.tui.stop();
256
257 const other = boot("bob");
258 await settleApp(other.tui);
259 await other.press("ctrl+k");
260 await other.type("Flags");
261 expect(other.tui.screen.toText()).not.toContain("set or clear a feature flag");
262 other.tui.stop();
263 });
264 });
test/mcp.test.ts +1
@@ -208,6 +208,7 @@ describe("the forge over MCP", () => {
208208 "capacity",
209209 "flow",
210210 "limits",
211 "flags",
211212 "report",
212213 ]);
213214 const byName = new Map<string, any>(

↑↓ navigate ↵ open ⌘↵ its app esc close

Keyboard shortcuts

Docs