Public: anyone can read this; the crew can change it.
Games G4: a console that knows the game: colours, crash summaries, command history (#17284) #17301
Merged 26h 37m ago, live in production
sold/game-console-g4 → main 0 commits 2 threads · 2 unresolved
17 files
changed +492
−20
- docs/features/games.md
- forge.json
- src/app.ts
- src/engine/crossing.ts
- src/games/agent.sh
- src/games/console.ts
- src/games/store.ts
- src/http/games_routes.ts
- src/http/lazy_lists.ts
- src/http/parseable_request.ts
- src/tui/screens/common.ts
- src/tui/screens/games.ts
- src/web/pages/games.ts
- test/egress-literals.test.ts
- test/engine-crossing.test.ts
- test/game-console-colour.test.ts
- test/game-sync-plain.test.ts
docs/features/games.md +2 −2
| @@ -8,8 +8,8 @@ A **game box** is a VM on your own cloud running Docker and `forge-game-agent`, | ||
| 8 | 8 | |
| 9 | 9 | ## Where |
| 10 | 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>`), the settings ([](game-settings.md)) 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`; `enter` opens a service, and `c` there its settings. | |
| 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 in the game's own colours: the agent and the sync route turn each colour escape into its § code before they drop every other escape, and the page draws § codes through the one renderer, with Raw for the lines as kept; an RCON input whose answer shows inline, with the service's earlier commands on up and down; a crash found in the log leads in one line, "Crashed: Fabric could not load the mods: Install fabric-api", with the crash folded under it and a Share on mclo.gs button that says it publishes the log where anyone with the link can read it, and posts only on that click), the environment editor (commits `games: <service> env: <keys>`), the settings ([](game-settings.md)) 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`; `enter` opens a service, and `c` there its settings; a service's console reads its log with the colour codes gone, a crash first in one line, and `:`'s prompt walks earlier commands with up and down. | |
| 13 | 13 | - **MCP:** `games` (admin-listed tonight): `list`, `console`, `power`, `env`, `plugin`, `config`, `config_set`, with the same grants. |
| 14 | 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 | 15 |
forge.json +2 −1
| @@ -29,7 +29,8 @@ | ||
| 29 | 29 | "api.first.org", |
| 30 | 30 | "api.modrinth.com", |
| 31 | 31 | "cdn.modrinth.com", |
| 32 | "www.cisa.gov" | |
| 32 | "www.cisa.gov", | |
| 33 | "api.mclo.gs" | |
| 33 | 34 | ], |
| 34 | 35 | "schedules": [ |
| 35 | 36 | { "name": "heartbeat", "cron": "5 7 * * *", "timezone": "UTC", "path": "/jobs/heartbeat", "timeout": 120, "retries": 3, "catchUp": "6h" } |
src/app.ts +2
| @@ -262,6 +262,8 @@ export interface ForgeConfig { | ||
| 262 | 262 | * says. |
| 263 | 263 | */ |
| 264 | 264 | releaseSend?: (url: string, body: string, headers: Record<string, string>) => Promise<boolean>; |
| 265 | /** The fetch a crash is shared to mclo.gs through (`games/console.ts`); the real one unless a test says. */ | |
| 266 | mclogsFetch?: (url: string, init: RequestInit) => Promise<Response>; | |
| 265 | 267 | } |
| 266 | 268 | |
| 267 | 269 | export interface App { |
src/engine/crossing.ts +2
| @@ -74,6 +74,8 @@ export const STAYS = { | ||
| 74 | 74 | "a function: a test's stand-in for SMTP; `mail`, where real mail goes out, crosses", |
| 75 | 75 | releaseSend: |
| 76 | 76 | "a function: a test's stand-in for the notify sender, used where a release is cut on the serving thread", |
| 77 | mclogsFetch: | |
| 78 | "a function: a test's stand-in for mclo.gs, asked when a person shares a crash from the games page on the serving thread", | |
| 77 | 79 | verifyHuman: |
| 78 | 80 | "a function: a test's stand-in for Turnstile, asked at sign-up on the serving thread only", |
| 79 | 81 | } as const satisfies { readonly [K in keyof ForgeConfig]?: string }; |
src/games/agent.sh +13 −2
| @@ -852,7 +852,9 @@ sync() { | ||
| 852 | 852 | metrics | json_or '{}' >"/.sync.metrics" |
| 853 | 853 | jq -c 'if type == "object" then . else {} end' "/snapshots.json" 2>/dev/null | json_or '{}' >"/.sync.snapshots" |
| 854 | 854 | # Every string as plain text: real servers print colour escapes and control bytes (itzg's logs, |
| 855 | # rcon-cli's colours), and the forge takes none of them. | |
| 855 | # rcon-cli's colours), and the forge takes none of them. Colours go first as Minecraft's own | |
| 856 | # printable section codes (\u00a7: the sixteen colours, l bold, n underline, r every reset), which | |
| 857 | # the console draws; the forge's cleanJson does the same for an older agent. | |
| 856 | 858 | jq -cn \ |
| 857 | 859 | --arg sha "$(cat "/.compose-sha" 2>/dev/null)" \ |
| 858 | 860 | --slurpfile services "/.sync.services" \ |
| @@ -863,7 +865,16 @@ sync() { | ||
| 863 | 865 | --slurpfile people "/.sync.people" \ |
| 864 | 866 | --slurpfile metrics "/.sync.metrics" \ |
| 865 | 867 | --slurpfile snapshots "/.sync.snapshots" \ |
| 866 | 'def plain: gsub("\u001b\\[[0-9;?]*[ -/]*[@-~]"; "") | gsub("\u001b[@-_]?"; "") | gsub("[\u0001-\u0008\u000b\u000c\u000e-\u001f\u007f]"; ""); | |
| 868 | 'def sect: {"0":"r","1":"l","4":"n","22":"r","24":"r","39":"r","30":"0","31":"4","32":"2","33":"6","34":"1","35":"5","36":"3","37":"7","90":"8","91":"c","92":"a","93":"e","94":"9","95":"d","96":"b","97":"f"} as $t | |
| 869 | | ["30","31","32","33","34","35","36","37","90","91","92","93","94","95","96","97"] as | |
| 870 | # 38;5;n is one of the sixteen colours by its number; a background (48) and the other | |
| 871 | # 38/48 forms (256 above 15, truecolour ;2;r;g;b) are skipped with their numbers. | |
| 872 | | def codes: if length == 0 then [] | |
| 873 | elif .[0] == "38" and .[1] == "5" then [[.[2] | tonumber? // 99] // ""] + (.[3:] | codes) | |
| 874 | elif .[0] == "38" or .[0] == "48" then (if .[1] == "5" then .[3:] elif .[1] == "2" then .[5:] else .[1:] end) | codes | |
| 875 | else [.[0]] + (.[1:] | codes) end; | |
| 876 | (if . == "" then ["0"] else split(";") end) | [codes[] | [.] // empty | "\u00a7" + .] | join(""); | |
| 877 | def plain: gsub("\u001b\\[(?<p>[0-9;]*)m"; (.p // "" | sect)) | gsub("^(\u00a7r)+|(\u00a7r)+$"; "") | gsub("(\u00a7r)+"; "\u00a7r") | gsub("\u001b\\[[0-9;?]*[ -/]*[@-~]"; "") | gsub("\u001b[@-_]?"; "") | gsub("[\u0001-\u0008\u000b\u000c\u000e-\u001f\u007f]"; ""); | |
| 867 | 878 | {agent: 1, composeSha: , services: [0], logs: [0], results: [0], host: [0], diag: [0], people: [0], metrics: [0], snapshots: [0]} |
| 868 | 879 | | walk(if type == "string" then plain else . end)' >"$DIR/.sync.body" || return 1 |
| 869 | 880 | answer="$(curl -fsS -m 20 -H "@" -H 'content-type: application/json' --data-binary "@/.sync.body" "/api/v1/games/agent/sync")" || return 1 |
src/games/console.ts added +174
| @@ -0,0 +1,174 @@ | ||
| 1 | /** | |
| 2 | * A game server's console, read as the game writes it (forge games, G4 of #17284): its colours | |
| 3 | * (ANSI escapes, and Minecraft's own § codes) drawn instead of stripped, and a crash found in the | |
| 4 | * log and said in one line ("Crashed: Fabric could not load the mods: …"). | |
| 5 | * | |
| 6 | * What reaches the forge carries no escapes: the agent and the sync route turn a colour escape | |
| 7 | * into its § code and drop every other one (`sgrToSection`). Colour goes through the one ANSI | |
| 8 | * renderer (`web/render/ansi.ts`): § codes become the SGR they | |
| 9 | * mean first, so the input never reaches a style attribute or a class name, and every other | |
| 10 | * escape is dropped there. Each line is drawn on its own, as the game means it: a colour never | |
| 11 | * runs into the next line. | |
| 12 | */ | |
| 13 | ||
| 14 | import type { App } from "../app.ts"; | |
| 15 | import { announcedOr } from "../kernel/version.ts"; | |
| 16 | import { readCapped } from "../spawn/bounded_read.ts"; | |
| 17 | import { ansiLines } from "../web/render/ansi.ts"; | |
| 18 | ||
| 19 | /** § code → SGR: Minecraft's sixteen colours onto the renderer's eight, bold, underline, reset. */ | |
| 20 | const SECTION: Readonly<Record<string, string>> = { | |
| 21 | "0": "30", | |
| 22 | "1": "34", | |
| 23 | "2": "32", | |
| 24 | "3": "36", | |
| 25 | "4": "31", | |
| 26 | "5": "35", | |
| 27 | "6": "33", | |
| 28 | "7": "30", | |
| 29 | "8": "30", | |
| 30 | "9": "94", | |
| 31 | a: "92", | |
| 32 | b: "96", | |
| 33 | c: "91", | |
| 34 | d: "95", | |
| 35 | e: "93", | |
| 36 | f: "39", | |
| 37 | l: "1", | |
| 38 | n: "4", | |
| 39 | r: "0", | |
| 40 | }; | |
| 41 | ||
| 42 | /** A line with its § codes turned into the SGR escapes they mean; §k, §m and §o are dropped. */ | |
| 43 | export function sectionToSgr(line: string): string { | |
| 44 | return line.replace(/§([0-9a-fk-or])/gi, (_, c: string) => { | |
| 45 | const code = SECTION[c.toLowerCase()]; | |
| 46 | return code === undefined ? "" : `\x1b[${code}m`; | |
| 47 | }); | |
| 48 | } | |
| 49 | ||
| 50 | /** Console lines as escaped markup, each in its own colours. */ | |
| 51 | export function consoleHtml(lines: readonly string[]): string[] { | |
| 52 | return lines.map((l) => ansiLines(sectionToSgr(l), 1).lines[0] ?? ""); | |
| 53 | } | |
| 54 | ||
| 55 | /** Console lines as plain text: what a person reads with the colour codes gone. */ | |
| 56 | export function consoleText(lines: readonly string[]): string[] { | |
| 57 | // eslint-disable-next-line no-control-regex | |
| 58 | return lines.map((l) => sectionToSgr(l).replace(/\x1b\[[0-9;:]*[ -/]*[@-~]?|\x1b[^[]?|[\x00-\x08\x0b-\x1f\x7f]/g, "")); | |
| 59 | } | |
| 60 | ||
| 61 | // ---- crashes ---- | |
| 62 | ||
| 63 | /** A crash in a server's log: one line that says what happened, and the lines it came from. */ | |
| 64 | export interface Crash { | |
| 65 | readonly summary: string; | |
| 66 | /** The crash's lines, from where it starts, at most 120. */ | |
| 67 | readonly lines: readonly string[]; | |
| 68 | } | |
| 69 | ||
| 70 | const START = [ | |
| 71 | /---- Minecraft Crash Report ----/, | |
| 72 | /Encountered an unexpected exception/, | |
| 73 | /Exception in server tick loop/, | |
| 74 | /Failed to start the minecraft server/i, | |
| 75 | /Mod resolution encountered an incompatible mod set/, | |
| 76 | /Incompatible mods found!/, | |
| 77 | /UnsupportedClassVersionError/, | |
| 78 | /Error: LinkageError occurred while loading main class/, | |
| 79 | ]; | |
| 80 | // After a crash, the server came back: the crash is over. | |
| 81 | const DONE = /Done \(\d+(?:\.\d+)?s\)! For help, type "help"/; | |
| 82 | const EXCEPTION = /\b((?:[a-z][\w$]*\.)+[A-Z][\w$]*(?:Exception|Error|Throwable))\b(?::\s*(.*))?/; | |
| 83 | ||
| 84 | const strip = (l: string): string => | |
| 85 | consoleText([l])[0]! | |
| 86 | // A log prefix: "[12:00:00] [Server thread/ERROR]: " or "[init] ". | |
| 87 | .replace(/^(?:\[[^\]]*\]\s*)+:?\s*/, "") | |
| 88 | .trim(); | |
| 89 | const clip = (s: string, n: number): string => (s.length <= n ? s : `${s.slice(0, n - 1)}…`); | |
| 90 | ||
| 91 | /** What the crash's lines say, in one line. */ | |
| 92 | function summarize(lines: readonly string[]): string { | |
| 93 | const text = lines.map(strip); | |
| 94 | const find = (re: RegExp): RegExpExecArray | undefined => { | |
| 95 | for (const t of text) { | |
| 96 | const m = re.exec(t); | |
| 97 | if (m) return m; | |
| 98 | } | |
| 99 | return undefined; | |
| 100 | }; | |
| 101 | // Fabric names what is missing or clashing, one "- Mod …" line each. | |
| 102 | if (text.some((t) => /incompatible mod set|Incompatible mods found/.test(t))) { | |
| 103 | const first = | |
| 104 | text.find((t) => /^-\s*(?:Mod|Replace|Remove|Install)\b/.test(t)) ?? | |
| 105 | text.find((t) => /requires|incompatible with|is missing/.test(t)); | |
| 106 | return clip(`Fabric could not load the mods${first === undefined ? "" : `: ${first.replace(/^-\s*/, "")}`}`, 300); | |
| 107 | } | |
| 108 | if (text.some((t) => /UnsupportedClassVersionError|LinkageError occurred/.test(t))) | |
| 109 | return "The server's Java is too old for this Minecraft or a mod: set the image's Java (a :java21 tag) or an older VERSION"; | |
| 110 | const description = find(/^Description:\s*(.+)$/)?.[1]; | |
| 111 | const exception = find(EXCEPTION); | |
| 112 | const suspect = find(/^Suspected Mods?:\s*(.+)$/)?.[1] ?? find(/^Mod File:\s*(?:.*\/)?([^/]+)$/)?.[1]; | |
| 113 | const what = exception === undefined ? "" : `${exception[1]!.split(".").at(-1)}${exception[2] ? `: ${exception[2]}` : ""}`; | |
| 114 | const parts = [ | |
| 115 | description, | |
| 116 | what, | |
| 117 | suspect !== undefined && !/^None$/i.test(suspect.trim()) ? `suspected: ${suspect.trim()}` : undefined, | |
| 118 | ].filter((p): p is string => p !== undefined && p !== ""); | |
| 119 | return clip(parts.length === 0 ? (text.find((t) => t !== "") ?? "The server stopped with an error") : parts.join(" · "), 300); | |
| 120 | } | |
| 121 | ||
| 122 | /** | |
| 123 | * The last crash in a server's log lines, unless the server started fine after it: its summary | |
| 124 | * and its lines. | |
| 125 | */ | |
| 126 | export function crashOf(lines: readonly string[]): Crash | undefined { | |
| 127 | let start = -1; | |
| 128 | for (let i = lines.length - 1; i >= 0; i--) { | |
| 129 | const l = lines[i]!; | |
| 130 | if (DONE.test(l)) return undefined; | |
| 131 | if (START.some((re) => re.test(l))) { | |
| 132 | start = i; | |
| 133 | // A crash report is one block: keep going back while its own lines continue. | |
| 134 | if (!/---- Minecraft Crash Report ----/.test(l)) { | |
| 135 | for (let j = i - 1; j >= Math.max(0, i - 40); j--) { | |
| 136 | if (/---- Minecraft Crash Report ----/.test(lines[j]!)) { | |
| 137 | start = j; | |
| 138 | break; | |
| 139 | } | |
| 140 | if (DONE.test(lines[j]!)) break; | |
| 141 | } | |
| 142 | } | |
| 143 | break; | |
| 144 | } | |
| 145 | } | |
| 146 | if (start < 0) return undefined; | |
| 147 | const block = lines.slice(start, start + 120); | |
| 148 | return { summary: `Crashed: ${summarize(block)}`, lines: block }; | |
| 149 | } | |
| 150 | ||
| 151 | // ---- sharing a crash ---- | |
| 152 | ||
| 153 | const MCLOGS = "https://api.mclo.gs/1/log"; | |
| 154 | ||
| 155 | /** | |
| 156 | * Publish a crash's text on mclo.gs (its API: POST /1/log, form field `content`), at the | |
| 157 | * person's own click; mclo.gs keeps it where anyone with the link can read it. Its id, or why not. | |
| 158 | */ | |
| 159 | export async function shareOnMclogs(app: App, text: string): Promise<{ ok: true; id: string } | { ok: false; error: string }> { | |
| 160 | try { | |
| 161 | const res = await (app.config.mclogsFetch ?? fetch)(MCLOGS, { | |
| 162 | method: "POST", | |
| 163 | headers: { "content-type": "application/x-www-form-urlencoded", "user-agent": `forge/${announcedOr()} (open-platform.sh)` }, | |
| 164 | body: new URLSearchParams({ content: text.slice(0, 1_000_000) }).toString(), | |
| 165 | signal: AbortSignal.timeout(15_000), | |
| 166 | }); | |
| 167 | const bytes = await readCapped(res, 64_000); | |
| 168 | const answer = bytes === undefined ? {} : (JSON.parse(new TextDecoder().decode(bytes)) as { success?: boolean; id?: unknown; error?: unknown }); | |
| 169 | if (answer.success === true && typeof answer.id === "string" && /^[A-Za-z0-9]{1,32}$/.test(answer.id)) return { ok: true, id: answer.id }; | |
| 170 | return { ok: false, error: `mclo.gs did not take the log${typeof answer.error === "string" ? `: ${answer.error.slice(0, 200)}` : ` (${String(res.status)})`}.` }; | |
| 171 | } catch { | |
| 172 | return { ok: false, error: "mclo.gs did not answer in 15 s; nothing was shared." }; | |
| 173 | } | |
| 174 | } |
src/games/store.ts +9
| @@ -299,6 +299,15 @@ export function commandOf(db: Database, id: string): CommandState | undefined { | ||
| 299 | 299 | }; |
| 300 | 300 | } |
| 301 | 301 | |
| 302 | /** A service's RCON commands as typed, newest first, each once: the console's history. */ | |
| 303 | export const commandHistory = (db: Database, boxId: string, service: string, limit = 50): string[] => | |
| 304 | db | |
| 305 | .query<{ text: string }, [string, string, number]>( | |
| 306 | "SELECT text FROM game_command WHERE box_id = ?1 AND service = ?2 AND kind = 'rcon' GROUP BY text ORDER BY max(created_at) DESC, max(rowid) DESC LIMIT ?3", | |
| 307 | ) | |
| 308 | .all(boxId, service, limit) | |
| 309 | .map((r) => r.text); | |
| 310 | ||
| 302 | 311 | export const recentCommands = (db: Database, boxId: string, service: string, limit = 10): CommandState[] => |
| 303 | 312 | db |
| 304 | 313 | .query<{ id: string }, [string, string, number]>( |
src/http/games_routes.ts +2 −1
| @@ -13,7 +13,7 @@ import { sleeping } from "../games/sleep.ts"; | ||
| 13 | 13 | import { boxByToken, envFiles, markAsleep, recordSync, signJarUrls, type SyncBody } from "../games/store.ts"; |
| 14 | 14 | import { BODY_CAPS } from "../kernel/body_caps.ts"; |
| 15 | 15 | import { |
| 16 | gameBoxPage, gameCommandSubmit, gameEnvSubmit, gameGrantSubmit, gameJarDownload, gameJarSubmit, gamePluginSubmit, gamePeopleSubmit, gameHead, gameWorldSubmit, gamePowerSubmit, gameSleepSubmit, gameServicePage, gameSettingsSubmit, gameServiceStream, gameShellStream, gameShellSubmit, gamesPage, | |
| 16 | gameBoxPage, gameCommandSubmit, gameCrashShare, gameEnvSubmit, gameGrantSubmit, gameJarDownload, gameJarSubmit, gamePluginSubmit, gamePeopleSubmit, gameHead, gameWorldSubmit, gamePowerSubmit, gameSleepSubmit, gameServicePage, gameSettingsSubmit, gameServiceStream, gameShellStream, gameShellSubmit, gamesPage, | |
| 17 | 17 | } from "../web/pages/games.ts"; |
| 18 | 18 | import type { Ctx, Handler } from "./context.ts"; |
| 19 | 19 | import { InvalidJson } from "./json_body.ts"; |
| @@ -91,4 +91,5 @@ export function gamesRoutes(router: Router<Handler>): void { | ||
| 91 | 91 | router.add("POST", "/games/:box/:service/world", gameWorldSubmit); |
| 92 | 92 | router.add("POST", "/games/:box/:service/jar", gameJarSubmit); |
| 93 | 93 | router.add("POST", "/games/:box/:service/settings", gameSettingsSubmit); |
| 94 | router.add("POST", "/games/:box/:service/crash/share", gameCrashShare); | |
| 94 | 95 | } |
src/http/lazy_lists.ts +1
| @@ -623,6 +623,7 @@ export const OPERATIONS_ROUTES = [ | ||
| 623 | 623 | ["POST", "/games/:box/:service/world"], |
| 624 | 624 | ["POST", "/games/:box/:service/jar"], |
| 625 | 625 | ["POST", "/games/:box/:service/settings"], |
| 626 | ["POST", "/games/:box/:service/crash/share"], | |
| 626 | 627 | ["GET", "/resilience"], |
| 627 | 628 | ["GET", "/advisories"], |
| 628 | 629 | ["POST", "/advisories"], |
src/http/parseable_request.ts +38 −2
| @@ -97,18 +97,54 @@ export function dirtyJson(value: unknown, raw: RawText = NO_RAW_TEXT, depth = 0) | ||
| 97 | 97 | return false; |
| 98 | 98 | } |
| 99 | 99 | |
| 100 | /** | |
| 101 | * A terminal colour (SGR) as Minecraft's own § codes, printable, so a game console keeps its | |
| 102 | * colours past the strip below: the sixteen colours, bold (§l), underline (§n), and every reset | |
| 103 | * as §r. Anything else an SGR asks for (background, blink, truecolour) is dropped. | |
| 104 | */ | |
| 105 | const SGR = /\u001B\[([0-9;:]*)m/g; | |
| 106 | const SECTION_OF: Readonly<Record<number, string>> = { | |
| 107 | 0: "r", 1: "l", 4: "n", 22: "r", 24: "r", 39: "r", | |
| 108 | 30: "0", 31: "4", 32: "2", 33: "6", 34: "1", 35: "5", 36: "3", 37: "7", | |
| 109 | 90: "8", 91: "c", 92: "a", 93: "e", 94: "9", 95: "d", 96: "b", 97: "f", | |
| 110 | }; | |
| 111 | const SIXTEEN = [30, 31, 32, 33, 34, 35, 36, 37, 90, 91, 92, 93, 94, 95, 96, 97]; | |
| 112 | export function sgrToSection(text: string): string { | |
| 113 | if (!text.includes("\u001b[")) return text; | |
| 114 | return text | |
| 115 | .replace(SGR, (_, params: string) => { | |
| 116 | const codes = params === "" ? [0] : params.split(/[;:]/).map((p) => (p === "" ? 0 : Number(p))); | |
| 117 | let out = ""; | |
| 118 | for (let i = 0; i < codes.length; i++) { | |
| 119 | const c = codes[i]!; | |
| 120 | if (c === 38 || c === 48) { | |
| 121 | // 38;5;n: one of the sixteen colours by its number; a background, 256 above 15 and | |
| 122 | // truecolour (…;2;r;g;b) are skipped, their numbers with them. | |
| 123 | const n = codes[i + 2]; | |
| 124 | if (c === 38 && codes[i + 1] === 5 && n !== undefined && Number.isInteger(n) && n >= 0 && n < 16) out += `\u00a7${SECTION_OF[SIXTEEN[n]!]!}`; | |
| 125 | i += codes[i + 1] === 5 ? 2 : codes[i + 1] === 2 ? 4 : 0; | |
| 126 | } else if (SECTION_OF[c] !== undefined) out += `\u00a7${SECTION_OF[c]}`; | |
| 127 | } | |
| 128 | return out; | |
| 129 | }) | |
| 130 | // A reset says something only between colours: none at either end, one where several stand. | |
| 131 | .replace(/^(?:\u00a7r)+|(?:\u00a7r)+$/g, "") | |
| 132 | .replace(/(?:\u00a7r)+/g, "\u00a7r"); | |
| 133 | } | |
| 134 | ||
| 100 | 135 | /** A terminal's escape sequence (colour, cursor): CSI, then any other ESC with the byte after it. */ |
| 101 | 136 | const ESCAPES = /\u001B\[[0-9;?]*[ -\/]*[@-~]|\u001B[@-_]?/g; |
| 102 | 137 | const CONTROLS = /[\u0000-\u0008\u000B\u000C\u000E-\u001F\u007F]/g; |
| 103 | 138 | |
| 104 | 139 | /** |
| 105 | 140 | * 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 | |
| 141 | * control characters (tab, newline and carriage return stay); its colours kept as § codes | |
| 142 | * (`sgrToSection`). For a body whose strings are what a | |
| 107 | 143 | * program printed (a game server's log lines, a command's output), which a route keeps as text: |
| 108 | 144 | * cleaned, where a person's input is refused (`refuseDirtyJson`). |
| 109 | 145 | */ |
| 110 | 146 | export function cleanJson(value: unknown, depth = 0): unknown { |
| 111 | if (typeof value === "string") return value.replace(ESCAPES, "").replace(CONTROLS, ""); | |
| 147 | if (typeof value === "string") return sgrToSection(value).replace(ESCAPES, "").replace(CONTROLS, ""); | |
| 112 | 148 | if (typeof value !== "object" || value === null || depth > 64) return value; |
| 113 | 149 | if (Array.isArray(value)) return value.map((v) => cleanJson(v, depth + 1)); |
| 114 | 150 | return Object.fromEntries(Object.entries(value).map(([k, v]) => [cleanJson(k) as string, cleanJson(v, depth + 1)])); |
src/tui/screens/common.ts +11
| @@ -555,12 +555,17 @@ export function promptScreen( | ||
| 555 | 555 | mask?: boolean; |
| 556 | 556 | /** A line drawn under the field as it is typed or pasted; "" falls back to `hint`. */ |
| 557 | 557 | says?: (value: string) => string; |
| 558 | /** Earlier values, newest first: up and down walk them into the field. */ | |
| 559 | history?: readonly string[]; | |
| 558 | 560 | /** Return an error string to keep the prompt open with a message. */ |
| 559 | 561 | onSubmit: (value: string) => string | undefined | Promise<void>; |
| 560 | 562 | }, |
| 561 | 563 | ): Screen { |
| 562 | 564 | let value = o.value ?? ""; |
| 563 | 565 | let error: string | undefined; |
| 566 | // -1: what is being typed; 0..: a history entry. | |
| 567 | let back = -1; | |
| 568 | const typed = { value }; | |
| 564 | 569 | return { |
| 565 | 570 | title: o.title, |
| 566 | 571 | keys: [binding(["enter"], "submit"), binding(["esc"], "cancel")], |
| @@ -613,6 +618,12 @@ export function promptScreen( | ||
| 613 | 618 | ); |
| 614 | 619 | return true; |
| 615 | 620 | } |
| 621 | if ((e.key === "up" || e.key === "down") && o.history !== undefined && o.history.length > 0) { | |
| 622 | if (back === -1) typed.value = value; | |
| 623 | back = Math.max(-1, Math.min(o.history.length - 1, back + (e.key === "up" ? 1 : -1))); | |
| 624 | value = back === -1 ? typed.value : o.history[back]!; | |
| 625 | return true; | |
| 626 | } | |
| 616 | 627 | if (e.key === "backspace") { |
| 617 | 628 | value = [...value].slice(0, -1).join(""); |
| 618 | 629 | error = undefined; |
src/tui/screens/games.ts +9 −4
| @@ -13,6 +13,7 @@ | ||
| 13 | 13 | |
| 14 | 14 | import { movedKey } from "./moved_key.ts"; |
| 15 | 15 | import { emptyText } from "../../core/empty_words.ts"; |
| 16 | import { consoleText, crashOf } from "../../games/console.ts"; | |
| 16 | 17 | import { commitPolicy, policyOf, stateWords } from "../../games/sleep.ts"; |
| 17 | 18 | import { SHELL_SERVICE, queueShell } from "../../games/shell.ts"; |
| 18 | 19 | import { onSync } from "../../games/notify.ts"; |
| @@ -33,6 +34,7 @@ import { | ||
| 33 | 34 | listBoxes, |
| 34 | 35 | logsOf, |
| 35 | 36 | mayDo, |
| 37 | commandHistory, | |
| 36 | 38 | queueCommand, |
| 37 | 39 | recentCommands, |
| 38 | 40 | roleOn, |
| @@ -198,7 +200,9 @@ export function gameServiceScreen(f: Session, ctx: Ctx, box: GameBox, service: s | ||
| 198 | 200 | if (part === "console") { |
| 199 | 201 | // A world command's link shows as host and path only: its query string may be a signed secret. |
| 200 | 202 | const done = recentCommands(f.app.db, box.id, service, 5).map((c) => `> ${c.kind === "world" ? worldWords(c.text) : c.text} ${c.done ? (c.ok ? "ok" : "failed") : "waiting for the box"}${c.output === "" ? "" : `: ${c.output.split("\n")[0]}`}`); |
| 201 | return [...logsOf(f.app.db, box.id, service, 200).lines, ...done]; | |
| 203 | // The game's colour codes read as plain text here; a crash leads, in one line. | |
| 204 | const crash = crashOf(logsOf(f.app.db, box.id, service, 2_000).lines); | |
| 205 | return [...(crash === undefined ? [] : [crash.summary]), ...consoleText(logsOf(f.app.db, box.id, service, 200).lines), ...done]; | |
| 202 | 206 | } |
| 203 | 207 | if (part === "people") { |
| 204 | 208 | const { online, lists } = peopleOf(f.app.db, box.id, service); |
| @@ -239,12 +243,13 @@ export function gameServiceScreen(f: Session, ctx: Ctx, box: GameBox, service: s | ||
| 239 | 243 | `Uploading a jar is on the web only: /games/${box.name}/${service}.`, |
| 240 | 244 | ]; |
| 241 | 245 | }; |
| 242 | const ask = (title: string, label: string, run: (value: string) => Promise<string>): void => { | |
| 246 | const ask = (title: string, label: string, run: (value: string) => Promise<string>, history?: readonly string[]): void => { | |
| 243 | 247 | if (!operator()) return say(`You are not an operator of ${service}.`); |
| 244 | 248 | ctx.push( |
| 245 | 249 | promptScreen(ctx, screen, { |
| 246 | 250 | title, |
| 247 | 251 | label, |
| 252 | ...(history === undefined ? {} : { history }), | |
| 248 | 253 | // The prompt closes itself; what came of it is said on this screen's head line. |
| 249 | 254 | onSubmit: async (value) => { |
| 250 | 255 | say(await run(value)); |
| @@ -283,12 +288,12 @@ export function gameServiceScreen(f: Session, ctx: Ctx, box: GameBox, service: s | ||
| 283 | 288 | return true; |
| 284 | 289 | } |
| 285 | 290 | if (e.key === ":") |
| 286 | ask("RCON", `A command for ${service}`, async (text) => { | |
| 291 | ask("RCON", `A command for ${service} (up and down: earlier ones)`, async (text) => { | |
| 287 | 292 | if (text.trim() === "") return "Type a command."; |
| 288 | 293 | queueCommand(f.app.db, box.id, service, "rcon", text.trim(), f.user?.id ?? ""); |
| 289 | 294 | part = "console"; |
| 290 | 295 | return "Sent; the answer shows under the console."; |
| 291 | }); | |
| 296 | }, commandHistory(f.app.db, box.id, service)); | |
| 292 | 297 | else if (e.key === "e") |
| 293 | 298 | ask("Env", "KEY=VALUE (an empty value removes the key)", async (raw) => { |
| 294 | 299 | const at = raw.indexOf("="); |
src/web/pages/games.ts +60 −5
| @@ -24,6 +24,7 @@ import { | ||
| 24 | 24 | listBoxes, |
| 25 | 25 | logsOf, |
| 26 | 26 | mayDo, |
| 27 | commandHistory, | |
| 27 | 28 | queueCommand, |
| 28 | 29 | recentCommands, |
| 29 | 30 | roleOn, |
| @@ -44,7 +45,8 @@ import type { Ctx } from "../../http/context.ts"; | ||
| 44 | 45 | import { eventStream } from "../../http/sse.ts"; |
| 45 | 46 | import { notFoundPage, pageHead, signInFirst } from "../chrome.ts"; |
| 46 | 47 | import { field, readForm, type Form } from "../form.ts"; |
| 47 | import { html, type Html } from "../html.ts"; | |
| 48 | import { html, raw, type Html } from "../html.ts"; | |
| 49 | import { consoleHtml, consoleText, crashOf, shareOnMclogs } from "../../games/console.ts"; | |
| 48 | 50 | import { flashTo, page } from "../layout.ts"; |
| 49 | 51 | import { badge, btn, disclosure, field as input, row, rowList, time } from "../ui.ts"; |
| 50 | 52 | import { onSync } from "../../games/notify.ts"; |
| @@ -287,13 +289,30 @@ export const gamesConsoleJs = /* js */ ` | ||
| 287 | 289 | es.addEventListener('lines', function (e) { |
| 288 | 290 | var d; try { d = JSON.parse(e.data); } catch (_) { return; } |
| 289 | 291 | var stick = log.scrollTop + log.clientHeight >= log.scrollHeight - 8; |
| 290 | (d.lines || []).forEach(function (l) { log.appendChild(document.createTextNode(l + '\\n')); }); | |
| 292 | // Each line comes drawn by the forge (escaped markup in fixed colour classes). | |
| 293 | // Raw: the lines as kept, as text; else as the forge drew them (escaped markup in fixed classes). | |
| 294 | if (log.hasAttribute('data-raw')) (d.lines || []).forEach(function (l) { log.appendChild(document.createTextNode(l + '\\n')); }); | |
| 295 | else (d.html || []).forEach(function (h) { log.insertAdjacentHTML('beforeend', h + '\\n'); }); | |
| 291 | 296 | if (stick) log.scrollTop = log.scrollHeight; |
| 292 | 297 | (d.results || []).forEach(function (r) { |
| 293 | 298 | var el = document.getElementById('cmd-' + r.id); |
| 294 | 299 | if (el) el.textContent = (r.ok ? 'ok: ' : 'failed: ') + r.output; |
| 295 | 300 | }); |
| 296 | 301 | }); |
| 302 | // The command box walks its history with up and down, as a terminal does. | |
| 303 | var input = document.getElementById('game-command'); | |
| 304 | var list = document.getElementById('game-history'); | |
| 305 | if (!input || !list) return; | |
| 306 | var at = -1, typed = ''; | |
| 307 | input.addEventListener('keydown', function (e) { | |
| 308 | if (e.key !== 'ArrowUp' && e.key !== 'ArrowDown') return; | |
| 309 | var past = Array.prototype.map.call(list.options, function (o) { return o.value; }); | |
| 310 | if (past.length === 0) return; | |
| 311 | e.preventDefault(); | |
| 312 | if (at === -1) typed = input.value; | |
| 313 | at = Math.max(-1, Math.min(past.length - 1, at + (e.key === 'ArrowUp' ? 1 : -1))); | |
| 314 | input.value = at === -1 ? typed : past[at]; | |
| 315 | }); | |
| 297 | 316 | })(); |
| 298 | 317 | `; |
| 299 | 318 | |
| @@ -307,6 +326,12 @@ export async function gameServicePage(ctx: Ctx): Promise<Response> { | ||
| 307 | 326 | if (!SERVICE_NAME.test(service)) return notFoundPage(ctx); |
| 308 | 327 | const act = mayDo(role, "operator"); |
| 309 | 328 | const tail = logsOf(ctx.app.db, box.id, service, 300); |
| 329 | // A crash is looked for in the whole kept log, so a long report is not missed by the tail. | |
| 330 | const crash = crashOf(logsOf(ctx.app.db, box.id, service, 2_000).lines); | |
| 331 | const history = act ? commandHistory(ctx.app.db, box.id, service) : []; | |
| 332 | // Raw: the lines exactly as kept, § codes and all; the console's own view draws them. | |
| 333 | const rawView = ctx.url.searchParams.get("raw") === "1"; | |
| 334 | const shared = /^[A-Za-z0-9]{1,32}$/.test(ctx.url.searchParams.get("shared") ?? "") ? ctx.url.searchParams.get("shared")! : ""; | |
| 310 | 335 | const compose = await readCompose(ctx.app, box); |
| 311 | 336 | const env = compose === undefined ? {} : serviceEnv(compose.text, service); |
| 312 | 337 | const plugins = compose === undefined ? { plugins: [], modrinth: [] } : pluginsOf(compose.text, service); |
| @@ -325,7 +350,21 @@ export async function gameServicePage(ctx: Ctx): Promise<Response> { | ||
| 325 | 350 | ${numbersBlock(ctx, box, service)} |
| 326 | 351 | ${peopleBlock(ctx, box, service, act)} |
| 327 | 352 | <section class="settings-block"> |
| 328 | <h2>Console</h2> | |
| 353 | <h2>Console <a class="small" href="${rawView ? base : `${base}?raw=1`}">${rawView ? "Colour" : "Raw"}</a></h2> | |
| 354 | ${crash === undefined | |
| 355 | ? null | |
| 356 | : html`<div class="notice danger" role="alert"> | |
| 357 | <p><strong>${crash.summary}</strong></p> | |
| 358 | ${disclosure("The crash", html`<pre class="run-log mono" tabindex="0" aria-label="The crash of ${service}">${raw(consoleHtml(crash.lines).join("\n"))}</pre>`, { small: true })} | |
| 359 | ${shared !== "" | |
| 360 | ? html`<p>Shared publicly: <a href="https://mclo.gs/${shared}" rel="noreferrer noopener" target="_blank">mclo.gs/${shared}</a></p>` | |
| 361 | : act | |
| 362 | ? html`<form method="post" action="${base}/crash/share" class="row-fields"> | |
| 363 | ${btn("Share on mclo.gs", { variant: "secondary", size: "sm" })} | |
| 364 | <span class="muted small">This publishes the crash log on mclo.gs, where anyone with the link can read it.</span> | |
| 365 | </form>` | |
| 366 | : null} | |
| 367 | </div>`} | |
| 329 | 368 | <pre |
| 330 | 369 | id="game-log" |
| 331 | 370 | class="run-log mono" |
| @@ -333,12 +372,14 @@ export async function gameServicePage(ctx: Ctx): Promise<Response> { | ||
| 333 | 372 | aria-label="Console of ${service}" |
| 334 | 373 | data-stream="${base}/stream" |
| 335 | 374 | data-last="${String(tail.last)}" |
| 375 | ${rawView ? html`data-raw="1"` : null} | |
| 336 | 376 | > |
| 337 | ${tail.lines.join("\n")}${tail.lines.length > 0 ? "\n" : ""}</pre | |
| 377 | ${rawView ? tail.lines.join("\n") : raw(consoleHtml(tail.lines).join("\n"))}${tail.lines.length > 0 ? "\n" : ""}</pre | |
| 338 | 378 | > |
| 339 | 379 | ${act |
| 340 | 380 | ? html`<form method="post" action="${base}/command" class="row-fields"> |
| 341 | 381 | <input |
| 382 | id="game-command" | |
| 342 | 383 | class="input mono" |
| 343 | 384 | name="text" |
| 344 | 385 | required |
| @@ -346,7 +387,9 @@ ${tail.lines.join("\n")}${tail.lines.length > 0 ? "\n" : ""}</pre | ||
| 346 | 387 | placeholder="say hello" |
| 347 | 388 | aria-label="Command for ${service}" |
| 348 | 389 | autocomplete="off" |
| 390 | list="game-history" | |
| 349 | 391 | /> |
| 392 | <datalist id="game-history">${history.map((h) => html`<option value="${h}"></option>`)}</datalist> | |
| 350 | 393 | ${btn("Send", { variant: "secondary" })} |
| 351 | 394 | </form>` |
| 352 | 395 | : null} |
| @@ -445,7 +488,7 @@ export function gameServiceStream(ctx: Ctx): Response { | ||
| 445 | 488 | const results = [...pending].map((id) => commandOf(ctx.app.db, id)).filter((c) => c !== undefined && c.done); |
| 446 | 489 | for (const r of results) pending.delete(r!.id); |
| 447 | 490 | if (got.lines.length > 0 || results.length > 0) |
| 448 | emit("lines", { lines: got.lines, results: results.map((r) => ({ id: r!.id, ok: r!.ok, output: r!.output })) }); | |
| 491 | emit("lines", { html: consoleHtml(got.lines), lines: got.lines, results: results.map((r) => ({ id: r!.id, ok: r!.ok, output: r!.output })) }); | |
| 449 | 492 | }), |
| 450 | 493 | ); |
| 451 | 494 | } |
| @@ -512,6 +555,18 @@ async function operatorForm(ctx: Ctx): Promise<{ box: GameBox; service: string; | ||
| 512 | 555 | return { box: got.box, service, form }; |
| 513 | 556 | } |
| 514 | 557 | |
| 558 | // POST /games/:box/:service/crash/share: the person's own click publishes the crash on mclo.gs. | |
| 559 | export async function gameCrashShare(ctx: Ctx): Promise<Response> { | |
| 560 | const got = await operatorForm(ctx); | |
| 561 | if (got instanceof Response) return got; | |
| 562 | const back = `/games/${got.box.name}/${got.service}`; | |
| 563 | const crash = crashOf(logsOf(ctx.app.db, got.box.id, got.service, 2_000).lines); | |
| 564 | if (crash === undefined) return flashTo(ctx, back, { tone: "danger", message: "There is no crash in the log to share." }); | |
| 565 | const shared = await shareOnMclogs(ctx.app, consoleText(crash.lines).join("\n")); | |
| 566 | if (!shared.ok) return flashTo(ctx, back, { tone: "danger", message: shared.error }); | |
| 567 | return flashTo(ctx, `${back}?shared=${shared.id}`, { message: `Shared publicly on mclo.gs: https://mclo.gs/${shared.id}` }); | |
| 568 | } | |
| 569 | ||
| 515 | 570 | // POST /games/:box/:service/command: an RCON command, queued for the box's next sync. |
| 516 | 571 | export async function gameCommandSubmit(ctx: Ctx): Promise<Response> { |
| 517 | 572 | const got = await operatorForm(ctx); |
test/egress-literals.test.ts +1
| @@ -35,6 +35,7 @@ const NOT_CALLED: Record<string, string> = { | ||
| 35 | 35 | "forge.open-platform.sh": "the upstream repository's link (core/upstream.ts) and a link-relation URI (apps/proxy.ts)", |
| 36 | 36 | "git.open-platform.sh": "placeholder in the follow-upstream form", |
| 37 | 37 | "jsonfeed.org": "the JSON Feed version URI, a name and not a request", |
| 38 | "mclo.gs": "a shared crash log's page, linked for a person on /games; the forge posts to api.mclo.gs", | |
| 38 | 39 | "ui.shadcn.com": "the registry schema URIs in registry/items.ts, names the shadcn CLI reads and the forge never requests", |
| 39 | 40 | "aka.ms": "the Minecraft EULA link in the games design text, shown to the user and never requested", |
| 40 | 41 | "ntfy.sh": "placeholder in the account notification field", |
test/engine-crossing.test.ts +2
| @@ -176,6 +176,7 @@ describe("every setting is on one list, and what crosses is data", () => { | ||
| 176 | 176 | "disk", |
| 177 | 177 | "hostFree", |
| 178 | 178 | "mailer", |
| 179 | "mclogsFetch", | |
| 179 | 180 | "memory", |
| 180 | 181 | "memoryWatch", |
| 181 | 182 | "releaseSend", |
| @@ -208,6 +209,7 @@ const whole = (dataDir: string): Required<ForgeConfig> => ({ | ||
| 208 | 209 | hostFree: () => 1, |
| 209 | 210 | memoryWatch: { grown: () => undefined }, |
| 210 | 211 | releaseSend: async () => true, |
| 212 | mclogsFetch: async () => new Response("{}"), | |
| 211 | 213 | memory: () => 1, |
| 212 | 214 | codeBudgetMs: 30, |
| 213 | 215 | port: 8080, |
test/game-console-colour.test.ts added +161
| @@ -0,0 +1,161 @@ | ||
| 1 | /** | |
| 2 | * The game console read as the game writes it (G4 of #17284): § codes and ANSI escapes drawn as | |
| 3 | * the renderer's fixed classes, each line on its own, nothing else let through; and a crash found | |
| 4 | * in the log and said in one line. | |
| 5 | */ | |
| 6 | import { afterAll, beforeAll, describe, expect, test } from "bun:test"; | |
| 7 | import { mkdtemp, rm } from "node:fs/promises"; | |
| 8 | import { tmpdir } from "node:os"; | |
| 9 | import { join } from "node:path"; | |
| 10 | import { commitToBranch, createRepo } from "../src/actions/repos.ts"; | |
| 11 | import { createApp, type App } from "../src/app.ts"; | |
| 12 | import { createToken } from "../src/core/tokens.ts"; | |
| 13 | import { createUser, getUserByName } from "../src/core/users.ts"; | |
| 14 | import { boxNamed, createGameBox, queueCommand, recordSync } from "../src/games/store.ts"; | |
| 15 | import { sgrToSection } from "../src/http/parseable_request.ts"; | |
| 16 | import { forgeHttp, type ForgeHttp } from "../src/http/server.ts"; | |
| 17 | import { consoleHtml, consoleText, crashOf, sectionToSgr } from "../src/games/console.ts"; | |
| 18 | ||
| 19 | test("a colour escape becomes its § code before the escapes are stripped; resets at either end go", () => { | |
| 20 | expect(sgrToSection("\u001b[0;39m[12:00] \u001b[1;91mFAIL\u001b[0m \u001b[38;5;10mok\u001b[0m \u001b[48;5;1mbg\u001b[0m")).toBe("[12:00] \u00a7l\u00a7cFAIL\u00a7r \u00a7aok\u00a7r bg"); | |
| 21 | }); | |
| 22 | ||
| 23 | test("§ codes become the SGR they mean; obfuscated, strikethrough and italic are dropped", () => { | |
| 24 | expect(sectionToSgr("§cRed §lbold§r plain §kx§mx§ox")).toBe("\x1b[91mRed \x1b[1mbold\x1b[0m plain xxx"); | |
| 25 | }); | |
| 26 | ||
| 27 | test("console lines are drawn in colour, each on its own, escaped, and with no other escape", () => { | |
| 28 | const [a, b, c] = consoleHtml(["§aJoined §f<b>alice</b>", "plain after a colour", "\x1b[33mwarn\x1b[0m \x1b]0;title\x07done"]); | |
| 29 | expect(a).toBe('<span class="ansi-green">Joined </span><b>alice</b>'); | |
| 30 | // The colour of one line never runs into the next. | |
| 31 | expect(b).toBe("plain after a colour"); | |
| 32 | expect(c).toBe('<span class="ansi-yellow">warn</span> done'); | |
| 33 | expect(consoleText(["§aJoined §falice", "\x1b[31mred\x1b[0m"])).toEqual(["Joined alice", "red"]); | |
| 34 | }); | |
| 35 | ||
| 36 | test("a crash report is found and said in one line: description, exception, suspected mod", () => { | |
| 37 | const log = [ | |
| 38 | "[12:00:00] [Server thread/INFO]: Starting minecraft server version 1.21.1", | |
| 39 | "---- Minecraft Crash Report ----", | |
| 40 | "// Uh... Did I do that?", | |
| 41 | "Time: 2026-12-01 20:00:00", | |
| 42 | "Description: Exception in server tick loop", | |
| 43 | "", | |
| 44 | "java.lang.NoSuchMethodError: 'void net.minecraft.class_123.method_456()'", | |
| 45 | "\tat me.jellysquid.mods.sodium.Foo.bar(Foo.java:10)", | |
| 46 | "Suspected Mods: Sodium (sodium), Version: 0.6.0", | |
| 47 | ]; | |
| 48 | const crash = crashOf(log); | |
| 49 | expect(crash?.summary).toBe( | |
| 50 | "Crashed: Exception in server tick loop · NoSuchMethodError: 'void net.minecraft.class_123.method_456()' · suspected: Sodium (sodium), Version: 0.6.0", | |
| 51 | ); | |
| 52 | expect(crash?.lines[0]).toBe("---- Minecraft Crash Report ----"); | |
| 53 | // Started fine since: no crash to tell of. | |
| 54 | expect(crashOf([...log, '[12:01:00] [Server thread/INFO]: Done (3.2s)! For help, type "help"'])).toBeUndefined(); | |
| 55 | }); | |
| 56 | ||
| 57 | test("Fabric's incompatible mod set and a Java too old are said plainly", () => { | |
| 58 | expect( | |
| 59 | crashOf([ | |
| 60 | "[12:00:00] [main/ERROR]: Incompatible mods found!", | |
| 61 | "net.fabricmc.loader.impl.FormattedException: Mod resolution encountered an incompatible mod set!", | |
| 62 | "A potential solution has been determined:", | |
| 63 | "\t - Install fabric-api, any version.", | |
| 64 | "Unmet dependency listing:", | |
| 65 | "\t - Mod 'Lithium' (lithium) 0.14.0 requires any version of fabric-api, which is missing!", | |
| 66 | ])?.summary, | |
| 67 | ).toBe("Crashed: Fabric could not load the mods: Install fabric-api, any version."); | |
| 68 | expect( | |
| 69 | crashOf([ | |
| 70 | 'Exception in thread "main" java.lang.UnsupportedClassVersionError: net/minecraft/server/Main has been compiled by a more recent version', | |
| 71 | ])?.summary, | |
| 72 | ).toBe("Crashed: The server's Java is too old for this Minecraft or a mod: set the image's Java (a :java21 tag) or an older VERSION"); | |
| 73 | expect(crashOf(['[12:00:00] [Server thread/INFO]: Done (3.2s)! For help, type "help"'])).toBeUndefined(); | |
| 74 | }); | |
| 75 | ||
| 76 | describe("the service page", () => { | |
| 77 | let dir = ""; | |
| 78 | let app: App; | |
| 79 | let http: ForgeHttp; | |
| 80 | let tok = ""; | |
| 81 | let boxTok = ""; | |
| 82 | const shared: string[] = []; | |
| 83 | const get = async (path: string) => (await http.handle(new Request(`http://forge.test${path}`, { headers: { authorization: `Bearer ${tok}` } }))).text(); | |
| 84 | ||
| 85 | beforeAll(async () => { | |
| 86 | dir = await mkdtemp(join(tmpdir(), "forge-game-console-")); | |
| 87 | app = createApp({ | |
| 88 | dataDir: dir, | |
| 89 | port: 0, | |
| 90 | mclogsFetch: async (_url, init) => { | |
| 91 | shared.push(new URLSearchParams(String(init.body)).get("content") ?? ""); | |
| 92 | return Response.json({ success: true, id: "Ab12Cd3", url: "https://mclo.gs/Ab12Cd3" }); | |
| 93 | }, | |
| 94 | }); | |
| 95 | http = forgeHttp(app); | |
| 96 | const made = await createUser(app.db, { origin: "seed", trusted: true, username: "alice", email: "[email protected]", password: "a-good-passphrase", adminIfFirst: true }); | |
| 97 | if (!made.ok) throw new Error(made.error); | |
| 98 | const alice = getUserByName(app.db, "alice")!; | |
| 99 | tok = createToken(app.db, alice.id, "admin", "admin").token; | |
| 100 | const repo = await createRepo(app, alice, { name: "mc-network", visibility: "private" }); | |
| 101 | if (!repo.ok) throw new Error(String(repo.error)); | |
| 102 | const seeded = await commitToBranch(app, alice, repo.value, { message: "network", files: [{ path: "docker-compose.yml", content: "services:\n hub:\n image: itzg/minecraft-server\n" }] }); | |
| 103 | if (!seeded.ok) throw new Error(JSON.stringify(seeded.error)); | |
| 104 | boxTok = createGameBox(app.db, { name: "net", repo: "alice/mc-network" }).token; | |
| 105 | const box = boxNamed(app.db, "net")!; | |
| 106 | recordSync(app.db, box, { | |
| 107 | composeSha: "", | |
| 108 | services: [{ name: "hub", state: "exited", health: "", startedAt: "", cpuPct: 0, memMiB: 0 }], | |
| 109 | logs: { hub: ["§aalice joined the game", "---- Minecraft Crash Report ----", "Description: Exception in server tick loop", "java.lang.IllegalStateException: boom"] }, | |
| 110 | results: [], | |
| 111 | host: {}, | |
| 112 | }); | |
| 113 | for (const text of ["say one", "op alice", "say one"]) queueCommand(app.db, box.id, "hub", "rcon", text, alice.id); | |
| 114 | }, 30_000); | |
| 115 | afterAll(async () => { | |
| 116 | app.close(); | |
| 117 | await rm(dir, { recursive: true, force: true }); | |
| 118 | }); | |
| 119 | ||
| 120 | test("the console is drawn in colour, a crash leads in one line, and the command box carries its history", async () => { | |
| 121 | const page = await get("/games/net/hub"); | |
| 122 | expect(page).toContain('<span class="ansi-green">alice joined the game</span>'); | |
| 123 | expect(page).not.toContain("§a"); | |
| 124 | expect(page).toContain("Crashed: Exception in server tick loop · IllegalStateException: boom"); | |
| 125 | // Newest first, each once. | |
| 126 | expect(page.indexOf('<option value="say one">')).toBeLessThan(page.indexOf('<option value="op alice">')); | |
| 127 | expect(page.split('<option value="say one">')).toHaveLength(2); | |
| 128 | }); | |
| 129 | ||
| 130 | test("a colour escape from the box is kept as its § code and drawn; Raw shows the line as kept", async () => { | |
| 131 | const res = await http.handle( | |
| 132 | new Request("http://forge.test/api/v1/games/agent/sync", { | |
| 133 | method: "POST", | |
| 134 | headers: { authorization: `Bearer ${boxTok}`, "content-type": "application/json" }, | |
| 135 | body: JSON.stringify({ agent: 1, composeSha: "", logs: { hub: ["\u001b[0;33mBob\u001b[0m left the game"] }, results: [] }), | |
| 136 | }), | |
| 137 | ); | |
| 138 | expect(res.status).toBe(200); | |
| 139 | expect(await get("/games/net/hub")).toContain('<span class="ansi-yellow">Bob</span> left the game'); | |
| 140 | const raw = await get("/games/net/hub?raw=1"); | |
| 141 | expect(raw).toContain("\u00a76Bob\u00a7r left the game"); | |
| 142 | expect(raw).toContain('data-raw="1"'); | |
| 143 | }); | |
| 144 | ||
| 145 | test("Share on mclo.gs says it publishes, posts the crash as text, and links where it went", async () => { | |
| 146 | expect(await get("/games/net/hub")).toContain("This publishes the crash log on mclo.gs, where anyone with the link can read it."); | |
| 147 | const r = await http.handle( | |
| 148 | new Request("http://forge.test/games/net/hub/crash/share", { | |
| 149 | method: "POST", | |
| 150 | headers: { authorization: `Bearer ${tok}`, origin: "http://forge.test", "content-type": "application/x-www-form-urlencoded" }, | |
| 151 | body: "", | |
| 152 | }), | |
| 153 | ); | |
| 154 | expect(r.status).toBe(303); | |
| 155 | expect(r.headers.get("location")).toContain("/games/net/hub?shared=Ab12Cd3"); | |
| 156 | expect(shared).toHaveLength(1); | |
| 157 | expect(shared[0]).toContain("---- Minecraft Crash Report ----"); | |
| 158 | expect(shared[0]).not.toContain("\u00a7"); | |
| 159 | expect(await get("/games/net/hub?shared=Ab12Cd3")).toContain('href="https://mclo.gs/Ab12Cd3"'); | |
| 160 | }); | |
| 161 | }); |
test/game-sync-plain.test.ts +3 −3
| @@ -98,7 +98,7 @@ esac | ||
| 98 | 98 | expect(first.services).toEqual([expect.objectContaining({ name: "hub" })]); |
| 99 | 99 | expect(first.logs["hub"]).toEqual(["[mc-image-helper] Downloaded", "[12:00:01 INFO]: Alice joined the game", "� old colour"]); |
| 100 | 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" })]); | |
| 101 | expect(second.results).toEqual([expect.objectContaining({ id: "c1", output: "\u00a76There are 1 of a max of 20 players online: Alice" })]); | |
| 102 | 102 | } finally { |
| 103 | 103 | forge.stop(true); |
| 104 | 104 | await rm(box, { recursive: true, force: true }); |
| @@ -161,9 +161,9 @@ describe("the forge", () => { | ||
| 161 | 161 | ).toBe(true); |
| 162 | 162 | }); |
| 163 | 163 | |
| 164 | test("cleanJson: escapes and control characters out of every string and key; tab, newline and carriage return stay", () => { | |
| 164 | test("cleanJson: escapes and control characters out of every string and key, colours kept as § codes; tab, newline and carriage return stay", () => { | |
| 165 | 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], | |
| 166 | k: ["\u00a74red", "a\tb\nc\r", "osc0;t", 3, null], | |
| 167 | 167 | }); |
| 168 | 168 | }); |
| 169 | 169 | }); |
new above
offline
Principle 6 and 7: a boxed notice around the crash, with a disclosure and a form nested inside. Use plain rows: the one-line summary, the folded crash, the share row.