Public: anyone can read this; the crew can change it.
Games survival step 2a: BlueMap behind login at /games/<box>/<server>/map, no published box port #18100
Merged 10h ago, live in production
scout/forge:scout/18087-games-survival-step-2a-bluemap-behind-lo → main 0 commits fork 3 threads · 3 unresolved
19 files
changed +608
−7
- docs/features/game-map.md
- src/games/agent.sh
- src/games/map.ts
- src/games/map_token.ts
- src/games/map_words.ts
- src/games/store.ts
- src/http/games_map.ts
- src/http/games_routes.ts
- src/http/lazy_lists.ts
- src/tui/screens/game_map.ts
- src/tui/screens/games.ts
- src/web/pages/games.ts
- test/budgets/unfixtured/games-box-service-m-pass-path.json
- test/budgets/unfixtured/games-box-service-map.json
- test/games-map.test.ts
- test/no-polling.test.ts
- test/open-routes-floor.test.ts
- test/security-floor-routes.test.ts
- test/timers-named.test.ts
docs/features/game-map.md added +16
| @@ -0,0 +1,16 @@ | ||
| 1 | --- | |
| 2 | topic: Hosting forges for others, and getting paid | |
| 3 | row: Game live map | |
| 4 | --- | |
| 5 | # Game live map | |
| 6 | ||
| 7 | A game server's BlueMap, a live 3D map with its players, is served by the forge behind login at | |
| 8 | `/games/<box>/<server>/map` (#18087, step 2a of #18059). The box publishes no port for it. | |
| 9 | ||
| 10 | - **The choice, a relay and not static files:** BlueMap's web server listens on the box's own loopback (`127.0.0.1:8100`) and the box's agent, which only ever calls out, fetches each file the forge asks for (`src/games/map.ts`, `kind: map`, the path as text) at its next light check-in (a second or two) and answers it as `<gzip 0|1>` and base64, 600 KB of file at most. The forge serves it and deletes the row: no tile is kept in the database. Static files would need the agent to upload a world's tiles, a second unbounded copy of the world on the forge, and would have no live players layer. The cost is a check-in's wait on a first look; the browser keeps a file for a minute. | |
| 11 | - **Set BlueMap up:** install it from the server's Mods block, then in its config: webserver `ip: "127.0.0.1"`, `port: 8100` (the agent reads `FORGE_GAME_MAP_PORT` for another), and in `core.conf` `render-thread-count: 1`, so rendering takes one thread of a shared box. Publish nothing. | |
| 12 | - **Use it, on the page:** the server's page has a "Live map" block, one sentence and an "Open the map" button. Reading needs a viewer's grant on the server, as its console does; a person without one, or signed out, gets the sign-in or a 404. The setup above is shown nowhere on the page: BlueMap not listening is a 502 that names what to set. | |
| 13 | - **Use it, in the terminal:** `w` on a service's screen opens `src/tui/screens/game_map.ts`: the same sentence and the map's address, and `p` asks the box for the map's front page and says whether it answered. | |
| 14 | - **What is refused:** a path with `..`, `//`, a leading dot, a query, or an extension the map does not use (`html js css json png jpg webp svg ico woff2 txt prbm gz bin wasm`); at most 64 files waiting on one box and 24 on one person; no answer in 12 s is a 504 saying the box is asleep or its agent has not checked in; BlueMap not listening is a 502 that says so. | |
| 15 | - **What the map's scripts may do, nothing of the viewer's:** the files are the box owner's, scripts included, so they never run with the forge's session. `/map` is the one door that reads the cookie; it buys a pass (`src/games/map_token.ts`: person, server and the hour it ends, signed with the forge's key) and redirects to `/games/<box>/<server>/m/<pass>/`. Every file under it answers from the pass alone, with `sandbox allow-scripts` in its policy: the document has no origin, sends no cookie, and a call to the forge's API from it is a stranger's. Its files are read by CORS without credentials. The pass lasts an hour, a grant taken back ends it at the next file, and the policy lets the scripts talk only to the map's own path. | |
| 16 | - **How it holds up:** a first look asks a few dozen files; the agent hands back up to eight a tick (about 1.2 MB at most in one sync, under the 2 MiB cap) and the box's own commands are handed before any map file, so a pan never waits in front of a stop. It has been run against faked answers only, not a live BlueMap; the 64 and 24 are judgments to tune with one. |
src/games/agent.sh +56
| @@ -723,6 +723,11 @@ run() { | ||
| 723 | 723 | shell_start "" "" |
| 724 | 724 | return |
| 725 | 725 | fi |
| 726 | # A map file is the box's too (#18087): fetched from BlueMap's loopback web server beside the sync. | |
| 727 | if [ "" = "map" ]; then | |
| 728 | map_start "" "" | |
| 729 | return | |
| 730 | fi | |
| 726 | 731 | if ! [[ "" =~ ]]; then |
| 727 | 732 | out="refused: the service name is not one compose can have" |
| 728 | 733 | ok=false |
| @@ -1086,6 +1091,55 @@ shell_tick() { | ||
| 1086 | 1091 | done |
| 1087 | 1092 | } |
| 1088 | 1093 | |
| 1094 | # ---- the live map (#18087): the forge asks for one file of BlueMap's web root (`kind: map`, the | |
| 1095 | # path as text); it is fetched from the box's own loopback (no published port), 600 KB at most, | |
| 1096 | # and answered as `<gzip 0|1>\n<base64>` at the next tick. A path is checked again here. ---- | |
| 1097 | ||
| 1098 | MAPS="/.map" | |
| 1099 | map_start() { | |
| 1100 | local id="$1" path="$2" | |
| 1101 | [[ "" =~ ]] || return | |
| 1102 | if ! [[ "" =~ ^[A-Za-z0-9][A-Za-z0-9._/-]{0,255}$ ]] || [[ "" == *..* ]] || [[ "" == *//* ]]; then | |
| 1103 | keep_result "" false "refused: not a map file" | |
| 1104 | return | |
| 1105 | fi | |
| 1106 | mkdir -p "" | |
| 1107 | ( | |
| 1108 | code="$(curl -sS -m 10 --max-filesize 600000 -D "/.head" -o "/.body" -w '%{http_code}' "http://127.0.0.1:/" 2>/dev/null)" | |
| 1109 | echo "" >"/.rc.next" && mv "/.rc.next" "/.rc" | |
| 1110 | ) & | |
| 1111 | } | |
| 1112 | ||
| 1113 | # Each tick: every fetch that ended becomes a result; a few at a time so a sync stays small. | |
| 1114 | map_tick() { | |
| 1115 | local f id rc gz ok n=0 sent=0 est | |
| 1116 | for f in ""/*.rc; do | |
| 1117 | [ -e "" ] || continue | |
| 1118 | [ "" -lt 8 ] || break | |
| 1119 | id="$(basename "" .rc)" | |
| 1120 | # The forge reads 2 MiB of one sync: answers are taken until about 1.2 MB of base64 (a file of | |
| 1121 | # 600 KB is 800 KB of it), the rest at the next tick. | |
| 1122 | est= | |
| 1123 | [ "" -eq 0 ] || [ -le 1200000 ] || break | |
| 1124 | n= | |
| 1125 | sent= | |
| 1126 | rc="$(cat "")" | |
| 1127 | gz=0 | |
| 1128 | grep -qi '^content-encoding: *gzip' "/.head" 2>/dev/null && gz=1 | |
| 1129 | if [ "" = 200 ]; then | |
| 1130 | ok=true | |
| 1131 | { printf '%s\n' ""; base64 -w0 "/.body"; } >"/.out" | |
| 1132 | else | |
| 1133 | ok=false | |
| 1134 | printf 'status %s' "" >"/.out" | |
| 1135 | fi | |
| 1136 | # --rawfile: a file's base64 is past the limit of one argument. | |
| 1137 | jq -c --arg id "" --argjson ok "" --rawfile out "/.out" '. + [{id: $id, ok: $ok, output: $out}]' "/.results" >"/.results.next" && | |
| 1138 | mv "/.results.next" "/.results" | |
| 1139 | rm -f "/".* | |
| 1140 | done | |
| 1141 | } | |
| 1142 | ||
| 1089 | 1143 | # Write what the answer carries; bring the project up when the compose or an env file changed. |
| 1090 | 1144 | apply() { |
| 1091 | 1145 | local answer="$1" sha changed=0 changed_env=0 name |
| @@ -2006,6 +2060,7 @@ light_sync() { | ||
| 2006 | 2060 | for round in 1 2; do |
| 2007 | 2061 | job_tick |
| 2008 | 2062 | shell_tick |
| 2063 | map_tick | |
| 2009 | 2064 | POLLED="" |
| 2010 | 2065 | if [ -f "/.desk.due" ] && desk_here; then desk_take; else echo '[]' >"/.sync.ask"; fi |
| 2011 | 2066 | json_or '[]' <"/.results" >"/.sync.results" |
| @@ -2049,6 +2104,7 @@ while :; do | ||
| 2049 | 2104 | ! grep -q '^no-volume ' "" 2>/dev/null || [ -z "$(volume_device)" ] || exit 0 |
| 2050 | 2105 | job_tick |
| 2051 | 2106 | shell_tick |
| 2107 | map_tick | |
| 2052 | 2108 | rename_strays |
| 2053 | 2109 | sync || echo "forge-game-agent: sync failed; again in s" >&2 |
| 2054 | 2110 | job_tick |
src/games/map.ts added +110
| @@ -0,0 +1,110 @@ | ||
| 1 | /** | |
| 2 | * The live map (#18087, step 2a of #18059): BlueMap's web server stays on the box's own loopback | |
| 3 | * (`127.0.0.1:8100`, no published port) and the box's agent relays it. The agent only ever calls | |
| 4 | * out, so a page asks as a command (`kind: "map"`, the text is the path under BlueMap's web root), | |
| 5 | * the agent fetches that file from loopback at its next light check-in (a second or two), and its | |
| 6 | * answer is the file: `<gzip 0|1>\n<base64>`. The forge reads it, deletes the row (a tile is never | |
| 7 | * kept in the database) and serves it behind login with the security floor on every response. | |
| 8 | * | |
| 9 | * Why a relay and not static files: BlueMap's live layer (players, the day's sun) is a request | |
| 10 | * the browser makes and static copies of a world's tiles would be a second, unbounded store of | |
| 11 | * the world on the forge. The cost is a check-in's latency on a first look; a tile is cached by | |
| 12 | * the browser for a minute, so a pan after it costs nothing. | |
| 13 | */ | |
| 14 | ||
| 15 | import type { App } from "../app.ts"; | |
| 16 | import { err, ok, type Result } from "../kernel/result.ts"; | |
| 17 | import { watchBox } from "./notify.ts"; | |
| 18 | import { commandOf, queueCommand, type GameBox } from "./store.ts"; | |
| 19 | import { mapWords } from "./map_words.ts"; | |
| 20 | ||
| 21 | /** A file under BlueMap's web root: plain names and slashes, no `..`, no dot-files, no query. */ | |
| 22 | const PATH = /^[A-Za-z0-9][A-Za-z0-9._/-]{0,255}$/; | |
| 23 | /** What the relay serves, by extension; its type is the forge's to say, never the box's. */ | |
| 24 | const TYPES: Readonly<Record<string, string>> = { | |
| 25 | html: "text/html; charset=utf-8", | |
| 26 | js: "text/javascript; charset=utf-8", | |
| 27 | mjs: "text/javascript; charset=utf-8", | |
| 28 | css: "text/css; charset=utf-8", | |
| 29 | json: "application/json", | |
| 30 | png: "image/png", | |
| 31 | jpg: "image/jpeg", | |
| 32 | jpeg: "image/jpeg", | |
| 33 | webp: "image/webp", | |
| 34 | svg: "image/svg+xml", | |
| 35 | ico: "image/x-icon", | |
| 36 | woff2: "font/woff2", | |
| 37 | woff: "font/woff", | |
| 38 | ttf: "font/ttf", | |
| 39 | txt: "text/plain; charset=utf-8", | |
| 40 | prbm: "application/octet-stream", | |
| 41 | gz: "application/gzip", | |
| 42 | bin: "application/octet-stream", | |
| 43 | wasm: "application/wasm", | |
| 44 | }; | |
| 45 | /** How long a file is waited for: a few check-ins. */ | |
| 46 | export const MAP_WAIT_MS = 12_000; | |
| 47 | /** | |
| 48 | * The most files asked of one box at once, and of one person: a map's first look asks a few dozen, | |
| 49 | * and one viewer cannot fill the box's lane. The agent hands back about eight a second, so a full | |
| 50 | * lane drains inside the wait. | |
| 51 | */ | |
| 52 | export const MAP_PENDING = 64; | |
| 53 | export const MAP_PER_PERSON = 24; | |
| 54 | ||
| 55 | /** A file asked for: its path under BlueMap's web root and the type the forge says it is. */ | |
| 56 | export interface MapAsk { | |
| 57 | readonly path: string; | |
| 58 | readonly type: string; | |
| 59 | } | |
| 60 | ||
| 61 | /** The file asked for, or why not. An empty path is the map's front page. */ | |
| 62 | export function mapPath(raw: string): Result<MapAsk, string> { | |
| 63 | const path = raw === "" ? "index.html" : raw; | |
| 64 | if (!PATH.test(path) || path.includes("..") || path.includes("//") || path.endsWith("/")) return err("not a map file"); | |
| 65 | const type = TYPES[path.split(".").at(-1)!.toLowerCase()]; | |
| 66 | return type === undefined ? err("not a kind of file the map serves") : ok({ path, type }); | |
| 67 | } | |
| 68 | ||
| 69 | export interface MapFile { | |
| 70 | readonly type: string; | |
| 71 | readonly gzip: boolean; | |
| 72 | readonly bytes: Uint8Array; | |
| 73 | } | |
| 74 | ||
| 75 | /** Ask the box for one file of its map, and wait for the answer; the row is gone either way. */ | |
| 76 | export async function askMap(app: App, box: GameBox, service: string, ask: MapAsk, by: string): Promise<Result<MapFile, { status: number; why: string }>> { | |
| 77 | const { type } = ask; | |
| 78 | const waiting = app.db | |
| 79 | .query<{ n: number; mine: number }, [string, string]>( | |
| 80 | "SELECT count(*) AS n, coalesce(sum(by = ?2), 0) AS mine FROM game_command WHERE box_id = ?1 AND kind = 'map' AND done_at = ''", | |
| 81 | ) | |
| 82 | .get(box.id, by)!; | |
| 83 | if (waiting.n >= MAP_PENDING || waiting.mine >= MAP_PER_PERSON) return err({ status: 503, why: "the map has too many files waiting; try again in a moment" }); | |
| 84 | const id = queueCommand(app.db, box.id, service, "map", ask.path, by); | |
| 85 | const done = await new Promise<boolean>((resolve) => { | |
| 86 | let off = (): void => {}; | |
| 87 | const finish = (v: boolean): void => { | |
| 88 | clearTimeout(timer); | |
| 89 | off(); | |
| 90 | resolve(v); | |
| 91 | }; | |
| 92 | const look = (): void => { | |
| 93 | if (commandOf(app.db, id)?.done === true) finish(true); | |
| 94 | }; | |
| 95 | const timer = setTimeout(() => finish(false), MAP_WAIT_MS); | |
| 96 | off = watchBox(app, box.id, look); | |
| 97 | }); | |
| 98 | const c = commandOf(app.db, id); | |
| 99 | app.db.query("DELETE FROM game_command WHERE id = ?1").run(id); | |
| 100 | if (!done || c === undefined || !c.done) return err({ status: 504, why: mapWords.silent }); | |
| 101 | if (c.ok !== true) { | |
| 102 | const status = /^status (\d{3})/.exec(c.output)?.[1]; | |
| 103 | return status === "404" ? err({ status: 404, why: "not on the map" }) : err({ status: 502, why: mapWords.unreachable }); | |
| 104 | } | |
| 105 | const nl = c.output.indexOf("\n"); | |
| 106 | const flag = c.output.slice(0, nl); | |
| 107 | const b64 = c.output.slice(nl + 1); | |
| 108 | if (nl === -1 || (flag !== "0" && flag !== "1") || !/^[A-Za-z0-9+/]*={0,2}$/.test(b64)) return err({ status: 502, why: "the box's answer was not a file" }); | |
| 109 | return ok({ type, gzip: flag === "1", bytes: Buffer.from(b64, "base64") }); | |
| 110 | } |
src/games/map_token.ts added +30
| @@ -0,0 +1,30 @@ | ||
| 1 | /** | |
| 2 | * The pass to one game server's map (#18087): `<user>.<expiry>.<mac>` in the map's path, an HMAC | |
| 3 | * with the forge's key over the box, the server, the person and the hour it ends. The map's files | |
| 4 | * are the box owner's, so they run in a sandboxed document with no origin and no cookie of the | |
| 5 | * forge's: what they may fetch is only this pass, good for this one server and nothing else. | |
| 6 | */ | |
| 7 | ||
| 8 | import { createHmac, timingSafeEqual } from "node:crypto"; | |
| 9 | import { loadKey } from "../kernel/secret.ts"; | |
| 10 | ||
| 11 | /** An hour: a map left open keeps working; a revoked grant is checked on every file, not here. */ | |
| 12 | export const MAP_PASS_MS = 3_600_000; | |
| 13 | ||
| 14 | const mac = (dataDir: string, boxId: string, service: string, user: string, until: string): string => | |
| 15 | createHmac("sha256", loadKey(dataDir)).update(`game-map\n${boxId}\n${service}\n${user}\n${until}`).digest("base64url"); | |
| 16 | ||
| 17 | export function mapPass(dataDir: string, boxId: string, service: string, user: string, now = Date.now()): string { | |
| 18 | const until = String(now + MAP_PASS_MS); | |
| 19 | return `${user}.${until}.${mac(dataDir, boxId, service, user, until)}`; | |
| 20 | } | |
| 21 | ||
| 22 | /** Whose pass it is, when it is genuine, for this server and not past its hour. */ | |
| 23 | export function passUser(dataDir: string, boxId: string, service: string, pass: string, now = Date.now()): string | undefined { | |
| 24 | const [user, until, got, ...rest] = pass.split("."); | |
| 25 | if (user === undefined || until === undefined || got === undefined || rest.length > 0 || !/^\d{1,16}$/.test(until)) return undefined; | |
| 26 | const want = Buffer.from(mac(dataDir, boxId, service, user, until)); | |
| 27 | const have = Buffer.from(got); | |
| 28 | if (want.length !== have.length || !timingSafeEqual(want, have)) return undefined; | |
| 29 | return Number(until) > now ? user : undefined; | |
| 30 | } |
src/games/map_words.ts added +16
| @@ -0,0 +1,16 @@ | ||
| 1 | /** | |
| 2 | * What every door says about the live map (#18087): the page's block and the terminal's line read | |
| 3 | * these. The setup for the box's owner is in docs/features/game-map.md and comes up only when the | |
| 4 | * map is not answering. | |
| 5 | */ | |
| 6 | ||
| 7 | export const mapWords = { | |
| 8 | silent: "The box did not answer in time: it is asleep, off, or its agent has not checked in. Try again in a moment.", | |
| 9 | unreachable: | |
| 10 | "The box answered, but BlueMap's web server is not listening on its loopback port 8100. Install BlueMap on this server and set its webserver `ip: \"127.0.0.1\"`, `port: 8100` (see docs/features/game-map.md).", | |
| 11 | /** The one sentence a viewer reads beside the button. */ | |
| 12 | blurb: "A live 3D map of the world, with its players.", | |
| 13 | } as const; | |
| 14 | ||
| 15 | /** Where a server's map is on the forge: it answers a signed-in viewer with the pass to the map. */ | |
| 16 | export const mapPathOf = (box: string, service: string): string => `/games/${box}/${service}/map`; |
src/games/store.ts +12 −6
| @@ -31,7 +31,12 @@ export const LOG_KEEP = 2_000; | ||
| 31 | 31 | const LINES_A_SYNC = 200; |
| 32 | 32 | /** The most of a command's output kept: a shell's 16 KB (`shell.ts`) and a pack's hash list (`hashes`); the rest say far less. */ |
| 33 | 33 | const OUTPUT_MAX = 16_384; |
| 34 | export const COMMAND_KINDS = ["rcon", "restart", "stop", "start", "recreate", "pull", "shell", "people", "world", "hashes", "tell"] as const; | |
| 34 | /** | |
| 35 | * A relayed map file answers in base64 (`games/map.ts`): 600 KB of file at most, so a sync stays | |
| 36 | * under its cap. | |
| 37 | */ | |
| 38 | const MAP_OUTPUT_MAX = 820_000; | |
| 39 | export const COMMAND_KINDS = ["rcon", "restart", "stop", "start", "recreate", "pull", "shell", "people", "world", "hashes", "tell", "map"] as const; | |
| 35 | 40 | export type CommandKind = (typeof COMMAND_KINDS)[number]; |
| 36 | 41 | export type Role = "owner" | "operator" | "viewer"; |
| 37 | 42 | const RANK: Record<Role, number> = { viewer: 1, operator: 2, owner: 3 }; |
| @@ -408,7 +413,7 @@ export function commandOf(db: Database, id: string, now = Date.now()): CommandSt | ||
| 408 | 413 | >("SELECT id, box_id, kind, service, text, handed_at, done_at, ok, output, after_log FROM game_command WHERE id = ?1") |
| 409 | 414 | .get(id); |
| 410 | 415 | if (r === null) return undefined; |
| 411 | const limit = ["rcon", "people", "tell", "shell"].includes(r.kind) ? ANSWER_MS : JOB_ANSWER_MS; | |
| 416 | const limit = ["rcon", "people", "tell", "shell", "map"].includes(r.kind) ? ANSWER_MS : JOB_ANSWER_MS; | |
| 412 | 417 | const unanswered = r.done_at === "" && r.handed_at !== "" && now - Date.parse(r.handed_at) > limit; |
| 413 | 418 | return { |
| 414 | 419 | id: r.id, |
| @@ -446,7 +451,7 @@ export const recentCommands = (db: Database, boxId: string, service: string, lim | ||
| 446 | 451 | // A pack check (`hashes`) is the forge's own, not a person's; it is said on the box, not |
| 447 | 452 | // here. A `tell` is the forge's words to one player (`chat.ts`): no one else who sees the |
| 448 | 453 | // service reads it. |
| 449 | "SELECT id FROM game_command WHERE box_id = ?1 AND service = ?2 AND kind NOT IN ('hashes', 'tell') ORDER BY created_at DESC LIMIT ?3", | |
| 454 | "SELECT id FROM game_command WHERE box_id = ?1 AND service = ?2 AND kind NOT IN ('hashes', 'tell', 'map') ORDER BY created_at DESC LIMIT ?3", | |
| 450 | 455 | ) |
| 451 | 456 | .all(boxId, service, limit) |
| 452 | 457 | .map((r) => commandOf(db, r.id, now)!); |
| @@ -690,7 +695,7 @@ function recordResults(db: Database, boxId: string, results: SyncBody["results"] | ||
| 690 | 695 | const id = str(r.id, 64); |
| 691 | 696 | const asked = db.query<{ kind: string; service: string; text: string }, [string, string]>("SELECT kind, service, text FROM game_command WHERE id = ?1 AND box_id = ?2 AND done_at = ''").get(id, boxId); |
| 692 | 697 | if (asked === null) continue; |
| 693 | const { ok, output } = outcomeOf(db, boxId, asked, { ok: r.ok === true, output: str(r.output, OUTPUT_MAX) }); | |
| 698 | const { ok, output } = outcomeOf(db, boxId, asked, { ok: r.ok === true, output: str(r.output, asked.kind === "map" ? MAP_OUTPUT_MAX : OUTPUT_MAX) }); | |
| 694 | 699 | // A full sync's own lines are in by now (`recordSync`): the answer stands after them. |
| 695 | 700 | db.query( |
| 696 | 701 | `UPDATE game_command SET done_at = ?2, ok = ?3, output = ?4, |
| @@ -761,12 +766,13 @@ export function recordSync( | ||
| 761 | 766 | })(); |
| 762 | 767 | // The boot report reads no answer (`say_boot`): a command in it would be lost. |
| 763 | 768 | if (body.light !== true && typeof body.boot === "string") return []; |
| 764 | // Handed out once: a command leaves the queue the moment it is in a reply. | |
| 769 | // A map's files go after every command of the owner's: a viewer's pan never waits in front of a | |
| 770 | // stop. Handed out once: a command leaves the queue the moment it is in a reply. | |
| 765 | 771 | const due = db |
| 766 | 772 | .query< |
| 767 | 773 | { id: string; kind: string; service: string; text: string }, |
| 768 | 774 | [string] |
| 769 | >("SELECT id, kind, service, text FROM game_command WHERE box_id = ?1 AND handed_at = '' ORDER BY created_at LIMIT 32") | |
| 775 | >("SELECT id, kind, service, text FROM game_command WHERE box_id = ?1 AND handed_at = '' ORDER BY (kind = 'map'), created_at LIMIT 32") | |
| 770 | 776 | .all(box.id) |
| 771 | 777 | // Only what this statement took is handed out: one taken back meanwhile is not. |
| 772 | 778 | .filter((c) => db.query("UPDATE game_command SET handed_at = ?2 WHERE id = ?1 AND handed_at = ''").run(c.id, at).changes === 1); |
src/http/games_map.ts added +71
| @@ -0,0 +1,71 @@ | ||
| 1 | /** | |
| 2 | * A game server's BlueMap (#18087), relayed through the box's agent (`games/map.ts`) behind login. | |
| 3 | * | |
| 4 | * The map's files are the box owner's, scripts included, so they never run with a viewer's | |
| 5 | * session. `GET /games/:box/:service/map` is the one door that reads the cookie: a viewer's grant | |
| 6 | * on the server buys a pass (`games/map_token.ts`) and a redirect to | |
| 7 | * `/games/:box/:service/m/<pass>/`. Everything under that path answers from the pass alone, in a | |
| 8 | * document the policy sandboxes to an origin of its own (`sandbox allow-scripts`): its requests | |
| 9 | * carry no cookie, and a call it makes to the forge's API is a stranger's. The pass is re-read | |
| 10 | * against the person's grant on every file. | |
| 11 | */ | |
| 12 | ||
| 13 | import { askMap, mapPath } from "../games/map.ts"; | |
| 14 | import { mapPass, passUser } from "../games/map_token.ts"; | |
| 15 | import { boxNamed, mayDo, roleOn, servicesOf } from "../games/store.ts"; | |
| 16 | import { getUserById } from "../core/users.ts"; | |
| 17 | import { boxOf } from "../web/pages/games.ts"; | |
| 18 | import type { Ctx } from "./context.ts"; | |
| 19 | import { securityFloor } from "./respond.ts"; | |
| 20 | ||
| 21 | /** | |
| 22 | * No origin, so no cookie and no same-origin reach into the forge; `connect-src 'self'` is the | |
| 23 | * map's own path. | |
| 24 | */ | |
| 25 | const POLICY = | |
| 26 | "sandbox allow-scripts; default-src 'self'; script-src 'self' 'unsafe-inline' blob:; style-src 'self' 'unsafe-inline'; img-src 'self' data: blob:; font-src 'self' data:; " + | |
| 27 | "connect-src 'self'; worker-src 'self' blob:; frame-ancestors 'none'; base-uri 'self'; form-action 'none'; object-src 'none'"; | |
| 28 | ||
| 29 | /** | |
| 30 | * What a sandboxed document with no origin needs to read its own files: they are asked for by the | |
| 31 | * pass in the path, with no credentials, so any origin may read them. | |
| 32 | */ | |
| 33 | const OPEN = { "access-control-allow-origin": "*", "cross-origin-resource-policy": "cross-origin" } as const; | |
| 34 | ||
| 35 | const refuse = (status: number, why: string): Response => | |
| 36 | securityFloor(new Response(why, { status, headers: { "content-type": "text/plain; charset=utf-8", "cache-control": "no-store", "content-security-policy": POLICY, ...OPEN } })); | |
| 37 | ||
| 38 | // GET /games/:box/:service/map: a viewer's grant becomes the pass; the map's relative URLs need the | |
| 39 | // slash after it. | |
| 40 | export function gameMapSlash(ctx: Ctx): Response { | |
| 41 | const service = ctx.params.service ?? ""; | |
| 42 | const got = boxOf(ctx, "viewer", service); | |
| 43 | if (got instanceof Response) return got; | |
| 44 | if (!servicesOf(ctx.app.db, got.box.id).some((s) => s.name === service)) return refuse(404, "no such server"); | |
| 45 | const pass = mapPass(ctx.app.config.dataDir, got.box.id, service, ctx.auth.user!.id); | |
| 46 | return new Response(null, { status: 303, headers: { location: `/games/${got.box.name}/${service}/m/${pass}/`, "cache-control": "no-store" } }); | |
| 47 | } | |
| 48 | ||
| 49 | // GET /games/:box/:service/m/:pass/*path | |
| 50 | export async function gameMap(ctx: Ctx): Promise<Response> { | |
| 51 | const service = ctx.params.service ?? ""; | |
| 52 | const box = boxNamed(ctx.app.db, ctx.params.box ?? ""); | |
| 53 | const userId = box === undefined ? undefined : passUser(ctx.app.config.dataDir, box.id, service, ctx.params.pass ?? ""); | |
| 54 | const user = userId === undefined ? undefined : getUserById(ctx.app.db, userId); | |
| 55 | // A grant taken back ends the pass at the next file. | |
| 56 | if (box === undefined || user === undefined || !mayDo(roleOn(ctx.app.db, user, box.id, service), "viewer")) return refuse(404, "no such map"); | |
| 57 | if (!servicesOf(ctx.app.db, box.id).some((s) => s.name === service)) return refuse(404, "no such server"); | |
| 58 | const ask = mapPath(ctx.params.path ?? ""); | |
| 59 | if (!ask.ok) return refuse(404, ask.error); | |
| 60 | const file = await askMap(ctx.app, box, service, ask.value, user.id); | |
| 61 | if (!file.ok) return refuse(file.error.status, file.error.why); | |
| 62 | const headers: Record<string, string> = { | |
| 63 | "content-type": file.value.type, | |
| 64 | // A minute in this browser alone: a pan costs nothing. | |
| 65 | "cache-control": "private, max-age=60", | |
| 66 | "content-security-policy": POLICY, | |
| 67 | ...OPEN, | |
| 68 | }; | |
| 69 | if (file.value.gzip) headers["content-encoding"] = "gzip"; | |
| 70 | return securityFloor(new Response(file.value.bytes, { headers })); | |
| 71 | } |
src/http/games_routes.ts +3
| @@ -23,6 +23,7 @@ import { | ||
| 23 | 23 | gameBoxPage, gameCommandSubmit, gameCrashShare, gameEnvSubmit, gameGrantSubmit, gameLendSubmit, gameServersSubmit, gameJarDownload, gameJarSubmit, gameModInstall, gameModPack, gameModRemove, gameModUpdate, gamePeopleSubmit, gameHead, gameWorldSubmit, gamePowerSubmit, gameSleepSubmit, gameServicePage, gameSettingsSubmit, gameServiceStream, gameShellStream, gameShellSubmit, gameTakeBackSubmit, gamesPage, |
| 24 | 24 | } from "../web/pages/games.ts"; |
| 25 | 25 | import { gamePackDownload, gamePackLink, gamePackRevoke } from "../web/pages/games_client_pack.ts"; |
| 26 | import { gameMap, gameMapSlash } from "./games_map.ts"; | |
| 26 | 27 | import { gameConfigCommit, gameConfigPage, gameConfigPreview } from "../web/pages/games_config.ts"; |
| 27 | 28 | import type { Ctx, Handler } from "./context.ts"; |
| 28 | 29 | import { InvalidJson } from "./json_body.ts"; |
| @@ -156,6 +157,8 @@ export function gamesRoutes(router: Router<Handler>): void { | ||
| 156 | 157 | router.add("POST", "/games/:box/:service/mods/update", gameModUpdate); |
| 157 | 158 | router.add("POST", "/games/:box/:service/mods/remove", gameModRemove); |
| 158 | 159 | router.add("POST", "/games/:box/:service/mods/pack", gameModPack); |
| 160 | router.add("GET", "/games/:box/:service/map", gameMapSlash); | |
| 161 | router.add("GET", "/games/:box/:service/m/:pass/*path", gameMap); | |
| 159 | 162 | router.add("GET", "/games/:box/:service/config", gameConfigPage); |
| 160 | 163 | router.add("POST", "/games/:box/:service/config/preview", gameConfigPreview); |
| 161 | 164 | router.add("POST", "/games/:box/:service/config/commit", gameConfigCommit); |
src/http/lazy_lists.ts +2
| @@ -657,6 +657,8 @@ export const OPERATIONS_ROUTES = [ | ||
| 657 | 657 | ["POST", "/games/:box/:service/mods/update"], |
| 658 | 658 | ["POST", "/games/:box/:service/mods/remove"], |
| 659 | 659 | ["POST", "/games/:box/:service/mods/pack"], |
| 660 | ["GET", "/games/:box/:service/map"], | |
| 661 | ["GET", "/games/:box/:service/m/:pass/*path"], | |
| 660 | 662 | ["GET", "/games/:box/:service/config"], |
| 661 | 663 | ["POST", "/games/:box/:service/config/preview"], |
| 662 | 664 | ["POST", "/games/:box/:service/config/commit"], |
src/tui/screens/game_map.ts added +46
| @@ -0,0 +1,46 @@ | ||
| 1 | /** | |
| 2 | * A game server's live map in the terminal (#18087), the page's "Live map" block | |
| 3 | * (/games/<box>/<service>/map/): the same words and the same address (`games/map_words.ts`). A 3D | |
| 4 | * map is a browser's, so `p` asks the box for the map's front page through its agent, as the page | |
| 5 | * would, and says whether it answered. Reading is a viewer's, as on the page. | |
| 6 | */ | |
| 7 | ||
| 8 | import { askMap, mapPath } from "../../games/map.ts"; | |
| 9 | import { mapPathOf, mapWords } from "../../games/map_words.ts"; | |
| 10 | import { roleOn, mayDo, type GameBox } from "../../games/store.ts"; | |
| 11 | import type { Ctx, Screen } from "../app/app.ts"; | |
| 12 | import { binding } from "../app/keys.ts"; | |
| 13 | import { style } from "../term/style.ts"; | |
| 14 | import { truncate, wrap } from "../term/width.ts"; | |
| 15 | import type { Session } from "../session.ts"; | |
| 16 | import { fill, len, split } from "../ui/layout.ts"; | |
| 17 | ||
| 18 | export function gameMapScreen(f: Session, ctx: Ctx, box: GameBox, service: string): Screen { | |
| 19 | let note = ""; | |
| 20 | return { | |
| 21 | title: `${box.name}/${service} live map`, | |
| 22 | keys: [binding(["p"], "ask the box if the map answers")], | |
| 23 | render(area, s) { | |
| 24 | const c = ctx.theme.c; | |
| 25 | const [head, body] = split(area, "v", [len(1), fill(1)]); | |
| 26 | s.text(head!.x, head!.y, truncate(note === "" ? "p asks the box if the map answers" : note, head!.w), style(c.mutedFg, c.bg), head!.x + head!.w); | |
| 27 | const lines = wrap(`${mapWords.blurb} ${mapPathOf(box.name, service)}`, body!.w); | |
| 28 | lines.slice(0, 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)); | |
| 29 | }, | |
| 30 | key(e) { | |
| 31 | if (e.ctrl || e.alt || e.key !== "p") return false; | |
| 32 | if (f.user === undefined || !mayDo(roleOn(f.app.db, f.user, box.id, service), "viewer")) note = `You may not see ${service}.`; | |
| 33 | else { | |
| 34 | note = "Asking the box…"; | |
| 35 | const front = mapPath(""); | |
| 36 | if (!front.ok) return true; | |
| 37 | void askMap(f.app, box, service, front.value, f.user.id).then((got) => { | |
| 38 | note = got.ok ? "The map answers." : got.error.why; | |
| 39 | ctx.invalidate(); | |
| 40 | }); | |
| 41 | } | |
| 42 | ctx.invalidate(); | |
| 43 | return true; | |
| 44 | }, | |
| 45 | }; | |
| 46 | } |
src/tui/screens/games.ts +3
| @@ -69,6 +69,7 @@ import { ListState, confirmScreen, drawList, promptScreen, type ListRow } from " | ||
| 69 | 69 | import { commitServer, planRemoveServer, planServer, wishOn, type ServerPlan } from "../../games/presets.ts"; |
| 70 | 70 | import { CODE_MS, linksOf, newLinkCode, NO_LINK_HERE } from "../../games/chat.ts"; |
| 71 | 71 | import type { PaletteEntry } from "./entries.ts"; |
| 72 | import { gameMapScreen } from "./game_map.ts"; | |
| 72 | 73 | import { gameConfigScreen } from "./game_config.ts"; |
| 73 | 74 | import { gameModsScreen } from "./game_mods.ts"; |
| 74 | 75 | |
| @@ -410,6 +411,7 @@ export function gameServiceScreen(f: Session, ctx: Ctx, box: GameBox, service: s | ||
| 410 | 411 | binding(["e"], "set env"), |
| 411 | 412 | binding(["m"], "mods"), |
| 412 | 413 | binding(["f"], "plugin config files"), |
| 414 | binding(["w"], "the live map"), | |
| 413 | 415 | binding(["c"], "settings"), |
| 414 | 416 | binding(["p"], "a player: op, ban, kick, move…"), |
| 415 | 417 | binding(["i"], "import a world"), |
| @@ -472,6 +474,7 @@ export function gameServiceScreen(f: Session, ctx: Ctx, box: GameBox, service: s | ||
| 472 | 474 | }); |
| 473 | 475 | else if (e.key === "m") ctx.push(gameModsScreen(f, ctx, box, service)); |
| 474 | 476 | else if (e.key === "f") ctx.push(gameConfigScreen(f, ctx, box, service)); |
| 477 | else if (e.key === "w") ctx.push(gameMapScreen(f, ctx, box, service)); | |
| 475 | 478 | else if (e.key === "i" || e.key === "u" || e.key === "n") { |
| 476 | 479 | const world = (op: WorldOp): string => { |
| 477 | 480 | const queued = queueWorld(f.app.db, boxNamed(f.app.db, box.name) ?? box, service, op, f.user); |
src/web/pages/games.ts +6
| @@ -60,6 +60,7 @@ import { MASK, secretKey } from "../../core/secret_text.ts"; | ||
| 60 | 60 | import { BODY_CAPS } from "../../kernel/body_caps.ts"; |
| 61 | 61 | import type { Ctx } from "../../http/context.ts"; |
| 62 | 62 | import { eventStream } from "../../http/sse.ts"; |
| 63 | import { mapPathOf, mapWords } from "../../games/map_words.ts"; | |
| 63 | 64 | import { notFoundPage, pageHead, signInFirst } from "../chrome.ts"; |
| 64 | 65 | import { field, readForm, type Form } from "../form.ts"; |
| 65 | 66 | import { html, type Html } from "../html.ts"; |
| @@ -651,6 +652,11 @@ export async function gameServicePage(ctx: Ctx): Promise<Response> { | ||
| 651 | 652 | <p class="muted small">A plugin's settings files, kept in ${box.path}: previewed, committed and reverted.</p> |
| 652 | 653 | <p>${btn("Open the plugin config", { href: `${base}/config`, variant: "secondary" })}</p> |
| 653 | 654 | </section>`)} |
| 655 | ${fold("Live map", "live-map", false, html`<section class="settings-block"> | |
| 656 | <h2>Live map</h2> | |
| 657 | <p class="muted small">${mapWords.blurb}</p> | |
| 658 | <p>${btn("Open the map", { href: mapPathOf(box.name, service), variant: "secondary" })}</p> | |
| 659 | </section>`)} | |
| 654 | 660 | ${fold("Settings", "settings", preview !== undefined, html`${settingsBlock({ base, act, settings, preview, sha: compose?.sha ?? "", wanted })}`)} |
| 655 | 661 | ${fold("Mods and plugins", "mods", query !== null || adding !== "" || packQuery !== null || packing !== "", html`${modsBlock({ base, act, mods, hits, ups, preview: modPreview, query, adding })} |
| 656 | 662 | ${mods?.ok && mods.value.target.kind === "mod" |
test/budgets/unfixtured/games-box-service-m-pass-path.json added +4
test/budgets/unfixtured/games-box-service-map.json added +4
test/games-map.test.ts added +221
| @@ -0,0 +1,221 @@ | ||
| 1 | import { afterAll, beforeAll, describe, expect, test } from "bun:test"; | |
| 2 | import { mkdtemp, rm } from "node:fs/promises"; | |
| 3 | import { tmpdir } from "node:os"; | |
| 4 | import { join } from "node:path"; | |
| 5 | import { createApp, type App } from "../src/app.ts"; | |
| 6 | import { createToken } from "../src/core/tokens.ts"; | |
| 7 | import { createUser, getUserByName } from "../src/core/users.ts"; | |
| 8 | import { MAP_PER_PERSON, mapPath } from "../src/games/map.ts"; | |
| 9 | import { mapPass } from "../src/games/map_token.ts"; | |
| 10 | import { createGameBox, grant, queueCommand } from "../src/games/store.ts"; | |
| 11 | import { forgeHttp, type ForgeHttp } from "../src/http/server.ts"; | |
| 12 | import { quietLogs } from "./helpers/globals.ts"; | |
| 13 | import { waitFor } from "./helpers/poll.ts"; | |
| 14 | ||
| 15 | quietLogs(); | |
| 16 | ||
| 17 | const ORIGIN = "http://forge.test"; | |
| 18 | ||
| 19 | describe("the live map relay", () => { | |
| 20 | let dataDir = ""; | |
| 21 | let app: App; | |
| 22 | let http: ForgeHttp; | |
| 23 | let token = ""; | |
| 24 | let bobTok = ""; | |
| 25 | let carolTok = ""; | |
| 26 | const get = (path: string, bearer?: string) => http.handle(new Request(ORIGIN + path, bearer === undefined ? {} : { headers: { authorization: `Bearer ${bearer}` } })); | |
| 27 | const light = async (results: unknown[] = []) => | |
| 28 | (await ( | |
| 29 | await http.handle( | |
| 30 | new Request(`${ORIGIN}/api/v1/games/agent/sync`, { | |
| 31 | method: "POST", | |
| 32 | headers: { authorization: `Bearer ${token}`, "content-type": "application/json" }, | |
| 33 | body: JSON.stringify({ agent: 1, light: true, results }), | |
| 34 | }), | |
| 35 | ) | |
| 36 | ).json()) as { commands: { id: string; kind: string; text: string }[] }; | |
| 37 | ||
| 38 | /** The map command the box is handed next: a light check-in each poll. */ | |
| 39 | const taken = async (): Promise<{ id: string; kind: string; text: string }> => { | |
| 40 | let found: { id: string; kind: string; text: string } | undefined; | |
| 41 | await waitFor(async () => (found = (await light()).commands.find((c) => c.kind === "map")) !== undefined, { every: 20, within: 2_000, what: "the box is handed the map file" }); | |
| 42 | return found!; | |
| 43 | }; | |
| 44 | ||
| 45 | beforeAll(async () => { | |
| 46 | dataDir = await mkdtemp(join(tmpdir(), "forge-map-")); | |
| 47 | app = createApp({ dataDir, port: 0, modrinthFetch: async () => Response.json([]) }); | |
| 48 | http = forgeHttp(app); | |
| 49 | for (const [username, adminIfFirst] of [ | |
| 50 | ["alice", true], | |
| 51 | ["bob", false], | |
| 52 | ["carol", false], | |
| 53 | ] as const) { | |
| 54 | const made = await createUser(app.db, { origin: "seed", trusted: true, username, email: `${username}@f.test`, password: "a-good-passphrase", adminIfFirst }); | |
| 55 | if (!made.ok) throw new Error(made.error); | |
| 56 | } | |
| 57 | bobTok = createToken(app.db, getUserByName(app.db, "bob")!.id, "rw", "rw").token; | |
| 58 | carolTok = createToken(app.db, getUserByName(app.db, "carol")!.id, "rw", "rw").token; | |
| 59 | const made = createGameBox(app.db, { name: "net", repo: "alice/mc-network" }); | |
| 60 | token = made.token; | |
| 61 | grant(app.db, made.id, getUserByName(app.db, "bob")!.id, "viewer"); | |
| 62 | await http.handle( | |
| 63 | new Request(`${ORIGIN}/api/v1/games/agent/sync`, { | |
| 64 | method: "POST", | |
| 65 | headers: { authorization: `Bearer ${token}`, "content-type": "application/json" }, | |
| 66 | body: JSON.stringify({ agent: 1, services: [{ name: "hub", state: "running" }] }), | |
| 67 | }), | |
| 68 | ); | |
| 69 | }, 30_000); | |
| 70 | ||
| 71 | afterAll(async () => { | |
| 72 | app.close(); | |
| 73 | await rm(dataDir, { recursive: true, force: true }); | |
| 74 | }); | |
| 75 | ||
| 76 | /** What a viewer's cookie-door gives: the map's path with the pass in it. */ | |
| 77 | const base = async (tok: string): Promise<string> => (await get("/games/net/hub/map", tok)).headers.get("location")!; | |
| 78 | const passOf = (path: string): string => path.split("/")[5]!; | |
| 79 | ||
| 80 | test("only a safe path under the web root is asked for", () => { | |
| 81 | expect(mapPath("")).toEqual({ ok: true, value: { path: "index.html", type: "text/html; charset=utf-8" } }); | |
| 82 | expect(mapPath("maps/world/tiles/0/x1/z-1.prbm").ok).toBe(true); | |
| 83 | for (const bad of ["../etc/passwd.json", "a/../b.json", ".hidden.json", "a//b.json", "dir/", "run.sh", "a b.json", "x.json?q=1"]) expect(mapPath(bad).ok).toBe(false); | |
| 84 | }); | |
| 85 | ||
| 86 | test("signed out or without a grant, there is no pass and nothing is asked of the box", async () => { | |
| 87 | expect((await get("/games/net/hub/map")).headers.get("location") ?? "").not.toContain("/m/"); | |
| 88 | expect((await get("/games/net/hub/map", carolTok)).status).toBe(404); | |
| 89 | expect((await get("/games/net/hub/m/nope/index.html")).status).toBe(404); | |
| 90 | expect((await light()).commands).toEqual([]); | |
| 91 | }); | |
| 92 | ||
| 93 | test("a pass that is forged, spent, for another server or for someone without a grant is refused", async () => { | |
| 94 | const bob = getUserByName(app.db, "bob")!; | |
| 95 | const carol = getUserByName(app.db, "carol")!; | |
| 96 | const box = app.db.query<{ id: string }, []>("SELECT id FROM game_box WHERE name = 'net'").get()!; | |
| 97 | const dir = app.config.dataDir; | |
| 98 | const good = mapPass(dir, box.id, "hub", bob.id); | |
| 99 | const [u, until, mac] = good.split("."); | |
| 100 | const bad = [ | |
| 101 | `${u}.${until}.${mac!.slice(0, -2)}AA`, | |
| 102 | `${carol.id}.${until}.${mac}`, | |
| 103 | mapPass(dir, box.id, "hub", bob.id, Date.now() - 2 * 3_600_000), | |
| 104 | mapPass(dir, box.id, "other", bob.id), | |
| 105 | mapPass(dir, box.id, "hub", carol.id), | |
| 106 | ]; | |
| 107 | for (const pass of bad) expect((await get(`/games/net/hub/m/${pass}/index.html`)).status).toBe(404); | |
| 108 | expect((await light()).commands).toEqual([]); | |
| 109 | }); | |
| 110 | ||
| 111 | test("a viewer's file is asked of the box, answered by it, served with the floor, and left no row", async () => { | |
| 112 | const slash = await get("/games/net/hub/map", bobTok); | |
| 113 | expect(slash.status).toBe(303); | |
| 114 | const at = await base(bobTok); | |
| 115 | expect(at).toMatch(/^\/games\/net\/hub\/m\/[^/]+\/$/); | |
| 116 | const asking = get(`${at}maps/world/settings.json`); | |
| 117 | const asked = await taken(); | |
| 118 | expect(asked.text).toBe("maps/world/settings.json"); | |
| 119 | await light([{ id: asked.id, ok: true, output: `0\n${Buffer.from('{"a":1}').toString("base64")}` }]); | |
| 120 | const res = await asking; | |
| 121 | expect(res.status).toBe(200); | |
| 122 | expect(res.headers.get("content-type")).toBe("application/json"); | |
| 123 | expect(res.headers.get("content-security-policy")).toContain("frame-ancestors 'none'"); | |
| 124 | expect(res.headers.get("x-content-type-options")).toBe("nosniff"); | |
| 125 | expect(res.headers.get("content-encoding")).toBeNull(); | |
| 126 | expect(await res.text()).toBe('{"a":1}'); | |
| 127 | expect(app.db.query("SELECT count(*) AS n FROM game_command WHERE kind = 'map'").get()).toEqual({ n: 0 }); | |
| 128 | }); | |
| 129 | ||
| 130 | test("a map answer has no same-origin power: a sandboxed document, no cookie read, no cookie set", async () => { | |
| 131 | const at = await base(bobTok); | |
| 132 | // The pass alone asks; a session with it adds nothing, and nothing a script runs here is the | |
| 133 | // viewer's. | |
| 134 | const asking = get(`${at}index.html`); | |
| 135 | const c = await taken(); | |
| 136 | await light([{ id: c.id, ok: true, output: `0\n${Buffer.from("<script>fetch('/api/v1/user',{method:'POST'})</script>").toString("base64")}` }]); | |
| 137 | const res = await asking; | |
| 138 | expect(res.status).toBe(200); | |
| 139 | const csp = res.headers.get("content-security-policy")!; | |
| 140 | expect(csp).toMatch(/(^|; )sandbox allow-scripts(;|$)/); | |
| 141 | expect(csp).not.toContain("allow-same-origin"); | |
| 142 | expect(csp).toContain("connect-src 'self'"); | |
| 143 | expect(res.headers.get("set-cookie")).toBeNull(); | |
| 144 | // An opaque origin reads its files by CORS, without credentials. | |
| 145 | expect(res.headers.get("access-control-allow-origin")).toBe("*"); | |
| 146 | expect(res.headers.get("access-control-allow-credentials")).toBeNull(); | |
| 147 | expect(res.headers.get("vary") ?? "").not.toContain("cookie"); | |
| 148 | }); | |
| 149 | ||
| 150 | test("a grant taken back ends the pass at the next file", async () => { | |
| 151 | const at = await base(bobTok); | |
| 152 | const bob = getUserByName(app.db, "bob")!; | |
| 153 | const box = app.db.query<{ id: string }, []>("SELECT id FROM game_box WHERE name = 'net'").get()!; | |
| 154 | app.db.query("UPDATE game_grant SET role = 'none' WHERE box_id = ?1 AND user_id = ?2").run(box.id, bob.id); | |
| 155 | expect((await get(`${at}index.html`)).status).toBe(404); | |
| 156 | app.db.query("UPDATE game_grant SET role = 'viewer' WHERE box_id = ?1 AND user_id = ?2").run(box.id, bob.id); | |
| 157 | expect(passOf(at)).not.toBe(""); | |
| 158 | }); | |
| 159 | ||
| 160 | test("a gzip tile says so, a missing one is 404, an unreachable web server is 502", async () => { | |
| 161 | const at = await base(bobTok); | |
| 162 | const answer = async (path: string, ok: boolean, output: string) => { | |
| 163 | const asking = get(`${at}${path}`); | |
| 164 | const c = await taken(); | |
| 165 | await light([{ id: c.id, ok, output }]); | |
| 166 | return asking; | |
| 167 | }; | |
| 168 | const tile = await answer("t/x0.prbm", true, `1\n${Buffer.from([1, 2, 3]).toString("base64")}`); | |
| 169 | expect(tile.headers.get("content-encoding")).toBe("gzip"); | |
| 170 | expect([...new Uint8Array(await tile.arrayBuffer())]).toEqual([1, 2, 3]); | |
| 171 | expect((await answer("t/x1.prbm", false, "status 404")).status).toBe(404); | |
| 172 | expect((await answer("t/x2.prbm", false, "status 000")).status).toBe(502); | |
| 173 | expect((await answer("t/x3.prbm", true, "1\n<script>")).status).toBe(502); | |
| 174 | }); | |
| 175 | ||
| 176 | test("a file of the biggest size the agent sends passes the sync's body cap and is served whole", async () => { | |
| 177 | const at = await base(bobTok); | |
| 178 | const file = Buffer.alloc(600_000, 7); | |
| 179 | const asking = get(`${at}maps/world/tiles/big.prbm`); | |
| 180 | const c = await taken(); | |
| 181 | const reply = await http.handle( | |
| 182 | new Request(`${ORIGIN}/api/v1/games/agent/sync`, { | |
| 183 | method: "POST", | |
| 184 | headers: { authorization: `Bearer ${token}`, "content-type": "application/json" }, | |
| 185 | body: JSON.stringify({ agent: 1, light: true, results: [{ id: c.id, ok: true, output: `0\n${file.toString("base64")}` }] }), | |
| 186 | }), | |
| 187 | ); | |
| 188 | expect(reply.status).toBe(200); | |
| 189 | const res = await asking; | |
| 190 | expect(res.status).toBe(200); | |
| 191 | expect((await res.arrayBuffer()).byteLength).toBe(600_000); | |
| 192 | }); | |
| 193 | ||
| 194 | test("the owner's commands are handed before a viewer's map files, however late they were queued", async () => { | |
| 195 | const box = app.db.query<{ id: string }, []>("SELECT id FROM game_box WHERE name = 'net'").get()!; | |
| 196 | const bob = getUserByName(app.db, "bob")!; | |
| 197 | const alice = getUserByName(app.db, "alice")!; | |
| 198 | for (let i = 0; i < 40; i++) queueCommand(app.db, box.id, "hub", "map", `t/q${i}.prbm`, bob.id); | |
| 199 | queueCommand(app.db, box.id, "hub", "stop", "", alice.id); | |
| 200 | const handed = (await light()).commands; | |
| 201 | expect(handed[0]!.kind).toBe("stop"); | |
| 202 | expect(handed.length).toBe(32); | |
| 203 | app.db.query("DELETE FROM game_command").run(); | |
| 204 | }); | |
| 205 | ||
| 206 | test("one viewer cannot fill the box's lane", async () => { | |
| 207 | const box = app.db.query<{ id: string }, []>("SELECT id FROM game_box WHERE name = 'net'").get()!; | |
| 208 | const bob = getUserByName(app.db, "bob")!; | |
| 209 | for (let i = 0; i < MAP_PER_PERSON; i++) queueCommand(app.db, box.id, "hub", "map", `t/p${i}.prbm`, bob.id); | |
| 210 | const at = await base(bobTok); | |
| 211 | expect((await get(`${at}t/more.prbm`)).status).toBe(503); | |
| 212 | app.db.query("DELETE FROM game_command").run(); | |
| 213 | }); | |
| 214 | ||
| 215 | test("a path that is not a map file is refused before the box is asked", async () => { | |
| 216 | const at = await base(bobTok); | |
| 217 | expect((await get(`${at}run.sh`)).status).toBe(404); | |
| 218 | expect((await get("/games/net/nope/map", bobTok)).status).toBe(404); | |
| 219 | expect((await light()).commands.filter((c) => c.kind === "map")).toEqual([]); | |
| 220 | }); | |
| 221 | }); |
test/no-polling.test.ts +2
| @@ -332,6 +332,8 @@ const NOT_WALKED: Record<string, string> = { | ||
| 332 | 332 | "/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)", |
| 333 | 333 | "/games/:box/:service/stream": "a game box, which the seed does not make (test/games.test.ts covers it)", |
| 334 | 334 | "/games/:box/:service/config": "a game box, which the seed does not make (test/game-plugin-config-doors.test.ts covers it)", |
| 335 | "/games/:box/:service/map": "a game box's map, which the seed does not make (test/games-map.test.ts covers it)", | |
| 336 | "/games/:box/:service/m/:pass/*path": "a game box's map, which the seed does not make (test/games-map.test.ts covers it)", | |
| 335 | 337 | "/games/jar/:id/:name": "a kept plugin jar, a download behind a signed URL, not a page", |
| 336 | 338 | "/games/@pack/:token/:file": "a client pack for whoever holds the link, a download, not a page; the seed makes no link (test/game-client-pack.test.ts covers it)", |
| 337 | 339 | "/games/head/:uuid": "a player's head, a PNG kept from mc-heads.net, not a page", |
test/open-routes-floor.test.ts +3 −1
| @@ -45,7 +45,9 @@ const FILL: Readonly<Record<string, string>> = { | ||
| 45 | 45 | }; |
| 46 | 46 | |
| 47 | 47 | /** Open GET routes that cannot be filled in from a seeded public repository, each with why. */ |
| 48 | const UNFILLED: Readonly<Record<string, string>> = {}; | |
| 48 | const UNFILLED: Readonly<Record<string, string>> = { | |
| 49 | "/games/:box/:service/m/:pass/*path": "a pass is minted for one box and one script run; nothing seeded holds one", | |
| 50 | }; | |
| 49 | 51 | |
| 50 | 52 | const openGets = (): string[] => { |
| 51 | 53 | const all = [...buildRouter().routes(), ...buildApiRouter().routes()]; |
test/security-floor-routes.test.ts +2
| @@ -76,6 +76,8 @@ const UNSEEDED: Record<string, string> = { | ||
| 76 | 76 | "/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)", |
| 77 | 77 | "/games/:box/:service/stream": "a game box, which the seed does not make (test/games.test.ts covers it)", |
| 78 | 78 | "/games/:box/:service/config": "a game box, which the seed does not make (test/game-plugin-config-doors.test.ts covers it)", |
| 79 | "/games/:box/:service/map": "a game box's map, which the seed does not make (test/games-map.test.ts covers it)", | |
| 80 | "/games/:box/:service/m/:pass/*path": "a game box's map, which the seed does not make (test/games-map.test.ts covers it)", | |
| 79 | 81 | "/games/@pack/:token/:file": "a client pack behind a link the seed does not make (test/game-client-pack.test.ts covers it)", |
| 80 | 82 | "/games/head/:uuid": "a player's head picture, by a Minecraft UUID only a game box's agent reports", |
| 81 | 83 | "/games/jar/:id/:name": "a kept plugin jar of a game box, behind a signed URL the seed does not make", |
test/timers-named.test.ts +1
| @@ -104,6 +104,7 @@ const ALLOWED: readonly Allowed[] = [ | ||
| 104 | 104 | ...allow("setTimeout", `an openai runner bash call's kill deadline, ${PER_CONNECTION}`, [["src/crew/openai_runner.ts", "() => { timedOut = true"]]), |
| 105 | 105 | ...allow("setTimeout", SLEEP, [["src/crew/openai_runner.ts", "r"]]), |
| 106 | 106 | ...allow("setTimeout", DEADLINE, [ |
| 107 | ["src/games/map.ts", "() => finish(false)"], | |
| 107 | 108 | ["src/checks/stall.ts", "() => { if (!wrote()"], |
| 108 | 109 | ["src/git/read.ts", "() => { this.close(); reject("], |
| 109 | 110 | ]), |
new above
offline
HIGH:
script-src 'self' 'unsafe-inline'plusconnect-src 'self'on the forge origin means the owner's map files run as the viewer on the forge, and can POST to the forge API with the viewer's cookie. Addsandbox allow-scripts(opaque origin) and authorize map requests with a scoped signed token in the path, or move the map to a cookieless origin. Add a test for it.