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

Flags for apps: a template flags file, FORGE_FLAGS_URL and a client #1758

Closed opened this
Closed without merging

scout/forge:scout/1572-flags-for-apps-a-template-flags-file-for → main 14 commits fork 3 threads · 3 unresolved

  • Closed without merging. Nothing was applied to main.

Review

Sign in to review this change.
18 files changed +1077 −10
scripts/gate.ts +1
@@ -302,6 +302,7 @@ export const GATE: readonly string[] = [
302302 ];
303303
304304 export const EXCLUDED: readonly Exclusion[] = [
305 { file: "test/app-flags.test.ts", reason: "new; not yet admitted (no ten-run flake hunt yet)", issue: 1572 },
305306 { file: "test/crew-sandbox-real.test.ts", reason: "landed unlisted and red locally; the builder admits it", issue: 1238 },
306307 { file: "test/api-errors.test.ts", reason: "not yet admitted", issue: 261 },
307308 { file: "test/apps-api.test.ts", reason: "not yet admitted", issue: 261 },
src/actions/apps.ts +80
@@ -41,6 +41,14 @@ import {
4141 type AppEnvName,
4242 type AppEnvScope,
4343 } from "../core/app_env.ts";
44 import {
45 deleteAppFlag,
46 listAppFlags,
47 resolveAppFlags,
48 setAppFlag,
49 type AppFlagError,
50 type AppFlagRow,
51 } from "../core/app_flags.ts";
4452 import { addCrew, getAgentByName } from "../core/agents.ts";
4553 import { listAllAgents } from "./crew.ts";
4654 import { plan, planIssueBody, planningAvailable } from "../crew/plan.ts";
@@ -199,6 +207,78 @@ export async function deleteAppEnvVar(
199207 return ok();
200208 }
201209
210 // ---- the app's flags ----
211
212 /** Values set, for an admin. */
213 export function listAppFlagValues(
214 app: App,
215 actor: User | undefined,
216 repo: Repo,
217 ): Result<AppFlagRow[], "not_found"> {
218 const admin = requireRepoAdmin(app, actor, repo);
219 if (!admin.ok) return admin;
220 const record = getAppByRepo(app.db, repo.id);
221 if (!record) return err("not_found");
222 return ok(listAppFlags(app.db, record.id));
223 }
224
225 /** What one environment sees: whoever may read the repository may ask. */
226 export function readAppFlags(
227 app: App,
228 repo: Repo,
229 env: string,
230 ): Result<Record<string, string>, "not_found"> {
231 const record = getAppByRepo(app.db, repo.id);
232 if (!record) return err("not_found");
233 return ok(resolveAppFlags(app.db, record.id, env));
234 }
235
236 /** Set a flag's value in a scope. Live: nothing redeploys. */
237 export function setAppFlagValue(
238 app: App,
239 actor: User | undefined,
240 repo: Repo,
241 name: string,
242 value: string,
243 scope: string = "all",
244 ): Result<AppFlagRow, "not_found" | AppFlagError> {
245 const admin = requireRepoAdmin(app, actor, repo);
246 if (!admin.ok) return admin;
247 const record = getAppByRepo(app.db, repo.id);
248 if (!record) return err("not_found");
249 const set = setAppFlag(app.db, record.id, name, value, scope);
250 if (!set.ok) return set;
251 app.bus.append({
252 kind: "app.flag_set",
253 repoId: repo.id,
254 actorId: admin.value.id,
255 payload: { name, scope: set.value.scope, value: set.value.value },
256 });
257 return set;
258 }
259
260 export function deleteAppFlagValue(
261 app: App,
262 actor: User | undefined,
263 repo: Repo,
264 name: string,
265 scope: string = "all",
266 ): Result<void, "not_found" | "no_such_flag"> {
267 const admin = requireRepoAdmin(app, actor, repo);
268 if (!admin.ok) return admin;
269 const record = getAppByRepo(app.db, repo.id);
270 if (!record) return err("not_found");
271 if (!isAppEnvScope(scope) || !deleteAppFlag(app.db, record.id, name, scope))
272 return err("no_such_flag");
273 app.bus.append({
274 kind: "app.flag_deleted",
275 repoId: repo.id,
276 actorId: admin.value.id,
277 payload: { name, scope },
278 });
279 return ok();
280 }
281
202282 /**
203283 * A process reads its environment once, at start: a change reaches the
204284 * app only through a new process. `redeploy` is what steps past the
src/apps/process.ts +8
@@ -54,6 +54,8 @@ export interface StartInput {
5454 readonly vars?: Record<string, string> | undefined;
5555 /** The process's read-only credential into the forge (`apps/token.ts`). */
5656 readonly forgeToken?: string | undefined;
57 /** `FORGE_FLAGS_URL`, when the forge serves this app's flags. */
58 readonly flagsUrl?: string | undefined;
5759 readonly log: (line: string) => void;
5860 /** Aborting cancels whatever step is in flight and fails the start. */
5961 readonly signal: AbortSignal;
@@ -136,6 +138,8 @@ export function appEnv(input: {
136138 identityKey: string;
137139 /** The exact `ssh …` that opens this environment's terminal, if any. */
138140 ssh?: string | undefined;
141 /** Where the app reads its flag values (`FORGE_FLAGS_URL`). */
142 flagsUrl?: string | undefined;
139143 /** The operator's variables: an admin password, an API key. */
140144 vars?: Record<string, string> | undefined;
141145 /** A read-only forge token for this process (`apps/token.ts`). */
@@ -164,6 +168,9 @@ export function appEnv(input: {
164168 ...(input.forgeToken === undefined
165169 ? {}
166170 : { FORGE_TOKEN: input.forgeToken }),
171 ...(input.flagsUrl === undefined
172 ? {}
173 : { FORGE_FLAGS_URL: input.flagsUrl }),
167174 ...(pull === undefined ? {} : { FORGE_APP_PULL: String(pull) }),
168175 // Printed verbatim by an app that tells people how to reach its
169176 // terminal; a guessed form (`[email protected]`) reaches the forge instead.
@@ -405,6 +412,7 @@ export async function startProcess(
405412 ssh: input.ssh,
406413 vars: input.vars,
407414 forgeToken: input.forgeToken,
415 flagsUrl: input.flagsUrl,
408416 });
409417 const proc = Bun.spawn(cell?.argv(command) ?? ["/bin/sh", "-c", command], {
410418 cwd: input.dir,
src/apps/runtime.ts +13 −1
@@ -24,7 +24,7 @@ import { join } from "node:path";
2424 import type { App } from "../app.ts";
2525 import { getAppByRepo, listApps, type AppRecord } from "../core/apps.ts";
2626 import { resolveAppEnv } from "../core/app_env.ts";
27 import { mintAppToken, renewAppToken, revokeAppToken } from "./token.ts";
27 import { flagsUrl, mintAppToken, renewAppToken, revokeAppToken } from "./token.ts";
2828 import type { ForgeEvent } from "../core/events.ts";
2929 import { announceRun } from "../actions/runs.ts";
3030 import { requeueAbandonedChecks } from "../checks/service.ts";
@@ -1235,6 +1235,12 @@ export class AppsRuntime {
12351235 state.env,
12361236 ),
12371237 forgeToken: token.token,
1238 flagsUrl: flagsUrl(
1239 this.options.forgeUrl,
1240 repo.ownerName,
1241 repo.name,
1242 state.env,
1243 ),
12381244 log: write,
12391245 warm,
12401246 cell: this.cellFor(state.app, state.env),
@@ -1525,6 +1531,12 @@ export class AppsRuntime {
15251531 env,
15261532 ),
15271533 forgeToken: token.token,
1534 flagsUrl: flagsUrl(
1535 this.options.forgeUrl,
1536 repo.ownerName,
1537 repo.name,
1538 env,
1539 ),
15281540 log: write,
15291541 signal: new AbortController().signal,
15301542 warm: true,
src/apps/scaffold.ts +227 −3
@@ -47,6 +47,8 @@ export function scaffoldFiles(input: ScaffoldInput): FileWrite[] {
4747 content: openapiJson(title, description),
4848 },
4949 { path: "design/tokens.json", content: TOKENS_JSON },
50 { path: "flags.json", content: FLAGS_JSON },
51 { path: "src/flags.ts", content: FLAGS_TS },
5052 { path: "src/env.ts", content: ENV_TS },
5153 { path: "src/who.ts", content: WHO_TS },
5254 { path: "src/can.ts", content: CAN_TS },
@@ -68,6 +70,7 @@ export function scaffoldFiles(input: ScaffoldInput): FileWrite[] {
6870 { path: "scripts/contract-emit.ts", content: CONTRACT_EMIT_TS },
6971 { path: "static/app.css", content: APP_CSS },
7072 { path: "static/live.js", content: LIVE_JS },
73 { path: "src/flags.test.ts", content: FLAGS_TEST },
7174 { path: "src/who.test.ts", content: WHO_TEST },
7275 { path: "src/db.test.ts", content: DB_TEST },
7376 { path: "src/actions.test.ts", content: ACTIONS_TEST },
@@ -237,9 +240,19 @@ runs (\`ssh -p 2222 <name>@<forge>\` — the app is the login name, the forge
237240 the host; \`<name>--<pull>@<forge>\` for a preview's). It is \`src/tty.ts\` on
238241 a real pty over the same data, as the account at the keyboard.
239242
243 ## Flags
244
245 \`flags.json\` declares each flag: a name, a one-line why, a default. The owner
246 sets values on the app's settings page on the forge (Flags: everywhere,
247 production only, or previews only); the forge serves them live at \`FORGE_FLAGS_URL\` and \`src/flags.ts\` reads them,
248 with no redeploy. Precedence: \`FLAG_<NAME>\` in the environment, then the
249 forge's value, then the default. \`readout()\` lists every flag, its value and
250 where it came from; reading an undeclared flag throws. The client is one file
251 with no dependencies.
252
240253 The forge sets \`PORT\`, \`FORGE_APP_DATA\`, \`FORGE_APP_ENV\` (\`production\` or
241 \`preview\`), \`FORGE_APP_URL\`, \`FORGE_APP_COMMIT\`, \`FORGE_APP_SSH\` and
242 \`FORGE_APP_IDENTITY_KEY\` when it starts the app. \`forge.json\` says how.
254 \`preview\`), \`FORGE_APP_URL\`, \`FORGE_APP_COMMIT\`, \`FORGE_APP_SSH\`,
255 \`FORGE_FLAGS_URL\` and \`FORGE_APP_IDENTITY_KEY\` when it starts the app. \`forge.json\` says how.
243256 `;
244257
245258 const AGENTS_MD = `# Working on this app
@@ -410,6 +423,216 @@ export const forgeUrl: string | undefined = process.env.FORGE_URL;
410423 export const identityKey: string = process.env.FORGE_APP_IDENTITY_KEY ?? "";
411424 `;
412425
426 const FLAGS_JSON = `{
427 "flags": [
428 {
429 "name": "show-terminal-hint",
430 "why": "Show how to open the terminal on the page; switch it off without a deploy.",
431 "default": true
432 }
433 ]
434 }
435 `;
436
437 const FLAGS_TS = `/**
438 * Flags: behaviour the owner can switch without a deploy. \`flags.json\` is
439 * the declaration (name, why, default); the forge serves the values the
440 * owner set at \`FORGE_FLAGS_URL\`; this file reads them. No dependencies.
441 *
442 * Precedence, highest first: the \`FLAG_<NAME>\` environment variable (for
443 * a local run or a test), the value the forge serves, the declared default.
444 * A value is read as the type of the default: boolean, number or string.
445 *
446 * \`flag(name)\` is synchronous and never waits on the network: it answers
447 * from the last snapshot and, when that is older than \`TTL_MS\`, refreshes
448 * in the background. A forge that cannot be reached leaves the last
449 * snapshot in place. Reading a flag \`flags.json\` does not declare throws.
450 */
451
452 import declared from "../flags.json";
453
454 export type FlagValue = boolean | number | string;
455 export interface FlagDecl {
456 readonly name: string;
457 readonly why: string;
458 readonly default: FlagValue;
459 }
460 export type FlagSource = "env" | "forge" | "default";
461
462 export const TTL_MS = 5_000;
463 export const flagDecls: readonly FlagDecl[] = declared.flags;
464
465 let snapshot: Record<string, string> = {};
466 let fetchedAt = 0;
467 let inflight: Promise<void> | undefined;
468
469 const find = (name: string): FlagDecl => {
470 const decl = flagDecls.find((f) => f.name === name);
471 if (decl === undefined) throw new Error(\`undeclared flag: \${name}\`);
472 return decl;
473 };
474
475 /** Text as the type of the default; undefined when it does not parse. */
476 export function coerce(text: string, like: FlagValue): FlagValue | undefined {
477 if (typeof like === "boolean")
478 return text === "true" ? true : text === "false" ? false : undefined;
479 if (typeof like === "number") {
480 const n = Number(text);
481 return text.trim() !== "" && Number.isFinite(n) ? n : undefined;
482 }
483 return text;
484 }
485
486 const envName = (name: string): string =>
487 \`FLAG_\${name.toUpperCase().replace(/-/g, "_")}\`;
488
489 function resolve(decl: FlagDecl): { value: FlagValue; source: FlagSource } {
490 const local = process.env[envName(decl.name)];
491 const fromEnv = local === undefined ? undefined : coerce(local, decl.default);
492 if (fromEnv !== undefined) return { value: fromEnv, source: "env" };
493 const served = snapshot[decl.name];
494 const fromForge =
495 served === undefined ? undefined : coerce(served, decl.default);
496 if (fromForge !== undefined) return { value: fromForge, source: "forge" };
497 return { value: decl.default, source: "default" };
498 }
499
500 /** Fetch the forge's values now. Resolves either way; failure keeps the old snapshot. */
501 export function refreshFlags(): Promise<void> {
502 const url = process.env.FORGE_FLAGS_URL;
503 if (url === undefined || url === "") return Promise.resolve();
504 inflight ??= (async () => {
505 try {
506 const token = process.env.FORGE_TOKEN;
507 const res = await fetch(url, {
508 headers: token ? { authorization: \`Bearer \${token}\` } : {},
509 signal: AbortSignal.timeout(2_000),
510 });
511 if (!res.ok) return;
512 const body = (await res.json()) as { flags?: unknown };
513 const next: Record<string, string> = {};
514 if (typeof body.flags === "object" && body.flags !== null)
515 for (const [k, v] of Object.entries(body.flags))
516 if (typeof v === "string") next[k] = v;
517 snapshot = next;
518 } catch {
519 // keep what we had
520 } finally {
521 fetchedAt = Date.now();
522 inflight = undefined;
523 }
524 })();
525 return inflight;
526 }
527
528 /** The value of a declared flag, now. */
529 export function flag<T extends FlagValue = FlagValue>(name: string): T {
530 const decl = find(name);
531 if (Date.now() - fetchedAt > TTL_MS) void refreshFlags();
532 return resolve(decl).value as T;
533 }
534
535 /** Every flag with its why, default, value and where the value came from. */
536 export function readout(): {
537 name: string;
538 why: string;
539 default: FlagValue;
540 value: FlagValue;
541 source: FlagSource;
542 }[] {
543 return flagDecls.map((d) => ({
544 name: d.name,
545 why: d.why,
546 default: d.default,
547 ...resolve(d),
548 }));
549 }
550
551 /** For tests: replace the snapshot and mark it fresh. */
552 export function setSnapshot(values: Record<string, string>): void {
553 snapshot = values;
554 fetchedAt = Date.now();
555 }
556 `;
557
558 const FLAGS_TEST = `import { afterEach, describe, expect, test } from "bun:test";
559 import { coerce, flag, flagDecls, readout, refreshFlags, setSnapshot } from "./flags.ts";
560
561 const name = flagDecls[0]!.name;
562 const envKey = \`FLAG_\${name.toUpperCase().replace(/-/g, "_")}\`;
563
564 afterEach(() => {
565 delete process.env[envKey];
566 delete process.env.FORGE_FLAGS_URL;
567 setSnapshot({});
568 });
569
570 describe("flags", () => {
571 test("every declared flag has a why and a default", () => {
572 for (const d of flagDecls) {
573 expect(d.why.length).toBeGreaterThan(0);
574 expect(d.default).toBeDefined();
575 }
576 });
577
578 test("an undeclared flag is refused", () => {
579 expect(() => flag("no-such-flag")).toThrow("undeclared flag");
580 });
581
582 test("the default, then the forge's value, then the environment", () => {
583 const d = flagDecls[0]!;
584 expect(flag(name)).toBe(d.default);
585 expect(readout()[0]!.source).toBe("default");
586 setSnapshot({ [name]: typeof d.default === "boolean" ? String(!d.default) : "7" });
587 expect(readout()[0]!.source).toBe("forge");
588 expect(flag(name)).not.toBe(d.default);
589 process.env[envKey] = typeof d.default === "boolean" ? String(d.default) : "9";
590 expect(readout()[0]!.source).toBe("env");
591 expect(flag(name)).toBe(typeof d.default === "boolean" ? d.default : 9);
592 });
593
594 test("a value of the wrong type falls through to the default", () => {
595 expect(coerce("maybe", true)).toBeUndefined();
596 expect(coerce("", 1)).toBeUndefined();
597 expect(coerce("x", 1)).toBeUndefined();
598 expect(coerce("true", false)).toBe(true);
599 expect(coerce("3", 1)).toBe(3);
600 });
601
602 test("it reads the values the forge serves, with the app's token", async () => {
603 let auth: string | null = null;
604 const server = Bun.serve({
605 port: 0,
606 fetch(req) {
607 auth = req.headers.get("authorization");
608 return Response.json({ env: "production", flags: { [name]: "false" } });
609 },
610 });
611 process.env.FORGE_FLAGS_URL = \`http://127.0.0.1:\${server.port}/flags\`;
612 process.env.FORGE_TOKEN = "tok";
613 try {
614 await refreshFlags();
615 expect(auth).toBe("Bearer tok");
616 expect(readout()[0]!.source).toBe(
617 typeof flagDecls[0]!.default === "boolean" ? "forge" : "default",
618 );
619 } finally {
620 delete process.env.FORGE_TOKEN;
621 await server.stop(true);
622 }
623 });
624
625 test("an unreachable forge keeps the last snapshot", async () => {
626 setSnapshot({ [name]: "false" });
627 process.env.FORGE_FLAGS_URL = "http://127.0.0.1:1/flags";
628 await refreshFlags();
629 expect(readout()[0]!.source).toBe(
630 typeof flagDecls[0]!.default === "boolean" ? "forge" : "default",
631 );
632 });
633 });
634 `;
635
413636 // Identity: the forge's signed headers, or anon.
414637 const WHO_TS = `/**
415638 * Who is asking. The forge signs every request it proxies to the app:
@@ -1351,6 +1574,7 @@ import {
13511574 title,
13521575 where,
13531576 } from "./env.ts";
1577 import { flag } from "./flags.ts";
13541578 import { asset, escape } from "./http.ts";
13551579 import { token, tokensHref } from "./tokens.ts";
13561580 import type { Who } from "./who.ts";
@@ -1401,7 +1625,7 @@ export function layout(body: string, who: Who, path = "/"): string {
14011625 </header>
14021626 <main>\${body}</main>
14031627 <footer class="muted">
1404 \${ssh === undefined ? "" : \`<p>Terminal: <code>\${escape(ssh)}</code></p>\`}
1628 \${ssh === undefined || !flag("show-terminal-hint") ? "" : \`<p>Terminal: <code>\${escape(ssh)}</code></p>\`}
14051629 <p>Also at <a href="/api/notes">/api/notes</a> (<a href="/openapi.json">described</a>) and <code>POST /mcp</code>, with the same rules.</p>
14061630 <p>Something wrong? <a href="/__forge/report">Report a problem</a>, no account needed.</p>
14071631 </footer>
src/apps/token.ts +9
@@ -61,3 +61,12 @@ export function revokeAppToken(db: Database, tokenId: string | undefined): void
6161 /** `FORGE_API_URL`: the forge's JSON API, from its public URL. */
6262 export const forgeApiUrl = (forgeUrl: string): string =>
6363 `${forgeUrl.replace(/\/+$/, "")}/api/v1`;
64
65 /** `FORGE_FLAGS_URL`: the values of an app's flags in one environment. */
66 export const flagsUrl = (
67 forgeUrl: string,
68 owner: string,
69 name: string,
70 env: string,
71 ): string =>
72 `${forgeApiUrl(forgeUrl)}/repos/${encodeURIComponent(owner)}/${encodeURIComponent(name)}/app/flags?env=${env === "production" ? "production" : "preview"}`;
src/apps/tty.ts +44 −6
@@ -23,7 +23,8 @@ import type { App as Forge } from "../app.ts";
2323 import { getAppBySlug, type AppRecord } from "../core/apps.ts";
2424 import { identityKey } from "./proxy.ts";
2525 import { resolveAppEnv } from "../core/app_env.ts";
26 import { canEnterApp, canRead, canWrite, getRepoById } from "../core/repos.ts";
26 import { flagsUrl, mintAppToken, revokeAppToken } from "./token.ts";
27 import { canEnterApp, canRead, canWrite, getRepoById, type Repo } from "../core/repos.ts";
2728 import type { User } from "../core/users.ts";
2829 import { err, ok, type Result } from "../kernel/result.ts";
2930 import type { SshSession } from "../ssh/server.ts";
@@ -105,6 +106,29 @@ export function ttyRefusalText(
105106 }
106107 }
107108
109 /**
110 * What lets the terminal read flags as the process does: the same URL and
111 * a read-only credential of its own, revoked when the terminal ends.
112 */
113 export function terminalFlags(
114 forge: Forge,
115 forgeUrl: string,
116 repo: Repo,
117 target: { app: AppRecord; env: EnvName },
118 ): { flagsUrl: string; token: string; tokenId: string } {
119 const minted = mintAppToken(
120 forge.db,
121 repo.ownerId,
122 target.app.slug,
123 target.env,
124 );
125 return {
126 flagsUrl: flagsUrl(forgeUrl, repo.ownerName, repo.name, target.env),
127 token: minted.token,
128 tokenId: minted.id,
129 };
130 }
131
108132 /**
109133 * Run the app's terminal on `host` until it exits. Every reason it cannot
110134 * is a refusal the caller says in words; a program that ran resolves with
@@ -149,7 +173,10 @@ export async function runAppTty(
149173 rows: Math.max(1, host.rows || 24),
150174 data: (_t, chunk) => host.write(chunk),
151175 });
176 const flags = terminalFlags(forge, runtime.options.forgeUrl, repo, target);

Low: this mints the owner's ro token before Bun.spawn. If the spawn throws, the only revoke (in proc.exited) never runs, and the token lives for 24 hours. Revoke it on the failure path, or mint it just after a successful spawn.

152177 const env = appEnv({
178 flagsUrl: flags.flagsUrl,
179 forgeToken: flags.token,
153180 port: live.port,
154181 dataDir: live.dataDir,
155182 env: live.env,
@@ -179,12 +206,23 @@ export async function runAppTty(
179206 // The terminal is held exactly as the app is (`apps/contain.ts`).
180207 const cell = live.cell === undefined ? undefined : openCell(live.cell);
181208 const command = `exec ${live.tty}`;
182 const proc = Bun.spawn(cell?.argv(command) ?? ["/bin/sh", "-c", command], {
183 terminal,
184 env: cell?.env(env) ?? env,
185 cwd: live.dir,
209 let proc: ReturnType<typeof Bun.spawn>;
210 try {
211 proc = Bun.spawn(cell?.argv(command) ?? ["/bin/sh", "-c", command], {
212 terminal,
213 env: cell?.env(env) ?? env,
214 cwd: live.dir,
215 });
216 } catch (e) {
217 // Nothing will exit to revoke the owner's token: do it here.
218 cell?.close();
219 revokeAppToken(forge.db, flags.tokenId);
220 throw e;
221 }
222 void proc.exited.then(() => {
223 cell?.close();
224 revokeAppToken(forge.db, flags.tokenId);
186225 });
187 void proc.exited.then(() => cell?.close());
188226 cell?.watch(proc.pid, () => killTree(proc.pid));
189227 forge.log.info("app terminal opened", {
190228 app: target.app.slug,
src/core/app_flags.ts added +99
@@ -0,0 +1,99 @@
1 /**
2 * An app's flag values — the rows. The app declares its flags in its own
3 * `flags.json` (name, why, default); the owner sets values here, per scope
4 * (`all`, `production`, `preview`, the narrower winning), and the app reads
5 * them live from `FORGE_FLAGS_URL`. A value is text; the app's client reads
6 * it as the type of the flag's default. Pure data: no authz, no events.
7 */
8
9 import type { Database } from "bun:sqlite";
10 import { err, ok, type Result } from "../kernel/result.ts";
11 import {
12 isAppEnvScope,
13 scopeOfEnv,
14 type AppEnvScope,
15 } from "./app_env.ts";
16
17 export const FLAG_NAME = /^[a-z][a-z0-9_-]{0,63}$/;
18 export const FLAG_VALUE_MAX = 1024;
19
20 export type AppFlagError = "invalid_name" | "invalid_value" | "invalid_scope";
21
22 export interface AppFlagRow {
23 readonly name: string;
24 readonly scope: AppEnvScope;
25 readonly value: string;
26 readonly updatedAt: string;
27 }
28
29 export function setAppFlag(
30 db: Database,
31 appId: string,
32 name: string,
33 value: string,
34 scope: string = "all",
35 ): Result<AppFlagRow, AppFlagError> {
36 if (!FLAG_NAME.test(name)) return err("invalid_name");
37 if (!isAppEnvScope(scope)) return err("invalid_scope");
38 if (value.length > FLAG_VALUE_MAX || value.includes("\0"))
39 return err("invalid_value");
40 db.query(
41 `INSERT INTO app_flag (app_id, name, scope, value) VALUES (?1, ?2, ?3, ?4)
42 ON CONFLICT(app_id, name, scope) DO UPDATE SET
43 value = excluded.value,
44 updated_at = strftime('%Y-%m-%dT%H:%M:%fZ','now')`,
45 ).run(appId, name, scope, value);
46 const row = db
47 .query<
48 { updated_at: string },
49 [string, string, string]
50 >("SELECT updated_at FROM app_flag WHERE app_id = ?1 AND name = ?2 AND scope = ?3")
51 .get(appId, name, scope)!;
52 return ok({ name, scope, value, updatedAt: row.updated_at });
53 }
54
55 export function deleteAppFlag(
56 db: Database,
57 appId: string,
58 name: string,
59 scope: string = "all",
60 ): boolean {
61 return (
62 db
63 .query("DELETE FROM app_flag WHERE app_id = ?1 AND name = ?2 AND scope = ?3")
64 .run(appId, name, scope).changes > 0
65 );
66 }
67
68 /** Every value set, for an admin: widest scope first within a name. */
69 export function listAppFlags(db: Database, appId: string): AppFlagRow[] {
70 return db
71 .query<
72 { name: string; scope: string; value: string; updated_at: string },
73 [string]
74 >(
75 `SELECT name, scope, value, updated_at FROM app_flag WHERE app_id = ?1
76 ORDER BY name, CASE scope WHEN 'all' THEN 0 WHEN 'production' THEN 1 ELSE 2 END`,
77 )
78 .all(appId)
79 .map((r) => ({
80 name: r.name,
81 scope: isAppEnvScope(r.scope) ? r.scope : "all",
82 value: r.value,
83 updatedAt: r.updated_at,
84 }));
85 }
86
87 /** What an environment is to see: `all`, then its own scope over it. */
88 export function resolveAppFlags(
89 db: Database,
90 appId: string,
91 env: string,
92 ): Record<string, string> {
93 const own = scopeOfEnv(env);
94 const out: Record<string, string> = {};
95 for (const r of listAppFlags(db, appId)) {
96 if (r.scope === "all" || r.scope === own) out[r.name] = r.value;
97 }
98 return out;
99 }
src/core/schema.ts +14
@@ -1754,6 +1754,20 @@ export const migrations: readonly string[] = [
17541754 );
17551755 CREATE INDEX deploy_pull_issue ON deploy_pull(issue_id);
17561756 `,
1757 // 87 — flags for apps (#1572): the values an owner sets for the flags the
1758 // app's own flags.json declares, per scope like the environment, served live
1759 // at FORGE_FLAGS_URL. Plain text: a flag is read by the app's pages, not sealed.
1760 `
1761 CREATE TABLE app_flag (
1762 app_id TEXT NOT NULL REFERENCES app(id) ON DELETE CASCADE,
1763 name TEXT NOT NULL,
1764 scope TEXT NOT NULL DEFAULT 'all'
1765 CHECK (scope IN ('all','production','preview')),
1766 value TEXT NOT NULL,
1767 updated_at TEXT NOT NULL DEFAULT (strftime('%Y-%m-%dT%H:%M:%fZ','now')),
1768 PRIMARY KEY (app_id, name, scope)
1769 );
1770 `,
17571771 ];
17581772
17591773 /**
src/design/activity.ts +7
@@ -58,6 +58,13 @@ export function eventVerb(event: ForgeEvent): string {
5858 ? `set ${which} in the app's environment`
5959 : `removed ${which} from the app's environment`;
6060 }
61 if (kind === "app.flag_set" || kind === "app.flag_deleted") {
62 const name = payload["name"];
63 const which = typeof name === "string" ? name : "a flag";
64 return kind === "app.flag_set"
65 ? `set the flag ${which}`
66 : `cleared the flag ${which}`;
67 }
6168 if (kind.startsWith("app.domain.")) {
6269 const host = payload["host"];
6370 const which = typeof host === "string" ? host : "a domain";
src/http/api.ts +69
@@ -219,6 +219,10 @@ import {
219219 disableApp,
220220 enableApp,
221221 listAppEnv,
222 listAppFlagValues,
223 readAppFlags,
224 setAppFlagValue,
225 deleteAppFlagValue,
222226 newApp,
223227 openEnvUrl,
224228 redeployEnv,
@@ -4572,6 +4576,71 @@ export function apiRoutes(router: Router<Handler>): void {
45724576 return json(set.value);
45734577 });
45744578
4579 // The app's flags (#1572). GET is what `FORGE_FLAGS_URL` points at: the
4580 // values one environment sees, for anyone who can read the repository (the
4581 // app's own read-only token does). Setting needs admin.
4582 router.add("GET", "/api/v1/repos/:owner/:name/app/flags", (ctx) => {
4583 const repo = loadRepo(ctx);
4584 if (!repo) return notFound();
4585 const asked = ctx.url.searchParams.get("env") ?? "production";
4586 const env = asked === "production" ? "production" : "preview";
4587 const read = readAppFlags(ctx.app, repo, env);
4588 if (!read.ok) return notFound();
4589 return json({ env, flags: read.value });
4590 });
4591
4592 router.add("GET", "/api/v1/repos/:owner/:name/app/flags/values", (ctx) => {
4593 const denied = requireScope(ctx, "admin");
4594 if (denied) return denied;
4595 const repo = loadRepo(ctx);
4596 if (!repo) return notFound();
4597 const listed = listAppFlagValues(ctx.app, ctx.auth.user, repo);
4598 if (!listed.ok) return notFound();
4599 return json({ items: listed.value, next_cursor: null });
4600 });
4601
4602 router.add(
4603 "PUT",
4604 "/api/v1/repos/:owner/:name/app/flags/:flag",
4605 async (ctx) => {
4606 const denied = requireScope(ctx, "admin");
4607 if (denied) return denied;
4608 const repo = loadRepo(ctx);
4609 if (!repo) return notFound();
4610 const input = await body(ctx.request);
4611 const set = setAppFlagValue(
4612 ctx.app,
4613 ctx.auth.user,
4614 repo,
4615 ctx.params.flag ?? "",
4616 str(input.value),
4617 str(input.scope) || "all",
4618 );
4619 if (!set.ok) return respondAccess(set.error, 422);
4620 return json(set.value);
4621 },
4622 );
4623
4624 router.add(
4625 "DELETE",
4626 "/api/v1/repos/:owner/:name/app/flags/:flag",
4627 (ctx) => {
4628 const denied = requireScope(ctx, "admin");
4629 if (denied) return denied;
4630 const repo = loadRepo(ctx);
4631 if (!repo) return notFound();
4632 const removed = deleteAppFlagValue(
4633 ctx.app,
4634 ctx.auth.user,
4635 repo,
4636 ctx.params.flag ?? "",
4637 ctx.url.searchParams.get("scope") ?? "all",
4638 );
4639 if (!removed.ok) return respondAccess(removed.error, 422);
4640 return json({}, 200);
4641 },
4642 );
4643
45754644 router.add(
45764645 "DELETE",
45774646 "/api/v1/repos/:owner/:name/app/env/:var",
src/http/mcp.ts +55
@@ -98,6 +98,11 @@ import {
9898 import { plannerDeclines } from "../crew/autonomy.ts";
9999 import { listActiveRuns } from "../core/runs.ts";
100100 import { scopeAllows } from "../core/tokens.ts";
101 import {
102 deleteAppFlagValue,
103 listAppFlagValues,
104 setAppFlagValue,
105 } from "../actions/apps.ts";
101106 import { getUsersByIds, type User } from "../core/users.ts";
102107 import { openapi } from "../contract/openapi.ts";
103108 import { audit } from "../contract/audit.ts";
@@ -1251,6 +1256,56 @@ const TOOLS: readonly Tool[] = [
12511256 return answer(setAppMembersThrough(ctx.app, user, repo, { members, dryRun }));
12521257 },
12531258 },
1259 {
1260 name: "app_flags",
1261 description:
1262 "An app's flags: the live values its owner has set, which the running app reads without a redeploy. Without `name`, the list (name, scope, value). With `name` and `value`, the flag is set in `scope` (everywhere by default, or production, or preview); with `name` and `clear` true, that scope's value is removed and the flag falls back to its default. Changing needs an admin-scope token and a repository admin. The same as the app's settings page and /api/v1/repos/:owner/:name/app/flags.",
1263 inputSchema: {
1264 type: "object",
1265 properties: {
1266 repo: REPO_ARG,
1267 name: { type: "string", maxLength: 64 },
outdated

Low: the schema says 4096, but setAppFlag refuses anything over FLAG_VALUE_MAX (1024). Advertise 1024 so a harness doesn't send a value that will be refused.

1268 value: { type: "string", maxLength: 1024 },
1269 scope: { type: "string", enum: ["all", "production", "preview"] },
1270 clear: { type: "boolean" },
1271 },
1272 required: ["repo"],
1273 },
1274 writes: true,
1275 run(ctx, user, args) {
1276 const repo = repoArg(ctx, user, args);
1277 if (isAnswer(repo)) return repo;
1278 const name = str(args["name"]);
1279 const scope = str(args["scope"]) || "all";
1280 if (name === "") {
1281 const listed = listAppFlagValues(ctx.app, user, repo);
1282 return listed.ok
1283 ? good({ flags: listed.value })
1284 : bad("not_found", "no such app or repository (owner/name)");
1285 }
1286 if (!scopeAllows(ctx.auth.scope ?? "ro", "admin"))
1287 return bad("forbidden", "changing a flag needs an admin-scope token");
1288 if (args["clear"] === true) {
1289 const removed = deleteAppFlagValue(ctx.app, user, repo, name, scope);
1290 return removed.ok
1291 ? good({ cleared: name, scope })
1292 : bad(
1293 removed.error === "no_such_flag" ? "invalid" : "not_found",
1294 removed.error === "no_such_flag"
1295 ? "no such flag value in that scope"
1296 : "no such app or repository (owner/name)",
1297 );
1298 }
1299 if (typeof args["value"] !== "string")
1300 return bad("invalid", "value is a string");
1301 const set = setAppFlagValue(ctx.app, user, repo, name, args["value"], scope);
1302 return set.ok
1303 ? good(set.value)
1304 : set.error === "not_found"
1305 ? bad("not_found", "no such app or repository (owner/name)")
1306 : bad("invalid", `refused: ${set.error}`);
1307 },
1308 },
12541309 {
12551310 name: "explore",
12561311 description:
src/http/server.ts +8
@@ -301,6 +301,8 @@ import {
301301 appDomainDelete,
302302 appEnvDelete,
303303 appEnvSet,
304 appFlagDelete,
305 appFlagSet,
304306 appSettingsPage,
305307 appSettingsUpdate,
306308 autonomySettingsPage,
@@ -1143,6 +1145,12 @@ export function buildRouter(): Router<Handler> {
11431145 "/:owner/:name/settings/app/env/:var/delete",
11441146 appEnvDelete,
11451147 );
1148 router.add("POST", "/:owner/:name/settings/app/flags", appFlagSet);
1149 router.add(
1150 "POST",
1151 "/:owner/:name/settings/app/flags/:flag/delete",
1152 appFlagDelete,
1153 );
11461154 // `:host` is one path segment — dots and all — like `:var` above it.
11471155 router.add("POST", "/:owner/:name/settings/app/domains", appDomainAdd);
11481156 router.add(
src/web/icons.ts +1
@@ -57,6 +57,7 @@ const PATHS = {
5757 user: `<path d="M19 21v-2a4 4 0 0 0-4-4H9a4 4 0 0 0-4 4v2"/><circle cx="12" cy="7" r="4"/>`,
5858 users: `<path d="M16 21v-2a4 4 0 0 0-4-4H6a4 4 0 0 0-4 4v2"/><circle cx="9" cy="7" r="4"/><path d="M22 21v-2a4 4 0 0 0-3-3.87"/><path d="M16 3.13a4 4 0 0 1 0 7.75"/>`,
5959 settings: `<path d="M12.22 2h-.44a2 2 0 0 0-2 2v.18a2 2 0 0 1-1 1.73l-.43.25a2 2 0 0 1-2 0l-.15-.08a2 2 0 0 0-2.73.73l-.22.38a2 2 0 0 0 .73 2.73l.15.1a2 2 0 0 1 1 1.72v.51a2 2 0 0 1-1 1.74l-.15.09a2 2 0 0 0-.73 2.73l.22.38a2 2 0 0 0 2.73.73l.15-.08a2 2 0 0 1 2 0l.43.25a2 2 0 0 1 1 1.73V20a2 2 0 0 0 2 2h.44a2 2 0 0 0 2-2v-.18a2 2 0 0 1 1-1.73l.43-.25a2 2 0 0 1 2 0l.15.08a2 2 0 0 0 2.73-.73l.22-.39a2 2 0 0 0-.73-2.73l-.15-.08a2 2 0 0 1-1-1.74v-.5a2 2 0 0 1 1-1.74l.15-.09a2 2 0 0 0 .73-2.73l-.22-.38a2 2 0 0 0-2.73-.73l-.15.08a2 2 0 0 1-2 0l-.43-.25a2 2 0 0 1-1-1.73V4a2 2 0 0 0-2-2z"/><circle cx="12" cy="12" r="3"/>`,
60 flag: `<path d="M4 15s1-1 4-1 5 2 8 2 4-1 4-1V3s-1 1-4 1-5-2-8-2-4 1-4 1z"/><line x1="4" x2="4" y1="22" y2="15"/>`,
6061 key: `<circle cx="7.5" cy="15.5" r="5.5"/><path d="m21 2-9.6 9.6"/><path d="m15.5 7.5 3 3L22 7l-3-3"/>`,
6162 webhook: `<path d="M18 16.98h-5.99c-1.1 0-1.95.94-2.48 1.9A4 4 0 0 1 2 17c.01-.7.2-1.4.57-2"/><path d="m6 17 3.13-5.78c.53-.97.1-2.18-.5-3.1a4 4 0 1 1 6.89-4.06"/><path d="m12 6 3.13 5.73C15.66 12.7 16.9 13 18 13a4 4 0 0 1 0 8"/>`,
6263 search: `<circle cx="11" cy="11" r="8"/><path d="m21 21-4.3-4.3"/>`,
src/web/pages/settings.ts +137
@@ -9,6 +9,9 @@
99 */
1010
1111 import {
12 deleteAppFlagValue,
13 listAppFlagValues,
14 setAppFlagValue,
1215 deleteAppEnvVar,
1316 disableApp,
1417 enableApp,
@@ -493,6 +496,9 @@ function appSettingsView(
493496 <div class="mt">
494497 ${appEnvView(base, listAppEnvNames(ctx.app.db, record.id))}
495498 </div>
499 <div class="mt">
500 ${appFlagsView(base, listAppFlagValues(ctx.app, ctx.auth.user, repo))}
501 </div>
496502 <div class="mt">
497503 ${appDomainsView(base, domains.ok ? domains.value : undefined)}
498504 </div>
@@ -603,6 +609,81 @@ function appEnvView(base: string, names: AppEnvName[]): Html {
603609 );
604610 }
605611
612 function appFlagsView(
613 base: string,
614 listed: ReturnType<typeof listAppFlagValues>,
615 ): Html {
616 const flags = listed.ok ? listed.value : [];
617 const rows = flags.map((f) =>
618 row({
619 lead: icon("flag"),
620 title: html`<span class="mono">${f.name}</span> =
621 <span class="mono">${f.value}</span>`,
622 meta: html`${SCOPE_WORDS[f.scope]} · set ${time(f.updatedAt)}`,
623 trail: html`<form
624 class="row-actions"
625 method="post"
626 action="${base}/settings/app/flags/${encodeURIComponent(f.name)}/delete"
627 >
628 <input type="hidden" name="scope" value="${f.scope}" />
629 ${btn("Clear", {
630 size: "sm",
631 icon: "x",
632 label: `Clear ${f.name} (${SCOPE_WORDS[f.scope]})`,
633 })}
634 </form>`,
635 }),
636 );
637 return card(
638 html`<div class="card-body">
639 <p class="muted small">
640 The switches the app declares in flags.json. A value set here reaches
641 the running app live — nothing redeploys — and a flag with no value
642 keeps its default. Values are shown, so keep secrets in the
643 environment above.
644 </p>
645 </div>
646 ${when(
647 rows.length > 0,
648 () =>
649 html`<ul class="list">
650 ${rows}
651 </ul>`,
652 )}
653 <form class="edit-row" method="post" action="${base}/settings/app/flags">
654 <input
655 class="input mono"
656 type="text"
657 name="name"
658 placeholder="show-terminal-hint"
659 aria-label="Flag name"
660 autocomplete="off"
661 spellcheck="false"
662 required
663 />
664 <input
665 class="input"
666 type="text"
667 name="value"
668 placeholder="Value"
669 aria-label="Value"
670 autocomplete="off"
671 />
672 <select class="input" name="scope" aria-label="Where it applies">
673 <option value="all">Everywhere</option>
674 <option value="production">Production only</option>
675 <option value="preview">Previews only</option>
676 </select>
677 ${btn("Set", { variant: "primary", size: "sm", icon: "plus" })}
678 </form>`,
679 {
680 head: html`${icon("flag")}
681 <h2>Flags</h2>`,
682 pad: false,
683 },
684 );
685 }
686
606687 /**
607688 * The app's own domains: each with what the last check said, the records
608689 * to publish while it waits, and a form for one more. The forge serves a
@@ -936,6 +1017,62 @@ export async function appEnvDelete(ctx: Ctx): Promise<Response> {
9361017 );
9371018 }
9381019
1020 const APP_FLAG_ERRORS: Record<string, string> = {
1021 invalid_name: "A flag name is lowercase letters, digits, hyphens and underscores.",
outdated

High (correctness): FLAG_NAME allows -, and the template's flag is show-terminal-hint. This message tells the owner to use underscores, which leads them to set a name the app never reads. Say "lowercase letters, digits, hyphens and underscores", and change the flag_name placeholder to a hyphenated example.

1022 invalid_value: "A flag's value is short and has no NUL.",
1023 invalid_scope: "A flag goes everywhere, to production, or to previews.",
1024 };
1025
1026 // POST /:owner/:name/settings/app/flags — set one flag's value.
1027 export async function appFlagSet(ctx: Ctx): Promise<Response> {
1028 const gate = await adminForm(ctx);
1029 if (gate instanceof Response) return gate;
1030 const { repo, form } = gate;
1031 const name = field(form, "name").trim();
1032 const set = setAppFlagValue(
1033 ctx.app,
1034 ctx.auth.user,
1035 repo,
1036 name,
1037 field(form, "value"),
1038 field(form, "scope") || "all",
1039 );
1040 if (!set.ok && set.error === "not_found") return repoNotFound(ctx);
1041 return flashTo(
1042 ctx,
1043 `${repoBase(repo)}/settings/app`,
1044 set.ok
1045 ? { message: `${set.value.name} is set, live.` }
1046 : {
1047 tone: "danger",
1048 message: APP_FLAG_ERRORS[set.error] ?? "That flag could not be set.",
1049 },
1050 );
1051 }
1052
1053 // POST /:owner/:name/settings/app/flags/:flag/delete
1054 export async function appFlagDelete(ctx: Ctx): Promise<Response> {
1055 const gate = await adminForm(ctx);
1056 if (gate instanceof Response) return gate;
1057 const { repo, form } = gate;
1058 const name = ctx.params.flag ?? "";
1059 const removed = deleteAppFlagValue(
1060 ctx.app,
1061 ctx.auth.user,
1062 repo,
1063 name,
1064 field(form, "scope") || "all",
1065 );
1066 if (!removed.ok && removed.error === "not_found") return repoNotFound(ctx);
1067 return flashTo(
1068 ctx,
1069 `${repoBase(repo)}/settings/app`,
1070 removed.ok
1071 ? { message: `${name} is cleared; it falls back to its default.` }
1072 : { tone: "danger", message: "No value for that flag." },
1073 );
1074 }
1075
9391076 const APP_DOMAIN_ERRORS: Record<string, string> = {
9401077 invalid_host:
9411078 "A domain is a hostname: letters, digits and hyphens in at least two labels, like app.example.com.",
test/app-flags.test.ts added +172
@@ -0,0 +1,172 @@
1 /**
2 * Flags for apps (#1572): the owner sets values, the app reads them live at
3 * the URL the forge hands it, and the template's client reads them with the
4 * documented precedence.
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 { createRepo } from "../src/actions/repos.ts";
13 import { appEnv } from "../src/apps/process.ts";
14 import { flagsUrl } from "../src/apps/token.ts";
15 import { scaffoldFiles } from "../src/apps/scaffold.ts";
16 import { createApp as createAppRecord } from "../src/core/apps.ts";
17 import { resolveAppFlags, setAppFlag } from "../src/core/app_flags.ts";
18 import { getRepo } from "../src/core/repos.ts";
19 import { createToken } from "../src/core/tokens.ts";
20 import { createUser } from "../src/core/users.ts";
21 import { serve, type Servers } from "../src/http/server.ts";
22
23 describe("app flags", () => {
24 let dataDir: string;
25 let app: App;
26 let servers: Servers;
27 let admin = "";
28 let ro = "";
29 let stranger = "";
30 let appId = "";
31
32 const call = (path: string, token: string | null, init: RequestInit = {}) =>
33 fetch(`${servers.url}${path}`, {
34 ...init,
35 headers: {
36 ...(token ? { authorization: `Bearer ${token}` } : {}),
37 "content-type": "application/json",
38 },
39 });
40 const base = "/api/v1/repos/alice/hello/app/flags";
41 const put = (name: string, body: unknown, token: string | null = admin) =>
42 call(`${base}/${name}`, token, { method: "PUT", body: JSON.stringify(body) });
43
44 beforeAll(async () => {
45 dataDir = await mkdtemp(join(tmpdir(), "forge-app-flags-"));
46 app = createApp({ dataDir, port: 0 });
47 servers = await serve(app);
48 const mk = async (username: string) => {
49 const made = await createUser(app.db, {
50 trusted: true,
51 username,
52 email: `${username}@forge.local`,
53 password: "a-good-passphrase",
54 adminIfFirst: true,
55 });
56 if (!made.ok) throw new Error(made.error);
57 return made.value;
58 };
59 const alice = await mk("alice");
60 const mallory = await mk("mallory");
61 const made = await createRepo(app, alice, { name: "hello" });
62 if (!made.ok) throw new Error(String(made.error));
63 const repo = getRepo(app.db, "alice", "hello")!;
64 const record = createAppRecord(app.db, {
65 repoId: repo.id,
66 slug: "hello",
67 access: "public",
68 });
69 if (!record.ok) throw new Error(record.error);
70 appId = record.value.id;
71 admin = createToken(app.db, alice.id, "admin", "admin").token;
72 ro = createToken(app.db, alice.id, "ro", "ro").token;
73 stranger = createToken(app.db, mallory.id, "admin", "admin").token;
74 });
75 afterAll(async () => {
76 await servers.stop();
77 await rm(dataDir, { recursive: true, force: true });
78 });
79
80 test("the narrower scope wins, and an environment sees only its own", () => {
81 setAppFlag(app.db, appId, "a", "all-value", "all");
82 setAppFlag(app.db, appId, "a", "prod-value", "production");
83 setAppFlag(app.db, appId, "b", "prev", "preview");
84 expect(resolveAppFlags(app.db, appId, "production")).toEqual({
85 a: "prod-value",
86 });
87 expect(resolveAppFlags(app.db, appId, "pull-3")).toEqual({
88 a: "all-value",
89 b: "prev",
90 });
91 app.db.query("DELETE FROM app_flag").run();
92 });
93
94 test("set over the API, read live with the app's read-only token", async () => {
95 expect((await put("dark", { value: "true" })).status).toBe(200);
96 const read = await call(`${base}?env=production`, ro);
97 expect(await read.json()).toEqual({
98 env: "production",
99 flags: { dark: "true" },
100 });
101 expect((await put("dark", { value: "false", scope: "preview" })).status).toBe(
102 200,
103 );
104 const preview = (await (await call(`${base}?env=pull-9`, ro)).json()) as {
105 env: string;
106 flags: Record<string, string>;
107 };
108 expect(preview).toEqual({ env: "preview", flags: { dark: "false" } });
109 const values = (await (await call(`${base}/values`, admin)).json()) as {
110 items: unknown[];
111 };
112 expect(values.items).toHaveLength(2);
113 const gone = await call(`${base}/dark?scope=preview`, admin, {
114 method: "DELETE",
115 });
116 expect(gone.status).toBe(200);
117 expect(
118 ((await (await call(`${base}?env=preview`, ro)).json()) as {
119 flags: unknown;
120 }).flags,
121 ).toEqual({ dark: "true" });
122 });
123
124 test("setting needs admin; a stranger is told nothing; bad input is refused", async () => {
125 expect((await put("dark", { value: "x" }, ro)).status).toBe(403);
126 expect((await put("dark", { value: "x" }, null)).status).toBe(401);
127 expect((await put("dark", { value: "x" }, stranger)).status).toBe(404);
128 for (const [name, body, error] of [
129 ["Bad_Name", { value: "x" }, "invalid_name"],
130 ["dark", { value: "x".repeat(2000) }, "invalid_value"],
131 ["dark", { value: "x", scope: "nowhere" }, "invalid_scope"],
132 ] as const) {
133 const res = await put(name, body);
134 expect(res.status).toBe(422);
135 expect(((await res.json()) as { error: string }).error).toBe(error);
136 }
137 const missing = await call(`${base}/nope`, admin, { method: "DELETE" });
138 expect(missing.status).toBe(422);
139 });
140
141 test("the process is told FORGE_FLAGS_URL", () => {
142 const url = flagsUrl("https://forge.example/", "alice", "hello", "pull-3");
143 expect(url).toBe(
144 "https://forge.example/api/v1/repos/alice/hello/app/flags?env=preview",
145 );
146 const env = appEnv({
147 port: 1,
148 dataDir: "/d",
149 env: "production",
150 url: "https://x",
151 commitOid: "abc",
152 forgeUrl: "https://forge.example",
153 identityKey: "k",
154 flagsUrl: url,
155 vars: { FORGE_FLAGS_URL: "https://evil.example" },
156 });
157 expect(env["FORGE_FLAGS_URL"]).toBe(url);
158 });
159
160 test("the template ships the declaration and the client", () => {
161 const files = new Map(
162 scaffoldFiles({ name: "x", description: "" }).map((f) => [f.path, f.content]),
163 );
164 const decl = JSON.parse(String(files.get("flags.json"))) as {
165 flags: { name: string; why: string; default: unknown }[];
166 };
167 expect(decl.flags.length).toBeGreaterThan(0);
168 expect(files.get("src/flags.ts")).toContain("FORGE_FLAGS_URL");
169 expect(files.get("src/flags.test.ts")).toContain("undeclared flag");
170 expect(String(files.get("src/page.ts"))).toContain(`flag("${decl.flags[0]!.name}")`);
171 });
172 });
test/mcp.test.ts +1
@@ -187,6 +187,7 @@ describe("the forge over MCP", () => {
187187 "thought",
188188 "asked",
189189 "app_members",
190 "app_flags",
190191 "explore",
191192 "feed",
192193 "make_it_yours",
test/web-apps.test.ts +132
@@ -24,6 +24,10 @@ import { AppsRuntime } from "../src/apps/runtime.ts";
2424 import { getAgentByName, listCrew } from "../src/core/agents.ts";
2525 import { listAppEnvNames } from "../src/core/app_env.ts";
2626 import { getAppByRepo } from "../src/core/apps.ts";
27 import { resolveAppFlags } from "../src/core/app_flags.ts";
28 import { listEvents } from "../src/core/events.ts";
29 import { createToken } from "../src/core/tokens.ts";
30 import { terminalFlags } from "../src/apps/tty.ts";
2731 import { getIssue } from "../src/core/issues.ts";
2832 import { getRepo, type Repo } from "../src/core/repos.ts";
2933 import { isTerminal, listRuns, type Run } from "../src/core/runs.ts";
@@ -572,6 +576,134 @@ describe("apps, runs and the crew on the web", () => {
572576 expect(flashOf(missing)).toContain("No variable by that name");
573577 });
574578
579 test("Flags: set and cleared on the page and through MCP, admin only, same-origin only, events recorded, the terminal reads them", async () => {
580 const appId = getAppByRepo(app.db, hello.id)!.id;
581 const page = await bodyOf(alice, "/alice/hello/settings/app");
582 expect(page).toContain("Flags");
583 expect(page).toContain("/alice/hello/settings/app/flags");
584
585 const set = await web(alice, "/alice/hello/settings/app/flags", {
586 form: { name: "dark_mode", value: "true", scope: "preview" },
587 });
588 expect(set.status).toBe(303);
589 expect(flashOf(set)).toContain("dark_mode is set");
590 expect(resolveAppFlags(app.db, appId, "pull-1")).toEqual({
591 dark_mode: "true",
592 });
593 expect(resolveAppFlags(app.db, appId, "production")).toEqual({});
594 const listed = await bodyOf(alice, "/alice/hello/settings/app");
595 expect(listed).toContain("dark_mode");
596 expect(listed).toContain(
597 "/alice/hello/settings/app/flags/dark_mode/delete",
598 );
599
600 const hyphen = await web(alice, "/alice/hello/settings/app/flags", {
601 form: { name: "show-terminal-hint", value: "true" },
602 });
603 expect(flashOf(hyphen)).toContain("show-terminal-hint is set");
604 expect(resolveAppFlags(app.db, appId, "production")).toEqual({
605 "show-terminal-hint": "true",
606 });
607 await web(alice, "/alice/hello/settings/app/flags/show-terminal-hint/delete", {
608 form: { scope: "all" },
609 });
610
611 const bad = await web(alice, "/alice/hello/settings/app/flags", {
612 form: { name: "Not A Name", value: "x" },
613 });
614 expect(flashOf(bad)).toContain("hyphens");
615 expect(
616 (
617 await web(bob, "/alice/hello/settings/app/flags", {
618 form: { name: "stolen", value: "x" },
619 })
620 ).status,
621 ).toBe(404);
622 expect(
623 (
624 await web(alice, "/alice/hello/settings/app/flags", {
625 form: { name: "stolen", value: "x" },
626 origin: "https://evil.example",
627 })
628 ).status,
629 ).toBe(403);
630
631 const cleared = await web(
632 alice,
633 "/alice/hello/settings/app/flags/dark_mode/delete",
634 { form: { scope: "preview" } },
635 );
636 expect(cleared.status).toBe(303);
637 expect(flashOf(cleared)).toContain("dark_mode is cleared");
638 expect(resolveAppFlags(app.db, appId, "pull-1")).toEqual({});
639 expect(
640 (
641 await web(bob, "/alice/hello/settings/app/flags/dark_mode/delete", {
642 form: { scope: "preview" },
643 })
644 ).status,
645 ).toBe(404);
646
647 // The same actions through MCP.
648 const admin = createToken(app.db, user("alice").id, "flags", "admin").token;
649 const ro = createToken(app.db, user("alice").id, "flags-ro", "ro").token;
650 const tool = async (token: string, args: Record<string, unknown>) => {
651 const res = await fetch(`${base}/mcp`, {
652 method: "POST",
653 headers: {
654 "content-type": "application/json",
655 accept: "application/json, text/event-stream",
656 authorization: `Bearer ${token}`,
657 },
658 body: JSON.stringify({
659 jsonrpc: "2.0",
660 id: 1,
661 method: "tools/call",
662 params: { name: "app_flags", arguments: { repo: "alice/hello", ...args } },
663 }),
664 });
665 const out = (await res.json()) as any;
666 const text: string = out.result.content[0].text;
667 const error = out.result.isError === true;
668 return { error, body: error ? text : JSON.parse(text) };
669 };
670 expect((await tool(admin, { name: "beta", value: "on" })).error).toBe(false);
671 const all = await tool(admin, {});
672 expect(all.body.flags.map((f: any) => f.name)).toEqual(["beta"]);
673 expect((await tool(ro, { name: "beta", value: "off" })).error).toBe(true);
674 expect((await tool(ro, { name: "beta", clear: true })).error).toBe(true);
675 expect(resolveAppFlags(app.db, appId, "production")).toEqual({ beta: "on" });
676 expect((await tool(admin, { name: "beta", clear: true })).error).toBe(false);
677 expect(resolveAppFlags(app.db, appId, "production")).toEqual({});
678
679 // Every change left an event.
680 const kinds = listEvents(app.db, {}).map((e) => e.kind);
681 expect(kinds.filter((k) => k === "app.flag_set").length).toBeGreaterThanOrEqual(2);
682 expect(kinds.filter((k) => k === "app.flag_deleted").length).toBeGreaterThanOrEqual(2);
683 const named = (kind: string) =>
684 listEvents(app.db, { kind }).map(
685 (e) => (e.payload as { name: string }).name,
686 );
687 expect(named("app.flag_set")).toContain("dark_mode");
688 expect(named("app.flag_deleted")).toContain("dark_mode");
689
690 // The terminal is told the forge's flags URL and holds a token that reads them.
691 await tool(admin, { name: "live", value: "yes" });
692 const flags = terminalFlags(
693 app,
694 base,
695 hello,
696 { app: getAppByRepo(app.db, hello.id)!, env: "production" },
697 );
698 expect(flags.flagsUrl).toBe(
699 `${base}/api/v1/repos/alice/hello/app/flags?env=production`,
700 );
701 const read = await fetch(flags.flagsUrl, {
702 headers: { authorization: `Bearer ${flags.token}` },
703 });
704 expect(((await read.json()) as any).flags).toEqual({ live: "yes" });
705 });
706
575707 test("a plain repository becomes an app from its settings, and stops being one", async () => {
576708 const plain = getRepo(app.db, "alice", "plain")!;
577709 const section = await bodyOf(alice, "/alice/plain/settings/app");

↑↓ navigate ↵ open ⌘↵ its app esc close

Keyboard shortcuts

Docs