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

Game boxes: a machine on your own cloud that runs a compose network, kept by a pull-based agent #16913

Merged opened this

Check · Review · Land · Live done — Landed and live in production.

Merged

sold/game-box → main 0 commits

  • Merged. sold/game-box was merged into main as 1d3fb6a.

Review

Sign in to review this change.
53 files changed +2866 −241
docs/design/audit.md +1
@@ -148,6 +148,7 @@ Machine routes are not pages and have no entry: `/audit.csv`,
148148 - `/settings/packs` — `pages/packs-settings.ts` · the repositories /packs lists, one textarea and Save · `/packs`, `/settings/features` · none seen.
149149 - `/settings/model` — `pages/model.ts` · which model the crew runs on · `/settings/crew` · none seen.
150150 - `/settings/cloud` — `pages/cloud.ts` · cloud provider connection · none · none seen.
151 - `/games` — `pages/games.ts` · game boxes and their services: console, power, env, plugins · Infra, where a box is made · none seen.
151152 - `/settings/cloud/audit` — `pages/cloud.ts` · what the cloud connection did · `/audit` (different subject, same word) · none seen.
152153 - `/cloud/connect` — `pages/cloud.ts` · connect a cloud in a minute, guided, one provider at a time · `/settings/cloud` (every key; this is the front door) · none seen.
153154 - `/settings/access` — `pages/access.ts` · who may reach the forge · `/settings/people`, `/settings/accounts` · none seen.
docs/features/game-box.md added +20
@@ -0,0 +1,20 @@
1 ---
2 topic: Hosting forges for others, and getting paid
3 row: Game boxes
4 ---
5 # Game boxes
6
7 A game box is a machine on your own cloud account that runs a Docker Compose project (a Minecraft
8 network, say) instead of a forge. The forge makes it the way it makes a pinned forge: through the
9 plan tray (each step, its monthly cost against the account's ceiling), the same drivers, volume,
10 hardening, DNS record and retire, so it shows in `infra`, the hourly watch and the cost reckoning,
11 and nothing appears at the provider unexplained. It never ends on its own: it is a home, not an
12 experiment.
13
14 - **Plan one (agents):** `infra` with `{ action: "plan", want: { game: true, where: "digitalocean/main@digitalocean:nyc3:s-4vcpu-8gb", name?: "mc", repo?: "trevato/mc-network", host?: "mc.trevato.dev" } }`, then `apply` its id. The plan says "Start a 4 vCPU, 8 GB game box in New York running trevato/mc-network's compose file" and waits for the address and the DNS record, not for an https answer. The web and terminal doors are `/games` and the Games screen.
15 - **The machine:** Ubuntu with Docker and its compose plugin (Ubuntu's packages, data on the box's volume), 4 GB of swap for the JVMs, and a firewall that lets in only 25565/tcp: no SSH, no web, no backend port. Password and root logins are off and updates are on, as on a forge.
16 - **The agent:** `/opt/forge-game/agent.sh` (`src/games/agent.sh`) under systemd (`forge-game-agent`). Every 5 s it POSTs the services, their CPU and memory, new log lines, command results and the host to `/api/v1/games/agent/sync`, and does what the answer asks: writes `compose.yml` and the answer's `.env` beside it (only that name: `FORWARDING_SECRET` and an `RCON_<SERVICE>` for every service; any other name is ignored and logged, so nothing can land on the agent's own files), runs `docker compose -p game --project-directory /opt/forge-game up -d --remove-orphans` when they change, and runs queued commands (rcon through `docker compose exec -T <service> rcon-cli -- <text>`, by service name, or restart, stop, start, pull, recreate). Nothing dials in to the box; a failed sync is tried again in 5 s, forever.
17 - **The token:** made whenever the box's machine is made (a create or a replace, which ends the old one's), kept only as its sha256 (`game_box.token_hash`, starting `fgb_`), and written only into the machine's `/opt/forge-game/agent.env` (mode 600), which the unit reads; the agent hands it to curl in a header file, never on a command line. `rotateGameBoxToken` makes a new one.
18 - **DNS:** an A record, not proxied, for the box's `host` in any Cloudflare zone a connected token can write; with none, the plan says to set it by hand.
19
20 Code: `src/games/store.ts` (the `game_box` row and its token, the games store's), `src/games/boot.ts` (the boot config), `src/games/agent.sh`, `gameWant` in `src/actions/infra.ts`, and `bootRow` in `src/actions/pinned.ts`.
docs/features/games.md added +26
@@ -0,0 +1,26 @@
1 ---
2 topic: Hosting forges for others, and getting paid
3 row: Games
4 ---
5 # Games
6
7 A **game box** is a VM on your own cloud running Docker and `forge-game-agent`, which pulls from the forge every 5 s. What it runs is a compose file in a forge repository (by default `trevato/mc-network`, `main`, `docker-compose.yml`), so an env change or a plugin is a commit, the crew can propose changes, and a merge redeploys.
8
9 ## Where
10
11 - **Web:** `/games` lists the boxes you may see; `/games/<box>` is the network, one row a service with Start, Stop and Restart; `/games/<box>/<service>` is the console (a live log over SSE and an RCON input whose answer shows inline), the environment editor (commits `games: <service> env: <keys>`) and the plugins (`PLUGINS`, `MODRINTH_PROJECTS`, Upload jar). Pages: `src/web/pages/games.ts`.
12 - **Terminal:** the Games screen (`src/tui/screens/games.ts`): each service, `s`, `x`, `r`.
13 - **MCP:** `games` (admin-listed tonight): `list`, `console`, `power`, `env`, `plugin`, with the same grants.
14 - **Agent:** `POST /api/v1/games/agent/sync` with the box token as bearer (`src/http/games_routes.ts`, `src/games/store.ts`): status, a log tail (2,000 lines a service), command results in; the compose (only when its sha differs), env files and queued commands (each handed out once) out.
15
16 ## Secrets
17
18 The Velocity forwarding secret (`forwarding.env`) and an RCON password a service (`rcon-<service>.env`) are generated once, sealed like every forge secret and sent only in the sync's `env`, never committed. A box token is shown once and stored hashed. An uploaded jar is kept by the forge at `/games/jar/<id>/<name>`; the compose a box gets carries it signed for 6 hours, and only for the box that uploaded it. A jar must be a `.jar` (a zip), at most 64 MiB, and a box keeps at most 20 jars and 256 MiB.
19
20 The environment editor refuses a key that looks like a secret (`PASSWORD`, `SECRET`, `TOKEN`, `KEY` in its name): a secret belongs in the sealed `.env` the forge writes to the box, never in the repository. An env or plugin change is a commit by the person who asks, so it needs write access to the compose repository; without it the forge says to ask the repository's owner.
21
22 A plugin or jar runs code on the game server; give operator only to people you trust.
23
24 ## Who may do what
25
26 Grants per box, optionally for one service: **owner** (everything and grants), **operator** (console, power, env, plugins), **viewer** (read). Forge admins own every box; owners grant on the box page.
src/actions/infra.ts +19
@@ -31,6 +31,7 @@ import type { User } from "../core/users.ts";
3131 import { resolveOid } from "../git/merge.ts";
3232 import { repoDir } from "../git/repos.ts";
3333 import { err, ok, type Result } from "../kernel/result.ts";
34 import { listBoxes } from "../games/store.ts";
3435 import { getBaseDomain } from "../settings/pinned_domain.ts";
3536 import { LIFETIME_DAYS, dayWords, endsWords } from "./pinned.ts";
3637 import { placeWords } from "../cloud/places.ts";
@@ -66,6 +67,8 @@ export interface Running {
6667 readonly atProvider: boolean;
6768 /** A dead row (failed, nothing at its provider) says so and what to do: "nothing exists at DigitalOcean; clear this row". Empty otherwise. */
6869 readonly clear: string;
70 /** A game box (`games/store.ts`): Docker and the game agent, not a forge. */
71 readonly game?: true;
6972 }
7073
7174 /** What a group of machines is for: an experiment's question, or the app they run. */
@@ -168,6 +171,7 @@ function reckon(app: App, now: Date): { view: InfraView; rows: Map<string, Runni
168171 .map((r) => [r.name, r.at]),
169172 );
170173 const pinned = listPinned(db);
174 const games = new Set(listBoxes(db).map((g) => g.name));
171175 for (const p of pinned) {
172176 const monthlyCents = cents.get(p.name) ?? 0;
173177 // A machine still being made is the build tray's, not a row yet.
@@ -188,6 +192,7 @@ function reckon(app: App, now: Date): { view: InfraView; rows: Map<string, Runni
188192 billing: billingSentence(p, monthlyCents, p.state === "retired" && retiredAt.has(p.name) ? dayWords(retiredAt.get(p.name)!) : undefined),
189193 atProvider: existsAtProvider(p),
190194 clear: p.state === "failed" && !existsAtProvider(p) ? `nothing exists at ${isProvider(p.target) ? LABEL[p.target] : p.target}; clear this row` : "",
195 ...(games.has(p.name) ? { game: true as const } : {}),
191196 };
192197 rows.set(p.name, r);
193198 if (p.state === "retired") {
@@ -431,6 +436,20 @@ export async function wantOf(app: App, c: Compose, choices: ComposeChoices = com
431436 });
432437 }
433438
439 /**
440 * A game box's want (`games/store.ts`): a machine at `where` (`account@placeId`) running the compose
441 * file in `repo` (`owner/name`, default `trevato/mc-network`), served on `host` when given. A home,
442 * not an experiment: it never ends on its own.
443 */
444 export function gameWant(g: { readonly name: string; readonly where: string; readonly repo?: string; readonly host?: string }): Result<MachineWant, string> {
445 const [account = "", place = ""] = g.where.split("@");
446 if (account === "" || place === "") return err("Pick where the game box runs.");
447 if (!NAME.test(g.name)) return err("A name is lowercase letters, digits and dashes, starting with a letter.");
448 const repo = g.repo === undefined || g.repo === "" ? "trevato/mc-network" : g.repo;
449 if (!/^[A-Za-z0-9._-]+\/[A-Za-z0-9._-]+$/.test(repo)) return err("Name the compose file's repository as owner/name.");
450 return ok({ kind: "machine", game: true, name: g.name, account, place, app: repo, source: "", ...(g.host ? { host: g.host } : {}) });
451 }
452
434453 /** A plan with the sentences and links every door shows beside it. */
435454 export interface Planned {
436455 readonly plan: Plan;
src/actions/pinned.ts +31 −4
@@ -25,6 +25,8 @@
2525 */
2626
2727 import { resolve4 } from "node:dns/promises";
28 import { boxNamed, createGameBox, rotateGameBoxToken, setGameBoxMachine } from "../games/store.ts";
29 import type { GameBoot } from "../games/boot.ts";
2830 import type { App } from "../app.ts";
2931 import { gatedFetch } from "../cloud/gate.ts";
3032 import { capped, CeilingRefusal, priced, refusalAt, rowCents } from "../cloud/ceiling.ts";
@@ -433,8 +435,24 @@ export type DeployInput = {
433435 plan?: PlanName | undefined;
434436 /** Days until the forge retires it on its own (#16696); absent, it never does. Never for an order. */
435437 lifetimeDays?: number | undefined;
438 /**
439 * A game box (`games/store.ts`): the machine boots Docker and the game agent, not a forge, and runs
440 * the compose file in `app` (`owner/name`).
441 */
442 game?: boolean | undefined;
436443 };
437444
445 /**
446 * The row a machine is made from: a game box's carries its boot (`games/boot.ts`) with a token made
447 * now, so each machine made for it (a create or a replace) has its own and ends the one before.
448 */
449 function bootRow(app: App, p: Pinned): Pinned & { game?: GameBoot } {
450 const box = boxNamed(app.db, p.name);
451 if (box === undefined) return p;
452 const token = rotateGameBoxToken(app.db, box.id);
453 return { ...p, game: { forgeUrl: (app.config.url ?? "").replace(/\/+$/, ""), token } };
454 }
455
438456 export async function deployPinned(app: App, actor: User | undefined, input: DeployInput): Promise<Result<Issued, string>> {
439457 const who = admin(actor);
440458 return who.ok ? deployAs(app, who.value, input) : who;
@@ -450,6 +468,7 @@ async function deployAs(app: App, who: Who, input: DeployInput): Promise<Result<
450468 const host = hostFor(app, input.name, input.host);
451469 if (!host.ok) return host;
452470 if (!APP.test(input.app)) return err("Name the app as owner/name.");
471 if (input.game === true && !/^https:\/\//.test(app.config.url ?? "")) return err("A game box answers to this forge over https, and this forge has no https address set.");
453472 const code = ownCode(app, input);
454473 if (!code.ok) return code;
455474 if (!validSource(code.value.source)) return err("The source is an https git address.");
@@ -476,15 +495,23 @@ async function deployAs(app: App, who: Who, input: DeployInput): Promise<Result<
476495 if (!at.ok) return at;
477496 if (old) dropPinned(app.db, old.name);
478497 const claim = newClaim();
479 const { place: _asked, plan: _plan, lifetimeDays, ...rest } = input;
498 const { place: _asked, plan: _plan, lifetimeDays, game, ...rest } = input;
480499 const p = insertPinned(app.db, { ...rest, ...code.value, target: t.id, config: config.value, host: host.value, claimHash: claim.hash, claimExpires: claim.expires, datacenter: at.value.datacenter, size: at.value.size }, who.by);
481500 app.bus.append({ kind: "pinned.deployed", actorId: who.id, payload: { name: p.name, target: p.target, version: p.version, ...orderOf(who) } });
482501 if (lifetimeDays !== undefined && who.order === undefined) setLifetime(app.db, p.id, new Date(Date.now() + lifetimeDays * DAY_MS).toISOString());
483502 if (old?.volume) setRemote(app.db, p.name, { volume: old.volume });
503 // A game box's row (the games store's): made with the machine, its compose file the app's
504 // repository, its place and monthly cost the catalog's; a box made first takes the machine.
505 if (game === true) {
506 const m = { pinnedId: p.id, place: placeIdOf(p), monthlyCents: priced(app.db).forge(placeIdOf(p)) ?? 0 };
507 const box = boxNamed(app.db, p.name);
508 if (box === undefined) createGameBox(app.db, { name: p.name, repo: p.app, ...m });
509 else setGameBoxMachine(app.db, box.id, m);
510 }
484511 const made = await create(
485512 app, who, p, "deploy",
486513 (f, token) =>
487 provision(capped(app, p.name, driverOf(p.target)), f, token, getPinned(app.db, p.name)!, {
514 provision(capped(app, p.name, driverOf(p.target)), f, token, bootRow(app, getPinned(app.db, p.name)!), {
488515 ...(old?.volume ? { have: old.volume } : {}),
489516 project: projectOf(app, p),
490517 onVolume: (volume) => setRemote(app.db, p.name, { volume }),
@@ -541,7 +568,7 @@ async function changeNow(
541568 const after = getPinned(app.db, name)!;
542569 const done = await create(
543570 app, who.value, after, kind,
544 (f, token) => replace(capped(app, after.name, driverOf(after.target)), f, token, after, { project: projectOf(app, after), onDeleted: () => setRemote(app.db, name, { remote: "", address: "" }), onUnfiled: unfiled(app, who.value, name) }),
571 (f, token) => replace(capped(app, after.name, driverOf(after.target)), f, token, bootRow(app, after), { project: projectOf(app, after), onDeleted: () => setRemote(app.db, name, { remote: "", address: "" }), onUnfiled: unfiled(app, who.value, name) }),
545572 (m) => setRemote(app.db, name, { ...m, address: "", state: "running" }),
546573 true,
547574 );
@@ -618,7 +645,7 @@ async function claimNow(app: App, who: Who, name: string, input: { host?: string
618645 const after: Pinned = { ...getPinned(app.db, name)!, claimHash: claim.hash, claimExpires: claim.expires };
619646 const done = await create(
620647 app, who, after, "claim",
621 (f, token) => replace(capped(app, after.name, driverOf(after.target)), f, token, after, { project: projectOf(app, after), onDeleted: () => setRemote(app.db, name, { remote: "", address: "" }), onUnfiled: unfiled(app, who, name) }),
648 (f, token) => replace(capped(app, after.name, driverOf(after.target)), f, token, bootRow(app, after), { project: projectOf(app, after), onDeleted: () => setRemote(app.db, name, { remote: "", address: "" }), onUnfiled: unfiled(app, who, name) }),
622649 (m) => {
623650 setClaim(app.db, name, { hash: claim.hash, expires: claim.expires });
624651 setRemote(app.db, name, { ...m, address: "", state: "running" });
src/cloud/machine.ts +8 −2
@@ -24,6 +24,7 @@ import { firstAdminSeed, readSeed } from "../core/first_admin.ts";
2424 import { BOOT_NAMES, portOf, validHost, validSource, type Pinned } from "../core/pinned.ts";
2525 import { OWN_FORGE_REPO } from "../spawn/own_forge.ts";
2626 import { BUN_INSTALLER, bunInstallScript } from "./bun_install.ts";
27 import { gameBootConfig, type GameBoot } from "../games/boot.ts";
2728 import { CHECKOUT, hardenEarly, hardenFiles, hardenHead, hardenLate, mount, proxyStore, serviceUnit } from "./harden.ts";
2829
2930 /**
@@ -36,8 +37,12 @@ export const BUN_VERSION = BUN_PIN ?? Bun.version;
3637 /** The name of the volume holding a forge's data, the same on every cloud. */
3738 export const volumeName = (name: string) => `forge-${name}-data`;
3839
39 /** What a machine is booted from: the pin, the name it is served on, and the hash of its claim. */
40 export type Booted = Pick<Pinned, "name" | "source" | "version" | "config" | "host" | "claimHash" | "claimExpires">;
40 /**
41 * What a machine is booted from: the pin, the name it is served on, and the hash of its claim. A
42 * game box's row carries `game` instead (`games/boot.ts`): the forge it answers to and its token,
43 * set only on the row handed to its own create, never stored.
44 */
45 export type Booted = Pick<Pinned, "name" | "source" | "version" | "config" | "host" | "claimHash" | "claimExpires"> & { readonly game?: GameBoot | undefined };
4146
4247 /**
4348 * What the forge is told about its name, its claim and its sandbox (#16217); these win over the
@@ -121,6 +126,7 @@ const proxyCommands = (dataDir: string): string => ` - install -d -m 0700 -o ca
121126 * is `harden.ts`. What the boot sets is written after the config, the data directory last.
122127 */
123128 export function bootConfig(p: Booted, dataDir: string, early: readonly string[] = []): string {
129 if (p.game !== undefined) return gameBootConfig(p.game, dataDir);
124130 // A row from before `checkConfig` refused these names may still hold one: it is dropped, so what
125131 // the boot sets is said once and in its own place.
126132 const settings = Object.fromEntries(Object.entries(p.config).filter(([k]) => !BOOT_NAMES.includes(k)));
src/cloud/plan.ts +11 −2
@@ -69,6 +69,11 @@ export interface MachineWant {
6969 readonly question?: string | undefined;
7070 /** `version` is the app's main as the plan was made: the steps say "latest", not a commit. */
7171 readonly latest?: boolean | undefined;
72 /**
73 * A game box (`games/store.ts`): Docker and the game agent running the compose file in `app`, not
74 * a forge; it never answers on https, so no step waits for that.
75 */
76 readonly game?: boolean | undefined;
7277 }
7378
7479 export type Want = MachineWant;
@@ -341,7 +346,10 @@ export function plan(wants: readonly Want[], have: readonly Have[], reads: Reads
341346 name: w.name,
342347 account: w.account,
343348 cents: add,
344 says: `Start a ${spot.shape} machine in ${spot.city} running ${w.app}${versionWords(w)}, ${daysWords(days)}`,
349 says:
350 w.game === true
351 ? `Start a ${spot.shape} game box in ${spot.city} running ${w.app}'s compose file, ${daysWords(days)}`
352 : `Start a ${spot.shape} machine in ${spot.city} running ${w.app}${versionWords(w)}, ${daysWords(days)}`,
345353 });
346354 calls += 1;
347355 }
@@ -371,7 +379,7 @@ export function plan(wants: readonly Want[], have: readonly Have[], reads: Reads
371379 cents: 0,
372380 says: `Point ${host} at it in Cloudflare`,
373381 });
374 if (reads.dnsAuto && (make || h?.answered !== true)) {
382 if (reads.dnsAuto && w.game !== true && (make || h?.answered !== true)) {
375383 step(waits, { kind: "ready", name: w.name, account: w.account, says: `Wait until ${host} answers`, cents: 0 });
376384 boots.push(BOOT_SECONDS[at.provider] ?? BOOT_DEFAULT);
377385 }
@@ -719,6 +727,7 @@ function handsOf(app: App, actor: User | undefined): Hands {
719727 ...(w.source === "" ? {} : { source: w.source }),
720728 ...(w.version === undefined ? {} : { version: w.version }),
721729 ...(w.lifetimeDays === undefined ? {} : { lifetimeDays: w.lifetimeDays }),
730 ...(w.game === true ? { game: true } : {}),
722731 });
723732 },
724733 retire: (name) => retirePinned(app, actor, name),
src/contract/openapi/routes/index.ts +1
@@ -364,6 +364,7 @@ export { route as postApiV1ForgeTemplates } from "./postApiV1ForgeTemplates.ts";
364364 export { route as postApiV1Forges } from "./postApiV1Forges.ts";
365365 export { route as postApiV1ForgesNameClaimLink } from "./postApiV1ForgesNameClaimLink.ts";
366366 export { route as postApiV1ForgesNameSandbox } from "./postApiV1ForgesNameSandbox.ts";
367 export { route as postApiV1GamesAgentSync } from "./postApiV1GamesAgentSync.ts";
367368 export { route as postApiV1Heartbeat } from "./postApiV1Heartbeat.ts";
368369 export { route as postApiV1MaintenanceDutiesName } from "./postApiV1MaintenanceDutiesName.ts";
369370 export { route as postApiV1Migrate } from "./postApiV1Migrate.ts";
src/contract/openapi/routes/postApiV1GamesAgentSync.ts added +11
@@ -0,0 +1,11 @@
1 import type { Route } from "../shared.ts";
2
3 export const route: Route = {
4 method: "post",
5 path: "/api/v1/games/agent/sync",
6 summary: "A game box agent's sync: status, logs and results in; compose, .env and commands out",
7 detail: "The bearer is the game box's token. Send `{ agent, composeSha, services, logs, results, host }`; the answer is `{ composeSha, compose? (only when the sha differs), env, commands }`, each command handed out once",
8 auth: false,
9 role: "anonymous",
10 refuses: [401],
11 };
src/contract/tags.ts +1
@@ -131,6 +131,7 @@ export const TAG_WORDS: Readonly<Record<string, string>> = {
131131 feed: "The timeline, posts, shares, search and exploring",
132132 forges: "Forges, organizations and boards: creating and following them",
133133 forks: "Forks, upstream following, offers and make-it-yours",
134 games: "Game boxes: the agent's sync with the forge",
134135 gates: "The gate queue and the log of each gate",
135136 hooks: "Webhooks of a repository and their deliveries",
136137 issues: "Issues, their comments, dependencies, teams and plans",
src/core/account_purge.ts +2
@@ -50,6 +50,8 @@ export const COVERED: Readonly<Record<string, Coverage>> = {
5050 // A person's own: sign-in links, notices, asks, search, grants, sessions.
5151 "access_link.user_id": DELETE,
5252 "access_link.created_by": FORMER,
53 // Who asked a game box to run a command: the record keeps it, as the former account.
54 "game_command.by": FORMER,
5355 "account_ceiling.set_by": FORMER,
5456 "allocation_entry.actor_id": FORMER,
5557 "allocation_weekly.set_by": FORMER,
src/core/empty_words.ts +3
@@ -93,6 +93,9 @@ const TABLE = {
9393 flags: { sentence: NO_FLAG },
9494 appFlags: { sentence: NO_FLAG, reason: `Add a ${FLAGS_FILE} to the repository to declare one.` },
9595 regValues: { sentence: "No values." },
96 gameBoxes: { sentence: "Nothing runs here yet.", reason: "A game box is a machine on your cloud running a compose project; an admin makes one from Infra." },
97 gameServices: { sentence: "Nothing has reported yet.", reason: "The box shows its services once its agent first syncs." },
98 gamePlugins: { sentence: "Nothing is installed.", reason: "Add a URL, a Modrinth project or a jar below." },
9699 } as const satisfies Readonly<Record<string, EmptyWords>>;
97100
98101 export type EmptyKind = keyof typeof TABLE;
src/core/migration-pins/20261201000000-games.pin added +1
@@ -0,0 +1,1 @@
1 7dbcce86494fe48905c1cab8f0de32065af32f808eaaad1368eff982e50f542a
src/core/migrations/20261201000000-games.ts added +69
@@ -0,0 +1,69 @@
1 // Game boxes (forge games, 2026-11-30): a VM running Docker and forge-game-agent, which pulls its
2 // compose from a repository and reports back every 5 s. Its token is stored hashed (like a runner's);
3 // services, a bounded log tail, a command queue, grants and uploaded plugin jars are rows here.
4 export default `
5 CREATE TABLE IF NOT EXISTS game_box (
6 id TEXT PRIMARY KEY,
7 name TEXT NOT NULL UNIQUE,
8 token_hash TEXT NOT NULL,
9 repo TEXT NOT NULL DEFAULT 'trevato/mc-network',
10 branch TEXT NOT NULL DEFAULT 'main',
11 path TEXT NOT NULL DEFAULT 'docker-compose.yml',
12 pinned_id TEXT NOT NULL DEFAULT '',
13 place TEXT NOT NULL DEFAULT '',
14 monthly_cents INTEGER NOT NULL DEFAULT 0,
15 host_json TEXT NOT NULL DEFAULT '{}',
16 compose_sha TEXT NOT NULL DEFAULT '',
17 seen_at TEXT NOT NULL DEFAULT '',
18 created_at TEXT NOT NULL
19 );
20 CREATE INDEX IF NOT EXISTS game_box_token ON game_box (token_hash);
21 CREATE TABLE IF NOT EXISTS game_service (
22 box_id TEXT NOT NULL,
23 name TEXT NOT NULL,
24 state TEXT NOT NULL DEFAULT '',
25 health TEXT NOT NULL DEFAULT '',
26 started_at TEXT NOT NULL DEFAULT '',
27 cpu_pct REAL NOT NULL DEFAULT 0,
28 mem_mib REAL NOT NULL DEFAULT 0,
29 seen_at TEXT NOT NULL DEFAULT '',
30 PRIMARY KEY (box_id, name)
31 );
32 CREATE TABLE IF NOT EXISTS game_log (
33 id INTEGER PRIMARY KEY,
34 box_id TEXT NOT NULL,
35 service TEXT NOT NULL,
36 line TEXT NOT NULL,
37 at TEXT NOT NULL
38 );
39 CREATE INDEX IF NOT EXISTS game_log_service ON game_log (box_id, service, id);
40 CREATE TABLE IF NOT EXISTS game_command (
41 id TEXT PRIMARY KEY,
42 box_id TEXT NOT NULL,
43 service TEXT NOT NULL,
44 kind TEXT NOT NULL,
45 text TEXT NOT NULL DEFAULT '',
46 by TEXT NOT NULL DEFAULT '',
47 created_at TEXT NOT NULL,
48 handed_at TEXT NOT NULL DEFAULT '',
49 done_at TEXT NOT NULL DEFAULT '',
50 ok INTEGER,
51 output TEXT NOT NULL DEFAULT ''
52 );
53 CREATE INDEX IF NOT EXISTS game_command_box ON game_command (box_id, handed_at);
54 CREATE TABLE IF NOT EXISTS game_grant (
55 box_id TEXT NOT NULL,
56 user_id TEXT NOT NULL REFERENCES user(id) ON DELETE CASCADE,
57 role TEXT NOT NULL,
58 service TEXT NOT NULL DEFAULT '',
59 PRIMARY KEY (box_id, user_id, service)
60 );
61 CREATE TABLE IF NOT EXISTS game_jar (
62 id TEXT PRIMARY KEY,
63 box_id TEXT NOT NULL,
64 name TEXT NOT NULL,
65 sha256 TEXT NOT NULL,
66 bytes INTEGER NOT NULL,
67 created_at TEXT NOT NULL
68 );
69 `;
src/core/reserved.ts +1
@@ -80,6 +80,7 @@ export const SYSTEM_NAMES: readonly string[] = [
8080 "csp-report",
8181 "deploy-to",
8282 "pinned",
83 "games",
8384 "infra",
8485 "cloud",
8586 "pipeline",
src/crew/conversation_ask.ts +8
@@ -321,6 +321,14 @@ export const ASKED_AS: Readonly<Record<string, Form>> = {
321321 },
322322 pinned_forge: (a) => pinnedForge(a),
323323 infra: (a) => infra(a),
324 games: (a) => {
325 const on = `${clause("", val(a, "service"), " on ")}${val(a, "box") || "a game box"}`;
326 if (a["action"] === "console") return `Run ${quote(a, "text") || "a command"} in the console of ${on}`;
327 if (a["action"] === "power") return `${val(a, "kind") || "Restart"} ${on}`.replace(/^./, (c) => c.toUpperCase());
328 if (a["action"] === "env") return `Set ${val(a, "key")} on ${on}${clause(" to ", val(a, "value"))}, a commit that redeploys it`;
329 if (a["action"] === "plugin") return `Add the plugin ${val(a, "modrinth") || val(a, "value")} to ${on}, a commit that redeploys it`;
330 return `Change ${on}`;
331 },
324332 crew_accounts: (a) => `Let the crew's runs for ${val(a, "repo") || val(a, "owner") || "your repositories"} spend the account ${val(a, "allow")}`,
325333 subscriptions: (a) =>
326334 val(a, "order") !== ""
src/crew/conversation_confirm.ts +1
@@ -142,6 +142,7 @@ export const ASKING: Readonly<Record<string, Asking>> = {
142142 origins: { asks: not("action", "list", "repos") },
143143 cloud_account: {},
144144 pinned_forge: { asks: not("verb", "list") },
145 games: { asks: not("action", "list") },
145146 // A plan built on the owner's own cloud spends their money: the person says so first (#16696).
146147 infra: { asks: (a) => a["action"] === "apply" },
147148 outsiders: {},
src/games/agent.sh added +147
@@ -0,0 +1,147 @@
1 #!/usr/bin/env bash
2 # forge-game-agent (forge games, 2026-11-30): keeps a game box's Docker Compose project as the forge
3 # says. Every 5 s it POSTs what runs (services, stats, new log lines, command results, the host) to
4 # $FORGE_URL/api/v1/games/agent/sync with the box's bearer token, and does what the answer asks:
5 # writes compose.yml and the secret env files beside it and brings the project up when the compose
6 # sha (or an env file) changes, and runs the queued commands. Nothing dials in to the box. A failed
7 # sync waits 5 s and tries again, forever. The token is read from the environment (systemd's
8 # EnvironmentFile, mode 600) and handed to curl in a header file, never on a command line.
9 set -u
10
11 DIR="${FORGE_GAME_DIR:-/opt/forge-game}"
12 DOCKER="${FORGE_GAME_DOCKER:-docker}"
13 EVERY="${FORGE_GAME_EVERY:-5}"
14 ONCE="${FORGE_GAME_ONCE:-0}"
15 : "${FORGE_URL:?FORGE_URL is the forge this box answers to}"
16 : "${FORGE_GAME_TOKEN:?FORGE_GAME_TOKEN is this box token}"
17
18 umask 077
19 mkdir -p "$DIR"
20 cd "$DIR" || exit 1
21 AUTH="$DIR/.auth"
22 printf 'Authorization: Bearer %s\n' "$FORGE_GAME_TOKEN" >"$AUTH"
23 unset FORGE_GAME_TOKEN
24
25 SAFE='^[A-Za-z0-9._-]{1,64}$'
26 # The project directory is the box's own, so compose reads the `.env` the forge writes beside it.
27 compose() { "$DOCKER" compose -p game --project-directory "$DIR" -f "$DIR/compose.yml" "$@"; }
28 now() { date -u +%Y-%m-%dT%H:%M:%SZ; }
29
30 since="$(now)"
31 [ -f "$DIR/.results" ] || echo '[]' >"$DIR/.results"
32
33 # The services as compose sees them, with each one's CPU and memory from docker stats.
34 services() {
35 local ps stats
36 ps="$(compose ps -a --format json 2>/dev/null | jq -cs 'flatten' 2>/dev/null)" || ps='[]'
37 [ -n "$ps" ] || ps='[]'
38 stats="$("$DOCKER" stats --no-stream --format json 2>/dev/null | jq -cs '.' 2>/dev/null)" || stats='[]'
39 [ -n "$stats" ] || stats='[]'
40 jq -cn --argjson ps "$ps" --argjson stats "$stats" '
41 def mib: (capture("^(?<n>[0-9.]+)\\s*(?<u>[KMGT]?i?B)") // {n: "0", u: "MiB"})
42 | (.n | tonumber) * ({"B": 1/1048576, "KiB": 1/1024, "KB": 1/1024, "MiB": 1, "MB": 1, "GiB": 1024, "GB": 1024, "TiB": 1048576}[.u] // 1);
43 ($stats | map({key: .Name, value: .}) | from_entries) as $s
44 | $ps | map({
45 name: .Service,
46 state: (.State // ""),
47 health: (.Health // ""),
48 startedAt: (.CreatedAt // ""),
49 cpuPct: (($s[.Name].CPUPerc // "0%") | rtrimstr("%") | tonumber? // 0),
50 memMiB: (($s[.Name].MemUsage // "0MiB") | split(" / ")[0] | mib | floor)
51 })'
52 }
53
54 # New log lines since the last sync, at most 200 a service: "hub | text" split at the first bar.
55 logs() {
56 compose logs --no-color --since "$1" 2>/dev/null | jq -cRn '
57 [inputs | capture("^(?<s>[^ |]+)[ ]*\\| ?(?<l>.*)$")?]
58 | group_by(.s) | map({key: .[0].s, value: (map(.l) | .[-200:])}) | from_entries' 2>/dev/null || echo '{}'
59 }
60
61 host() {
62 local total avail load disk
63 total="$(awk '/^MemTotal:/ {print int($2/1024)}' /proc/meminfo 2>/dev/null || echo 0)"
64 avail="$(awk '/^MemAvailable:/ {print int($2/1024)}' /proc/meminfo 2>/dev/null || echo 0)"
65 load="$(cut -d' ' -f1 /proc/loadavg 2>/dev/null || echo 0)"
66 disk="$(df -BG --output=avail "$DIR" 2>/dev/null | tail -1 | tr -dc '0-9')"
67 jq -cn --argjson t "${total:-0}" --argjson a "${avail:-0}" --argjson l "${load:-0}" --argjson d "${disk:-0}" \
68 '{memMiB: $t, memUsedMiB: ($t - $a), load1: $l, diskFreeGiB: $d}'
69 }
70
71 # Run one command from the forge and keep its result for the next sync (output at most 4 KB).
72 run() {
73 local cmd="$1" id kind service text out ok=true
74 id="$(jq -r '.id // ""' <<<"$cmd")"
75 kind="$(jq -r '.kind // ""' <<<"$cmd")"
76 service="$(jq -r '.service // ""' <<<"$cmd")"
77 text="$(jq -r '.text // ""' <<<"$cmd")"
78 if ! [[ "$service" =~ $SAFE ]]; then
79 out="refused: the service name is not one compose can have"
80 ok=false
81 else
82 case "$kind" in
83 # Through compose, by service: a container is named game-<service>-1 unless the file says otherwise.
84 rcon) out="$(compose exec -T "$service" rcon-cli -- "$text" 2>&1)" || ok=false ;;
85 restart | stop | start | pull) out="$(compose "$kind" "$service" 2>&1)" || ok=false ;;
86 recreate) out="$(compose up -d --force-recreate "$service" 2>&1)" || ok=false ;;
87 *)
88 out="refused: $kind is not a command this agent runs"
89 ok=false
90 ;;
91 esac
92 fi
93 jq -c --arg id "$id" --argjson ok "$ok" --arg out "${out:0:4096}" '. + [{id: $id, ok: $ok, output: $out}]' "$DIR/.results" >"$DIR/.results.next" &&
94 mv "$DIR/.results.next" "$DIR/.results"
95 }
96
97 # Write what the answer carries; bring the project up when the compose or an env file changed.
98 apply() {
99 local answer="$1" sha changed=0 name
100 sha="$(jq -r '.composeSha // ""' <<<"$answer")"
101 if jq -e 'has("compose") and (.compose | type == "string")' <<<"$answer" >/dev/null 2>&1 &&
102 [ "$sha" != "$(cat "$DIR/.compose-sha" 2>/dev/null)" ]; then
103 jq -j '.compose' <<<"$answer" >"$DIR/compose.yml.next" && mv "$DIR/compose.yml.next" "$DIR/compose.yml"
104 changed=1
105 fi
106 while IFS= read -r name; do
107 # Only `.env`, compose's own: any other name could land on the agent's own files (agent.env, .auth).
108 if [ "$name" != ".env" ]; then
109 echo "forge-game-agent: ignored env file $name: only .env is written" >&2
110 continue
111 fi
112 jq -j --arg n "$name" '.env[$n] // ""' <<<"$answer" >"$DIR/$name.next" || continue
113 cmp -s "$DIR/$name.next" "$DIR/$name" || changed=1
114 mv "$DIR/$name.next" "$DIR/$name"
115 done < <(jq -r '(.env // {}) | keys[]' <<<"$answer" 2>/dev/null)
116 if [ "$changed" = 1 ] && [ -f "$DIR/compose.yml" ]; then
117 if compose up -d --remove-orphans >"$DIR/.up.log" 2>&1; then
118 printf '%s' "$sha" >"$DIR/.compose-sha"
119 fi
120 fi
121 while IFS= read -r cmd; do
122 [ -n "$cmd" ] && run "$cmd"
123 done < <(jq -c '.commands // [] | .[]' <<<"$answer" 2>/dev/null)
124 }
125
126 sync() {
127 local next body answer
128 next="$(now)"
129 body="$(jq -cn \
130 --arg sha "$(cat "$DIR/.compose-sha" 2>/dev/null)" \
131 --argjson services "$(services)" \
132 --argjson logs "$(logs "$since")" \
133 --slurpfile results "$DIR/.results" \
134 --argjson host "$(host)" \
135 '{agent: 1, composeSha: $sha, services: $services, logs: $logs, results: $results[0], host: $host}')" || return 1
136 answer="$(curl -fsS -m 20 -H "@$AUTH" -H 'content-type: application/json' --data-binary "$body" "${FORGE_URL%/}/api/v1/games/agent/sync")" || return 1
137 # Delivered: the results and the log lines are the forge's now.
138 echo '[]' >"$DIR/.results"
139 since="$next"
140 apply "$answer"
141 }
142
143 while :; do
144 sync || echo "forge-game-agent: sync failed; again in ${EVERY}s" >&2
145 [ "$ONCE" = 1 ] && exit 0
146 sleep "$EVERY"
147 done
src/games/agent_sh.d.ts added +5
@@ -0,0 +1,5 @@
1 /** `agent.sh` is imported as text (`with { type: "text" }`), so the bundle carries it. */
2 declare module "*.sh" {
3 const text: string;
4 export default text;
5 }
src/games/boot.ts added +91
@@ -0,0 +1,91 @@
1 /**
2 * A game box's boot config (forge games, 2026-11-30): the cloud-config a game box's machine boots
3 * with, where a pinned forge's is `cloud/machine.ts` `bootConfig`. What hardens it is the same as a
4 * forge's (no password or root login, updates, `harden.ts`); then a firewall that lets in only the
5 * game's port (25565/tcp; no SSH, as a forge has none), swap for the JVMs, Docker with its compose
6 * plugin (Ubuntu's own packages) keeping its data on the box's volume, and the agent (`agent.sh`) under systemd. The token
7 * is in one place only: `/opt/forge-game/agent.env`, mode 600, which the unit reads.
8 */
9
10 import agentScript from "./agent.sh" with { type: "text" };
11 import { hardenFiles } from "../cloud/harden.ts";
12
13 /** The one port a game box opens to the world: Velocity's, in front of every backend. */
14 export const GAME_PORT = 25565;
15 /** Where the agent, its env file and the compose project live. */
16 export const GAME_DIR = "/opt/forge-game";
17 /** How much swap the box gets, in GiB: room for the JVMs' peaks on an 8 GB machine. */
18 const SWAP_GIB = 4;
19
20 /** The agent, as it ships beside this file. */
21 export const AGENT_SH: string = agentScript;
22
23 /** What only the box's own boot config carries: the forge it answers to and its token. */
24 export interface GameBoot {
25 readonly forgeUrl: string;
26 readonly token: string;
27 }
28
29 const TOKEN = /^fgb_[A-Za-z0-9_-]{43}$/;
30
31 /** The agent's unit: restarted always, the env file its only source of the token. */
32 export const AGENT_UNIT = `[Unit]
33 Description=forge game agent
34 After=network-online.target docker.service
35 Wants=network-online.target docker.service
36 [Service]
37 EnvironmentFile=${GAME_DIR}/agent.env
38 ExecStart=/bin/bash ${GAME_DIR}/agent.sh
39 Restart=always
40 RestartSec=5
41 [Install]
42 WantedBy=multi-user.target
43 `;
44
45 /** The cloud-config for a game box whose volume is mounted at `dataDir`. */
46 export function gameBootConfig(g: GameBoot, dataDir: string): string {
47 const url = new URL(g.forgeUrl);
48 if (url.protocol !== "https:" && url.hostname !== "127.0.0.1" && url.hostname !== "localhost") throw new Error("a game box answers to its forge over https");
49 if (!TOKEN.test(g.token)) throw new Error("that is not a game box token");
50 if (!/^\/[A-Za-z0-9/_.-]+$/.test(dataDir)) throw new Error("the volume's mount is not a plain path");
51 const env = `FORGE_URL=${url.origin}\nFORGE_GAME_TOKEN=${g.token}\n`;
52 const daemon = JSON.stringify({ "data-root": `${dataDir}/docker`, "log-driver": "local" });
53 return `#cloud-config
54 ssh_pwauth: false
55 disable_root: true
56 package_update: true
57 package_upgrade: true
58 packages:
59 - ufw
60 - curl
61 - jq
62 - ca-certificates
63 - unattended-upgrades
64 - docker.io
65 - docker-compose-v2
66 write_files:
67 - path: ${GAME_DIR}/agent.env
68 permissions: "0600"
69 content: ${JSON.stringify(env)}
70 - path: ${GAME_DIR}/agent.sh
71 permissions: "0755"
72 content: ${JSON.stringify(AGENT_SH)}
73 - path: /etc/systemd/system/forge-game-agent.service
74 permissions: "0644"
75 content: ${JSON.stringify(AGENT_UNIT)}
76 - path: /etc/docker/daemon.json
77 permissions: "0644"
78 content: ${JSON.stringify(daemon + "\n")}
79 ${hardenFiles()}
80 runcmd:
81 - ufw default deny incoming
82 - ufw default allow outgoing
83 - ufw allow ${GAME_PORT}/tcp
84 - ufw --force enable
85 - fallocate -l ${SWAP_GIB}G /swapfile && chmod 600 /swapfile && mkswap /swapfile && swapon /swapfile && echo '/swapfile none swap sw 0 0' >> /etc/fstab
86 - mkdir -p ${dataDir}/docker
87 - systemctl restart docker
88 - systemctl daemon-reload
89 - systemctl enable --now forge-game-agent.service
90 `;
91 }
src/games/compose.ts added +192
@@ -0,0 +1,192 @@
1 /**
2 * A game box's compose file, in its repository (forge games): read at the box's branch HEAD, and
3 * changed only by a commit (an env key, a plugin), so the crew can propose changes and a merge
4 * redeploys. Edits are textual, under the service's `environment:` block, so the rest of the file
5 * and its comments stay as the owner wrote them.
6 */
7
8 import type { App } from "../app.ts";
9 import { commitToBranch } from "../actions/repos.ts";
10 import { canWrite, getRepo } from "../core/repos.ts";
11 import type { User } from "../core/users.ts";
12 import { runGit } from "../git/env.ts";
13 import { repoDir } from "../git/repos.ts";
14 import type { GameBox } from "./store.ts";
15
16 export interface Compose {
17 readonly sha: string;
18 readonly text: string;
19 }
20
21 /** The compose file at the box's branch HEAD, with that commit's sha; undefined when missing. */
22 export async function readCompose(app: App, box: GameBox): Promise<Compose | undefined> {
23 const [owner = "", name = ""] = box.repo.split("/");
24 const repo = getRepo(app.db, owner, name);
25 if (repo === undefined) return undefined;
26 const cwd = repoDir(app.reposRoot, repo.ownerName, repo.name);
27 const sha = await runGit(["rev-parse", "--verify", `refs/heads/${box.branch}`], { cwd });
28 if (!sha.ok) return undefined;
29 const text = await runGit(["show", `${sha.value.trim()}:${box.path}`], { cwd });
30 return text.ok ? { sha: sha.value.trim(), text: text.value } : undefined;
31 }
32
33 /** The services the compose file names. */
34 export function composeServices(text: string): string[] {
35 try {
36 const doc = Bun.YAML.parse(text) as { services?: Record<string, unknown> } | null;
37 return Object.keys(doc?.services ?? {});
38 } catch {
39 return [];
40 }
41 }
42
43 /** A service's environment as the compose file says it (map or list form). */
44 export function serviceEnv(text: string, service: string): Record<string, string> {
45 try {
46 const doc = Bun.YAML.parse(text) as { services?: Record<string, { environment?: unknown }> } | null;
47 const env = doc?.services?.[service]?.environment;
48 if (Array.isArray(env))
49 return Object.fromEntries(
50 env.filter((e): e is string => typeof e === "string").map((e) => [e.split("=")[0]!, e.slice(e.indexOf("=") + 1)]),
51 );
52 if (env !== null && typeof env === "object")
53 return Object.fromEntries(Object.entries(env).map(([k, v]) => [k, v === null ? "" : String(v)]));
54 } catch {}
55 return {};
56 }
57
58 const KEY = /^[A-Za-z_][A-Za-z0-9_]*$/;
59 const quote = (v: string): string => JSON.stringify(v);
60
61 /**
62 * The compose text with `values` set under `service`'s environment (a value of null removes the
63 * key). The block keeps its own form: `KEY: value` lines, or `- KEY=value` lines.
64 */
65 export function setServiceEnv(text: string, service: string, values: Record<string, string | null>): string {
66 for (const k of Object.keys(values)) if (!KEY.test(k)) throw new Error(`${k} is not an environment variable name`);
67 const lines = text.split("\n");
68 const indentOf = (l: string): number => l.length - l.trimStart().length;
69 const svc = lines.findIndex(
70 (l, i) => new RegExp(`^\\s+${service.replace(/[.]/g, "\\.")}:\\s*$`).test(l) && lines.slice(0, i).some((p) => /^services:\s*$/.test(p)),
71 );
72 if (svc < 0) throw new Error(`${service} is not a service in this compose file`);
73 const svcIndent = indentOf(lines[svc]!);
74 let end = lines.length;
75 for (let i = svc + 1; i < lines.length; i++)
76 if (lines[i]!.trim() !== "" && !lines[i]!.trimStart().startsWith("#") && indentOf(lines[i]!) <= svcIndent) {
77 end = i;
78 break;
79 }
80 let env = -1;
81 for (let i = svc + 1; i < end; i++)
82 if (/^\s+environment:\s*$/.test(lines[i]!)) {
83 env = i;
84 break;
85 }
86 if (env < 0) {
87 const child = svcIndent + 2;
88 const block = Object.entries(values)
89 .filter(([, v]) => v !== null)
90 .map(([k, v]) => `${" ".repeat(child + 2)}${k}: ${quote(v!)}`);
91 lines.splice(svc + 1, 0, `${" ".repeat(child)}environment:`, ...block);
92 return lines.join("\n");
93 }
94 const envIndent = indentOf(lines[env]!);
95 let envEnd = end;
96 for (let i = env + 1; i < end; i++)
97 if (lines[i]!.trim() !== "" && !lines[i]!.trimStart().startsWith("#") && indentOf(lines[i]!) <= envIndent) {
98 envEnd = i;
99 break;
100 }
101 const body = lines.slice(env + 1, envEnd);
102 const listForm = body.some((l) => l.trimStart().startsWith("- "));
103 const itemIndent = body.find((l) => l.trim() !== "")?.length !== undefined ? indentOf(body.find((l) => l.trim() !== "")!) : envIndent + 2;
104 const keyOf = (l: string): string | undefined => {
105 const t = l.trimStart();
106 if (listForm) return t.startsWith("- ") ? t.slice(2).replace(/^["']/, "").split("=")[0] : undefined;
107 return /^[A-Za-z_][A-Za-z0-9_]*:/.test(t) ? t.split(":")[0] : undefined;
108 };
109 const render = (k: string, v: string): string =>
110 listForm ? `${" ".repeat(itemIndent)}- ${quote(`${k}=${v}`)}` : `${" ".repeat(itemIndent)}${k}: ${quote(v)}`;
111 const left = { ...values };
112 const next: string[] = [];
113 for (const l of body) {
114 const k = keyOf(l);
115 if (k !== undefined && k in left) {
116 const v = left[k];
117 delete left[k];
118 if (v !== null && v !== undefined) next.push(render(k, v));
119 } else next.push(l);
120 }
121 for (const [k, v] of Object.entries(left)) if (v !== null) next.push(render(k, v));
122 lines.splice(env + 1, envEnd - env - 1, ...next);
123 return lines.join("\n");
124 }
125
126 /** A key that names a secret: it belongs in the sealed `.env` the forge writes, never in the repository. */
127 export const SECRET_KEY = /PASSWORD|SECRET|TOKEN|KEY/i;
128
129 /** Commit `values` into the service's environment: "games: <service> env: <keys>". */
130 export async function commitServiceEnv(
131 app: App,
132 user: User,
133 box: GameBox,
134 service: string,
135 values: Record<string, string | null>,
136 ): Promise<{ ok: true; sha: string } | { ok: false; error: string }> {
137 const secret = Object.keys(values).find((k) => SECRET_KEY.test(k));
138 if (secret !== undefined)
139 return { ok: false, error: `${secret} looks like a secret, and the repository is no place for one: the forge seals secrets and writes them to the box's .env itself.` };
140 const compose = await readCompose(app, box);
141 if (compose === undefined) return { ok: false, error: `No ${box.path} on ${box.repo}@${box.branch}.` };
142 let text: string;
143 try {
144 text = setServiceEnv(compose.text, service, values);
145 } catch (e) {
146 return { ok: false, error: e instanceof Error ? e.message : String(e) };
147 }
148 const [owner = "", name = ""] = box.repo.split("/");
149 const repo = getRepo(app.db, owner, name);
150 if (repo === undefined || !canWrite(app.db, repo, user))
151 return { ok: false, error: `Changing env needs write access to ${box.repo}, which this account does not have.` };
152 const keys = Object.keys(values).sort().join(", ");
153 const done = await commitToBranch(app, user, repo, {
154 branch: box.branch,
155 message: `games: ${service} env: ${keys}`,
156 files: [{ path: box.path, content: text }],
157 expectTip: compose.sha,
158 });
159 return done.ok
160 ? { ok: true, sha: done.value.commitOid }
161 : { ok: false, error: `The commit was refused: ${JSON.stringify(done.error).slice(0, 200)}` };
162 }
163
164 /** PLUGINS (comma or newline separated URLs) and MODRINTH_PROJECTS of a service. */
165 export function pluginsOf(text: string, service: string): { plugins: string[]; modrinth: string[] } {
166 const env = serviceEnv(text, service);
167 const split = (v: string | undefined): string[] => (v ?? "").split(/[\s,]+/).filter(Boolean);
168 return { plugins: split(env["PLUGINS"]), modrinth: split(env["MODRINTH_PROJECTS"]) };
169 }
170
171 /** Add a plugin URL or a Modrinth slug to a service, by commit. */
172 export async function addPlugin(
173 app: App,
174 user: User,
175 box: GameBox,
176 service: string,
177 add: { url?: string; modrinth?: string },
178 ): Promise<{ ok: true; sha: string } | { ok: false; error: string }> {
179 const compose = await readCompose(app, box);
180 if (compose === undefined) return { ok: false, error: `No ${box.path} on ${box.repo}@${box.branch}.` };
181 const now = pluginsOf(compose.text, service);
182 if (add.modrinth !== undefined) {
183 if (!/^[a-z0-9][a-z0-9_.:-]{0,99}$/i.test(add.modrinth)) return { ok: false, error: "A Modrinth project is its slug, like luckperms." };
184 if (now.modrinth.includes(add.modrinth)) return { ok: false, error: `${add.modrinth} is already there.` };
185 return commitServiceEnv(app, user, box, service, { MODRINTH_PROJECTS: [...now.modrinth, add.modrinth].join(",") });
186 }
187 if (add.url !== undefined) {
188 if (now.plugins.includes(add.url)) return { ok: false, error: "That plugin is already there." };
189 return commitServiceEnv(app, user, box, service, { PLUGINS: [...now.plugins, add.url].join(",") });
190 }
191 return { ok: false, error: "Name a plugin." };
192 }
src/games/notify.ts added +30
@@ -0,0 +1,30 @@
1 /**
2 * Who is watching a game box (forge games): a console's stream subscribes here and is told after
3 * each sync of that box, so it reads the new lines then and never polls. Per forge (#12569).
4 */
5
6 import type { App } from "../app.ts";
7
8 const watchers = new WeakMap<App, Map<string, Set<() => void>>>();
9
10 /** Call `told` after each sync of `boxId`; the returned function stops it. */
11 export function onSync(app: App, boxId: string, told: () => void): () => void {
12 const byBox = watchers.get(app) ?? new Map<string, Set<() => void>>();
13 watchers.set(app, byBox);
14 const set = byBox.get(boxId) ?? new Set<() => void>();
15 byBox.set(boxId, set);
16 set.add(told);
17 return () => {
18 set.delete(told);
19 if (set.size === 0) byBox.delete(boxId);
20 };
21 }
22
23 /** A box synced: tell its watchers. */
24 export function synced(app: App, boxId: string): void {
25 for (const told of [...(watchers.get(app)?.get(boxId) ?? [])]) {
26 try {
27 told();
28 } catch {}
29 }
30 }
src/games/store.ts added +459
@@ -0,0 +1,459 @@
1 /**
2 * Game boxes (forge games): a VM on the owner's cloud running Docker and forge-game-agent, which
3 * pulls every 5 s (`POST /api/v1/games/agent/sync`, its token hashed here like a runner's). The
4 * desired state is a compose file in a forge repository (repo, branch, path on the box); the forge
5 * keeps each service's status, a bounded log tail, a command queue handed out once, the grants
6 * and uploaded plugin jars. Secrets (the Velocity forwarding secret, an RCON password a service)
7 * are generated once, sealed like every other secret, and only ever reach the box in `env`.
8 */
9
10 import type { Database } from "bun:sqlite";
11 import { createHmac, randomBytes, timingSafeEqual } from "node:crypto";
12 import { rm } from "node:fs/promises";
13 import type { App } from "../app.ts";
14 import { resolveSecrets, setSecret } from "../core/secret_store.ts";
15 import type { User } from "../core/users.ts";
16 import { sha256 } from "../kernel/hash.ts";
17 import { id as newId } from "../kernel/id.ts";
18
19 export const BOX_NAME = /^[a-z][a-z0-9-]{0,39}$/;
20 export const SERVICE_NAME = /^[a-z0-9][a-z0-9_.-]{0,63}$/;
21 /** The most log lines kept a service; the oldest go first. */
22 export const LOG_KEEP = 2_000;
23 const LINES_A_SYNC = 200;
24 const OUTPUT_MAX = 4_096;
25 export const COMMAND_KINDS = ["rcon", "restart", "stop", "start", "recreate", "pull"] as const;
26 export type CommandKind = (typeof COMMAND_KINDS)[number];
27 export type Role = "owner" | "operator" | "viewer";
28 const RANK: Record<Role, number> = { viewer: 1, operator: 2, owner: 3 };
29
30 export interface GameBox {
31 readonly id: string;
32 readonly name: string;
33 readonly repo: string;
34 readonly branch: string;
35 readonly path: string;
36 readonly pinnedId: string;
37 readonly place: string;
38 readonly monthlyCents: number;
39 readonly host: Record<string, number>;
40 readonly composeSha: string;
41 readonly seenAt: string;
42 readonly createdAt: string;
43 }
44
45 export interface GameService {
46 readonly name: string;
47 readonly state: string;
48 readonly health: string;
49 readonly startedAt: string;
50 readonly cpuPct: number;
51 readonly memMiB: number;
52 readonly seenAt: string;
53 }
54
55 interface BoxRow {
56 id: string;
57 name: string;
58 repo: string;
59 branch: string;
60 path: string;
61 pinned_id: string;
62 place: string;
63 monthly_cents: number;
64 host_json: string;
65 compose_sha: string;
66 seen_at: string;
67 created_at: string;
68 }
69 const toBox = (r: BoxRow): GameBox => {
70 let host: Record<string, number> = {};
71 try {
72 host = JSON.parse(r.host_json) as Record<string, number>;
73 } catch {}
74 return {
75 id: r.id,
76 name: r.name,
77 repo: r.repo,
78 branch: r.branch,
79 path: r.path,
80 pinnedId: r.pinned_id,
81 place: r.place,
82 monthlyCents: r.monthly_cents,
83 host,
84 composeSha: r.compose_sha,
85 seenAt: r.seen_at,
86 createdAt: r.created_at,
87 };
88 };
89
90 /** A new box: its token is returned once and only its hash is kept. */
91 export function createGameBox(
92 db: Database,
93 o: { name: string; repo?: string; branch?: string; path?: string; pinnedId?: string; place?: string; monthlyCents?: number },
94 ): { id: string; token: string } {
95 if (!BOX_NAME.test(o.name)) throw new Error("A box name is lowercase letters, digits and dashes, starting with a letter.");
96 const id = newId();
97 const token = `fgb_${randomBytes(32).toString("base64url")}`;
98 db.query(
99 "INSERT INTO game_box (id, name, token_hash, repo, branch, path, pinned_id, place, monthly_cents, created_at) VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7, ?8, ?9, ?10)",
100 ).run(
101 id,
102 o.name,
103 sha256(token),
104 o.repo ?? "trevato/mc-network",
105 o.branch ?? "main",
106 o.path ?? "docker-compose.yml",
107 o.pinnedId ?? "",
108 o.place ?? "",
109 o.monthlyCents ?? 0,
110 new Date().toISOString(),
111 );
112 return { id, token };
113 }
114
115 /** The machine made for a box after its row (the plan tray's deploy). */
116 export function setGameBoxMachine(db: Database, id: string, m: { pinnedId: string; place: string; monthlyCents: number }): void {
117 db.query("UPDATE game_box SET pinned_id = ?2, place = ?3, monthly_cents = ?4 WHERE id = ?1").run(id, m.pinnedId, m.place, m.monthlyCents);
118 }
119
120 /** A new token for a box (each machine's boot config carries its own); the old one stops at once. */
121 export function rotateGameBoxToken(db: Database, id: string): string {
122 const token = `fgb_${randomBytes(32).toString("base64url")}`;
123 db.query("UPDATE game_box SET token_hash = ?2 WHERE id = ?1").run(id, sha256(token));
124 return token;
125 }
126
127 export const listBoxes = (db: Database): GameBox[] => db.query<BoxRow, []>("SELECT * FROM game_box ORDER BY name").all().map(toBox);
128 export const boxNamed = (db: Database, name: string): GameBox | undefined => {
129 const r = db.query<BoxRow, [string]>("SELECT * FROM game_box WHERE name = ?1").get(name);
130 return r === null ? undefined : toBox(r);
131 };
132 export function boxByToken(db: Database, token: string): GameBox | undefined {
133 if (!token.startsWith("fgb_")) return undefined;
134 const r = db
135 .query<BoxRow, [string]>(
136 "SELECT b.* FROM game_box b WHERE b.token_hash = ?1 AND NOT EXISTS (SELECT 1 FROM pinned_forge p WHERE p.state = 'retired' AND (p.id = b.pinned_id OR (b.pinned_id = '' AND p.name = b.name)))",
137 )
138 .get(sha256(token));
139 return r === null ? undefined : toBox(r);
140 }
141
142 export const servicesOf = (db: Database, boxId: string): GameService[] =>
143 db
144 .query<
145 { name: string; state: string; health: string; started_at: string; cpu_pct: number; mem_mib: number; seen_at: string },
146 [string]
147 >("SELECT name, state, health, started_at, cpu_pct, mem_mib, seen_at FROM game_service WHERE box_id = ?1 ORDER BY name")
148 .all(boxId)
149 .map((r) => ({
150 name: r.name,
151 state: r.state,
152 health: r.health,
153 startedAt: r.started_at,
154 cpuPct: r.cpu_pct,
155 memMiB: r.mem_mib,
156 seenAt: r.seen_at,
157 }));
158
159 /** The newest `limit` log lines of a service, oldest first, with the id of the last. */
160 export function logsOf(db: Database, boxId: string, service: string, limit = 200, after = 0): { lines: string[]; last: number } {
161 const rows = db
162 .query<
163 { id: number; line: string },
164 [string, string, number, number]
165 >("SELECT id, line FROM game_log WHERE box_id = ?1 AND service = ?2 AND id > ?3 ORDER BY id DESC LIMIT ?4")
166 .all(boxId, service, after, limit)
167 .reverse();
168 return { lines: rows.map((r) => r.line), last: rows.at(-1)?.id ?? after };
169 }
170
171 // ---- grants -----------------------------------------------------------------------------------
172
173 /** What `user` may do on a box, or on one service of it: forge admins own every box. */
174 export function roleOn(db: Database, user: User | undefined, boxId: string, service = ""): Role | undefined {
175 if (user === undefined) return undefined;
176 if (user.isAdmin) return "owner";
177 const rows = db
178 .query<
179 { role: Role },
180 [string, string, string]
181 >("SELECT role FROM game_grant WHERE box_id = ?1 AND user_id = ?2 AND (service = '' OR service = ?3)")
182 .all(boxId, user.id, service);
183 let best: Role | undefined;
184 for (const r of rows) if (RANK[r.role] !== undefined && (best === undefined || RANK[r.role] > RANK[best])) best = r.role;
185 return best;
186 }
187 export const mayDo = (role: Role | undefined, need: Role): boolean => role !== undefined && RANK[role] >= RANK[need];
188
189 /** Whether `user` sees a box at all: any grant on it (box-wide or one service), or forge admin. */
190 export function seesBox(db: Database, user: User | undefined, boxId: string): boolean {
191 if (user === undefined) return false;
192 if (user.isAdmin) return true;
193 return db.query("SELECT 1 FROM game_grant WHERE box_id = ?1 AND user_id = ?2").get(boxId, user.id) !== null;
194 }
195
196 export function grant(db: Database, boxId: string, userId: string, role: Role | "none", service = ""): void {
197 if (role === "none") db.query("DELETE FROM game_grant WHERE box_id = ?1 AND user_id = ?2 AND service = ?3").run(boxId, userId, service);
198 else
199 db.query(
200 "INSERT INTO game_grant (box_id, user_id, role, service) VALUES (?1, ?2, ?3, ?4) ON CONFLICT (box_id, user_id, service) DO UPDATE SET role = excluded.role",
201 ).run(boxId, userId, role, service);
202 }
203
204 export const grantsOf = (db: Database, boxId: string): { userId: string; username: string; role: Role; service: string }[] =>
205 db
206 .query<{ user_id: string; username: string; role: Role; service: string }, [string]>(
207 "SELECT g.user_id, u.username, g.role, g.service FROM game_grant g JOIN user u ON u.id = g.user_id WHERE g.box_id = ?1 ORDER BY u.username, g.service",
208 )
209 .all(boxId)
210 .map((r) => ({ userId: r.user_id, username: r.username, role: r.role, service: r.service }));
211
212 // ---- commands ---------------------------------------------------------------------------------
213
214 export function queueCommand(db: Database, boxId: string, service: string, kind: CommandKind, text: string, by: string): string {
215 const id = newId();
216 db.query("INSERT INTO game_command (id, box_id, service, kind, text, by, created_at) VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7)").run(
217 id,
218 boxId,
219 service,
220 kind,
221 text.slice(0, 1_000),
222 by,
223 new Date().toISOString(),
224 );
225 return id;
226 }
227
228 export interface CommandState {
229 readonly id: string;
230 readonly kind: string;
231 readonly service: string;
232 readonly text: string;
233 readonly handed: boolean;
234 readonly done: boolean;
235 readonly ok: boolean | null;
236 readonly output: string;
237 }
238 export function commandOf(db: Database, id: string): CommandState | undefined {
239 const r = db
240 .query<
241 { id: string; kind: string; service: string; text: string; handed_at: string; done_at: string; ok: number | null; output: string },
242 [string]
243 >("SELECT id, kind, service, text, handed_at, done_at, ok, output FROM game_command WHERE id = ?1")
244 .get(id);
245 return r === null
246 ? undefined
247 : {
248 id: r.id,
249 kind: r.kind,
250 service: r.service,
251 text: r.text,
252 handed: r.handed_at !== "",
253 done: r.done_at !== "",
254 ok: r.ok === null ? null : r.ok === 1,
255 output: r.output,
256 };
257 }
258
259 export const recentCommands = (db: Database, boxId: string, service: string, limit = 10): CommandState[] =>
260 db
261 .query<{ id: string }, [string, string, number]>(
262 "SELECT id FROM game_command WHERE box_id = ?1 AND service = ?2 ORDER BY created_at DESC LIMIT ?3",
263 )
264 .all(boxId, service, limit)
265 .map((r) => commandOf(db, r.id)!);
266
267 // ---- secrets: the env files the box gets -----------------------------------------------------
268
269 const secretKey = (s: string): string => s.toUpperCase().replace(/[^A-Z0-9]+/g, "_");
270 export const forwardingSecretName = (box: Pick<GameBox, "name">): string => `GAME_${secretKey(box.name)}_FORWARDING`;
271 export const envSecretName = (box: Pick<GameBox, "name">, key: string): string => `GAME_${secretKey(box.name)}_${key}`;
272 export const JAR_KEY = "GAME_JAR_SIGNING_KEY";
273
274 /** A sealed secret's value, made (32 random bytes, hex: alphanumerics only) and sealed the first time. */
275 function sealedOnce(app: App, name: string, run: string): string {
276 const have = resolveSecrets(app.db, app.config.dataDir, app.bus, [name], { run })[name];
277 if (have !== undefined) return have;
278 const value = randomBytes(32).toString("hex");
279 const set = setSecret(app.db, app.config.dataDir, "forge", "", name, value);
280 if (!set.ok) throw new Error(`could not seal ${name}: ${set.error}`);
281 return value;
282 }
283
284 /**
285 * The RCON keys of a compose file: each `${RCON_…}` it interpolates and an RCON_<SERVICE> for each
286 * of its services, so a server added later gets its password.
287 */
288 export const rconKeys = (compose: string, services: readonly string[] = []): string[] =>
289 [...new Set([...[...compose.matchAll(/\$\{(RCON_[A-Z0-9_]+)/g)].map((m) => m[1]!), ...services.map((s) => `RCON_${secretKey(s)}`)])].sort();
290
291 /**
292 * The one env file written beside compose.yml, `.env`, which compose interpolates from:
293 * FORWARDING_SECRET (Velocity's modern forwarding) and each RCON_<SERVICE> the compose names. Each
294 * is generated once a box, sealed, and never committed.
295 */
296 export function envFiles(app: App, box: GameBox, compose: string, services: readonly string[] = []): Record<string, string> {
297 const run = `games:${box.name}`;
298 const lines = [`FORWARDING_SECRET=${sealedOnce(app, forwardingSecretName(box), run)}`];
299 for (const key of rconKeys(compose, services)) lines.push(`${key}=${sealedOnce(app, envSecretName(box, key), run)}`);
300 return { ".env": `${lines.join("\n")}\n` };
301 }
302
303 // ---- plugin jars: kept in the forge, fetched by the box through a signed, expiring URL -------
304
305 /** How long a jar URL handed to a box stays good. */
306 export const JAR_URL_MS = 6 * 3_600_000;
307
308 export function jarPath(app: App, jarId: string): string {
309 return `${app.config.dataDir}/games/jars/${jarId}.jar`;
310 }
311
312 /** What one box keeps: jars, and their bytes together; one jar is at most `JAR_MAX_BYTES`. */
313 export const JAR_MAX_BYTES = 64 * 1024 * 1024;
314 export const JARS_PER_BOX = 20;
315 export const JAR_BYTES_PER_BOX = 256 * 1024 * 1024;
316
317 /**
318 * Keep an uploaded plugin jar: a `.jar` name, a zip inside (`PK\x03\x04`), and room in the box's
319 * bounds. The file is written straight from the upload and hashed as a stream, so it is never
320 * held twice.
321 */
322 export async function storeJar(app: App, boxId: string, file: Blob, name: string): Promise<{ ok: true; id: string; name: string } | { ok: false; error: string }> {
323 if (!/\.jar$/i.test(name)) return { ok: false, error: "A plugin is a .jar file." };
324 if (file.size > JAR_MAX_BYTES) return { ok: false, error: "A jar is at most 64 MiB." };
325 const head = new Uint8Array(await file.slice(0, 4).arrayBuffer());
326 if (head[0] !== 0x50 || head[1] !== 0x4b || head[2] !== 0x03 || head[3] !== 0x04) return { ok: false, error: "That file is not a jar (a jar is a zip)." };
327 const kept = app.db.query<{ n: number; bytes: number | null }, [string]>("SELECT COUNT(*) AS n, SUM(bytes) AS bytes FROM game_jar WHERE box_id = ?1").get(boxId)!;
328 if (kept.n >= JARS_PER_BOX) return { ok: false, error: `This box keeps ${JARS_PER_BOX} jars already.` };
329 if ((kept.bytes ?? 0) + file.size > JAR_BYTES_PER_BOX) return { ok: false, error: "This box's jars would pass 256 MiB." };
330 const id = newId();
331 const clean = name.replace(/[^A-Za-z0-9._-]+/g, "-").replace(/^-+/, "").slice(0, 120);
332 const hash = new Bun.CryptoHasher("sha256");
333 for await (const chunk of file.stream()) hash.update(chunk);
334 await Bun.write(jarPath(app, id), file);
335 app.db
336 .query("INSERT INTO game_jar (id, box_id, name, sha256, bytes, created_at) VALUES (?1, ?2, ?3, ?4, ?5, ?6)")
337 .run(id, boxId, clean, hash.digest("hex"), file.size, new Date().toISOString());
338 return { ok: true, id, name: clean };
339 }
340
341 /** Forget a jar and its file: an upload whose commit was refused. */
342 export async function dropJar(app: App, id: string): Promise<void> {
343 app.db.query("DELETE FROM game_jar WHERE id = ?1").run(id);
344 await rm(jarPath(app, id), { force: true });
345 }
346
347 export const jarOf = (db: Database, id: string): { id: string; boxId: string; name: string } | undefined => {
348 const r = db.query<{ id: string; box_id: string; name: string }, [string]>("SELECT id, box_id, name FROM game_jar WHERE id = ?1").get(id);
349 return r === null ? undefined : { id: r.id, boxId: r.box_id, name: r.name };
350 };
351
352 const signature = (key: string, jarId: string, expires: number): string =>
353 createHmac("sha256", key).update(`${jarId}.${expires}`).digest("base64url");
354
355 /** The path a jar is served at, unsigned: what the repo's PLUGINS keeps. */
356 export const jarHref = (jar: { id: string; name: string }): string => `/games/jar/${jar.id}/${jar.name}`;
357
358 /** The same path with a signature good for `JAR_URL_MS`. */
359 export function signedJarHref(app: App, jar: { id: string; name: string }, now = Date.now()): string {
360 const expires = now + JAR_URL_MS;
361 return `${jarHref(jar)}?e=${expires}&s=${signature(sealedOnce(app, JAR_KEY, "games:jars"), jar.id, expires)}`;
362 }
363
364 export function jarSignatureGood(app: App, jarId: string, e: string, s: string, now = Date.now()): boolean {
365 const expires = Number(e);
366 if (!Number.isFinite(expires) || expires < now || expires > now + JAR_URL_MS + 60_000) return false;
367 const want = Buffer.from(signature(sealedOnce(app, JAR_KEY, "games:jars"), jarId, expires));
368 const got = Buffer.from(s);
369 return want.length === got.length && timingSafeEqual(want, got);
370 }
371
372 /** Compose text with each forge jar URL signed for the box that will fetch it. */
373 export function signJarUrls(app: App, box: Pick<GameBox, "id">, compose: string, origin: string): string {
374 return compose.replace(
375 /(https?:\/\/[^\s"',]*)?\/games\/jar\/([0-9a-z]+)\/([A-Za-z0-9._-]+\.jar)(\?[^\s"',]*)?/g,
376 (whole, _host, id: string, name: string) => {
377 // Only this box's own jars: another box's id in a compose file stays unsigned.
378 if (jarOf(app.db, id)?.boxId !== box.id) return whole;
379 return `${origin}${signedJarHref(app, { id, name })}`;
380 },
381 );
382 }
383
384 // ---- the sync ---------------------------------------------------------------------------------
385
386 export interface SyncBody {
387 readonly composeSha?: string;
388 readonly services?: readonly {
389 name?: unknown;
390 state?: unknown;
391 health?: unknown;
392 startedAt?: unknown;
393 cpuPct?: unknown;
394 memMiB?: unknown;
395 }[];
396 readonly logs?: Record<string, unknown>;
397 readonly results?: readonly { id?: unknown; ok?: unknown; output?: unknown }[];
398 readonly host?: Record<string, unknown>;
399 }
400
401 const str = (v: unknown, max = 200): string => (typeof v === "string" ? v.slice(0, max) : "");
402 const num = (v: unknown): number => (typeof v === "number" && Number.isFinite(v) ? v : 0);
403
404 /** One sync: store what the box says, hand out what is queued (once), say what to run. */
405 export function recordSync(
406 db: Database,
407 box: GameBox,
408 body: SyncBody,
409 now = new Date(),
410 ): { id: string; kind: string; service: string; text: string }[] {
411 const at = now.toISOString();
412 db.transaction(() => {
413 const host: Record<string, number> = {};
414 for (const [k, v] of Object.entries(body.host ?? {}))
415 if (typeof v === "number" && Number.isFinite(v) && Object.keys(host).length < 16) host[k.slice(0, 40)] = v;
416 db.query("UPDATE game_box SET seen_at = ?2, host_json = ?3, compose_sha = ?4 WHERE id = ?1").run(
417 box.id,
418 at,
419 JSON.stringify(host),
420 str(body.composeSha, 80),
421 );
422 for (const s of (body.services ?? []).slice(0, 64)) {
423 const name = str(s.name, 64);
424 if (!SERVICE_NAME.test(name)) continue;
425 db.query(
426 `INSERT INTO game_service (box_id, name, state, health, started_at, cpu_pct, mem_mib, seen_at) VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7, ?8)
427 ON CONFLICT (box_id, name) DO UPDATE SET state = excluded.state, health = excluded.health, started_at = excluded.started_at, cpu_pct = excluded.cpu_pct, mem_mib = excluded.mem_mib, seen_at = excluded.seen_at`,
428 ).run(box.id, name, str(s.state, 20), str(s.health, 20), str(s.startedAt, 40), num(s.cpuPct), num(s.memMiB), at);
429 }
430 for (const [service, lines] of Object.entries(body.logs ?? {}).slice(0, 64)) {
431 if (!SERVICE_NAME.test(service) || !Array.isArray(lines)) continue;
432 const insert = db.query("INSERT INTO game_log (box_id, service, line, at) VALUES (?1, ?2, ?3, ?4)");
433 for (const line of lines.slice(-LINES_A_SYNC)) if (typeof line === "string") insert.run(box.id, service, line.slice(0, 2_000), at);
434 db.query(
435 "DELETE FROM game_log WHERE box_id = ?1 AND service = ?2 AND id <= (SELECT id FROM game_log WHERE box_id = ?1 AND service = ?2 ORDER BY id DESC LIMIT 1 OFFSET ?3)",
436 ).run(box.id, service, LOG_KEEP);
437 }
438 for (const r of (body.results ?? []).slice(0, 64)) {
439 const id = str(r.id, 64);
440 if (id === "") continue;
441 db.query("UPDATE game_command SET done_at = ?3, ok = ?4, output = ?5 WHERE id = ?1 AND box_id = ?2 AND done_at = ''").run(
442 id,
443 box.id,
444 at,
445 r.ok === true ? 1 : 0,
446 str(r.output, OUTPUT_MAX),
447 );
448 }
449 })();
450 // Handed out once: a command leaves the queue the moment it is in a reply.
451 const due = db
452 .query<
453 { id: string; kind: string; service: string; text: string },
454 [string]
455 >("SELECT id, kind, service, text FROM game_command WHERE box_id = ?1 AND handed_at = '' ORDER BY created_at LIMIT 32")
456 .all(box.id);
457 for (const c of due) db.query("UPDATE game_command SET handed_at = ?2 WHERE id = ?1").run(c.id, at);
458 return due;
459 }
src/generated/marks.ts +161 −157
@@ -38,163 +38,165 @@ import k33 from "../http/marks/api-v1-forge-templates.json";
3838 import k34 from "../http/marks/api-v1-forge.json";
3939 import k35 from "../http/marks/api-v1-forges.json";
4040 import k36 from "../http/marks/api-v1-front.json";
41 import k37 from "../http/marks/api-v1-health.json";
42 import k38 from "../http/marks/api-v1-heartbeat.json";
43 import k39 from "../http/marks/api-v1-here.json";
44 import k40 from "../http/marks/api-v1-keeper.json";
45 import k41 from "../http/marks/api-v1-maintenance.json";
46 import k42 from "../http/marks/api-v1-map.json";
47 import k43 from "../http/marks/api-v1-migrate.json";
48 import k44 from "../http/marks/api-v1-offers.json";
49 import k45 from "../http/marks/api-v1-openapi.json.json";
50 import k46 from "../http/marks/api-v1-orgs.json";
51 import k47 from "../http/marks/api-v1-packs.json";
52 import k48 from "../http/marks/api-v1-passport.json";
53 import k49 from "../http/marks/api-v1-places.json";
54 import k50 from "../http/marks/api-v1-plans.json";
55 import k51 from "../http/marks/api-v1-proof.json";
56 import k52 from "../http/marks/api-v1-reach.json";
57 import k53 from "../http/marks/api-v1-release.json";
58 import k54 from "../http/marks/api-v1-releases.json";
59 import k55 from "../http/marks/api-v1-repos.json";
60 import k56 from "../http/marks/api-v1-returns.json";
61 import k57 from "../http/marks/api-v1-runner.json";
62 import k58 from "../http/marks/api-v1-search.json";
63 import k59 from "../http/marks/api-v1-secrets.json";
64 import k60 from "../http/marks/api-v1-sessions.json";
65 import k61 from "../http/marks/api-v1-share.json";
66 import k62 from "../http/marks/api-v1-slash.json";
67 import k63 from "../http/marks/api-v1-start.json";
68 import k64 from "../http/marks/api-v1-status.json";
69 import k65 from "../http/marks/api-v1-telemetry.json";
70 import k66 from "../http/marks/api-v1-templates.json";
71 import k67 from "../http/marks/api-v1-thoughts.json";
72 import k68 from "../http/marks/api-v1-timers.json";
73 import k69 from "../http/marks/api-v1-tokens.json";
74 import k70 from "../http/marks/api-v1-usage.json";
75 import k71 from "../http/marks/api-v1-user.json";
76 import k72 from "../http/marks/api-v1-users.json";
77 import k73 from "../http/marks/api-v1-version.json";
78 import k74 from "../http/marks/api-v1.json";
79 import k75 from "../http/marks/api.json";
80 import k76 from "../http/marks/apple-touch-icon-precomposed.png.json";
81 import k77 from "../http/marks/apple-touch-icon.png.json";
82 import k78 from "../http/marks/apps.json";
83 import k79 from "../http/marks/asked.json";
84 import k80 from "../http/marks/asks.json";
85 import k81 from "../http/marks/assets.json";
86 import k82 from "../http/marks/audit.csv.json";
87 import k83 from "../http/marks/audit.json";
88 import k84 from "../http/marks/big.json";
89 import k85 from "../http/marks/board.json";
90 import k86 from "../http/marks/boards.json";
91 import k87 from "../http/marks/bring.json";
92 import k88 from "../http/marks/broker.json";
93 import k89 from "../http/marks/changelog.atom.json";
94 import k90 from "../http/marks/changelog.json";
95 import k91 from "../http/marks/claim.json";
96 import k92 from "../http/marks/cloud.json";
97 import k93 from "../http/marks/contract.json";
98 import k94 from "../http/marks/contribute.json";
99 import k95 from "../http/marks/csp-report.json";
100 import k96 from "../http/marks/dash.json";
101 import k97 from "../http/marks/data.json";
102 import k98 from "../http/marks/dataset.json";
103 import k99 from "../http/marks/deploy-to.json";
104 import k100 from "../http/marks/design.json";
105 import k101 from "../http/marks/desk.json";
106 import k102 from "../http/marks/displays.json";
107 import k103 from "../http/marks/docs.json";
108 import k104 from "../http/marks/edge.json";
109 import k105 from "../http/marks/edition.json";
110 import k106 from "../http/marks/events.json";
111 import k107 from "../http/marks/explore.atom.json";
112 import k108 from "../http/marks/explore.json";
113 import k109 from "../http/marks/explore.json.json";
114 import k110 from "../http/marks/family.json";
115 import k111 from "../http/marks/favicon.ico.json";
116 import k112 from "../http/marks/feed.json";
117 import k113 from "../http/marks/feed.json.json";
118 import k114 from "../http/marks/first-admin.json";
119 import k115 from "../http/marks/fleet.json";
120 import k116 from "../http/marks/flow.json";
121 import k117 from "../http/marks/forge.json";
122 import k118 from "../http/marks/forges.json";
123 import k119 from "../http/marks/front.json";
124 import k120 from "../http/marks/funnel.json";
125 import k121 from "../http/marks/go.json";
126 import k122 from "../http/marks/health.json";
127 import k123 from "../http/marks/home.json";
128 import k124 from "../http/marks/hooks.json";
129 import k125 from "../http/marks/icons.json";
130 import k126 from "../http/marks/infra.json";
131 import k127 from "../http/marks/join.json";
132 import k128 from "../http/marks/live.json";
133 import k129 from "../http/marks/llms-full.txt.json";
134 import k130 from "../http/marks/llms.txt.json";
135 import k131 from "../http/marks/login.json";
136 import k132 from "../http/marks/logout.json";
137 import k133 from "../http/marks/maintenance-json.json";
138 import k134 from "../http/marks/maintenance.json";
139 import k135 from "../http/marks/manifest.webmanifest.json";
140 import k136 from "../http/marks/map.json";
141 import k137 from "../http/marks/mcp.json";
142 import k138 from "../http/marks/measure.json";
143 import k139 from "../http/marks/metrics.json";
144 import k140 from "../http/marks/migrate.json";
145 import k141 from "../http/marks/new.json";
146 import k142 from "../http/marks/next.json";
147 import k143 from "../http/marks/notes.json";
148 import k144 from "../http/marks/now.json";
149 import k145 from "../http/marks/oauth.json";
150 import k146 from "../http/marks/oembed.json";
151 import k147 from "../http/marks/offers.json";
152 import k148 from "../http/marks/offline.json";
153 import k149 from "../http/marks/og.json";
154 import k150 from "../http/marks/openapi.json.json";
155 import k151 from "../http/marks/opensearch.xml.json";
156 import k152 from "../http/marks/organizations.json";
157 import k153 from "../http/marks/origins.json";
158 import k154 from "../http/marks/owner.atom.json";
159 import k155 from "../http/marks/owner.json";
160 import k156 from "../http/marks/packs.json";
161 import k157 from "../http/marks/peek.json";
162 import k158 from "../http/marks/pinned.json";
163 import k159 from "../http/marks/pipeline.json";
164 import k160 from "../http/marks/plugins.json";
165 import k161 from "../http/marks/pricing.json";
166 import k162 from "../http/marks/privacy.json";
167 import k163 from "../http/marks/recover.json";
168 import k164 from "../http/marks/releases.json";
169 import k165 from "../http/marks/releases.json.json";
170 import k166 from "../http/marks/repos.json";
171 import k167 from "../http/marks/resilience.json";
172 import k168 from "../http/marks/review.json";
173 import k169 from "../http/marks/robots.txt.json";
174 import k170 from "../http/marks/root.json";
175 import k171 from "../http/marks/runs.json";
176 import k172 from "../http/marks/script-error.json";
177 import k173 from "../http/marks/search.json";
178 import k174 from "../http/marks/security.json";
179 import k175 from "../http/marks/settings.json";
180 import k176 from "../http/marks/sign-in.json";
181 import k177 from "../http/marks/signin.json";
182 import k178 from "../http/marks/signup.json";
183 import k179 from "../http/marks/sitemap.xml.json";
184 import k180 from "../http/marks/status.json";
185 import k181 from "../http/marks/sw.js.json";
186 import k182 from "../http/marks/system.json";
187 import k183 from "../http/marks/talk.json";
188 import k184 from "../http/marks/tell.json";
189 import k185 from "../http/marks/templates.json";
190 import k186 from "../http/marks/templates.json.json";
191 import k187 from "../http/marks/terms.json";
192 import k188 from "../http/marks/theme.json";
193 import k189 from "../http/marks/toolbar-lab.js.json";
194 import k190 from "../http/marks/toolbar-lab.json";
195 import k191 from "../http/marks/verify.json";
196 import k192 from "../http/marks/welcome.json";
197 import k193 from "../http/marks/well-known.json";
41 import k37 from "../http/marks/api-v1-games.json";
42 import k38 from "../http/marks/api-v1-health.json";
43 import k39 from "../http/marks/api-v1-heartbeat.json";
44 import k40 from "../http/marks/api-v1-here.json";
45 import k41 from "../http/marks/api-v1-keeper.json";
46 import k42 from "../http/marks/api-v1-maintenance.json";
47 import k43 from "../http/marks/api-v1-map.json";
48 import k44 from "../http/marks/api-v1-migrate.json";
49 import k45 from "../http/marks/api-v1-offers.json";
50 import k46 from "../http/marks/api-v1-openapi.json.json";
51 import k47 from "../http/marks/api-v1-orgs.json";
52 import k48 from "../http/marks/api-v1-packs.json";
53 import k49 from "../http/marks/api-v1-passport.json";
54 import k50 from "../http/marks/api-v1-places.json";
55 import k51 from "../http/marks/api-v1-plans.json";
56 import k52 from "../http/marks/api-v1-proof.json";
57 import k53 from "../http/marks/api-v1-reach.json";
58 import k54 from "../http/marks/api-v1-release.json";
59 import k55 from "../http/marks/api-v1-releases.json";
60 import k56 from "../http/marks/api-v1-repos.json";
61 import k57 from "../http/marks/api-v1-returns.json";
62 import k58 from "../http/marks/api-v1-runner.json";
63 import k59 from "../http/marks/api-v1-search.json";
64 import k60 from "../http/marks/api-v1-secrets.json";
65 import k61 from "../http/marks/api-v1-sessions.json";
66 import k62 from "../http/marks/api-v1-share.json";
67 import k63 from "../http/marks/api-v1-slash.json";
68 import k64 from "../http/marks/api-v1-start.json";
69 import k65 from "../http/marks/api-v1-status.json";
70 import k66 from "../http/marks/api-v1-telemetry.json";
71 import k67 from "../http/marks/api-v1-templates.json";
72 import k68 from "../http/marks/api-v1-thoughts.json";
73 import k69 from "../http/marks/api-v1-timers.json";
74 import k70 from "../http/marks/api-v1-tokens.json";
75 import k71 from "../http/marks/api-v1-usage.json";
76 import k72 from "../http/marks/api-v1-user.json";
77 import k73 from "../http/marks/api-v1-users.json";
78 import k74 from "../http/marks/api-v1-version.json";
79 import k75 from "../http/marks/api-v1.json";
80 import k76 from "../http/marks/api.json";
81 import k77 from "../http/marks/apple-touch-icon-precomposed.png.json";
82 import k78 from "../http/marks/apple-touch-icon.png.json";
83 import k79 from "../http/marks/apps.json";
84 import k80 from "../http/marks/asked.json";
85 import k81 from "../http/marks/asks.json";
86 import k82 from "../http/marks/assets.json";
87 import k83 from "../http/marks/audit.csv.json";
88 import k84 from "../http/marks/audit.json";
89 import k85 from "../http/marks/big.json";
90 import k86 from "../http/marks/board.json";
91 import k87 from "../http/marks/boards.json";
92 import k88 from "../http/marks/bring.json";
93 import k89 from "../http/marks/broker.json";
94 import k90 from "../http/marks/changelog.atom.json";
95 import k91 from "../http/marks/changelog.json";
96 import k92 from "../http/marks/claim.json";
97 import k93 from "../http/marks/cloud.json";
98 import k94 from "../http/marks/contract.json";
99 import k95 from "../http/marks/contribute.json";
100 import k96 from "../http/marks/csp-report.json";
101 import k97 from "../http/marks/dash.json";
102 import k98 from "../http/marks/data.json";
103 import k99 from "../http/marks/dataset.json";
104 import k100 from "../http/marks/deploy-to.json";
105 import k101 from "../http/marks/design.json";
106 import k102 from "../http/marks/desk.json";
107 import k103 from "../http/marks/displays.json";
108 import k104 from "../http/marks/docs.json";
109 import k105 from "../http/marks/edge.json";
110 import k106 from "../http/marks/edition.json";
111 import k107 from "../http/marks/events.json";
112 import k108 from "../http/marks/explore.atom.json";
113 import k109 from "../http/marks/explore.json";
114 import k110 from "../http/marks/explore.json.json";
115 import k111 from "../http/marks/family.json";
116 import k112 from "../http/marks/favicon.ico.json";
117 import k113 from "../http/marks/feed.json";
118 import k114 from "../http/marks/feed.json.json";
119 import k115 from "../http/marks/first-admin.json";
120 import k116 from "../http/marks/fleet.json";
121 import k117 from "../http/marks/flow.json";
122 import k118 from "../http/marks/forge.json";
123 import k119 from "../http/marks/forges.json";
124 import k120 from "../http/marks/front.json";
125 import k121 from "../http/marks/funnel.json";
126 import k122 from "../http/marks/games.json";
127 import k123 from "../http/marks/go.json";
128 import k124 from "../http/marks/health.json";
129 import k125 from "../http/marks/home.json";
130 import k126 from "../http/marks/hooks.json";
131 import k127 from "../http/marks/icons.json";
132 import k128 from "../http/marks/infra.json";
133 import k129 from "../http/marks/join.json";
134 import k130 from "../http/marks/live.json";
135 import k131 from "../http/marks/llms-full.txt.json";
136 import k132 from "../http/marks/llms.txt.json";
137 import k133 from "../http/marks/login.json";
138 import k134 from "../http/marks/logout.json";
139 import k135 from "../http/marks/maintenance-json.json";
140 import k136 from "../http/marks/maintenance.json";
141 import k137 from "../http/marks/manifest.webmanifest.json";
142 import k138 from "../http/marks/map.json";
143 import k139 from "../http/marks/mcp.json";
144 import k140 from "../http/marks/measure.json";
145 import k141 from "../http/marks/metrics.json";
146 import k142 from "../http/marks/migrate.json";
147 import k143 from "../http/marks/new.json";
148 import k144 from "../http/marks/next.json";
149 import k145 from "../http/marks/notes.json";
150 import k146 from "../http/marks/now.json";
151 import k147 from "../http/marks/oauth.json";
152 import k148 from "../http/marks/oembed.json";
153 import k149 from "../http/marks/offers.json";
154 import k150 from "../http/marks/offline.json";
155 import k151 from "../http/marks/og.json";
156 import k152 from "../http/marks/openapi.json.json";
157 import k153 from "../http/marks/opensearch.xml.json";
158 import k154 from "../http/marks/organizations.json";
159 import k155 from "../http/marks/origins.json";
160 import k156 from "../http/marks/owner.atom.json";
161 import k157 from "../http/marks/owner.json";
162 import k158 from "../http/marks/packs.json";
163 import k159 from "../http/marks/peek.json";
164 import k160 from "../http/marks/pinned.json";
165 import k161 from "../http/marks/pipeline.json";
166 import k162 from "../http/marks/plugins.json";
167 import k163 from "../http/marks/pricing.json";
168 import k164 from "../http/marks/privacy.json";
169 import k165 from "../http/marks/recover.json";
170 import k166 from "../http/marks/releases.json";
171 import k167 from "../http/marks/releases.json.json";
172 import k168 from "../http/marks/repos.json";
173 import k169 from "../http/marks/resilience.json";
174 import k170 from "../http/marks/review.json";
175 import k171 from "../http/marks/robots.txt.json";
176 import k172 from "../http/marks/root.json";
177 import k173 from "../http/marks/runs.json";
178 import k174 from "../http/marks/script-error.json";
179 import k175 from "../http/marks/search.json";
180 import k176 from "../http/marks/security.json";
181 import k177 from "../http/marks/settings.json";
182 import k178 from "../http/marks/sign-in.json";
183 import k179 from "../http/marks/signin.json";
184 import k180 from "../http/marks/signup.json";
185 import k181 from "../http/marks/sitemap.xml.json";
186 import k182 from "../http/marks/status.json";
187 import k183 from "../http/marks/sw.js.json";
188 import k184 from "../http/marks/system.json";
189 import k185 from "../http/marks/talk.json";
190 import k186 from "../http/marks/tell.json";
191 import k187 from "../http/marks/templates.json";
192 import k188 from "../http/marks/templates.json.json";
193 import k189 from "../http/marks/terms.json";
194 import k190 from "../http/marks/theme.json";
195 import k191 from "../http/marks/toolbar-lab.js.json";
196 import k192 from "../http/marks/toolbar-lab.json";
197 import k193 from "../http/marks/verify.json";
198 import k194 from "../http/marks/welcome.json";
199 import k195 from "../http/marks/well-known.json";
198200
199201 /** Each file of `http/marks/`, parsed, in name order. */
200202 export const MARK_FILES: readonly unknown[] = [
@@ -392,4 +394,6 @@ export const MARK_FILES: readonly unknown[] = [
392394 k191,
393395 k192,
394396 k193,
397 k194,
398 k195,
395399 ];
src/generated/migrations.ts +2
@@ -439,6 +439,7 @@ import m434 from "../core/migrations/20261130140000-look-drops-old-key.ts";
439439 import m435 from "../core/migrations/20261130170000-fence-read-from.ts";
440440 import m436 from "../core/migrations/20261130170100-chat-build-lane.ts";
441441 import m437 from "../core/migrations/20261130235220-run-check-plan.ts";
442 import m438 from "../core/migrations/20261201000000-games.ts";
442443
443444 /** Each migration file's name and its default export, in name order. */
444445 export const MIGRATION_MODULES: readonly (readonly [string, unknown])[] = [
@@ -880,4 +881,5 @@ export const MIGRATION_MODULES: readonly (readonly [string, unknown])[] = [
880881 ["20261130170000-fence-read-from.ts", m435],
881882 ["20261130170100-chat-build-lane.ts", m436],
882883 ["20261130235220-run-check-plan.ts", m437],
884 ["20261201000000-games.ts", m438],
883885 ];
src/generated/screens.ts +72 −70
@@ -57,72 +57,73 @@ import * as s52 from "../tui/screens/forgeview.ts";
5757 import * as s53 from "../tui/screens/front.ts";
5858 import * as s54 from "../tui/screens/frontms.ts";
5959 import * as s55 from "../tui/screens/funnel.ts";
60 import * as s56 from "../tui/screens/gifts.ts";
61 import * as s57 from "../tui/screens/health_voice.ts";
62 import * as s58 from "../tui/screens/home_pins.ts";
63 import * as s59 from "../tui/screens/hostreach.ts";
64 import * as s60 from "../tui/screens/infra.ts";
65 import * as s61 from "../tui/screens/inventory.ts";
66 import * as s62 from "../tui/screens/invites.ts";
67 import * as s63 from "../tui/screens/knobs.ts";
68 import * as s64 from "../tui/screens/lapsed.ts";
69 import * as s65 from "../tui/screens/limits.ts";
70 import * as s66 from "../tui/screens/loopstalls.ts";
71 import * as s67 from "../tui/screens/madefrom.ts";
72 import * as s68 from "../tui/screens/maintainruns.ts";
73 import * as s69 from "../tui/screens/maintenance.ts";
74 import * as s70 from "../tui/screens/maintenanceweek.ts";
75 import * as s71 from "../tui/screens/mergedbranches.ts";
76 import * as s72 from "../tui/screens/mirrorpacks.ts";
77 import * as s73 from "../tui/screens/model.ts";
78 import * as s74 from "../tui/screens/money.ts";
79 import * as s75 from "../tui/screens/newissue.ts";
80 import * as s76 from "../tui/screens/next.ts";
81 import * as s77 from "../tui/screens/nowlist.ts";
82 import * as s78 from "../tui/screens/offers.ts";
83 import * as s79 from "../tui/screens/offsite.ts";
84 import * as s80 from "../tui/screens/orggrants.ts";
85 import * as s81 from "../tui/screens/orgteams.ts";
86 import * as s82 from "../tui/screens/originahead.ts";
87 import * as s83 from "../tui/screens/owner.ts";
88 import * as s84 from "../tui/screens/packrepos.ts";
89 import * as s85 from "../tui/screens/payments.ts";
90 import * as s86 from "../tui/screens/people.ts";
91 import * as s87 from "../tui/screens/pinned.ts";
92 import * as s88 from "../tui/screens/planner.ts";
93 import * as s89 from "../tui/screens/planrow.ts";
94 import * as s90 from "../tui/screens/plans.ts";
95 import * as s91 from "../tui/screens/previewdirs.ts";
96 import * as s92 from "../tui/screens/profile.ts";
97 import * as s93 from "../tui/screens/quotas.ts";
98 import * as s94 from "../tui/screens/recoverykit.ts";
99 import * as s95 from "../tui/screens/refused.ts";
100 import * as s96 from "../tui/screens/repolist.ts";
101 import * as s97 from "../tui/screens/requests.ts";
102 import * as s98 from "../tui/screens/resilience.ts";
103 import * as s99 from "../tui/screens/returning.ts";
104 import * as s100 from "../tui/screens/returns.ts";
105 import * as s101 from "../tui/screens/scorecard.ts";
106 import * as s102 from "../tui/screens/scrapes.ts";
107 import * as s103 from "../tui/screens/secrets.ts";
108 import * as s104 from "../tui/screens/sentinel.ts";
109 import * as s105 from "../tui/screens/ship_time.ts";
110 import * as s106 from "../tui/screens/slowpages.ts";
111 import * as s107 from "../tui/screens/sold.ts";
112 import * as s108 from "../tui/screens/spend.ts";
113 import * as s109 from "../tui/screens/stalepulls.ts";
114 import * as s110 from "../tui/screens/subscriptions.ts";
115 import * as s111 from "../tui/screens/system.ts";
116 import * as s112 from "../tui/screens/teams.ts";
117 import * as s113 from "../tui/screens/telemetry.ts";
118 import * as s114 from "../tui/screens/tell_undo.ts";
119 import * as s115 from "../tui/screens/traffic.ts";
120 import * as s116 from "../tui/screens/trafficview.ts";
121 import * as s117 from "../tui/screens/valves.ts";
122 import * as s118 from "../tui/screens/waiting.ts";
123 import * as s119 from "../tui/screens/waiting_for_me.ts";
124 import * as s120 from "../tui/screens/wayback.ts";
125 import * as s121 from "../tui/screens/weekcard.ts";
60 import * as s56 from "../tui/screens/games.ts";
61 import * as s57 from "../tui/screens/gifts.ts";
62 import * as s58 from "../tui/screens/health_voice.ts";
63 import * as s59 from "../tui/screens/home_pins.ts";
64 import * as s60 from "../tui/screens/hostreach.ts";
65 import * as s61 from "../tui/screens/infra.ts";
66 import * as s62 from "../tui/screens/inventory.ts";
67 import * as s63 from "../tui/screens/invites.ts";
68 import * as s64 from "../tui/screens/knobs.ts";
69 import * as s65 from "../tui/screens/lapsed.ts";
70 import * as s66 from "../tui/screens/limits.ts";
71 import * as s67 from "../tui/screens/loopstalls.ts";
72 import * as s68 from "../tui/screens/madefrom.ts";
73 import * as s69 from "../tui/screens/maintainruns.ts";
74 import * as s70 from "../tui/screens/maintenance.ts";
75 import * as s71 from "../tui/screens/maintenanceweek.ts";
76 import * as s72 from "../tui/screens/mergedbranches.ts";
77 import * as s73 from "../tui/screens/mirrorpacks.ts";
78 import * as s74 from "../tui/screens/model.ts";
79 import * as s75 from "../tui/screens/money.ts";
80 import * as s76 from "../tui/screens/newissue.ts";
81 import * as s77 from "../tui/screens/next.ts";
82 import * as s78 from "../tui/screens/nowlist.ts";
83 import * as s79 from "../tui/screens/offers.ts";
84 import * as s80 from "../tui/screens/offsite.ts";
85 import * as s81 from "../tui/screens/orggrants.ts";
86 import * as s82 from "../tui/screens/orgteams.ts";
87 import * as s83 from "../tui/screens/originahead.ts";
88 import * as s84 from "../tui/screens/owner.ts";
89 import * as s85 from "../tui/screens/packrepos.ts";
90 import * as s86 from "../tui/screens/payments.ts";
91 import * as s87 from "../tui/screens/people.ts";
92 import * as s88 from "../tui/screens/pinned.ts";
93 import * as s89 from "../tui/screens/planner.ts";
94 import * as s90 from "../tui/screens/planrow.ts";
95 import * as s91 from "../tui/screens/plans.ts";
96 import * as s92 from "../tui/screens/previewdirs.ts";
97 import * as s93 from "../tui/screens/profile.ts";
98 import * as s94 from "../tui/screens/quotas.ts";
99 import * as s95 from "../tui/screens/recoverykit.ts";
100 import * as s96 from "../tui/screens/refused.ts";
101 import * as s97 from "../tui/screens/repolist.ts";
102 import * as s98 from "../tui/screens/requests.ts";
103 import * as s99 from "../tui/screens/resilience.ts";
104 import * as s100 from "../tui/screens/returning.ts";
105 import * as s101 from "../tui/screens/returns.ts";
106 import * as s102 from "../tui/screens/scorecard.ts";
107 import * as s103 from "../tui/screens/scrapes.ts";
108 import * as s104 from "../tui/screens/secrets.ts";
109 import * as s105 from "../tui/screens/sentinel.ts";
110 import * as s106 from "../tui/screens/ship_time.ts";
111 import * as s107 from "../tui/screens/slowpages.ts";
112 import * as s108 from "../tui/screens/sold.ts";
113 import * as s109 from "../tui/screens/spend.ts";
114 import * as s110 from "../tui/screens/stalepulls.ts";
115 import * as s111 from "../tui/screens/subscriptions.ts";
116 import * as s112 from "../tui/screens/system.ts";
117 import * as s113 from "../tui/screens/teams.ts";
118 import * as s114 from "../tui/screens/telemetry.ts";
119 import * as s115 from "../tui/screens/tell_undo.ts";
120 import * as s116 from "../tui/screens/traffic.ts";
121 import * as s117 from "../tui/screens/trafficview.ts";
122 import * as s118 from "../tui/screens/valves.ts";
123 import * as s119 from "../tui/screens/waiting.ts";
124 import * as s120 from "../tui/screens/waiting_for_me.ts";
125 import * as s121 from "../tui/screens/wayback.ts";
126 import * as s122 from "../tui/screens/weekcard.ts";
126127
127128 /** Each screen file that declares palette entries: its module and the export names. */
128129 export const SCREEN_MODULES: readonly (readonly [Record<string, unknown>, readonly string[]])[] = [
@@ -199,11 +200,11 @@ export const SCREEN_MODULES: readonly (readonly [Record<string, unknown>, readon
199200 [s70, ["entry"]],
200201 [s71, ["entry"]],
201202 [s72, ["entry"]],
202 [s73, ["modelGrantEntry","modelCeilingEntry"]],
203 [s74, ["entry"]],
203 [s73, ["entry"]],
204 [s74, ["modelGrantEntry","modelCeilingEntry"]],
204205 [s75, ["entry"]],
205 [s76, ["nextAllEntry"]],
206 [s77, ["entry"]],
206 [s76, ["entry"]],
207 [s77, ["nextAllEntry"]],
207208 [s78, ["entry"]],
208209 [s79, ["entry"]],
209210 [s80, ["entry"]],
@@ -248,4 +249,5 @@ export const SCREEN_MODULES: readonly (readonly [Record<string, unknown>, readon
248249 [s119, ["entry"]],
249250 [s120, ["entry"]],
250251 [s121, ["entry"]],
252 [s122, ["entry"]],
251253 ];
src/http/api.ts +2
@@ -9,6 +9,7 @@
99 */
1010
1111 import { cursorRefusal, limitRefusal } from "../contract/page_query.ts";
12 import { gamesApiRoutes } from "./games_routes.ts";
1213 import { parseCursor, parseLimit } from "../contract/page_query.ts";
1314 import { noneMatch } from "./conditional.ts";
1415 import { queryTooLong, QUERY_TOO_LONG } from "../core/query_limit.ts";
@@ -1264,6 +1265,7 @@ export function apiRoutes(router: Router<Handler>, isPage: (path: string) => boo
12641265 forgeOriginRoutes(router);
12651266 adminRoutes(router);
12661267 runnerRoutes(router);
1268 gamesApiRoutes(router);
12671269 maintenanceRoutes(router);
12681270 maintenanceRunsRoutes(router);
12691271 diskReadingRoutes(router);
src/http/games_routes.ts added +53
@@ -0,0 +1,53 @@
1 /**
2 * The routes of forge games: the agent's sync (`POST /api/v1/games/agent/sync`, the box token as
3 * bearer), the signed jar download, and the `/games` pages (`web/pages/games.ts`).
4 */
5
6 import { composeServices, readCompose } from "../games/compose.ts";
7 import { synced } from "../games/notify.ts";
8 import { boxByToken, envFiles, recordSync, signJarUrls, type SyncBody } from "../games/store.ts";
9 import { BODY_CAPS } from "../kernel/body_caps.ts";
10 import {
11 gameBoxPage, gameCommandSubmit, gameEnvSubmit, gameGrantSubmit, gameJarDownload, gameJarSubmit, gamePluginSubmit, gamePowerSubmit, gameServicePage, gameServiceStream, gamesPage,
12 } from "../web/pages/games.ts";
13 import type { Ctx, Handler } from "./context.ts";
14 import { apiError, boundedBody, json } from "./respond.ts";
15 import type { Router } from "./router.ts";
16
17 /** POST /api/v1/games/agent/sync: one pull of a game box's agent (the contract in docs/features/games.md). */
18 export async function gameAgentSync(ctx: Ctx): Promise<Response> {
19 const auth = ctx.request.headers.get("authorization") ?? "";
20 const box = auth.startsWith("Bearer ") ? boxByToken(ctx.app.db, auth.slice(7).trim()) : undefined;
21 if (box === undefined) return apiError("unauthorized", 401, "send the game box's token as the bearer");
22 const sent = await boundedBody(ctx.request, BODY_CAPS.gameSync.bytes);
23 if (sent === "too_large") return apiError("too_large", 413, "a sync is at most 200 log lines a service");
24 const body = sent as SyncBody;
25 const commands = recordSync(ctx.app.db, box, body);
26 synced(ctx.app, box.id);
27 const compose = await readCompose(ctx.app, box);
28 const reply: Record<string, unknown> = {
29 composeSha: compose?.sha ?? "",
30 env: envFiles(ctx.app, box, compose?.text ?? "", compose === undefined ? [] : composeServices(compose.text)),
31 commands,
32 };
33 if (compose !== undefined && compose.sha !== (typeof body.composeSha === "string" ? body.composeSha : "")) reply["compose"] = signJarUrls(ctx.app, box, compose.text, ctx.url.origin);
34 return json(reply);
35 }
36
37 export function gamesApiRoutes(router: Router<Handler>): void {
38 router.add("POST", "/api/v1/games/agent/sync", gameAgentSync);
39 }
40
41 export function gamesRoutes(router: Router<Handler>): void {
42 router.add("GET", "/games", gamesPage);
43 router.add("GET", "/games/jar/:id/:name", gameJarDownload);
44 router.add("GET", "/games/:box", gameBoxPage);
45 router.add("POST", "/games/:box/grant", gameGrantSubmit);
46 router.add("GET", "/games/:box/:service", gameServicePage);
47 router.add("GET", "/games/:box/:service/stream", gameServiceStream);
48 router.add("POST", "/games/:box/:service/command", gameCommandSubmit);
49 router.add("POST", "/games/:box/:service/power", gamePowerSubmit);
50 router.add("POST", "/games/:box/:service/env", gameEnvSubmit);
51 router.add("POST", "/games/:box/:service/plugin", gamePluginSubmit);
52 router.add("POST", "/games/:box/:service/jar", gameJarSubmit);
53 }
src/http/marks/api-v1-games.json added +4
@@ -0,0 +1,4 @@
1 {
2 "head": "/api/v1/games",
3 "mark": "open"
4 }
src/http/marks/games.json added +4
@@ -0,0 +1,4 @@
1 {
2 "head": "/games",
3 "mark": "open"
4 }
src/http/mcp/tools/games.ts added +62
@@ -0,0 +1,62 @@
1 import { addPlugin, commitServiceEnv } from "../../../games/compose.ts";
2 import { boxNamed, listBoxes, mayDo, queueCommand, roleOn, seesBox, SERVICE_NAME, servicesOf, type CommandKind } from "../../../games/store.ts";
3 import { good, bad, type Tool, str } from "../shared.ts";
4
5 const POWER = ["start", "stop", "restart", "recreate", "pull"];
6
7 export const tool: Tool = {
8 name: "games",
9 listedTo: "admin",
10 doc: "`{ action, box?, service?, text?, kind?, key?, value?, modrinth? }`: game boxes. `list`; `console` queues `text` as RCON; `power` `kind` (start, stop, restart); `env` commits `key`=`value` (empty removes); `plugin` adds a `modrinth` slug. Grants as on /games",
11 description: "Game boxes: list, console, power, env, plugins.",
12 inputSchema: {
13 type: "object",
14 properties: {
15 action: { type: "string", enum: ["list", "console", "power", "env", "plugin"] },
16 box: { type: "string", maxLength: 40 },
17 service: { type: "string", maxLength: 64 },
18 text: { type: "string", maxLength: 1000 },
19 kind: { type: "string", enum: POWER },
20 key: { type: "string", maxLength: 100 },
21 value: { type: "string", maxLength: 2000 },
22 modrinth: { type: "string", maxLength: 100 },
23 },
24 required: ["action"],
25 },
26 writes: true,
27 heldNotWhen: (args) => args["action"] === "list",
28 async run(ctx, user, args) {
29 const action = str(args["action"]);
30 const db = ctx.app.db;
31 if (action === "list")
32 return good({
33 items: listBoxes(db)
34 .filter((b) => seesBox(db, user, b.id))
35 .map((b) => ({ name: b.name, place: b.place, monthlyCents: b.monthlyCents, seenAt: b.seenAt, host: b.host, services: servicesOf(db, b.id).filter((s) => mayDo(roleOn(db, user, b.id, s.name), "viewer")) })),
36 });
37 const box = boxNamed(db, str(args["box"]));
38 const service = str(args["service"]);
39 if (box === undefined || !seesBox(db, user, box.id) || !SERVICE_NAME.test(service)) return bad("not_found", "no such box or service here");
40 if (!mayDo(roleOn(db, user, box.id, service), "operator")) return bad("forbidden", `you are not an operator of ${service} on ${box.name}`);
41 if (action === "console") {
42 const text = str(args["text"]).trim();
43 if (text === "") return bad("invalid", "say the command as text");
44 return good({ says: "Queued; the box runs it on its next sync.", id: queueCommand(db, box.id, service, "rcon", text, user.id) });
45 }
46 if (action === "power") {
47 const kind = str(args["kind"]);
48 if (!POWER.includes(kind)) return bad("invalid", "kind is start, stop, restart, recreate or pull");
49 return good({ says: `${kind} ${service}: asked.`, id: queueCommand(db, box.id, service, kind as CommandKind, "", user.id) });
50 }
51 if (action === "env") {
52 const value = str(args["value"]);
53 const done = await commitServiceEnv(ctx.app, user, box, service, { [str(args["key"])]: value === "" ? null : value });
54 return done.ok ? good({ says: `Committed ${done.sha.slice(0, 10)}.`, sha: done.sha }) : bad("refused", done.error);
55 }
56 if (action === "plugin") {
57 const done = await addPlugin(ctx.app, user, box, service, { modrinth: str(args["modrinth"]) });
58 return done.ok ? good({ says: `Committed ${done.sha.slice(0, 10)}.`, sha: done.sha }) : bad("refused", done.error);
59 }
60 return bad("bad_action", "action is list, console, power, env or plugin");
61 },
62 };
src/http/mcp/tools/index.ts +1
@@ -91,6 +91,7 @@ export { tool as fork } from "./fork.ts";
9191 export { tool as fork_tree } from "./fork_tree.ts";
9292 export { tool as forks } from "./forks.ts";
9393 export { tool as front_page } from "./front_page.ts";
94 export { tool as games } from "./games.ts";
9495 export { tool as health } from "./health.ts";
9596 export { tool as held } from "./held.ts";
9697 export { tool as here } from "./here.ts";
src/http/mcp/tools/infra.ts +11 −2
@@ -1,4 +1,4 @@
1 import { buildOf, goneWords, infraOf, infraSays, machineOf, nameFor, planById, planCompose, planWants, startBuild } from "../../../actions/infra.ts";
1 import { buildOf, gameWant, goneWords, infraOf, infraSays, machineOf, nameFor, planById, planCompose, planWants, startBuild } from "../../../actions/infra.ts";
22 import { endsWords, keepPinned } from "../../../actions/pinned.ts";
33 import { EXPERIMENT_WORDS, attachMachine, beginExperiment, findExperiment, recordResult } from "../../../cloud/experiments.ts";
44 import { good, bad, type Tool, str } from "../shared.ts";
@@ -14,7 +14,7 @@ const s = (v: unknown, max: number): string => str(v).slice(0, max);
1414 export const tool: Tool = {
1515 name: "infra",
1616 listedTo: "admin",
17 doc: "`{ action, id?, want?, question?, names?, result? }`: `list` (its `says` names every machine), `show` an `id` (a plan, an experiment or a machine's name), `plan` a `want` `{app, where, question?, experiment?, days?}` or dead `names`, `apply` its `id`, `keep`, `begin`, `attach`, `record_result`.",
17 doc: "`{ action, id?, want?, question?, names?, result? }`: `list` (its `says` names every machine), `show` an `id` (a plan, an experiment or a machine's name), `plan` a `want` `{app, where, question?, experiment?, days?}` or a game box `{game: true, where, name?, repo?, host?}` or dead `names`, `apply` its `id`, `keep`, `begin`, `attach`, `record_result`.",
1818 description: "Cloud machines and spend.",
1919 inputSchema: {
2020 type: "object",
@@ -67,6 +67,15 @@ export const tool: Tool = {
6767 }
6868 if (action === "plan") {
6969 const w = (typeof args["want"] === "object" && args["want"] !== null ? args["want"] : {}) as Record<string, unknown>;
70 // A game box: Docker and the game agent on the owner's cloud, running a compose file.
71 if (w["game"] === true) {
72 const want = gameWant({ name: s(w["name"], 40) || nameFor(s(w["repo"], 140) || "trevato/game"), where: s(w["where"], 260), repo: s(w["repo"], 140), host: s(w["host"], 253) });
73 if (!want.ok) return bad("incomplete", want.error);
74 const planned = planWants(ctx.app, user, [want.value]);
75 if (!planned.ok) return bad("not_found", "no such tool here");
76 const p = planned.value;
77 return good({ id: p.plan.id, says: p.summary, steps: p.plan.steps.map((x) => x.says), refusals: p.fixes, byAccount: p.plan.byAccount, deltaCents: p.plan.deltaCents });
78 }
7079 const app = s(w["app"], 140);
7180 const experiment = s(w["experiment"], 60);
7281 const question = s(w["question"], 300);
src/http/server.ts +2
@@ -6,6 +6,7 @@
66 */
77
88 import { forgeTemplateUpdate } from "../web/pages/forge-template-setting.ts";
9 import { gamesRoutes } from "./games_routes.ts";
910 import { allocationMove, allocationPage, allocationWeekly } from "../web/pages/allocation.ts";
1011 import { cloudConnectBuild, cloudConnectPage, cloudConnectProvider, cloudConnectSubmit } from "../web/pages/cloud.ts";
1112 import { runOwnToken } from "../web/own_token.ts";
@@ -1184,6 +1185,7 @@ export function buildRouter(): Router<Handler> {
11841185 // The Deploy to… page for a pinned forge (#8744); literal, above /:owner.
11851186 pinnedRoutes(router);
11861187 infraRoutes(router);
1188 gamesRoutes(router);
11871189 // Each THREATS.md protection against the last gate; literal, above /:owner.
11881190 router.add("GET", "/resilience", resiliencePage);
11891191 router.add("GET", "/data", dataPage);
src/kernel/body_caps.ts +8
@@ -59,6 +59,14 @@ export const BODY_CAPS = {
5959 bytes: 8 * KIB,
6060 reason: "a browser's Content-Security-Policy report: one violation, its URLs and a sample",
6161 },
62 gameSync: {
63 bytes: 2 * MIB,
64 reason: "a game box agent's sync: up to 200 log lines for each of its services, their stats and command results",
65 },
66 gameJar: {
67 bytes: 64 * MIB,
68 reason: "a Minecraft plugin jar uploaded for a game box, kept by the forge and fetched by the box",
69 },
6270 stripeHook: {
6371 bytes: 256 * KIB,
6472 reason: "a Stripe event delivery, signed over its exact bytes: one event, never a batch",
src/tui/screens/games.ts added +258
@@ -0,0 +1,258 @@
1 /**
2 * Games in the terminal (forge games): every service of every game box the person may see, as
3 * /games lists them, with `s` start, `x` stop and `r` restart for an operator, each queued for the
4 * box's next sync through `games/store.ts`, the same queue the page and the MCP tool use. `enter`
5 * opens a service as /games/<box>/<service> does: its console (the log tail, and `:` queues an
6 * rcon command), its env (`e` sets or clears a key, committed through `commitServiceEnv`) and its
7 * plugins (`a` adds a Modrinth slug or a URL through `addPlugin`; uploading a jar is the page's
8 * alone). `g` opens the box's grants, which an owner sets with `a`, through `grant`.
9 */
10
11 import { emptyText } from "../../core/empty_words.ts";
12 import { getUserByName } from "../../core/users.ts";
13 import { addPlugin, commitServiceEnv, pluginsOf, readCompose, serviceEnv } from "../../games/compose.ts";
14 import {
15 SERVICE_NAME,
16 grant,
17 grantsOf,
18 listBoxes,
19 logsOf,
20 mayDo,
21 queueCommand,
22 recentCommands,
23 roleOn,
24 seesBox,
25 servicesOf,
26 type CommandKind,
27 type GameBox,
28 type Role,
29 } from "../../games/store.ts";
30 import type { Ctx, Screen } from "../app/app.ts";
31 import { binding } from "../app/keys.ts";
32 import { style } from "../term/style.ts";
33 import { truncate } from "../term/width.ts";
34 import type { Session } from "../session.ts";
35 import { fill, len, split } from "../ui/layout.ts";
36 import { ListState, drawList, promptScreen, type ListRow } from "./common.ts";
37 import type { PaletteEntry } from "./entries.ts";
38
39 export function gamesScreen(f: Session, ctx: Ctx): Screen {
40 const state = new ListState();
41 let note = "";
42 const rows = () =>
43 listBoxes(f.app.db)
44 .filter((b) => seesBox(f.app.db, f.user, b.id))
45 .flatMap((b) => servicesOf(f.app.db, b.id).filter((s) => mayDo(roleOn(f.app.db, f.user, b.id, s.name), "viewer")).map((s) => ({ box: b, service: s })));
46 const screen: Screen = {
47 title: "Games",
48 keys: [
49 binding(["j", "k"], "move cursor"),
50 binding(["enter"], "console, env, plugins"),
51 binding(["g"], "grants"),
52 binding(["s"], "start"),
53 binding(["x"], "stop"),
54 binding(["r"], "restart"),
55 ],
56 render(area, s) {
57 const c = ctx.theme.c;
58 const [head, list] = split(area, "v", [len(1), fill(1)]);
59 const all = rows();
60 s.text(head!.x, head!.y, truncate(note !== "" ? note : all.length === 0 ? emptyText("gameServices") : "Each service of each game box you may see.", head!.w), style(c.mutedFg, c.bg), head!.x + head!.w);
61 const view: ListRow[] = all.map(({ box, service }) => ({
62 title: `${box.name}/${service.name}`,
63 ...(service.state === "exited" ? { tone: "danger" as const } : {}),
64 secondary: `${service.state || "unknown"} · ${Math.round(service.memMiB)} MiB · ${service.cpuPct.toFixed(1)}% CPU`,
65 meta: box.seenAt.slice(11, 19),
66 }));
67 drawList(s, list!, c, state, view);
68 },
69 key(e) {
70 const all = rows();
71 if (state.key(e, all.length)) return true;
72 const at = all[state.index];
73 if (at !== undefined && !e.ctrl && !e.alt && e.key === "enter") {
74 ctx.push(gameServiceScreen(f, ctx, at.box, at.service.name));
75 return true;
76 }
77 if (at !== undefined && !e.ctrl && !e.alt && e.key === "g") {
78 ctx.push(gameGrantsScreen(f, ctx, at.box));
79 return true;
80 }
81 const kind: CommandKind | undefined = e.key === "s" ? "start" : e.key === "x" ? "stop" : e.key === "r" ? "restart" : undefined;
82 if (kind === undefined || at === undefined || e.ctrl || e.alt) return false;
83 if (!mayDo(roleOn(f.app.db, f.user, at.box.id, at.service.name), "operator")) note = `You are not an operator of ${at.service.name}.`;
84 else {
85 queueCommand(f.app.db, at.box.id, at.service.name, kind, "", f.user?.id ?? "");
86 note = `${kind} ${at.box.name}/${at.service.name}: asked; the box does it on its next sync.`;
87 }
88 ctx.invalidate();
89 return true;
90 },
91 };
92 return screen;
93 }
94
95 const PARTS = ["console", "env", "plugins"] as const;
96 type Part = (typeof PARTS)[number];
97
98 /**
99 * One service, as /games/<box>/<service>: `tab` moves between its console, env and plugins. Each
100 * change goes through the action the page's form calls, with the page's refusals in its words.
101 */
102 export function gameServiceScreen(f: Session, ctx: Ctx, box: GameBox, service: string): Screen {
103 let part: Part = "console";
104 let note = "";
105 let compose: string | undefined;
106 let loaded = false;
107 const operator = () => mayDo(roleOn(f.app.db, f.user, box.id, service), "operator");
108 const load = async (): Promise<void> => {
109 compose = (await readCompose(f.app, box))?.text;
110 loaded = true;
111 ctx.invalidate();
112 };
113 void load();
114 const say = (words: string): void => {
115 note = words;
116 ctx.invalidate();
117 };
118 const lines = (): string[] => {
119 if (part === "console") {
120 const done = recentCommands(f.app.db, box.id, service, 5).map((c) => `> ${c.text} ${c.done ? (c.ok ? "ok" : "failed") : "waiting for the box"}${c.output === "" ? "" : `: ${c.output.split("\n")[0]}`}`);
121 return [...logsOf(f.app.db, box.id, service, 200).lines, ...done];
122 }
123 if (!loaded) return ["Reading the compose file…"];
124 if (compose === undefined) return [`No ${box.path} on ${box.repo}@${box.branch}.`];
125 if (part === "env") {
126 const env = Object.entries(serviceEnv(compose, service));
127 return env.length === 0 ? ["No environment set for this service."] : env.map(([k, v]) => `${k}=${v}`);
128 }
129 const p = pluginsOf(compose, service);
130 return [
131 ...p.modrinth.map((m) => `modrinth: ${m}`),
132 ...p.plugins.map((u) => `plugin: ${u}`),
133 ...(p.modrinth.length + p.plugins.length === 0 ? ["No plugins yet."] : []),
134 `Uploading a jar is on the web only: /games/${box.name}/${service}.`,
135 ];
136 };
137 const ask = (title: string, label: string, run: (value: string) => Promise<string>): void => {
138 if (!operator()) return say(`You are not an operator of ${service}.`);
139 ctx.push(
140 promptScreen(ctx, screen, {
141 title,
142 label,
143 // The prompt closes itself; what came of it is said on this screen's head line.
144 onSubmit: async (value) => {
145 say(await run(value));
146 },
147 }),
148 );
149 };
150 const screen: Screen = {
151 title: `${box.name}/${service}`,
152 keys: [binding(["tab"], "console, env, plugins"), binding([":"], "rcon"), binding(["e"], "set env"), binding(["a"], "add plugin")],
153 render(area, s) {
154 const c = ctx.theme.c;
155 const [head, body] = split(area, "v", [len(1), fill(1)]);
156 const tabs = PARTS.map((p) => (p === part ? `[${p}]` : p)).join(" ");
157 s.text(head!.x, head!.y, truncate(note === "" ? tabs : `${tabs} · ${note}`, head!.w), style(c.mutedFg, c.bg), head!.x + head!.w);
158 const all = lines();
159 const shown = part === "console" ? all.slice(-body!.h) : all.slice(0, body!.h);
160 shown.forEach((l, i) => s.text(body!.x, body!.y + i, truncate(l, body!.w), style(c.fg, c.bg), body!.x + body!.w));
161 },
162 key(e) {
163 if (e.ctrl || e.alt) return false;
164 if (e.key === "tab") {
165 part = PARTS[(PARTS.indexOf(part) + 1) % PARTS.length]!;
166 note = "";
167 ctx.invalidate();
168 return true;
169 }
170 if (e.key === ":")
171 ask("RCON", `A command for ${service}`, async (text) => {
172 if (text.trim() === "") return "Type a command.";
173 queueCommand(f.app.db, box.id, service, "rcon", text.trim(), f.user?.id ?? "");
174 part = "console";
175 return "Sent; the answer shows under the console.";
176 });
177 else if (e.key === "e")
178 ask("Env", "KEY=VALUE (an empty value removes the key)", async (raw) => {
179 const at = raw.indexOf("=");
180 const key = (at < 0 ? raw : raw.slice(0, at)).trim();
181 const value = at < 0 ? "" : raw.slice(at + 1);
182 const done = await commitServiceEnv(f.app, f.user!, box, service, { [key]: value === "" ? null : value });
183 if (!done.ok) return done.error;
184 part = "env";
185 await load();
186 return `Committed ${done.sha.slice(0, 10)}; the box redeploys on its next sync.`;
187 });
188 else if (e.key === "a")
189 ask("Plugin", "A Modrinth slug, or an https URL to a jar", async (raw) => {
190 const v = raw.trim();
191 const done = await addPlugin(f.app, f.user!, box, service, /^https?:\/\//.test(v) ? { url: v } : { modrinth: v });
192 if (!done.ok) return done.error;
193 part = "plugins";
194 await load();
195 return `Committed ${done.sha.slice(0, 10)}.`;
196 });
197 else return false;
198 return true;
199 },
200 };
201 return screen;
202 }
203
204 /** A box's grants, as /games/<box> lists them; an owner sets one with `a` ("user role [service]"). */
205 export function gameGrantsScreen(f: Session, ctx: Ctx, box: GameBox): Screen {
206 const state = new ListState();
207 let note = "";
208 const owner = () => mayDo(roleOn(f.app.db, f.user, box.id), "owner");
209 const screen: Screen = {
210 title: `${box.name} grants`,
211 keys: [binding(["j", "k"], "move cursor"), binding(["a"], "grant")],
212 render(area, s) {
213 const c = ctx.theme.c;
214 const [head, list] = split(area, "v", [len(1), fill(1)]);
215 const all = grantsOf(f.app.db, box.id);
216 s.text(head!.x, head!.y, truncate(note !== "" ? note : all.length === 0 ? "No one is granted this box; forge admins own it." : "Who may do what on this box.", head!.w), style(c.mutedFg, c.bg), head!.x + head!.w);
217 drawList(s, list!, c, state, all.map((g) => ({ title: g.username, secondary: `${g.role}${g.service === "" ? " of the box" : ` of ${g.service}`}` })));
218 },
219 key(e) {
220 if (state.key(e, grantsOf(f.app.db, box.id).length)) return true;
221 if (e.ctrl || e.alt || e.key !== "a") return false;
222 if (!owner()) {
223 note = "Only an owner of this box sets grants.";
224 ctx.invalidate();
225 return true;
226 }
227 ctx.push(
228 promptScreen(ctx, screen, {
229 title: "Grant",
230 label: "user role [service] (role: owner, operator, viewer, or none to remove)",
231 onSubmit: (raw) => {
232 const [name = "", role = "", service = ""] = raw.trim().split(/\s+/);
233 const user = getUserByName(f.app.db, name);
234 if (user === undefined || !["owner", "operator", "viewer", "none"].includes(role) || (service !== "" && !SERVICE_NAME.test(service)))
235 return "Name an account, a role and, if any, a service.";
236 grant(f.app.db, box.id, user.id, role as Role | "none", service);
237 note = role === "none" ? `${user.username} no longer has that grant.` : `${user.username} is ${role}${service === "" ? "" : ` of ${service}`}.`;
238 ctx.invalidate();
239 return undefined;
240 },
241 }),
242 );
243 return true;
244 },
245 };
246 return screen;
247 }
248
249 /** Games: the services of the game boxes a person may see. */
250 export const entry: PaletteEntry = {
251 rank: 872,
252 id: "games",
253 title: "Games",
254 hint: "game servers on your cloud: state, start, stop, restart",
255 after: ["pinned"],
256 offered: (session) => session.user !== undefined,
257 run: (session, ctx) => ctx.push(gamesScreen(session, ctx)),
258 };
src/web/pages/games.ts added +429
@@ -0,0 +1,429 @@
1 /**
2 * `/games` (forge games): the game boxes a person may see, each box's network (one row a service,
3 * with Start, Stop and Restart), and a service's console (a live log over SSE and an RCON input),
4 * environment editor and plugins. Every route asks `roleOn` first: viewer reads, operator acts,
5 * owner (and every forge admin) also grants. Env and plugin changes are commits to the box's
6 * compose repository, so a merge redeploys and the crew can propose them too.
7 */
8
9 import { addPlugin, commitServiceEnv, composeServices, pluginsOf, readCompose, SECRET_KEY, serviceEnv } from "../../games/compose.ts";
10 import {
11 boxNamed,
12 COMMAND_KINDS,
13 commandOf,
14 grant,
15 grantsOf,
16 jarHref,
17 jarOf,
18 jarPath,
19 jarSignatureGood,
20 listBoxes,
21 logsOf,
22 mayDo,
23 queueCommand,
24 recentCommands,
25 roleOn,
26 seesBox,
27 SERVICE_NAME,
28 servicesOf,
29 storeJar,
30 dropJar,
31 type CommandKind,
32 type GameBox,
33 type Role,
34 } from "../../games/store.ts";
35 import { notePhase, takeSessionTime, timePhase } from "../../core/route_timing.ts";
36 import { getUserByName } from "../../core/users.ts";
37 import { BODY_CAPS } from "../../kernel/body_caps.ts";
38 import type { Ctx } from "../../http/context.ts";
39 import { eventStream } from "../../http/sse.ts";
40 import { notFoundPage, pageHead, signInFirst } from "../chrome.ts";
41 import { field, readForm, type Form } from "../form.ts";
42 import { html, type Html } from "../html.ts";
43 import { flashTo, page } from "../layout.ts";
44 import { badge, btn, field as input, row, rowList, time } from "../ui.ts";
45 import { onSync } from "../../games/notify.ts";
46 import { emptyLine } from "../empty_words.ts";
47
48 const dollars = (cents: number): string => `$${(cents / 100).toFixed(2)}`;
49 const mib = (n: number | undefined): string =>
50 n === undefined || n === 0 ? "?" : n >= 1024 ? `${(n / 1024).toFixed(1)} GiB` : `${Math.round(n)} MiB`;
51 const TONE: Record<string, "success" | "danger" | "default"> = { running: "success", exited: "danger", restarting: "danger" };
52
53 function boxOf(ctx: Ctx, need: Role, service = ""): { box: GameBox; role: Role } | Response {
54 if (!ctx.auth.user) return signInFirst(ctx);
55 const box = boxNamed(ctx.app.db, ctx.params.box ?? "");
56 if (box === undefined || !seesBox(ctx.app.db, ctx.auth.user, box.id)) return notFoundPage(ctx);
57 const role = roleOn(ctx.app.db, ctx.auth.user, box.id, service);
58 // Seeing the box's page needs a grant on any of it; acting on it, the role there.
59 if (service === "" && need === "viewer") return { box, role: role ?? "viewer" };
60 if (!mayDo(role, need)) return notFoundPage(ctx);
61 return { box, role: role! };
62 }
63
64 // GET /games
65 export function gamesPage(ctx: Ctx): Response {
66 notePhase(ctx.request, "session", takeSessionTime(ctx.request));
67 if (!ctx.auth.user) return signInFirst(ctx);
68 const user = ctx.auth.user;
69 const boxes = listBoxes(ctx.app.db).filter((b) => seesBox(ctx.app.db, user, b.id));
70 return timePhase(ctx.request, "render", () => page({
71 ctx,
72 title: "Games",
73 body: html`${pageHead("Games", { sub: "Game servers on your own cloud, run from a compose file in a repository." })}
74 ${boxes.length === 0
75 ? html`${emptyLine("gameBoxes")}${user.isAdmin ? html`<p><a href="/infra">Make one from Infra</a></p>` : null}`
76 : rowList(
77 boxes.map((b) =>
78 row({
79 href: `/games/${b.name}`,
80 title: b.name,
81 meta: html`${b.place || "no machine yet"} · ${dollars(b.monthlyCents)} a month · agent
82 ${b.seenAt === "" ? "never seen" : html`seen ${time(b.seenAt)}`} · host ${mib(b.host["memUsedMiB"])} of
83 ${mib(b.host["memMiB"])}`,
84 }),
85 ),
86 )}`,
87 }));
88 }
89
90 const power = (box: GameBox, service: string): Html =>
91 html`<span class="row-fields"
92 >${(["start", "stop", "restart"] as const).map(
93 (kind) =>
94 html`<form method="post" action="/games/${box.name}/${service}/power">
95 <input type="hidden" name="kind" value="${kind}" />${btn(kind[0]!.toUpperCase() + kind.slice(1), {
96 size: "sm",
97 variant: "ghost",
98 label: `${kind} ${service}`,
99 })}
100 </form>`,
101 )}</span
102 >`;
103
104 // GET /games/:box
105 export async function gameBoxPage(ctx: Ctx): Promise<Response> {
106 notePhase(ctx.request, "session", takeSessionTime(ctx.request));
107 const got = boxOf(ctx, "viewer");
108 if (got instanceof Response) return got;
109 const { box, role } = got;
110 const seen = servicesOf(ctx.app.db, box.id);
111 const compose = await readCompose(ctx.app, box);
112 const names = [...new Set([...seen.map((s) => s.name), ...(compose === undefined ? [] : composeServices(compose.text))])].sort();
113 const user = ctx.auth.user!;
114 const visible = names.filter((n) => mayDo(roleOn(ctx.app.db, user, box.id, n), "viewer"));
115 return timePhase(ctx.request, "render", () => page({
116 ctx,
117 title: `Games · ${box.name}`,
118 body: html`${pageHead(box.name, {
119 sub: `${box.repo}@${box.branch}:${box.path}${box.composeSha === "" ? "" : ` · running ${box.composeSha.slice(0, 10)}`}`,
120 })}
121 ${visible.length === 0
122 ? emptyLine("gameServices")
123 : rowList(
124 visible.map((n) => {
125 const s = seen.find((x) => x.name === n);
126 const act = mayDo(roleOn(ctx.app.db, user, box.id, n), "operator");
127 return row({
128 href: `/games/${box.name}/${n}`,
129 title: n,
130 trail: badge(s?.state || "unknown", { tone: TONE[s?.state ?? ""] ?? "default" }),
131 meta: html`${mib(s?.memMiB)} ·
132 ${s === undefined ? "" : `${s.cpuPct.toFixed(1)}% CPU`}${s?.startedAt ? html` · up since ${time(s.startedAt)}` : ""}`,
133 ...(act ? { after: power(box, n) } : {}),
134 });
135 }),
136 )}
137 ${role === "owner" ? grantsBlock(ctx, box) : null}`,
138 }));
139 }
140
141 function grantsBlock(ctx: Ctx, box: GameBox): Html {
142 const grants = grantsOf(ctx.app.db, box.id);
143 return html`<section class="settings-block">
144 <h2>Who may use ${box.name}</h2>
145 ${grants.length === 0
146 ? html`<p class="muted small">Only forge admins, so far.</p>`
147 : rowList(
148 grants.map((g) =>
149 row({ title: g.username, meta: html`${g.role}${g.service === "" ? " of the whole box" : ` of ${g.service}`}` }),
150 ),
151 )}
152 <form method="post" action="/games/${box.name}/grant" class="row-fields">
153 ${input({ name: "user", label: "Username", required: true })}
154 <select class="input" name="role" aria-label="Role">
155 <option value="operator">operator</option>
156 <option value="viewer">viewer</option>
157 <option value="owner">owner</option>
158 <option value="none">none (remove)</option>
159 </select>
160 ${input({ name: "service", label: "Service (empty for the whole box)" })} ${btn("Grant", { variant: "secondary" })}
161 </form>
162 </section>`;
163 }
164
165 /** The console's client: the live log over the page's own stream, appended in place. */
166 export const gamesConsoleJs = /* js */ `
167 (function () {
168 var log = document.getElementById('game-log');
169 if (!log || typeof EventSource === 'undefined') return;
170 var es = new EventSource(log.getAttribute('data-stream') + '?after=' + (log.getAttribute('data-last') || '0'));
171 es.addEventListener('lines', function (e) {
172 var d; try { d = JSON.parse(e.data); } catch (_) { return; }
173 var stick = log.scrollTop + log.clientHeight >= log.scrollHeight - 8;
174 (d.lines || []).forEach(function (l) { log.appendChild(document.createTextNode(l + '\\n')); });
175 if (stick) log.scrollTop = log.scrollHeight;
176 (d.results || []).forEach(function (r) {
177 var el = document.getElementById('cmd-' + r.id);
178 if (el) el.textContent = (r.ok ? 'ok: ' : 'failed: ') + r.output;
179 });
180 });
181 })();
182 `;
183
184 // GET /games/:box/:service
185 export async function gameServicePage(ctx: Ctx): Promise<Response> {
186 notePhase(ctx.request, "session", takeSessionTime(ctx.request));
187 const service = ctx.params.service ?? "";
188 const got = boxOf(ctx, "viewer", service);
189 if (got instanceof Response) return got;
190 const { box, role } = got;
191 if (!SERVICE_NAME.test(service)) return notFoundPage(ctx);
192 const act = mayDo(role, "operator");
193 const tail = logsOf(ctx.app.db, box.id, service, 300);
194 const compose = await readCompose(ctx.app, box);
195 const env = compose === undefined ? {} : serviceEnv(compose.text, service);
196 const plugins = compose === undefined ? { plugins: [], modrinth: [] } : pluginsOf(compose.text, service);
197 const commands = recentCommands(ctx.app.db, box.id, service, 5);
198 const base = `/games/${box.name}/${service}`;
199 return timePhase(ctx.request, "render", () => page({
200 ctx,
201 title: `${service} · ${box.name}`,
202 scriptJs: gamesConsoleJs,
203 body: html`${pageHead(service, { sub: `on ${box.name}`, actions: act ? power(box, service) : undefined })}
204 <section class="settings-block">
205 <h2>Console</h2>
206 <pre
207 id="game-log"
208 class="run-log mono"
209 tabindex="0"
210 aria-label="Console of ${service}"
211 data-stream="${base}/stream"
212 data-last="${String(tail.last)}"
213 >
214 ${tail.lines.join("\n")}${tail.lines.length > 0 ? "\n" : ""}</pre
215 >
216 ${act
217 ? html`<form method="post" action="${base}/command" class="row-fields">
218 <input
219 class="input mono"
220 name="text"
221 required
222 maxlength="1000"
223 placeholder="say hello"
224 aria-label="Command for ${service}"
225 autocomplete="off"
226 />
227 ${btn("Send", { variant: "secondary" })}
228 </form>`
229 : null}
230 ${commands.length === 0
231 ? null
232 : rowList(
233 commands.map((c) =>
234 row({
235 title: html`<span class="mono">${c.kind} ${c.text}</span>`,
236 meta: html`<span id="cmd-${c.id}"
237 >${c.done ? `${c.ok ? "ok" : "failed"}: ${c.output}` : c.handed ? "sent to the box" : "queued"}</span
238 >`,
239 }),
240 ),
241 )}
242 </section>
243 <section class="settings-block">
244 <h2>Environment</h2>
245 ${Object.keys(env).length === 0
246 ? html`<p class="muted small">None set in ${box.path}.</p>`
247 : rowList(
248 Object.entries(env).map(([k, v]) =>
249 row({
250 title: html`<span class="mono">${k}</span>`,
251 meta: html`<span class="mono">${SECRET_KEY.test(k) ? "(hidden)" : v}</span>`,
252 }),
253 ),
254 )}
255 ${act
256 ? html`<form method="post" action="${base}/env" class="row-fields">
257 ${input({ name: "key", label: "Key", required: true, mono: true })}
258 ${input({ name: "value", label: "Value (empty removes it)", mono: true })} ${btn("Commit", { variant: "secondary" })}
259 </form>`
260 : null}
261 </section>
262 <section class="settings-block">
263 <h2>Plugins</h2>
264 ${plugins.plugins.length + plugins.modrinth.length === 0
265 ? emptyLine("gamePlugins")
266 : rowList([
267 ...plugins.modrinth.map((m) => row({ title: m, meta: html`Modrinth` })),
268 ...plugins.plugins.map((p) => row({ title: html`<span class="mono">${p}</span>`, meta: html`jar URL` })),
269 ])}
270 ${act
271 ? html`<form method="post" action="${base}/plugin" class="row-fields">
272 ${input({ name: "modrinth", label: "Modrinth slug", required: true, mono: true })} ${btn("Add", { variant: "secondary" })}
273 </form>
274 <form method="post" action="${base}/jar" enctype="multipart/form-data" class="row-fields">
275 <input class="input" type="file" name="jar" accept=".jar" required aria-label="Plugin jar" />
276 ${btn("Upload jar", { variant: "secondary" })}
277 </form>`
278 : null}
279 </section>`,
280 }));
281 }
282
283 // GET /games/:box/:service/stream: new log lines and command results after each sync.
284 export function gameServiceStream(ctx: Ctx): Response {
285 const service = ctx.params.service ?? "";
286 const got = boxOf(ctx, "viewer", service);
287 if (got instanceof Response) return got;
288 const { box } = got;
289 let after = Number(ctx.url.searchParams.get("after") ?? "0") || 0;
290 const pending = new Set(
291 recentCommands(ctx.app.db, box.id, service, 10)
292 .filter((c) => !c.done)
293 .map((c) => c.id),
294 );
295 return eventStream(ctx.app, ctx.request, (emit, _close, ready) =>
296 onSync(ctx.app, box.id, () => {
297 if (!ready()) return;
298 const got = logsOf(ctx.app.db, box.id, service, 500, after);
299 after = got.last;
300 for (const c of recentCommands(ctx.app.db, box.id, service, 10)) if (!c.done) pending.add(c.id);
301 const results = [...pending].map((id) => commandOf(ctx.app.db, id)).filter((c) => c !== undefined && c.done);
302 for (const r of results) pending.delete(r!.id);
303 if (got.lines.length > 0 || results.length > 0)
304 emit("lines", { lines: got.lines, results: results.map((r) => ({ id: r!.id, ok: r!.ok, output: r!.output })) });
305 }),
306 );
307 }
308
309 async function operatorForm(ctx: Ctx): Promise<{ box: GameBox; service: string; form: Form } | Response> {
310 const service = ctx.params.service ?? "";
311 const got = boxOf(ctx, "operator", service);
312 if (got instanceof Response) return got;
313 if (!SERVICE_NAME.test(service)) return notFoundPage(ctx);
314 const form = await readForm(ctx, "rw");
315 if (form instanceof Response) return form;
316 return { box: got.box, service, form };
317 }
318
319 // POST /games/:box/:service/command: an RCON command, queued for the box's next sync.
320 export async function gameCommandSubmit(ctx: Ctx): Promise<Response> {
321 const got = await operatorForm(ctx);
322 if (got instanceof Response) return got;
323 const text = field(got.form, "text").trim();
324 if (text === "") return flashTo(ctx, `/games/${got.box.name}/${got.service}`, { tone: "danger", message: "Type a command." });
325 queueCommand(ctx.app.db, got.box.id, got.service, "rcon", text, ctx.auth.user!.id);
326 return flashTo(ctx, `/games/${got.box.name}/${got.service}`, { message: "Sent; the answer shows under the console." });
327 }
328
329 // POST /games/:box/:service/power
330 export async function gamePowerSubmit(ctx: Ctx): Promise<Response> {
331 const got = await operatorForm(ctx);
332 if (got instanceof Response) return got;
333 const kind = field(got.form, "kind") as CommandKind;
334 if (
335 !(["start", "stop", "restart", "recreate", "pull"] as readonly string[]).includes(kind) ||
336 !(COMMAND_KINDS as readonly string[]).includes(kind)
337 )
338 return notFoundPage(ctx);
339 queueCommand(ctx.app.db, got.box.id, got.service, kind, "", ctx.auth.user!.id);
340 return flashTo(ctx, `/games/${got.box.name}`, { message: `${kind} ${got.service}: asked; the box does it on its next sync.` });
341 }
342
343 // POST /games/:box/:service/env: one key, committed to the compose file.
344 export async function gameEnvSubmit(ctx: Ctx): Promise<Response> {
345 const got = await operatorForm(ctx);
346 if (got instanceof Response) return got;
347 const key = field(got.form, "key").trim();
348 const value = field(got.form, "value");
349 const done = await commitServiceEnv(ctx.app, ctx.auth.user!, got.box, got.service, { [key]: value === "" ? null : value });
350 return flashTo(
351 ctx,
352 `/games/${got.box.name}/${got.service}`,
353 done.ok
354 ? { message: `Committed ${done.sha.slice(0, 10)}; the box redeploys on its next sync.` }
355 : { tone: "danger", message: done.error },
356 );
357 }
358
359 // POST /games/:box/:service/plugin: a Modrinth slug.
360 export async function gamePluginSubmit(ctx: Ctx): Promise<Response> {
361 const got = await operatorForm(ctx);
362 if (got instanceof Response) return got;
363 const done = await addPlugin(ctx.app, ctx.auth.user!, got.box, got.service, { modrinth: field(got.form, "modrinth").trim() });
364 return flashTo(
365 ctx,
366 `/games/${got.box.name}/${got.service}`,
367 done.ok ? { message: `Committed ${done.sha.slice(0, 10)}.` } : { tone: "danger", message: done.error },
368 );
369 }
370
371 // POST /games/:box/:service/jar: an uploaded plugin jar, kept here and added to PLUGINS.
372 export async function gameJarSubmit(ctx: Ctx): Promise<Response> {
373 const service = ctx.params.service ?? "";
374 const got = boxOf(ctx, "operator", service);
375 if (got instanceof Response) return got;
376 const form = await readForm(ctx, "rw", BODY_CAPS.gameJar.bytes);
377 if (form instanceof Response) return form;
378 const file = form.get("jar");
379 if (!(file instanceof File) || file.size === 0)
380 return flashTo(ctx, `/games/${got.box.name}/${service}`, { tone: "danger", message: "Choose a .jar file." });
381 const jar = await storeJar(ctx.app, got.box.id, file, file.name);
382 if (!jar.ok) return flashTo(ctx, `/games/${got.box.name}/${service}`, { tone: "danger", message: jar.error });
383 const done = await addPlugin(ctx.app, ctx.auth.user!, got.box, service, { url: `${ctx.url.origin}${jarHref(jar)}` });
384 if (!done.ok) await dropJar(ctx.app, jar.id);
385 return flashTo(
386 ctx,
387 `/games/${got.box.name}/${service}`,
388 done.ok
389 ? { message: `${jar.name} is kept here and added to PLUGINS (${done.sha.slice(0, 10)}).` }
390 : { tone: "danger", message: done.error },
391 );
392 }
393
394 // POST /games/:box/grant: an owner grants or removes a role.
395 export async function gameGrantSubmit(ctx: Ctx): Promise<Response> {
396 const got = boxOf(ctx, "owner");
397 if (got instanceof Response) return got;
398 const form = await readForm(ctx, "rw");
399 if (form instanceof Response) return form;
400 const user = getUserByName(ctx.app.db, field(form, "user").trim());
401 const role = field(form, "role") as Role | "none";
402 const service = field(form, "service").trim();
403 if (user === undefined || !["owner", "operator", "viewer", "none"].includes(role) || (service !== "" && !SERVICE_NAME.test(service)))
404 return flashTo(ctx, `/games/${got.box.name}`, { tone: "danger", message: "Name an account, a role and, if any, a service." });
405 grant(ctx.app.db, got.box.id, user.id, role, service);
406 return flashTo(ctx, `/games/${got.box.name}`, {
407 message:
408 role === "none"
409 ? `${user.username} no longer has that grant.`
410 : `${user.username} is ${role}${service === "" ? "" : ` of ${service}`}.`,
411 });
412 }
413
414 // GET /games/jar/:id/:name?e=&s=: a kept jar, for the box's image to download while the signature is good.
415 export async function gameJarDownload(ctx: Ctx): Promise<Response> {
416 const jar = jarOf(ctx.app.db, ctx.params.id ?? "");
417 if (jar === undefined || jar.name !== ctx.params.name) return new Response("not found", { status: 404 });
418 if (!jarSignatureGood(ctx.app, jar.id, ctx.url.searchParams.get("e") ?? "", ctx.url.searchParams.get("s") ?? ""))
419 return new Response("this link has expired or is not signed", { status: 403 });
420 const file = Bun.file(jarPath(ctx.app, jar.id));
421 if (!(await file.exists())) return new Response("not found", { status: 404 });
422 return new Response(file, {
423 headers: {
424 "content-type": "application/java-archive",
425 "content-disposition": `attachment; filename="${jar.name}"`,
426 "cache-control": "private, no-store",
427 },
428 });
429 }
test/behaviors-rule.test.ts +1
@@ -48,6 +48,7 @@ const OWN_SCRIPT = new Set([
4848 "src/web/pages/fleet-graph.ts",
4949 "src/web/pages/flow.ts",
5050 "src/web/pages/flows.ts",
51 "src/web/pages/games.ts",
5152 "src/web/pages/global-map.ts",
5253 "src/web/pages/home_flow.ts",
5354 "src/web/pages/iterations.ts",
test/conversation-ask.test.ts +4
@@ -517,6 +517,10 @@ const SAID: readonly (readonly [string, Record<string, unknown>, string])[] = [
517517 ["wall", { repo: "marin/cakes", number: 2, answer: "send_back" }, "Send pull #2 in marin/cakes back at the access wall."],
518518 ["infra", { action: "apply", id: "plan-0123456789abcdef" }, "Build the infrastructure plan plan-0123456789abcdef on your own cloud: it spends money each month."],
519519 ["infra", { action: "apply", id: "plan-0123456789abcdef", names: ["canary1", "trevato"] }, "Clear the dead rows canary1, trevato: nothing exists at the provider for them, so only the forge's rows go and nothing is deleted there."],
520 ["games", { action: "power", box: "net", service: "hub", kind: "restart" }, "Restart hub on net."],
521 ["games", { action: "console", box: "net", service: "hub", text: "say hi" }, 'Run "say hi" in the console of hub on net.'],
522 ["games", { action: "env", box: "net", service: "hub", key: "MOTD", value: "Hello" }, "Set MOTD on hub on net to Hello, a commit that redeploys it."],
523 ["games", { action: "plugin", box: "net", service: "survival", modrinth: "waystones" }, "Add the plugin waystones to survival on net, a commit that redeploys it."],
520524 ["crew_accounts", { repo: "marin/cakes", allow: "espo-corp" }, "Let the crew's runs for marin/cakes spend the account espo-corp."],
521525 ["subscriptions", { everywhere: "espo-corp" }, "Put the account espo-corp in the pool, so the crew uses it by default on every repository a forge admin owns."],
522526 ["subscriptions", { limit: "espo-corp" }, "Keep the account espo-corp to where it is allowed."],
test/design-audit.test.ts +1 −1
@@ -10,7 +10,7 @@ import { expect, test } from "bun:test";
1010 import { readFileSync } from "node:fs";
1111
1212 // The settings routes register from their own module (#8309), so both are read.
13 const server = ["src/http/server.ts", "src/http/settings_routes.ts", "src/http/forges_routes.ts"]
13 const server = ["src/http/server.ts", "src/http/settings_routes.ts", "src/http/forges_routes.ts", "src/http/games_routes.ts"]
1414 .map((file) => readFileSync(file, "utf8"))
1515 .join("\n");
1616 const doc = readFileSync("docs/design/audit.md", "utf8");
test/forge-looks.test.ts +1
@@ -38,6 +38,7 @@ const NOT_A_PAGE: Record<string, string> = {
3838 "/pinned": "no picture: its slot went to /settings/crew, the crew page; covered by test/pinned-page.test.ts",
3939 "/dataset": "no picture: not in app.looks; admin only, a guest sees the not-found page, and the page is covered by test/dataset.test.ts",
4040 "/infra": "no picture: app.looks is at its 32 paths; an admin's view of their own cloud, screenshotted at 390 and 1280 in #16706 and covered by test/infra-page.test.ts",
41 "/games": "no picture: not in app.looks; a game box's network, seen only with a grant on a box, covered by test/games.test.ts",
4142 "/data": "no picture: not in app.looks; a guest sees the not-found page and the page is covered by its own tests",
4243 "/asked": "no picture: its slot went to /notes, the page that now leads with a person's thoughts; /asked is covered by test/asked.test.ts",
4344 "/forges": "no picture: its slot went to the preview's /waves and /milestones; the page is covered by its own tests",
test/game-box.test.ts added +245
@@ -0,0 +1,245 @@
1 /**
2 * Game boxes (forge games, 2026-11-30): the boot config carries the agent, opens only 25565/tcp and
3 * holds the token in the env file alone; the token is kept hashed and rotates with each machine; the plan for a box costs what the catalog says and waits for no https answer; and
4 * the agent passes `bash -n` and does one whole sync against a stand-in forge with a fake docker:
5 * it reports the services, stats, logs and host in the contract's shape, writes the compose file
6 * and the env file (mode 600), brings the project up, runs an rcon command, and sends its result
7 * on the next sync.
8 */
9 import { afterAll, beforeAll, describe, expect, test } from "bun:test";
10 import { chmodSync, existsSync, mkdtempSync, readFileSync, statSync, writeFileSync } from "node:fs";
11 import { rm } from "node:fs/promises";
12 import { tmpdir } from "node:os";
13 import { join } from "node:path";
14 import { createApp, type App } from "../src/app.ts";
15 import { gameWant, planWants } from "../src/actions/infra.ts";
16 import { readPlaces } from "../src/cloud/places_read.ts";
17 import { bootConfig } from "../src/cloud/droplet.ts";
18 import { insertPinned } from "../src/core/pinned.ts";
19 import { createUser, type User } from "../src/core/users.ts";
20 import { AGENT_SH, GAME_PORT, gameBootConfig } from "../src/games/boot.ts";
21 import { boxByToken, boxNamed, createGameBox, rotateGameBoxToken } from "../src/games/store.ts";
22 import { sha256 } from "../src/kernel/hash.ts";
23
24 const AGENT = join(import.meta.dir, "../src/games/agent.sh");
25 const TOKEN = "fgb_abcdefghijklmnopqrstuvwxyz0123456789ABCDEFG";
26
27 describe("the boot config", () => {
28 const cfg = gameBootConfig({ forgeUrl: "https://forge.example", token: TOKEN }, "/mnt/forge_box_data");
29
30 test("carries the agent and its unit, Docker with compose, and swap", () => {
31 expect(cfg.startsWith("#cloud-config\n")).toBe(true);
32 expect(cfg).toContain(`path: /opt/forge-game/agent.sh\n permissions: "0755"\n content: ${JSON.stringify(AGENT_SH)}`);
33 expect(cfg).toContain("path: /etc/systemd/system/forge-game-agent.service");
34 expect(cfg).toContain("systemctl enable --now forge-game-agent.service");
35 for (const pkg of ["docker.io", "docker-compose-v2", "jq", "curl", "ufw"]) expect(cfg).toContain(` - ${pkg}\n`);
36 expect(cfg).toContain('{\\"data-root\\":\\"/mnt/forge_box_data/docker\\"');
37 expect(cfg).toContain("mkswap /swapfile");
38 });
39
40 test("opens only the game's port: no SSH, no backend, no web", () => {
41 const allowed = cfg.split("\n").filter((l) => l.includes("ufw allow"));
42 expect(allowed).toEqual([` - ufw allow ${GAME_PORT}/tcp`]);
43 expect(cfg).toContain("ufw default deny incoming");
44 expect(cfg).toContain("PasswordAuthentication no");
45 });
46
47 test("the token is in the env file alone, mode 600", () => {
48 expect(cfg.split(TOKEN)).toHaveLength(2);
49 expect(cfg).toContain(
50 `path: /opt/forge-game/agent.env\n permissions: "0600"\n content: "FORGE_URL=https://forge.example\\nFORGE_GAME_TOKEN=${TOKEN}\\n"`,
51 );
52 expect(AGENT_SH).not.toContain("forge_game_a");
53 });
54
55 test("a droplet's boot is the game box's when its row carries one, a forge's otherwise", () => {
56 const row = {
57 name: "box1",
58 source: "https://forge.example/trevato/forge.git",
59 version: "v1.0.0",
60 config: {},
61 host: "box1.example.com",
62 claimHash: "",
63 claimExpires: "",
64 };
65 expect(bootConfig({ ...row, game: { forgeUrl: "https://forge.example", token: TOKEN } })).toContain("forge-game-agent.service");
66 expect(bootConfig(row)).not.toContain("forge-game-agent");
67 });
68
69 test("refuses a plain-http forge and a token of the wrong shape", () => {
70 expect(() => gameBootConfig({ forgeUrl: "http://forge.example", token: TOKEN }, "/mnt/x")).toThrow("https");
71 expect(() => gameBootConfig({ forgeUrl: "https://forge.example", token: "nope" }, "/mnt/x")).toThrow("token");
72 });
73 });
74
75 describe("on a forge", () => {
76 let dir = "";
77 let app: App;
78 let alice: User;
79
80 beforeAll(async () => {
81 dir = mkdtempSync(join(tmpdir(), "forge-game-box-"));
82 app = createApp({ dataDir: dir, port: 0, url: "https://forge.example" });
83 const made = await createUser(app.db, {
84 origin: "seed",
85 trusted: true,
86 username: "alice",
87 email: "[email protected]",
88 password: "a-good-passphrase",
89 adminIfFirst: true,
90 });
91 if (!made.ok) throw new Error(made.error);
92 alice = made.value;
93 const json = (o: unknown): Response => new Response(JSON.stringify(o), { status: 200 });
94 const sizes = [
95 { slug: "s-4vcpu-8gb", memory: 8192, vcpus: 4, disk: 160, transfer: 5, price_monthly: 48, available: true, regions: ["nyc3"] },
96 ];
97 await readPlaces(
98 app.db,
99 "digitalocean",
100 async (url) => json(String(url).includes("/sizes") ? { sizes } : { regions: [{ slug: "nyc3", available: true }] }),
101 "t",
102 );
103 app.db.run(
104 "INSERT INTO cloud_account (provider, name, summary, write_allowed, ceiling_dollars) VALUES ('digitalocean', 'main', '', 1, 50)",
105 );
106 });
107 afterAll(async () => {
108 app.close();
109 await rm(dir, { recursive: true, force: true });
110 });
111
112 test("a new machine's token replaces the old: kept as its hash, the old one refused", () => {
113 insertPinned(app.db, { name: "box1", target: "digitalocean", account: "main", app: "trevato/mc-network", source: "", version: "v1", config: {}, host: "", claimHash: "", claimExpires: "", datacenter: "nyc3", size: "s-4vcpu-8gb" }, alice.id);
114 const { id, token } = createGameBox(app.db, { name: "box1" });
115 expect(boxNamed(app.db, "box1")).toMatchObject({ id, name: "box1", repo: "trevato/mc-network" });
116 expect(boxByToken(app.db, token)?.name).toBe("box1");
117 const next = rotateGameBoxToken(app.db, id);
118 expect(next).toMatch(/^fgb_[A-Za-z0-9_-]{43}$/);
119 expect(app.db.query<{ h: string }, []>("SELECT token_hash AS h FROM game_box").get()!.h).toBe(sha256(next));
120 expect(JSON.stringify(app.db.query("SELECT * FROM game_box").all())).not.toContain(next);
121 expect(boxByToken(app.db, token)).toBeUndefined();
122 expect(boxByToken(app.db, next)?.name).toBe("box1");
123 expect(boxNamed(app.db, "nobox")).toBeUndefined();
124 // The boot config takes the token the store makes.
125 expect(gameBootConfig({ forgeUrl: "https://forge.example", token: next }, "/mnt/x")).toContain(next);
126 });
127
128 test("a game box's plan costs what the catalog says, never ends, and waits for no https answer", () => {
129 const want = gameWant({ name: "mc", where: "digitalocean/main@digitalocean:nyc3:s-4vcpu-8gb", host: "mc.trevato.dev" });
130 if (!want.ok) throw new Error(want.error);
131 expect(want.value).toMatchObject({ game: true, app: "trevato/mc-network", host: "mc.trevato.dev" });
132 const planned = planWants(app, alice, [want.value]);
133 if (!planned.ok) throw new Error(planned.error);
134 const p = planned.value.plan;
135 expect(p.refusals).toEqual([]);
136 // $48 the machine and $1 its disk: under the $50 ceiling.
137 expect(p.deltaCents).toBe(4_900);
138 const machine = p.steps.find((s) => s.kind === "machine")!;
139 expect(machine.says).toBe("Start a 4 vCPU, 8 GB game box in New York running trevato/mc-network's compose file, with no end");
140 expect(p.steps.some((s) => s.kind === "ready")).toBe(false);
141 expect(gameWant({ name: "mc", where: "nowhere" }).ok).toBe(false);
142 });
143 });
144
145 describe("the agent", () => {
146 test("passes bash -n", () => {
147 expect(Bun.spawnSync(["bash", "-n", AGENT]).exitCode).toBe(0);
148 });
149
150 // The agent's own tools, which the box installs; a machine without them cannot run it.
151 const lacks = ["bash", "curl", "jq"].filter((t) => Bun.which(t) === null);
152 test.skipIf(lacks.length > 0)(`one sync against a stand-in forge with a fake docker: reports, deploys, runs a command, and reports its result${lacks.length > 0 ? ` (skipped: no ${lacks.join(", ")} here)` : ""}`, async () => {
153 const box = mkdtempSync(join(tmpdir(), "forge-game-agent-"));
154 const calls = join(box, "docker-calls");
155 // A docker that answers ps, stats and logs as the real one does, and records every call.
156 const fake = join(box, "docker");
157 writeFileSync(
158 fake,
159 `#!/usr/bin/env bash
160 echo "$*" >> "${calls}"
161 case "$*" in
162 *" ps -a --format json") echo '{"Service":"hub","Name":"hub","State":"running","Health":"healthy","CreatedAt":"2026-11-30 23:00:00"}'; echo '{"Service":"lobby","Name":"lobby","State":"exited","Health":"","CreatedAt":"x"}' ;;
163 "stats --no-stream --format json") echo '{"Name":"hub","CPUPerc":"12.5%","MemUsage":"812MiB / 7.8GiB"}'; echo '{"Name":"lobby","CPUPerc":"0.00%","MemUsage":"1.5GiB / 7.8GiB"}' ;;
164 *" logs --no-color --since "*) printf 'hub | [Server] Done (3.2s)!\\nlobby | joined the game\\nhub | second line\\n' ;;
165 *" exec -T hub rcon-cli -- say hi") echo "said hi" ;;
166 esac
167 `,
168 );
169 chmodSync(fake, 0o755);
170 const bodies: Record<string, any>[] = [];
171 let auth = "";
172 const forge = Bun.serve({
173 port: 0,
174 hostname: "127.0.0.1",
175 async fetch(req) {
176 auth = req.headers.get("authorization") ?? "";
177 const body = (await req.json()) as Record<string, any>;
178 bodies.push(body);
179 return Response.json(
180 bodies.length === 1
181 ? {
182 composeSha: "abc",
183 compose: "services:\n hub:\n image: itzg/mc-proxy\n",
184 env: { ".env": "FORWARDING_SECRET=s3cret\n", "agent.env": "FORGE_URL=https://evil.example\n", ".auth": "no", "velocity.env": "no", "../escape.env": "no" },
185 commands: [{ id: "c1", kind: "rcon", service: "hub", text: "say hi" }],
186 }
187 : { composeSha: "abc", commands: [] },
188 );
189 },
190 });
191 try {
192 let said = "";
193 const run = async () => {
194 const p = Bun.spawn(["bash", AGENT], {
195 env: {
196 PATH: process.env["PATH"] ?? "",
197 FORGE_URL: `http://127.0.0.1:${String(forge.port)}`,
198 FORGE_GAME_TOKEN: TOKEN,
199 FORGE_GAME_DIR: box,
200 FORGE_GAME_DOCKER: fake,
201 FORGE_GAME_ONCE: "1",
202 },
203 stdout: "pipe",
204 stderr: "pipe",
205 });
206 const code = await p.exited;
207 said = await new Response(p.stderr).text();
208 return code;
209 };
210 expect(await run()).toBe(0);
211 // What the agent said goes with any failure, so a machine that differs says how.
212 expect(bodies.length, `the agent sent nothing; it said: ${said}`).toBe(1);
213 expect(auth).toBe(`Bearer ${TOKEN}`);
214 const first = bodies[0]!;
215 expect(first).toMatchObject({ agent: 1, composeSha: "", results: [] });
216 expect(first["services"]).toEqual([
217 { name: "hub", state: "running", health: "healthy", startedAt: "2026-11-30 23:00:00", cpuPct: 12.5, memMiB: 812 },
218 { name: "lobby", state: "exited", health: "", startedAt: "x", cpuPct: 0, memMiB: 1536 },
219 ]);
220 expect(first["logs"]).toEqual({ hub: ["[Server] Done (3.2s)!", "second line"], lobby: ["joined the game"] });
221 expect(Object.keys(first["host"]).sort()).toEqual(["diskFreeGiB", "load1", "memMiB", "memUsedMiB"]);
222 // What the answer asked: the compose file and the env file (600), the project up, the rcon.
223 expect(readFileSync(join(box, "compose.yml"), "utf8")).toBe("services:\n hub:\n image: itzg/mc-proxy\n");
224 // Only `.env` is written (600); every other name is ignored and said, the agent's own files untouched.
225 expect(readFileSync(join(box, ".env"), "utf8")).toBe("FORWARDING_SECRET=s3cret\n");
226 expect(statSync(join(box, ".env")).mode & 0o777).toBe(0o600);
227 for (const bad of ["agent.env", "velocity.env"]) expect(existsSync(join(box, bad))).toBe(false);
228 expect(existsSync(join(box, "..", "escape.env"))).toBe(false);
229 expect(readFileSync(join(box, ".auth"), "utf8")).toBe(`Authorization: Bearer ${TOKEN}\n`);
230 expect(said).toContain("ignored env file agent.env: only .env is written");
231 expect(readFileSync(join(box, ".compose-sha"), "utf8")).toBe("abc");
232 const called = readFileSync(calls, "utf8");
233 expect(called).toContain(`compose -p game --project-directory ${box} -f ${box}/compose.yml up -d --remove-orphans`);
234 expect(called).toContain(`compose -p game --project-directory ${box} -f ${box}/compose.yml exec -T hub rcon-cli -- say hi`);
235 // The next sync carries the command's result; the token never sat on a command line.
236 expect(await run()).toBe(0);
237 expect(bodies[1]!).toMatchObject({ composeSha: "abc", results: [{ id: "c1", ok: true, output: "said hi" }] });
238 expect(called).not.toContain(TOKEN);
239 expect(statSync(join(box, ".auth")).mode & 0o777).toBe(0o600);
240 } finally {
241 forge.stop(true);
242 await rm(box, { recursive: true, force: true });
243 }
244 });
245 });
test/games.test.ts added +239
@@ -0,0 +1,239 @@
1 /**
2 * Forge games: the agent's sync round trip (status, logs, results in; compose, env files and
3 * queued commands out), a command handed out once, an env change committed to the compose repo,
4 * the plugin jar's signed and expiring URL, and grants (an operator of one service is refused
5 * another). In-process (`forgeHttp`), no socket.
6 */
7 import { afterAll, beforeAll, describe, expect, test } from "bun:test";
8 import { mkdtemp, rm } from "node:fs/promises";
9 import { tmpdir } from "node:os";
10 import { join } from "node:path";
11 import { commitToBranch, createRepo } from "../src/actions/repos.ts";
12 import { createApp, type App } from "../src/app.ts";
13 import { getRepo } from "../src/core/repos.ts";
14 import { createToken } from "../src/core/tokens.ts";
15 import { createUser, getUserByName, type User } from "../src/core/users.ts";
16 import { commitServiceEnv, readCompose, serviceEnv, setServiceEnv } from "../src/games/compose.ts";
17 import {
18 boxNamed,
19 commandOf,
20 createGameBox,
21 grant,
22 JAR_URL_MS,
23 jarSignatureGood,
24 logsOf,
25 queueCommand,
26 servicesOf,
27 signedJarHref,
28 signJarUrls,
29 dropJar,
30 storeJar,
31 rotateGameBoxToken,
32 setGameBoxMachine,
33 } from "../src/games/store.ts";
34 import { forgeHttp, type ForgeHttp } from "../src/http/server.ts";
35 import { quietLogs } from "./helpers/globals.ts";
36
37 quietLogs();
38
39 const ORIGIN = "http://forge.test";
40 const COMPOSE = `services:
41 proxy:
42 image: itzg/mc-proxy
43 container_name: proxy
44 environment:
45 TYPE: VELOCITY
46 hub:
47 image: itzg/minecraft-server
48 container_name: hub
49 environment:
50 TYPE: PAPER
51 MOTD: "hello"
52 RCON_PASSWORD: \${RCON_HUB}
53 lobby:
54 image: itzg/minecraft-server
55 container_name: lobby
56 environment:
57 - TYPE=PAPER
58 - RCON_PASSWORD=\${RCON_LOBBY}
59 `;
60
61 describe("forge games", () => {
62 let dataDir = "";
63 let app: App;
64 let http: ForgeHttp;
65 let alice: User;
66 let token = "";
67 let bobTok = "";
68 const sync = (body: unknown, bearer = token) =>
69 http.handle(
70 new Request(`${ORIGIN}/api/v1/games/agent/sync`, {
71 method: "POST",
72 headers: { authorization: `Bearer ${bearer}`, "content-type": "application/json" },
73 body: JSON.stringify(body),
74 }),
75 );
76 const asBob = (path: string, form?: Record<string, string>) =>
77 http.handle(
78 new Request(
79 ORIGIN + path,
80 form === undefined
81 ? { headers: { authorization: `Bearer ${bobTok}` } }
82 : {
83 method: "POST",
84 headers: { authorization: `Bearer ${bobTok}`, origin: ORIGIN, "content-type": "application/x-www-form-urlencoded" },
85 body: new URLSearchParams(form),
86 },
87 ),
88 );
89
90 beforeAll(async () => {
91 dataDir = await mkdtemp(join(tmpdir(), "forge-games-"));
92 app = createApp({ dataDir, port: 0 });
93 http = forgeHttp(app);
94 for (const [username, adminIfFirst] of [
95 ["alice", true],
96 ["bob", false],
97 ] as const) {
98 const made = await createUser(app.db, {
99 origin: "seed",
100 trusted: true,
101 username,
102 email: `${username}@f.test`,
103 password: "a-good-passphrase",
104 adminIfFirst,
105 });
106 if (!made.ok) throw new Error(made.error);
107 }
108 alice = getUserByName(app.db, "alice")!;
109 bobTok = createToken(app.db, getUserByName(app.db, "bob")!.id, "rw", "rw").token;
110 const repo = await createRepo(app, alice, { name: "mc-network", visibility: "private" });
111 if (!repo.ok) throw new Error(String(repo.error));
112 const seeded = await commitToBranch(app, alice, repo.value, {
113 message: "network",
114 files: [{ path: "docker-compose.yml", content: COMPOSE }],
115 });
116 if (!seeded.ok) throw new Error(JSON.stringify(seeded.error));
117 token = createGameBox(app.db, { name: "net", repo: "alice/mc-network" }).token;
118 }, 30_000);
119
120 afterAll(async () => {
121 app.close();
122 await rm(dataDir, { recursive: true, force: true });
123 });
124
125 test("a sync stores status and logs, and answers the compose, its sha and the sealed env files", async () => {
126 expect((await sync({ agent: 1 }, "fgb_wrong")).status).toBe(401);
127 const r = await sync({
128 agent: 1,
129 composeSha: "",
130 services: [{ name: "hub", state: "running", health: "healthy", startedAt: "2026-11-30T23:00:00Z", cpuPct: 1.5, memMiB: 812 }],
131 logs: { hub: ["[Server] Done", "[Server] hello"] },
132 host: { memMiB: 7900, memUsedMiB: 5100 },
133 });
134 expect(r.status).toBe(200);
135 const got = (await r.json()) as { composeSha: string; compose?: string; env: Record<string, string>; commands: unknown[] };
136 const compose = await readCompose(app, boxNamed(app.db, "net")!);
137 expect(got.composeSha).toBe(compose!.sha);
138 expect(got.compose).toContain("itzg/mc-proxy");
139 expect(Object.keys(got.env)).toEqual([".env"]);
140 // Every service gets an RCON key (proxy too), each ${RCON_…} the compose names among them.
141 expect(got.env[".env"]).toMatch(/^FORWARDING_SECRET=[0-9a-f]{64}\nRCON_HUB=[0-9a-f]{64}\nRCON_LOBBY=[0-9a-f]{64}\nRCON_PROXY=[0-9a-f]{64}\n$/);
142 expect(got.commands).toEqual([]);
143 const box = boxNamed(app.db, "net")!;
144 expect(servicesOf(app.db, box.id)[0]).toMatchObject({ name: "hub", state: "running", memMiB: 812 });
145 expect(logsOf(app.db, box.id, "hub").lines).toEqual(["[Server] Done", "[Server] hello"]);
146 expect(box.host["memMiB"]).toBe(7900);
147 // The same secrets every time, and no compose once the box runs this sha.
148 const again = (await (await sync({ agent: 1, composeSha: got.composeSha })).json()) as {
149 compose?: string;
150 env: Record<string, string>;
151 };
152 expect(again.compose).toBeUndefined();
153 expect(again.env[".env"]).toBe(got.env[".env"]);
154 });
155
156 test("a rotated token ends the old one, and a retired machine's box is refused", async () => {
157 const spare = createGameBox(app.db, { name: "spare", repo: "alice/mc-network" });
158 const next = rotateGameBoxToken(app.db, spare.id);
159 expect((await sync({ agent: 1 }, spare.token)).status).toBe(401);
160 expect((await sync({ agent: 1 }, next)).status).toBe(200);
161 app.db.query("INSERT INTO pinned_forge (id, name, target, account, app, source, version, config, change_id, created_at, state) VALUES ('p-spare', 'spare', 'digitalocean', 'main', 'a/b', 's', 'v', '{}', 0, '2026-11-30', 'retired')").run();
162 setGameBoxMachine(app.db, spare.id, { pinnedId: "p-spare", place: "", monthlyCents: 0 });
163 expect((await sync({ agent: 1 }, next)).status).toBe(401);
164 });
165
166 test("a queued command is handed out once, and its result is kept", async () => {
167 const box = boxNamed(app.db, "net")!;
168 const id = queueCommand(app.db, box.id, "hub", "rcon", "say hi", alice.id);
169 const first = (await (await sync({ agent: 1 })).json()) as { commands: { id: string; kind: string; service: string; text: string }[] };
170 expect(first.commands).toEqual([{ id, kind: "rcon", service: "hub", text: "say hi" }]);
171 const second = (await (await sync({ agent: 1, results: [{ id, ok: true, output: "[Server] hi" }] })).json()) as { commands: unknown[] };
172 expect(second.commands).toEqual([]);
173 expect(commandOf(app.db, id)).toMatchObject({ handed: true, done: true, ok: true, output: "[Server] hi" });
174 });
175
176 test("an env change is a commit to the compose file, and both environment forms are kept", async () => {
177 expect(serviceEnv(setServiceEnv(COMPOSE, "lobby", { MOTD: "lobby!" }), "lobby")).toEqual({ TYPE: "PAPER", RCON_PASSWORD: "${RCON_LOBBY}", MOTD: "lobby!" });
178 expect(serviceEnv(setServiceEnv(COMPOSE, "hub", { MOTD: null }), "hub")).toEqual({ TYPE: "PAPER", RCON_PASSWORD: "${RCON_HUB}" });
179 const box = boxNamed(app.db, "net")!;
180 expect(await commitServiceEnv(app, alice, box, "hub", { RCON_PASSWORD: "x" })).toMatchObject({ ok: false, error: expect.stringContaining("the forge seals secrets") });
181 expect(await commitServiceEnv(app, getUserByName(app.db, "bob")!, box, "hub", { MAX_PLAYERS: "41" })).toEqual({
182 ok: false,
183 error: "Changing env needs write access to alice/mc-network, which this account does not have.",
184 });
185 const done = await commitServiceEnv(app, alice, box, "hub", { MAX_PLAYERS: "40" });
186 expect(done.ok).toBe(true);
187 const now = await readCompose(app, box);
188 expect(serviceEnv(now!.text, "hub")).toEqual({ TYPE: "PAPER", MOTD: "hello", RCON_PASSWORD: "${RCON_HUB}", MAX_PLAYERS: "40" });
189 expect(now!.text).toContain("container_name: proxy");
190 const repo = getRepo(app.db, "alice", "mc-network")!;
191 expect(repo.name).toBe("mc-network");
192 const log = Bun.spawnSync(["git", "log", "-1", "--format=%s", "main"], { cwd: join(app.reposRoot, "alice", "mc-network.git") });
193 expect(log.stdout.toString().trim()).toBe("games: hub env: MAX_PLAYERS");
194 });
195
196 test("a kept jar is served only on a good signature before it expires", async () => {
197 const box = boxNamed(app.db, "net")!;
198 const body = "PK\u0003\u0004 fake jar";
199 expect(await storeJar(app, box.id, new Blob(["not a zip"]), "x.jar")).toEqual({ ok: false, error: "That file is not a jar (a jar is a zip)." });
200 expect(await storeJar(app, box.id, new Blob([body]), "x.zip")).toEqual({ ok: false, error: "A plugin is a .jar file." });
201 const jar = await storeJar(app, box.id, new Blob([body]), "Hello World.jar");
202 if (!jar.ok) throw new Error(jar.error);
203 const href = signedJarHref(app, jar);
204 const ok = await http.handle(new Request(ORIGIN + href));
205 expect(ok.status).toBe(200);
206 expect(await ok.text()).toBe(body);
207 const url = new URL(ORIGIN + href);
208 expect((await http.handle(new Request(`${ORIGIN}${url.pathname}?e=${url.searchParams.get("e")}&s=bad`))).status).toBe(403);
209 expect((await http.handle(new Request(`${ORIGIN}${url.pathname}`))).status).toBe(403);
210 const old = signedJarHref(app, jar, Date.now() - JAR_URL_MS - 1_000);
211 const oldUrl = new URL(ORIGIN + old);
212 expect(jarSignatureGood(app, jar.id, oldUrl.searchParams.get("e")!, oldUrl.searchParams.get("s")!)).toBe(false);
213 expect((await http.handle(new Request(ORIGIN + old))).status).toBe(403);
214 // The compose the box gets carries a signed URL for each kept jar.
215 const plugins = `PLUGINS: "https://elsewhere.test/games/jar/${jar.id}/${jar.name}"`;
216 expect(signJarUrls(app, box, plugins, ORIGIN)).toMatch(new RegExp(`${ORIGIN}/games/jar/${jar.id}/${jar.name.replace(".", "\\.")}\\?e=\\d+&s=`));
217 // Another box's compose naming this jar gets no signature for it.
218 expect(signJarUrls(app, { id: "another-box" }, plugins, ORIGIN)).toBe(plugins);
219 await dropJar(app, jar.id);
220 expect((await http.handle(new Request(ORIGIN + signedJarHref(app, jar)))).status).toBe(404);
221 });
222
223 test("an operator of one service may run it and is refused another", async () => {
224 expect((await asBob("/games")).status).toBe(200);
225 expect((await asBob("/games/net")).status).toBe(404);
226 const box = boxNamed(app.db, "net")!;
227 grant(app.db, box.id, getUserByName(app.db, "bob")!.id, "operator", "hub");
228 expect((await asBob("/games/net")).status).toBe(200);
229 expect((await asBob("/games/net/hub")).status).toBe(200);
230 expect((await asBob("/games/net/lobby")).status).toBe(404);
231 expect((await asBob("/games/net/lobby/command", { text: "op bob" })).status).toBe(404);
232 expect((await asBob("/games/net/lobby/power", { kind: "stop" })).status).toBe(404);
233 expect((await asBob("/games/net/grant", { user: "bob", role: "owner", service: "" })).status).toBe(404);
234 const sent = await asBob("/games/net/hub/command", { text: "say from bob" });
235 expect(sent.status).toBe(303);
236 const queued = (await (await sync({ agent: 1 })).json()) as { commands: { service: string; text: string }[] };
237 expect(queued.commands).toEqual([expect.objectContaining({ service: "hub", text: "say from bob" })]);
238 });
239 });
test/mcp-forge-protocol.test.ts +1
@@ -237,6 +237,7 @@ describe("the forge over MCP: protocol", () => {
237237 "bets",
238238 "bet",
239239 "pinned_forge",
240 "games",
240241 "infra",
241242 "search",
242243 "feed",
test/mixed-actions-held.test.ts +1
@@ -49,6 +49,7 @@ const MIXED: Readonly<
4949 restore_drill: { key: "action", reads: [{ action: "status" }] },
5050 egress_grants: { key: "op", reads: [{ repo: "o/r", op: "list" }] },
5151 infra: { key: "action", reads: [{ action: "list" }, { action: "show", id: "x" }, { action: "plan" }, { action: "keep" }] },
52 games: { key: "action", reads: [{ action: "list" }] },
5253 pinned_forge: { key: "verb", reads: [{ verb: "list" }] },
5354 proposal_tokens: { key: "verb", reads: [{ verb: "list" }] },
5455 app_flags: { key: "action", reads: [{ repo: "o/r", action: "list" }] },
test/no-polling.test.ts +4
@@ -323,6 +323,10 @@ const NOT_WALKED: Record<string, string> = {
323323 "/:owner/:name/runs/:id": "the seed creates no run",
324324 "/:owner/:name/settings/app/flags/:flag": "needs an app whose flags.json declares a flag",
325325 "/:owner/:name/variants/:group": "needs a variant group of agent tries",
326 "/games/:box": "a game box, which the seed does not make (test/games.test.ts covers it)",
327 "/games/:box/:service": "a game box, which the seed does not make (test/games.test.ts covers it)",
328 "/games/:box/:service/stream": "a game box, which the seed does not make (test/games.test.ts covers it)",
329 "/games/jar/:id/:name": "a kept plugin jar, a download behind a signed URL, not a page",
326330 "/:owner/:name/waves/:version": "needs a wave of a milestone",
327331 "/boards/:slug": "needs a board",
328332 "/boards/:slug/stream": "needs a board; a stream, not a page",
test/open-routes-floor.test.ts +1 −1
@@ -41,7 +41,7 @@ const FILL: Readonly<Record<string, string>> = {
4141 ref: "main", branch: "main", oid: "0".repeat(40), sha: "0".repeat(40), commit: "0".repeat(40),
4242 // Not seeded: each still has to answer its not-found with the floor.
4343 team: "core", env: "prod", file: "README.md", label: "v1", chapter: "1", kind: "desktop", machine: "web",
44 range: `${"0".repeat(40)}...${"1".repeat(40)}`, op: "x", step: "1", group: "a", version: "1", slug: "board", receipt: "r", token: "t", code: "c", spec: "16", stage: "build", walk: "1", flag: "x", room: "lobby",
44 range: `${"0".repeat(40)}...${"1".repeat(40)}`, op: "x", step: "1", group: "a", version: "1", slug: "board", receipt: "r", token: "t", code: "c", spec: "16", stage: "build", walk: "1", flag: "x", room: "lobby", box: "net", service: "hub",
4545 };
4646
4747 /** Open GET routes that cannot be filled in from a seeded public repository, each with why. */
test/openapi.test.ts +1 −1
@@ -41,7 +41,7 @@ test("every http route the manifest names is described", () => {
4141 });
4242
4343 test("every described route is registered in the router", () => {
44 const src = ["src/http/server.ts", "src/http/api.ts", "src/http/mcp.ts", "src/http/passport_edge.ts", "src/http/feed.ts", "src/http/config.ts", "src/http/checks_recheck.ts", "src/http/settings_routes.ts", "src/http/forges_routes.ts", "src/contract/served.ts",
44 const src = ["src/http/server.ts", "src/http/api.ts", "src/http/mcp.ts", "src/http/passport_edge.ts", "src/http/feed.ts", "src/http/config.ts", "src/http/checks_recheck.ts", "src/http/settings_routes.ts", "src/http/forges_routes.ts", "src/http/games_routes.ts", "src/contract/served.ts",
4545 ...readdirSync("src/http/api").map((f) => `src/http/api/${f}`)]
4646 .map((f) => readFileSync(f, "utf8"))
4747 .join("\n")
test/pages-budget.test.ts +1 −1
@@ -71,7 +71,7 @@ const HEAVIER: Record<string, { statements?: number; git?: number }> = {
7171 };
7272
7373 /** Patterns with no fixture today: lower this as fixtures are added, never raise it silently. */
74 const MAX_UNFIXTURED = 163; // +1: /api/v1/runner/jobs/:id/seed, a seed of a runner job, readable only with a claimed job's token, which the fixture holds none of (#16881) // +1: /:owner/:name/large/:oid, a redirect to a presigned URL with no large blob in the fixture (#4490) // +1: /:owner/:name/bets/:id/walk/:walk, a journey walk of a closed bet scope the fixture has not run (#8715) // +2: /status/:token and /api/v1/status/:token, an outsider status link the fixture has not been handed (#15768); // +1: /tell/share/:id, a receipt of a share the fixture has not sent; +1: /docs/features/:file, a static reference note with no fixture (#12069); +1: /:owner/:name/pulls/:number/check.txt, plain text with no page to fixture (#12165) // +1: /:owner/:name/data/:file, a CSV download with no app data in the fixture (#12684) // +1: /api/v1/repos/:owner/:name/drop/:file, a private file with no drop in the fixture (#645) // +1: /:owner/:name/stl/:ref/*path, an .stl download with no model file in the fixture (#15856) // +1: /api/v1/devices/:id/print/:job, a printer job the fixture has not sent (#16656) // +1: /:owner/:name/settings/app/flags/:flag, a flag the fixture app does not declare (#1830) // +1: /api/v1/repos/:owner/:name/changes/:room, a change stream of an app that declares sync, which the fixture does not (#10839)
74 const MAX_UNFIXTURED = 167; // +4: /games/:box, /games/:box/:service, its stream and /games/jar/:id/:name, a game box the fixture does not make (#games, 2026-11-30) // +1: /api/v1/runner/jobs/:id/seed, a seed of a runner job, readable only with a claimed job's token, which the fixture holds none of (#16881) // +1: /:owner/:name/large/:oid, a redirect to a presigned URL with no large blob in the fixture (#4490) // +1: /:owner/:name/bets/:id/walk/:walk, a journey walk of a closed bet scope the fixture has not run (#8715) // +2: /status/:token and /api/v1/status/:token, an outsider status link the fixture has not been handed (#15768); // +1: /tell/share/:id, a receipt of a share the fixture has not sent; +1: /docs/features/:file, a static reference note with no fixture (#12069); +1: /:owner/:name/pulls/:number/check.txt, plain text with no page to fixture (#12165) // +1: /:owner/:name/data/:file, a CSV download with no app data in the fixture (#12684) // +1: /api/v1/repos/:owner/:name/drop/:file, a private file with no drop in the fixture (#645) // +1: /:owner/:name/stl/:ref/*path, an .stl download with no model file in the fixture (#15856) // +1: /api/v1/devices/:id/print/:job, a printer job the fixture has not sent (#16656) // +1: /:owner/:name/settings/app/flags/:flag, a flag the fixture app does not declare (#1830) // +1: /api/v1/repos/:owner/:name/changes/:room, a change stream of an app that declares sync, which the fixture does not (#10839)
7575
7676 /** Streams and live fragments: no page. */
7777 const NOT_PAGES = new Set([
test/palette-roster.test.ts +3
@@ -230,6 +230,7 @@ test("a site-admin person is offered the whole roster", () => {
230230 ["infra", "Infrastructure", "what runs on your own cloud, what it costs, when it ends"],
231231 ["pinned", "Pinned forges", "deploy, update and roll back a forge on your cloud"],
232232 ["experiments", "Experiments", "what each cloud machine costs and answers"],
233 ["games", "Games", "game servers on your cloud: state, start, stop, restart"],
233234 ["bets", "Bets", "back, stop and finish a repository\'s bets"],
234235 ["origins", "Connected accounts", "the hosts your mirrors come from"],
235236 ["design-gallery", "Component gallery", "every component the design names"],
@@ -347,6 +348,7 @@ test("a site-admin agent is offered the roster without the person-only entries",
347348 ["infra", "Infrastructure", "what runs on your own cloud, what it costs, when it ends"],
348349 ["pinned", "Pinned forges", "deploy, update and roll back a forge on your cloud"],
349350 ["experiments", "Experiments", "what each cloud machine costs and answers"],
351 ["games", "Games", "game servers on your cloud: state, start, stop, restart"],
350352 ["design-gallery", "Component gallery", "every component the design names"],
351353 ["feed", "Feed", "what happened, ranked; r replies on a post about an issue or pull, l likes, h who liked, p its permalink, o a run's log"],
352354 ["feature-feed", "Feature feeds", "the feed items about an absorbed app, as Settings › Features shows them"],
@@ -463,6 +465,7 @@ test("a member person is offered the signed-in roster without the admin entries"
463465 ["claim-link", "A fresh claim link for a forge I sent", "the old link stops; shown once"],
464466 ["recovery-link", "A recovery link for a forge's owner who lost their passkey", "shown once; works once"],
465467 ["bulk", "Bulk actions", "your last bulk actions; u undoes one inside its day"],
468 ["games", "Games", "game servers on your cloud: state, start, stop, restart"],
466469 ["bets", "Bets", "back, stop and finish a repository\'s bets"],
467470 ["origins", "Connected accounts", "the hosts your mirrors come from"],
468471 ["design-gallery", "Component gallery", "every component the design names"],
test/private-by-default.test.ts +1
@@ -127,6 +127,7 @@ const DOORS: Readonly<Record<string, Door>> = {
127127 "mcp fork": { walked: FORK },
128128 "mcp fork_tree": { noRepository: "reads the fork tree" },
129129 "mcp forks": { noRepository: "reads the forks" },
130 "mcp games start": { noRepository: "a game service started (power), not a repository" },
130131 "mcp make_it_yours": { proven: "test/make-it-yours.test.ts", says: 'plan.value.visibility).toBe("private")' },
131132 "mcp migrate": { proven: "test/migrate-trail.test.ts", says: "a migration that asks for no visibility is private" },
132133 "mcp migrate_data": { noRepository: "an app's data" },
test/security-floor-routes.test.ts +4
@@ -70,6 +70,10 @@ const REPORT = "needs a report an outsider filed; the seed has none";
7070 const SHOT = "needs a pin with a picture kept by refs/shots; the seed pins nothing";
7171 const CART = "the seed pins no build with a cart (test/build-cart.test.ts covers its headers)";
7272 const UNSEEDED: Record<string, string> = {
73 "/games/:box": "a game box, which the seed does not make (test/games.test.ts covers it)",
74 "/games/:box/:service": "a game box, which the seed does not make (test/games.test.ts covers it)",
75 "/games/:box/:service/stream": "a game box, which the seed does not make (test/games.test.ts covers it)",
76 "/games/jar/:id/:name": "a kept plugin jar of a game box, behind a signed URL the seed does not make",
7377 "/edge/config/:file": "a published file name, written by a config change the seed does not make (test/config-store.test.ts covers its headers)",
7478 "/:owner/-/teams/:team": ORG,
7579 "/api/v1/repos/:owner/:name/changes/:room": "an app's change stream needs forge.json sync:true on its default branch, which the seed does not declare (test/app-changes.test.ts covers it)",
test/tui-games.test.ts added +151
@@ -0,0 +1,151 @@
1 /**
2 * Games in the terminal, both doors (review of #16913): from the Games screen, `enter` opens a
3 * service's console (its log tail, and `:` queues an rcon command), env (`e` commits a key through
4 * the page's own `commitServiceEnv`, refusals in its words) and plugins (`a` adds a Modrinth slug
5 * through `addPlugin`; a jar upload is the page's alone, and the screen says so), and `g` opens the
6 * box's grants, which only an owner sets.
7 */
8 import { afterAll, beforeAll, expect, test } from "bun:test";
9 import { mkdtemp, rm } from "node:fs/promises";
10 import { tmpdir } from "node:os";
11 import { join } from "node:path";
12 import { commitToBranch, createRepo } from "../src/actions/repos.ts";
13 import { createApp, type App } from "../src/app.ts";
14 import { createUser, getUserByName, type User } from "../src/core/users.ts";
15 import { readCompose, serviceEnv } from "../src/games/compose.ts";
16 import { boxNamed, createGameBox, grantsOf, recentCommands, recordSync } from "../src/games/store.ts";
17 import { createForgeApp } from "../src/tui/forge.ts";
18 import { gameGrantsScreen, gameServiceScreen } from "../src/tui/screens/games.ts";
19 import { headlessTerminal } from "../src/tui/term/terminal.ts";
20 import { quietLogs } from "./helpers/globals.ts";
21 import { settleApp, settleUntil } from "./helpers/tui.ts";
22
23 quietLogs();
24
25 const COMPOSE = `services:
26 hub:
27 image: itzg/minecraft-server
28 environment:
29 TYPE: PAPER
30 MOTD: "hello"
31 `;
32
33 let dir = "";
34 let app: App;
35 let alice: User;
36 let bob: User;
37
38 beforeAll(async () => {
39 dir = await mkdtemp(join(tmpdir(), "forge-tui-games-"));
40 app = createApp({ dataDir: dir, port: 0 });
41 for (const [username, adminIfFirst] of [
42 ["alice", true],
43 ["bob", false],
44 ] as const) {
45 const made = await createUser(app.db, {
46 origin: "seed",
47 trusted: true,
48 username,
49 email: `${username}@f.test`,
50 password: "a-good-passphrase",
51 adminIfFirst,
52 });
53 if (!made.ok) throw new Error(made.error);
54 }
55 alice = getUserByName(app.db, "alice")!;
56 bob = getUserByName(app.db, "bob")!;
57 const repo = await createRepo(app, alice, { name: "mc-network", visibility: "private" });
58 if (!repo.ok) throw new Error(String(repo.error));
59 const seeded = await commitToBranch(app, alice, repo.value, {
60 message: "network",
61 files: [{ path: "docker-compose.yml", content: COMPOSE }],
62 });
63 if (!seeded.ok) throw new Error(JSON.stringify(seeded.error));
64 createGameBox(app.db, { name: "net", repo: "alice/mc-network" });
65 const box = boxNamed(app.db, "net")!;
66 recordSync(app.db, box, {
67 composeSha: "",
68 services: [{ name: "hub", state: "running", health: "", startedAt: "", cpuPct: 1, memMiB: 900 }],
69 logs: { hub: ["[Server] Done (3.2s)!"] },
70 results: [],
71 host: { memMiB: 8000, memUsedMiB: 4000, load1: 0.2, diskFreeGiB: 60 },
72 });
73 }, 30_000);
74
75 afterAll(async () => {
76 app.close();
77 await rm(dir, { recursive: true, force: true });
78 });
79
80 const drive = (user: User) => {
81 const terminal = headlessTerminal(140, 30);
82 const { app: tui, session } = createForgeApp(
83 app,
84 { sshUsername: user.username, remoteAddress: "127.0.0.1", fingerprint: "SHA256:test", user },
85 { terminal, exitHooks: false },
86 );
87 tui.start();
88 return {
89 tui,
90 session,
91 terminal,
92 type: async (keys: string) => {
93 for (const k of keys) {
94 terminal.feed(k);
95 await settleApp(tui);
96 }
97 },
98 };
99 };
100
101 test("a service's console shows its log and queues an rcon command; env and plugins commit through the page's actions", async () => {
102 const { tui, session, terminal, type } = drive(alice);
103 const box = boxNamed(app.db, "net")!;
104 tui.ctx.push(gameServiceScreen(session, tui.ctx, box, "hub"));
105 await settleApp(tui);
106 expect(tui.screen.toText()).toContain("[Server] Done (3.2s)!");
107 await type(":");
108 await type("say hi");
109 terminal.feed("\r");
110 await settleUntil(tui, "Sent; the answer shows under the console.");
111 expect(recentCommands(app.db, box.id, "hub", 1)[0]).toMatchObject({ kind: "rcon", text: "say hi" });
112 expect(tui.screen.toText()).toContain("Sent; the answer shows under the console.");
113 // Env: a key committed to the compose file, as the page's form does.
114 await type("e");
115 await type("MOTD=welcome");
116 terminal.feed("\r");
117 await settleUntil(tui, "Committed ");
118 expect(serviceEnv((await readCompose(app, box))!.text, "hub")["MOTD"]).toBe("welcome");
119 expect(tui.screen.toText()).toContain("MOTD=welcome");
120 // A refusal comes back in the action's words.
121 await type("a");
122 await type("not a slug!");
123 terminal.feed("\r");
124 await settleUntil(tui, "A Modrinth project is its slug");
125 await type("a");
126 await type("luckperms");
127 terminal.feed("\r");
128 await settleUntil(tui, "modrinth: luckperms");
129 expect(tui.screen.toText()).toContain("Uploading a jar is on the web only: /games/net/hub.");
130 tui.stop?.();
131 });
132
133 test("grants: listed to the box's owner, set by them; a member who is not an owner is refused", async () => {
134 const box = boxNamed(app.db, "net")!;
135 const asBob = drive(bob);
136 asBob.tui.ctx.push(gameGrantsScreen(asBob.session, asBob.tui.ctx, box));
137 await settleApp(asBob.tui);
138 await asBob.type("a");
139 expect(asBob.tui.screen.toText()).toContain("Only an owner of this box sets grants.");
140 asBob.tui.stop?.();
141 const { tui, session, terminal, type } = drive(alice);
142 tui.ctx.push(gameGrantsScreen(session, tui.ctx, box));
143 await settleApp(tui);
144 await type("a");
145 await type("bob operator hub");
146 terminal.feed("\r");
147 await settleUntil(tui, "bob is operator of hub.");
148 expect(grantsOf(app.db, box.id)[0]).toMatchObject({ username: "bob", role: "operator", service: "hub" });
149 expect(tui.screen.toText()).toContain("bob is operator of hub.");
150 tui.stop?.();
151 });

Search
↑↓ navigate ↵ open ⌘↵ its app esc close

Keyboard shortcuts

Docs