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 #1876
scout/forge:scout/1828-feature-flags-part-2-settings-flags-lets → main 2 commits fork 2 threads · 2 unresolved
11 files
changed +580
−1
README.md +2
| @@ -939,6 +939,8 @@ While the default branch's own last check is red, the forge holds its pulls' che | ||
| 939 | 939 | |
| 940 | 940 | 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. |
| 941 | 941 | |
| 942 | 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`, or the `flags` MCP tool; an agent can't change a flag. A no-op change writes no audit row. | |
| 943 | ||
| 942 | 944 | ## Choosing among variants |
| 943 | 945 | |
| 944 | 946 | A tell with `variants: n` starts n builders whose pulls share a variant group. |
scripts/gate.ts +1
| @@ -294,6 +294,7 @@ export const GATE: readonly string[] = [ | ||
| 294 | 294 | "test/holds.test.ts", |
| 295 | 295 | "test/hollow.test.ts", |
| 296 | 296 | "test/flags.test.ts", |
| 297 | "test/flags-settings.test.ts", | |
| 297 | 298 | "test/home-feed.test.ts", |
| 298 | 299 | "test/home-walk.test.ts", |
| 299 | 300 | "test/oauth-discovery.test.ts", |
src/actions/flags.ts added +87
| @@ -0,0 +1,87 @@ | ||
| 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 | /** A JSON body as `FlagInput`: `{clear:true}` clears; else forge (true/false/null), users/roles (arrays), percent (number/null). */ | |
| 53 | export function flagInputOf(raw: Record<string, unknown>): FlagInput { | |
| 54 | if (raw["clear"] === true) return null; | |
| 55 | const join = (v: unknown): string => | |
| 56 | Array.isArray(v) ? v.filter((x) => typeof x === "string").join(",") : typeof v === "string" ? v : ""; | |
| 57 | return { | |
| 58 | forge: raw["forge"] === true ? "on" : raw["forge"] === false ? "off" : typeof raw["forge"] === "string" ? raw["forge"] : "", | |
| 59 | users: join(raw["users"]), | |
| 60 | roles: join(raw["roles"]), | |
| 61 | percent: typeof raw["percent"] === "number" ? String(raw["percent"]) : typeof raw["percent"] === "string" ? raw["percent"] : "", | |
| 62 | }; | |
| 63 | } | |
| 64 | ||
| 65 | export type ChangeFlagError = | |
| 66 | | { readonly kind: "not_found" } | |
| 67 | | { readonly kind: "no_such_flag" } | |
| 68 | | { readonly kind: "invalid"; readonly message: string }; | |
| 69 | ||
| 70 | /** Set `name` to `input`, or clear it with `null`; live in this request. */ | |
| 71 | export function changeFlag( | |
| 72 | app: App, | |
| 73 | actor: User | undefined, | |
| 74 | name: string, | |
| 75 | input: FlagInput, | |
| 76 | ): Result<{ name: string; value: FlagValue | undefined }, ChangeFlagError> { | |
| 77 | const who = admin(actor); | |
| 78 | if (!who.ok) return err({ kind: "not_found" }); | |
| 79 | const checked = input === null ? ok<FlagValue>({}) : checkValue(input); | |
| 80 | if (!checked.ok) return err({ kind: "invalid", message: checked.error }); | |
| 81 | const set = forgeFlags.set(app.db, name, checked.value, who.value.id); | |
| 82 | if (!set.ok) return err({ kind: "no_such_flag" }); | |
| 83 | return ok({ | |
| 84 | name, | |
| 85 | value: Object.keys(checked.value).length === 0 ? undefined : checked.value, | |
| 86 | }); | |
| 87 | } |
src/core/flags.ts +96 −1
| @@ -17,6 +17,7 @@ | ||
| 17 | 17 | */ |
| 18 | 18 | |
| 19 | 19 | import type { Database } from "bun:sqlite"; |
| 20 | import { err, ok, type Result } from "../kernel/result.ts"; | |
| 20 | 21 | |
| 21 | 22 | export type FlagDecl = { |
| 22 | 23 | /** One line: what the flag switches and why it exists. */ |
| @@ -121,6 +122,51 @@ export function unreadFlags( | ||
| 121 | 122 | }); |
| 122 | 123 | } |
| 123 | 124 | |
| 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 | ||
| 124 | 170 | /** A flag registry over `decls`; the forge's own is `flag`/`loadFlags` below. */ |
| 125 | 171 | export function makeFlags<const D extends Record<string, FlagDecl>>(decls: D) { |
| 126 | 172 | let values = new Map<string, FlagValue>(); |
| @@ -145,13 +191,62 @@ export function makeFlags<const D extends Record<string, FlagDecl>>(decls: D) { | ||
| 145 | 191 | values = new Map(); |
| 146 | 192 | } |
| 147 | 193 | }, |
| 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 | }, | |
| 148 | 243 | flag(name: keyof D & string, viewer?: Viewer): boolean { |
| 149 | 244 | return evaluate(name, decls[name]!.default, values.get(name), viewer); |
| 150 | 245 | }, |
| 151 | 246 | }; |
| 152 | 247 | } |
| 153 | 248 | |
| 154 | const forgeFlags = makeFlags(FLAGS); | |
| 249 | export const forgeFlags = makeFlags(FLAGS); | |
| 155 | 250 | |
| 156 | 251 | /** Read the stored flag values into memory; never throws. */ |
| 157 | 252 | export const loadFlags = forgeFlags.load; |
src/http/api.ts +23
| @@ -18,6 +18,7 @@ import { bodyCapFor, readBounded } from "./limits.ts"; | ||
| 18 | 18 | import { askCheck } from "../checks/again.ts"; |
| 19 | 19 | import { mayView, mayViewId, sealedScope } from "../core/sealed.ts"; |
| 20 | 20 | import { changeCapacity, listCapacity } from "../actions/capacity.ts"; |
| 21 | import { changeFlag, flagInputOf, listFlags } from "../actions/flags.ts"; | |
| 21 | 22 | import { changeLimit, listLimits } from "../actions/limits.ts"; |
| 22 | 23 | import { |
| 23 | 24 | accountSignIns, |
| @@ -1402,6 +1403,28 @@ export function apiRoutes(router: Router<Handler>): void { | ||
| 1402 | 1403 | ); |
| 1403 | 1404 | }); |
| 1404 | 1405 | |
| 1406 | // The forge's feature flags (`core/flags.ts`): the same door as limits. | |
| 1407 | router.add("GET", "/api/v1/admin/flags", (ctx) => { | |
| 1408 | const denied = accountAdmin(ctx, "ro"); | |
| 1409 | if (denied) return denied; | |
| 1410 | const listed = listFlags(ctx.auth.user); | |
| 1411 | return listed.ok ? json({ flags: listed.value }) : notFound(); | |
| 1412 | }); | |
| 1413 | ||
| 1414 | router.add("PUT", "/api/v1/admin/flags/:name", async (ctx) => { | |
| 1415 | const denied = accountAdmin(ctx, "admin"); | |
| 1416 | if (denied) return denied; | |
| 1417 | const input = await body(ctx.request); | |
| 1418 | const changed = changeFlag(ctx.app, ctx.auth.user, ctx.params.name!, flagInputOf(input)); | |
| 1419 | if (changed.ok) return json(changed.value); | |
| 1420 | if (changed.error.kind === "not_found") return notFound(); | |
| 1421 | return apiError( | |
| 1422 | changed.error.kind, | |
| 1423 | 422, | |
| 1424 | changed.error.kind === "no_such_flag" ? "no such flag" : changed.error.message, | |
| 1425 | ); | |
| 1426 | }); | |
| 1427 | ||
| 1405 | 1428 | router.add("GET", "/api/v1/admin/accounts", (ctx) => { |
| 1406 | 1429 | const denied = accountAdmin(ctx, "ro"); |
| 1407 | 1430 | if (denied) return denied; |
src/http/mcp.ts +38
| @@ -23,6 +23,7 @@ import { listAccess } from "../actions/access_log.ts"; | ||
| 23 | 23 | import { changeCapacity, listCapacity } from "../actions/capacity.ts"; |
| 24 | 24 | import { readPipeline, verdict } from "../flow/pipeline.ts"; |
| 25 | 25 | import { readThroughput, stageOut, throughputSays } from "../flow/throughput.ts"; |
| 26 | import { changeFlag, flagInputOf, listFlags } from "../actions/flags.ts"; | |
| 26 | 27 | import { changeLimit, listLimits } from "../actions/limits.ts"; |
| 27 | 28 | import { LIMIT_KEYS } from "../settings/limits.ts"; |
| 28 | 29 | import { relationOf, takeUpdates } from "../actions/forks.ts"; |
| @@ -2075,6 +2076,43 @@ const TOOLS: readonly Tool[] = [ | ||
| 2075 | 2076 | }); |
| 2076 | 2077 | }, |
| 2077 | 2078 | }, |
| 2079 | { | |
| 2080 | name: "flags", | |
| 2081 | description: | |
| 2082 | "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.", | |
| 2083 | inputSchema: { | |
| 2084 | type: "object", | |
| 2085 | properties: { | |
| 2086 | name: { type: "string", maxLength: 64 }, | |
| 2087 | forge: { type: "string", enum: ["", "on", "off"] }, | |
| 2088 | users: { type: "string", maxLength: 512 }, | |
| 2089 | roles: { type: "string", maxLength: 512 }, | |
| 2090 | percent: { type: "number", minimum: 0, maximum: 100 }, | |
| 2091 | clear: { type: "boolean" }, | |
| 2092 | dryRun: { type: "boolean", description: "Plan only (the default). Send false to change it." }, | |
| 2093 | }, | |
| 2094 | }, | |
| 2095 | writes: true, | |
| 2096 | dryByDefault: true, | |
| 2097 | run(ctx, user, args) { | |
| 2098 | const listed = listFlags(user); | |
| 2099 | if (!listed.ok) return bad("not_found", "no such tool here"); | |
| 2100 | const name = typeof args["name"] === "string" ? args["name"] : undefined; | |
| 2101 | if (name === undefined) return good({ flags: listed.value }); | |
| 2102 | const now = listed.value.find((f) => f.name === name); | |
| 2103 | if (now === undefined) return bad("no_such_flag", `no flag ${name}`); | |
| 2104 | const input = flagInputOf(args); | |
| 2105 | if (args["dryRun"] !== false) | |
| 2106 | return good({ | |
| 2107 | says: `Would ${input === null ? "clear" : "set"} ${name}${input === null ? "" : ` to ${JSON.stringify(input)}`}. Send dryRun: false to change it.`, | |
| 2108 | }); | |
| 2109 | if (!scopeAllows(ctx.auth.scope ?? "ro", "admin")) | |
| 2110 | return bad("forbidden", "changing the forge's flags needs an admin-scope token"); | |
| 2111 | const changed = changeFlag(ctx.app, user, name, input); | |
| 2112 | if (!changed.ok) return bad(changed.error.kind, changed.error.kind === "invalid" ? changed.error.message : "no such flag"); | |
| 2113 | return good({ says: `${name} ${changed.value.value === undefined ? "cleared" : "saved"}, live now.`, ...changed.value }); | |
| 2114 | }, | |
| 2115 | }, | |
| 2078 | 2116 | ]; |
| 2079 | 2117 | |
| 2080 | 2118 | /** |
src/http/server.ts +3
| @@ -10,6 +10,7 @@ import { unsealReleased } from "../actions/sealed.ts"; | ||
| 10 | 10 | import { accessPage } from "../web/pages/access.ts"; |
| 11 | 11 | import { capacityPage, capacitySet } from "../web/pages/capacity.ts"; |
| 12 | 12 | import { flowPage } from "../web/pages/flow.ts"; |
| 13 | import { flagsPage, flagsSet } from "../web/pages/flags.ts"; | |
| 13 | 14 | import { limitsPage, limitsSet } from "../web/pages/admin-limits.ts"; |
| 14 | 15 | import { boardsPage } from "../web/pages/boards.ts"; |
| 15 | 16 | import { boardNew, boardPin, boardPost } from "../web/pages/boards-edit.ts"; |
| @@ -715,6 +716,8 @@ export function buildRouter(): Router<Handler> { | ||
| 715 | 716 | router.add("GET", "/boards/:slug", boardShow); |
| 716 | 717 | router.add("GET", "/boards/:slug/live", boardLive); |
| 717 | 718 | router.add("POST", "/boards/:slug/:op", boardPost); |
| 719 | router.add("GET", "/settings/flags", flagsPage); | |
| 720 | router.add("POST", "/settings/flags", flagsSet); | |
| 718 | 721 | router.add("GET", "/admin/limits", limitsPage); |
| 719 | 722 | router.add("POST", "/admin/limits", limitsSet); |
| 720 | 723 | router.add("GET", "/settings/backups", backupsPage); |
src/main.ts +2
| @@ -11,6 +11,7 @@ import { parentUrlProblem } from "./core/parent_releases.ts"; | ||
| 11 | 11 | import { releaseEnv } from "./release/env.ts"; |
| 12 | 12 | import { createApp } from "./app.ts"; |
| 13 | 13 | import { backfillCarried } from "./core/carried.ts"; |
| 14 | import { loadFlags } from "./core/flags.ts"; | |
| 14 | 15 | import { reconcile } from "./core/reconcile.ts"; |
| 15 | 16 | import { syncAllPillars } from "./actions/pillars.ts"; |
| 16 | 17 | import { firstBoot } from "./spawn/first-boot.ts"; |
| @@ -229,6 +230,7 @@ const app = createApp({ | ||
| 229 | 230 | }), |
| 230 | 231 | }); |
| 231 | 232 | |
| 233 | loadFlags(app.db); | |
| 232 | 234 | await reconcile(app); |
| 233 | 235 | // Issues linked under a pillar's umbrella before pillars had labels. |
| 234 | 236 | const labelled = syncAllPillars(app); |
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 | ||
outdated
The checks and the write live in the page handler, so no other door can reuse them. Move them into an action that this handler, a JSON API route and an MCP tool all call, the same way |
||
| 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 = | ||
| 83 | 83 | | "capacity" |
| 84 | 84 | | "access" |
| 85 | 85 | | "limits" |
| 86 | | "flags" | |
| 86 | 87 | | "cloud"; |
| 87 | 88 | |
| 88 | 89 | /** |
| @@ -146,6 +147,12 @@ export function accountSections( | ||
| 146 | 147 | icon: "activity" as const, |
| 147 | 148 | current: current === "limits", |
| 148 | 149 | }, |
| 150 | { | |
| 151 | label: "Flags", | |
| 152 | href: "/settings/flags", | |
| 153 | icon: "activity" as const, | |
| 154 | current: current === "flags", | |
| 155 | }, | |
| 149 | 156 | { |
| 150 | 157 | label: "Backups", |
| 151 | 158 | href: "/settings/backups", |
test/flags-settings.test.ts added +178
| @@ -0,0 +1,178 @@ | ||
| 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 | ||
| 17 | describe("checkValue", () => { | |
| 18 | const blank = { forge: "", users: "", roles: "", percent: "" }; | |
| 19 | test("accepts a typed value and refuses the rest", () => { | |
| 20 | expect(checkValue({ ...blank, forge: "on", users: "a, b", percent: "30" })).toEqual({ | |
| 21 | ok: true, | |
| 22 | value: { forge: true, users: ["a", "b"], percent: 30 }, | |
| 23 | }); | |
| 24 | expect(checkValue(blank)).toEqual({ ok: true, value: {} }); | |
| 25 | for (const bad of [ | |
| 26 | { forge: "maybe" }, | |
| 27 | { percent: "101" }, | |
| 28 | { percent: "-1" }, | |
| 29 | { percent: "1.5" }, | |
| 30 | { users: "<script>" }, | |
| 31 | { roles: "Admin!" }, | |
| 32 | ]) | |
| 33 | expect(checkValue({ ...blank, ...bad }).ok).toBe(false); | |
| 34 | }); | |
| 35 | }); | |
| 36 | ||
| 37 | describe("Settings → Flags", () => { | |
| 38 | let dataDir: string; | |
| 39 | let app: App; | |
| 40 | let servers: Servers; | |
| 41 | const decls = FLAGS as Record<string, unknown>; | |
| 42 | ||
| 43 | const login = async (username: string) => { | |
| 44 | const res = await fetch(`${servers.url}/signin`, { | |
| 45 | method: "POST", | |
| 46 | redirect: "manual", | |
| 47 | headers: { "content-type": "application/x-www-form-urlencoded", origin: servers.url }, | |
| 48 | body: new URLSearchParams({ username, password: "a-good-passphrase" }), | |
| 49 | }); | |
| 50 | return (res.headers.get("set-cookie") ?? "").split(";")[0] ?? ""; | |
| 51 | }; | |
| 52 | const post = (cookie: string, body: Record<string, string>, origin = servers.url) => | |
| 53 | fetch(`${servers.url}/settings/flags`, { | |
| 54 | method: "POST", | |
| 55 | redirect: "manual", | |
| 56 | headers: { cookie, "content-type": "application/x-www-form-urlencoded", origin }, | |
| 57 | body: new URLSearchParams(body), | |
| 58 | }); | |
| 59 | ||
| 60 | beforeAll(async () => { | |
| 61 | decls["probe"] = { why: "A <probe> flag for the test.", default: false, issue: 1828 }; | |
| 62 | dataDir = await mkdtemp(join(tmpdir(), "forge-flags-")); | |
| 63 | app = createApp({ dataDir, port: 0 }); | |
| 64 | servers = await serve(app); | |
| 65 | for (const [username, first] of [["alice", true], ["bob", false]] as const) { | |
| 66 | const made = await createUser(app.db, { | |
| 67 | trusted: true, | |
| 68 | username, | |
| 69 | email: `${username}@forge.local`, | |
| 70 | password: "a-good-passphrase", | |
| 71 | adminIfFirst: first, | |
| 72 | }); | |
| 73 | if (!made.ok) throw new Error(made.error); | |
| 74 | } | |
| 75 | }); | |
| 76 | afterAll(async () => { | |
| 77 | delete decls["probe"]; | |
| 78 | forgeFlags.load(app.db); | |
| 79 | await servers.stop(); | |
| 80 | await rm(dataDir, { recursive: true, force: true }); | |
| 81 | }); | |
| 82 | ||
| 83 | test("a non-admin, signed in or not, gets a 403 and changes nothing", async () => { | |
| 84 | const bob = await login("bob"); | |
| 85 | for (const cookie of [bob, ""]) { | |
| 86 | const got = await fetch(`${servers.url}/settings/flags`, { headers: { cookie } }); | |
| 87 | expect(got.status).toBe(403); | |
| 88 | expect((await post(cookie, { name: "probe", forge: "on" })).status).toBe(403); | |
| 89 | } | |
| 90 | expect((flag as (n: string) => boolean)("probe")).toBe(false); | |
| 91 | expect(app.db.query("SELECT 1 FROM forge_setting WHERE key = 'flag.probe'").get()).toBeNull(); | |
| 92 | }); | |
| 93 | ||
| 94 | test("the admin sees the flag, its why (escaped), default and owner", async () => { | |
| 95 | const cookie = await login("alice"); | |
| 96 | const text = await (await fetch(`${servers.url}/settings/flags`, { headers: { cookie } })).text(); | |
| 97 | expect(text).toContain("probe"); | |
| 98 | expect(text).toContain("A <probe> flag for the test."); | |
| 99 | expect(text).toContain("#1828"); | |
| 100 | }); | |
| 101 | ||
| 102 | test("a cross-origin or invalid post is refused; a valid one is live at once, and clears", async () => { | |
| 103 | const cookie = await login("alice"); | |
| 104 | const read = (n: string, id = "u1") => (flag as (n: string, v: { id: string }) => boolean)(n, { id }); | |
| 105 | expect((await post(cookie, { name: "probe", forge: "on" }, "https://evil.example")).status).toBe(403); | |
| 106 | expect(read("probe")).toBe(false); | |
| 107 | for (const bad of [{ forge: "maybe" }, { percent: "500" }, { name: "nope", forge: "on" }]) { | |
| 108 | const res = await post(cookie, { name: "probe", ...bad }); | |
| 109 | expect(res.status).toBe(303); | |
| 110 | } | |
| 111 | expect(read("probe")).toBe(false); | |
| 112 | expect(app.db.query("SELECT 1 FROM forge_setting WHERE key = 'flag.probe'").get()).toBeNull(); | |
| 113 | ||
| 114 | expect((await post(cookie, { name: "probe", forge: "on" })).status).toBe(303); | |
| 115 | expect(read("probe")).toBe(true); | |
| 116 | const page = await (await fetch(`${servers.url}/settings/flags`, { headers: { cookie } })).text(); | |
| 117 | expect(page).toContain("live"); | |
| 118 | expect(app.db.query("SELECT COUNT(*) n FROM forge_setting_change WHERE key = 'flag.probe'").get()).toEqual({ n: 1 }); | |
| 119 | ||
| 120 | expect((await post(cookie, { name: "probe", clear: "1" })).status).toBe(303); | |
| 121 | expect(read("probe")).toBe(false); | |
| 122 | }); | |
| 123 | ||
| 124 | test("clearing a flag that has no value leaves no audit row", async () => { | |
| 125 | const cookie = await login("alice"); | |
| 126 | const rows = () => app.db.query("SELECT COUNT(*) n FROM forge_setting_change WHERE key = 'flag.probe'").get(); | |
| 127 | const before = rows(); | |
| 128 | expect((await post(cookie, { name: "probe", clear: "1" })).status).toBe(303); | |
| 129 | expect(rows()).toEqual(before); | |
| 130 | }); | |
| 131 | ||
| 132 | test("the API door: a non-admin is refused; an admin's change is live", async () => { | |
| 133 | const read = (id = "u1") => (flag as (n: string, v: { id: string }) => boolean)("probe", { id }); | |
| 134 | const alice = createToken(app.db, (app.db.query("SELECT id FROM user WHERE username='alice'").get() as { id: string }).id, "t", "admin").token; | |
| 135 | const bob = createToken(app.db, (app.db.query("SELECT id FROM user WHERE username='bob'").get() as { id: string }).id, "t", "admin").token; | |
| 136 | const api = (token: string, method: string, path: string, body?: unknown) => | |
| 137 | fetch(`${servers.url}/api/v1/admin/flags${path}`, { | |
| 138 | method, | |
| 139 | headers: { authorization: `Bearer ${token}`, "content-type": "application/json" }, | |
| 140 | ...(body === undefined ? {} : { body: JSON.stringify(body) }), | |
| 141 | }); | |
| 142 | expect((await api(bob, "GET", "")).status).toBe(404); | |
| 143 | expect((await api(bob, "PUT", "/probe", { forge: true })).status).toBe(404); | |
| 144 | expect(read()).toBe(false); | |
| 145 | const listed = (await (await api(alice, "GET", "")).json()) as { flags: { name: string }[] }; | |
| 146 | expect(listed.flags.map((f) => f.name)).toContain("probe"); | |
| 147 | expect((await api(alice, "PUT", "/nope", { forge: true })).status).toBe(422); | |
| 148 | expect((await api(alice, "PUT", "/probe", { percent: 500 })).status).toBe(422); | |
| 149 | expect((await api(alice, "PUT", "/probe", { forge: true })).status).toBe(200); | |
| 150 | expect(read()).toBe(true); | |
| 151 | expect((await api(alice, "PUT", "/probe", { clear: true })).status).toBe(200); | |
| 152 | expect(read()).toBe(false); | |
| 153 | }); | |
| 154 | ||
| 155 | test("the MCP door: a non-admin is refused; an admin's change is live", async () => { | |
| 156 | const read = () => (flag as (n: string, v: { id: string }) => boolean)("probe", { id: "u1" }); | |
| 157 | const id = (n: string) => (app.db.query("SELECT id FROM user WHERE username=?1").get(n) as { id: string }).id; | |
| 158 | const call = async (token: string, args: Record<string, unknown>) => { | |
| 159 | const res = await fetch(`${servers.url}/mcp`, { | |
| 160 | method: "POST", | |
| 161 | headers: { "content-type": "application/json", accept: "application/json, text/event-stream", authorization: `Bearer ${token}` }, | |
| 162 | body: JSON.stringify({ jsonrpc: "2.0", id: 1, method: "tools/call", params: { name: "flags", arguments: args } }), | |
| 163 | }); | |
| 164 | const b = (await res.json()) as any; | |
| 165 | return { error: b.result.isError === true, text: b.result.content[0].text as string }; | |
| 166 | }; | |
| 167 | const bob = createToken(app.db, id("bob"), "t", "admin").token; | |
| 168 | const alice = createToken(app.db, id("alice"), "t", "admin").token; | |
| 169 | expect((await call(bob, { name: "probe", forge: "on", dryRun: false })).error).toBe(true); | |
| 170 | expect(read()).toBe(false); | |
| 171 | expect((await call(alice, { name: "probe", forge: "on" })).text).toContain("Would set"); | |
| 172 | expect(read()).toBe(false); | |
| 173 | expect((await call(alice, { name: "probe", forge: "on", dryRun: false })).error).toBe(false); | |
| 174 | expect(read()).toBe(true); | |
| 175 | await call(alice, { name: "probe", clear: true, dryRun: false }); | |
| 176 | expect(read()).toBe(false); | |
| 177 | }); | |
| 178 | }); |
new above
offline
When
fromalready equalsnext ?? "unset"(for example, clearing a flag that was never set), skip the DELETE and the audit insert. Otherwise every no-op Clear leaves a change row.