Public: anyone can read this; the crew can change it.
Add a machine gives one line to paste, served by the forge, that installs a service that stays up and reports the machine's own os, arch, docker and xcode #18522
Conflicts with main in 5 files
src/checks/runner_jobs.ts · src/http/lazy_lists.ts · src/http/marks/settings.json · and 2 more
torque/forge:torque/18491-add-a-machine-gives-one-line-to-paste-se → main 5 commits fork 6 threads · 6 unresolved
33 files
changed +977
−13
- docs/features/machine-join.md
- src/actions/machine_join.ts
- src/checks/runner_jobs.ts
- src/contract/openapi/routes/getApiV1AgentInstallSh.ts
- src/contract/openapi/routes/getApiV1AgentRunnerJs.ts
- src/contract/openapi/routes/index.ts
- src/contract/openapi/routes/postApiV1AdminMachinesJoin.ts
- src/contract/openapi/routes/postApiV1AgentJoin.ts
- src/core/account_purge.ts
- src/core/event_audience.ts
- src/core/migration-pins/20261206180000-machine-join.pin
- src/core/migrations/20261206180000-machine-join.ts
- src/http/api.ts
- src/http/api/agent_join.ts
- src/http/api/runners.ts
- src/http/lazy_lists.ts
- src/http/marks/settings.json
- src/http/settings_routes.ts
- src/machines/facts.ts
- src/machines/install.sh
- src/machines/join.ts
- src/machines/protocol.ts
- src/machines/runner_bundle.ts
- src/runner/main.ts
- src/tui/screens/addmachine.ts
- src/tui/screens/runners.ts
- src/web/pages/runners.ts
- test/data-browser.test.ts
- test/machine-join.test.ts
- test/route-timing-coverage.test.ts
- test/settings-runners.test.ts
- test/spawn-pipes.test.ts
- test/spawn-sites.test.ts
docs/features/machine-join.md added +49
| @@ -0,0 +1,49 @@ | ||
| 1 | --- | |
| 2 | topic: Ship and undo | |
| 3 | row: Add a machine: one line to paste, served by the forge, that installs a runner service and reports the machine's own os, arch, docker and xcode | |
| 4 | --- | |
| 5 | # Add a machine (#18491) | |
| 6 | ||
| 7 | A forge admin opens **Settings → Runners → Add a machine** (`/settings/runners`) and presses | |
| 8 | *Get the line* (a form: the next page shows the line once); in the terminal, **Runners** (`a`) shows the same line; over the API, | |
| 9 | `POST /api/v1/admin/machines/join`. The line is a `curl` to this forge's own installer: | |
| 10 | ||
| 11 | sh | |
| 12 | curl -fsSL https://your.forge/api/v1/agent/install.sh | FORGE_URL=https://your.forge FORGE_JOIN=fjoin_… sh | |
| 13 | ||
| 14 | ||
| 15 | **The forge is trusted to run code on the machine.** The service fetches the runner from the forge | |
| 16 | before every start and runs it with the runner's token, so the road must be https: the line is made | |
| 17 | only for an https forge address (plain http only to `localhost`), and the installer refuses any | |
| 18 | other, and refuses to run as root (every check would run as root). A forge with no https `url` | |
| 19 | set says so instead of printing a line; in the terminal, a forge with no public `url` prints a line | |
| 20 | for this machine only and says so. | |
| 21 | ||
| 22 | **The line is a credential.** Its code is 256 random bits, kept only as a hash, good once and for 15 | |
| 23 | minutes, and at most twenty wait unused per admin. Spending it enrols one runner (the runner role: | |
| 24 | it claims work and reports on it, and may send no box message) and hands the installer that | |
| 25 | runner's token, once. A wrong, used or expired code is one `403 join_refused`. The two downloads are limited per address, and a failed `runner.js` build is not tried again for a minute. | |
| 26 | ||
| 27 | On the machine (needs `curl`, `git`, `bun`; run it as the user that should run checks) the | |
| 28 | installer keeps the token in `~/.forge-runner/env` (mode 600) and installs a launchd agent | |
| 29 | (`sh.forge.runner`, macOS) or a systemd unit (`forge-runner`, a user unit). The | |
| 30 | service fetches `GET /api/v1/agent/runner.js` (the runner, bundled by the forge) before each start, | |
| 31 | so it follows the forge's build, and starts again if it stops. | |
| 32 | ||
| 33 | ## What the machine says | |
| 34 | ||
| 35 | The runner detects, with fixed commands and nothing typed, its **os** (`macos`/`linux`), **arch** | |
| 36 | (`arm64`/`x64`), **docker** (`docker info` answers) and **xcode** (`xcodebuild -version`), and says | |
| 37 | them with every claim and in the protocol's heartbeat (`facts`). They show beside the runner on both | |
| 38 | doors. | |
| 39 | ||
| 40 | They only **narrow routing**: a job whose `forge.json` check names the label `docker`, `macos`, | |
| 41 | `arm64` or `xcode` goes to a machine that says it has it, so a machine that says less is offered | |
| 42 | fewer jobs. They never touch the repositories a runner serves, its scope, trust for secrets, pause | |
| 43 | or revocation: those stay the admin's. A lent runner's facts add no label. A machine that lies | |
| 44 | about docker is handed jobs it fails; it is handed nothing it could not have had. | |
| 45 | ||
| 46 | Not yet: Windows, and removing the service from the machine (the admin removes the runner here; on | |
| 47 | the machine `launchctl bootout gui/$(id -u)/sh.forge.runner` or `systemctl disable --now forge-runner`). | |
| 48 | A forge that runs from a bundle with no source beside it cannot build `runner.js`: the installer says | |
| 49 | so and the runner is run from a checkout as in [](runners.md). |
src/actions/machine_join.ts added +48
| @@ -0,0 +1,48 @@ | ||
| 1 | /** | |
| 2 | * Add a machine (#18491). An admin asks for one line to paste (`offerJoin`); the machine that runs | |
| 3 | * it spends the line's code (`joinMachine`) and is enrolled as a runner, the role that claims work | |
| 4 | * and reports on it and nothing else. Each is an event, the audit; the code and the token are in | |
| 5 | * neither. Anyone but a forge admin who is a person is told it is not there. | |
| 6 | */ | |
| 7 | ||
| 8 | import type { App } from "../app.ts"; | |
| 9 | import { enrolRunner } from "../checks/runner_jobs.ts"; | |
| 10 | import type { User } from "../core/users.ts"; | |
| 11 | import { err, ok, type Result } from "../kernel/result.ts"; | |
| 12 | import { JOIN_TTL_MS, isJoinCode, isSecureOrigin, joinLine, machineName, mintJoin, spendJoin } from "../machines/join.ts"; | |
| 13 | import { publicOrigin } from "../core/public_origin.ts"; | |
| 14 | ||
| 15 | export interface Offer { | |
| 16 | readonly line: string; | |
| 17 | readonly expiresAt: number; | |
| 18 | readonly minutes: number; | |
| 19 | } | |
| 20 | ||
| 21 | /** The line to paste, made now for this admin; `fallback` is the origin the request came in on. */ | |
| 22 | export function offerJoin(app: App, actor: User | undefined, fallback: string): Result<Offer, "not_found" | "too_many" | "insecure"> { | |
| 23 | if (actor === undefined || !actor.isAdmin || actor.kind !== "user") return err("not_found"); | |
| 24 | const origin = publicOrigin(app.config.url, fallback); | |
| 25 | // Before a code is minted: a line nobody may paste spends none of the admin's twenty. | |
| 26 | if (!isSecureOrigin(origin)) return err("insecure"); | |
| 27 | const now = Date.now(); | |
| 28 | const made = mintJoin(app.db, actor.id, now); | |
| 29 | if (made === undefined) return err("too_many"); | |
| 30 | const line = joinLine(origin, made.code); | |
| 31 | if (line === undefined) return err("not_found"); | |
| 32 | app.bus.append({ kind: "machine.join_offered", actorId: actor.id, payload: { expiresAt: made.expiresAt } }); | |
| 33 | return ok({ line, expiresAt: made.expiresAt, minutes: Math.round(JOIN_TTL_MS / 60_000) }); | |
| 34 | } | |
| 35 | ||
| 36 | /** | |
| 37 | * A machine spends its code: one runner enrolled, its token given once; `refused` says nothing | |
| 38 | * more. | |
| 39 | */ | |
| 40 | export function joinMachine(app: App, code: unknown, name: unknown): Result<{ id: string; name: string; token: string }, "refused"> { | |
| 41 | if (!isJoinCode(code)) return err("refused"); | |
| 42 | const now = Date.now(); | |
| 43 | const minted = spendJoin(app.db, code, now); | |
| 44 | if (minted === undefined) return err("refused"); | |
| 45 | const made = enrolRunner(app.db, machineName(name), minted.adminId, undefined, now); | |
| 46 | app.bus.append({ kind: "machine.joined", actorId: minted.adminId, payload: { id: made.runner.id, name: made.runner.name } }); | |
| 47 | return ok({ id: made.runner.id, name: made.runner.name, token: made.token }); | |
| 48 | } |
src/checks/runner_jobs.ts +32 −8
| @@ -20,6 +20,7 @@ | ||
| 20 | 20 | import type { Database } from "bun:sqlite"; |
| 21 | 21 | import type { App } from "../app.ts"; |
| 22 | 22 | import { sha256 } from "../kernel/hash.ts"; |
| 23 | import { factLabels, factsWords, parseFacts, readFacts, type Facts } from "../machines/facts.ts"; | |
| 23 | 24 | import { boxAuthors, boxSpareMiB } from "../games/lend_fit.ts"; |
| 24 | 25 | import { startProof } from "../games/lent_proof.ts"; |
| 25 | 26 | import { id, secret } from "../kernel/id.ts"; |
| @@ -161,6 +162,10 @@ export interface Enrolled { | ||
| 161 | 162 | readonly labels: readonly string[]; |
| 162 | 163 | /** The repositories (ids) it serves; none listed is every one, as a runner always did. */ |
| 163 | 164 | readonly repos: readonly string[]; |
| 165 | /** | |
| 166 | * What it last said it is (`machines/facts.ts`): os, arch, docker, xcode; none before it said. | |
| 167 | */ | |
| 168 | readonly facts?: Facts; | |
| 164 | 169 | /** What it last said in its heartbeat: `idle`, `busy` or `paused`; "" before one. */ |
| 165 | 170 | readonly state: string; |
| 166 | 171 | /** Whether a site admin marked it trusted for secrets (`environment.ts`). */ |
| @@ -188,8 +193,9 @@ type RunnerRow = { | ||
| 188 | 193 | repos: string; |
| 189 | 194 | state: string; |
| 190 | 195 | trusted_at: number; |
| 196 | facts: string; | |
| 191 | 197 | }; |
| 192 | const RUNNER_COLUMNS = "id, name, created_at, seen_at, scope, core_ms, day, day_core_ms, paused, revoked_at, jobs, cpus, memory_mib, host_cpus, labels, repos, state, trusted_at"; | |
| 198 | const RUNNER_COLUMNS = "id, name, created_at, seen_at, scope, core_ms, day, day_core_ms, paused, revoked_at, jobs, cpus, memory_mib, host_cpus, labels, repos, state, trusted_at, facts"; | |
| 193 | 199 | |
| 194 | 200 | /** A JSON array of strings as kept in a column; anything else is none. */ |
| 195 | 201 | const stringList = (raw: string): string[] => { |
| @@ -218,6 +224,7 @@ const toEnrolled = (r: RunnerRow, now: number = Date.now()): Enrolled => { | ||
| 218 | 224 | hostCpus: r.host_cpus, |
| 219 | 225 | labels: stringList(r.labels), |
| 220 | 226 | repos: stringList(r.repos), |
| 227 | ...(parseFacts(r.facts) === undefined ? {} : { facts: parseFacts(r.facts)! }), | |
| 221 | 228 | state: r.state, |
| 222 | 229 | trusted: r.trusted_at > 0, |
| 223 | 230 | }; |
| @@ -341,8 +348,9 @@ export function pauseRunner(db: Database, runnerId: string, why: string): boolea | ||
| 341 | 348 | * its token's lookup. Labels are never taken from it: the admin's registration is their only |
| 342 | 349 | * source. |
| 343 | 350 | */ |
| 344 | export function noteHeartbeat(db: Database, runnerId: string, said: { state: string }): void { | |
| 351 | export function noteHeartbeat(db: Database, runnerId: string, said: { state: string; facts?: unknown }): void { | |
| 345 | 352 | db.query("UPDATE check_runner SET state = ?2 WHERE id = ?1").run(runnerId, said.state); |
| 353 | noteRunnerFacts(db, runnerId, said.facts); | |
| 346 | 354 | } |
| 347 | 355 | |
| 348 | 356 | /** |
| @@ -355,7 +363,7 @@ export function labelServed(db: Database, repoId: string, label: string, now: nu | ||
| 355 | 363 | .query<{ n: number }, [number, string, string]>( |
| 356 | 364 | `SELECT COUNT(*) AS n FROM check_runner |
| 357 | 365 | WHERE seen_at > ?1 - ${SEEN_FRESH_MS} AND revoked_at = 0 AND paused = '' AND state != 'paused' |
| 358 | AND EXISTS (SELECT 1 FROM json_each(labels) WHERE value = ?3) | |
| 366 | AND (EXISTS (SELECT 1 FROM json_each(labels) WHERE value = ?3) OR (scope IS NULL AND EXISTS (SELECT 1 FROM json_each(said_labels) WHERE value = ?3))) | |
| 359 | 367 | AND (repos = '[]' OR EXISTS (SELECT 1 FROM json_each(repos) WHERE value = ?2)) |
| 360 | 368 | AND (scope IS NULL OR EXISTS (SELECT 1 FROM repo r WHERE r.id = ?2 AND r.visibility = 'public'))`, |
| 361 | 369 | ) |
| @@ -451,10 +459,11 @@ export function noteRunnerJobs(db: Database, runnerId: string, said: unknown): v | ||
| 451 | 459 | * A runner's machine in words, as both doors show it: "16 cores and 24 GiB, on a 72-core host"; |
| 452 | 460 | * nothing before its first claim says it. |
| 453 | 461 | */ |
| 454 | export function runnerMachineWords(r: Pick<Enrolled, "cpus" | "memoryMiB" | "hostCpus">): string { | |
| 455 | if (r.cpus === 0) return ""; | |
| 462 | export function runnerMachineWords(r: Pick<Enrolled, "cpus" | "memoryMiB" | "hostCpus" | "facts">): string { | |
| 463 | const said = r.facts === undefined ? "" : factsWords(r.facts); | |
| 464 | if (r.cpus === 0) return said; | |
| 456 | 465 | const gib = Math.round(r.memoryMiB / 102.4) / 10; |
| 457 | return `${r.cpus} cores and ${gib} GiB${r.hostCpus > r.cpus ? `, on a ${r.hostCpus}-core host` : ""}`; | |
| 466 | return `${r.cpus} cores and ${gib} GiB${r.hostCpus > r.cpus ? `, on a ${r.hostCpus}-core host` : ""}${said === "" ? "" : ` · ${said}`}`; | |
| 458 | 467 | } |
| 459 | 468 | |
| 460 | 469 | /** |
| @@ -470,6 +479,7 @@ const MACHINE_MAX = { cpus: 4096, memoryMiB: 64 * 1024 * 1024 }; | ||
| 470 | 479 | export function noteRunnerMachine(db: Database, runnerId: string, said: unknown): void { |
| 471 | 480 | if (typeof said !== "object" || said === null) return; |
| 472 | 481 | const m = said as Record<string, unknown>; |
| 482 | noteRunnerFacts(db, runnerId, m["facts"]); | |
| 473 | 483 | const whole = (v: unknown, max: number): number | undefined => (typeof v === "number" && Number.isInteger(v) && v >= 1 && v <= max ? v : undefined); |
| 474 | 484 | const cpus = whole(m["cpus"], MACHINE_MAX.cpus); |
| 475 | 485 | const memoryMiB = whole(m["memoryMiB"], MACHINE_MAX.memoryMiB); |
| @@ -480,6 +490,17 @@ export function noteRunnerMachine(db: Database, runnerId: string, said: unknown) | ||
| 480 | 490 | ).run(runnerId, cpus, memoryMiB, hostCpus); |
| 481 | 491 | } |
| 482 | 492 | |
| 493 | /** | |
| 494 | * Keep what a runner says its machine is (os, arch, docker, xcode) and the label words those make | |
| 495 | * (`said_labels`); a malformed answer is ignored and an unchanged one writes nothing. Never touches | |
| 496 | * `labels`, `repos`, scope or trust. | |
| 497 | */ | |
| 498 | export function noteRunnerFacts(db: Database, runnerId: string, said: unknown): void { | |
| 499 | const facts = readFacts(said); | |
| 500 | if (facts === undefined) return; | |
| 501 | db.query("UPDATE check_runner SET facts = ?2, said_labels = ?3 WHERE id = ?1 AND facts != ?2").run(runnerId, JSON.stringify(facts), JSON.stringify(factLabels(facts))); | |
| 502 | } | |
| 503 | ||
| 483 | 504 | /** |
| 484 | 505 | * Put a check's steps on the desk. `dir` is the bare repository the commit is in; it stays here. |
| 485 | 506 | */ |
| @@ -533,6 +554,7 @@ type ClaimRow = { | ||
| 533 | 554 | canary_at: number; |
| 534 | 555 | box_id: string; |
| 535 | 556 | labels: string; |
| 557 | said_labels: string; | |
| 536 | 558 | repos: string; |
| 537 | 559 | state: string; |
| 538 | 560 | }; |
| @@ -549,7 +571,7 @@ export function claimJob( | ||
| 549 | 571 | ): Claim | undefined { |
| 550 | 572 | const me = db |
| 551 | 573 | .query<ClaimRow, [string]>( |
| 552 | "SELECT id, name, created_at, scope, day, day_core_ms, paused, revoked_at, salt, ran, canary_at, box_id, labels, repos, state FROM check_runner WHERE id = ?1", | |
| 574 | "SELECT id, name, created_at, scope, day, day_core_ms, paused, revoked_at, salt, ran, canary_at, box_id, labels, said_labels, repos, state FROM check_runner WHERE id = ?1", | |
| 553 | 575 | ) |
| 554 | 576 | .get(runner.id); |
| 555 | 577 | // A runner that said `paused` in its heartbeat (a Mac on battery) takes nothing until it says |
| @@ -568,7 +590,9 @@ export function claimJob( | ||
| 568 | 590 | // which is 0 while a server wakes (`games/lend_fit.ts`); -1 for one that is not. |
| 569 | 591 | // A job naming a label goes only to a runner holding it, and a runner that lists repositories |
| 570 | 592 | // serves only those (#18037); both are `[]` for a runner as it always was. |
| 571 | const labels = me.labels; | |
| 593 | // The labels its own facts make (`machines/facts.ts`) are added for a runner this forge owns | |
| 594 | // the enrolment of, never a lent one: they only decide which labelled jobs it may be offered. | |
| 595 | const labels = scope === undefined ? JSON.stringify([...new Set([...stringList(me.labels), ...stringList(me.said_labels)])]) : me.labels; | |
| 572 | 596 | const repos = me.repos; |
| 573 | 597 | const spareMiB = me.box_id === "" ? -1 : boxSpareMiB(db, me.box_id, now); |
| 574 | 598 | const queued = |
src/contract/openapi/routes/getApiV1AgentInstallSh.ts added +12
| @@ -0,0 +1,12 @@ | ||
| 1 | import type { Route } from "../shared.ts"; | |
| 2 | ||
| 3 | export const route: Route = { | |
| 4 | method: "get", | |
| 5 | path: "/api/v1/agent/install.sh", | |
| 6 | summary: "The forge's installer for a machine: a shell script with no secret in it", | |
| 7 | detail: | |
| 8 | "The script the line an admin pastes fetches (`machines/install.sh`). It needs `FORGE_URL` and `FORGE_JOIN` in its environment, joins once, keeps the runner token in a mode 600 file, and installs launchd or systemd so the runner stays up. The same for everyone: it holds nothing of this forge's but its own address, which the caller gives it", | |
| 9 | auth: false, | |
| 10 | role: "anonymous", | |
| 11 | refuses: [], | |
| 12 | }; |
src/contract/openapi/routes/getApiV1AgentRunnerJs.ts added +13
| @@ -0,0 +1,13 @@ | ||
| 1 | import type { Route } from "../shared.ts"; | |
| 2 | ||
| 3 | export const route: Route = { | |
| 4 | method: "get", | |
| 5 | path: "/api/v1/agent/runner.js", | |
| 6 | summary: "The runner this forge runs, as one file for a machine to fetch", | |
| 7 | detail: | |
| 8 | "`src/runner/main.ts` bundled at first use, served with an ETag so a machine that holds it gets a 304. A forge with no source beside it answers 404 `no_runner_here`. The service an added machine runs fetches this before each start, so it follows the forge's build", | |
| 9 | auth: false, | |
| 10 | role: "anonymous", | |
| 11 | refusals: { no_runner_here: "404: this forge cannot build a runner" }, | |
| 12 | refuses: [], | |
| 13 | }; |
src/contract/openapi/routes/index.ts +4
| @@ -79,6 +79,8 @@ export { route as getApiV1AdminSubscriptions } from "./getApiV1AdminSubscription | ||
| 79 | 79 | export { route as getApiV1AdminTeams } from "./getApiV1AdminTeams.ts"; |
| 80 | 80 | export { route as getApiV1AdminTrafficProbe } from "./getApiV1AdminTrafficProbe.ts"; |
| 81 | 81 | export { route as getApiV1AdminTrafficVisitors } from "./getApiV1AdminTrafficVisitors.ts"; |
| 82 | export { route as getApiV1AgentInstallSh } from "./getApiV1AgentInstallSh.ts"; | |
| 83 | export { route as getApiV1AgentRunnerJs } from "./getApiV1AgentRunnerJs.ts"; | |
| 82 | 84 | export { route as getApiV1Agents } from "./getApiV1Agents.ts"; |
| 83 | 85 | export { route as getApiV1AgentsUsername } from "./getApiV1AgentsUsername.ts"; |
| 84 | 86 | export { route as getApiV1AppTemplates } from "./getApiV1AppTemplates.ts"; |
| @@ -361,6 +363,7 @@ export { route as postApiV1AdminInvites } from "./postApiV1AdminInvites.ts"; | ||
| 361 | 363 | export { route as postApiV1AdminLending } from "./postApiV1AdminLending.ts"; |
| 362 | 364 | export { route as postApiV1AdminLendingIdResume } from "./postApiV1AdminLendingIdResume.ts"; |
| 363 | 365 | export { route as postApiV1AdminLendingIdStop } from "./postApiV1AdminLendingIdStop.ts"; |
| 366 | export { route as postApiV1AdminMachinesJoin } from "./postApiV1AdminMachinesJoin.ts"; | |
| 364 | 367 | export { route as postApiV1AdminMaintenancePrepare } from "./postApiV1AdminMaintenancePrepare.ts"; |
| 365 | 368 | export { route as postApiV1AdminMaintenanceResume } from "./postApiV1AdminMaintenanceResume.ts"; |
| 366 | 369 | export { route as postApiV1AdminPinned } from "./postApiV1AdminPinned.ts"; |
| @@ -378,6 +381,7 @@ export { route as postApiV1AdminRunnersIdPause } from "./postApiV1AdminRunnersId | ||
| 378 | 381 | export { route as postApiV1AdminRunnersIdResume } from "./postApiV1AdminRunnersIdResume.ts"; |
| 379 | 382 | export { route as postApiV1AdminRunnersIdRevoke } from "./postApiV1AdminRunnersIdRevoke.ts"; |
| 380 | 383 | export { route as postApiV1AdminRunnersIdTrust } from "./postApiV1AdminRunnersIdTrust.ts"; |
| 384 | export { route as postApiV1AgentJoin } from "./postApiV1AgentJoin.ts"; | |
| 381 | 385 | export { route as postApiV1AgentV1Message } from "./postApiV1AgentV1Message.ts"; |
| 382 | 386 | export { route as postApiV1Agents } from "./postApiV1Agents.ts"; |
| 383 | 387 | export { route as postApiV1Apps } from "./postApiV1Apps.ts"; |
src/contract/openapi/routes/postApiV1AdminMachinesJoin.ts added +15
| @@ -0,0 +1,15 @@ | ||
| 1 | import type { Route } from "../shared.ts"; | |
| 2 | ||
| 3 | export const route: Route = { | |
| 4 | method: "post", | |
| 5 | path: "/api/v1/admin/machines/join", | |
| 6 | summary: "Make the one line to paste on a machine to add it (admin)", | |
| 7 | detail: | |
| 8 | "A forge admin's request for `{ line, expiresAt, minutes }`: a curl to this forge's own installer with a one-use join code, good for fifteen minutes. The line is a credential. At most twenty wait unused per admin (429 `too_many_lines`)", | |
| 9 | auth: true, | |
| 10 | role: "admin", | |
| 11 | status: 201, | |
| 12 | reply: { line: "string", expiresAt: "integer", minutes: "integer" }, | |
| 13 | refusals: { too_many_lines: "429: twenty lines wait unused" }, | |
| 14 | refuses: [404], | |
| 15 | }; |
src/contract/openapi/routes/postApiV1AgentJoin.ts added +17
| @@ -0,0 +1,17 @@ | ||
| 1 | import type { Route } from "../shared.ts"; | |
| 2 | ||
| 3 | export const route: Route = { | |
| 4 | method: "post", | |
| 5 | path: "/api/v1/agent/join", | |
| 6 | summary: "A machine spends its one-use join code and is enrolled as a runner", | |
| 7 | detail: | |
| 8 | "What the installer of an added machine sends (`machines/install.sh`): `{ code, name }`. The code is the one in the line an admin pasted; it works once and for fifteen minutes. The answer holds the runner token, once, with the role `runner`: it claims work and reports on it and nothing else. A code that is wrong, used or expired is one 403 `join_refused` that says no more", | |
| 9 | auth: false, | |
| 10 | role: "anonymous", | |
| 11 | body: { code: "string", name: "string" }, | |
| 12 | status: 201, | |
| 13 | reply: { id: "string", name: "string", role: "string", token: "string" }, | |
| 14 | refusals: { join_refused: "403: the code is wrong, used or expired" }, | |
| 15 | refuses: [], | |
| 16 | errorStatus: { 403: "`join_refused`: the join code is not good" }, | |
| 17 | }; |
src/core/account_purge.ts +2
| @@ -100,6 +100,8 @@ export const COVERED: Readonly<Record<string, Coverage>> = { | ||
| 100 | 100 | "bet.backed_by": FORMER, |
| 101 | 101 | "check_proven.proven_by": FORMER, |
| 102 | 102 | "check_runner.created_by": FORMER, |
| 103 | // A one-line join code is its maker's to give: it goes with them. | |
| 104 | "machine_join.created_by": DELETE, | |
| 103 | 105 | "check_job.author": { do: "none", why: "the login a lent runner's authors scope matches, copied from the pull while its check is in flight" }, |
| 104 | 106 | "child_reach_ask.asked_by": FORMER, |
| 105 | 107 | "child_reach_ask.answered_by": FORMER, |
src/core/event_audience.ts +4
| @@ -267,6 +267,10 @@ export function classifiedAudience(kind: string): EventAudience | undefined { | ||
| 267 | 267 | kind.startsWith("drill.") || |
| 268 | 268 | // Which machines take this forge's checks is its admin's (`actions/runners.ts`). |
| 269 | 269 | kind.startsWith("runner.") || |
| 270 | // A line to add a machine, and a machine joining with it, are its admin's | |
| 271 | // (`actions/machine_join.ts`). | |
| 272 | kind === "machine.join_offered" || | |
| 273 | kind === "machine.joined" || | |
| 270 | 274 | // An environment entry set or removed is its repo admin's (`actions/environments.ts`). |
| 271 | 275 | kind.startsWith("environment.") || |
| 272 | 276 | // A shell on a game box and everything it said: its owner's, the forge admin's (`games/shell.ts`). |
src/core/migration-pins/20261206180000-machine-join.pin added +1
| @@ -0,0 +1,1 @@ | ||
| 1 | 4a5794864dbcbe2cce36c6572adc9dc00b3a1895fdcf870055a2f66db773626c |
src/core/migrations/20261206180000-machine-join.ts added +15
| @@ -0,0 +1,15 @@ | ||
| 1 | // Add a machine (#18491): a one-use, short-lived join code an admin mints (kept as a hash), and | |
| 2 | // what a runner last said its machine is (`facts`, the JSON of os, arch, docker, xcode) with the | |
| 3 | // label words those facts make (`said_labels`), kept apart from `labels`, which only an admin | |
| 4 | // writes. Additive. | |
| 5 | export default ` | |
| 6 | CREATE TABLE IF NOT EXISTS machine_join ( | |
| 7 | code_hash TEXT PRIMARY KEY, | |
| 8 | created_by TEXT NOT NULL, | |
| 9 | created_at INTEGER NOT NULL, | |
| 10 | expires_at INTEGER NOT NULL, | |
| 11 | used_at INTEGER NOT NULL DEFAULT 0 | |
| 12 | ); | |
| 13 | ALTER TABLE check_runner ADD COLUMN facts TEXT NOT NULL DEFAULT '{}'; | |
| 14 | ALTER TABLE check_runner ADD COLUMN said_labels TEXT NOT NULL DEFAULT '[]'; | |
| 15 | `; |
src/http/api.ts +2
| @@ -350,6 +350,7 @@ import { accountAdmin, adminRoutes } from "./api/admin.ts"; | ||
| 350 | 350 | import { arcadeRoutes } from "./api/arcade.ts"; |
| 351 | 351 | import { runnerRoutes } from "./api/runners.ts"; |
| 352 | 352 | import { agentV1Routes } from "./api/agent_v1.ts"; |
| 353 | import { agentJoinRoutes } from "./api/agent_join.ts"; | |
| 353 | 354 | import { environmentRoutes } from "./api/environments.ts"; |
| 354 | 355 | import { maintenanceRoutes } from "./api/maintenance.ts"; |
| 355 | 356 | import { maintenanceRunsRoutes } from "./api/maintenance_runs.ts"; |
| @@ -1299,6 +1300,7 @@ export function apiRoutes(router: Router<Handler>, isPage: (path: string) => boo | ||
| 1299 | 1300 | adminRoutes(router); |
| 1300 | 1301 | runnerRoutes(router); |
| 1301 | 1302 | agentV1Routes(router); |
| 1303 | agentJoinRoutes(router); | |
| 1302 | 1304 | environmentRoutes(router); |
| 1303 | 1305 | arcadeRoutes(router); |
| 1304 | 1306 | gamesApiRoutes(router); |
src/http/api/agent_join.ts added +57
| @@ -0,0 +1,57 @@ | ||
| 1 | /** | |
| 2 | * Add a machine over HTTP (#18491): the forge's installer and runner, served to whoever holds the | |
| 3 | * line (`GET /api/v1/agent/install.sh`, `GET /api/v1/agent/runner.js`: constants of this forge, | |
| 4 | * no secret in either), the join a machine's installer makes with its one-use code | |
| 5 | * (`POST /api/v1/agent/join`: runner token out, once), and the admin's request for a line | |
| 6 | * (`POST /api/v1/admin/machines/join`). | |
| 7 | */ | |
| 8 | ||
| 9 | import { joinMachine, offerJoin } from "../../actions/machine_join.ts"; | |
| 10 | import { INSECURE_WORDS, INSTALL_SH, JOIN_TTL_MS } from "../../machines/join.ts"; | |
| 11 | import { runnerBundle } from "../../machines/runner_bundle.ts"; | |
| 12 | import type { Ctx, Handler } from "../context.ts"; | |
| 13 | import { clientBucket } from "../peer.ts"; | |
| 14 | import { minuteLimiter } from "../../actions/outside_limits.ts"; | |
| 15 | import { STRANGER_MAX } from "../limits.ts"; | |
| 16 | import { apiError, boundedBody, json, notFound, tryAgain } from "../respond.ts"; | |
| 17 | import type { Router } from "../router.ts"; | |
| 18 | import { accountAdmin } from "./admin.ts"; | |
| 19 | ||
| 20 | const SCRIPT_HEADERS = { "content-type": "text/x-shellscript; charset=utf-8", "cache-control": "no-store" }; | |
| 21 | ||
| 22 | /** | |
| 23 | * The two anonymous downloads share a budget per address: a script and a bundle are cheap, a build | |
| 24 | * is not. | |
| 25 | */ | |
| 26 | const downloads = minuteLimiter(30); | |
| 27 | ||
| 28 | async function runnerJs(ctx: Ctx): Promise<Response> { | |
| 29 | const verdict = downloads.take(clientBucket(ctx.request), "ro"); | |
| 30 | if (!verdict.allowed) return tryAgain("too_many_downloads", 429, "too many downloads: try again shortly", verdict.retryAfter); | |
| 31 | const bundle = await runnerBundle(); | |
| 32 | if (bundle === undefined) return apiError("no_runner_here", 404, "this forge has no runner to serve; run src/runner/main.ts from a checkout"); | |
| 33 | if (ctx.request.headers.get("if-none-match") === bundle.etag) return new Response(null, { status: 304, headers: { etag: bundle.etag } }); | |
| 34 | return new Response(bundle.code, { headers: { "content-type": "text/javascript; charset=utf-8", "cache-control": "no-cache", etag: bundle.etag } }); | |
| 35 | } | |
| 36 | ||
| 37 | async function join(ctx: Ctx): Promise<Response> { | |
| 38 | const input = await boundedBody(ctx.request, STRANGER_MAX); | |
| 39 | if (input === "too_large") return apiError("too_large", 413, `at most ${STRANGER_MAX} bytes`); | |
| 40 | const made = joinMachine(ctx.app, input["code"], input["name"]); | |
| 41 | // One answer for a code that is wrong, spent or expired: it says nothing about which. | |
| 42 | if (!made.ok) return apiError("join_refused", 403, "this join code is not good: it is used, expired or wrong"); | |
| 43 | return json({ id: made.value.id, name: made.value.name, role: "runner", token: made.value.token }, 201); | |
| 44 | } | |
| 45 | ||
| 46 | export function agentJoinRoutes(router: Router<Handler>): void { | |
| 47 | router.add("GET", "/api/v1/agent/install.sh", () => new Response(INSTALL_SH, { headers: SCRIPT_HEADERS })); | |
| 48 | router.add("GET", "/api/v1/agent/runner.js", runnerJs); | |
| 49 | router.add("POST", "/api/v1/agent/join", join); | |
| 50 | router.add("POST", "/api/v1/admin/machines/join", (ctx) => { | |
| 51 | const denied = accountAdmin(ctx, "admin"); | |
| 52 | if (denied) return denied; | |
| 53 | const offer = offerJoin(ctx.app, ctx.auth.user, ctx.url.origin); | |
| 54 | if (!offer.ok) return offer.error === "not_found" ? notFound() : offer.error === "insecure" ? apiError("insecure_origin", 409, INSECURE_WORDS) : tryAgain("too_many_lines", 429, "twenty lines are waiting to be used; use or let them expire first", JOIN_TTL_MS / 1000); | |
| 55 | return json(offer.value, 201); | |
| 56 | }); | |
| 57 | } |
src/http/api/runners.ts +1 −1
| @@ -263,7 +263,7 @@ export function runnerRoutes(router: Router<Handler>, record = true): void { | ||
| 263 | 263 | const state = str(input.state); |
| 264 | 264 | if (state !== "idle" && state !== "busy" && state !== "paused") |
| 265 | 265 | return apiError("invalid_heartbeat", 422, "state is idle, busy or paused"); |
| 266 | noteHeartbeat(ctx.app.db, runner.id, { state }); | |
| 266 | noteHeartbeat(ctx.app.db, runner.id, { state, facts: input.facts }); | |
| 267 | 267 | if (runner.wasQuiet === true || runner.state !== state) tellRunners(ctx.app, "seen", runner.id); |
| 268 | 268 | wakeClaimers(ctx.app); |
| 269 | 269 | return new Response(null, { status: 204 }); |
src/http/lazy_lists.ts +5
| @@ -35,6 +35,7 @@ export const SETTINGS_ROUTES = [ | ||
| 35 | 35 | ["POST", "/settings/runners/:id/trust"], |
| 36 | 36 | ["POST", "/settings/runners/:id/untrust"], |
| 37 | 37 | ["POST", "/settings/runners/register"], |
| 38 | ["POST", "/settings/runners/machine"], | |
| 38 | 39 | ["GET", "/settings/runners/lending/live"], |
| 39 | 40 | ["POST", "/settings/runners/lending"], |
| 40 | 41 | ["POST", "/settings/runners/lending/:id/stop"], |
| @@ -1366,6 +1367,10 @@ export const API_ROUTES = [ | ||
| 1366 | 1367 | ["GET", "/api/v1/runner/jobs/:id/git/info/refs"], |
| 1367 | 1368 | ["POST", "/api/v1/runner/jobs/:id/git/git-upload-pack"], |
| 1368 | 1369 | ["POST", "/api/v1/agent/v1/:message"], |
| 1370 | ["GET", "/api/v1/agent/install.sh"], | |
| 1371 | ["GET", "/api/v1/agent/runner.js"], | |
| 1372 | ["POST", "/api/v1/agent/join"], | |
| 1373 | ["POST", "/api/v1/admin/machines/join"], | |
| 1369 | 1374 | ["GET", "/api/v1/repos/:owner/:name/environments"], |
| 1370 | 1375 | ["PUT", "/api/v1/repos/:owner/:name/environments/:env/:entry"], |
| 1371 | 1376 | ["DELETE", "/api/v1/repos/:owner/:name/environments/:env/:entry"], |
src/http/marks/settings.json +1
| @@ -15,6 +15,7 @@ | ||
| 15 | 15 | "/settings/runners/:id/resume": "open", |
| 16 | 16 | "/settings/runners/:id/pause": "open", |
| 17 | 17 | "/settings/runners/register": "open", |
| 18 | "/settings/runners/machine": "open", | |
| 18 | 19 | "/settings/runners/lending/live": "open", |
| 19 | 20 | "/settings/runners/lending": "open", |
| 20 | 21 | "/settings/runners/lending/:id/stop": "open", |
src/http/settings_routes.ts +2 −1
| @@ -26,7 +26,7 @@ import { paymentsCsv, paymentsPage } from "../web/pages/payments.ts"; | ||
| 26 | 26 | import { billingPage, billingChange, billingGrant, billingSetLinks, billingSetPortal, billingMakeCode, billingRevokeCode, stripeConnect, stripeDisconnect, stripeSecret, orderRetry } from "../web/pages/billing.ts"; |
| 27 | 27 | import { economicsPage, economicsSet } from "../web/pages/economics.ts"; |
| 28 | 28 | import { trustedAdd, trustedPage, trustedRemove, trustedRevert, trustedStop } from "../web/pages/trusted.ts"; |
| 29 | import { lendingLive, lendingOffer, lendingResume, lendingStop, lendingStopNow, runnerPause, runnerRegister, runnerRemove, runnerResume, runnerRevoke, runnerTrust, runnersLive, runnersPage } from "../web/pages/runners.ts"; | |
| 29 | import { lendingLive, lendingOffer, lendingResume, lendingStop, lendingStopNow, machineLine, runnerPause, runnerRegister, runnerRemove, runnerResume, runnerRevoke, runnerTrust, runnersLive, runnersPage } from "../web/pages/runners.ts"; | |
| 30 | 30 | import { usagePage } from "../web/pages/usage.ts"; |
| 31 | 31 | import { spendPage } from "../web/pages/spend-tab.ts"; |
| 32 | 32 | import { securityControlsPage } from "../web/pages/security_controls.ts"; |
| @@ -183,6 +183,7 @@ export function settingsRoutes(router: Router<Handler>, knownPatterns: () => rea | ||
| 183 | 183 | router.add("POST", "/settings/runners/:id/trust", runnerTrust(true)); |
| 184 | 184 | router.add("POST", "/settings/runners/:id/untrust", runnerTrust(false)); |
| 185 | 185 | router.add("POST", "/settings/runners/register", runnerRegister); |
| 186 | router.add("POST", "/settings/runners/machine", machineLine); | |
| 186 | 187 | router.add("GET", "/settings/runners/lending/live", lendingLive); |
| 187 | 188 | router.add("POST", "/settings/runners/lending", lendingOffer); |
| 188 | 189 | router.add("POST", "/settings/runners/lending/:id/stop", lendingStop); |
src/machines/facts.ts added +79
| @@ -0,0 +1,79 @@ | ||
| 1 | /** | |
| 2 | * What a machine says it is (#18491): its os, arch, whether it has Docker and which Xcode. The | |
| 3 | * runner detects them itself (`detectFacts`, fixed commands, no text from anywhere) and says them | |
| 4 | * with every claim; nobody types a label. The forge reads them (`readFacts`) field by field and | |
| 5 | * turns them into label words (`factLabels`). | |
| 6 | * | |
| 7 | * Facts only narrow routing: a job that names `docker` or `macos` goes to a machine that says it | |
| 8 | * has it, so a machine that says less gets fewer jobs. They never touch what a machine may see or | |
| 9 | * do: its repositories, its scope, trust for secrets, pause and revocation are the admin's alone. | |
| 10 | */ | |
| 11 | ||
| 12 | export interface Facts { | |
| 13 | readonly os: "macos" | "linux" | "other"; | |
| 14 | readonly arch: "arm64" | "x64" | "other"; | |
| 15 | readonly docker: boolean; | |
| 16 | /** The Xcode version (`16.2`), "" for none. */ | |
| 17 | readonly xcode: string; | |
| 18 | } | |
| 19 | ||
| 20 | const XCODE_RE = /^[0-9]{1,3}(\.[0-9]{1,3}){0,2}$/; | |
| 21 | ||
| 22 | /** A machine's facts as it said them; undefined unless every field is well formed. */ | |
| 23 | export function readFacts(raw: unknown): Facts | undefined { | |
| 24 | if (typeof raw !== "object" || raw === null || Array.isArray(raw)) return undefined; | |
| 25 | const f = raw as Record<string, unknown>; | |
| 26 | const { os, arch, docker, xcode } = f; | |
| 27 | if (os !== "macos" && os !== "linux" && os !== "other") return undefined; | |
| 28 | if (arch !== "arm64" && arch !== "x64" && arch !== "other") return undefined; | |
| 29 | if (typeof docker !== "boolean") return undefined; | |
| 30 | if (typeof xcode !== "string" || (xcode !== "" && !XCODE_RE.test(xcode))) return undefined; | |
| 31 | return { os, arch, docker, xcode }; | |
| 32 | } | |
| 33 | ||
| 34 | /** The label words facts make: `macos`, `arm64`, `docker`, `xcode`; "other" makes none. */ | |
| 35 | export function factLabels(f: Facts): string[] { | |
| 36 | return [f.os, f.arch, ...(f.docker ? ["docker"] : []), ...(f.xcode === "" ? [] : ["xcode"])].filter((w) => w !== "other"); | |
| 37 | } | |
| 38 | ||
| 39 | /** Facts in words for a page or a terminal line: "macos arm64 · docker · Xcode 16.2". */ | |
| 40 | export function factsWords(f: Facts): string { | |
| 41 | return [`${f.os} ${f.arch}`, f.docker ? "docker" : "no docker", f.xcode === "" ? "no Xcode" : `Xcode ${f.xcode}`].join(" · "); | |
| 42 | } | |
| 43 | ||
| 44 | /** The facts as kept in the column; none for a machine that never said. */ | |
| 45 | export function parseFacts(column: string): Facts | undefined { | |
| 46 | try { | |
| 47 | return readFacts(JSON.parse(column)); | |
| 48 | } catch { | |
| 49 | return undefined; | |
| 50 | } | |
| 51 | } | |
| 52 | ||
| 53 | /** The two things asked of the machine; each is one fixed command. */ | |
| 54 | type Probe = "docker" | "xcode"; | |
| 55 | type Run = (probe: Probe) => Promise<string | undefined>; | |
| 56 | ||
| 57 | /** One fixed command's first stdout line, undefined when it is absent, fails or takes over 4 s. */ | |
| 58 | const runFixed: Run = async (probe) => { | |
| 59 | if (Bun.which(probe === "docker" ? "docker" : "xcodebuild") === null) return undefined; | |
| 60 | try { | |
| 61 | const p = | |
| 62 | probe === "docker" | |
| 63 | ? Bun.spawn(["docker", "info", "--format", "{{.ServerVersion}}"], { stdout: "pipe", stderr: "ignore", stdin: "ignore", timeout: 4000 }) | |
| 64 | : Bun.spawn(["xcodebuild", "-version"], { stdout: "pipe", stderr: "ignore", stdin: "ignore", timeout: 4000 }); | |
| 65 | const out = await new Response(p.stdout).text(); | |
| 66 | return (await p.exited) === 0 ? out.split("\n")[0]!.trim() : undefined; | |
| 67 | } catch { | |
| 68 | return undefined; | |
| 69 | } | |
| 70 | }; | |
| 71 | ||
| 72 | /** Detect this machine's facts. `run` is for a test; the argv are constants. */ | |
| 73 | export async function detectFacts(platform: string = process.platform, arch: string = process.arch, run: Run = runFixed): Promise<Facts> { | |
| 74 | const os = platform === "darwin" ? "macos" : platform === "linux" ? "linux" : "other"; | |
| 75 | const docker = (await run("docker")) !== undefined; | |
| 76 | const line = os === "macos" ? await run("xcode") : undefined; | |
| 77 | const xcode = /^Xcode ([0-9.]+)$/.exec(line ?? "")?.[1] ?? ""; | |
| 78 | return { os, arch: arch === "arm64" ? "arm64" : arch === "x64" ? "x64" : "other", docker, xcode: XCODE_RE.test(xcode) ? xcode : "" }; | |
| 79 | } |
src/machines/install.sh added +108
| @@ -0,0 +1,108 @@ | ||
| 1 | #!/bin/sh | |
| 2 | # The forge's installer for a machine that takes its checks (#18491). Pasted as | |
| 3 | # curl -fsSL $FORGE_URL/api/v1/agent/install.sh | FORGE_URL=… FORGE_JOIN=… sh | |
| 4 | # It joins once with the one-use code, keeps the runner's token in a file only this user reads, | |
| 5 | # and installs a service (launchd on macOS, systemd on Linux) that starts at login or boot, comes | |
| 6 | # back if it stops, and fetches the forge's current runner before each start. The runner detects | |
| 7 | # this machine's os, arch, Docker and Xcode itself and says them to the forge; nothing is typed. | |
| 8 | # Needs: curl, git and bun. Run it as the user that should run the checks (not root: refused). | |
| 9 | # The forge is trusted to run code on this machine: the service runs the runner it serves. | |
| 10 | set -eu | |
| 11 | ||
| 12 | : "" | |
| 13 | : "" | |
| 14 | # This machine runs what the forge serves it, with the runner's token in its environment: the | |
| 15 | # road must be https (plain http only to this machine itself). | |
| 16 | case "" in | |
| 17 | https://* | http://localhost | http://localhost:* | http://127.0.0.1 | http://127.0.0.1:*) ;; | |
| 18 | *) echo "FORGE_URL must be https (http only to localhost): the forge is trusted to run code here" >&2; exit 1 ;; | |
| 19 | esac | |
| 20 | [ "$(id -u)" != 0 ] || { echo "run this as the user that should run the checks, not root: every check would run as root" >&2; exit 1; } | |
| 21 | case "" in *[!A-Za-z0-9/:._-]*) echo "unexpected characters in FORGE_URL, FORGE_JOIN or HOME" >&2; exit 1 ;; esac | |
| 22 | ||
| 23 | for tool in curl git bun; do | |
| 24 | command -v "" >/dev/null 2>&1 || { echo " is needed first (bun: https://bun.sh)" >&2; exit 1; } | |
| 25 | done | |
| 26 | BUN= | |
| 27 | OS= | |
| 28 | DIR="/.forge-runner" | |
| 29 | umask 077 | |
| 30 | mkdir -p "" | |
| 31 | ||
| 32 | NAME= | |
| 33 | NAME= | |
| 34 | ||
| 35 | # Join: the code is spent here; the answer holds the runner's token, shown to nobody. | |
| 36 | ANSWER= | |
| 37 | -d "{\"code\":\"\",\"name\":\"\"}" "/api/v1/agent/join") || | |
| 38 | { echo "the forge refused the join: the code is used, expired or wrong; ask for another line" >&2; exit 1; } | |
| 39 | TOKEN= | |
| 40 | [ -n "" ] || { echo "the forge's answer held no token" >&2; exit 1; } | |
| 41 | ||
| 42 | # The token's file: mode 600, read by the service's start script and by nothing else. | |
| 43 | { | |
| 44 | printf 'FORGE_URL=%s\n' "" | |
| 45 | printf 'FORGE_RUNNER_TOKEN=%s\n' "" | |
| 46 | printf 'FORGE_RUNNER_DIR=%s\n' "/work" | |
| 47 | } >"/env" | |
| 48 | chmod 600 "/env" | |
| 49 | unset TOKEN ANSWER FORGE_JOIN | |
| 50 | ||
| 51 | # What the service runs: take the forge's current runner (keep the last one when the forge is | |
| 52 | # away), then run it. The runner exits between jobs when the forge's build changes, and the | |
| 53 | # service starts it again, so it follows the forge without a person. | |
| 54 | cat >"/run.sh" << | |
| 55 | #!/bin/sh | |
| 56 | set -eu | |
| 57 | cd "" | |
| 58 | set -a | |
| 59 | . "/env" | |
| 60 | set +a | |
| 61 | curl -fsSL "\$FORGE_URL/api/v1/agent/runner.js" -o runner.js.new && mv runner.js.new runner.js || true | |
| 62 | exec "" runner.js | |
| 63 | ||
| 64 | chmod 700 "/run.sh" | |
| 65 | curl -fsSL "/api/v1/agent/runner.js" -o "/runner.js" || | |
| 66 | { echo "this forge does not serve a runner to fetch; run its src/runner/main.ts from a checkout instead" >&2; exit 1; } | |
| 67 | ||
| 68 | case "" in | |
| 69 | Darwin) | |
| 70 | PLIST="/Library/LaunchAgents/sh.forge.runner.plist" | |
| 71 | mkdir -p "/Library/LaunchAgents" | |
| 72 | cat >"" << | |
| 73 | <?xml version="1.0" encoding="UTF-8"?> | |
| 74 | <!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd"> | |
| 75 | <plist version="1.0"><dict> | |
| 76 | <key>Label</key><string>sh.forge.runner</string> | |
| 77 | <key>ProgramArguments</key><array><string>/run.sh</string></array> | |
| 78 | <key>RunAtLoad</key><true/> | |
| 79 | <key>KeepAlive</key><true/> | |
| 80 | <key>StandardOutPath</key><string>/runner.log</string> | |
| 81 | <key>StandardErrorPath</key><string>/runner.log</string> | |
| 82 | </dict></plist> | |
| 83 | ||
| 84 | launchctl bootout "gui/$(id -u)/sh.forge.runner" >/dev/null 2>&1 || true | |
| 85 | launchctl bootstrap "gui/$(id -u)" "" | |
| 86 | echo "installed: launchd service sh.forge.runner (log: /runner.log)" | |
| 87 | ;; | |
| 88 | Linux) | |
| 89 | command -v systemctl >/dev/null 2>&1 || { echo "systemd is needed on Linux" >&2; exit 1; } | |
| 90 | UNIT="[Unit] | |
| 91 | Description=Forge runner | |
| 92 | After=network-online.target | |
| 93 | ||
| 94 | [Service] | |
| 95 | ExecStart=/run.sh | |
| 96 | Restart=always | |
| 97 | RestartSec=5 | |
| 98 | " | |
| 99 | mkdir -p "/.config/systemd/user" | |
| 100 | printf '%s\n[Install]\nWantedBy=default.target\n' "" >"/.config/systemd/user/forge-runner.service" | |
| 101 | systemctl --user daemon-reload | |
| 102 | systemctl --user enable --now forge-runner.service | |
| 103 | loginctl enable-linger "$(id -un)" >/dev/null 2>&1 || echo "note: run 'loginctl enable-linger $(id -un)' as root so it stays up after logout" >&2 | |
| 104 | echo "installed: systemd user service forge-runner (journalctl --user -u forge-runner)" | |
| 105 | ;; | |
| 106 | *) echo "this installer knows macOS and Linux; run src/runner/main.ts by hand on " >&2; exit 1 ;; | |
| 107 | esac | |
| 108 | echo "joined as : the machine reports its os, arch, docker and xcode to the forge on its own" |
src/machines/join.ts added +79
| @@ -0,0 +1,79 @@ | ||
| 1 | /** | |
| 2 | * Add a machine (#18491): an admin gets one line to paste on a machine. The line fetches the | |
| 3 | * forge's own installer (`install.sh`, constant: it holds no secret and no text from a request) | |
| 4 | * and hands it a join code. A join code is the credential in that line, so it is made hard to | |
| 5 | * misuse: 256 random bits, kept only as a hash, good for one use and for `JOIN_TTL_MS`. Spending | |
| 6 | * it enrols one runner (the runner role, no more) and gives back that runner's token once. | |
| 7 | * Plain data in, plain data out: nothing here reads a request. | |
| 8 | */ | |
| 9 | ||
| 10 | import type { Database } from "bun:sqlite"; | |
| 11 | import { secret } from "../kernel/id.ts"; | |
| 12 | import { sha256 } from "../kernel/hash.ts"; | |
| 13 | import installScript from "./install.sh" with { type: "text" }; | |
| 14 | ||
| 15 | /** How long a pasted line works: the time to open a terminal and paste. */ | |
| 16 | export const JOIN_TTL_MS = 15 * 60_000; | |
| 17 | export const JOIN_PREFIX = "fjoin_"; | |
| 18 | /** The most codes an admin has outstanding at once, so a page cannot be made to fill the table. */ | |
| 19 | export const JOIN_OPEN_MAX = 20; | |
| 20 | ||
| 21 | export const INSTALL_SH: string = installScript; | |
| 22 | ||
| 23 | /** A join code's shape: what the installer sends back, checked before it is hashed or looked up. */ | |
| 24 | export const isJoinCode = (v: unknown): v is string => typeof v === "string" && /^fjoin_[A-Za-z0-9_-]{43}$/.test(v); | |
| 25 | ||
| 26 | /** | |
| 27 | * Make a code; false when this admin already holds `JOIN_OPEN_MAX` that are neither spent nor | |
| 28 | * expired. | |
| 29 | */ | |
| 30 | export function mintJoin(db: Database, adminId: string, now: number): { code: string; expiresAt: number } | undefined { | |
| 31 | const open = db.query<{ n: number }, [string, number]>("SELECT COUNT(*) AS n FROM machine_join WHERE created_by = ?1 AND used_at = 0 AND expires_at > ?2").get(adminId, now)!.n; | |
| 32 | if (open >= JOIN_OPEN_MAX) return undefined; | |
| 33 | const code = `${JOIN_PREFIX}${secret()}`; | |
| 34 | const expiresAt = now + JOIN_TTL_MS; | |
| 35 | db.query("INSERT INTO machine_join (code_hash, created_by, created_at, expires_at) VALUES (?1, ?2, ?3, ?4)").run(sha256(code), adminId, now, expiresAt); | |
| 36 | // Old rows are no use to anyone: a day past their end they go. | |
| 37 | db.query("DELETE FROM machine_join WHERE expires_at < ?1").run(now - 86_400_000); | |
| 38 | return { code, expiresAt }; | |
| 39 | } | |
| 40 | ||
| 41 | /** | |
| 42 | * Spend a code: the UPDATE's WHERE is the check, so of two requests with one code only one changes | |
| 43 | * the row. Returns who minted it, or undefined for a code that is unknown, spent or expired. | |
| 44 | */ | |
| 45 | export function spendJoin(db: Database, code: string, now: number): { adminId: string } | undefined { | |
| 46 | const hash = sha256(code); | |
| 47 | const row = db.query<{ created_by: string }, [string]>("SELECT created_by FROM machine_join WHERE code_hash = ?1").get(hash); | |
| 48 | if (row === null) return undefined; | |
| 49 | const took = db.query("UPDATE machine_join SET used_at = ?2 WHERE code_hash = ?1 AND used_at = 0 AND expires_at > ?2").run(hash, now).changes; | |
| 50 | return took === 1 ? { adminId: row.created_by } : undefined; | |
| 51 | } | |
| 52 | ||
| 53 | /** | |
| 54 | * https, or http to this machine itself: the machine runs what the forge serves it, so the road | |
| 55 | * must not be one anyone can write on. `install.sh` holds the same rule. | |
| 56 | */ | |
| 57 | export const isSecureOrigin = (origin: string): boolean => /^https:\/\//.test(origin) || /^http:\/\/(localhost|127\.0\.0\.1)(:[0-9]{1,5})?$/.test(origin); | |
| 58 | ||
| 59 | export const INSECURE_WORDS = "this forge's address is plain http: set its https url (FORGE_URL) so the line cannot be rewritten on the way"; | |
| 60 | ||
| 61 | /** | |
| 62 | * The line to paste. `origin` is the forge's own public origin (the caller's configured URL), so | |
| 63 | * it is checked to be a bare http(s) origin before it goes inside a shell line. | |
| 64 | */ | |
| 65 | export function joinLine(origin: string, code: string): string | undefined { | |
| 66 | if (!/^https?:\/\/[A-Za-z0-9.-]+(:[0-9]{1,5})?$/.test(origin) || !isJoinCode(code)) return undefined; | |
| 67 | if (!isSecureOrigin(origin)) return undefined; | |
| 68 | return `curl -fsSL ${origin}/api/v1/agent/install.sh | FORGE_URL=${origin} FORGE_JOIN=${code} sh`; | |
| 69 | } | |
| 70 | ||
| 71 | /** | |
| 72 | * A machine's name from what it calls itself: lower-case letters, digits and hyphens, never a name | |
| 73 | * the forge reserves. | |
| 74 | */ | |
| 75 | export function machineName(raw: unknown): string { | |
| 76 | const plain = (typeof raw === "string" ? raw : "").toLowerCase().replace(/[^a-z0-9-]/g, "-").replace(/^-+|-+$/g, "").slice(0, 32); | |
| 77 | if (plain === "") return "machine"; | |
| 78 | return /^(lent|local)/.test(plain) ? `host-${plain}` : plain; | |
| 79 | } |
src/machines/protocol.ts +7 −1
| @@ -12,6 +12,8 @@ | ||
| 12 | 12 | * it, a helper (the Mac app's) says it is here. Nothing here touches a database or a request. |
| 13 | 13 | */ |
| 14 | 14 | |
| 15 | import { readFacts } from "./facts.ts"; | |
| 16 | ||
| 15 | 17 | export const PROTOCOL_VERSION = 1; |
| 16 | 18 | |
| 17 | 19 | export const MESSAGES = ["heartbeat", "claim", "logs", "result", "containers"] as const; |
| @@ -68,7 +70,11 @@ export function readMessage(role: Role, message: Message, raw: unknown): Read { | ||
| 68 | 70 | case "heartbeat": { |
| 69 | 71 | const state = rest["state"]; |
| 70 | 72 | if (state !== "idle" && state !== "busy" && state !== "paused") return bad("invalid_heartbeat", "state is idle, busy or paused"); |
| 71 | return { ok: true, body: { state } }; | |
| 73 | // Facts are checked field by field here; a heartbeat whose facts are malformed is refused, | |
| 74 | // not trimmed. | |
| 75 | const facts = rest["facts"]; | |
| 76 | if (facts !== undefined && readFacts(facts) === undefined) return bad("invalid_heartbeat", "facts are { os: macos|linux|other, arch: arm64|x64|other, docker: boolean, xcode: version or empty }"); | |
| 77 | return { ok: true, body: { state, ...(facts === undefined ? {} : { facts }) } }; | |
| 72 | 78 | } |
| 73 | 79 | case "claim": { |
| 74 | 80 | const { wait, cells, jobs, machine } = rest; |
src/machines/runner_bundle.ts added +60
| @@ -0,0 +1,60 @@ | ||
| 1 | /** | |
| 2 | * The runner as one file a machine fetches (#18491): `src/runner/main.ts` bundled by `Bun.build` | |
| 3 | * the first time it is asked for, then held for the life of the process. A forge that runs from a | |
| 4 | * bundle with no source beside it cannot build it and says so (undefined): the installer then | |
| 5 | * tells the person to run the runner from a checkout. | |
| 6 | */ | |
| 7 | ||
| 8 | import { sha256 } from "../kernel/hash.ts"; | |
| 9 | import { createLog } from "../kernel/log.ts"; | |
| 10 | ||
| 11 | const log = createLog("machines"); | |
| 12 | ||
| 13 | export interface RunnerBundle { | |
| 14 | readonly code: string; | |
| 15 | readonly etag: string; | |
| 16 | } | |
| 17 | ||
| 18 | /** | |
| 19 | * A failed build is not tried again for this long: an anonymous route cannot start a build per hit. | |
| 20 | */ | |
| 21 | export const RETRY_MS = 60_000; | |
| 22 | ||
High: failure handling. |
||
| 23 | let pending: Promise<RunnerBundle | undefined> | undefined; | |
| 24 | let failedAt = 0; | |
| 25 | ||
| 26 | export function runnerBundle(now: number = Date.now()): Promise<RunnerBundle | undefined> { | |
| 27 | if (pending !== undefined) return pending; | |
| 28 | if (failedAt !== 0 && now - failedAt < RETRY_MS) return Promise.resolve(undefined); | |
| 29 | const mine = build().then((bundle) => { | |
| 30 | if (bundle === undefined) { | |
| 31 | failedAt = now; | |
| 32 | pending = undefined; | |
| 33 | } else failedAt = 0; | |
| 34 | return bundle; | |
| 35 | }); | |
| 36 | pending = mine; | |
| 37 | return mine; | |
| 38 | } | |
| 39 | ||
| 40 | /** Forget what was built and what failed (tests). */ | |
| 41 | export function resetRunnerBundle(): void { | |
| 42 | pending = undefined; | |
| 43 | failedAt = 0; | |
| 44 | } | |
| 45 | ||
| 46 | async function build(): Promise<RunnerBundle | undefined> { | |
| 47 | try { | |
| 48 | const built = await Bun.build({ entrypoints: [Bun.fileURLToPath(new URL("../runner/main.ts", import.meta.url))], target: "bun", format: "esm", minify: false }); | |
| 49 | const first = built.outputs[0]; | |
| 50 | if (!built.success || first === undefined || built.outputs.length !== 1) { | |
| 51 | log.warn("machines.runner_bundle_failed", { logs: built.logs.length }); | |
| 52 | return undefined; | |
| 53 | } | |
| 54 | const code = await first.text(); | |
| 55 | return { code, etag: `"${sha256(code)}"` }; | |
| 56 | } catch (error) { | |
| 57 | log.warn("machines.runner_bundle_failed", { error: String(error) }); | |
| 58 | return undefined; | |
| 59 | } | |
| 60 | } |
src/runner/main.ts +4 −1
| @@ -57,6 +57,7 @@ import { runGit } from "../git/env.ts"; | ||
| 57 | 57 | import { isSafeOid } from "../git/guard.ts"; |
| 58 | 58 | import { background } from "../perf/jobs.ts"; |
| 59 | 59 | import { BuildWatch, exitOnUpgrade, RUNNER_VERSION_HEADER } from "./upgrade.ts"; |
| 60 | import { detectFacts } from "../machines/facts.ts"; | |
| 60 | 61 | import { PROTOCOL_VERSION, splitReport } from "../machines/protocol.ts"; |
| 61 | 62 | |
| 62 | 63 | /** |
| @@ -687,7 +688,9 @@ export async function runRunner(options: RunnerOptions): Promise<RunnerEnd> { | ||
| 687 | 688 | // shows, said on each claim so the forge counts the machines its checks run on |
| 688 | 689 | // (`noteRunnerMachine`). |
| 689 | 690 | const box = machineLimits(); |
| 690 | const machine = { cpus: box.cpus, memoryMiB: Math.floor(box.memoryBytes / 1_048_576), hostCpus: availableParallelism() }; | |
| 691 | // Its os, arch, Docker and Xcode, found here and said with every claim: nobody types a label | |
| 692 | // (`machines/facts.ts`). | |
| 693 | const machine = { cpus: box.cpus, memoryMiB: Math.floor(box.memoryBytes / 1_048_576), hostCpus: availableParallelism(), facts: await detectFacts() }; | |
| 691 | 694 | |
| 692 | 695 | // Paused by its lender: no claim is made, and one waiting is let go when the pause begins. |
| 693 | 696 | const lookMs = Math.max(10, options.pauseLookMs ?? PAUSE_LOOK_MS); |
src/tui/screens/addmachine.ts added +31
| @@ -0,0 +1,31 @@ | ||
| 1 | /** | |
| 2 | * Add a machine in the terminal (#18491), a forge admin's: the one line to paste on it, made now | |
| 3 | * (`actions/machine_join.ts` `offerJoin`, the same as the page and `POST | |
| 4 | * /api/v1/admin/machines/join`) and shown once. Reached from the Runners screen with `a`. | |
| 5 | */ | |
| 6 | ||
| 7 | import { offerJoin } from "../../actions/machine_join.ts"; | |
| 8 | import { INSECURE_WORDS } from "../../machines/join.ts"; | |
| 9 | import type { Ctx, Screen } from "../app/app.ts"; | |
| 10 | import type { Session } from "../session.ts"; | |
| 11 | import { confirmScreen } from "./common.ts"; | |
| 12 | ||
| 13 | /** The line, or a screen that says why there is none. `back` is the screen to return to. */ | |
| 14 | export function addMachineScreen(f: Session, ctx: Ctx, back: Screen): Screen { | |
| 15 | const made = offerJoin(f.app, f.user, `http://${f.app.config.host ?? "localhost"}:${f.app.config.port ?? 3000}`); | |
| 16 | const local = f.app.config.url === undefined; | |
| 17 | let body: string[]; | |
| 18 | if (made.ok) { | |
| 19 | body = [`Paste this on the machine (it works once, for ${made.value.minutes} minutes):`, made.value.line]; | |
| 20 | if (local) body.push("This forge has no public url set: the line reaches this machine only, not another one."); | |
| 21 | } else if (made.error === "not_found") body = ["Only a forge admin adds a machine."]; | |
| 22 | else if (made.error === "insecure") body = [INSECURE_WORDS]; | |
| 23 | else body = ["Twenty lines are waiting to be used; use or let them expire first."]; | |
| 24 | return confirmScreen(ctx, back, { | |
| 25 | title: "Add a machine", | |
| 26 | body, | |
| 27 | actions: [{ label: "Done" }], | |
| 28 | onChoose: () => {}, | |
| 29 | width: 100, | |
| 30 | }); | |
| 31 | } |
src/tui/screens/runners.ts +6
| @@ -7,6 +7,7 @@ | ||
| 7 | 7 | */ |
| 8 | 8 | |
| 9 | 9 | import { setRunnerTrust } from "../../actions/environments.ts"; |
| 10 | import { addMachineScreen } from "./addmachine.ts"; | |
| 10 | 11 | import { enrol, list, pause, removeHandMade, resume, revoke, runnerState } from "../../actions/runners.ts"; |
| 11 | 12 | import { isLocal } from "../../checks/runner_pool.ts"; |
| 12 | 13 | import { listLending, offerLending, resumeLending, stopLending, type LendView } from "../../actions/lending.ts"; |
| @@ -186,6 +187,7 @@ export function runnersScreen(f: Session, ctx: Ctx): Screen { | ||
| 186 | 187 | binding(["p"], "pause"), |
| 187 | 188 | binding(["u"], "resume"), |
| 188 | 189 | binding(["n"], "register an outside runner"), |
| 190 | binding(["a"], "add a machine: one line to paste"), | |
| 189 | 191 | binding(["c"], "lend runners to a forge"), |
| 190 | 192 | binding(["s"], "stop lending"), |
| 191 | 193 | binding(["S"], "stop lending now"), |
| @@ -216,6 +218,10 @@ export function runnersScreen(f: Session, ctx: Ctx): Screen { | ||
| 216 | 218 | register(); |
| 217 | 219 | return true; |
| 218 | 220 | } |
| 221 | if (e.key === "a") { | |
| 222 | ctx.push(addMachineScreen(f, ctx, screen)); | |
| 223 | return true; | |
| 224 | } | |
| 219 | 225 | const picked = all[state.index]; |
| 220 | 226 | if (picked?.kind === "offer") return e.key === "s" || e.key === "S" || e.key === "u" ? onOffer(picked.o, e.key) : false; |
| 221 | 227 | const at = picked?.r; |
src/web/pages/runners.ts +40 −1
| @@ -23,6 +23,8 @@ import { nextQuiet, runnerLines, type RunnerLine } from "../../machines/live_run | ||
| 23 | 23 | import { notePhase, takeSessionTime } from "../../core/route_timing.ts"; |
| 24 | 24 | import type { Ctx } from "../../http/context.ts"; |
| 25 | 25 | import { sshOn } from "../../settings/ssh.ts"; |
| 26 | import { INSECURE_WORDS, JOIN_TTL_MS } from "../../machines/join.ts"; | |
| 27 | import { offerJoin } from "../../actions/machine_join.ts"; | |
| 26 | 28 | import { liveRegionsJs } from "../client.ts"; |
| 27 | 29 | import { behaviorsJs } from "../behaviors.ts"; |
| 28 | 30 | import { runnerTailJs } from "../runner_tail.ts"; |
| @@ -187,6 +189,43 @@ function lendingBlock(ctx: Ctx) { | ||
| 187 | 189 | </section>`; |
| 188 | 190 | } |
| 189 | 191 | |
| 192 | /** | |
| 193 | * Add a machine (#18491): a post form; its answer page shows the line once, never in a URL or a | |
| 194 | * flash (`machineLine`). | |
| 195 | */ | |
| 196 | function addMachineBlock() { | |
| 197 | return html`<section class="settings-block" id="add-machine"> | |
| 198 | <h2>Add a machine</h2> | |
| 199 | <form method="post" action="${HERE}/machine" id="add-machine-form"> | |
| 200 | <p class="muted small">One line to paste on the machine: it works once, for ${String(Math.round(JOIN_TTL_MS / 60_000))} minutes, so treat it like a password.</p> | |
| 201 | ${btn("Get the line", { label: "Get the line to paste on a new machine" })} | |
| 202 | </form> | |
| 203 | </section>`; | |
| 204 | } | |
| 205 | ||
| 206 | // POST /settings/runners/machine | |
| 207 | export async function machineLine(ctx: Ctx): Promise<Response> { | |
| 208 | const denied = admin(ctx); | |
| 209 | if (denied) return denied; | |
| 210 | const form = await readForm(ctx, "admin"); | |
| 211 | if (form instanceof Response) return form; | |
| 212 | const made = offerJoin(ctx.app, ctx.auth.user, ctx.url.origin); | |
| 213 | if (!made.ok) | |
| 214 | return flashTo(ctx, `${HERE}-machine`, { | |
| 215 | tone: "danger", | |
| 216 | message: made.error === "not_found" ? "Only a forge admin adds a machine." : made.error === "insecure" ? INSECURE_WORDS : "Twenty lines are waiting to be used; use or let them expire first.", | |
| 217 | }); | |
| 218 | const res = page({ | |
| 219 | ctx, | |
| 220 | title: "Add a machine", | |
| 221 | body: html`${pageHead("Add a machine", { sub: `Paste this on the machine; it works once, for ${made.value.minutes} minutes.` })} | |
| 222 | <section class="settings-block"><pre class="mono" id="add-machine-line">${made.value.line}</pre> | |
| 223 | <p class="muted small">The machine runs what this forge serves it, so it trusts the forge. <a href="${HERE}">Back to runners</a></p></section>`, | |
| 224 | }); | |
| 225 | res.headers.set("cache-control", "no-store"); | |
| 226 | return res; | |
| 227 | } | |
| 228 | ||
| 190 | 229 | /** |
| 191 | 230 | * Register an outside runner (#18037), a Mac say: its name, the labels it holds and the |
| 192 | 231 | * repositories it serves. The owner's word here is the only source of its labels. Posts without |
| @@ -329,7 +368,7 @@ export function runnersPage(ctx: Ctx): Response { | ||
| 329 | 368 | ${lent === "" ? "" : html`<p class="muted small" id="lent-line">${lent}</p>`} |
| 330 | 369 | <p class="muted small">Enrol one with <code>POST /api/v1/admin/runners</code>, or register a machine below.</p> |
| 331 | 370 | ${runnersLivePart(ctx, seen.value)} |
| 332 | </section>${registerBlock()}${lendingBlock(ctx)}`; | |
| 371 | </section>${addMachineBlock()}${registerBlock()}${lendingBlock(ctx)}`; | |
| 333 | 372 | notePhase(ctx.request, "render", performance.now() - rendering); |
| 334 | 373 | return page({ |
| 335 | 374 | ctx, |
test/data-browser.test.ts +2
| @@ -28,6 +28,8 @@ const AUDITED_CLEAR: string[] = [ | ||
| 28 | 28 | "app_feature_setting.value", |
| 29 | 29 | "app_flag.value", |
| 30 | 30 | "ask_filter.value", |
| 31 | // Label words a runner's own facts make (os, arch, docker): public, never a credential. | |
| 32 | "check_runner.said_labels", | |
| 31 | 33 | // Which hosted forge an ask or a grant is for (`core/child_reach.ts`): a spawn's body id, or `*` |
| 32 | 34 | // for every one. |
| 33 | 35 | "child_reach_ask.body_id", |
test/machine-join.test.ts added +263
| @@ -0,0 +1,263 @@ | ||
| 1 | /** | |
| 2 | * Add a machine (#18491): one line, a one-use code for the runner role, an installer for launchd | |
| 3 | * and systemd, and facts the machine detected that only narrow which jobs it is offered. | |
| 4 | */ | |
| 5 | import { describe, expect, test } from "bun:test"; | |
| 6 | import { claimJob, enrolRunner, labelServed, noteRunnerFacts, offerJob, getRunner, type RunnerJob } from "../src/checks/runner_jobs.ts"; | |
| 7 | import { createToken } from "../src/core/tokens.ts"; | |
| 8 | import { JOIN_OPEN_MAX, JOIN_TTL_MS, INSTALL_SH, isJoinCode, joinLine, machineName, mintJoin, spendJoin } from "../src/machines/join.ts"; | |
| 9 | import { detectFacts, factLabels, factsWords, readFacts } from "../src/machines/facts.ts"; | |
| 10 | import { offerJoin } from "../src/actions/machine_join.ts"; | |
| 11 | import { RETRY_MS, resetRunnerBundle, runnerBundle } from "../src/machines/runner_bundle.ts"; | |
| 12 | import { readMessage } from "../src/machines/protocol.ts"; | |
| 13 | import { checksForge } from "./helpers/checks-forge.ts"; | |
| 14 | import { quietLogs } from "./helpers/globals.ts"; | |
| 15 | ||
| 16 | quietLogs(); | |
| 17 | const f = checksForge("forge-machine-join-"); | |
| 18 | ||
| 19 | const post = (path: string, token: string, body: unknown, origin?: string): Promise<Response> => | |
| 20 | fetch(`${f.servers.url}${path}`, { | |
| 21 | method: "POST", | |
| 22 | headers: { ...(token === "" ? {} : { authorization: `Bearer ${token}` }), "content-type": "application/json", ...(origin === undefined ? {} : { origin }) }, | |
| 23 | body: JSON.stringify(body), | |
| 24 | }); | |
| 25 | ||
| 26 | const labelled = (label: string): Omit<RunnerJob, "id"> => ({ | |
| 27 | run: "run1", | |
| 28 | repo: "alice/lib", | |
| 29 | commit: "a".repeat(40), | |
| 30 | depth: 1, | |
| 31 | steps: [{ name: "check", command: "true" }], | |
| 32 | env: {}, | |
| 33 | limits: {}, | |
| 34 | timeoutS: 60, | |
| 35 | egress: [], | |
| 36 | egressMode: "enforce", | |
| 37 | cell: "preferred", | |
| 38 | cache: { repo: "r", tree: "", base: "" }, | |
| 39 | label, | |
| 40 | }); | |
| 41 | ||
| 42 | describe("facts", () => { | |
| 43 | test("a machine's facts are read field by field, and make label words", () => { | |
| 44 | const mac = { os: "macos", arch: "arm64", docker: true, xcode: "16.2" } as const; | |
| 45 | expect(readFacts(mac)).toEqual(mac); | |
| 46 | expect(factLabels(readFacts(mac)!)).toEqual(["macos", "arm64", "docker", "xcode"]); | |
| 47 | expect(factsWords(readFacts(mac)!)).toBe("macos arm64 · docker · Xcode 16.2"); | |
| 48 | expect(factLabels(readFacts({ os: "other", arch: "x64", docker: false, xcode: "" })!)).toEqual(["x64"]); | |
| 49 | for (const bad of [null, [], { os: "windows", arch: "x64", docker: false, xcode: "" }, { ...mac, docker: "yes" }, { ...mac, xcode: "16.2; rm -rf /" }, { ...mac, arch: undefined }]) | |
| 50 | expect(readFacts(bad)).toBeUndefined(); | |
| 51 | }); | |
| 52 | ||
| 53 | test("detection runs only fixed commands and reads their answers", async () => { | |
| 54 | const asked: string[] = []; | |
| 55 | const run = async (probe: "docker" | "xcode"): Promise<string | undefined> => { | |
| 56 | asked.push(probe); | |
| 57 | return probe === "docker" ? "27.1.1" : "Xcode 16.2"; | |
| 58 | }; | |
| 59 | expect(await detectFacts("darwin", "arm64", run)).toEqual({ os: "macos", arch: "arm64", docker: true, xcode: "16.2" }); | |
| 60 | expect(asked).toEqual(["docker", "xcode"]); | |
| 61 | asked.length = 0; | |
| 62 | // Linux never asks about Xcode; a failed docker is no docker. | |
| 63 | expect(await detectFacts("linux", "x64", async (p) => (asked.push(p), undefined))).toEqual({ os: "linux", arch: "x64", docker: false, xcode: "" }); | |
| 64 | expect(asked).toEqual(["docker"]); | |
| 65 | }); | |
| 66 | }); | |
| 67 | ||
| 68 | describe("the join code", () => { | |
| 69 | test("works once, and not after its quarter hour", () => { | |
| 70 | const now = 1_000_000; | |
| 71 | const a = mintJoin(f.app.db, f.alice.id, now)!; | |
| 72 | expect(isJoinCode(a.code)).toBe(true); | |
| 73 | expect(a.expiresAt).toBe(now + JOIN_TTL_MS); | |
| 74 | expect(JOIN_TTL_MS).toBe(15 * 60_000); | |
| 75 | expect(spendJoin(f.app.db, a.code, now + 1)).toEqual({ adminId: f.alice.id }); | |
| 76 | expect(spendJoin(f.app.db, a.code, now + 2)).toBeUndefined(); | |
| 77 | const b = mintJoin(f.app.db, f.alice.id, now)!; | |
| 78 | expect(spendJoin(f.app.db, b.code, now + JOIN_TTL_MS)).toBeUndefined(); | |
| 79 | expect(spendJoin(f.app.db, `fjoin_${"x".repeat(43)}`, now)).toBeUndefined(); | |
| 80 | // Only a hash is kept. | |
| 81 | const kept = f.app.db.query<{ code_hash: string }, []>("SELECT code_hash FROM machine_join").all(); | |
| 82 | expect(kept.some((r) => r.code_hash.includes(a.code))).toBe(false); | |
| 83 | }); | |
| 84 | ||
| 85 | test("an admin holds at most twenty open", () => { | |
| 86 | const now = 5_000_000; | |
| 87 | let made = 0; | |
| 88 | while (mintJoin(f.app.db, "someone", now) !== undefined) made++; | |
| 89 | expect(made).toBe(JOIN_OPEN_MAX); | |
| 90 | }); | |
| 91 | ||
| 92 | test("the line is a curl to the forge's own script, and nothing odd goes into a shell line", () => { | |
| 93 | const code = `fjoin_${"A".repeat(43)}`; | |
| 94 | expect(joinLine("https://forge.example", code)).toBe(`curl -fsSL https://forge.example/api/v1/agent/install.sh | FORGE_URL=https://forge.example FORGE_JOIN=${code} sh`); | |
| 95 | expect(joinLine("https://forge.example; rm -rf /", code)).toBeUndefined(); | |
| 96 | expect(joinLine("https://forge.example", "fjoin_short")).toBeUndefined(); | |
| 97 | }); | |
| 98 | ||
| 99 | test("a line is made for https, or http to this machine, and for no other plain http", () => { | |
| 100 | const code = `fjoin_${"A".repeat(43)}`; | |
| 101 | expect(joinLine("http://localhost:3000", code)).toBeDefined(); | |
| 102 | expect(joinLine("http://127.0.0.1:3000", code)).toBeDefined(); | |
| 103 | expect(joinLine("http://forge.example", code)).toBeUndefined(); | |
| 104 | expect(joinLine("http://10.0.0.5:3000", code)).toBeUndefined(); | |
| 105 | expect(joinLine("http://localhost.evil.example", code)).toBeUndefined(); | |
| 106 | }); | |
| 107 | ||
| 108 | test("offering a line over plain http spends no code and says why", () => { | |
| 109 | const before = f.app.db.query<{ n: number }, []>("SELECT COUNT(*) AS n FROM machine_join").get()!.n; | |
| 110 | const made = offerJoin(f.app, f.alice, "http://forge.example"); | |
| 111 | expect(made).toEqual({ ok: false, error: "insecure" }); | |
| 112 | expect(f.app.db.query<{ n: number }, []>("SELECT COUNT(*) AS n FROM machine_join").get()!.n).toBe(before); | |
| 113 | }); | |
| 114 | ||
| 115 | test("a machine's name is plain, and never one the forge reserves", () => { | |
| 116 | expect(machineName("Mac Mini.local")).toBe("mac-mini-local"); | |
| 117 | expect(machineName("local-1")).toBe("host-local-1"); | |
| 118 | expect(machineName("lent-x")).toBe("host-lent-x"); | |
| 119 | expect(machineName(42)).toBe("machine"); | |
| 120 | }); | |
| 121 | }); | |
| 122 | ||
| 123 | describe("the installer", () => { | |
| 124 | test("holds no secret, installs launchd and systemd, and keeps the token in a mode 600 file", () => { | |
| 125 | expect(INSTALL_SH).toContain("launchctl bootstrap"); | |
| 126 | expect(INSTALL_SH).toContain("systemctl"); | |
| 127 | expect(INSTALL_SH).toContain("KeepAlive"); | |
| 128 | expect(INSTALL_SH).toContain("Restart=always"); | |
| 129 | expect(INSTALL_SH).toContain("chmod 600"); | |
| 130 | expect(INSTALL_SH).not.toContain("forge_runner_"); | |
| 131 | expect(INSTALL_SH).not.toMatch(/\beval\b/); | |
| 132 | // No label is typed: nothing in it names os, arch, docker or xcode as a label to send. | |
| 133 | expect(INSTALL_SH).not.toContain("labels"); | |
| 134 | }); | |
| 135 | ||
| 136 | test("refuses plain http to another machine, refuses root, and installs no system unit", () => { | |
| 137 | expect(INSTALL_SH).toContain("FORGE_URL must be https"); | |
| 138 | expect(INSTALL_SH).toContain('"$(id -u)" != 0'); | |
| 139 | expect(INSTALL_SH).not.toContain("/etc/systemd/system"); | |
| 140 | }); | |
| 141 | }); | |
| 142 | ||
| 143 | describe("over HTTP", () => { | |
| 144 | test("an admin gets a line; pasting it once enrols a runner-role machine; the second use is refused", async () => { | |
| 145 | const admin = createToken(f.app.db, f.alice.id, "admin", "admin").token; | |
| 146 | const made = await post("/api/v1/admin/machines/join", admin, {}); | |
| 147 | expect(made.status).toBe(201); | |
| 148 | const { line, minutes } = (await made.json()) as { line: string; minutes: number }; | |
| 149 | expect(minutes).toBe(15); | |
| 150 | const code = /FORGE_JOIN=(fjoin_[A-Za-z0-9_-]{43}) sh$/.exec(line)![1]!; | |
| 151 | expect(line).toStartWith("curl -fsSL "); | |
| 152 | expect(line).toContain("/api/v1/agent/install.sh"); | |
| 153 | ||
| 154 | const script = await fetch(`${f.servers.url}/api/v1/agent/install.sh`); | |
| 155 | expect(script.status).toBe(200); | |
| 156 | expect(await script.text()).toBe(INSTALL_SH); | |
| 157 | ||
| 158 | const joined = await post("/api/v1/agent/join", "", { code, name: "Studio Mac" }); | |
| 159 | expect(joined.status).toBe(201); | |
| 160 | const body = (await joined.json()) as { id: string; name: string; role: string; token: string }; | |
| 161 | expect(body.role).toBe("runner"); | |
| 162 | expect(body.name).toBe("studio-mac"); | |
| 163 | expect(body.token).toStartWith("forge_runner_"); | |
| 164 | expect((await post("/api/v1/agent/join", "", { code, name: "again" })).status).toBe(403); | |
| 165 | ||
| 166 | // The token is the runner role: it says it is here and claims, and sends nothing a box does. | |
| 167 | expect((await post("/api/v1/agent/v1/heartbeat", body.token, { v: 1, state: "idle" })).status).toBe(204); | |
| 168 | const wrong = await post("/api/v1/agent/v1/containers", body.token, { v: 1 }); | |
| 169 | expect(wrong.status).toBe(403); | |
| 170 | expect(((await wrong.json()) as { error: { code?: string } | string }).error).toBeDefined(); | |
| 171 | // It enrols no repository restriction and no label an admin did not give: its labels are empty. | |
| 172 | expect(getRunner(f.app.db, body.id)!.labels).toEqual([]); | |
| 173 | }); | |
| 174 | ||
| 175 | test("a failed bundle is remembered for a minute, not rebuilt by every anonymous request", async () => { | |
| 176 | resetRunnerBundle(); | |
| 177 | const realBuild = Bun.build; | |
| 178 | let builds = 0; | |
| 179 | (Bun as { build: unknown }).build = async () => { | |
| 180 | builds++; | |
| 181 | return { success: false, outputs: [], logs: [] }; | |
| 182 | }; | |
| 183 | try { | |
| 184 | const t = Date.now(); | |
| 185 | expect(await runnerBundle(t)).toBeUndefined(); | |
| 186 | expect(await runnerBundle(t + 1000)).toBeUndefined(); | |
| 187 | expect(await runnerBundle(t + 2000)).toBeUndefined(); | |
| 188 | expect(builds).toBe(1); | |
| 189 | expect(await runnerBundle(t + RETRY_MS + 1)).toBeUndefined(); | |
| 190 | expect(builds).toBe(2); | |
| 191 | } finally { | |
| 192 | (Bun as { build: unknown }).build = realBuild; | |
| 193 | resetRunnerBundle(); | |
| 194 | } | |
| 195 | }); | |
| 196 | ||
| 197 | test("the runner download is limited per address", async () => { | |
| 198 | let refused = 0; | |
| 199 | for (let i = 0; i < 40; i++) if ((await fetch(`${f.servers.url}/api/v1/agent/runner.js`)).status === 429) refused++; | |
| 200 | expect(refused).toBeGreaterThan(0); | |
| 201 | }); | |
| 202 | ||
| 203 | test("a stranger or a member cannot ask for a line", async () => { | |
| 204 | expect((await post("/api/v1/admin/machines/join", "", {})).status).toBeGreaterThanOrEqual(401); | |
| 205 | const bob = createToken(f.app.db, f.bob.id, "bob", "admin").token; | |
| 206 | expect((await post("/api/v1/admin/machines/join", bob, {})).status).toBeGreaterThanOrEqual(403); | |
| 207 | expect((await post("/api/v1/agent/join", "", { code: "nope", name: "x" })).status).toBe(403); | |
| 208 | expect((await post("/api/v1/agent/join", "", {})).status).toBe(403); | |
| 209 | }); | |
| 210 | ||
| 211 | test("a heartbeat's facts are checked: malformed ones are refused, good ones kept", async () => { | |
| 212 | const { runner, token } = enrolRunner(f.app.db, "facts-hb", f.alice.id); | |
| 213 | expect(readMessage("runner", "heartbeat", { v: 1, state: "idle", facts: { os: "beos" } }).ok).toBe(false); | |
| 214 | expect((await post("/api/v1/agent/v1/heartbeat", token, { v: 1, state: "idle", facts: { os: "beos" } })).status).toBe(422); | |
| 215 | const facts = { os: "linux", arch: "x64", docker: true, xcode: "" } as const; | |
| 216 | expect((await post("/api/v1/agent/v1/heartbeat", token, { v: 1, state: "idle", facts })).status).toBe(204); | |
| 217 | expect(getRunner(f.app.db, runner.id)!.facts).toEqual(facts); | |
| 218 | }); | |
| 219 | }); | |
| 220 | ||
| 221 | describe("what a machine says only narrows routing", () => { | |
| 222 | test("a job naming a label goes to a machine that says it, and saying it changes nothing else", () => { | |
| 223 | // Alone on the desk: runners and jobs of the tests before it are not part of this one. | |
| 224 | f.app.db.query("DELETE FROM check_runner").run(); | |
| 225 | f.app.db.query("DELETE FROM check_job").run(); | |
| 226 | const { runner } = enrolRunner(f.app.db, "narrow", f.alice.id); | |
| 227 | const now = Date.now(); | |
| 228 | offerJob(f.app.db, { runId: "r-docker", repoId: "r", dir: "/nowhere", job: labelled("docker") }); | |
| 229 | offerJob(f.app.db, { runId: "r-plain", repoId: "r", dir: "/nowhere", job: labelled("") }); | |
| 230 | // Before it says anything it takes the unlabelled job only. | |
| 231 | const first = claimJob(f.app.db, { id: runner.id, cells: false }, now); | |
| 232 | expect(first?.job.label ?? "").toBe(""); | |
| 233 | expect(labelServed(f.app.db, "r", "docker", now)).toBe(false); | |
| 234 | noteRunnerFacts(f.app.db, runner.id, { os: "linux", arch: "x64", docker: true, xcode: "" }); | |
| 235 | f.app.db.query("UPDATE check_runner SET seen_at = ?2 WHERE id = ?1").run(runner.id, now); | |
| 236 | expect(labelServed(f.app.db, "r", "docker", now)).toBe(true); | |
| 237 | expect(labelServed(f.app.db, "r", "xcode", now)).toBe(false); | |
| 238 | const second = claimJob(f.app.db, { id: runner.id, cells: false }, now); | |
| 239 | expect(second?.job.label).toBe("docker"); | |
| 240 | // What the facts did not touch. | |
| 241 | const after = getRunner(f.app.db, runner.id)!; | |
| 242 | expect(after.labels).toEqual([]); | |
| 243 | expect(after.repos).toEqual([]); | |
| 244 | expect(after.trusted).toBe(false); | |
| 245 | expect(after.paused).toBe(""); | |
| 246 | expect(after.revokedAt).toBe(0); | |
| 247 | }); | |
| 248 | ||
| 249 | test("a lent runner's facts add no label, though the same facts do for one this forge owns", () => { | |
| 250 | f.app.db.query("DELETE FROM check_job").run(); | |
| 251 | const facts = { os: "macos", arch: "arm64", docker: true, xcode: "16.2" }; | |
| 252 | const now = Date.now(); | |
| 253 | // The job is on a real public repository, so a lent runner could take it but for its label. | |
| 254 | const lent = enrolRunner(f.app.db, "lent-pal", f.alice.id, { authors: [], days: 1, coreMinPerDay: 10 }).runner; | |
| 255 | noteRunnerFacts(f.app.db, lent.id, facts); | |
| 256 | offerJob(f.app.db, { runId: "r-mac", repoId: f.repo.id, dir: "/nowhere", job: labelled("macos") }); | |
| 257 | expect(claimJob(f.app.db, { id: lent.id, cells: true }, now)).toBeUndefined(); | |
| 258 | // Control: the same facts on an owned runner do take it, so the refusal above is the scope's. | |
| 259 | const own = enrolRunner(f.app.db, "own-mac", f.alice.id).runner; | |
| 260 | noteRunnerFacts(f.app.db, own.id, facts); | |
| 261 | expect(claimJob(f.app.db, { id: own.id, cells: false }, now)?.job.label).toBe("macos"); | |
| 262 | }); | |
| 263 | }); |
test/route-timing-coverage.test.ts +2
| @@ -21,6 +21,8 @@ import { seedAdmin } from "./helpers/admin.ts"; | ||
| 21 | 21 | |
| 22 | 22 | /** Routes that answer 200 without a `session` phase → why. */ |
| 23 | 23 | const UNTIMED: Record<string, string> = { |
| 24 | "/api/v1/agent/install.sh": "a static script served to a joining machine, no session and no read; no page to phase", | |
| 25 | "/api/v1/agent/runner.js": "a static file served to a joining machine, no session and no read; no page to phase", | |
| 24 | 26 | "/api/v1/models": "the models offered to a person, two indexed reads; no page to phase", |
| 25 | 27 | "/api/v1/conversation-confirms": "the caller's held confirms, one indexed read; no page to phase", |
| 26 | 28 | "/api/v1/conversations": "a person's conversation list, one indexed query; no page to phase", |
test/settings-runners.test.ts +13
| @@ -262,6 +262,19 @@ describe("an outside runner, from the page", () => { | ||
| 262 | 262 | body, |
| 263 | 263 | }); |
| 264 | 264 | |
| 265 | test("Add a machine is a post form: its answer page shows the line once, no-store, to an admin only", async () => { | |
| 266 | const page = await (await get(alice)).text(); | |
| 267 | expect(page).toContain('action="/settings/runners/machine"'); | |
| 268 | expect(page).not.toContain("add-machine-go"); | |
| 269 | expect(page).not.toContain("fjoin_"); | |
| 270 | expect((await form(bob, "/settings/runners/machine", "")).status).toBeGreaterThanOrEqual(403); | |
| 271 | expect((await form(alice, "/settings/runners/machine", "", "http://elsewhere.test")).status).toBe(403); | |
| 272 | const made = await form(alice, "/settings/runners/machine", ""); | |
| 273 | expect(made.status).toBe(200); | |
| 274 | expect(made.headers.get("cache-control")).toBe("no-store"); | |
| 275 | expect(await made.text()).toMatch(/curl -fsSL [^<]*FORGE_JOIN=fjoin_[A-Za-z0-9_-]{43} sh/); | |
| 276 | }); | |
| 277 | ||
| 265 | 278 | test("the admin registers one with labels and repositories, sees its token once, and may pause and resume it", async () => { |
| 266 | 279 | const bad = await form(alice, "/settings/runners/register", "name=mac&labels=macos&repos=nobody%2Fnone"); |
| 267 | 280 | expect(bad.status).toBe(303); |
test/spawn-pipes.test.ts +1
| @@ -44,6 +44,7 @@ const PIPING: Record<string, { sites: string[]; reason: string }> = { | ||
| 44 | 44 | "src/looks/capture.ts": { sites: ["stderr"], reason: "stderr read in a background loop; stdout ignored" }, |
| 45 | 45 | "src/release/devtools.ts": { sites: ["stderr"], reason: "stderr read for the DevTools address, then drained in a background loop; stdout ignored" }, |
| 46 | 46 | "src/release/launch.ts": { sites: ["stderr"], reason: "hear() reads stderr to its end for the release's life, passing every chunk through to ours and keeping the tail until ready; stdout inherited" }, |
| 47 | "src/machines/facts.ts": { sites: ["stdout", "stdout"], reason: "each probe's stdout read to its end via Response.text() before the exit is awaited, under a 4 s timeout; stderr ignored" }, | |
| 47 | 48 | "src/release/boot.ts": { sites: ["stderr"], reason: "stderr read to its end in a background loop, awaited before the reason is read; stdout ignored" }, |
| 48 | 49 | "src/release/reuse.ts": { sites: ["stdout"], reason: "stdout (the label) read to its end before the exit is awaited; stderr ignored" }, |
| 49 | 50 | "src/release/small_forge.ts": { sites: ["stderr", "stdout"], reason: "run() reads each git stderr to its end via Response.text() before the exit is awaited, stdout ignored; spawnSync buffers rev-parse stdout, stderr ignored" }, |
test/spawn-sites.test.ts +2
| @@ -81,6 +81,8 @@ const SITES: Record<string, string> = { | ||
| 81 | 81 | "git on the forge's own data directory with arguments the code fixes", |
| 82 | 82 | "src/looks/capture.ts": |
| 83 | 83 | "headless Chromium from configuration with fixed flags and a URL the forge built for its own preview", |
| 84 | "src/machines/facts.ts": | |
| 85 | "`docker info --format` and `xcodebuild -version`: fixed argv, no user text", | |
| 84 | 86 | "src/machines/rc.ts": |
| 85 | 87 | "`git clone --quiet -- <bare> <partial>` between two paths the forge derived", |
| 86 | 88 | "src/release/boot.ts": |
new above
offline
High:
http://is accepted. run.sh fetches and executes runner.js before each start with the token in its environment, so anyone on the path can run code as this user. Require https, except for loopback.