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

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

Closed opened this
Closed without merging

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

  • Closed without merging. Nothing was applied to main.

Review

Sign in to review this change.
17 files changed +1047 −6
scripts/gate.ts +1
@@ -285,6 +285,7 @@ export const GATE: readonly string[] = [
285285 ];
286286
287287 export const EXCLUDED: readonly Exclusion[] = [
288 { file: "test/app-flags.test.ts", reason: "new; not yet admitted (no ten-run flake hunt yet)", issue: 1572 },
288289 { file: "test/crew-sandbox-real.test.ts", reason: "landed unlisted and red locally; the builder admits it", issue: 1238 },
289290 { file: "test/api-errors.test.ts", reason: "not yet admitted", issue: 261 },
290291 { 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(

Take actor here and call requireRepoAdmin, like listAppFlagValues above. As written, any reader of the repository can see every value.

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;

src/apps/tty.ts:152 also calls appEnv for the app's terminal, but it doesn't pass flagsUrl (or a token to read it with). That makes flag() in the terminal answer defaults while the page answers the forge's value. Pass the same URL and credential there, and add a test that covers it.

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
@@ -23,7 +23,7 @@ import { join } from "node:path";
2323 import type { App } from "../app.ts";
2424 import { getAppByRepo, listApps, type AppRecord } from "../core/apps.ts";
2525 import { resolveAppEnv } from "../core/app_env.ts";
26 import { mintAppToken, renewAppToken, revokeAppToken } from "./token.ts";
26 import { flagsUrl, mintAppToken, renewAppToken, revokeAppToken } from "./token.ts";
2727 import type { ForgeEvent } from "../core/events.ts";
2828 import { announceRun } from "../actions/runs.ts";
2929 import { requeueAbandonedChecks } from "../checks/service.ts";
@@ -1218,6 +1218,12 @@ export class AppsRuntime {
12181218 state.env,
12191219 ),
12201220 forgeToken: token.token,
1221 flagsUrl: flagsUrl(
1222 this.options.forgeUrl,
1223 repo.ownerName,
1224 repo.name,
1225 state.env,
1226 ),
12211227 log: write,
12221228 warm,
12231229 cell: this.cellFor(state.app, state.env),
@@ -1508,6 +1514,12 @@ export class AppsRuntime {
15081514 env,
15091515 ),
15101516 forgeToken: token.token,
1517 flagsUrl: flagsUrl(
1518 this.options.forgeUrl,
1519 repo.ownerName,
1520 repo.name,
1521 env,
1522 ),
15111523 log: write,
15121524 signal: new AbortController().signal,
15131525 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 +32 −2
@@ -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 } {

Low: every ssh session, a guest's included, mints an owner ro token row that lasts 24 hours. It is revoked on exit, but if anything between this line and Bun.spawn throws, the token lives on until it expires. Mint it just before the spawn, or revoke it in a finally.

Medium: this mints the owner's read-only token, which covers every repository the owner can read, into the environment of a terminal opened by whoever is at the keyboard, possibly a guest. Before this pull the terminal had no forge token. Give it a credential limited to this app's flags instead.

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);
152177 const env = appEnv({
178 flagsUrl: flags.flagsUrl,
179 forgeToken: flags.token,
153180 port: live.port,
154181 dataDir: live.dataDir,
155182 env: live.env,
@@ -184,7 +211,10 @@ export async function runAppTty(
184211 env: cell?.env(env) ?? env,
185212 cwd: live.dir,
186213 });
187 void proc.exited.then(() => cell?.close());
214 void proc.exited.then(() => {
215 cell?.close();
216 revokeAppToken(forge.db, flags.tokenId);
217 });
188218 cell?.watch(proc.pid, () => killTree(proc.pid));
189219 forge.log.info("app terminal opened", {
190220 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
@@ -1705,6 +1705,20 @@ export const migrations: readonly string[] = [
17051705 );
17061706 CREATE INDEX passkey_user ON passkey(user_id);
17071707 `,
1708 // 83 — flags for apps (#1572): the values an owner sets for the flags the
1709 // app's own flags.json declares, per scope like the environment, served live
1710 // at FORGE_FLAGS_URL. Plain text: a flag is read by the app's pages, not sealed.
1711 `
1712 CREATE TABLE app_flag (
1713 app_id TEXT NOT NULL REFERENCES app(id) ON DELETE CASCADE,
1714 name TEXT NOT NULL,
1715 scope TEXT NOT NULL DEFAULT 'all'
1716 CHECK (scope IN ('all','production','preview')),
1717 value TEXT NOT NULL,
1718 updated_at TEXT NOT NULL DEFAULT (strftime('%Y-%m-%dT%H:%M:%fZ','now')),
1719 PRIMARY KEY (app_id, name, scope)
1720 );
1721 `,
17081722 ];
17091723
17101724 /**
src/http/api.ts +69
@@ -215,6 +215,10 @@ import {
215215 disableApp,
216216 enableApp,
217217 listAppEnv,
218 listAppFlagValues,
219 readAppFlags,
220 setAppFlagValue,
221 deleteAppFlagValue,
218222 newApp,
219223 openEnvUrl,
220224 redeployEnv,
@@ -4524,6 +4528,71 @@ export function apiRoutes(router: Router<Handler>): void {
45244528 return json(set.value);
45254529 });
45264530
outdated

High: this read is gated only by loadRepo's canRead, so an anonymous request on a public app gets every value, while the settings card, /values and MCP show values to admins only. Gate it on the repository admin, allowing a read-only scope. The app's owner-minted read-only token still passes.

4531 // The app's flags (#1572). GET is what `FORGE_FLAGS_URL` points at: the
4532 // values one environment sees, for anyone who can read the repository (the
4533 // app's own read-only token does). Setting needs admin.
4534 router.add("GET", "/api/v1/repos/:owner/:name/app/flags", (ctx) => {
4535 const repo = loadRepo(ctx);
4536 if (!repo) return notFound();
4537 const asked = ctx.url.searchParams.get("env") ?? "production";
4538 const env = asked === "production" ? "production" : "preview";
4539 const read = readAppFlags(ctx.app, repo, env);
4540 if (!read.ok) return notFound();
4541 return json({ env, flags: read.value });
4542 });
4543
4544 router.add("GET", "/api/v1/repos/:owner/:name/app/flags/values", (ctx) => {
4545 const denied = requireScope(ctx, "admin");
4546 if (denied) return denied;
4547 const repo = loadRepo(ctx);
4548 if (!repo) return notFound();
4549 const listed = listAppFlagValues(ctx.app, ctx.auth.user, repo);
4550 if (!listed.ok) return notFound();
4551 return json({ items: listed.value, next_cursor: null });
4552 });
4553
4554 router.add(
4555 "PUT",
4556 "/api/v1/repos/:owner/:name/app/flags/:flag",
4557 async (ctx) => {
4558 const denied = requireScope(ctx, "admin");
4559 if (denied) return denied;
4560 const repo = loadRepo(ctx);
4561 if (!repo) return notFound();
4562 const input = await body(ctx.request);
4563 const set = setAppFlagValue(
4564 ctx.app,
4565 ctx.auth.user,
4566 repo,
4567 ctx.params.flag ?? "",
4568 str(input.value),
4569 str(input.scope) || "all",
4570 );
4571 if (!set.ok) return respondAccess(set.error, 422);
4572 return json(set.value);
4573 },
4574 );
4575
4576 router.add(
4577 "DELETE",
4578 "/api/v1/repos/:owner/:name/app/flags/:flag",
4579 (ctx) => {
4580 const denied = requireScope(ctx, "admin");
4581 if (denied) return denied;
4582 const repo = loadRepo(ctx);
4583 if (!repo) return notFound();
4584 const removed = deleteAppFlagValue(
4585 ctx.app,
4586 ctx.auth.user,
4587 repo,
4588 ctx.params.flag ?? "",
4589 ctx.url.searchParams.get("scope") ?? "all",
4590 );
4591 if (!removed.ok) return respondAccess(removed.error, 422);
4592 return json({}, 200);
4593 },
4594 );
4595
45274596 router.add(
45284597 "DELETE",
45294598 "/api/v1/repos/:owner/:name/app/env/:var",
src/http/mcp.ts +55
@@ -87,6 +87,11 @@ import {
8787 import { plannerDeclines } from "../crew/autonomy.ts";
8888 import { listActiveRuns } from "../core/runs.ts";
8989 import { scopeAllows } from "../core/tokens.ts";
90 import {
91 deleteAppFlagValue,
92 listAppFlagValues,
93 setAppFlagValue,
94 } from "../actions/apps.ts";
9095 import { getUsersByIds, type User } from "../core/users.ts";
9196 import { openapi } from "../contract/openapi.ts";
9297 import { audit } from "../contract/audit.ts";
@@ -1124,6 +1129,56 @@ const TOOLS: readonly Tool[] = [
11241129 return answer(setAppMembersThrough(ctx.app, user, repo, { members, dryRun }));
11251130 },
outdated

Low: the schema allows 4096 characters, but FLAG_VALUE_MAX is 1024, so a value between the two passes the schema and is then refused as invalid_value. Use FLAG_VALUE_MAX here.

11261131 },
outdated

FLAG_VALUE_MAX is 1024. Make this maxLength match so the schema does not promise 4096.

1132 {
1133 name: "app_flags",
1134 description:
1135 "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.",
1136 inputSchema: {
1137 type: "object",
1138 properties: {
1139 repo: REPO_ARG,
1140 name: { type: "string", maxLength: 64 },
1141 value: { type: "string", maxLength: 4096 },
1142 scope: { type: "string", enum: ["all", "production", "preview"] },
1143 clear: { type: "boolean" },
1144 },
1145 required: ["repo"],
1146 },
1147 writes: true,
1148 run(ctx, user, args) {
1149 const repo = repoArg(ctx, user, args);
1150 if (isAnswer(repo)) return repo;
1151 const name = str(args["name"]);
1152 const scope = str(args["scope"]) || "all";
1153 if (name === "") {
1154 const listed = listAppFlagValues(ctx.app, user, repo);
1155 return listed.ok
1156 ? good({ flags: listed.value })
1157 : bad("not_found", "no such app or repository (owner/name)");
1158 }
1159 if (!scopeAllows(ctx.auth.scope ?? "ro", "admin"))
1160 return bad("forbidden", "changing a flag needs an admin-scope token");
1161 if (args["clear"] === true) {
1162 const removed = deleteAppFlagValue(ctx.app, user, repo, name, scope);
1163 return removed.ok
1164 ? good({ cleared: name, scope })
1165 : bad(
1166 removed.error === "no_such_flag" ? "invalid" : "not_found",
1167 removed.error === "no_such_flag"
1168 ? "no such flag value in that scope"
1169 : "no such app or repository (owner/name)",
1170 );
1171 }
1172 if (typeof args["value"] !== "string")
1173 return bad("invalid", "value is a string");
1174 const set = setAppFlagValue(ctx.app, user, repo, name, args["value"], scope);
1175 return set.ok
1176 ? good(set.value)
1177 : set.error === "not_found"
1178 ? bad("not_found", "no such app or repository (owner/name)")
1179 : bad("invalid", `refused: ${set.error}`);
1180 },
1181 },
11271182 {
11281183 name: "explore",
11291184 description:
src/http/server.ts +8
@@ -294,6 +294,8 @@ import {
294294 appDomainDelete,
295295 appEnvDelete,
296296 appEnvSet,
297 appFlagDelete,
298 appFlagSet,
297299 appSettingsPage,
298300 appSettingsUpdate,
299301 autonomySettingsPage,
@@ -1112,6 +1114,12 @@ export function buildRouter(): Router<Handler> {
11121114 "/:owner/:name/settings/app/env/:var/delete",
11131115 appEnvDelete,
11141116 );
1117 router.add("POST", "/:owner/:name/settings/app/flags", appFlagSet);
1118 router.add(
1119 "POST",
1120 "/:owner/:name/settings/app/flags/:flag/delete",
1121 appFlagDelete,
1122 );
11151123 // `:host` is one path segment — dots and all — like `:var` above it.
11161124 router.add("POST", "/:owner/:name/settings/app/domains", appDomainAdd);
11171125 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(

The names here are free text: the forge never reads the app's flags.json, so the owner cannot see which flags exist, their why or their default, and a typo is set silently. Read the declaration from the default branch and list those flags with their current values.

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="flag_name"
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 and underscores.",

Low: FLAG_NAME also allows -, and the template's own flag is show-terminal-hint. Say "lowercase letters, digits, hyphens and underscores" so the message matches the rule.

FLAG_NAME allows -, and the template's flag is show-terminal-hint. Say 'lowercase letters, digits, - and _'.

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
@@ -183,6 +183,7 @@ describe("the forge over MCP", () => {
183183 "next_steps",
184184 "asked",
185185 "app_members",
186 "app_flags",
186187 "explore",
187188 "feed",
188189 "make_it_yours",
test/web-apps.test.ts +121
@@ -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,123 @@ 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 bad = await web(alice, "/alice/hello/settings/app/flags", {
601 form: { name: "Not A Name", value: "x" },
602 });
603 expect(flashOf(bad)).toContain("lowercase");
604 expect(
605 (
606 await web(bob, "/alice/hello/settings/app/flags", {
607 form: { name: "stolen", value: "x" },
608 })
609 ).status,
610 ).toBe(404);
611 expect(
612 (
613 await web(alice, "/alice/hello/settings/app/flags", {
614 form: { name: "stolen", value: "x" },
615 origin: "https://evil.example",
616 })
617 ).status,
618 ).toBe(403);
619
620 const cleared = await web(
621 alice,
622 "/alice/hello/settings/app/flags/dark_mode/delete",
623 { form: { scope: "preview" } },
624 );
625 expect(cleared.status).toBe(303);
626 expect(flashOf(cleared)).toContain("dark_mode is cleared");
627 expect(resolveAppFlags(app.db, appId, "pull-1")).toEqual({});
628 expect(
629 (
630 await web(bob, "/alice/hello/settings/app/flags/dark_mode/delete", {
631 form: { scope: "preview" },
632 })
633 ).status,
634 ).toBe(404);
635
636 // The same actions through MCP.
637 const admin = createToken(app.db, user("alice").id, "flags", "admin").token;
638 const ro = createToken(app.db, user("alice").id, "flags-ro", "ro").token;
639 const tool = async (token: string, args: Record<string, unknown>) => {
640 const res = await fetch(`${base}/mcp`, {
641 method: "POST",
642 headers: {
643 "content-type": "application/json",
644 accept: "application/json, text/event-stream",
645 authorization: `Bearer ${token}`,
646 },
647 body: JSON.stringify({
648 jsonrpc: "2.0",
649 id: 1,
650 method: "tools/call",
651 params: { name: "app_flags", arguments: { repo: "alice/hello", ...args } },
652 }),
653 });
654 const out = (await res.json()) as any;
655 const text: string = out.result.content[0].text;
656 const error = out.result.isError === true;
657 return { error, body: error ? text : JSON.parse(text) };
658 };
659 expect((await tool(admin, { name: "beta", value: "on" })).error).toBe(false);
660 const all = await tool(admin, {});
661 expect(all.body.flags.map((f: any) => f.name)).toEqual(["beta"]);
662 expect((await tool(ro, { name: "beta", value: "off" })).error).toBe(true);
663 expect((await tool(ro, { name: "beta", clear: true })).error).toBe(true);
664 expect(resolveAppFlags(app.db, appId, "production")).toEqual({ beta: "on" });
665 expect((await tool(admin, { name: "beta", clear: true })).error).toBe(false);
666 expect(resolveAppFlags(app.db, appId, "production")).toEqual({});
667
668 // Every change left an event.
669 const kinds = listEvents(app.db, {}).map((e) => e.kind);
670 expect(kinds.filter((k) => k === "app.flag_set").length).toBeGreaterThanOrEqual(2);
671 expect(kinds.filter((k) => k === "app.flag_deleted").length).toBeGreaterThanOrEqual(2);
672 const named = (kind: string) =>
673 listEvents(app.db, { kind }).map(
674 (e) => (e.payload as { name: string }).name,
675 );
676 expect(named("app.flag_set")).toContain("dark_mode");
677 expect(named("app.flag_deleted")).toContain("dark_mode");
678
679 // The terminal is told the forge's flags URL and holds a token that reads them.
680 await tool(admin, { name: "live", value: "yes" });
681 const flags = terminalFlags(
682 app,
683 base,
684 hello,
685 { app: getAppByRepo(app.db, hello.id)!, env: "production" },
686 );
687 expect(flags.flagsUrl).toBe(
688 `${base}/api/v1/repos/alice/hello/app/flags?env=production`,
689 );
690 const read = await fetch(flags.flagsUrl, {
691 headers: { authorization: `Bearer ${flags.token}` },
692 });
693 expect(((await read.json()) as any).flags).toEqual({ live: "yes" });
694 });
695
575696 test("a plain repository becomes an app from its settings, and stops being one", async () => {
576697 const plain = getRepo(app.db, "alice", "plain")!;
577698 const section = await bodyOf(alice, "/alice/plain/settings/app");

↑↓ navigate ↵ open ⌘↵ its app esc close

Keyboard shortcuts

Docs