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

The cache spectrum, chosen on purpose: in-process snapshots, SQLite, the edge's own cache, and a global read-cheap config pushed to the edge in seconds; offered to apps #1496

Closed opened this in answer to
Closed without merging

scout/forge:scout/1138-the-cache-spectrum-chosen-on-purpose-in → main 6 commits fork 5 threads · 5 unresolved

  • Closed without merging. Nothing was applied to main.

Review

Sign in to review this change.
24 files changed +1636 −6
README.md +13
@@ -237,6 +237,19 @@ something in the 60–110 MB range; `dist/` is gitignored and binaries are never
237237 committed). Until you build it, `bun run src/cli/main.ts …` is the same
238238 program.
239239
240 ## Config and the cache spectrum
241
242 Flags and settings live in a config store: reads come from memory, one write
243 makes one snapshot, other processes see it within a second and the edge
244 within seconds. Read or change them where you are:
245
246 - terminal: `forge config [app] [--changes]`, `forge config set [app] flag=true --why "reason"`
247 - MCP: `config_get` (with `changes` for who changed what and why) and `config_set` (`why` required, admin-scope token)
248 - HTTP: `GET`/`PATCH /api/v1/config` and `/api/v1/apps/:slug/config` (`?changes=1`)
249
250 An app's config needs admin on the app to change; the forge's own needs a
251 site admin. Which data lives on which cache rung, and why: `docs/CACHE.md`.
252
240253 ## Apps
241254
242255 A repository that runs. Press **New app**, give it a name and — if you like —
docs/CACHE.md added +73
@@ -0,0 +1,73 @@
1 # The cache spectrum
2
3 Each kind of data lives on one rung, chosen on purpose. Climb only when the
4 rung below is too slow for who reads it; never keep the same fact as truth on
5 two rungs.
6
7 | Rung | What lives there | Read cost | Changes | Truth? |
8 |---|---|---|---|---|
9 | **git** | code, `forge.json`, the repository's own files | a `git` read | a push | yes — the only truth (CLAUDE.md, invariant 4) |
10 | **SQLite** | the derived index (issues, pulls, events), config rows and their ledger (`config`, `config_change`), sessions | one indexed query | every action | derived from git, except config and sessions |
11 | **process** | the current config snapshot of each scope, held by every forge process | a map lookup | refreshed on the `config.set` bus event, or by a half-second poll for another process's write | a copy of SQLite |
12 | **edge** | the signed snapshot file, at a stable URL and (behind Cloudflare) in KV | none of the forge's | published within seconds of a write | a copy of SQLite |
13 | **validator** | `ETag` + `If-None-Match`: the client keeps the body, the forge answers `304` | a lookup | per request | n/a |
14
15 ## Which data, which rung
16
17 - **Flags, settings, the forge's and an app's config** — small, read
18 everywhere, written rarely: the **config store** (`src/core/config.ts`).
19 Truth in SQLite, copy in every process, signed copy on the edge. Values
20 are public by contract; secrets go in the secret store, never here.
21 - **Pages, lists, issues, pulls** — large, personal, changing: SQLite, with
22 `fragment` or `config` validators. Not the edge.
23 - **Content-addressed assets** (`/assets/<hash>.css`) — `immutable`.
24 - **Repository contents** — git, read through the pooled `cat-file` readers.
25
26 ## One helper per kind
27
28 `Cache-Control` and `ETag` come from `cacheHeaders(kind, etag)` and
29 `cached(...)` in `src/http/respond.ts`; a route names the kind and never
30 writes the header. The table `CACHE_CONTROL` is the single source and
31 `test/config-store.test.ts` checks this page against it.
32
33 | Kind | `Cache-Control` | `ETag` | Used for |
34 |---|---|---|---|
35 | `immutable` | `public, max-age=31536000, immutable` | optional | the built script and the stylesheet (`web/asset.ts`) |
36 | `edge` | `public, max-age=5, stale-while-revalidate=30` | snapshot id | the published snapshot, the forge's public config |
37 | `config` | `private, no-cache` | snapshot id | an app's config for its signed-in reader |
38 | `live` | `no-store` | never | anything that must not be kept |
39
40 Routes that predate the helper still set their own headers
41 (`web/pages/*`, `apps/proxy.ts`); they move to a kind as they are touched.
42
43 ## The edge rung
44
45 Every write produces one snapshot id. Each process that learns of it
46 publishes `<data>/edge/config/<name>.json`, an Ed25519-signed
47 `{ payload, sig }`, served at `/edge/config/<name>.json` (`forge`, or
48 `app-<id>` for an app whose repository anyone can read). The public key is
49 at `/edge/config/key.pem`. With `FORGE_CF_ACCOUNT`, `FORGE_CF_KV_NAMESPACE`
50 and `FORGE_CF_API_TOKEN` set, the same bytes are also `PUT` to that KV
51 namespace under the same name, so a Worker reads flags without the forge.
52
53 **A stale edge is visible.** Every response carries `X-Forge-Config`, the id
54 of the snapshot this forge holds; compare it with the `snapshot` in the file
55 you have (`isStale` in `src/cloud/edge.ts`).
56
57 ## Apps
58
59 `GET /api/v1/apps/:slug/config` (any credential that can read the app, so
60 the read-only token an app starts with) returns
61 `{ snapshot, version, values, updated_at }` with the id as `ETag`; send it
62 back as `If-None-Match` for a `304`. `PATCH` with `{ "set": { key: value |
63 null }, "why": "…" }` needs an admin token and repository admin. The edge
64 file of a public app is the same data without the forge.
65
66 From an assistant: `config_get` / `config_set` (MCP). From a terminal: `forge config`.
67
68 ## Checking the choice
69
70 `GET /api/v1/cache` (admin) returns this process's hit/miss counts per rung:
71 `process` (snapshot already held), `sqlite` (loaded or refreshed), `edge`
72 (published file served), `validator` (`304`s). The counters are in memory
73 and reset with the process.
forge.json +2 −1
@@ -1,6 +1,7 @@
11 {
22 "egress": [
3 "api.anthropic.com"
3 "api.anthropic.com",
4 "api.cloudflare.com"
45 ],
56 "app": {
67 "run": "bun run src/main.ts",
scripts/gate.ts +2
@@ -41,6 +41,7 @@ export const GATE: readonly string[] = [
4141 "test/crew-brief-audience.test.ts",
4242 "test/crew.test.ts",
4343 "test/commit-identity.test.ts",
44 "test/config-store.test.ts",
4445 "test/enterable-apps.test.ts",
4546 "test/event-order.test.ts",
4647 "test/refresh-meta.test.ts",
@@ -227,6 +228,7 @@ export const GATE: readonly string[] = [
227228 "test/qr.test.ts",
228229 "test/branches.test.ts",
229230 "test/cli-sync.test.ts",
231 "test/cli-config.test.ts",
230232 "test/code.test.ts",
231233 "test/counts.test.ts",
232234 "test/crew-loop.test.ts",
src/actions/config.ts added +84
@@ -0,0 +1,84 @@
1 /**
2 * Read and change the config store (`core/config.ts`, `docs/CACHE.md`) as a
3 * person or agent: the forge's own flags, or an app's. The routes, the MCP
4 * tools `config_get` / `config_set` and `forge config` all answer from here.
5 *
6 * - The forge's config is public to read; changing it needs a site admin.
7 * - An app's config is read by whoever may read the app and changed by
8 * whoever may administer it.
9 * - A change names its reason: the ledger keeps who, what keys, and why.
10 */
11
12 import type { App } from "../app.ts";
13 import { getAppByRepo } from "../core/apps.ts";
14 import {
15 FORGE_SCOPE,
16 appScope,
17 type ConfigError,
18 type ConfigValue,
19 type Snapshot,
20 } from "../core/config.ts";
21 import { canAdmin, canRead, type Repo } from "../core/repos.ts";
22 import type { User } from "../core/users.ts";
23 import { err, ok, type Result } from "../kernel/result.ts";
24
25 export type ConfigAccessError = ConfigError | "not_found" | "forbidden";
26
27 export interface ConfigView {
28 readonly scope: string;
29 readonly snapshot: string;
30 readonly version: number;
31 readonly values: Readonly<Record<string, ConfigValue>>;
32 readonly updatedAt: string;
33 /** Newest first; only when asked for. */
34 readonly changes?: ReturnType<App["configs"]["changes"]>;
35 }
36
37 function view(app: App, snap: Snapshot, changes: boolean): ConfigView {
38 return {
39 scope: snap.scope,
40 snapshot: snap.id,
41 version: snap.version,
42 values: snap.values,
43 updatedAt: snap.updatedAt,
44 ...(changes ? { changes: app.configs.changes(snap.scope) } : {}),
45 };
46 }
47
48 /** The scope a repository's app keeps, or the forge's when `repo` is absent. */
49 function scopeOf(
50 app: App,
51 actor: User | undefined,
52 repo: Repo | undefined,
53 need: "read" | "admin",
54 ): Result<string, ConfigAccessError> {
55 if (repo === undefined) return ok(FORGE_SCOPE);
56 const record = getAppByRepo(app.db, repo.id);
57 if (!record || !canRead(app.db, repo, actor)) return err("not_found");
58 if (need === "admin" && !canAdmin(app.db, repo, actor)) return err("forbidden");
59 return ok(appScope(record.id));
60 }
61
62 export function readConfig(
63 app: App,
64 actor: User | undefined,
65 repo: Repo | undefined,
66 changes = false,
67 ): Result<ConfigView, ConfigAccessError> {
68 const scope = scopeOf(app, actor, repo, "read");
69 return scope.ok ? ok(view(app, app.configs.snapshot(scope.value), changes)) : scope;
70 }
71
72 export function changeConfig(
73 app: App,
74 actor: User,
75 repo: Repo | undefined,
76 set: Record<string, unknown>,
77 why: string,
78 ): Result<ConfigView, ConfigAccessError> {
79 if (repo === undefined && actor.isAdmin !== true) return err("forbidden");
80 const scope = scopeOf(app, actor, repo, "admin");
81 if (!scope.ok) return scope;
82 const made = app.configs.set(scope.value, set, actor.username, why);
83 return made.ok ? ok(view(app, made.value, false)) : made;
84 }
src/app.ts +23 −1
@@ -12,6 +12,8 @@ import { mkdirSync } from "node:fs";
1212 import { join, resolve } from "node:path";
1313 import { migrations } from "./core/schema.ts";
1414 import { dropLegacyNewAccountGuards } from "./core/schema.ts";
15 import { ConfigStore } from "./core/config.ts";
16 import { EdgePublisher, kvFromEnv } from "./cloud/edge.ts";
1517 import { EventBus } from "./core/events.ts";
1618 import { follow } from "./core/following.ts";
1719 import { enqueueForEvent } from "./core/webhooks.ts";
@@ -134,6 +136,10 @@ export interface App {
134136 readonly log: Log;
135137 readonly reposRoot: string;
136138 readonly socketPath: string;
139 /** Small read-mostly values, held in memory (`core/config.ts`). */
140 readonly configs: ConfigStore;
141 /** Where config snapshots are published for the edge (`cloud/edge.ts`); made on first use. */
142 edge(): EdgePublisher;
137143 /** Where the internal listener answers: `socketPath`, or a loopback port (`git/hook-address.ts`). */
138144 readonly hookAddress: { current: string };
139145 /** Per-boot secret every internal request must carry (`FORGE_HOOK_SECRET` in a hook's env). */
@@ -166,11 +172,26 @@ export function createApp(config: ForgeConfig): App {
166172 // and the forks whose default branch is still a copy of this one's.
167173 follow({ db, reposRoot, bus });
168174
175 const log = createLog("forge");
176 const configs = new ConfigStore(db, bus);
177 let publisher: EdgePublisher | undefined;
178 const edge = (): EdgePublisher =>
179 (publisher ??= new EdgePublisher(dataDir, { kv: kvFromEnv(process.env) }));
180 // A snapshot this process newly holds is published within the same tick
181 // (the file) and the next round trip (KV).
182 configs.onChange((snap) => {
183 edge()
184 .publish(snap)
185 .catch((error) => log.error("edge publish failed", { error: String(error) }));
186 });
187
169188 return {
170189 config: { ...config, dataDir },
190 configs,
191 edge,
171192 db,
172193 bus,
173 log: createLog("forge"),
194 log,
174195 reposRoot,
175196 // This process's own: two forges share a data directory for the length
176197 // of a release, and each spawns git with its own socket in the env.
@@ -183,6 +204,7 @@ export function createApp(config: ForgeConfig): App {
183204 // otherwise. One data dir is one forge, so closing the forge is where
184205 // that is said.
185206 closeReadersUnder(reposRoot);
207 configs.stop();
186208 db.close();
187209 },
188210 };
src/apps/scaffold.ts +122
@@ -48,6 +48,7 @@ export function scaffoldFiles(input: ScaffoldInput): FileWrite[] {
4848 },
4949 { path: "design/tokens.json", content: TOKENS_JSON },
5050 { path: "src/env.ts", content: ENV_TS },
51 { path: "src/flags.ts", content: FLAGS_TS },
5152 { path: "src/who.ts", content: WHO_TS },
5253 { path: "src/can.ts", content: CAN_TS },
5354 { path: "src/contract.ts", content: CONTRACT_TS },
@@ -69,6 +70,7 @@ export function scaffoldFiles(input: ScaffoldInput): FileWrite[] {
6970 { path: "static/app.css", content: APP_CSS },
7071 { path: "static/live.js", content: LIVE_JS },
7172 { path: "src/who.test.ts", content: WHO_TEST },
73 { path: "src/flags.test.ts", content: FLAGS_TEST },
7274 { path: "src/db.test.ts", content: DB_TEST },
7375 { path: "src/actions.test.ts", content: ACTIONS_TEST },
7476 { path: "src/contract.test.ts", content: CONTRACT_TEST },
@@ -264,6 +266,9 @@ preview at its own address, deployed from your branch as you push.
264266 and nothing more: the terminal gates its reads and writes exactly as the
265267 page does (\`FORGE_APP_USER_ROLE\` is the forge's word on who is there), and a
266268 write made there reaches web viewers live like any other.
269 - Flags and settings live in the forge's config store, not in code or the
270 database: \`flag(name, fallback)\` from \`src/flags.ts\` is a lookup in a
271 snapshot held in memory (\`docs/CACHE.md\` in the forge). Values are public.
267272 - Keep it dependency-free unless a dependency is clearly worth it, and say
268273 why in the pull. A dependency is code you now maintain.
269274 - When you are done, push and stop. Your last message becomes the pull's
@@ -408,6 +413,123 @@ export const publicOrigin: string = new URL(
408413 export const forgeUrl: string | undefined = process.env.FORGE_URL;
409414 /** The key the forge signs identities with (\`who.ts\`). Unset, everyone is anonymous. */
410415 export const identityKey: string = process.env.FORGE_APP_IDENTITY_KEY ?? "";
416 /** Where the forge's API is, and the read-only token the forge gave this process (\`flags.ts\`). */
417 export const forgeApiUrl: string | undefined = process.env.FORGE_API_URL;
418 export const forgeToken: string | undefined = process.env.FORGE_TOKEN;
419 `;
420
421 // Flags: the forge's config store, held in memory (docs/CACHE.md).
422 const FLAGS_TS = `/**
423 * Flags and settings from the forge's config store (\`GET
424 * /api/v1/apps/<slug>/config\`). The current snapshot is held in memory, so
425 * \`flag()\` is a map lookup that never waits on the network; \`refresh()\`
426 * revalidates with the snapshot id as the ETag (a 304 costs the forge one
427 * lookup), and \`start()\` does it every few seconds. Values are public by
428 * contract: no secrets here. Change them with \`PATCH\` and a \`why\`.
429 * Without a forge to ask, every flag is its fallback.
430 */
431
432 import { forgeApiUrl, forgeToken, publicOrigin } from "./env.ts";
433
434 export type FlagValue = string | number | boolean | null | FlagValue[] | { [k: string]: FlagValue };
435
436 /** \`<slug>.<domain>\` or \`<slug>--<n>.<domain>\`: the app's slug. */
437 export function slugOf(origin: string): string {
438 return new URL(origin).hostname.split(".")[0]!.split("--")[0]!;
439 }
440
441 export class Flags {
442 /** The id of the snapshot held; changes with every write. \`"0"\` before the first answer. */
443 snapshot = "0";
444 private values: Record<string, FlagValue> = {};
445 private timer: ReturnType<typeof setInterval> | undefined;
446
447 constructor(
448 private readonly url: string | undefined,
449 private readonly token: string | undefined,
450 private readonly slug: string,
451 private readonly fetcher: typeof fetch = fetch,
452 ) {}
453
454 flag<T extends FlagValue>(name: string, fallback: T): T {
455 const value = this.values[name];
456 return value === undefined ? fallback : (value as T);
457 }
458
459 /** Ask the forge whether the snapshot moved; true when this call changed it. */
460 async refresh(): Promise<boolean> {
461 if (this.url === undefined || this.token === undefined) return false;
462 try {
463 const res = await this.fetcher(\`\${this.url}/apps/\${this.slug}/config\`, {
464 headers: {
465 authorization: \`Bearer \${this.token}\`,
466 ...(this.snapshot === "0" ? {} : { "if-none-match": \`"\${this.snapshot}"\` }),
467 },
468 });
469 if (res.status !== 200) return false;
470 const body = (await res.json()) as { snapshot?: unknown; values?: unknown };
471 if (typeof body.snapshot !== "string" || typeof body.values !== "object" || body.values === null)
472 return false;
473 this.values = body.values as Record<string, FlagValue>;
474 this.snapshot = body.snapshot;
475 return true;
476 } catch {
477 // The forge being away keeps the last snapshot; flags are never a reason to fail a request.
478 return false;
479 }
480 }
481
482 start(ms = 5000): void {
483 if (this.timer !== undefined) return;
484 void this.refresh();
485 this.timer = setInterval(() => void this.refresh(), ms);
486 this.timer.unref?.();
487 }
488 }
489
490 export const flags = new Flags(forgeApiUrl, forgeToken, slugOf(publicOrigin));
491 `;
492
493 const FLAGS_TEST = `import { expect, test } from "bun:test";
494 import { Flags, slugOf } from "./flags.ts";
495
496 const forge = (snapshot: string, values: object, seen: string[]): typeof fetch =>
497 (async (_url: string, init: RequestInit) => {
498 const sent = (init.headers as Record<string, string>)["if-none-match"];
499 seen.push(sent ?? "");
500 if (sent === \`"\${snapshot}"\`) return new Response(null, { status: 304 });
501 return Response.json({ snapshot, values });
502 }) as unknown as typeof fetch;
503
504 test("a flag is its fallback until the forge answers, then the held value", async () => {
505 const seen: string[] = [];
506 const f = new Flags("http://forge/api/v1", "t", "notes", forge("s1", { beta: true }, seen));
507 expect(f.flag<boolean>("beta", false)).toBe(false);
508 expect(await f.refresh()).toBe(true);
509 expect(f.flag<boolean>("beta", false)).toBe(true);
510 expect(f.snapshot).toBe("s1");
511 });
512
513 test("an unchanged snapshot is revalidated, not re-read", async () => {
514 const seen: string[] = [];
515 const f = new Flags("http://forge/api/v1", "t", "notes", forge("s1", { a: 1 }, seen));
516 await f.refresh();
517 expect(await f.refresh()).toBe(false);
518 expect(seen).toEqual(["", '"s1"']);
519 });
520
521 test("no forge, or a forge that is down, leaves the fallbacks", async () => {
522 expect(await new Flags(undefined, undefined, "notes").refresh()).toBe(false);
523 const down = (async () => { throw new Error("away"); }) as unknown as typeof fetch;
524 const f = new Flags("http://forge/api/v1", "t", "notes", down);
525 expect(await f.refresh()).toBe(false);
526 expect(f.flag("x", 3)).toBe(3);
527 });
528
529 test("the slug is the hostname's first label, without a preview number", () => {
530 expect(slugOf("https://notes.apps.example")).toBe("notes");
531 expect(slugOf("https://notes--3.apps.example")).toBe("notes");
532 });
411533 `;
412534
413535 // Identity: the forge's signed headers, or anon.
src/cli/api.ts +33
@@ -36,6 +36,22 @@ export interface Whoami {
3636 readonly displayName: string;
3737 }
3838
39 export interface ConfigRead {
40 readonly snapshot: string;
41 readonly version: number;
42 readonly values: Record<string, unknown>;
43 readonly changes?: readonly {
44 version: number;
45 keys: string[];
46 by: string;
47 why: string;
48 at: string;
49 }[];
50 }
51
52 const configPath = (slug?: string): string =>
53 slug === undefined ? "/api/v1/config" : `/api/v1/apps/${encodeURIComponent(slug)}/config`;
54
3955 export class ForgeApi {
4056 /** True once `pins()` has had to fall back, so the CLI can say it once. */
4157 pinsUnavailable = false;
@@ -154,6 +170,23 @@ export class ForgeApi {
154170 );
155171 }
156172
173 /** The forge's config, or an app's by slug; `changes` adds the ledger. */
174 config(slug?: string, changes = false): Promise<ApiResult<ConfigRead>> {
175 return this.call<ConfigRead>(`${configPath(slug)}${changes ? "?changes=1" : ""}`);
176 }
177
178 /** One write: a value sets, `null` removes; `why` is kept in the ledger. */
179 setConfig(
180 slug: string | undefined,
181 set: Record<string, unknown>,
182 why: string,
183 ): Promise<ApiResult<ConfigRead>> {
184 return this.call<ConfigRead>(configPath(slug), {
185 method: "PATCH",
186 body: JSON.stringify({ set, why }),
187 });
188 }
189
157190 /** The page a person would open in a browser. */
158191 webUrl(owner: string, name: string): string {
159192 return `${this.url}/${encode(owner)}/${encode(name)}`;
src/cli/flags.ts added +39
@@ -0,0 +1,39 @@
1 /**
2 * `forge config` operands: an optional app slug and, for a change,
3 * `key=value` pairs. A value is JSON when it parses (`true`, `3`, `null`
4 * removes the key) and the text itself when it does not.
5 */
6
7 export interface ConfigOperands {
8 readonly slug: string | undefined;
9 readonly set: Record<string, unknown>;
10 }
11
12 const SLUG = /^[a-z0-9][a-z0-9-]{0,62}$/;
13
14 export function parseConfigOperands(
15 operands: readonly string[],
16 ): ConfigOperands | string {
17 let slug: string | undefined;
18 const set: Record<string, unknown> = {};
19 for (const operand of operands) {
20 const eq = operand.indexOf("=");
21 if (eq < 0) {
22 if (slug !== undefined || !SLUG.test(operand))
23 return `expected an app name or key=value, got "${operand}"`;
24 slug = operand;
25 continue;
26 }
27 const key = operand.slice(0, eq);
28 if (key === "") return `missing key in "${operand}"`;
29 const raw = operand.slice(eq + 1);
30 let value: unknown = raw;
31 try {
32 value = JSON.parse(raw);
33 } catch {
34 // Plain text stays text.
35 }
36 set[key] = value;
37 }
38 return { slug, set };
39 }
src/cli/main.ts +46 −1
@@ -24,6 +24,7 @@ import {
2424 saveConfig,
2525 type Config,
2626 } from "./config.ts";
27 import { parseConfigOperands } from "./flags.ts";
2728 import { systemNotifier } from "./notify.ts";
2829 import { cell, createOut, type Out } from "./out.ts";
2930 import { dirtyCount, printReport, settled, since } from "./report.ts";
@@ -51,7 +52,7 @@ export const EXIT = {
5152 partial: 4,
5253 } as const;
5354
54 const VALUE_FLAGS = ["token", "interval", "root", "url", "limit"];
55 const VALUE_FLAGS = ["token", "interval", "root", "url", "limit", "why"];
5556
5657 export async function main(argv: readonly string[]): Promise<number> {
5758 const args = parseArgs(argv, { values: VALUE_FLAGS });
@@ -95,6 +96,8 @@ export async function main(argv: readonly string[]): Promise<number> {
9596 return setPin(out, args, false);
9697 case "open":
9798 return openRepo(out, args);
99 case "config":
100 return configCommand(out, args);
98101 case "ui":
99102 return openTui(out, args);
100103 default:
@@ -121,6 +124,8 @@ function usage(out: Out): void {
121124 out.line(b(" forge pin <owner/name>"));
122125 out.line(b(" forge unpin <owner/name>"));
123126 out.line(b(" forge open <owner/name>") + " [--web]");
127 out.line(b(" forge config [app]") + " [--changes] [--json]");
128 out.line(b(" forge config set [app] k=v ...") + " --why \"reason\"");
124129 out.line();
125130 out.line(
126131 out.paint(` config ${configPath()} root ${rootDir()}`, out.c.faint),
@@ -366,6 +371,46 @@ async function setPin(out: Out, args: Args, on: boolean): Promise<number> {
366371 return EXIT.ok;
367372 }
368373
374 /** Read the config store, or change it: `forge config set app flag=true --why "…"`. */
375 async function configCommand(out: Out, args: Args): Promise<number> {
376 const setting = args.positional[0] === "set";
377 const operands = parseConfigOperands(
378 setting ? args.positional.slice(1) : args.positional,
379 );
380 if (typeof operands === "string") {
381 out.err(`forge config: ${operands}`);
382 return EXIT.usage;
383 }
384 const why = args.value("why") ?? "";
385 if (setting && (why.trim() === "" || Object.keys(operands.set).length === 0)) {
386 out.err('forge config set: give key=value pairs and --why "the reason"');
387 return EXIT.usage;
388 }
389 const loaded = await requireConfig(out);
390 if (typeof loaded === "number") return loaded;
391 const api = new ForgeApi(loaded.url, loaded.token);
392 const result = setting
393 ? await api.setConfig(operands.slug, operands.set, why)
394 : await api.config(operands.slug, args.flag("changes"));
395 if (!result.ok) {
396 out.err(`forge config: ${result.error.message}`);
397 return EXIT.failed;
398 }
399 if (args.flag("json")) {
400 out.line(JSON.stringify(result.value));
401 return EXIT.ok;
402 }
403 const snap = result.value;
404 out.line(out.paint(`snapshot ${snap.snapshot} · version ${snap.version}`, out.c.faint));
405 for (const [k, v] of Object.entries(snap.values))
406 out.line(`${k} = ${JSON.stringify(v)}`);
407 for (const c of snap.changes ?? [])
408 out.line(
409 out.paint(`v${c.version} ${c.at} ${c.by}: ${c.keys.join(", ")} — ${c.why}`, out.c.faint),
410 );
411 return EXIT.ok;
412 }
413
369414 async function openRepo(out: Out, args: Args): Promise<number> {
370415 const ref = parseRepoRef(args.positional[0]);
371416 if (ref === undefined) {
src/cloud/edge.ts added +169
@@ -0,0 +1,169 @@
1 /**
2 * The edge rung of the cache spectrum (`docs/CACHE.md`): the config store's
3 * snapshots, published where readers need not touch the forge.
4 *
5 * Every snapshot becomes one signed file, `<data>/edge/<name>.json`, served
6 * at the stable URL `/edge/config/<name>.json` (and any CDN in front caches
7 * that URL). Where the forge runs behind Cloudflare, the same bytes are also
8 * written to a KV namespace, so Workers read flags at the edge itself.
9 *
10 * The file is `{ payload, sig }`: `payload` is the snapshot as a JSON
11 * string, `sig` an Ed25519 signature over exactly those bytes, so nothing
12 * between the forge and the reader can alter it. The public key is served at
13 * `/edge/config/key.pem`; the private key lives in the data directory and
14 * never leaves it.
15 *
16 * A stale edge is visible: every forge response carries `X-Forge-Config`,
17 * the id of the snapshot the forge holds, and a reader that kept an older id
18 * can see that it lags.
19 */
20
21 import {
22 createPrivateKey,
23 createPublicKey,
24 generateKeyPairSync,
25 sign,
26 verify,
27 type KeyObject,
28 } from "node:crypto";
29 import {
30 chmodSync,
31 existsSync,
32 mkdirSync,
33 readFileSync,
34 renameSync,
35 writeFileSync,
36 } from "node:fs";
37 import { join } from "node:path";
38 import { id } from "../kernel/id.ts";
39 import type { ConfigValue, Snapshot } from "../core/config.ts";
40
41 export interface KvTarget {
42 readonly account: string;
43 readonly namespace: string;
44 readonly token: string;
45 }
46
47 /** The Cloudflare KV target from the environment, when all three are set. */
48 export function kvFromEnv(env: Record<string, string | undefined>): KvTarget | undefined {
49 const account = (env.FORGE_CF_ACCOUNT ?? "").trim();
50 const namespace = (env.FORGE_CF_KV_NAMESPACE ?? "").trim();
51 const token = (env.FORGE_CF_API_TOKEN ?? "").trim();
52 const safe = /^[0-9a-zA-Z]{1,64}$/;
53 if (!safe.test(account) || !safe.test(namespace) || token === "") return undefined;
54 return { account, namespace, token };
55 }
56
57 /** The file name a scope is published under, or undefined for a bad scope. */
58 export function edgeName(scope: string): string | undefined {
59 if (scope === "forge") return "forge";
60 const m = /^app\/([0-9a-z]{1,40})$/.exec(scope);
61 return m ? `app-${m[1]}` : undefined;
62 }
63
64 export interface EdgeFile {
65 readonly payload: string;
66 readonly sig: string;
67 }
68
69 export interface Published {
70 readonly scope: string;
71 readonly snapshot: string;
72 readonly version: number;
73 readonly values: Record<string, ConfigValue>;
74 readonly at: string;
75 }
76
77 function loadKey(dir: string): { priv: KeyObject; publicPem: string } {
78 const path = join(dir, "signing.pem");
79 if (!existsSync(path)) {
80 mkdirSync(dir, { recursive: true });
81 const { privateKey } = generateKeyPairSync("ed25519");
82 const tmp = join(dir, `signing.${id()}.tmp`);
83 writeFileSync(tmp, privateKey.export({ type: "pkcs8", format: "pem" }), { mode: 0o600 });
84 chmodSync(tmp, 0o600);
85 // rename wins the race between two processes booting together
86 if (!existsSync(path)) renameSync(tmp, path);
87 }
88 const priv = createPrivateKey(readFileSync(path));
89 const publicPem = createPublicKey(priv).export({ type: "spki", format: "pem" }).toString();
90 return { priv, publicPem };
91 }
92
93 /** Sign a snapshot into the file the edge serves. */
94 export function signSnapshot(priv: KeyObject, snap: Snapshot): EdgeFile {
95 const published: Published = {
96 scope: snap.scope,
97 snapshot: snap.id,
98 version: snap.version,
99 values: { ...snap.values },
100 at: snap.updatedAt,
101 };
102 const payload = JSON.stringify(published);
103 return { payload, sig: sign(null, Buffer.from(payload), priv).toString("base64") };
104 }
105
106 /** The snapshot a file carries, if its signature holds under `publicPem`. */
107 export function verifyEdgeFile(file: unknown, publicPem: string): Published | undefined {
108 if (typeof file !== "object" || file === null) return undefined;
109 const { payload, sig } = file as Record<string, unknown>;
110 if (typeof payload !== "string" || typeof sig !== "string") return undefined;
111 try {
112 const good = verify(null, Buffer.from(payload), createPublicKey(publicPem), Buffer.from(sig, "base64"));
113 return good ? (JSON.parse(payload) as Published) : undefined;
114 } catch {
115 return undefined;
116 }
117 }
118
119 export class EdgePublisher {
120 readonly dir: string;
121 readonly publicPem: string;
122 private readonly priv: KeyObject;
123
124 constructor(
outdated

Only the tests call this. Either the forge or the scaffolded flags.ts uses it (compare X-Forge-Config against the snapshot it holds), or it is dead code.

125 dataDir: string,
126 private readonly options: { kv?: KvTarget | undefined; fetch?: typeof fetch | undefined } = {},
127 ) {
128 this.dir = join(dataDir, "edge");
129 const key = loadKey(this.dir);
130 this.priv = key.priv;
131 this.publicPem = key.publicPem;
132 mkdirSync(join(this.dir, "config"), { recursive: true });
133 writeFileSync(join(this.dir, "config", "key.pem"), this.publicPem);
134 }
135
136 pathOf(scope: string): string | undefined {
137 const name = edgeName(scope);
138 return name === undefined ? undefined : join(this.dir, "config", `${name}.json`);
139 }
140
141 /** Write the signed file (atomically), then KV when configured. */
142 async publish(snap: Snapshot): Promise<void> {
143 const path = this.pathOf(snap.scope);
144 if (path === undefined) return;
145 const body = JSON.stringify(signSnapshot(this.priv, snap));
146 const tmp = `${path}.${id()}.tmp`;
147 writeFileSync(tmp, body);
148 renameSync(tmp, path);
149 const kv = this.options.kv;
150 if (kv === undefined) return;
151 const name = edgeName(snap.scope)!;
152 const url =
153 `https://api.cloudflare.com/client/v4/accounts/${kv.account}` +
154 `/storage/kv/namespaces/${kv.namespace}/values/${name}`;
155 const res = await (this.options.fetch ?? fetch)(url, {
156 method: "PUT",
157 headers: { authorization: `Bearer ${kv.token}`, "content-type": "application/json" },
158 body,
159 });
160 if (!res.ok) throw new Error(`edge kv put ${name}: ${res.status}`);
161 }
162
163 /** The published file for a scope, as text, or undefined when none. */
164 read(scope: string): string | undefined {
165 const path = this.pathOf(scope);
166 if (path === undefined || !existsSync(path)) return undefined;
167 return readFileSync(path, "utf8");
168 }
169 }
src/core/config.ts added +301
@@ -0,0 +1,301 @@
1 /**
2 * The config store — small values read everywhere and changed rarely: flags,
3 * settings, an app's configuration. The middle rung of the cache spectrum
4 * (`docs/CACHE.md`).
5 *
6 * - A scope (`forge`, or `app/<id>`) holds one map of key to JSON value.
7 * One write is one new snapshot: a fresh id, the next version, the whole
8 * map replaced in one row — a reader sees the snapshot before or after,
9 * never half.
10 * - Every process keeps the current snapshot of each scope in memory; a read
11 * is a map lookup. A write wakes this process's store at once through the
12 * bus; another process on the same database notices the changed snapshot
13 * id on its next poll (`start`, half a second), which is the "within a
14 * second" the store promises.
15 * - Writes say who and why, and each lands in `config_change`.
16 *
17 * Values are public by contract: the snapshot is published to the edge
18 * (`cloud/edge.ts`). Secrets belong in `core/secret_store.ts`.
19 */
20
21 import type { Database } from "bun:sqlite";
22 import { id } from "../kernel/id.ts";
23 import { err, ok, type Result } from "../kernel/result.ts";
24 import type { EventBus } from "./events.ts";
25 import { noteRung } from "./rungs.ts";
26
27 export type ConfigValue =
28 | string
29 | number
30 | boolean
31 | null
32 | ConfigValue[]
33 | { [k: string]: ConfigValue };
34
35 export interface Snapshot {
36 readonly scope: string;
37 /** Changes with every write; sent as `X-Forge-Config` and as the ETag. */
38 readonly id: string;
39 readonly version: number;
40 readonly values: Readonly<Record<string, ConfigValue>>;
41 readonly updatedAt: string;
42 }
43
44 export type ConfigError =
45 | "invalid_scope"
46 | "invalid_key"
47 | "invalid_value"
48 | "too_large"
49 | "too_many_keys"
50 | "invalid_who"
51 | "invalid_why"
52 | "empty";
53
54 export const FORGE_SCOPE = "forge";
55 export const appScope = (appId: string): string => `app/${appId}`;
56
57 const KEY = /^[a-z0-9][a-z0-9._-]{0,63}$/;
58 const SCOPE = /^(forge|app\/[0-9a-z]{1,40})$/;
59 const MAX_VALUE_BYTES = 4096;
60 const MAX_TOTAL_BYTES = 65536;
61 const MAX_KEYS = 256;
62 const MAX_WHY = 200;
63 const POLL_MS = 500;
64
65 interface Row {
66 scope: string;
67 snapshot: string;
68 version: number;
69 vals: string;
70 updated_at: string;
71 }
72
73 const EMPTY = (scope: string): Snapshot => ({
74 scope,
75 id: "0",
76 version: 0,
77 values: {},
78 updatedAt: "",
79 });
80
81 function toSnapshot(r: Row): Snapshot {
82 return {
83 scope: r.scope,
84 id: r.snapshot,
85 version: r.version,
86 values: JSON.parse(r.vals) as Record<string, ConfigValue>,
87 updatedAt: r.updated_at,
88 };
89 }
90
91 const bytes = (s: string): number => new TextEncoder().encode(s).length;
92
93 /** Whether `v` is plain JSON (no undefined, functions, NaN, cycles). */
94 function isJson(v: unknown, depth = 0): v is ConfigValue {
95 if (depth > 8) return false;
96 if (v === null || typeof v === "string" || typeof v === "boolean") return true;
97 if (typeof v === "number") return Number.isFinite(v);
98 if (Array.isArray(v)) return v.every((x) => isJson(x, depth + 1));
99 if (typeof v === "object")
100 return Object.entries(v).every(([k, x]) => k !== "__proto__" && isJson(x, depth + 1));
101 return false;
102 }
103
104 export class ConfigStore {
105 private readonly held = new Map<string, Snapshot>();
106 private readonly listeners = new Set<(s: Snapshot) => void>();
107 private timer: ReturnType<typeof setInterval> | undefined;
108 private unsubscribe: (() => void) | undefined;
109
110 constructor(
111 private readonly db: Database,
112 private readonly bus?: EventBus,
113 ) {
114 this.unsubscribe = bus?.subscribe((e) => {
115 if (e.kind === "config.set") this.refresh();
116 });
117 }
118
119 /** The current snapshot of a scope: held in memory, loaded on first ask. */
120 snapshot(scope: string): Snapshot {
121 const held = this.held.get(scope);
122 if (held !== undefined) {
123 noteRung("process");
124 return held;
125 }
126 noteRung("process", false);
127 const row = this.db
128 .query<Row, [string]>("SELECT * FROM config WHERE scope = ?1")
129 .get(scope);
130 noteRung("sqlite", row !== null);
131 const snap = row ? toSnapshot(row) : EMPTY(scope);
132 this.held.set(scope, snap);
133 return snap;
134 }
135
136 /** One value: a map lookup. */
137 get(scope: string, key: string): ConfigValue | undefined {
138 return this.snapshot(scope).values[key];
139 }
140
141 /**
142 * Change keys in one write: a value sets, `null` removes. One new snapshot
143 * comes of it, and the change is recorded with `who` and `why`.
144 */
145 set(
146 scope: string,
147 patch: Record<string, unknown>,
148 who: string,
149 why: string,
150 ): Result<Snapshot, ConfigError> {
151 if (!SCOPE.test(scope)) return err("invalid_scope");
152 if (who.trim() === "" || who.length > 80) return err("invalid_who");
153 const reason = why.trim();
154 if (reason === "" || reason.length > MAX_WHY) return err("invalid_why");
155 const entries = Object.entries(patch);
156 if (entries.length === 0) return err("empty");
157 for (const [k, v] of entries) {
158 if (!KEY.test(k)) return err("invalid_key");
159 if (v !== null && !isJson(v)) return err("invalid_value");
160 if (v !== null && bytes(JSON.stringify(v)) > MAX_VALUE_BYTES)
161 return err("too_large");
162 }
163
164 const write = this.db.transaction((): Result<Snapshot, ConfigError> => {
165 const row = this.db
166 .query<Row, [string]>("SELECT * FROM config WHERE scope = ?1")
167 .get(scope);
168 const values: Record<string, ConfigValue> = row
169 ? { ...(JSON.parse(row.vals) as Record<string, ConfigValue>) }
170 : {};
171 for (const [k, v] of entries) {
172 if (v === null) delete values[k];
173 else values[k] = v as ConfigValue;
174 }
175 if (Object.keys(values).length > MAX_KEYS) return err("too_many_keys");
176 const vals = JSON.stringify(values);
177 if (bytes(vals) > MAX_TOTAL_BYTES) return err("too_large");
178 const at = new Date().toISOString();
179 const snapshot = id();
180 const version = (row?.version ?? 0) + 1;
181 this.db
182 .query(
183 `INSERT INTO config (scope, snapshot, version, vals, updated_at)
184 VALUES (?1, ?2, ?3, ?4, ?5)
185 ON CONFLICT (scope) DO UPDATE SET snapshot = excluded.snapshot,
186 version = excluded.version, vals = excluded.vals,
187 updated_at = excluded.updated_at`,
188 )
189 .run(scope, snapshot, version, vals, at);
190 this.db
191 .query(
192 `INSERT INTO config_change (id, scope, snapshot, version, keys, by, why, at)
193 VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7, ?8)`,
194 )
195 .run(id(), scope, snapshot, version, JSON.stringify(entries.map(([k]) => k)), who, reason, at);
196 return ok({ scope, id: snapshot, version, values, updatedAt: at });
197 });
198 // IMMEDIATE: take the write lock before reading, so two processes
199 // changing one scope serialize into consecutive versions.
200 const result = write.immediate();
201 if (!result.ok) return result;
202 this.adopt(result.value);
203 this.bus?.append({
204 kind: "config.set",
205 payload: {
206 scope,
207 snapshot: result.value.id,
208 version: result.value.version,
209 keys: entries.map(([k]) => k),
210 why: reason,
211 },
212 });
213 return result;
214 }
215
216 /** Every scope that has been written, for republishing at boot. */
217 scopes(): string[] {
218 return this.db
219 .query<{ scope: string }, []>("SELECT scope FROM config")
220 .all()
221 .map((r) => r.scope);
222 }
223
224 /** The recent changes to a scope, newest first. */
225 changes(scope: string, limit = 20) {

The ledger has no reader outside the tests. 'Writes say who and why' is only worth something if the owner can read it. Expose it through the same MCP tool and tty command as the config itself (and on GET …/config?changes=1, or wherever fits), or drop it.

226 return this.db
227 .query<
228 { snapshot: string; version: number; keys: string; by: string; why: string; at: string },
229 [string, number]
230 >(
231 "SELECT snapshot, version, keys, by, why, at FROM config_change WHERE scope = ?1 ORDER BY version DESC LIMIT ?2",
232 )
233 .all(scope, limit)
234 .map((r) => ({ ...r, keys: JSON.parse(r.keys) as string[] }));
235 }
236
237 /**
238 * Reload every held scope whose stored snapshot id differs from the one
239 * in memory. One indexed read of a handful of short rows; returns how many
240 * scopes changed.
241 */
242 refresh(): number {
243 let changed = 0;
244 const stored = this.db
245 .query<{ scope: string; snapshot: string }, []>(
246 "SELECT scope, snapshot FROM config",
247 )
248 .all();
249 for (const { scope, snapshot } of stored) {
250 const held = this.held.get(scope);
251 if (held?.id === snapshot) continue;
252 const row = this.db
253 .query<Row, [string]>("SELECT * FROM config WHERE scope = ?1")
254 .get(scope);
255 if (!row) continue;
256 noteRung("sqlite");
257 this.adopt(toSnapshot(row));
258 changed++;
259 }
260 return changed;
261 }
262
263 /** Called with each snapshot this process newly holds (edge publication). */
264 onChange(listener: (s: Snapshot) => void): () => void {
265 this.listeners.add(listener);
266 return () => this.listeners.delete(listener);
267 }
268
269 /** Poll for writes made by another process on this database. */
270 start(ms = POLL_MS): void {
271 if (this.timer !== undefined) return;
272 this.timer = setInterval(() => {
273 try {
274 this.refresh();
275 } catch {
276 // A closing database ends the poll; the next boot starts it again.
277 }
278 }, ms);
279 this.timer.unref?.();
280 }
281
282 stop(): void {
283 if (this.timer !== undefined) clearInterval(this.timer);
284 this.timer = undefined;
285 this.unsubscribe?.();
286 this.unsubscribe = undefined;
287 }
288
289 private adopt(snap: Snapshot): void {
290 const held = this.held.get(snap.scope);
291 if (held !== undefined && held.version >= snap.version) return;
292 this.held.set(snap.scope, snap);
293 for (const l of this.listeners) {
294 try {
295 l(snap);
296 } catch {
297 // A failed publication must not undo the write that caused it.
298 }
299 }
300 }
301 }
src/core/reserved.ts +1
@@ -63,6 +63,7 @@ export const SYSTEM_NAMES: readonly string[] = [
6363 "audit.csv",
6464 "big",
6565 "board",
66 "edge",
6667 "events",
6768 "explore",
6869 "fleet",
src/core/rungs.ts added +32
@@ -0,0 +1,32 @@
1 /**
2 * The cache spectrum's counter (`docs/CACHE.md`): every answer that comes
3 * from a cache says which rung gave it, so the choice of rung for a kind of
4 * data can be checked against what actually happened. In memory and per
5 * process — a counter is not state worth a write on the hot path; it resets
6 * with the process and `GET /api/v1/cache` reads this process's.
7 */
8
9 export const RUNGS = ["process", "sqlite", "edge", "validator"] as const;
outdated

Nothing ever calls noteRung("git"), so /api/v1/cache reports a rung that is always 0/0. Count the pooled cat-file reads or drop the rung. resetRungs (line 34) is test-only as well.

10 export type Rung = (typeof RUNGS)[number];
11
12 export interface RungCount {
13 readonly hit: number;
14 readonly miss: number;
15 }
16
17 const counts = new Map<Rung, { hit: number; miss: number }>(
18 RUNGS.map((r) => [r, { hit: 0, miss: 0 }]),
19 );
20
21 /** One answer from `rung` (`hit`), or one that had to go a rung further (`miss`). */
22 export function noteRung(rung: Rung, hit = true): void {
23 const c = counts.get(rung)!;
24 if (hit) c.hit++;
25 else c.miss++;
26 }
27
28 export function rungCounts(): Record<Rung, RungCount> {
29 return Object.fromEntries(
30 RUNGS.map((r) => [r, { ...counts.get(r)! }]),
31 ) as Record<Rung, RungCount>;
32 }
src/core/schema.ts +26
@@ -1595,6 +1595,32 @@ export const migrations: readonly string[] = [
15951595 PRIMARY KEY (repo_id, parent_id, issue_id)
15961596 );
15971597 `,
1598 // 76 — the config store (#1138): small read-mostly values, one row per
1599 // scope holding the whole current snapshot, so a write is one new
1600 // snapshot id and a reader never sees half of it. `config_change` is
1601 // the ledger: who changed which keys, when, and why. A scope is `forge`
1602 // or `app/<id>`; neither row is derived from git, and each costs a
1603 // re-entry of the flags to lose, which `config_change` lists.
1604 `
1605 CREATE TABLE config (
1606 scope TEXT PRIMARY KEY,
1607 snapshot TEXT NOT NULL,
1608 version INTEGER NOT NULL,
1609 vals TEXT NOT NULL,
1610 updated_at TEXT NOT NULL
1611 );
1612 CREATE TABLE config_change (
1613 id TEXT PRIMARY KEY,
1614 scope TEXT NOT NULL,
1615 snapshot TEXT NOT NULL,
1616 version INTEGER NOT NULL,
1617 keys TEXT NOT NULL,
1618 by TEXT NOT NULL,
1619 why TEXT NOT NULL,
1620 at TEXT NOT NULL
1621 );
1622 CREATE INDEX config_change_scope ON config_change(scope, version);
1623 `,
15981624 ];
15991625
16001626 /**
src/http/config.ts added +159
@@ -0,0 +1,159 @@
1 /**
2 * The config store's routes (`core/config.ts`): the forge's own snapshot,
3 * an app's, the published edge files, and the cache counters. A read is the
4 * snapshot id and a map; a write is `{ set: { key: value | null }, why }`.
5 */
6
7 import { getAppById, getAppBySlug } from "../core/apps.ts";
8 import {
9 FORGE_SCOPE,
10 appScope,
11 type ConfigError,
12 type Snapshot,
13 } from "../core/config.ts";
14 import { canAdmin, canRead, getRepoById } from "../core/repos.ts";
15 import { noteRung, rungCounts } from "../core/rungs.ts";
16 import type { Ctx, Handler } from "./context.ts";
17 import type { Router } from "./router.ts";
18 import {
19 apiError,
20 boundedBody,
21 cached,
22 forbidden,
23 json,
24 notFound,
25 requireScope,
26 unauthorized,
27 } from "./respond.ts";
28
29 const STATUS: Record<ConfigError, number> = {
30 invalid_scope: 422,
31 invalid_key: 422,
32 invalid_value: 422,
33 too_large: 413,
34 too_many_keys: 422,
35 invalid_who: 422,
36 invalid_why: 422,
37 empty: 422,
38 };
39
40 /** Room for the store's own limits to answer first. */
41 const MAX_BODY = 160 * 1024;
42
43 const shape = (s: Snapshot) => ({
44 snapshot: s.id,
45 version: s.version,
46 values: s.values,
47 updated_at: s.updatedAt,
48 });
49
50 /** `?changes=1` adds the ledger: who changed which keys, and why. */
51 function read(ctx: Ctx, snap: Snapshot, kind: "edge" | "config"): Response {
52 const changes = ctx.url.searchParams.get("changes") === "1";
53 const out = changes
54 ? { ...shape(snap), changes: ctx.app.configs.changes(snap.scope) }
outdated

body() turns an over-cap body into {}, so an oversized PATCH gets 422 invalid_set. Use boundedBody(ctx.request, <cap>) and return 413 too_large, the same answer configs.set gives for an oversized value.

55 : shape(snap);
56 return cached(
57 ctx.request,
58 kind,
59 changes ? `${snap.id}.changes` : snap.id,
60 JSON.stringify(out),
61 "application/json",
62 { "x-forge-config": snap.id },
63 );
64 }
65
66 async function write(ctx: Ctx, scope: string): Promise<Response> {
67 const input = await boundedBody(ctx.request, MAX_BODY);
68 if (input === "too_large") return apiError("too_large", 413, "the change is too large");
69 const set = input.set;
70 if (typeof set !== "object" || set === null || Array.isArray(set))
71 return apiError("invalid_set", 422, "set is an object of key to value (null removes)");
72 const why = typeof input.why === "string" ? input.why : "";
73 const made = ctx.app.configs.set(
74 scope,
75 set as Record<string, unknown>,
76 ctx.auth.user!.username,
77 why,
78 );
79 if (!made.ok) return apiError(made.error, STATUS[made.error], `config refused: ${made.error}`);
80 return json(shape(made.value), 200, { "x-forge-config": made.value.id });
81 }
82
83 /** The app named by the URL, if the caller may read it; its repo with it. */
84 function appFor(ctx: Ctx) {
85 const record = getAppBySlug(ctx.app.db, ctx.params.slug!);
86 const repo = record && getRepoById(ctx.app.db, record.repoId);
87 if (!record || !repo || !canRead(ctx.app.db, repo, ctx.auth.user)) return undefined;
88 return { record, repo };
89 }
90
91 export function configRoutes(router: Router<Handler>): void {
92 // The forge's own flags and settings are public by contract.
93 router.add("GET", "/api/v1/config", (ctx) =>
94 read(ctx, ctx.app.configs.snapshot(FORGE_SCOPE), "edge"),
95 );
96
97 router.add("PATCH", "/api/v1/config", async (ctx) => {
98 const denied = requireScope(ctx, "admin");
99 if (denied) return denied;
100 if (ctx.auth.user!.isAdmin !== true) return forbidden();
101 return write(ctx, FORGE_SCOPE);
102 });
103
104 router.add("GET", "/api/v1/apps/:slug/config", (ctx) => {
105 const found = appFor(ctx);
106 if (!found) return notFound();
107 return read(ctx, ctx.app.configs.snapshot(appScope(found.record.id)), "config");
108 });
109
110 router.add("PATCH", "/api/v1/apps/:slug/config", async (ctx) => {
111 const denied = requireScope(ctx, "admin");
112 if (denied) return denied;
113 const found = appFor(ctx);
114 if (!found) return notFound();
115 if (!canAdmin(ctx.app.db, found.repo, ctx.auth.user)) return forbidden();
116 return write(ctx, appScope(found.record.id));
117 });
118
119 router.add("GET", "/api/v1/cache", (ctx) => {
120 if (!ctx.auth.user) return unauthorized();
121 if (!ctx.auth.user.isAdmin) return notFound();
122 return json(
123 {
124 forge_snapshot: ctx.app.configs.snapshot(FORGE_SCOPE).id,
125 rungs: rungCounts(),
126 },
127 200,
128 { "cache-control": "no-store" },
129 );
130 });
131 }
132
133 /** `/edge/config/<name>.json` and `/edge/config/key.pem`: what the edge serves. */
134 export function edgeRoutes(router: Router<Handler>): void {
135 router.add("GET", "/edge/config/:file", (ctx) => {
136 const file = ctx.params.file!;
137 const edge = ctx.app.edge();
138 if (file === "key.pem")
139 return cached(ctx.request, "edge", "key", edge.publicPem, "application/x-pem-file");
140 const m = /^(forge|app-[0-9a-z]{1,40})\.json$/.exec(file);
141 if (!m) return notFound();
142 const name = m[1]!;
143 let scope = FORGE_SCOPE;
144 if (name !== "forge") {
145 const record = getAppById(ctx.app.db, name.slice(4));
146 const repo = record && getRepoById(ctx.app.db, record.repoId);
147 // Published for anyone only when the app is readable by anyone.
148 if (!record || !repo || !canRead(ctx.app.db, repo, undefined)) return notFound();
149 scope = appScope(record.id);
150 }
151 const text = edge.read(scope);
152 if (text === undefined) return notFound();
153 noteRung("edge");
154 const snapshot = (JSON.parse(JSON.parse(text).payload) as { snapshot: string }).snapshot;
155 return cached(ctx.request, "edge", snapshot, text, "application/json", {
156 "x-forge-config": snapshot,
157 });
158 });
159 }
src/http/mcp.ts +57
@@ -19,6 +19,7 @@
1919
2020 import { mayView, mayViewId, sealedScope } from "../core/sealed.ts";
2121 import { changeCapacity, listCapacity } from "../actions/capacity.ts";
22 import { changeConfig, readConfig } from "../actions/config.ts";
2223 import { relationOf, takeUpdates } from "../actions/forks.ts";
2324 import { watchMilestone } from "../actions/watches.ts";
2425 import {
@@ -1712,6 +1713,62 @@ const TOOLS: readonly Tool[] = [
17121713 });
17131714 },
17141715 },
1716 {
1717 name: "config_get",
1718 description:
1719 "The config store: the flags and settings an app (or, without `repo`, the forge) reads in microseconds from memory and an edge reads from a signed file. Returns the snapshot id, version and values; with `changes`, the ledger of who changed which keys and why. The same as GET /api/v1/apps/:slug/config and /api/v1/config (docs/CACHE.md).",
1720 inputSchema: {
1721 type: "object",
1722 properties: {
1723 repo: { type: "string", description: "The app, as owner/name. Omit for the forge's own." },
1724 changes: { type: "boolean", description: "Include the recent changes, newest first." },
1725 },
1726 },
1727 writes: false,
1728 run(ctx, user, args) {
1729 const repo = args["repo"] === undefined ? undefined : repoArg(ctx, user, args);
1730 if (repo !== undefined && isAnswer(repo)) return repo;
1731 const read = readConfig(ctx.app, user, repo, args["changes"] === true);
1732 return read.ok ? good(read.value) : bad("not_found", "no such app or repository (owner/name)");
1733 },
1734 },
1735 {
1736 name: "config_set",
1737 description:
1738 "Change config keys in one write: `set` maps key to a JSON value, or null to remove it. `why` is required and is kept with who and when. Needs an admin-scope token and admin on the app (a site admin for the forge's own, with `repo` omitted). One write makes one new snapshot, live in other processes within a second and at the edge within seconds.",
1739 inputSchema: {
1740 type: "object",
1741 properties: {
1742 repo: { type: "string", description: "The app, as owner/name. Omit for the forge's own." },
1743 set: { type: "object", description: "Key to value; null removes the key." },
1744 why: { type: "string", description: "The reason, kept in the ledger." },
1745 },
1746 required: ["set", "why"],
1747 },
1748 writes: true,
1749 run(ctx, user, args) {
1750 const repo = args["repo"] === undefined ? undefined : repoArg(ctx, user, args);
1751 if (repo !== undefined && isAnswer(repo)) return repo;
1752 const set = args["set"];
1753 if (typeof set !== "object" || set === null || Array.isArray(set))
1754 return bad("invalid", "set is an object of key to value (null removes)");
1755 if (!scopeAllows(ctx.auth.scope ?? "ro", "admin"))
1756 return bad("forbidden", "changing config needs an admin-scope token");
1757 const made = changeConfig(
1758 ctx.app,
1759 user,
1760 repo,
1761 set as Record<string, unknown>,
1762 typeof args["why"] === "string" ? args["why"] : "",
1763 );
1764 if (made.ok) return good(made.value);
1765 return made.error === "forbidden"
1766 ? bad("forbidden", "that config is an admin's to change")
1767 : made.error === "not_found"
1768 ? bad("not_found", "no such app or repository (owner/name)")
1769 : bad(made.error, `config refused: ${made.error}`);
1770 },
1771 },
17151772 ];
17161773
17171774 /**
src/http/respond.ts +81
@@ -7,6 +7,8 @@
77 import { bodyCapFor, readBounded } from "./limits.ts";
88 import { scopeAllows, type TokenScope } from "../core/tokens.ts";
99 import { NEW_ACCOUNT_GUARD_MESSAGE } from "../core/capacity.ts";
10 import { noteRung } from "../core/rungs.ts";
11 import type { App } from "../app.ts";
1012 import type { User } from "../core/users.ts";
1113 import { crossOrigin, type Ctx } from "./context.ts";
1214
@@ -281,3 +283,82 @@ export function paged<T>(
281283 items.length >= limit && last !== undefined ? cursorOf(last) : null,
282284 };
283285 }
286
287 /**
288 * What a kind of response may be kept for, by whom (`docs/CACHE.md`). A
289 * route names its kind; it never writes `Cache-Control` itself.
290 *
291 * - `immutable`: content addressed, never changes under its URL.
292 * - `edge`: a published snapshot — any cache may hold it a few seconds,
293 * and serve it stale while it refetches; the ETag is the snapshot id.
294 * - `config`: the same data for a signed-in reader — only that reader's
295 * cache, and revalidated every time (a 304 costs one lookup).
296 * - `live`: never kept.
297 */
298 export type CacheKind = "immutable" | "edge" | "config" | "live";
299
300 export const CACHE_CONTROL: Readonly<Record<CacheKind, string>> = {
301 immutable: "public, max-age=31536000, immutable",
302 edge: "public, max-age=5, stale-while-revalidate=30",
303 config: "private, no-cache",
304 live: "no-store",
305 };
outdated

No route uses fragment or immutable, but docs/CACHE.md lists them as 'Used for' fragments and hashed assets. Move at least the hashed-asset route onto immutable so the table is true, or cut the unused kinds.

306
307 /** The headers a kind sets: `Cache-Control`, and `ETag` when it has a validator. */
308 export function cacheHeaders(
309 kind: CacheKind,
310 etag?: string,
311 ): Record<string, string> {
312 const headers: Record<string, string> = { "cache-control": CACHE_CONTROL[kind] };
313 if (etag !== undefined && kind !== "live") headers.etag = `"${etag}"`;
314 return headers;
315 }
316
317 /** Whether `If-None-Match` already names this validator (or `*`). */
318 export function notModified(request: Request, etag: string): boolean {
319 const sent = request.headers.get("if-none-match");
320 if (sent === null) return false;
321 return sent
322 .split(",")
323 .map((t) => t.trim().replace(/^W\//, ""))
324 .some((t) => t === `"${etag}"` || t === "*");
325 }
326
327 /**
328 * A body of a kind, answered `304` when the reader already holds `etag`.
329 * The one place a conditional response is made; the 304 is counted as a
330 * `validator` hit so the spectrum can be checked against reality.
331 */
332 export function cached(
333 request: Request,
334 kind: CacheKind,
335 etag: string,
336 body: string,
337 contentType = "application/json",
338 extra: Record<string, string> = {},
339 ): Response {
340 const headers = { ...cacheHeaders(kind, etag), ...extra };
341 if (notModified(request, etag)) {
342 noteRung("validator");
343 return new Response(null, { status: 304, headers });
344 }
345 noteRung("validator", false);
346 return new Response(body, {
347 status: 200,
348 headers: { "content-type": contentType, ...headers },
349 });
350 }
351
352 /**
353 * Say which config snapshot this forge holds, on every response: an edge
354 * or an app that cached an older id can see that it lags.
355 */
356 export function stampConfig(response: Response, app: App): Response {
357 try {
358 if (!response.headers.has("x-forge-config"))
359 response.headers.set("x-forge-config", app.configs.snapshot("forge").id);
360 } catch {
361 // A carried, immutable header set keeps what it came with.
362 }
363 return response;
364 }
src/http/server.ts +11 −1
@@ -366,6 +366,7 @@ import { notFoundPage } from "../web/chrome.ts";
366366 import { targetForShortCode } from "../origins/oauth.ts";
367367 import { apiRoutes } from "./api.ts";
368368 import { feedRoutes } from "./feed.ts";
369 import { configRoutes, edgeRoutes } from "./config.ts";
369370 import { mcpRoutes } from "./mcp.ts";
370371 import { oauthRoutes } from "./oauth.ts";
371372 import { carryPeer, clientAddress, notePeer, type ProxyTrust } from "./peer.ts";
@@ -391,6 +392,7 @@ import {
391392 notFound,
392393 prefersHtml,
393394 securityFloor,
395 stampConfig,
394396 } from "./respond.ts";
395397 import { RateLimiter, type Verdict } from "../core/ratelimit.ts";
396398 import {
@@ -512,6 +514,8 @@ const gitChallenge = () =>
512514 export function buildRouter(): Router<Handler> {
513515 const router = new Router<Handler>();
514516
517 edgeRoutes(router);
518
515519 // Literal-prefix routes come before parameterized repo routes; the router
516520 // matches in insertion order. The stylesheet and the highlighter bundle are
517521 // both content-addressed: a stale hash is a 404 rather than a redirect, the
@@ -1135,6 +1139,7 @@ export function buildApiRouter(): Router<Handler> {
11351139 const router = new Router<Handler>();
11361140 apiRoutes(router);
11371141 feedRoutes(router);
1142 configRoutes(router);
11381143 return router;
11391144 }
11401145
@@ -1802,7 +1807,12 @@ async function answer(
18021807 limiter: RateLimiter,
18031808 request: Request,
18041809 ): Promise<Response> {
1805 const response = await answerGet(app, router, apiRouter, limiter, request);
1810 // Every answer the forge writes for itself names the config snapshot it
1811 // holds, so a stale edge or app is visible (`docs/CACHE.md`).
1812 const response = stampConfig(
1813 await answerGet(app, router, apiRouter, limiter, request),
1814 app,
1815 );
18061816 return request.method === "HEAD"
18071817 ? new Response(null, { status: response.status, headers: response.headers })
18081818 : response;
src/main.ts +7
@@ -167,6 +167,13 @@ await reconcile(app);
167167 // Issues linked under a pillar's umbrella before pillars had labels.
168168 const labelled = syncAllPillars(app);
169169 if (labelled > 0) app.log.info("pillars labelled", { issues: labelled });
170 // Config snapshots: poll for another process's writes, and publish what is
171 // held now so the edge file exists from the first request.
172 app.configs.start();
173 for (const scope of app.configs.scopes())
174 await app.edge().publish(app.configs.snapshot(scope)).catch((error) =>
175 app.log.warn("edge publish failed", { scope, error: String(error) }),
176 );
170177 const servers = await serve(app);
171178 const sshStarted =
172179 sshPort > 0 ? await startForgeSsh(app, { port: sshPort }) : undefined;
src/web/asset.ts +3 −2
@@ -16,6 +16,7 @@
1616 * JavaScript switched off.
1717 */
1818
19 import { cacheHeaders } from "../http/respond.ts";
1920 import { sha256 } from "../kernel/hash.ts";
2021 import { createLog } from "../kernel/log.ts";
2122 import { shellJs } from "./client.ts";
@@ -66,7 +67,7 @@ export function assetResponse(asset: BuiltAsset): Response {
6667 return new Response(asset.code, {
6768 headers: {
6869 "content-type": "text/javascript; charset=utf-8",
69 "cache-control": "public, max-age=31536000, immutable",
70 ...cacheHeaders("immutable"),
7071 "x-content-type-options": "nosniff",
7172 },
7273 });
@@ -95,7 +96,7 @@ export function stylesheetResponse(): Response {
9596 return new Response(css, {
9697 headers: {
9798 "content-type": "text/css; charset=utf-8",
98 "cache-control": "public, max-age=31536000, immutable",
99 ...cacheHeaders("immutable"),
99100 "x-content-type-options": "nosniff",
100101 },
101102 });
test/cli-config.test.ts added +13
@@ -0,0 +1,13 @@
1 import { expect, test } from "bun:test";
2 import { parseConfigOperands } from "../src/cli/flags.ts";
3
4 test("forge config operands: an app name, and key=value with JSON when it parses", () => {
5 expect(parseConfigOperands([])).toEqual({ slug: undefined, set: {} });
6 expect(parseConfigOperands(["notes", "on=true", "n=3", "old=null", "motd=hello world"])).toEqual({
7 slug: "notes",
8 set: { on: true, n: 3, old: null, motd: "hello world" },
9 });
10 expect(typeof parseConfigOperands(["Bad Name"])).toBe("string");
11 expect(typeof parseConfigOperands(["a", "b"])).toBe("string");
12 expect(typeof parseConfigOperands(["=x"])).toBe("string");
13 });
test/config-store.test.ts added +337
@@ -0,0 +1,337 @@
1 /**
2 * The config store and the edge rung (#1138): one write is one snapshot,
3 * another process sees it within a second, the signed edge file carries the
4 * new id, a stale id is detected, and each kind of response sets the headers
5 * `docs/CACHE.md` says.
6 */
7
8 import { afterAll, beforeAll, describe, expect, test } from "bun:test";
9 import { Database } from "bun:sqlite";
10 import { existsSync, readFileSync } from "node:fs";
11 import { mkdtemp, rm } from "node:fs/promises";
12 import { tmpdir } from "node:os";
13 import { join } from "node:path";
14 import { createApp, type App } from "../src/app.ts";
15 import { newApp } from "../src/actions/apps.ts";
16 import { ConfigStore, FORGE_SCOPE, appScope } from "../src/core/config.ts";
17 import { noteRung, rungCounts } from "../src/core/rungs.ts";
18 import { createToken } from "../src/core/tokens.ts";
19 import { createUser, type User } from "../src/core/users.ts";
20 import {
21 EdgePublisher,
22 edgeName,
23 kvFromEnv,
24 verifyEdgeFile,
25 } from "../src/cloud/edge.ts";
26 import {
27 CACHE_CONTROL,
28 cacheHeaders,
29 cached,
30 type CacheKind,
31 } from "../src/http/respond.ts";
32 import { forgeHttp, type ForgeHttp } from "../src/http/server.ts";
33
34 async function admin(app: App, username: string): Promise<User> {
35 const made = await createUser(app.db, {
36 trusted: true,
37 username,
38 email: `${username}@forge.local`,
39 password: "a-good-passphrase",
40 adminIfFirst: true,
41 });
42 if (!made.ok) throw new Error(made.error);
43 return made.value;
44 }
45
46 describe("config store", () => {
47 let dir: string;
48 let app: App;
49 beforeAll(async () => {
50 dir = await mkdtemp(join(tmpdir(), "forge-config-"));
51 app = createApp({ dataDir: dir, port: 0 });
52 });
53 afterAll(async () => {
54 app.close();
55 await rm(dir, { recursive: true, force: true });
56 });
57
58 test("one write is one new snapshot; null removes; reads are the held map", () => {
59 const a = app.configs.set(FORGE_SCOPE, { "flag.new-ui": true, motd: "hi" }, "alice", "try it");
60 expect(a.ok).toBe(true);
61 if (!a.ok) return;
62 expect(a.value.version).toBe(1);
63 expect(app.configs.get(FORGE_SCOPE, "flag.new-ui")).toBe(true);
64 const b = app.configs.set(FORGE_SCOPE, { motd: null }, "alice", "drop motd");
65 if (!b.ok) throw new Error(b.error);
66 expect(b.value.id).not.toBe(a.value.id);
67 expect(b.value.version).toBe(2);
68 expect(app.configs.get(FORGE_SCOPE, "motd")).toBeUndefined();
69 expect(app.configs.snapshot(FORGE_SCOPE).id).toBe(b.value.id);
70 });
71
72 test("a write says who and why, and the ledger keeps both", () => {
73 const changes = app.configs.changes(FORGE_SCOPE);
74 expect(changes[0]).toMatchObject({ by: "alice", why: "drop motd", keys: ["motd"], version: 2 });
75 expect(app.configs.set(FORGE_SCOPE, { x: 1 }, "alice", " ").ok).toBe(false);
76 expect(app.configs.set(FORGE_SCOPE, { x: 1 }, "", "why").ok).toBe(false);
77 });
78
79 test("input is validated at the boundary", () => {
80 const err = (patch: Record<string, unknown>, scope = FORGE_SCOPE) => {
81 const r = app.configs.set(scope, patch, "a", "w");
82 return r.ok ? "ok" : r.error;
83 };
84 expect(err({ "Bad Key": 1 })).toBe("invalid_key");
85 expect(err({ "": 1 })).toBe("invalid_key");
86 expect(err({ k: undefined })).toBe("invalid_value");
87 expect(err({ k: Number.NaN })).toBe("invalid_value");
88 expect(err({ k: "x".repeat(5000) })).toBe("too_large");
89 expect(err({})).toBe("empty");
90 expect(err({ k: 1 }, "nope")).toBe("invalid_scope");
91 expect(err({ k: 1 }, "app/../x")).toBe("invalid_scope");
92 });
93
94 test("a write is visible to a second process within a second", async () => {
95 // A second process is a second connection and a second store on the same file.
96 const other = new ConfigStore(new Database(join(dir, "forge.db")));
97 other.start();
98 try {
99 expect(other.get(FORGE_SCOPE, "seen")).toBeUndefined();
100 const wrote = app.configs.set(FORGE_SCOPE, { seen: "yes" }, "alice", "cross-process");
101 if (!wrote.ok) throw new Error(wrote.error);
102 const t0 = Date.now();
103 while (other.snapshot(FORGE_SCOPE).id !== wrote.value.id && Date.now() - t0 < 1000)
104 await Bun.sleep(25);
105 expect(other.snapshot(FORGE_SCOPE).id).toBe(wrote.value.id);
106 expect(other.get(FORGE_SCOPE, "seen")).toBe("yes");
107 expect(Date.now() - t0).toBeLessThan(1000);
108 } finally {
109 other.stop();
110 }
111 });
112
113 test("the edge file carries the new id after a write, signed", async () => {
114 const wrote = app.configs.set(FORGE_SCOPE, { edge: 1 }, "alice", "publish");
115 if (!wrote.ok) throw new Error(wrote.error);
116 const text = app.edge().read(FORGE_SCOPE)!;
117 const file = JSON.parse(text);
118 const published = verifyEdgeFile(file, app.edge().publicPem)!;
119 expect(published.snapshot).toBe(wrote.value.id);
120 expect(published.values.edge).toBe(1);
121 // altered bytes do not verify
122 const forged = { ...file, payload: file.payload.replace('"edge":1', '"edge":2') };
123 expect(verifyEdgeFile(forged, app.edge().publicPem)).toBeUndefined();
124 // the private key stays in the data directory and is not world readable
125 expect(existsSync(join(dir, "edge", "signing.pem"))).toBe(true);
126 });
127
128 test("the edge names its files", () => {
129 expect(edgeName("forge")).toBe("forge");
130 expect(edgeName("app/abc")).toBe("app-abc");
131 expect(edgeName("../x")).toBeUndefined();
132 });
133
134 test("Cloudflare KV gets the same bytes as the file when configured", async () => {
135 const calls: { url: string; init: RequestInit }[] = [];
136 const fake = (async (url: string, init: RequestInit) => {
137 calls.push({ url, init });
138 return new Response("{}", { status: 200 });
139 }) as unknown as typeof fetch;
140 const kv = kvFromEnv({ FORGE_CF_ACCOUNT: "acct1", FORGE_CF_KV_NAMESPACE: "ns1", FORGE_CF_API_TOKEN: "t" });
141 expect(kvFromEnv({ FORGE_CF_ACCOUNT: "a/../b" })).toBeUndefined();
142 const edge = new EdgePublisher(dir, { kv, fetch: fake });
143 await edge.publish(app.configs.snapshot(FORGE_SCOPE));
144 expect(calls).toHaveLength(1);
145 expect(calls[0]!.url).toBe(
146 "https://api.cloudflare.com/client/v4/accounts/acct1/storage/kv/namespaces/ns1/values/forge",
147 );
148 expect(calls[0]!.init.body).toBe(edge.read(FORGE_SCOPE));
149 });
150 });
151
152 describe("cache headers, one helper per kind", () => {
153 test("each kind sets what the table in docs/CACHE.md says", () => {
154 const table: Record<CacheKind, string> = {
155 immutable: "public, max-age=31536000, immutable",
156 edge: "public, max-age=5, stale-while-revalidate=30",
157 config: "private, no-cache",
158 live: "no-store",
159 };
160 for (const [kind, value] of Object.entries(table)) {
161 expect(CACHE_CONTROL[kind as CacheKind]).toBe(value);
162 expect(cacheHeaders(kind as CacheKind)["cache-control"]).toBe(value);
163 }
164 expect(cacheHeaders("edge", "abc").etag).toBe('"abc"');
165 expect(cacheHeaders("live", "abc").etag).toBeUndefined();
166 const docs = readFileSync(join(import.meta.dir, "..", "docs", "CACHE.md"), "utf8");
167 for (const value of Object.values(table)) expect(docs).toContain(value);
168 });
169
170 test("a matching If-None-Match is a 304, counted as a validator hit", async () => {
171 const before = rungCounts().validator;
172 const url = "http://x/y";
173 const fresh = cached(new Request(url), "config", "s1", "{}");
174 expect(fresh.status).toBe(200);
175 const again = cached(new Request(url, { headers: { "if-none-match": '"s1"' } }), "config", "s1", "{}");
176 expect(again.status).toBe(304);
177 expect(await again.text()).toBe("");
178 const after = rungCounts().validator;
179 expect(after.hit - before.hit).toBe(1);
180 expect(after.miss - before.miss).toBe(1);
181 const edge = rungCounts().edge.hit;
182 noteRung("edge");
183 expect(rungCounts().edge.hit - edge).toBe(1);
184 });
185 });
186
187 describe("config over HTTP", () => {
188 let dir: string;
189 let app: App;
190 let http: ForgeHttp;
191 let token: string;
192 let ro: string;
193 let slug: string;
194
195 beforeAll(async () => {
196 dir = await mkdtemp(join(tmpdir(), "forge-config-http-"));
197 app = createApp({ dataDir: dir, port: 0 });
198 http = forgeHttp(app);
199 const alice = await admin(app, "alice");
200 token = createToken(app.db, alice.id, "admin", "admin").token;
201 ro = createToken(app.db, alice.id, "ro", "ro").token;
202 const made = await newApp(app, alice, { name: "flags", description: "d", visibility: "public" });
203 if (!made.ok) throw new Error(String(made.error));
204 slug = made.value.app.slug;
205 });
206 afterAll(async () => {
207 app.close();
208 await rm(dir, { recursive: true, force: true });
209 });
210
211 const call = (path: string, init: RequestInit = {}, bearer?: string) =>
212 http.handle(new Request(`http://forge.test${path}`, {
213 ...init,
214 headers: {
215 ...(bearer ? { authorization: `Bearer ${bearer}` } : {}),
216 "content-type": "application/json",
217 ...(init.headers as Record<string, string> | undefined),
218 },
219 }));
220 const patch = (path: string, body: unknown, bearer?: string) =>
221 call(path, { method: "PATCH", body: JSON.stringify(body) }, bearer);
222
223 test("an app reads its config with the snapshot id, and revalidates with it", async () => {
224 expect((await patch(`/api/v1/apps/${slug}/config`, { set: { a: 1 }, why: "x" })).status).toBe(401);
225 expect((await patch(`/api/v1/apps/${slug}/config`, { set: { a: 1 }, why: "x" }, ro)).status).toBe(403);
226 const w = await patch(`/api/v1/apps/${slug}/config`, { set: { a: 1, theme: "dark" }, why: "launch" }, token);
227 expect(w.status).toBe(200);
228 const wrote = (await w.json()) as { snapshot: string };
229 const r = await call(`/api/v1/apps/${slug}/config`, {}, ro);
230 expect(r.status).toBe(200);
231 const read = (await r.json()) as { snapshot: string; values: Record<string, unknown> };
232 expect(read.snapshot).toBe(wrote.snapshot);
233 expect(read.values).toEqual({ a: 1, theme: "dark" });
234 expect(r.headers.get("etag")).toBe(`"${wrote.snapshot}"`);
235 expect(r.headers.get("cache-control")).toBe(CACHE_CONTROL.config);
236 const again = await call(`/api/v1/apps/${slug}/config`, { headers: { "if-none-match": `"${wrote.snapshot}"` } }, ro);
237 expect(again.status).toBe(304);
238 });
239
240 test("a bad write is a 422 and an unknown app a 404", async () => {
241 expect((await patch(`/api/v1/apps/${slug}/config`, { set: { "Bad": 1 }, why: "x" }, token)).status).toBe(422);
242 expect((await patch(`/api/v1/apps/${slug}/config`, { set: { a: 1 } }, token)).status).toBe(422);
243 expect((await call(`/api/v1/apps/nope/config`, {}, ro)).status).toBe(404);
244 });
245
246 test("an oversized change is a 413, not a 422", async () => {
247 const big = await patch(`/api/v1/apps/${slug}/config`, { set: { k: "x".repeat(300 * 1024) }, why: "x" }, token);
248 expect(big.status).toBe(413);
249 expect(((await big.json()) as { error: string }).error).toBe("too_large");
250 });
251
252 test("?changes=1 reads the ledger, under its own validator", async () => {
253 await patch(`/api/v1/apps/${slug}/config`, { set: { led: 1 }, why: "ledger please" }, token);
254 const r = await call(`/api/v1/apps/${slug}/config?changes=1`, {}, ro);
255 const body = (await r.json()) as { snapshot: string; changes: { by: string; why: string; keys: string[] }[] };
256 expect(body.changes[0]).toMatchObject({ by: "alice", why: "ledger please", keys: ["led"] });
257 expect(r.headers.get("etag")).not.toBe(`"${body.snapshot}"`);
258 expect(((await (await call(`/api/v1/apps/${slug}/config`, {}, ro)).json()) as object)).not.toHaveProperty("changes");
259 });
260
261 test("the built assets take the immutable kind", async () => {
262 const { stylesheetResponse } = await import("../src/web/asset.ts");
263 expect(stylesheetResponse().headers.get("cache-control")).toBe(CACHE_CONTROL.immutable);
264 });
265
266 test("MCP config_get / config_set carry the routes' gates and require why", async () => {
267 const mcp = async (bearer: string, name: string, args: unknown) => {
268 const res = await call("/mcp", {
269 method: "POST",
270 headers: { accept: "application/json, text/event-stream" },
271 body: JSON.stringify({ jsonrpc: "2.0", id: 1, method: "tools/call", params: { name, arguments: args } }),
272 }, bearer);
273 const out = (await res.json()) as { result: { isError?: boolean; content: { text: string }[] } };
274 return { error: out.result.isError === true, text: out.result.content[0]!.text };
275 };
276 const set = await mcp(token, "config_set", { repo: "alice/flags", set: { m: "tool" }, why: "via mcp" });
277 expect(set.error).toBe(false);
278 const got = await mcp(ro, "config_get", { repo: "alice/flags", changes: true });
279 const view = JSON.parse(got.text) as { values: Record<string, unknown>; changes: { why: string }[] };
280 expect(view.values.m).toBe("tool");
281 expect(view.changes[0]!.why).toBe("via mcp");
282 expect((await mcp(token, "config_set", { repo: "alice/flags", set: { m: 1 }, why: " " })).error).toBe(true);
283 expect((await mcp(ro, "config_set", { repo: "alice/flags", set: { m: 1 }, why: "no" })).error).toBe(true);
284 expect((await mcp(ro, "config_set", { set: { m: 1 }, why: "no" })).error).toBe(true);
285 expect((await mcp(token, "config_get", { repo: "alice/nope" })).error).toBe(true);
286 const forge = await mcp(ro, "config_get", {});
287 expect(forge.error).toBe(false);
288 });
289
290 test("the forge's flags are readable by anyone and written only by an admin token", async () => {
291 expect((await patch("/api/v1/config", { set: { f: true }, why: "w" }, ro)).status).toBe(403);
292 const w = await patch("/api/v1/config", { set: { f: true }, why: "w" }, token);
293 expect(w.status).toBe(200);
294 const r = await call("/api/v1/config");
295 expect(((await r.json()) as { values: Record<string, unknown> }).values.f).toBe(true);
296 expect(r.headers.get("cache-control")).toBe(CACHE_CONTROL.edge);
297 });
298
299 test("every response names the snapshot the forge holds", async () => {
300 const id = app.configs.snapshot(FORGE_SCOPE).id;
301 for (const path of ["/healthz", "/api/v1/config", "/nowhere-at-all"]) {
302 const r = await call(path, { headers: { accept: "application/json" } });
303 expect(r.headers.get("x-forge-config")).toBe(id);
304 }
305 });
306
307 test("the edge serves the signed file at a stable URL; a lagging copy is visible", async () => {
308 const r = await call("/edge/config/forge.json");
309 expect(r.status).toBe(200);
310 expect(r.headers.get("cache-control")).toBe(CACHE_CONTROL.edge);
311 const key = await (await call("/edge/config/key.pem")).text();
312 const published = verifyEdgeFile(await r.json(), key)!;
313 const id = app.configs.snapshot(FORGE_SCOPE).id;
314 expect(published.snapshot).toBe(id);
315 // a public app's file is served, under its id
316 const scope = appScope(
317 (await import("../src/core/apps.ts")).getAppBySlug(app.db, slug)!.id,
318 );
319 const name = edgeName(scope)!;
320 const mine = await call(`/edge/config/${name}.json`);
321 expect(mine.status).toBe(200);
322 expect(verifyEdgeFile(await mine.json(), key)!.scope).toBe(scope);
323 // the write moves the id; the copy held before it now reads stale
324 const w = await patch("/api/v1/config", { set: { g: 2 }, why: "move" }, token);
325 const next = ((await w.json()) as { snapshot: string }).snapshot;
326 expect(next).not.toBe(published.snapshot);
327 expect((await call("/edge/config/..%2fsigning.pem")).status).toBe(404);
328 expect((await call("/edge/config/app-nope.json")).status).toBe(404);
329 });
330
331 test("the cache counters are an admin's to read", async () => {
332 expect((await call("/api/v1/cache")).status).toBe(401);
333 const r = await call("/api/v1/cache", {}, token);
334 const body = (await r.json()) as { rungs: Record<string, { hit: number }> };
335 expect(body.rungs.process!.hit).toBeGreaterThan(0);
336 });
337 });
test/mcp.test.ts +2
@@ -195,6 +195,8 @@ describe("the forge over MCP", () => {
195195 "hold",
196196 "plan",
197197 "capacity",
198 "config_get",
199 "config_set",
198200 "report",
199201 ]);
200202 const byName = new Map<string, any>(

↑↓ navigate ↵ open ⌘↵ its app esc close

Keyboard shortcuts

Docs