Public: anyone can read this; the crew can change it.
Family tree across forges: a forge shows its parent and its children #1780
scout/forge:scout/425-family-tree-across-forges-a-forge-shows → main 3 commits fork
12 files
changed +637
−2
docs/SPAWN.md +6
| @@ -48,6 +48,12 @@ Spawn makes the child's `secret.key` and SSH host key in the child's own directo | ||
| 48 | 48 | |
| 49 | 49 | A spawner may give the child one credential: `modelKey`, an API-billed key (`sk-ant-api…`), with `budgetUsd`, a whole-life budget in dollars from 1 to 1000. A subscription token (`sk-ant-oat…`) is refused, because it is a person's own plan. The key never enters the plan, the dry run, the answer, the ledger or the idempotency table. In the child it is sealed with the child's own key as the account `starter` and granted to its organisation's crew. The budget is locked on that account (`lockBudget`): it is enforced where every run picks its account, whoever started the run and on whichever repository, and the child's admin cannot raise it, only add their own key. A retry with a different key is refused; a key is given once. Said plainly in every answer that carries a key (`keyNote`): the budget holds while this forge hosts the child, whose admin has no shell or database access; on a machine the child's owner controls, only a spend limit set at the provider binds the key, so use a key from a workspace with its own spend limit. The MCP `spawn` tool refuses `modelKey`, so a secret never passes through an agent's conversation. With no key the child is in a clean state: its pages say the crew has no model key yet and where an admin adds one. |
| 50 | 50 | |
| 51 | ## The family across forges (#425) | |
| 52 | ||
| 53 | `/family` draws the forge-level tree as nested lists: the parent (from `FORGE_PARENT_URL`, or the `upstream` in a spawned child's `parent.json`), this forge, and the forges it sent, each with last seen, version, releases behind this forge, and open proposals. Anyone may see the parent; only this forge's admins see children. Bounded: 100 children, four levels. | |
| 54 | ||
| 55 | Children report in; the parent never reaches in. Every ten minutes a spawned child POSTs `/api/v1/heartbeat` (`src/spawn/heartbeat.ts`): `{name, at, version, openProposals, children}` and nothing else, signed HMAC-SHA256 over the body in `x-forge-signature` with a per-child `beatKey` that spawn put in the parent's ledger and the child's `parent.json`. A name the parent did not make, a bad signature, a time more than ten minutes off, a replay or any extra field gets the same 404 and changes nothing. The last beat per child is kept in `<data>/beats/<name>.json`. A child silent for thirty minutes reads "quiet", never an error; one never heard from reads "has not reported yet". Children made before this change have no key and stay unheard until respawned. | |
| 56 | ||
| 51 | 57 | ## Choices |
| 52 | 58 | |
| 53 | 59 | - Following across forges is HTTPS git with scoped tokens, because hosted |
scripts/gate.ts +1
| @@ -59,6 +59,7 @@ export const GATE: readonly string[] = [ | ||
| 59 | 59 | "test/health.test.ts", |
| 60 | 60 | "test/client-address.test.ts", |
| 61 | 61 | "test/client-list.test.ts", |
| 62 | "test/family-heartbeat.test.ts", | |
| 62 | 63 | "test/contents-api.test.ts", |
| 63 | 64 | "test/crew-agents-only.test.ts", |
| 64 | 65 | "test/crew-brief-audience.test.ts", |
src/actions/spawn.ts +16 −2
| @@ -108,6 +108,11 @@ interface Ledger { | ||
| 108 | 108 | * last happened); the child keeps only its hash. Never in an answer. |
| 109 | 109 | */ |
| 110 | 110 | statusToken?: string; |
| 111 | /** | |
| 112 | * The key a child signs its heartbeats with (`spawn/heartbeat.ts`); the | |
| 113 | * child holds the same one in its `parent.json`. Never in an answer. | |
| 114 | */ | |
| 115 | beatKey?: string; | |
| 111 | 116 | } |
| 112 | 117 | |
| 113 | 118 | const SAFE_ID = /^[A-Za-z0-9_-]{1,80}$/; |
| @@ -219,8 +224,9 @@ async function make( | ||
| 219 | 224 | } |
| 220 | 225 | if (ledger.done) |
| 221 | 226 | return ok({ name: plan.name, org: plan.org, url: liveChildUrl(app, plan.name), bodyId: ledger.bodyId, existed: true }); |
| 222 | if (ledger.statusToken === undefined) { | |
| 223 | ledger.statusToken = secret(); | |
| 227 | if (ledger.statusToken === undefined || ledger.beatKey === undefined) { | |
| 228 | ledger.statusToken ??= secret(); | |
| 229 | ledger.beatKey ??= secret(); | |
| 224 | 230 | await writeLedger(app, ledger); |
| 225 | 231 | } |
| 226 | 232 | } else { |
| @@ -240,6 +246,7 @@ async function make( | ||
| 240 | 246 | apps: plan.apps.map((a) => a.ref), |
| 241 | 247 | createdAt: new Date().toISOString(), |
| 242 | 248 | statusToken: secret(), |
| 249 | beatKey: secret(), | |
| 243 | 250 | }; |
| 244 | 251 | await writeLedger(app, ledger); |
| 245 | 252 | } |
| @@ -426,6 +433,8 @@ async function copyInto( | ||
| 426 | 433 | : { forgeCode: { repo: `${plan.org}/forge`, upstream: forgeCode.value } }), |
| 427 | 434 | // Only the hash: the parent alone holds what it answers to. |
| 428 | 435 | ...(ledger.statusToken === undefined ? {} : { statusHash: sha256(ledger.statusToken) }), |
| 436 | // The key the child signs its heartbeats with; the parent holds the same. | |
| 437 | ...(ledger.beatKey === undefined ? {} : { beatKey: ledger.beatKey }), | |
| 429 | 438 | }), |
| 430 | 439 | ); |
| 431 | 440 | return ok(mintClaim(child.db, org.id)); |
| @@ -544,6 +553,11 @@ export async function statusTokenOf(app: App, name: string): Promise<string | un | ||
| 544 | 553 | return (await readLedger(app, name))?.statusToken; |
| 545 | 554 | } |
| 546 | 555 | |
| 556 | /** The key a child of this forge signs heartbeats with; undefined for a name this forge did not make. */ | |
| 557 | export async function beatKeyOf(app: App, name: string): Promise<string | undefined> { | |
| 558 | return (await readLedger(app, name))?.beatKey; | |
| 559 | } | |
| 560 | ||
| 547 | 561 | /** One child, as the ledger keeps it. */ |
| 548 | 562 | export interface Child { |
| 549 | 563 | readonly name: string; |
src/http/api.ts +11
| @@ -47,6 +47,7 @@ import { emailVerified } from "../core/verify.ts"; | ||
| 47 | 47 | import { readHealth } from "../actions/health.ts"; |
| 48 | 48 | import { listChildren } from "../actions/spawn.ts"; |
| 49 | 49 | import { forgeState, PARENT_HEADER } from "../spawn/clients.ts"; |
| 50 | import { receiveBeat, SIGNATURE_HEADER } from "../spawn/heartbeat.ts"; | |
| 50 | 51 | import { reissueDoor, spawnDoor } from "../spawn/door.ts"; |
| 51 | 52 | import { listSecrets, putSecret, removeSecret } from "../actions/secrets.ts"; |
| 52 | 53 | import { proposeUpstream } from "../actions/upstream.ts"; |
| @@ -4134,6 +4135,16 @@ export function apiRoutes(router: Router<Handler>): void { | ||
| 4134 | 4135 | return json(state); |
| 4135 | 4136 | }); |
| 4136 | 4137 | |
| 4138 | // A child's signed heartbeat (docs/SPAWN.md): counts and version, never | |
| 4139 | // data. Every refusal is the same 404, so nothing says who is a child. | |
| 4140 | router.add("POST", "/api/v1/heartbeat", async (ctx) => { | |
| 4141 | const length = Number(ctx.request.headers.get("content-length") ?? "0"); | |
| 4142 | if (!(length <= 1024)) return apiError("not_found", 404, "no such door"); | |
| 4143 | const raw = await ctx.request.text(); | |
| 4144 | const kept = await receiveBeat(ctx.app, raw, ctx.request.headers.get(SIGNATURE_HEADER)); | |
| 4145 | return kept ? json({ ok: true }) : apiError("not_found", 404, "no such door"); | |
| 4146 | }); | |
| 4147 | ||
| 4137 | 4148 | // A forge's children (docs/SPAWN.md): an admin's, planned before made. |
| 4138 | 4149 | router.add("GET", "/api/v1/forges", async (ctx) => { |
| 4139 | 4150 | const denied = requireScope(ctx, "ro"); |
src/http/server.ts +2
| @@ -202,6 +202,7 @@ import { | ||
| 202 | 202 | } from "../web/studio/actions.ts"; |
| 203 | 203 | import { everydayCreate, everydayKeep, everydaySwitch } from "../web/pages/everyday.ts"; |
| 204 | 204 | import { claimFragmentPage, claimSubmit } from "../web/pages/claim.ts"; |
| 205 | import { familyPage } from "../web/pages/family.ts"; | |
| 205 | 206 | import { forgeLinkSubmit, forgesPage } from "../web/pages/forges.ts"; |
| 206 | 207 | import { newForgePage, newForgeSubmit } from "../web/pages/new-forge.ts"; |
| 207 | 208 | import { askedPage } from "../web/studio/asked_page.ts"; |
| @@ -579,6 +580,7 @@ export function buildRouter(): Router<Handler> { | ||
| 579 | 580 | router.add("POST", "/claim", claimSubmit); |
| 580 | 581 | // "+ New forge": the spawn door as a page, any signed-in person (spawn/door.ts). |
| 581 | 582 | router.add("GET", "/forges", forgesPage); |
| 583 | router.add("GET", "/family", familyPage); | |
| 582 | 584 | router.add("POST", "/forges/:name/claim-link", forgeLinkSubmit); |
| 583 | 585 | router.add("GET", "/forges/new", newForgePage); |
| 584 | 586 | router.add("POST", "/forges/new", newForgeSubmit); |
src/main.ts +4
| @@ -12,6 +12,7 @@ import { createApp } from "./app.ts"; | ||
| 12 | 12 | import { reconcile } from "./core/reconcile.ts"; |
| 13 | 13 | import { syncAllPillars } from "./actions/pillars.ts"; |
| 14 | 14 | import { firstBoot } from "./spawn/first-boot.ts"; |
| 15 | import { startHeartbeat } from "./spawn/heartbeat.ts"; | |
| 15 | 16 | import { pruneSessions } from "./core/sessions.ts"; |
| 16 | 17 | import { runDelivery } from "./core/webhooks.ts"; |
| 17 | 18 | import { isHookName, runHookClient } from "./git/hooks.ts"; |
| @@ -320,6 +321,8 @@ const crew = appsOn && !crewHeldOff | ||
| 320 | 321 | // A spawned child's first boot: its direction, opened once for its planner |
| 321 | 322 | // (spawn/first-boot.ts). A forge that was not spawned is untouched. |
| 322 | 323 | await firstBoot(app); |
| 324 | // A spawned child reports its standing to its parent (spawn/heartbeat.ts). | |
| 325 | const heartbeatTimer = startHeartbeat(app); | |
| 323 | 326 | // Prompts from Instagram (docs/APPS.md): once a day, for each repository |
| 324 | 327 | // that connected an account, the top comment on its latest Reel is told to |
| 325 | 328 | // the crew. A minute's clock; nothing leaves the box until a source exists. |
| @@ -465,6 +468,7 @@ function shutdown(signal: NodeJS.Signals): void { | ||
| 465 | 468 | // process that replaced this one, not to this one while it finishes. |
| 466 | 469 | drainStreams(); |
| 467 | 470 | clearInterval(deliveryTimer); |
| 471 | clearInterval(heartbeatTimer); | |
| 468 | 472 | clearInterval(syncTimer); |
| 469 | 473 | clearInterval(staleTimer); |
| 470 | 474 | clearInterval(leaseTimer); |
src/spawn/heartbeat.ts added +244
| @@ -0,0 +1,244 @@ | ||
| 1 | /** | |
| 2 | * The family across forges (#425): a child tells its parent how it stands, | |
| 3 | * and the parent never reaches in. A heartbeat is a small signed JSON | |
| 4 | * document carrying the child's name, a time, its version and two counts — | |
| 5 | * open proposals and children of its own — and nothing else: no titles, no | |
| 6 | * names, no data. The parent keeps the last one per child under | |
| 7 | * `<data>/beats/<name>.json`. | |
| 8 | * | |
| 9 | * Signed with the key spawn gave both sides (`beatKey` in the parent's | |
| 10 | * ledger and in the child's `parent.json`): HMAC-SHA256 over the exact body | |
| 11 | * bytes. A name the parent did not make, a bad signature, a stale or | |
| 12 | * replayed time, a malformed body all get the same answer and change | |
| 13 | * nothing: unknown children are ignored. | |
| 14 | */ | |
| 15 | ||
| 16 | import { createHmac, timingSafeEqual } from "node:crypto"; | |
| 17 | import { mkdir, readFile, rename, writeFile } from "node:fs/promises"; | |
| 18 | import { join } from "node:path"; | |
| 19 | import type { App } from "../app.ts"; | |
| 20 | import { beatKeyOf, listChildren } from "../actions/spawn.ts"; | |
| 21 | import releases from "../core/releases.json" with { type: "json" }; | |
| 22 | import { running } from "../kernel/version.ts"; | |
| 23 | ||
| 24 | export const SIGNATURE_HEADER = "x-forge-signature"; | |
| 25 | /** A child reports this often; one silent for three beats reads as quiet. */ | |
| 26 | export const BEAT_MS = 10 * 60_000; | |
| 27 | export const QUIET_MS = 3 * BEAT_MS; | |
| 28 | /** A heartbeat's time may differ from the parent's clock by this much. */ | |
| 29 | const SKEW_MS = 10 * 60_000; | |
| 30 | const MAX_BODY = 1024; | |
| 31 | export const MAX_CHILDREN = 100; | |
| 32 | export const MAX_DEPTH = 4; | |
| 33 | const NAME = /^[a-z0-9](?:[a-z0-9-]{0,37}[a-z0-9])?$/; | |
| 34 | const VERSION = /^[0-9A-Za-z][0-9A-Za-z.+_-]{0,63}$/; | |
| 35 | const COUNT_MAX = 1_000_000; | |
| 36 | ||
| 37 | export interface Beat { | |
| 38 | readonly name: string; | |
| 39 | /** The child's clock, ms since the epoch. */ | |
| 40 | readonly at: number; | |
| 41 | readonly version: string; | |
| 42 | readonly openProposals: number; | |
| 43 | readonly children: number; | |
| 44 | } | |
| 45 | ||
| 46 | export function sign(key: string, body: string): string { | |
| 47 | return createHmac("sha256", key).update(body).digest("hex"); | |
| 48 | } | |
| 49 | ||
| 50 | function verified(key: string, body: string, shown: string | null): boolean { | |
| 51 | if (shown === null || !/^[0-9a-f]{64}$/.test(shown)) return false; | |
| 52 | return timingSafeEqual(Buffer.from(sign(key, body)), Buffer.from(shown)); | |
| 53 | } | |
| 54 | ||
| 55 | const count = (v: unknown): v is number => | |
| 56 | typeof v === "number" && Number.isInteger(v) && v >= 0 && v <= COUNT_MAX; | |
| 57 | ||
| 58 | /** The beat in `raw`, or undefined when it is not exactly one. */ | |
| 59 | export function parseBeat(raw: string): Beat | undefined { | |
| 60 | if (raw.length > MAX_BODY) return undefined; | |
| 61 | let doc: unknown; | |
| 62 | try { | |
| 63 | doc = JSON.parse(raw); | |
| 64 | } catch { | |
| 65 | return undefined; | |
| 66 | } | |
| 67 | if (typeof doc !== "object" || doc === null || Array.isArray(doc)) return undefined; | |
| 68 | const d = doc as Record<string, unknown>; | |
| 69 | const keys = Object.keys(d).sort().join(","); | |
| 70 | if (keys !== "at,children,name,openProposals,version") return undefined; | |
| 71 | const { name, at, version, openProposals, children } = d; | |
| 72 | if (typeof name !== "string" || !NAME.test(name)) return undefined; | |
| 73 | if (typeof at !== "number" || !Number.isSafeInteger(at) || at <= 0) return undefined; | |
| 74 | if (typeof version !== "string" || !VERSION.test(version)) return undefined; | |
| 75 | if (!count(openProposals) || !count(children)) return undefined; | |
| 76 | return { name, at, version, openProposals, children }; | |
| 77 | } | |
| 78 | ||
| 79 | const beatPath = (app: App, name: string): string => | |
| 80 | join(app.config.dataDir, "beats", `${name}.json`); | |
| 81 | ||
| 82 | /** What this forge heard, and when (ms), for one child. */ | |
| 83 | export interface Heard { | |
| 84 | readonly beat: Beat; | |
| 85 | readonly receivedAt: number; | |
| 86 | } | |
| 87 | ||
| 88 | async function lastHeard(app: App, name: string): Promise<Heard | undefined> { | |
| 89 | try { | |
| 90 | const doc = JSON.parse(await readFile(beatPath(app, name), "utf8")) as { | |
| 91 | receivedAt?: unknown; | |
| 92 | beat?: unknown; | |
| 93 | }; | |
| 94 | const beat = parseBeat(JSON.stringify(doc.beat)); | |
| 95 | return beat !== undefined && typeof doc.receivedAt === "number" | |
| 96 | ? { beat, receivedAt: doc.receivedAt } | |
| 97 | : undefined; | |
| 98 | } catch { | |
| 99 | return undefined; | |
| 100 | } | |
| 101 | } | |
| 102 | ||
| 103 | /** | |
| 104 | * Take one heartbeat. True when it was kept; false for every refusal, which | |
| 105 | * the caller answers alike so nothing says whether a name is a child. | |
| 106 | */ | |
| 107 | export async function receiveBeat( | |
| 108 | app: App, | |
| 109 | raw: string, | |
| 110 | signature: string | null, | |
| 111 | now = Date.now(), | |
| 112 | ): Promise<boolean> { | |
| 113 | const beat = parseBeat(raw); | |
| 114 | if (beat === undefined) return false; | |
| 115 | const key = await beatKeyOf(app, beat.name); | |
| 116 | if (key === undefined || !verified(key, raw, signature)) return false; | |
| 117 | if (Math.abs(now - beat.at) > SKEW_MS) return false; | |
| 118 | const before = await lastHeard(app, beat.name); | |
| 119 | if (before !== undefined && beat.at <= before.beat.at) return false; | |
| 120 | await mkdir(join(app.config.dataDir, "beats"), { recursive: true }); | |
| 121 | const path = beatPath(app, beat.name); | |
| 122 | await writeFile(`${path}.tmp`, JSON.stringify({ receivedAt: now, beat })); | |
| 123 | await rename(`${path}.tmp`, path); | |
| 124 | return true; | |
| 125 | } | |
| 126 | ||
| 127 | /** What a child knows of its parent from `parent.json`, when it has all of it. */ | |
| 128 | async function parentLink( | |
| 129 | app: App, | |
| 130 | ): Promise<{ name: string; upstream: string; key: string } | undefined> { | |
| 131 | try { | |
| 132 | const doc = (await Bun.file(join(app.config.dataDir, "parent.json")).json()) as Record<string, unknown>; | |
| 133 | const { name, upstream, beatKey } = doc; | |
| 134 | if (typeof name !== "string" || !NAME.test(name)) return undefined; | |
| 135 | if (typeof upstream !== "string" || !/^https?:\/\/[^\s?#]+$/.test(upstream)) return undefined; | |
| 136 | if (typeof beatKey !== "string" || beatKey === "") return undefined; | |
| 137 | return { name, upstream: upstream.replace(/\/+$/, ""), key: beatKey }; | |
| 138 | } catch { | |
| 139 | return undefined; | |
| 140 | } | |
| 141 | } | |
| 142 | ||
| 143 | /** This forge's standing, as the beat carries it. Counts only. */ | |
| 144 | export function standing(app: App, name: string, at = Date.now()): Beat { | |
| 145 | const proposals = app.db | |
| 146 | .query<{ n: number }, []>( | |
| 147 | `SELECT COUNT(*) AS n FROM pull JOIN issue ON issue.id = pull.issue_id WHERE issue.state = 'open'`, | |
| 148 | ) | |
| 149 | .get(); | |
| 150 | return { | |
| 151 | name, | |
| 152 | at, | |
| 153 | version: running().version, | |
| 154 | openProposals: Math.min(proposals?.n ?? 0, COUNT_MAX), | |
| 155 | children: 0, | |
| 156 | }; | |
| 157 | } | |
| 158 | ||
| 159 | type FetchLike = (url: string, init?: RequestInit) => Promise<Response>; | |
| 160 | let lastAt = 0; | |
| 161 | ||
| 162 | /** A spawned child's one report to its parent; false when it has no parent or the try failed. Never throws. */ | |
| 163 | export async function sendBeat( | |
| 164 | app: App, | |
| 165 | fetcher: FetchLike = fetch, | |
| 166 | now = Date.now(), | |
| 167 | ): Promise<boolean> { | |
| 168 | const link = await parentLink(app); | |
| 169 | if (link === undefined) return false; | |
| 170 | const own = (await listChildren(app)).length; | |
| 171 | // Strictly later than the last one sent, so a quick restart is not a replay. | |
| 172 | lastAt = Math.max(now, lastAt + 1); | |
| 173 | const body = JSON.stringify({ | |
| 174 | ...standing(app, link.name, lastAt), | |
| 175 | children: Math.min(own, COUNT_MAX), | |
| 176 | }); | |
| 177 | try { | |
| 178 | const res = await fetcher(`${link.upstream}/api/v1/heartbeat`, { | |
| 179 | method: "POST", | |
| 180 | headers: { "content-type": "application/json", [SIGNATURE_HEADER]: sign(link.key, body) }, | |
| 181 | body, | |
| 182 | signal: AbortSignal.timeout(5000), | |
| 183 | redirect: "error", | |
| 184 | }); | |
| 185 | return res.ok; | |
| 186 | } catch { | |
| 187 | return false; | |
| 188 | } | |
| 189 | } | |
| 190 | ||
| 191 | /** Report now and then every BEAT_MS; returns the timer to clear. */ | |
| 192 | export function startHeartbeat(app: App): ReturnType<typeof setInterval> { | |
| 193 | void sendBeat(app); | |
| 194 | return setInterval(() => void sendBeat(app), BEAT_MS); | |
| 195 | } | |
| 196 | ||
| 197 | export type Standing = "reporting" | "quiet" | "unheard"; | |
| 198 | ||
| 199 | export interface ChildStanding { | |
| 200 | readonly name: string; | |
| 201 | readonly url: string; | |
| 202 | readonly state: Standing; | |
| 203 | /** ms since the epoch the parent last heard, or null. */ | |
| 204 | readonly lastSeen: number | null; | |
| 205 | readonly version: string | null; | |
| 206 | /** Releases the child is behind this forge, or null when its version is not one of ours. */ | |
| 207 | readonly behind: number | null; | |
| 208 | readonly openProposals: number | null; | |
| 209 | readonly ownChildren: number | null; | |
| 210 | } | |
| 211 | ||
| 212 | /** How many releases of this forge are newer than `version`; null when it is not one of them. */ | |
| 213 | export function releasesBehind(version: string): number | null { | |
| 214 | const i = releases.releases.findIndex((r) => r.version === version); | |
| 215 | return i < 0 ? null : i; | |
| 216 | } | |
| 217 | ||
| 218 | /** Each child this forge made, as last heard; bounded, and a silent one is quiet, not broken. */ | |
| 219 | export async function childStandings( | |
| 220 | app: App, | |
| 221 | now = Date.now(), | |
| 222 | ): Promise<{ items: ChildStanding[]; more: number }> { | |
| 223 | const all = await listChildren(app); | |
| 224 | const items: ChildStanding[] = []; | |
| 225 | for (const c of all.slice(0, MAX_CHILDREN)) { | |
| 226 | const heard = await lastHeard(app, c.name); | |
| 227 | items.push({ | |
| 228 | name: c.name, | |
| 229 | url: c.url, | |
| 230 | state: heard === undefined ? "unheard" : now - heard.receivedAt > QUIET_MS ? "quiet" : "reporting", | |
| 231 | lastSeen: heard?.receivedAt ?? null, | |
| 232 | version: heard?.beat.version ?? null, | |
| 233 | behind: heard === undefined ? null : releasesBehind(heard.beat.version), | |
| 234 | openProposals: heard?.beat.openProposals ?? null, | |
| 235 | ownChildren: heard?.beat.children ?? null, | |
| 236 | }); | |
| 237 | } | |
| 238 | return { items, more: Math.max(0, all.length - MAX_CHILDREN) }; | |
| 239 | } | |
| 240 | ||
| 241 | /** The address of the forge that sent this one, when it was spawned and told. */ | |
| 242 | export async function parentUpstream(app: App): Promise<string | undefined> { | |
| 243 | return (await parentLink(app))?.upstream; | |
| 244 | } |
src/web/layout.ts +1
| @@ -324,6 +324,7 @@ function paletteIndex(ctx: Ctx, extra: PaletteItem[]): Html { | ||
| 324 | 324 | ? [ |
| 325 | 325 | { t: "Flow", h: "/flow", c: "Go to" }, |
| 326 | 326 | { t: "Forges you sent", h: "/forges", c: "Go to" }, |
| 327 | { t: "Family of forges", h: "/family", c: "Go to" }, | |
| 327 | 328 | ] |
| 328 | 329 | : []), |
| 329 | 330 | ]; |
src/web/pages/family.ts added +143
| @@ -0,0 +1,143 @@ | ||
| 1 | /** | |
| 2 | * `/family`: the forge-level family (#425). The forge this one was spawned | |
| 3 | * from, this forge, and the forges it sent, each with how it stands as it | |
| 4 | * last reported (`spawn/heartbeat.ts`). Nested lists, like the repository | |
| 5 | * family tree, bounded in depth and count. Anyone may see the parent; only | |
| 6 | * this forge's admins see its children. A child that stopped reporting | |
| 7 | * reads "quiet": a fact about the clock, not a fault. | |
| 8 | */ | |
| 9 | ||
| 10 | import type { Ctx } from "../../http/context.ts"; | |
| 11 | import { parentForgeFor } from "../../core/parent_releases.ts"; | |
| 12 | import { running } from "../../kernel/version.ts"; | |
| 13 | import { | |
| 14 | childStandings, | |
| 15 | parentUpstream, | |
| 16 | MAX_DEPTH, | |
| 17 | type ChildStanding, | |
| 18 | } from "../../spawn/heartbeat.ts"; | |
| 19 | import { pageHead } from "../chrome.ts"; | |
| 20 | import { html, type Html } from "../html.ts"; | |
| 21 | import { page } from "../layout.ts"; | |
| 22 | import { card, time } from "../ui.ts"; | |
| 23 | ||
| 24 | interface Node { | |
| 25 | readonly label: string; | |
| 26 | readonly href: string | null; | |
| 27 | readonly meta: readonly Html[]; | |
| 28 | readonly badge: Html | null; | |
| 29 | readonly here?: boolean; | |
| 30 | readonly children: readonly Node[]; | |
| 31 | } | |
| 32 | ||
| 33 | const plural = (n: number, one: string, many = `${one}s`) => | |
| 34 | `${n} ${n === 1 ? one : many}`; | |
| 35 | ||
| 36 | function standingNode(c: ChildStanding): Node { | |
| 37 | const meta: Html[] = []; | |
| 38 | if (c.state === "unheard") meta.push(html`has not reported yet`); | |
| 39 | else { | |
| 40 | if (c.lastSeen !== null) | |
| 41 | meta.push(html`last seen ${time(new Date(c.lastSeen).toISOString())}`); | |
| 42 | if (c.version !== null) meta.push(html`version ${c.version}`); | |
| 43 | if (c.behind !== null) | |
| 44 | meta.push(html`${c.behind === 0 ? "up to date" : `${plural(c.behind, "release")} behind`}`); | |
| 45 | if (c.openProposals !== null) | |
| 46 | meta.push(html`${plural(c.openProposals, "open proposal")}`); | |
| 47 | if (c.ownChildren !== null && c.ownChildren > 0) | |
| 48 | meta.push(html`${plural(c.ownChildren, "forge")} of its own`); | |
| 49 | } | |
| 50 | return { | |
| 51 | label: c.name, | |
| 52 | href: c.url, | |
| 53 | meta, | |
| 54 | badge: | |
| 55 | c.state === "reporting" | |
| 56 | ? html`<span class="pill" data-tone="accent">reporting</span>` | |
| 57 | : html`<span class="pill">quiet</span>`, | |
| 58 | children: [], | |
| 59 | }; | |
| 60 | } | |
| 61 | ||
| 62 | function row(n: Node, depth: number): Html { | |
| 63 | const inner = html`<span class="row-main"> | |
| 64 | <span class="row-title" | |
| 65 | >${n.label}${n.here ? html` <span class="lineage-here">you are here</span>` : null}</span | |
| 66 | > | |
| 67 | ${n.meta.length === 0 | |
| 68 | ? null | |
| 69 | : html`<span class="row-meta" | |
| 70 | >${n.meta.map((m, i) => html`${i > 0 ? " · " : ""}${m}`)}</span | |
| 71 | >`} | |
| 72 | </span> | |
| 73 | ${n.badge === null ? null : html`<span class="row-trail">${n.badge}</span>`}`; | |
| 74 | return html`<li> | |
| 75 | ${n.href === null | |
| 76 | ? html`<div class="row">${inner}</div>` | |
| 77 | : html`<a class="row" href="${n.href}" rel="noopener noreferrer">${inner}</a>`} | |
| 78 | ${n.children.length === 0 || depth + 1 >= MAX_DEPTH | |
| 79 | ? null | |
| 80 | : html`<ul class="lineage-children"> | |
| 81 | ${n.children.map((c) => row(c, depth + 1))} | |
| 82 | </ul>`} | |
| 83 | </li>`; | |
| 84 | } | |
| 85 | ||
| 86 | // GET /family | |
| 87 | export async function familyPage(ctx: Ctx): Promise<Response> { | |
| 88 | const app = ctx.app; | |
| 89 | const parent = parentForgeFor(app.config); | |
| 90 | const parentUrl = | |
| 91 | app.config.parentUrl ?? (await parentUpstream(app)); | |
| 92 | const owns = ctx.auth.user?.isAdmin === true; | |
| 93 | const kids = owns ? await childStandings(app) : { items: [], more: 0 }; | |
| 94 | ||
| 95 | const here: Node = { | |
| 96 | label: app.config.url === undefined ? "this forge" : new URL(app.config.url).host, | |
| 97 | href: null, | |
| 98 | meta: [html`version ${running().version}`], | |
| 99 | badge: null, | |
| 100 | here: true, | |
| 101 | children: kids.items.map(standingNode), | |
| 102 | }; | |
| 103 | const root: Node = | |
| 104 | parentUrl === undefined | |
| 105 | ? here | |
| 106 | : { | |
| 107 | label: parent?.host ?? new URL(parentUrl).host, | |
| 108 | href: parentUrl, | |
| 109 | meta: | |
| 110 | parent === null || parent.behind === null | |
| 111 | ? [] | |
| 112 | : [html`this forge is ${parent.behind === 0 ? "up to date" : plural(parent.behind, "release") + " behind"}`], | |
| 113 | badge: null, | |
| 114 | children: [here], | |
| 115 | }; | |
| 116 | ||
| 117 | const alone = parentUrl === undefined && kids.items.length === 0; | |
| 118 | return page({ | |
| 119 | ctx, | |
| 120 | title: "Family", | |
| 121 | body: html`<div class="narrow-wide"> | |
| 122 | ${pageHead("Family", { | |
| 123 | sub: "The forge this one came from, and the forges it sent. Children report in; nothing here reaches into one.", | |
| 124 | })} | |
| 125 | ${card( | |
| 126 | html`<ul class="list lineage" aria-label="Forges, by who sent whom"> | |
| 127 | ${row(root, 0)} | |
| 128 | </ul> | |
| 129 | ${kids.more > 0 | |
| 130 | ? html`<p class="muted small card-body"> | |
| 131 | ${plural(kids.more, "more forge")} not shown. | |
| 132 | </p>` | |
| 133 | : null} | |
| 134 | ${alone | |
| 135 | ? html`<p class="muted small card-body"> | |
| 136 | This forge has no parent and has sent none${owns ? "" : " that you can see"}. | |
| 137 | </p>` | |
| 138 | : null}`, | |
| 139 | { pad: false }, | |
| 140 | )} | |
| 141 | </div>`, | |
| 142 | }); | |
| 143 | } |
test/family-heartbeat.test.ts added +206
| @@ -0,0 +1,206 @@ | ||
| 1 | /** | |
| 2 | * The family across forges (#425): signed heartbeats carry counts and | |
| 3 | * version only, unknown children and bad signatures are ignored alike, a | |
| 4 | * silent child reads quiet, and only the parent's admins see children. | |
| 5 | */ | |
| 6 | ||
| 7 | import { afterAll, beforeAll, describe, expect, test } from "bun:test"; | |
| 8 | import { mkdtemp, readFile, rm } from "node:fs/promises"; | |
| 9 | import { tmpdir } from "node:os"; | |
| 10 | import { join } from "node:path"; | |
| 11 | import { createRepo } from "../src/actions/repos.ts"; | |
| 12 | import { beatKeyOf, childDirOf } from "../src/actions/spawn.ts"; | |
| 13 | import { createApp, type App } from "../src/app.ts"; | |
| 14 | import { createUser } from "../src/core/users.ts"; | |
| 15 | import { commitFiles } from "../src/git/write.ts"; | |
| 16 | import { repoDir } from "../src/git/repos.ts"; | |
| 17 | import { createToken } from "../src/core/tokens.ts"; | |
| 18 | import { serve, type Servers } from "../src/http/server.ts"; | |
| 19 | import { | |
| 20 | childStandings, | |
| 21 | parseBeat, | |
| 22 | QUIET_MS, | |
| 23 | sendBeat, | |
| 24 | sign, | |
| 25 | SIGNATURE_HEADER, | |
| 26 | } from "../src/spawn/heartbeat.ts"; | |
| 27 | import { firstBoot } from "../src/spawn/first-boot.ts"; | |
| 28 | import { quietLogs } from "./helpers/globals.ts"; | |
| 29 | ||
| 30 | quietLogs(); | |
| 31 | ||
| 32 | const PASSWORD = "a-long-family-passphrase"; | |
| 33 | ||
| 34 | describe("family heartbeats", () => { | |
| 35 | let dir = ""; | |
| 36 | let parent: App; | |
| 37 | let child: App; | |
| 38 | let servers: Servers; | |
| 39 | let key = ""; | |
| 40 | let adminCookie = ""; | |
| 41 | let bobCookie = ""; | |
| 42 | ||
| 43 | const post = (body: string, sig: string | null) => | |
| 44 | fetch(`${servers.url}/api/v1/heartbeat`, { | |
| 45 | method: "POST", | |
| 46 | headers: sig === null ? {} : { [SIGNATURE_HEADER]: sig }, | |
| 47 | body, | |
| 48 | }); | |
| 49 | const beat = (o: Record<string, unknown> = {}) => | |
| 50 | JSON.stringify({ | |
| 51 | name: "maria", | |
| 52 | at: Date.now(), | |
| 53 | version: "0.7.114", | |
| 54 | openProposals: 3, | |
| 55 | children: 0, | |
| 56 | ...o, | |
| 57 | }); | |
| 58 | const signIn = async (username: string) => { | |
| 59 | const res = await fetch(`${servers.url}/signin`, { | |
| 60 | method: "POST", | |
| 61 | body: new URLSearchParams({ username, password: PASSWORD }), | |
| 62 | redirect: "manual", | |
| 63 | }); | |
| 64 | return (res.headers.get("set-cookie") ?? "").split(";")[0]!; | |
| 65 | }; | |
| 66 | const family = async (cookie?: string) => | |
| 67 | ( | |
| 68 | await fetch(`${servers.url}/family`, { | |
| 69 | headers: cookie === undefined ? {} : { cookie }, | |
| 70 | }) | |
| 71 | ).text(); | |
| 72 | ||
| 73 | beforeAll(async () => { | |
| 74 | dir = await mkdtemp(join(tmpdir(), "forge-family-")); | |
| 75 | parent = createApp({ dataDir: dir, url: "https://forge.test", port: 0 }); | |
| 76 | const alice = await createUser(parent.db, { | |
| 77 | trusted: true, | |
| 78 | username: "alice", | |
| 79 | email: "[email protected]", | |
| 80 | password: PASSWORD, | |
| 81 | isAdmin: true, | |
| 82 | }); | |
| 83 | const bob = await createUser(parent.db, { | |
| 84 | trusted: true, | |
| 85 | username: "bob", | |
| 86 | email: "[email protected]", | |
| 87 | password: PASSWORD, | |
| 88 | }); | |
| 89 | if (!alice.ok || !bob.ok) throw new Error("users"); | |
| 90 | const token = createToken(parent.db, alice.value.id, "rw", "rw").token; | |
| 91 | const repo = await createRepo(parent, alice.value, { name: "bakery" }); | |
| 92 | if (!repo.ok) throw new Error("repo"); | |
| 93 | const c = await commitFiles(repoDir(parent.reposRoot, "alice", "bakery"), { | |
| 94 | branch: "main", | |
| 95 | message: "bakery", | |
| 96 | files: [{ path: "README.md", content: "# bakery\n" }], | |
| 97 | author: { name: "a", email: "[email protected]" }, | |
| 98 | }); | |
| 99 | if (!c.ok) throw new Error("commit"); | |
| 100 | servers = await serve(parent); | |
| 101 | const made = await fetch(`${servers.url}/api/v1/forges`, { | |
| 102 | method: "POST", | |
| 103 | headers: { authorization: `Bearer ${token}`, "content-type": "application/json" }, | |
| 104 | body: JSON.stringify({ name: "maria", apps: ["alice/bakery"], dryRun: false }), | |
| 105 | }); | |
| 106 | if (made.status !== 201) throw new Error(`spawn ${made.status}`); | |
| 107 | const { bodyId } = (await made.json()) as { bodyId: string }; | |
| 108 | child = createApp({ dataDir: childDirOf(parent, bodyId), port: 0 }); | |
| 109 | await firstBoot(child); | |
| 110 | key = (await beatKeyOf(parent, "maria")) ?? ""; | |
| 111 | adminCookie = await signIn("alice"); | |
| 112 | bobCookie = await signIn("bob"); | |
| 113 | }, 60_000); | |
| 114 | ||
| 115 | afterAll(async () => { | |
| 116 | servers.stop(); | |
| 117 | child.close(); | |
| 118 | parent.close(); | |
| 119 | await rm(dir, { recursive: true, force: true }); | |
| 120 | }); | |
| 121 | ||
| 122 | test("before any report a child reads as not heard from, not as an error", async () => { | |
| 123 | const html = await family(adminCookie); | |
| 124 | expect(html).toContain("maria"); | |
| 125 | expect(html).toContain("has not reported yet"); | |
| 126 | expect(html).toContain("quiet"); | |
| 127 | }); | |
| 128 | ||
| 129 | test("a heartbeat holds only name, time, version and two counts", () => { | |
| 130 | expect(parseBeat(beat())).toBeDefined(); | |
| 131 | expect(parseBeat(beat({ title: "secret plans" }))).toBeUndefined(); | |
| 132 | expect(parseBeat(beat({ openProposals: -1 }))).toBeUndefined(); | |
| 133 | expect(parseBeat(beat({ version: "<b>" }))).toBeUndefined(); | |
| 134 | expect(parseBeat(beat({ name: "../x" }))).toBeUndefined(); | |
| 135 | expect(parseBeat("x".repeat(5000))).toBeUndefined(); | |
| 136 | }); | |
| 137 | ||
| 138 | test("unknown children, bad signatures and stale times are ignored alike", async () => { | |
| 139 | const stranger = beat({ name: "nobody" }); | |
| 140 | const a = await post(stranger, sign(key, stranger)); | |
| 141 | const own = beat(); | |
| 142 | const b = await post(own, sign("not-the-key", own)); | |
| 143 | const c = await post(own, null); | |
| 144 | const old = beat({ at: Date.now() - 3_600_000 }); | |
| 145 | const d = await post(old, sign(key, old)); | |
| 146 | for (const r of [a, b, c, d]) expect(r.status).toBe(404); | |
| 147 | const state = await childStandings(parent); | |
| 148 | expect(state.items[0]?.state).toBe("unheard"); | |
| 149 | }); | |
| 150 | ||
| 151 | test("a signed heartbeat is kept, shown with its standing, and not replayable", async () => { | |
| 152 | const at = Date.now(); | |
| 153 | const body = beat({ at }); | |
| 154 | expect((await post(body, sign(key, body))).status).toBe(200); | |
| 155 | expect((await post(body, sign(key, body))).status).toBe(404); | |
| 156 | const html = await family(adminCookie); | |
| 157 | expect(html).toContain("reporting"); | |
| 158 | expect(html).toContain("version 0.7.114"); | |
| 159 | expect(html).toContain("3 open proposals"); | |
| 160 | expect(html).toMatch(/\d+ releases? behind/); | |
| 161 | const stored = await readFile(join(dir, "beats", "maria.json"), "utf8"); | |
| 162 | expect(Object.keys(JSON.parse(stored).beat).sort()).toEqual([ | |
| 163 | "at", | |
| 164 | "children", | |
| 165 | "name", | |
| 166 | "openProposals", | |
| 167 | "version", | |
| 168 | ]); | |
| 169 | }); | |
| 170 | ||
| 171 | test("a child that stops reporting reads quiet", async () => { | |
| 172 | const state = await childStandings(parent, Date.now() + QUIET_MS + 60_000); | |
| 173 | expect(state.items[0]?.state).toBe("quiet"); | |
| 174 | expect(state.items[0]?.lastSeen).not.toBeNull(); | |
| 175 | }); | |
| 176 | ||
| 177 | test("only an admin of the parent sees children", async () => { | |
| 178 | expect(await family(bobCookie)).not.toContain("maria"); | |
| 179 | expect(await family()).not.toContain("maria"); | |
| 180 | expect(await family(adminCookie)).toContain("maria"); | |
| 181 | }); | |
| 182 | ||
| 183 | test("a child sends its own beat, signed with the key spawn gave it", async () => { | |
| 184 | const sent: { url: string; body: string; sig: string }[] = []; | |
| 185 | const ok = await sendBeat(child, async (url, init) => { | |
| 186 | sent.push({ | |
| 187 | url, | |
| 188 | body: String(init?.body), | |
| 189 | sig: String((init?.headers as Record<string, string>)[SIGNATURE_HEADER]), | |
| 190 | }); | |
| 191 | return new Response("{}"); | |
| 192 | }); | |
| 193 | expect(ok).toBe(true); | |
| 194 | expect(sent[0]?.url).toBe("https://forge.test/api/v1/heartbeat"); | |
| 195 | expect(sent[0]?.sig).toBe(sign(key, sent[0]!.body)); | |
| 196 | expect(Object.keys(JSON.parse(sent[0]!.body)).sort()).toEqual([ | |
| 197 | "at", | |
| 198 | "children", | |
| 199 | "name", | |
| 200 | "openProposals", | |
| 201 | "version", | |
| 202 | ]); | |
| 203 | // A forge that was not spawned has no one to tell. | |
| 204 | expect(await sendBeat(parent, async () => new Response("{}"))).toBe(false); | |
| 205 | }); | |
| 206 | }); |
test/spawn-keys.test.ts +1
| @@ -357,6 +357,7 @@ describe("a spawned child's own keys and domain", () => { | ||
| 357 | 357 | await Bun.file(join(childDir, "parent.json")).text(), |
| 358 | 358 | ) as Record<string, unknown>; |
| 359 | 359 | expect(Object.keys(record).sort()).toEqual([ |
| 360 | "beatKey", | |
| 360 | 361 | "keepAccess", |
| 361 | 362 | "name", |
| 362 | 363 | "org", |
test/spawn.test.ts +2
| @@ -86,6 +86,8 @@ describe("spawnForge", () => { | ||
| 86 | 86 | keepAccess: false, |
| 87 | 87 | // A hash only: what the parent answers to stays in its own ledger. |
| 88 | 88 | statusHash: expect.stringMatching(/^[0-9a-f]{64}$/), |
| 89 | // The child signs heartbeats to its parent with it (#425). | |
| 90 | beatKey: expect.stringMatching(/^[A-Za-z0-9_-]{20,}$/), | |
| 89 | 91 | }); |
| 90 | 92 | }); |
| 91 | 93 |
new above
offline