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

A game box's sync is never refused for terminal colours: the forge cleans machine output, and the agent sends it plain #17279

opened this

Merged 42h 52m ago, live in production

sold/agent-json → main 0 commits 1 thread · 1 unresolved

  • Merged. sold/agent-json was merged into main as 033ee45.

Review

Sign in to review this change.
6 files changed +252 −12
docs/features/games.md +4
@@ -13,6 +13,10 @@ A **game box** is a VM on your own cloud running Docker and `forge-game-agent`,
1313 - **MCP:** `games` (admin-listed tonight): `list`, `console`, `power`, `env`, `plugin`, with the same grants.
1414 - **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.
1515
16 ## What a sync carries
17
18 The agent sends every string plain: terminal colour escapes and control bytes (which itzg images and `rcon-cli` print) are taken out, and every part is checked as JSON and passed through a file, never a command line, so a large sync still goes. The forge cleans the same from what an older agent sends (`boundedMachineBody`), and refuses only a body that is not JSON, with where it broke; its log holds the first 200 bytes.
19
1620 ## Secrets
1721
1822 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.
src/games/agent.sh +28 −9
@@ -107,6 +107,14 @@ probe() {
107107 capped 5 "$@" 2>&1 | tail -c "$max" || true
108108 }
109109
110 # A JSON text from stdin, or `fallback` when what came is not one (a warning line, two documents,
111 # nothing at all): no --argjson is ever handed text that is not JSON.
112 json_or() {
113 local v
114 v="$(cat)"
115 if [ -n "$v" ] && jq -e . >/dev/null 2>&1 <<<"$v"; then printf '%s' "$v"; else printf '%s' "$1"; fi
116 }
117
110118 since="$(now)"
111119 [ -f "$DIR/.results" ] || echo '[]' >"$DIR/.results"
112120
@@ -346,17 +354,28 @@ bounded_diag() {
346354 }
347355
348356 sync() {
349 local next body answer
357 local next answer
350358 next="$(now)"
351 body="$(jq -cn \
359 # Each part through a file, checked as JSON on the way: a sync can pass the 128 KB one argument
360 # may hold (200 log lines from each of several servers), and then curl would never run.
361 services | json_or '[]' >"$DIR/.sync.services"
362 logs "$since" | json_or '{}' >"$DIR/.sync.logs"
363 json_or '[]' <"$DIR/.results" >"$DIR/.sync.results"
364 host | json_or '{}' >"$DIR/.sync.host"
365 bounded_diag | json_or '{}' >"$DIR/.sync.diag"
366 # Every string as plain text: real servers print colour escapes and control bytes (itzg's logs,
367 # rcon-cli's colours), and the forge takes none of them.
368 jq -cn \
352369 --arg sha "$(cat "$DIR/.compose-sha" 2>/dev/null)" \
353 --argjson services "$(services)" \
354 --argjson logs "$(logs "$since")" \
355 --slurpfile results "$DIR/.results" \
356 --argjson host "$(host)" \
357 --argjson diag "$(bounded_diag)" \
358 '{agent: 1, composeSha: $sha, services: $services, logs: $logs, results: $results[0], host: $host, diag: $diag}')" || return 1
359 answer="$(curl -fsS -m 20 -H "@$AUTH" -H 'content-type: application/json' --data-binary "$body" "${FORGE_URL%/}/api/v1/games/agent/sync")" || return 1
370 --slurpfile services "$DIR/.sync.services" \
371 --slurpfile logs "$DIR/.sync.logs" \
372 --slurpfile results "$DIR/.sync.results" \
373 --slurpfile host "$DIR/.sync.host" \
374 --slurpfile diag "$DIR/.sync.diag" \
375 'def plain: gsub("\u001b\\[[0-9;?]*[ -/]*[@-~]"; "") | gsub("\u001b[@-_]?"; "") | gsub("[\u0001-\u0008\u000b\u000c\u000e-\u001f\u007f]"; "");
376 {agent: 1, composeSha: $sha, services: $services[0], logs: $logs[0], results: $results[0], host: $host[0], diag: $diag[0]}
377 | walk(if type == "string" then plain else . end)' >"$DIR/.sync.body" || return 1
378 answer="$(curl -fsS -m 20 -H "@$AUTH" -H 'content-type: application/json' --data-binary "@$DIR/.sync.body" "${FORGE_URL%/}/api/v1/games/agent/sync")" || return 1
360379 # Delivered: the results and the log lines are the forge's now.
361380 echo '[]' >"$DIR/.results"
362381 since="$next"
src/http/games_routes.ts +12 −2
@@ -11,7 +11,8 @@ import {
1111 gameBoxPage, gameCommandSubmit, gameEnvSubmit, gameGrantSubmit, gameJarDownload, gameJarSubmit, gamePluginSubmit, gamePowerSubmit, gameServicePage, gameServiceStream, gamesPage,
1212 } from "../web/pages/games.ts";
1313 import type { Ctx, Handler } from "./context.ts";
14 import { apiError, boundedBody, json } from "./respond.ts";
14 import { InvalidJson } from "./json_body.ts";
15 import { apiError, boundedMachineBody, json } from "./respond.ts";
1516 import type { Router } from "./router.ts";
1617
1718 /** POST /api/v1/games/agent/sync: one pull of a game box's agent (the contract in docs/features/games.md). */
@@ -19,7 +20,16 @@ export async function gameAgentSync(ctx: Ctx): Promise<Response> {
1920 const auth = ctx.request.headers.get("authorization") ?? "";
2021 const box = auth.startsWith("Bearer ") ? boxByToken(ctx.app.db, auth.slice(7).trim()) : undefined;
2122 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 // Log lines and command output are what the box's programs printed (colour escapes and all):
24 // cleaned, not refused. A body that is not JSON is refused, and the log says where it broke.
25 let sent: Awaited<ReturnType<typeof boundedMachineBody>>;
26 try {
27 sent = await boundedMachineBody(ctx.request, BODY_CAPS.gameSync.bytes, (why) => ctx.app.log.warn(`game box ${box.name}: a sync that is not JSON`, { why }));
28 } catch (e) {
29 // The box hears where its body broke; the log above keeps the first bytes for whoever looks.
30 if (e instanceof InvalidJson) return apiError("invalid_json", 400, `the sync is not JSON: ${e.message} at ${JSON.stringify(e.token)}`);
31 throw e;
32 }
2333 if (sent === "too_large") return apiError("too_large", 413, "a sync is at most 200 log lines a service");
2434 const body = sent as SyncBody;
2535 const commands = recordSync(ctx.app.db, box, body);
src/http/parseable_request.ts +17
@@ -97,6 +97,23 @@ export function dirtyJson(value: unknown, raw: RawText = NO_RAW_TEXT, depth = 0)
9797 return false;
9898 }
9999
100 /** A terminal's escape sequence (colour, cursor): CSI, then any other ESC with the byte after it. */
101 const ESCAPES = /\u001B\[[0-9;?]*[ -\/]*[@-~]|\u001B[@-_]?/g;
102 const CONTROLS = /[\u0000-\u0008\u000B\u000C\u000E-\u001F\u007F]/g;
103
104 /**
105 * Machine text made plain: every string, object keys included, without its terminal escapes and
106 * control characters (tab, newline and carriage return stay). For a body whose strings are what a
107 * program printed (a game server's log lines, a command's output), which a route keeps as text:
108 * cleaned, where a person's input is refused (`refuseDirtyJson`).
109 */
110 export function cleanJson(value: unknown, depth = 0): unknown {
111 if (typeof value === "string") return value.replace(ESCAPES, "").replace(CONTROLS, "");
112 if (typeof value !== "object" || value === null || depth > 64) return value;
113 if (Array.isArray(value)) return value.map((v) => cleanJson(v, depth + 1));
114 return Object.fromEntries(Object.entries(value).map(([k, v]) => [cleanJson(k) as string, cleanJson(v, depth + 1)]));

Low: past depth 64 the value is returned uncleaned, so a deeply nested string keeps its escapes. Refuse the body past that depth, or keep recursing.

115 }
116
100117 /**
101118 * The one check every parsed JSON body goes through, `body()` and the routes
102119 * that parse their own alike: throws `ControlInput`, which the server's door
src/http/respond.ts +22 −1
@@ -5,7 +5,7 @@
55 */
66
77 import { InvalidJson, noteSent, objectOf } from "./json_body.ts";
8 import { NO_RAW_TEXT, refuseDirtyJson, type RawText } from "./parseable_request.ts";
8 import { cleanJson, NO_RAW_TEXT, refuseDirtyJson, type RawText } from "./parseable_request.ts";
99 import { bodyCapFor, readBounded } from "./limits.ts";
1010 import { namesReader } from "./reader.ts";
1111 import { scopeAllows, type TokenScope } from "../core/tokens.ts";
@@ -549,6 +549,27 @@ export async function boundedBody(
549549 return value;
550550 }
551551
552 /**
553 * A bounded JSON body whose strings are machine text (what a program printed: a game box's log
554 * lines and command output): escapes and control characters are taken out (`cleanJson`), never
555 * refused, so one coloured log line cannot stop a box from syncing. A body that is not JSON is still
556 * refused (`InvalidJson`, the door's 400), and `said` hears where it broke and its first 200 bytes.
557 */
558 export async function boundedMachineBody(request: Request, max: number, said: (why: string) => void): Promise<Record<string, unknown> | "too_large"> {
559 const bytes = await readBounded(request, max);
560 if (bytes === "too_large") return "too_large";
561 let value: Record<string, unknown>;
562 try {
563 value = objectOf(bytes);
564 } catch (e) {
565 if (e instanceof InvalidJson) said(`${e.message} at ${JSON.stringify(e.token)}; its first 200 bytes: ${JSON.stringify(new TextDecoder().decode(bytes.slice(0, 200)))}`);
566 throw e;
567 }
568 const clean = cleanJson(value) as Record<string, unknown>;
569 noteSent(request, clean);
570 return clean;
571 }
572
552573 export const str = (v: unknown): string => (typeof v === "string" ? v : "");
553574
554575 /**
test/game-sync-plain.test.ts added +169
@@ -0,0 +1,169 @@
1 /**
2 * A real game box's sync is taken (mc, 2026-12-01: every sync refused 400 once its servers ran):
3 * itzg's logs and rcon-cli print colour escapes and control bytes, which the forge refuses in a
4 * person's input. The agent sends every string plain and every part checked as JSON, through files
5 * (docker that prints a warning line, a ps with blank lines, a log line with ESC, BEL and a byte
6 * that is not UTF-8); the forge cleans what an older agent still sends, and a body that is not JSON
7 * is refused with where it broke, in the log with its first 200 bytes.
8 */
9 import { afterAll, beforeAll, describe, expect, test } from "bun:test";
10 import { chmodSync, mkdtempSync, 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 { boxNamed, createGameBox, logsOf } from "../src/games/store.ts";
16 import { cleanJson } from "../src/http/parseable_request.ts";
17 import { forgeHttp, type ForgeHttp } from "../src/http/server.ts";
18 import { quietLogs } from "./helpers/globals.ts";
19
20 quietLogs();
21
22 const AGENT = join(import.meta.dir, "../src/games/agent.sh");
23 const TOKEN = "fgb_abcdefghijklmnopqrstuvwxyz0123456789ABCDEFG";
24 const CONTROL = /[\u0000-\u0008\u000B\u000C\u000E-\u001F\u007F]/;
25
26 /** Every string anywhere in a parsed value. */
27 const strings = (v: unknown): string[] =>
28 typeof v === "string"
29 ? [v]
30 : Array.isArray(v)
31 ? v.flatMap(strings)
32 : v !== null && typeof v === "object"
33 ? Object.entries(v).flatMap(([k, x]) => [k, ...strings(x)])
34 : [];
35
36 describe("the agent", () => {
37 const lacks = ["bash", "curl", "jq"].filter((t) => Bun.which(t) === null);
38 test.skipIf(lacks.length > 0)(
39 `sends valid JSON with every string plain, whatever docker and the servers print${lacks.length > 0 ? ` (skipped: no ${lacks.join(", ")} here)` : ""}`,
40 async () => {
41 const box = mkdtempSync(join(tmpdir(), "forge-game-plain-"));
42 const fake = join(box, "docker");
43 // As a real box answers: stats with a warning line before its JSON, ps with blank lines, logs
44 // in itzg's colours with a bell and a Latin-1 section sign (0xA7, not UTF-8), rcon in colour.
45 writeFileSync(
46 fake,
47 `#!/usr/bin/env bash
48 case "$*" in
49 *" ps -a --format json") printf '\\n{"Service":"hub","Name":"hub","State":"running","Health":"healthy","CreatedAt":"x"}\\n\\n' ;;
50 "stats --no-stream --format json") echo 'WARNING: No swap limit support'; echo '{"Name":"hub","CPUPerc":"1.5%","MemUsage":"900MiB / 7.8GiB"}' ;;
51 *" logs --no-color --since "*) printf 'hub | \\033[0;39m\\033[39m[mc-image-helper] Downloaded\\033[0m\\nhub | [12:00:01 INFO]: Alice joined the game\\a\\nhub | \\247 old colour\\n' ;;
52 *" exec -T hub rcon-cli -- list") printf '\\033[0;33mThere are 1 of a max of 20 players online: Alice\\033[0m\\n' ;;
53 *) : ;;
54 esac
55 `,
56 );
57 chmodSync(fake, 0o755);
58 const bodies: string[] = [];
59 const forge = Bun.serve({
60 port: 0,
61 hostname: "127.0.0.1",
62 async fetch(req) {
63 bodies.push(await req.text());
64 return Response.json(
65 bodies.length === 1
66 ? { composeSha: "", commands: [{ id: "c1", kind: "rcon", service: "hub", text: "list" }] }
67 : { composeSha: "", commands: [] },
68 );
69 },
70 });
71 try {
72 const run = async (): Promise<string> => {
73 const p = Bun.spawn(["bash", AGENT], {
74 env: {
75 PATH: process.env["PATH"] ?? "",
76 FORGE_URL: `http://127.0.0.1:${String(forge.port)}`,
77 FORGE_GAME_TOKEN: TOKEN,
78 FORGE_GAME_DIR: box,
79 FORGE_GAME_DOCKER: fake,
80 FORGE_GAME_ONCE: "1",
81 },
82 stdout: "pipe",
83 stderr: "pipe",
84 });
85 await p.exited;
86 return new Response(p.stderr).text();
87 };
88 const said = await run();
89 expect(bodies.length, `the agent sent nothing; it said: ${said}`).toBe(1);
90 await run();
91 expect(bodies.length).toBe(2);
92 for (const raw of bodies) {
93 const body = JSON.parse(raw) as Record<string, unknown>;
94 expect(strings(body).filter((s) => CONTROL.test(s))).toEqual([]);
95 }
96 const first = JSON.parse(bodies[0]!) as { services: { name: string; memMiB: number }[]; logs: Record<string, string[]> };
97 // The warning line costs the stats (read as none this sync), never the sync or the services.
98 expect(first.services).toEqual([expect.objectContaining({ name: "hub" })]);
99 expect(first.logs["hub"]).toEqual(["[mc-image-helper] Downloaded", "[12:00:01 INFO]: Alice joined the game", "� old colour"]);
100 const second = JSON.parse(bodies[1]!) as { results: { id: string; output: string }[] };
101 expect(second.results).toEqual([expect.objectContaining({ id: "c1", output: "There are 1 of a max of 20 players online: Alice" })]);
102 } finally {
103 forge.stop(true);
104 await rm(box, { recursive: true, force: true });
105 }
106 },
107 );
108 });
109
110 describe("the forge", () => {
111 let dataDir = "";
112 let app: App;
113 let http: ForgeHttp;
114 let token = "";
115 const warned: string[] = [];
116 beforeAll(() => {
117 dataDir = mkdtempSync(join(tmpdir(), "forge-game-plain-forge-"));
118 app = createApp({ dataDir, port: 0 });
119 http = forgeHttp(app);
120 token = createGameBox(app.db, { name: "mc" }).token;
121 const warn = app.log.warn.bind(app.log);
122 Object.assign(app.log, {
123 warn: (message: string, fields?: Parameters<App["log"]["warn"]>[1]) => {
124 warned.push(`${message} ${JSON.stringify(fields ?? {})}`);
125 warn(message, fields);
126 },
127 });
128 });
129 afterAll(async () => {
130 app.close();
131 await rm(dataDir, { recursive: true, force: true });
132 });
133 const send = (body: string) =>
134 http.handle(
135 new Request("http://forge.test/api/v1/games/agent/sync", {
136 method: "POST",
137 headers: { authorization: `Bearer ${token}`, "content-type": "application/json" },
138 body,
139 }),
140 );
141
142 test("what an older agent still sends, colour escapes and all, is taken and kept plain", async () => {
143 const res = await send(
144 JSON.stringify({
145 agent: 1,
146 services: [{ name: "hub", state: "running" }],
147 logs: { hub: ["\u001b[0;39m[12:00:00 INFO]: Done (3.2s)!\u001b[0m", "bell\u0007"] },
148 }),
149 );
150 expect(res.status).toBe(200);
151 expect(logsOf(app.db, boxNamed(app.db, "mc")!.id, "hub").lines).toEqual(["[12:00:00 INFO]: Done (3.2s)!", "bell"]);
152 });
153
154 test("a body that is not JSON is refused 400, and the log says where it broke and its first bytes", async () => {
155 const res = await send('{"agent": 1, "logs": {"hub": ["cut');
156 expect(res.status).toBe(400);
157 expect(
158 warned.some(
159 (w) => w.includes("game box mc: a sync that is not JSON") && w.includes("first 200 bytes") && w.includes("agent") && w.includes("logs"),
160 ),
161 ).toBe(true);
162 });
163
164 test("cleanJson: escapes and control characters out of every string and key; tab, newline and carriage return stay", () => {
165 expect(cleanJson({ "k\u0007": ["\u001b[31mred\u001b[0m", "a\tb\nc\r", "osc\u001b]0;t\u0007", 3, null] })).toEqual({
166 k: ["red", "a\tb\nc\r", "osc0;t", 3, null],
167 });
168 });
169 });

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

Keyboard shortcuts

Docs