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

A console that works with the firewall closed: a shell on the box through its agent, and Hetzner's own console #17247

opened this

Merged 39h 46m ago, live in production

sold/game-console → main 0 commits

  • Merged. sold/game-console was merged into main as ac6850a.

Review

Sign in to review this change.
22 files changed +681 −22
docs/features/game-box.md +2
@@ -20,3 +20,5 @@ experiment.
2020 - **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.
2121
2222 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`.
23 - **Console (owner only):** `/games/<box>` has a Console for the box's owner (forge admins are owners): a command is queued like an rcon (`kind: "shell"`, no service), and the agent runs it with `bash -lc` under `capped`, beside the sync: at most 30 s, no terminal and no input, at most 16 KB of output back at the next sync, streamed into the console over the box's own sync. A program that waits on a person (an editor, a pager, `top`, a bare shell or REPL, a `-f` follow) is refused before it is queued, saying what to run instead. Every command (`game.shell.asked`) and its output (`game.shell.done`) go to the audit, the owner's to read. In the terminal, `!` on a box's row opens the same console (`:` runs a command). `src/games/shell.ts`.
24
docs/features/infra.md +2
@@ -82,3 +82,5 @@ Not yet: the page, committing the compose file, sleep and wake, backups, and a S
8282
8383 Every DigitalOcean and Hetzner account is read into provider ▸ account ▸ project ▸ resource every five minutes (the `cloud-projects` duty), and on demand (Read now under Projects on /infra, `P` in the terminal's Infra). GETs only, through the audited fetch (`gatedFetch`), with the account's sealed key. DigitalOcean: `GET /v2/projects`, then each project's `/v2/projects/{id}/resources` (URNs `do:droplet:…`, `do:volume:…`), joined with `/v2/droplets` and `/v2/volumes`; a droplet or volume in no project's list is filed under the default. Hetzner: one token is one project, named by the account's project label (else its name); servers, volumes, firewalls and primary IPs, each with its `forge` label. Kept in `cloud_project` and `cloud_resource`, columns named for the OpenTelemetry `cloud.*`/`host.*` attributes (`cloud_provider`, `cloud_account_id`, `cloud_region`, `cloud_resource_id`, `host_type`). Whether a thing is the forge's is the cloud watch's judgement; the rest is "found", named and never touched. /infra's Projects section lists each project with its resources, its monthly cost at list price (a thing the catalog cannot price is counted, not guessed), and made by the forge against found; the terminal's Infra lists the same; `infra` `list` carries `projects` (ten at most, five strays named each) with a `says` line.
8484
85 **Provider console (Hetzner):** a Hetzner machine on /infra has a Provider console button (`o` in the terminal's Infra). It asks Hetzner for the server's own console (`POST /v1/servers/{id}/actions/request_console`, through the audited fetch with the account's sealed key) and shows its `wss://` address and password once, on a page no cache keeps: good for about a minute, kept nowhere. The way in when a box's agent is silent and its firewall lets no SSH through. `src/cloud/provider_console.ts`.
86
src/actions/infra.ts +24 −1
@@ -15,6 +15,7 @@
1515
1616 import type { App } from "../app.ts";
1717 import { projectsOf, refreshProjects, type ProjectView } from "../cloud/projects.ts";
18 import { requestConsole, type ProviderConsole } from "../cloud/provider_console.ts";
1819 import { gatedFetch } from "../cloud/gate.ts";
1920 import { resolveSecrets } from "../core/secret_store.ts";
2021 import { billingSentence, billsOf, existsAtProvider, type Bills } from "../cloud/billing.ts";
@@ -30,7 +31,7 @@ import { keptRate } from "../cloud/rates.ts";
3031 import { TARGETS } from "../cloud/targets.ts";
3132 import { lastReading } from "../cloud/watch_read.ts";
3233 import { listApps } from "../core/apps.ts";
33 import { listCloudAccounts, READ_ONLY } from "../core/cloud_account.ts";
34 import { listCloudAccounts, READ_ONLY, secretNameOf } from "../core/cloud_account.ts";
3435 import { listDns } from "../core/dns_record.ts";
3536 import { dnsRecordOf, getPinned, HOST_NEEDED, listPinned, NAME, placeIdOf, urlOf, lifetimeOf } from "../core/pinned.ts";
3637 import { getRepoById } from "../core/repos.ts";
@@ -839,3 +840,25 @@ export async function readProjectsNow(app: App, actor: User | undefined): Promis
839840 ),
840841 );
841842 }
843
844 /**
845 * A Hetzner machine's provider console, for a forge admin, shown once and never kept
846 * (`cloud/provider_console.ts`): the one way in when its agent is silent. Through the audited fetch
847 * with the account's sealed key.
848 */
849 export async function providerConsole(app: App, actor: User | undefined, name: string): Promise<Result<ProviderConsole, string>> {
850 const who = admin(actor);
851 if (!who.ok) return who;
852 const p = getPinned(app.db, name);
853 if (p === undefined || p.state === "retired") return err(`No machine called ${name} runs here.`);
854 if (p.target !== "hetzner") return err("A provider console is Hetzner's; this machine is on another cloud.");
855 if (p.remote === "") return err(`${name} has no machine at Hetzner yet.`);
856 const secret = secretNameOf(p.target, p.account);
857 const token = resolveSecrets(app.db, app.config.dataDir, app.bus, [secret], { actor: who.value.id, run: "infra:console" })[secret];
858 if (token === undefined) return err(`The key of hetzner/${p.account} could not be opened.`);
859 try {
860 return ok(await requestConsole(gatedFetch(app.db, { provider: p.target, account: p.account }, "infra:console", net.fetch), token, p.remote));
861 } catch (e) {
862 return err(e instanceof Error ? e.message : "Hetzner did not answer.");
863 }
864 }
src/cloud/provider_console.ts added +29
@@ -0,0 +1,29 @@
1 /**
2 * A Hetzner machine's own console (#17151 V4): `POST /v1/servers/{id}/actions/request_console`
3 * answers a WebSocket URL and a password for the server's VNC console, good for about a minute.
4 * Shown once to the forge admin who asked, never kept: the forge holds neither. The way in when the
5 * agent cannot be reached and the firewall lets no SSH through.
6 */
7
8 import type { Fetch } from "./providers.ts";
9
10 export interface ProviderConsole {
11 readonly wssUrl: string;
12 readonly password: string;
13 }
14
15 /** Ask Hetzner for server `id`'s console. Throws in words when it answers anything else. */
16 export async function requestConsole(f: Fetch, token: string, id: string): Promise<ProviderConsole> {
17 if (!/^\d{1,20}$/.test(id)) throw new Error("that machine has no Hetzner server id");
18 const res = await f(`https://api.hetzner.cloud/v1/servers/${id}/actions/request_console`, {
19 method: "POST",
20 headers: { authorization: `Bearer ${token}`, "content-type": "application/json" },
21 body: "{}",
22 });
23 if (!res.ok) throw new Error(`Hetzner answered ${res.status} to the console request`);
24 const body = (await res.json()) as { wss_url?: unknown; password?: unknown };
25 const wssUrl = typeof body.wss_url === "string" && body.wss_url.startsWith("wss://") ? body.wss_url : "";
26 const password = typeof body.password === "string" ? body.password : "";
27 if (wssUrl === "" || password === "") throw new Error("Hetzner's answer held no console URL and password");
28 return { wssUrl, password };
29 }
src/core/event_audience.ts +2
@@ -262,6 +262,8 @@ export function classifiedAudience(kind: string): EventAudience | undefined {
262262 kind.startsWith("drill.") ||
263263 // Which machines take this forge's checks is its admin's (`actions/runners.ts`).
264264 kind.startsWith("runner.") ||
265 // A shell on a game box and everything it said: its owner's, the forge admin's (`games/shell.ts`).
266 kind.startsWith("game.shell.") ||
265267 // A snapshot moving is the forge owner's too, and has no repository.
266268 kind.startsWith("backup.") ||
267269 // Preparing for a power-off and ending it are the forge owner's (`maintenance/service.ts`).
src/games/agent.sh +60 −9
@@ -82,7 +82,7 @@ now() { date -u +%Y-%m-%dT%H:%M:%SZ; }
8282 # Run a command for at most `secs` seconds, timeout(1) or not: a docker that hangs never holds the
8383 # loop. Its output passes through; past the limit it is killed and says nothing more.
8484 capped() {
85 local secs="$1" pid i
85 local secs="$1" pid
8686 shift
8787 if command -v timeout >/dev/null 2>&1; then
8888 timeout "$secs" "$@"
@@ -90,15 +90,22 @@ capped() {
9090 fi
9191 "$@" &
9292 pid=$!
93 for ((i = 0; i < secs * 20; i++)); do
94 kill -0 "$pid" 2>/dev/null || break
95 sleep 0.05
96 done
97 if kill -0 "$pid" 2>/dev/null; then
98 pkill -P "$pid" 2>/dev/null
93 # One watchdog, no polling: it stops the command at the limit (the command first, so it runs
94 # nothing more, then what it started, named before it went); a command that ends first ends it.
95 (
96 sleep "$secs"
97 kids="$(pgrep -P "$pid" 2>/dev/null | tr '\n' ' ')"
9998 kill "$pid" 2>/dev/null
100 fi
99 # shellcheck disable=SC2086 # a list of pids
100 [ -n "$kids" ] && kill $kids 2>/dev/null
101 ) 2>/dev/null &
102 local dog=$! rc
101103 wait "$pid" 2>/dev/null
104 rc=$?
105 pkill -P "$dog" 2>/dev/null
106 kill "$dog" 2>/dev/null
107 wait "$dog" 2>/dev/null
108 return "$rc"
102109 }
103110 bounded30() { capped 30 "$@"; }
104111 # A diag probe: at most 5 s, its output cut to `max` bytes, nothing on failure.
@@ -164,6 +171,11 @@ run() {
164171 kind="$(jq -r '.kind // ""' <<<"$cmd")"
165172 service="$(jq -r '.service // ""' <<<"$cmd")"
166173 text="$(jq -r '.text // ""' <<<"$cmd")"
174 # A shell command is the box's, not a service's: it runs beside the sync, never in it.
175 if [ "$kind" = "shell" ]; then
176 shell_start "$id" "$text"
177 return
178 fi
167179 if ! [[ "$service" =~ $SAFE ]]; then
168180 out="refused: the service name is not one compose can have"
169181 ok=false
@@ -219,7 +231,8 @@ queue_job() {
219231
220232 # Keep a command's result for the next sync.
221233 keep_result() {
222 jq -c --arg id "$1" --argjson ok "$2" --arg out "${3:0:4096}" '. + [{id: $id, ok: $ok, output: $out}]' "$DIR/.results" >"$DIR/.results.next" &&
234 local most="${4:-4096}"
235 jq -c --arg id "$1" --argjson ok "$2" --arg out "${3:0:$most}" '. + [{id: $id, ok: $ok, output: $out}]' "$DIR/.results" >"$DIR/.results.next" &&
223236 mv "$DIR/.results.next" "$DIR/.results"
224237 }
225238
@@ -263,6 +276,38 @@ job_tick() {
263276 echo $! >"$DIR/.job.pid"
264277 }
265278
279 # ---- the owner's shell (#17151 V4): `bash -lc` under `capped`, at most FORGE_GAME_SHELL_S
280 # seconds (30) with no terminal and no input, so an interactive program ends at once; its output,
281 # at most 16 KB, is the command's result at the next sync. Each runs beside the sync. ----
282
283 SHELLS="$DIR/.shell"
284 shell_start() {
285 local id="$1" text="$2"
286 [[ "$id" =~ $SAFE ]] || return
287 mkdir -p "$SHELLS"
288 printf '%s' "$text" >"$SHELLS/$id.cmd"
289 (
290 TERM=dumb capped "${FORGE_GAME_SHELL_S:-30}" bash -lc "$text" </dev/null >"$SHELLS/$id.out" 2>&1
291 echo $? >"$SHELLS/$id.rc.next" && mv "$SHELLS/$id.rc.next" "$SHELLS/$id.rc"
292 ) &
293 }
294
295 # Each tick: every shell command that ended becomes a result (16 KB of its output at most).
296 shell_tick() {
297 local rc f id out
298 for f in "$SHELLS"/*.rc; do
299 [ -e "$f" ] || continue
300 id="$(basename "$f" .rc)"
301 rc="$(cat "$f")"
302 out="$(tail -c 16384 "$SHELLS/$id.out" 2>/dev/null)"
303 # 124 and 137: capped stopped it at its limit (timeout(1), or our own kill).
304 case "$rc" in 124 | 137 | 143) out="${out}
305 [stopped after ${FORGE_GAME_SHELL_S:-30} s]" ;; esac
306 keep_result "$id" "$([ "$rc" = 0 ] && echo true || echo false)" "$out" 16384
307 rm -f "$SHELLS/$id.rc" "$SHELLS/$id.out" "$SHELLS/$id.cmd"
308 done
309 }
310
266311 # Write what the answer carries; bring the project up when the compose or an env file changed.
267312 apply() {
268313 local answer="$1" sha changed=0 changed_env=0 name
@@ -335,6 +380,11 @@ diag() {
335380 # that does not answer) never holds the sync. Over it, an empty diag that says so.
336381 bounded_diag() {
337382 local out="$DIR/.diag.next" pid i limit
383 # 0 turns the diag off (a test that needs only the sync): nothing probed, an empty diag sent.
384 if [ "${FORGE_GAME_DIAG_S:-8}" = 0 ]; then
385 echo '{}'
386 return
387 fi
338388 limit="$(( ${FORGE_GAME_DIAG_S:-8} * 5 ))"
339389 rm -f "$out"
340390 diag >"$out" 2>/dev/null &
@@ -385,6 +435,7 @@ sync() {
385435
386436 while :; do
387437 job_tick
438 shell_tick
388439 sync || echo "forge-game-agent: sync failed; again in ${EVERY}s" >&2
389440 job_tick
390441 [ "$ONCE" = 1 ] && exit 0
src/games/shell.ts added +109
@@ -0,0 +1,109 @@
1 /**
2 * The console (#17151 V4): a shell on a game box, through its agent. A command is queued like an
3 * rcon (`kind: "shell"`, the box's and no service's), the box's owner's alone, and the agent runs
4 * it with `bash -lc` under its cap: 30 s, no terminal, no input, 16 KB of output. Every command
5 * and its output go to the audit (`game.shell.asked`, `game.shell.done`, the owner's to read).
6 * A program that waits on a person (an editor, a pager, a REPL, a follow) is refused here, before
7 * it is queued, in words that say what to run instead.
8 */
9
10 import type { App } from "../app.ts";
11 import type { User } from "../core/users.ts";
12 import { err, ok, type Result } from "../kernel/result.ts";
13 import { commandOf, mayDo, queueCommand, roleOn, type GameBox } from "./store.ts";
14
15 /** Shell commands are the box's: they carry this service, which no compose service can have. */
16 export const SHELL_SERVICE = "";
17 /** The most a shell command may say back, bytes. */
18 export const SHELL_OUTPUT = 16_384;
19
20 /** Programs that wait on a person: an editor, a pager, a monitor, a session. */
21 const INTERACTIVE = new Set([
22 "vi",
23 "vim",
24 "nvim",
25 "nano",
26 "emacs",
27 "less",
28 "more",
29 "most",
30 "top",
31 "htop",
32 "btop",
33 "watch",
34 "man",
35 "ssh",
36 "telnet",
37 "ftp",
38 "sftp",
39 "tmux",
40 "screen",
41 "mc",
42 "passwd",
43 "su",
44 ]);
45 /** Shells and interpreters: interactive without something to run. */
46 const REPLS = new Set([
47 "bash",
48 "sh",
49 "zsh",
50 "fish",
51 "python",
52 "python3",
53 "node",
54 "bun",
55 "irb",
56 "ruby",
57 "perl",
58 "mysql",
59 "psql",
60 "redis-cli",
61 "sqlite3",
62 "rcon-cli",
63 ]);
64
65 /** Why a command would wait on a person, or undefined when it runs and ends by itself. */
66 export function shellRefusal(text: string): string | undefined {
67 const line = text.trim();
68 if (line === "") return "Type a command.";
69 if (line.length > 1_000) return "A command is at most 1,000 characters.";
70 for (const part of line.split(/&&|\|\||;|\|/)) {
71 const words = part
72 .trim()
73 .split(/\s+/)
74 .filter((w) => !/^[A-Za-z_][A-Za-z0-9_]*=/.test(w) && w !== "sudo" && w !== "exec");
75 const head = (words[0] ?? "").split("/").at(-1) ?? "";
76 if (INTERACTIVE.has(head))
77 return `${head} waits on a person, and the console has no terminal: run something that ends by itself (cat, head, ps, df).`;
78 if (REPLS.has(head) && words.length === 1)
79 return `${head} alone waits for input: give it something to run (${head === "bash" || head === "sh" ? `${head} -c '…'` : `${head} -c '…' or a file`}).`;
80 if (
81 (head === "tail" || head === "journalctl" || head === "docker" || head === "kubectl") &&
82 words.some((w) => w === "-f" || w === "--follow" || (/^-[a-zA-Z]*f[a-zA-Z]*$/.test(w) && head === "tail"))
83 )
84 return "Following never ends, and a command here stops at 30 s: drop -f, or ask for the last lines (-n 100).";
85 }
86 return undefined;
87 }
88
89 /** Queue a shell command on the box, as its owner; said in the audit. The id is the command's. */
90 export function queueShell(app: App, actor: User | undefined, box: GameBox, text: string): Result<string, string> {
91 if (actor === undefined || !mayDo(roleOn(app.db, actor, box.id), "owner")) return err("Only the box's owner runs a shell on it.");
92 const refused = shellRefusal(text);
93 if (refused !== undefined) return err(refused);
94 const id = queueCommand(app.db, box.id, SHELL_SERVICE, "shell", text.trim(), actor.id);
95 app.bus.append({ kind: "game.shell.asked", actorId: actor.id, payload: { box: box.name, command: id, text: text.trim() } });
96 return ok(id);
97 }
98
99 /** After a sync: each shell command the box answered goes to the audit, its output with it. */
100 export function auditShellResults(app: App, box: GameBox, ids: readonly unknown[]): void {
101 for (const raw of ids.slice(0, 64)) {
102 const c = typeof raw === "string" ? commandOf(app.db, raw) : undefined;
103 if (c === undefined || c.kind !== "shell" || !c.done) continue;
104 app.bus.append({
105 kind: "game.shell.done",
106 payload: { box: box.name, command: c.id, text: c.text, ok: c.ok === true, output: c.output.slice(0, SHELL_OUTPUT) },
107 });
108 }
109 }
src/games/store.ts +3 −2
@@ -22,8 +22,9 @@ export const SERVICE_NAME = /^[a-z0-9][a-z0-9_.-]{0,63}$/;
2222 /** The most log lines kept a service; the oldest go first. */
2323 export const LOG_KEEP = 2_000;
2424 const LINES_A_SYNC = 200;
25 const OUTPUT_MAX = 4_096;
26 export const COMMAND_KINDS = ["rcon", "restart", "stop", "start", "recreate", "pull"] as const;
25 /** The most of a command's output kept: a shell's 16 KB (`shell.ts`); the rest say far less. */
26 const OUTPUT_MAX = 16_384;
27 export const COMMAND_KINDS = ["rcon", "restart", "stop", "start", "recreate", "pull", "shell"] as const;
2728 export type CommandKind = (typeof COMMAND_KINDS)[number];
2829 export type Role = "owner" | "operator" | "viewer";
2930 const RANK: Record<Role, number> = { viewer: 1, operator: 2, owner: 3 };
src/http/games_routes.ts +7 −1
@@ -5,10 +5,11 @@
55
66 import { composeServices, readCompose } from "../games/compose.ts";
77 import { synced } from "../games/notify.ts";
8 import { auditShellResults } from "../games/shell.ts";
89 import { boxByToken, envFiles, recordSync, signJarUrls, type SyncBody } from "../games/store.ts";
910 import { BODY_CAPS } from "../kernel/body_caps.ts";
1011 import {
11 gameBoxPage, gameCommandSubmit, gameEnvSubmit, gameGrantSubmit, gameJarDownload, gameJarSubmit, gamePluginSubmit, gamePowerSubmit, gameServicePage, gameSettingsSubmit, gameServiceStream, gamesPage,
12 gameBoxPage, gameCommandSubmit, gameEnvSubmit, gameGrantSubmit, gameJarDownload, gameJarSubmit, gamePluginSubmit, gamePowerSubmit, gameServicePage, gameSettingsSubmit, gameServiceStream, gameShellStream, gameShellSubmit, gamesPage,
1213 } from "../web/pages/games.ts";
1314 import type { Ctx, Handler } from "./context.ts";
1415 import { InvalidJson } from "./json_body.ts";
@@ -33,6 +34,8 @@ export async function gameAgentSync(ctx: Ctx): Promise<Response> {
3334 if (sent === "too_large") return apiError("too_large", 413, "a sync is at most 200 log lines a service");
3435 const body = sent as SyncBody;
3536 const commands = recordSync(ctx.app.db, box, body);
37 // Every shell command the box answered, its output with it, into the audit.
38 auditShellResults(ctx.app, box, (body.results ?? []).map((r) => r.id));
3639 synced(ctx.app, box.id);
3740 const compose = await readCompose(ctx.app, box);
3841 const reply: Record<string, unknown> = {
@@ -53,6 +56,9 @@ export function gamesRoutes(router: Router<Handler>): void {
5356 router.add("GET", "/games/jar/:id/:name", gameJarDownload);
5457 router.add("GET", "/games/:box", gameBoxPage);
5558 router.add("POST", "/games/:box/grant", gameGrantSubmit);
59 // Before the service routes: no compose service can be named "@shell".
60 router.add("POST", "/games/:box/@shell", gameShellSubmit);
61 router.add("GET", "/games/:box/@shell/stream", gameShellStream);
5662 router.add("GET", "/games/:box/:service", gameServicePage);
5763 router.add("GET", "/games/:box/:service/stream", gameServiceStream);
5864 router.add("POST", "/games/:box/:service/command", gameCommandSubmit);
src/http/infra_routes.ts +10 −2
@@ -5,7 +5,7 @@
55 */
66
77 import { infraCode } from "../cloud/infra_read.ts";
8 import { buildOf, machineOf, projectsView, readProjectsNow, type ComposeChoices, composeChoices, domainOf, infraOf, nameFor, planCompose, planRecord, rebuild, recordAccounts, startBuild } from "../actions/infra.ts";
8 import { buildOf, machineOf, projectsView, providerConsole, readProjectsNow, type ComposeChoices, composeChoices, domainOf, infraOf, nameFor, planCompose, planRecord, rebuild, recordAccounts, startBuild } from "../actions/infra.ts";
99 import { dropRecord } from "../actions/dns_record.ts";
1010 import { deleteSnapshot, endWithSnapshot, restoreSnapshot } from "../actions/infra_snapshot.ts";
1111 import { clearPinned, endsWords, keepPinned, retirePinned, retireWords } from "../actions/pinned.ts";
@@ -16,7 +16,7 @@ import { liveRegionsJs } from "../web/client.ts";
1616 import { field, readForm } from "../web/form.ts";
1717 import { html } from "../web/html.ts";
1818 import { flashTo, fragment, page } from "../web/layout.ts";
19 import { INFRA_CSS, endingPage, buildTray, placesRegion, composeForm, infraJs, infraPage, planTray, recordForm, runningRegion, type ComposeState } from "../web/pages/infra.ts";
19 import { INFRA_CSS, consolePage, endingPage, buildTray, placesRegion, composeForm, infraJs, infraPage, planTray, recordForm, runningRegion, type ComposeState } from "../web/pages/infra.ts";
2020 import type { Ctx, Handler } from "./context.ts";
2121 import type { Router } from "./router.ts";
2222
@@ -201,6 +201,14 @@ async function infraMachine(ctx: Ctx): Promise<Response> {
201201 const form = await readForm(ctx, "admin");
202202 if (form instanceof Response) return form;
203203 const name = ctx.params.name ?? "";
204 if (ctx.params.act === "console") {
205 // Shown once, never kept: the answer is this page alone, and no cache keeps it.
206 const opened = await providerConsole(ctx.app, ctx.auth.user, name);
207 if (!opened.ok) return flashTo(ctx, `/infra#machine-${name}`, { tone: "danger", message: opened.error });
208 const shown = page({ ctx, title: `${name}'s console`, body: consolePage(name, opened.value) });
209 shown.headers.set("cache-control", "no-store");
210 return shown;
211 }
204212 if (ctx.params.act === "keep") {
205213 const kept = keepPinned(ctx.app, ctx.auth.user, name);
206214 return flashTo(
src/http/lazy_lists.ts +2
@@ -601,6 +601,8 @@ export const OPERATIONS_ROUTES = [
601601 ["GET", "/games/jar/:id/:name"],
602602 ["GET", "/games/:box"],
603603 ["POST", "/games/:box/grant"],
604 ["POST", "/games/:box/@shell"],
605 ["GET", "/games/:box/@shell/stream"],
604606 ["GET", "/games/:box/:service"],
605607 ["GET", "/games/:box/:service/stream"],
606608 ["POST", "/games/:box/:service/command"],
src/tui/screens/games.ts +54
@@ -12,6 +12,8 @@
1212
1313 import { movedKey } from "./moved_key.ts";
1414 import { emptyText } from "../../core/empty_words.ts";
15 import { SHELL_SERVICE, queueShell } from "../../games/shell.ts";
16 import { onSync } from "../../games/notify.ts";
1517 import { boxStatus, boxStatusShared } from "../../games/diag.ts";
1618 import { getUserByName } from "../../core/users.ts";
1719 import { addPlugin, commitServiceEnv, pluginsOf, readCompose, serviceEnv } from "../../games/compose.ts";
@@ -56,6 +58,7 @@ export function gamesScreen(f: Session, ctx: Ctx): Screen {
5658 binding(["j", "k"], "move cursor"),
5759 binding(["enter"], "console, env, plugins"),
5860 binding(["G"], "grants"),
61 binding(["!"], "console (the box's owner)"),
5962 binding(["s"], "start"),
6063 binding(["x"], "stop"),
6164 binding(["r"], "restart"),
@@ -104,6 +107,12 @@ export function gamesScreen(f: Session, ctx: Ctx): Screen {
104107 ctx.push(gameServiceScreen(f, ctx, at.box, at.service.name));
105108 return true;
106109 }
110 if (at !== undefined && !e.ctrl && !e.alt && e.key === "!") {
111 if (!mayDo(roleOn(f.app.db, f.user, at.box.id), "owner")) note = `Only the owner of ${at.box.name} runs a shell on it.`;
112 else ctx.push(gameShellScreen(f, ctx, at.box));
113 ctx.invalidate();
114 return true;
115 }
107116 const kind: CommandKind | undefined = e.key === "s" ? "start" : e.key === "x" ? "stop" : e.key === "r" ? "restart" : undefined;
108117 if (kind === undefined || at === undefined || e.ctrl || e.alt) return false;
109118 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}.`;
@@ -396,6 +405,51 @@ export function gameGrantsScreen(f: Session, ctx: Ctx, box: GameBox): Screen {
396405 return screen;
397406 }
398407
408 /**
409 * The owner's console on a box (#17151 V4), as /games/<box> has it: each shell command and what it
410 * said, newest last, redrawn as the box syncs; `:` runs one through `queueShell`, refusals in its
411 * words. 30 s and 16 KB a command, every one in the audit.
412 */
413 export function gameShellScreen(f: Session, ctx: Ctx, box: GameBox): Screen {
414 let note = "";
415 const screen: Screen = {
416 title: `${box.name} console`,
417 keys: [binding([":"], "run a command")],
418 async load(signal) {
419 // Each sync may bring an answer: redraw then, and stop listening when the screen goes.
420 const off = onSync(f.app, box.id, () => ctx.invalidate());
421 signal.addEventListener("abort", off, { once: true });
422 },
423 render(area, s) {
424 const c = ctx.theme.c;
425 const [head, body] = split(area, "v", [len(1), fill(1)]);
426 s.text(head!.x, head!.y, truncate(note !== "" ? note : `A shell on ${box.name}: bash -lc, 30 s, no terminal, 16 KB back. : runs one.`, head!.w), style(c.mutedFg, c.bg), head!.x + head!.w);
427 const lines = recentCommands(f.app.db, box.id, SHELL_SERVICE, 10)
428 .reverse()
429 .flatMap((cmd) => [`$ ${cmd.text}`, ...(cmd.done ? cmd.output.split("\n") : ["(waiting for the box's next sync)"])]);
430 lines.slice(-body!.h).forEach((l, i) => s.text(body!.x, body!.y + i, truncate(l, body!.w), style(c.fg, c.bg), body!.x + body!.w));
431 },
432 key(e) {
433 if (e.ctrl || e.alt || e.key !== ":") return false;
434 ctx.push(
435 promptScreen(ctx, screen, {
436 title: "Console",
437 label: `A command for ${box.name}`,
438 onSubmit: (text) => {
439 const queued = queueShell(f.app, f.user, box, text);
440 if (!queued.ok) return queued.error;
441 note = "Sent; the answer shows here at the box's next sync.";
442 ctx.invalidate();
443 return undefined;
444 },
445 }),
446 );
447 return true;
448 },
449 };
450 return screen;
451 }
452
399453 /** Games: the services of the game boxes a person may see. */
400454 export const entry: PaletteEntry = {
401455 rank: 872,
src/tui/screens/infra.ts +11 −2
@@ -14,7 +14,7 @@
1414
1515 import { dropRecord, lookAtRecords, lookWords } from "../../actions/dns_record.ts";
1616 import { infraCode, type CodeFile } from "../../cloud/infra_read.ts";
17 import { buildOf, composeChoices, databaseChoices, infraOf, projectsView, readProjectsNow, nameFor, planCompose, planDatabase, planRecord, recordAccounts, startBuild, type Compose, type Planned, type Running } from "../../actions/infra.ts";
17 import { buildOf, composeChoices, providerConsole, databaseChoices, infraOf, projectsView, readProjectsNow, nameFor, planCompose, planDatabase, planRecord, recordAccounts, startBuild, type Compose, type Planned, type Running } from "../../actions/infra.ts";
1818 import { deleteSnapshot, endWithSnapshot, restoredName, restoreSnapshot } from "../../actions/infra_snapshot.ts";
1919 import { planMinecraft } from "../../actions/minecraft.ts";
2020 import { LIFETIME_DAYS, clearPinned, endsWords, keepPinned, retirePinned, retireWords } from "../../actions/pinned.ts";
@@ -344,6 +344,7 @@ export function infraScreen(f: Session, ctx: Ctx): Screen {
344344 binding(["r"], "restore a snapshot"),
345345 binding(["d"], "delete a snapshot"),
346346 binding(["P"], "read cloud projects now"),
347 binding(["o"], "provider console (Hetzner)"),
347348 ],
348349 async load(signal) {
349350 live(
@@ -554,12 +555,20 @@ export function infraScreen(f: Session, ctx: Ctx): Screen {
554555 if (next !== screen) ctx.push(next);
555556 return true;
556557 }
557 if (e.key !== "+" && e.key !== "x" && e.key !== "c") return false;
558 if (e.key !== "+" && e.key !== "x" && e.key !== "c" && e.key !== "o") return false;
558559 const picked = all[state.index - progress - drift];
559560 if (picked === undefined) {
560561 say("Select a machine first.");
561562 return true;
562563 }
564 // Hetzner's own console: its address and password, good for about a minute, shown once.
565 if (e.key === "o") {
566 say(`Asking Hetzner for ${picked.name}'s console…`);
567 void providerConsole(f.app, f.user, picked.name).then((c) =>
568 say(c.ok ? `${picked.name}'s console, for about a minute: ${c.value.wssUrl} password ${c.value.password}` : c.error),
569 );
570 return true;
571 }
563572 if (e.key === "+") {
564573 const kept = keepPinned(f.app, f.user, picked.name);
565574 say(kept.ok ? `${picked.name} now ends ${endsWords(kept.value.endsAt!)}.` : kept.error);
src/web/pages/games.ts +52 −1
@@ -7,6 +7,7 @@
77 */
88
99 import { addPlugin, commitServiceEnv, composeServices, pluginsOf, readCompose, SECRET_KEY, serviceEnv } from "../../games/compose.ts";
10 import { SHELL_SERVICE, queueShell } from "../../games/shell.ts";
1011 import { boxStatus, boxStatusShared } from "../../games/diag.ts";
1112 import { commitSettings, planSettings, previewSettings, settingsOf, SETTINGS, type SettingValue, type SettingsPlan } from "../../games/settings.ts";
1213 import {
@@ -120,6 +121,8 @@ export async function gameBoxPage(ctx: Ctx): Promise<Response> {
120121 return timePhase(ctx.request, "render", () => page({
121122 ctx,
122123 title: `Games · ${box.name}`,
124 // The owner's console streams its answers over the box's own sync, as a service's does.
125 ...(role === "owner" ? { scriptJs: gamesConsoleJs } : {}),
123126 body: html`${pageHead(box.name, {
124127 sub: `${box.repo}@${box.branch}:${box.path}${box.composeSha === "" ? "" : ` · running ${box.composeSha.slice(0, 10)}`}`,
125128 })}
@@ -139,10 +142,58 @@ export async function gameBoxPage(ctx: Ctx): Promise<Response> {
139142 });
140143 }),
141144 )}
142 ${role === "owner" ? boxBlock(box) : sharedBoxBlock(box)} ${role === "owner" ? grantsBlock(ctx, box) : null}`,
145 ${role === "owner" ? boxBlock(box) : sharedBoxBlock(box)} ${role === "owner" ? shellBlock(ctx, box) : null}
146 ${role === "owner" ? grantsBlock(ctx, box) : null}`,
143147 }));
144148 }
145149
150 /**
151 * The owner's console (#17151 V4): a shell on the box through its agent, each command and what it
152 * said, newest last, and the answers to come streamed in over the sync. 30 s and 16 KB a command.
153 */
154 function shellBlock(ctx: Ctx, box: GameBox): Html {
155 const done = recentCommands(ctx.app.db, box.id, SHELL_SERVICE, 10).reverse();
156 const lines = done.flatMap((c) => [`$ ${c.text}`, c.done ? c.output : "(waiting for the box's next sync)"]);
157 return html`<section class="settings-block" id="shell">
158 <h2>Console</h2>
159 <p class="muted small">A shell on ${box.name}: each command runs as <code>bash -lc</code> for at most 30 s, with no terminal, and says back at most 16 KB. Every command and its output go to the audit.</p>
160 <pre id="game-log" class="run-log mono" tabindex="0" aria-label="Console of ${box.name}" data-stream="/games/${box.name}/@shell/stream" data-last="0">
161 ${lines.join("\n")}${lines.length > 0 ? "\n" : ""}</pre
162 >
163 <form method="post" action="/games/${box.name}/@shell" class="row-fields">
164 <input class="input mono" name="text" aria-label="Command" placeholder="df -h /; docker ps" autocomplete="off" />
165 ${btn("Run", { type: "submit" })}
166 </form>
167 </section>`;
168 }
169
170 // POST /games/:box/@shell: the owner's shell command, queued for the box's next sync.
171 export async function gameShellSubmit(ctx: Ctx): Promise<Response> {
172 const got = boxOf(ctx, "owner");
173 if (got instanceof Response) return got;
174 const form = await readForm(ctx, "rw");
175 if (form instanceof Response) return form;
176 const queued = queueShell(ctx.app, ctx.auth.user, got.box, field(form, "text"));
177 return flashTo(ctx, `/games/${got.box.name}#shell`, queued.ok ? { message: "Sent; the answer shows in the console." } : { tone: "danger", message: queued.error });
178 }
179
180 // GET /games/:box/@shell/stream: the console's answers as they come back, the owner's alone.
181 export function gameShellStream(ctx: Ctx): Response {
182 const got = boxOf(ctx, "owner");
183 if (got instanceof Response) return got;
184 const { box } = got;
185 const pending = new Set(recentCommands(ctx.app.db, box.id, SHELL_SERVICE, 10).filter((c) => !c.done).map((c) => c.id));
186 return eventStream(ctx.app, ctx.request, (emit, _close, ready) =>
187 onSync(ctx.app, box.id, () => {
188 if (!ready()) return;
189 for (const c of recentCommands(ctx.app.db, box.id, SHELL_SERVICE, 10)) if (!c.done) pending.add(c.id);
190 const results = [...pending].map((id) => commandOf(ctx.app.db, id)).filter((c) => c !== undefined && c.done);
191 for (const r of results) pending.delete(r!.id);
192 if (results.length > 0) emit("lines", { lines: [], results: results.map((r) => ({ id: r!.id, ok: r!.ok, output: `$ ${r!.text}\n${r!.output}` })) });
193 }),
194 );
195 }
196
146197 /** What anyone who may see a service is told of the box: what it is doing, never its tails. */
147198 function sharedBoxBlock(box: GameBox): Html | null {
148199 const lines = boxStatusShared(box.diag);
src/web/pages/infra.ts +21
@@ -117,6 +117,22 @@ function meters(v: InfraView): Html {
117117 )}</div>`;
118118 }
119119
120 /**
121 * A Hetzner console's address and password, shown once: good for about a minute, kept nowhere, so
122 * this page is the only place they appear.
123 */
124 export function consolePage(name: string, c: { wssUrl: string; password: string }): Html {
125 return html`${pageHead(`${name}'s console`, { sub: "Hetzner's own console for this machine: good for about a minute, and shown only now." })}
126 <section class="settings-block">
127 <dl class="row-facts">
128 <dt>Address</dt><dd><code>${c.wssUrl}</code></dd>
129 <dt>Password</dt><dd><code>${c.password}</code></dd>
130 </dl>
131 <p class="muted small">Open it in a noVNC client, or from the server's Console button in Hetzner's own panel. Ask again for a new one once it lapses.</p>
132 <p><a href="/infra#machine-${name}">Back to Infrastructure</a></p>
133 </section>`;
134 }
135
120136 /** Keep and End now: Keep is reversible and posts at once; End now goes through the confirm. */
121137 const machineActions = (r: Running): Html =>
122138 html`<div class="row-fields">
@@ -125,6 +141,11 @@ const machineActions = (r: Running): Html =>
125141 : html`<form method="post" action="/infra/${r.name}/keep">
126142 ${btn(`Keep ${LIFETIME_DAYS} more days`, { variant: "ghost", size: "sm", label: `Keep ${r.name} ${LIFETIME_DAYS} more days` })}
127143 </form>`}
144 ${r.atProvider && r.account.startsWith("hetzner/")
145 ? html`<form method="post" action="/infra/${r.name}/console">
146 ${btn("Provider console", { variant: "ghost", size: "sm", label: `Open ${r.name}'s console at Hetzner` })}
147 </form>`
148 : null}
128149 ${r.atProvider && r.offer !== ""
129150 ? btn("End now", { href: `/infra/${r.name}/ending`, variant: "ghost", size: "sm", label: `End ${r.name} now` })
130151 : r.atProvider
test/budgets/unfixtured/games-box-shell-stream.json added +4
@@ -0,0 +1,4 @@
1 {
2 "pattern": "/games/:box/@shell/stream",
3 "why": "no fixture holds the id this route needs"
4 }
test/game-boot.test.ts +2
@@ -75,6 +75,8 @@ describe("the agent, missing a tool", () => {
7575 FORGE_GAME_DIR: join(box, "game"),
7676 FORGE_GAME_DOCKER: "docker",
7777 FORGE_GAME_ONCE: "1",
78 // No diag: this case reads the sync, and a probe per sync is time on a loaded machine.
79 FORGE_GAME_DIAG_S: "0",
7880 },
7981 stdout: "pipe",
8082 stderr: "pipe",
test/game-box.test.ts +2
@@ -229,6 +229,8 @@ esac
229229 FORGE_GAME_DIR: box,
230230 FORGE_GAME_DOCKER: fake,
231231 FORGE_GAME_ONCE: "1",
232 // No diag: this case reads the sync, and a probe per sync is time on a loaded machine.
233 FORGE_GAME_DIAG_S: "0",
232234 },
233235 stdout: "pipe",
234236 stderr: "pipe",
test/game-console.test.ts added +279
@@ -0,0 +1,279 @@
1 /**
2 * The console (#17151 V4): a shell on a game box through its agent. Queued like an rcon (`kind:
3 * "shell"`), the box's owner's alone, every command and its output in the audit; an interactive
4 * program refused before it is queued; the agent runs it with `bash -lc` under its cap (30 s, no
5 * terminal, 16 KB back); the answer shows on /games/<box> and the terminal's console. And
6 * Hetzner's own console: a URL and password, asked with a POST, shown once.
7 */
8 import { afterAll, beforeAll, describe, expect, test } from "bun:test";
9 import { existsSync, mkdirSync, mkdtempSync, readdirSync, writeFileSync } from "node:fs";
10 import { rm } from "node:fs/promises";
11 import { tmpdir } from "node:os";
12 import { join } from "node:path";
13 import { createApp, type App } from "../src/app.ts";
14 import { requestConsole } from "../src/cloud/provider_console.ts";
15 import { createSession } from "../src/core/sessions.ts";
16 import { createUser, type User } from "../src/core/users.ts";
17 import { queueShell, shellRefusal } from "../src/games/shell.ts";
18 import { boxNamed, commandOf, createGameBox, grant, rotateGameBoxToken } from "../src/games/store.ts";
19 import { serve, type Servers } from "../src/http/server.ts";
20 import { createForgeApp } from "../src/tui/forge.ts";
21 import { gameShellScreen } from "../src/tui/screens/games.ts";
22 import { headlessTerminal } from "../src/tui/term/terminal.ts";
23 import { consolePage } from "../src/web/pages/infra.ts";
24 import { pollUntil } from "./helpers/poll.ts";
25 import { settleApp } from "./helpers/tui.ts";
26
27 const AGENT = join(import.meta.dir, "../src/games/agent.sh");
28 const TOKEN = "fgb_abcdefghijklmnopqrstuvwxyz0123456789ABCDEFG";
29 const lacks = ["bash", "curl", "jq"].filter((t) => Bun.which(t) === null);
30
31 describe("what the console refuses", () => {
32 test("a program that waits on a person, a bare shell or REPL, and a follow; a command that ends runs", () => {
33 expect(shellRefusal("vim /etc/hosts")).toStartWith("vim waits on a person");
34 expect(shellRefusal("sudo top")).toStartWith("top waits on a person");
35 expect(shellRefusal("python3")).toStartWith("python3 alone waits for input");
36 expect(shellRefusal("bash")).toStartWith("bash alone waits for input: give it something to run (bash -c '…')");
37 expect(shellRefusal("docker logs -f hub")).toStartWith("Following never ends");
38 expect(shellRefusal("journalctl -u docker -f")).toStartWith("Following never ends");
39 expect(shellRefusal("tail -f /var/log/syslog")).toStartWith("Following never ends");
40 expect(shellRefusal("df -h / && docker ps | head -5")).toBeUndefined();
41 expect(shellRefusal("python3 -c 'print(1)'")).toBeUndefined();
42 expect(shellRefusal(" ")).toBe("Type a command.");
43 });
44 });
45
46 describe("on a forge", () => {
47 let dir = "";
48 let app: App;
49 let servers: Servers;
50 let alice: User;
51 let bob: User;
52
53 beforeAll(async () => {
54 dir = mkdtempSync(join(tmpdir(), "forge-game-console-"));
55 app = createApp({ dataDir: dir, port: 0 });
56 servers = await serve(app);
57 for (const [username, adminIfFirst] of [
58 ["alice", true],
59 ["bob", false],
60 ] as const) {
61 const made = await createUser(app.db, {
62 origin: "seed",
63 trusted: true,
64 username,
65 email: `${username}@f.test`,
66 password: "a-good-passphrase",
67 adminIfFirst,
68 });
69 if (!made.ok) throw new Error(made.error);
70 if (username === "alice") alice = made.value;
71 else bob = made.value;
72 }
73 createGameBox(app.db, { name: "mc" });
74 // Bob runs the box's servers, and is not its owner.
75 grant(app.db, boxNamed(app.db, "mc")!.id, bob.id, "operator");
76 });
77 afterAll(async () => {
78 servers.stop();
79 app.close();
80 await rm(dir, { recursive: true, force: true });
81 });
82
83 const events = (kind: string) =>
84 app.db
85 .query<{ payload: string }, [string]>("SELECT payload FROM event WHERE kind = ?1 ORDER BY rowid")
86 .all(kind)
87 .map((r) => JSON.parse(r.payload) as Record<string, unknown>);
88
89 test("only the box's owner queues a shell command; it is said in the audit; a refusal queues nothing", () => {
90 const box = boxNamed(app.db, "mc")!;
91 expect(queueShell(app, bob, box, "df -h")).toEqual({ ok: false, error: "Only the box's owner runs a shell on it." });
92 expect(queueShell(app, alice, box, "less /etc/os-release")).toMatchObject({
93 ok: false,
94 error: expect.stringContaining("less waits on a person"),
95 });
96 const queued = queueShell(app, alice, box, "df -h /");
97 if (!queued.ok) throw new Error(queued.error);
98 expect(commandOf(app.db, queued.value)).toMatchObject({ kind: "shell", service: "", text: "df -h /" });
99 expect(events("game.shell.asked").at(-1)).toEqual({ box: "mc", command: queued.value, text: "df -h /" });
100 });
101
102 test("the box's answer, up to 16 KB, is kept and said in the audit with its output", async () => {
103 const box = boxNamed(app.db, "mc")!;
104 const token = rotateGameBoxToken(app.db, box.id);
105 const queued = queueShell(app, alice, box, "cat /var/log/big");
106 if (!queued.ok) throw new Error(queued.error);
107 const big = "x".repeat(20_000);
108 const res = await fetch(`${servers.url}/api/v1/games/agent/sync`, {
109 method: "POST",
110 headers: { authorization: `Bearer ${token}`, "content-type": "application/json" },
111 body: JSON.stringify({ agent: 1, results: [{ id: queued.value, ok: true, output: big }] }),
112 });
113 expect(res.status).toBe(200);
114 expect(commandOf(app.db, queued.value)!.output).toHaveLength(16_384);
115 expect(events("game.shell.done").at(-1)).toMatchObject({ box: "mc", command: queued.value, text: "cat /var/log/big", ok: true });
116 expect((events("game.shell.done").at(-1)!["output"] as string).length).toBe(16_384);
117 });
118
119 test("/games/<box>: the owner has the console and its answers; an operator neither sees it nor runs one", async () => {
120 const as = (who: User) => ({ cookie: `forge_session=${createSession(app.db, who.id).token}` });
121 const owner = await (await fetch(`${servers.url}/games/mc`, { headers: as(alice) })).text();
122 expect(owner).toContain('<section class="settings-block" id="shell">');
123 expect(owner).toContain('action="/games/mc/@shell"');
124 expect(owner).toContain("$ df -h /");
125 const operator = await (await fetch(`${servers.url}/games/mc`, { headers: as(bob) })).text();
126 expect(operator).not.toContain('id="shell"');
127 const posted = await fetch(`${servers.url}/games/mc/@shell`, {
128 method: "POST",
129 redirect: "manual",
130 headers: { ...as(bob), origin: servers.url, "content-type": "application/x-www-form-urlencoded" },
131 body: "text=id",
132 });
133 expect(posted.status).toBe(404);
134 const stream = await fetch(`${servers.url}/games/mc/@shell/stream`, { headers: as(bob) });
135 expect(stream.status).toBe(404);
136 });
137
138 test("the terminal's console shows each command and its answer", async () => {
139 const terminal = headlessTerminal(120, 30);
140 const { app: tui, session } = createForgeApp(
141 app,
142 { sshUsername: "alice", remoteAddress: "127.0.0.1", fingerprint: "SHA256:test", user: alice },
143 { terminal, exitHooks: false },
144 );
145 tui.start();
146 tui.ctx.push(gameShellScreen(session, tui.ctx, boxNamed(app.db, "mc")!));
147 await settleApp(tui);
148 const text = tui.screen.toText();
149 tui.stop?.();
150 expect(text).toContain("$ df -h /");
151 expect(text).toContain("$ cat /var/log/big");
152 });
153 });
154
155 describe("the agent", () => {
156 /** One run of the agent against a forge that hands `commands` once, keeping every body. */
157 async function box() {
158 const root = mkdtempSync(join(tmpdir(), "forge-game-shell-"));
159 const game = join(root, "game");
160 mkdirSync(game);
161 const bin = join(root, "bin");
162 mkdirSync(bin);
163 writeFileSync(join(bin, "docker"), "#!/usr/bin/env bash\nexit 0\n", { mode: 0o755 });
164 const bodies: Record<string, any>[] = [];
165 let commands: unknown[] = [];
166 const forge = Bun.serve({
167 port: 0,
168 hostname: "127.0.0.1",
169 async fetch(req) {
170 bodies.push((await req.json()) as Record<string, any>);
171 const handed = commands;
172 commands = [];
173 return Response.json({ composeSha: "", commands: handed });
174 },
175 });
176 const run = async (env: Record<string, string> = {}) => {
177 const p = Bun.spawn(["bash", AGENT], {
178 env: {
179 PATH: `${bin}:${process.env["PATH"] ?? ""}`,
180 FORGE_URL: `http://127.0.0.1:${String(forge.port)}`,
181 FORGE_GAME_TOKEN: TOKEN,
182 FORGE_GAME_DIR: game,
183 FORGE_GAME_DOCKER: join(bin, "docker"),
184 FORGE_GAME_ONCE: "1",
185 FORGE_GAME_DIAG_S: "0",
186 // A home of its own: `bash -lc` reads a login profile, and this machine's is not the box's.
187 HOME: root,
188 ...env,
189 },
190 stdout: "pipe",
191 stderr: "pipe",
192 });
193 return p.exited;
194 };
195 const ended = (n: number) =>
196 pollUntil(
197 () => existsSync(join(game, ".shell")) && readdirSync(join(game, ".shell")).filter((f) => f.endsWith(".rc")).length >= n,
198 `${n} shell commands ended`,
199 10_000,
200 );
201 const done = async () => {
202 forge.stop(true);
203 await rm(root, { recursive: true, force: true });
204 };
205 return { bodies, hand: (c: unknown[]) => (commands = c), run, ended, done };
206 }
207
208 test.skipIf(lacks.length > 0)("runs a command with bash -lc beside the sync, and sends its output and status next sync", async () => {
209 const b = await box();
210 try {
211 b.hand([
212 { id: "s1", kind: "shell", service: "", text: "echo hi; echo oops >&2; test -t 0 || echo no-tty" },
213 { id: "s2", kind: "shell", service: "", text: "exit 3" },
214 ]);
215 expect(await b.run()).toBe(0);
216 await b.ended(2);
217 expect(await b.run()).toBe(0);
218 const results = b.bodies.at(-1)!["results"] as { id: string; ok: boolean; output: string }[];
219 expect(results.find((r) => r.id === "s1")).toEqual({ id: "s1", ok: true, output: "hi\noops\nno-tty" });
220 expect(results.find((r) => r.id === "s2")).toMatchObject({ ok: false });
221 } finally {
222 await b.done();
223 }
224 });
225
226 test.skipIf(lacks.length > 0)("a command past its limit is stopped and says so; its output is cut at 16 KB", async () => {
227 const b = await box();
228 try {
229 b.hand([
230 { id: "slow", kind: "shell", service: "", text: "echo started; sleep 20; echo never" },
231 { id: "loud", kind: "shell", service: "", text: "head -c 40000 /dev/zero | tr '\\0' a" },
232 ]);
233 expect(await b.run({ FORGE_GAME_SHELL_S: "1" })).toBe(0);
234 await b.ended(2);
235 expect(await b.run({ FORGE_GAME_SHELL_S: "1" })).toBe(0);
236 const results = b.bodies.at(-1)!["results"] as { id: string; ok: boolean; output: string }[];
237 const slow = results.find((r) => r.id === "slow")!;
238 // Stopped at its limit: what it said before, never what came after (bash may note the kill between).
239 expect(slow.ok).toBe(false);
240 expect(slow.output).toStartWith("started\n");
241 expect(slow.output).toEndWith("[stopped after 1 s]");
242 expect(slow.output).not.toContain("never");
243 expect(results.find((r) => r.id === "loud")!.output).toHaveLength(16_384);
244 } finally {
245 await b.done();
246 }
247 });
248 });
249
250 describe("Hetzner's console", () => {
251 test("asked with a POST, its URL and password answered; anything else is refused in words", async () => {
252 const asked: string[] = [];
253 const f = async (url: string | URL | Request, init?: RequestInit) => {
254 asked.push(`${init?.method} ${new URL(String(url)).pathname}`);
255 return Response.json({
256 wss_url: "wss://web-console.hetzner.cloud/?server_id=42&token=abc",
257 password: "9MQaTg2VAGI0FIpc10k3UpRXcHj2wQ6x",
258 action: { id: 1, command: "request_console" },
259 });
260 };
261 expect(await requestConsole(f, "t", "42")).toEqual({
262 wssUrl: "wss://web-console.hetzner.cloud/?server_id=42&token=abc",
263 password: "9MQaTg2VAGI0FIpc10k3UpRXcHj2wQ6x",
264 });
265 expect(asked).toEqual(["POST /v1/servers/42/actions/request_console"]);
266 await expect(requestConsole(async () => Response.json({ wss_url: "http://x", password: "p" }), "t", "42")).rejects.toThrow(
267 "no console URL and password",
268 );
269 await expect(requestConsole(async () => new Response("no", { status: 403 }), "t", "42")).rejects.toThrow("Hetzner answered 403");
270 await expect(requestConsole(f, "t", "not-a-number")).rejects.toThrow("no Hetzner server id");
271 });
272
273 test("the page shows them once, says how long they last, and links back", () => {
274 const shown = String(consolePage("box", { wssUrl: "wss://web-console.hetzner.cloud/?x", password: "pw" }));
275 expect(shown).toContain("<code>wss://web-console.hetzner.cloud/?x</code>");
276 expect(shown).toContain("<code>pw</code>");
277 expect(shown).toContain("good for about a minute, and shown only now");
278 });
279 });
test/game-diag.test.ts +4 −4
@@ -99,9 +99,9 @@ esac
9999 chmodSync(join(box.bin, "journalctl"), 0o755);
100100 const agent = Bun.spawn(["bash", AGENT], { env: box.env({ FORGE_GAME_EVERY: "0.2" }), stdout: "pipe", stderr: "pipe" });
101101 try {
102 await pollUntil(() => box.bodies.length >= 3, "three syncs while compose up runs", 15_000);
102 await pollUntil(() => box.bodies.length >= 2, "a sync while compose up runs", 15_000);
103103 // The first sync handed the compose file; every later one comes while the up still runs.
104 const during = box.bodies.slice(2);
104 const during = box.bodies.slice(1);
105105 for (const b of during) {
106106 expect(b["diag"]["job"]).toMatchObject({ label: "compose up", running: true });
107107 expect(b["diag"]["upLog"]).toContain("downloading 41%");
@@ -152,7 +152,7 @@ esac
152152 [".job.id", ""],
153153 ] as const)
154154 writeFileSync(join(box.dir, f), v);
155 const agent = Bun.spawn(["bash", AGENT], { env: box.env({ FORGE_GAME_ONCE: "1" }), stdout: "pipe", stderr: "pipe" });
155 const agent = Bun.spawn(["bash", AGENT], { env: box.env({ FORGE_GAME_ONCE: "1", FORGE_GAME_DIAG_S: "0" }), stdout: "pipe", stderr: "pipe" });
156156 try {
157157 expect(await agent.exited).toBe(0);
158158 expect(await new Response(agent.stderr).text()).toContain("the last job was interrupted; queued again");
@@ -187,7 +187,7 @@ describe("a reused pid", () => {
187187 [".job.id", ""],
188188 ] as const)
189189 writeFileSync(join(box.dir, f), v);
190 const agent = Bun.spawn(["bash", AGENT], { env: box.env({ FORGE_GAME_ONCE: "1" }), stdout: "pipe", stderr: "pipe" });
190 const agent = Bun.spawn(["bash", AGENT], { env: box.env({ FORGE_GAME_ONCE: "1", FORGE_GAME_DIAG_S: "0" }), stdout: "pipe", stderr: "pipe" });
191191 try {
192192 expect(await agent.exited).toBe(0);
193193 expect(await new Response(agent.stderr).text()).toContain("the last job was interrupted; queued again");
test/no-polling.test.ts +1
@@ -328,6 +328,7 @@ const NOT_WALKED: Record<string, string> = {
328328 "/:owner/:name/variants/:group": "needs a variant group of agent tries",
329329 "/games/:box": "a game box, which the seed does not make (test/games.test.ts covers it)",
330330 "/games/:box/:service": "a game box, which the seed does not make (test/games.test.ts covers it)",
331 "/games/:box/@shell/stream": "a game box's shell output for its owner, which the seed does not make (test/game-console.test.ts covers it)",
331332 "/games/:box/:service/stream": "a game box, which the seed does not make (test/games.test.ts covers it)",
332333 "/games/jar/:id/:name": "a kept plugin jar, a download behind a signed URL, not a page",
333334 "/:owner/:name/waves/:version": "needs a wave of a milestone",
test/security-floor-routes.test.ts +1
@@ -72,6 +72,7 @@ const CART = "the seed pins no build with a cart (test/build-cart.test.ts covers
7272 const UNSEEDED: Record<string, string> = {
7373 "/games/:box": "a game box, which the seed does not make (test/games.test.ts covers it)",
7474 "/games/:box/:service": "a game box, which the seed does not make (test/games.test.ts covers it)",
75 "/games/:box/@shell/stream": "a game box's shell output for its owner, which the seed does not make (test/game-console.test.ts covers it)",
7576 "/games/:box/:service/stream": "a game box, which the seed does not make (test/games.test.ts covers it)",
7677 "/games/jar/:id/:name": "a kept plugin jar of a game box, behind a signed URL the seed does not make",
7778 "/talk/dev/:token": "a dev cell reached by a one-time token the seed does not mint (test/dev-cell.test.ts covers it)",

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

Keyboard shortcuts

Docs