Public: anyone can read this; the crew can change it.
A game box stores spark profiles in the forge: POST /post gives a Location, reads need the box's game grants #18146
Merged 8h 20m ago, live in production
scout/forge:scout/18137-a-game-box-stores-spark-profiles-in-the → main 0 commits fork
19 files
changed +408
−2
- docs/features/game-spark.md
- src/core/migration-pins/20261204080000-game-spark.pin
- src/core/migrations/20261204080000-game-spark.ts
- src/games/spark.ts
- src/http/games_routes.ts
- src/http/lazy_lists.ts
- src/kernel/body_caps.ts
- src/tui/screens/game_spark.ts
- src/tui/screens/games.ts
- src/web/pages/games.ts
- src/web/pages/games_spark.ts
- test/budgets/unfixtured/games-box-spark-key.json
- test/budgets/unfixtured/games-spark-secret-key.json
- test/data-browser.test.ts
- test/game-spark.test.ts
- test/no-polling.test.ts
- test/open-routes-floor.test.ts
- test/security-floor-routes.test.ts
- test/tui-games.test.ts
docs/features/game-spark.md added +9
| @@ -0,0 +1,9 @@ | ||
| 1 | --- | |
| 2 | topic: Hosting forges for others, and getting paid | |
| 3 | row: Game spark profiles | |
| 4 | --- | |
| 5 | # Spark profiles (#18137) | |
| 6 | ||
| 7 | A box stores the profiles its servers' spark plugin posts, so a lag report is read from the forge, not a public paste. The box's owner makes an upload address on `/games/<box>` (Profiles, "Make an upload address"; `p` on the terminal's box screen opens `src/tui/screens/game_spark.ts`, where `u`), shown once: `<forge>/games/@spark/<secret>/`. Set it as spark's `bytebin-url`. spark posts `<address>post` (a gzipped protobuf, `Content-Type: application/x-spark-*`) and is answered `201` with `Location: <key>` and no body; a wrong secret is a `403`, a body past 8 MiB a `413`, anything not gzip or not a spark type a `400`. The secret only allows writes and only its hash is kept; a new address ends the old. | |
| 8 | ||
| 9 | `GET <address><key>` returns the bytes and type to a forge session with any grant on the box (forge admins too), and `403` to anyone else; no grant table is new. The box's page and the terminal's box screen list what is stored (newest 50, type, time, size); the page's link opens one without the secret. A profile is kept 14 days and a box keeps its newest 50 (`SPARK_KEEP_DAYS`, `SPARK_KEEP_COUNT`, `BODY_CAPS.gameSpark`, each with its reason). Not done: the bytes are not decoded (the forge does not render a profile; spark's own viewer reads it), and the gzip is checked by its magic bytes only. Code: `src/games/spark.ts`, `src/web/pages/games_spark.ts`. |
src/core/migration-pins/20261204080000-game-spark.pin added +1
| @@ -0,0 +1,1 @@ | ||
| 1 | 7188641ab28d3623df4ce4102eed02db763a68a884afc9ac4f7430101000369f |
src/core/migrations/20261204080000-game-spark.ts added +20
| @@ -0,0 +1,20 @@ | ||
| 1 | // A game box's stored spark profiles (#18137): the box's upload secret (only its hash is kept, so | |
| 2 | // the address is shown once; one per box, a new one ends the old) and the profiles posted with it, | |
| 3 | // each kept until `expires_at`. Additive: two tables. | |
| 4 | export default ` | |
| 5 | CREATE TABLE IF NOT EXISTS game_spark_secret ( | |
| 6 | box_id TEXT PRIMARY KEY, | |
| 7 | secret_hash TEXT NOT NULL UNIQUE, | |
| 8 | created_at TEXT NOT NULL | |
| 9 | ); | |
| 10 | CREATE TABLE IF NOT EXISTS game_spark_profile ( | |
| 11 | key TEXT PRIMARY KEY, | |
| 12 | box_id TEXT NOT NULL, | |
| 13 | type TEXT NOT NULL, | |
| 14 | body BLOB NOT NULL, | |
| 15 | size INTEGER NOT NULL, | |
| 16 | created_at TEXT NOT NULL, | |
| 17 | expires_at TEXT NOT NULL | |
| 18 | ); | |
| 19 | CREATE INDEX IF NOT EXISTS game_spark_profile_box ON game_spark_profile (box_id, created_at); | |
| 20 | `; |
src/games/spark.ts added +76
| @@ -0,0 +1,76 @@ | ||
| 1 | /** | |
| 2 | * A game box stores the spark profiles its servers post (#18137). spark (the profiler plugin) posts | |
| 3 | * a gzipped protobuf to `<bytebin-url>/post` and reads the `Location` it is answered with; the | |
| 4 | * forge is that bytebin. The address a box is given carries its own upload secret, which only | |
| 5 | * allows writes (only its hash is kept, one per box, a new one ends the old). Reading a profile | |
| 6 | * back needs a forge session with a grant on the box (`seesBox`), the same grants as the rest of | |
| 7 | * the box: no new table. | |
| 8 | * | |
| 9 | * The settings, each with its reason: a profile is at most `BODY_CAPS.gameSpark` bytes (a minute's | |
| 10 | * sample is a few hundred KiB; the cap keeps one box from filling the database), it is kept | |
| 11 | * `SPARK_KEEP_DAYS` days (long enough to read a report of last weekend's lag), and a box keeps at | |
| 12 | * most `SPARK_KEEP_COUNT` (a plugin that posts in a loop cannot grow it without end). | |
| 13 | */ | |
| 14 | ||
| 15 | import type { Database } from "bun:sqlite"; | |
| 16 | import { sha256 } from "../kernel/hash.ts"; | |
| 17 | import { secret } from "../kernel/id.ts"; | |
| 18 | import { err, ok, type Result } from "../kernel/result.ts"; | |
| 19 | ||
| 20 | export const SPARK_KEEP_DAYS = 14; | |
| 21 | export const SPARK_KEEP_COUNT = 50; | |
| 22 | ||
| 23 | /** What spark sends: `application/x-spark-sampler`, `-heap`, `-health`, nothing with parameters. */ | |
| 24 | const SPARK_TYPE = /^application\/x-spark-[a-z0-9.+-]{1,40}$/; | |
| 25 | ||
| 26 | /** The box an upload secret belongs to, or none: the secret is only ever compared by its hash. */ | |
| 27 | export function boxOfSparkSecret(db: Database, given: string): string | undefined { | |
| 28 | if (given === "" || given.length > 100) return undefined; | |
| 29 | return db.query<{ box_id: string }, [string]>("SELECT box_id FROM game_spark_secret WHERE secret_hash = ?1").get(sha256(given))?.box_id; | |
| 30 | } | |
| 31 | ||
| 32 | /** A new upload secret for the box, shown once; the old one stops working. */ | |
| 33 | export function newSparkSecret(db: Database, boxId: string, now = Date.now()): string { | |
| 34 | const s = secret(); | |
| 35 | db.query("INSERT INTO game_spark_secret (box_id, secret_hash, created_at) VALUES (?1, ?2, ?3) ON CONFLICT (box_id) DO UPDATE SET secret_hash = excluded.secret_hash, created_at = excluded.created_at").run(boxId, sha256(s), new Date(now).toISOString()); | |
| 36 | return s; | |
| 37 | } | |
| 38 | ||
| 39 | /** Whether an upload address exists for the box (the secret itself is not kept). */ | |
| 40 | export const hasSparkSecret = (db: Database, boxId: string): boolean => db.query("SELECT 1 FROM game_spark_secret WHERE box_id = ?1").get(boxId) !== null; | |
| 41 | ||
| 42 | /** | |
| 43 | * Keep one profile: its type and gzip magic judged, the box's old ones pruned. The key is the | |
| 44 | * `Location`. | |
| 45 | */ | |
| 46 | export function keepProfile(db: Database, boxId: string, type: string, bytes: Uint8Array, now = Date.now()): Result<string, string> { | |
| 47 | if (!SPARK_TYPE.test(type)) return err("send a spark profile: Content-Type application/x-spark-*"); | |
| 48 | if (bytes.length < 2 || bytes[0] !== 0x1f || bytes[1] !== 0x8b) return err("a spark profile is gzipped"); | |
| 49 | const key = secret().slice(0, 16); | |
| 50 | const at = new Date(now).toISOString(); | |
| 51 | db.query("INSERT INTO game_spark_profile (key, box_id, type, body, size, created_at, expires_at) VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7)").run( | |
| 52 | key, boxId, type, bytes, bytes.length, at, new Date(now + SPARK_KEEP_DAYS * 86_400_000).toISOString(), | |
| 53 | ); | |
| 54 | db.query("DELETE FROM game_spark_profile WHERE box_id = ?1 AND (expires_at <= ?2 OR key NOT IN (SELECT key FROM game_spark_profile WHERE box_id = ?1 ORDER BY created_at DESC, key LIMIT ?3))").run(boxId, at, SPARK_KEEP_COUNT); | |
| 55 | return ok(key); | |
| 56 | } | |
| 57 | ||
| 58 | /** One stored profile of the box, unless it has expired. */ | |
| 59 | export function profileOf(db: Database, boxId: string, key: string, now = Date.now()): { type: string; body: Uint8Array } | undefined { | |
| 60 | const r = db.query<{ type: string; body: Uint8Array }, [string, string, string]>("SELECT type, body FROM game_spark_profile WHERE box_id = ?1 AND key = ?2 AND expires_at > ?3").get(boxId, key, new Date(now).toISOString()); | |
| 61 | return r ?? undefined; | |
| 62 | } | |
| 63 | ||
| 64 | /** The box's stored profiles, newest first, as its page and its terminal list them. */ | |
| 65 | export function profilesOf(db: Database, boxId: string, now = Date.now()): { key: string; type: string; size: number; at: string }[] { | |
| 66 | return db | |
| 67 | .query<{ key: string; type: string; size: number; created_at: string }, [string, string]>("SELECT key, type, size, created_at FROM game_spark_profile WHERE box_id = ?1 AND expires_at > ?2 ORDER BY created_at DESC, key LIMIT 50") | |
| 68 | .all(boxId, new Date(now).toISOString()) | |
| 69 | .map((r) => ({ key: r.key, type: r.type, size: r.size, at: r.created_at })); | |
| 70 | } | |
| 71 | ||
| 72 | /** The words that say what the box keeps, for the page and the terminal alike. */ | |
| 73 | export const SPARK_WORDS = `Profiles from spark: at most 8 MiB each, kept ${String(SPARK_KEEP_DAYS)} days, the newest ${String(SPARK_KEEP_COUNT)} of the box. Set the address below as spark's bytebin-url; anyone with a grant on the box reads them here.`; | |
| 74 | ||
| 75 | /** The upload address a secret makes: spark's `bytebin-url`. */ | |
| 76 | export const sparkBase = (origin: string, s: string): string => `${origin}/games/@spark/${s}/`; |
src/http/games_routes.ts +6
| @@ -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 { gameSparkLink, gameSparkOpen, gameSparkPost, gameSparkRead } from "../web/pages/games_spark.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"; |
| @@ -138,6 +139,9 @@ export function gamesRoutes(router: Router<Handler>): void { | ||
| 138 | 139 | router.add("GET", "/games/jar/:id/:name", gameJarDownload); |
| 139 | 140 | // "@pack" is no box name, so a box named "pack" keeps its /games/pack/<service>/stream. |
| 140 | 141 | router.add("GET", "/games/@pack/:token/:file", gamePackDownload); |
| 142 | // A box's spark profiles (#18137): "@spark" is no box name, as "@pack". | |
| 143 | router.add("POST", "/games/@spark/:secret/post", gameSparkPost); | |
| 144 | router.add("GET", "/games/@spark/:secret/:key", gameSparkRead); | |
| 141 | 145 | router.add("GET", "/games/head/:uuid", gameHead); |
| 142 | 146 | router.add("GET", "/games/:box", gameBoxPage); |
| 143 | 147 | router.add("POST", "/games/:box/grant", gameGrantSubmit); |
| @@ -145,6 +149,8 @@ export function gamesRoutes(router: Router<Handler>): void { | ||
| 145 | 149 | // Before the service routes: no compose service can be named "@shell". |
| 146 | 150 | router.add("POST", "/games/:box/@shell", gameShellSubmit); |
| 147 | 151 | router.add("GET", "/games/:box/@shell/stream", gameShellStream); |
| 152 | router.add("POST", "/games/:box/@spark", gameSparkLink); | |
| 153 | router.add("GET", "/games/:box/@spark/:key", gameSparkOpen); | |
| 148 | 154 | router.add("POST", "/games/:box/take-back", gameTakeBackSubmit); |
| 149 | 155 | router.add("POST", "/games/:box/servers", gameServersSubmit); |
| 150 | 156 | router.add("GET", "/games/:box/:service", gameServicePage); |
src/http/lazy_lists.ts +4
| @@ -642,12 +642,16 @@ export const OPERATIONS_ROUTES = [ | ||
| 642 | 642 | ["GET", "/games"], |
| 643 | 643 | ["GET", "/games/jar/:id/:name"], |
| 644 | 644 | ["GET", "/games/@pack/:token/:file"], |
| 645 | ["POST", "/games/@spark/:secret/post"], | |
| 646 | ["GET", "/games/@spark/:secret/:key"], | |
| 645 | 647 | ["GET", "/games/head/:uuid"], |
| 646 | 648 | ["GET", "/games/:box"], |
| 647 | 649 | ["POST", "/games/:box/grant"], |
| 648 | 650 | ["POST", "/games/:box/lend"], |
| 649 | 651 | ["POST", "/games/:box/@shell"], |
| 650 | 652 | ["GET", "/games/:box/@shell/stream"], |
| 653 | ["POST", "/games/:box/@spark"], | |
| 654 | ["GET", "/games/:box/@spark/:key"], | |
| 651 | 655 | ["POST", "/games/:box/take-back"], |
| 652 | 656 | ["POST", "/games/:box/servers"], |
| 653 | 657 | ["GET", "/games/:box/:service"], |
src/kernel/body_caps.ts +4
| @@ -71,6 +71,10 @@ export const BODY_CAPS = { | ||
| 71 | 71 | bytes: 2 * MIB, |
| 72 | 72 | reason: "a game box agent's sync: up to 200 log lines for each of its services, their stats and command results", |
| 73 | 73 | }, |
| 74 | gameSpark: { | |
| 75 | bytes: 8 * MIB, | |
| 76 | reason: "a spark profile a game server posts to its box's address: one gzipped protobuf, a few hundred KiB for a minute's sample", | |
| 77 | }, | |
| 74 | 78 | gameJar: { |
| 75 | 79 | bytes: 64 * MIB, |
| 76 | 80 | reason: "a Minecraft plugin jar uploaded for a game box, kept by the forge and fetched by the box", |
src/tui/screens/game_spark.ts added +41
| @@ -0,0 +1,41 @@ | ||
| 1 | /** | |
| 2 | * A box's stored spark profiles in the terminal (#18137), as /games/<box>'s Profiles block: what is | |
| 3 | * kept (type, time, size, key) in the same words, and `u`, for the box's owner, makes the upload | |
| 4 | * address (shown once, here, until the screen closes: only its hash is kept). | |
| 5 | */ | |
| 6 | ||
| 7 | import { publicOrigin } from "../../core/public_origin.ts"; | |
| 8 | import { SPARK_WORDS, newSparkSecret, profilesOf, sparkBase } from "../../games/spark.ts"; | |
| 9 | import { mayDo, roleOn, type GameBox } from "../../games/store.ts"; | |
| 10 | import type { Ctx, Screen } from "../app/app.ts"; | |
| 11 | import { binding } from "../app/keys.ts"; | |
| 12 | import { style } from "../term/style.ts"; | |
| 13 | import { truncate, wrap } from "../term/width.ts"; | |
| 14 | import type { Session } from "../session.ts"; | |
| 15 | ||
| 16 | export function gameSparkScreen(f: Session, ctx: Ctx, box: GameBox): Screen { | |
| 17 | let address = ""; | |
| 18 | const lines = (w: number): string[] => { | |
| 19 | const stored = profilesOf(f.app.db, box.id); | |
| 20 | return [ | |
| 21 | ...wrap(SPARK_WORDS, w), | |
| 22 | "", | |
| 23 | ...(address === "" ? [] : [`bytebin-url: ${address}`, "This is the only time it is shown.", ""]), | |
| 24 | ...(stored.length === 0 ? ["None stored yet."] : stored.map((p) => `${p.at.slice(0, 16).replace("T", " ")} ${p.type.replace("application/x-spark-", "spark ")} ${String(Math.ceil(p.size / 1024))} KiB ${p.key}`)), | |
| 25 | ]; | |
| 26 | }; | |
| 27 | return { | |
| 28 | title: `${box.name}: spark profiles`, | |
| 29 | keys: [binding(["u"], "new upload address (owner)")], | |
| 30 | render(area, s) { | |
| 31 | const c = ctx.theme.c; | |
| 32 | lines(Math.max(10, area.w)).slice(0, area.h).forEach((l, i) => s.text(area.x, area.y + i, truncate(l, area.w), style(c.fg, c.bg), area.x + area.w)); | |
| 33 | }, | |
| 34 | key(e) { | |
| 35 | if (e.ctrl || e.alt || e.key !== "u" || !mayDo(roleOn(f.app.db, f.user, box.id), "owner")) return false; | |
| 36 | address = sparkBase(publicOrigin(f.app.config.url, `http://localhost:${String(f.app.config.port)}`), newSparkSecret(f.app.db, box.id)); | |
| 37 | ctx.invalidate(); | |
| 38 | return true; | |
| 39 | }, | |
| 40 | }; | |
| 41 | } |
src/tui/screens/games.ts +6 −2
| @@ -72,6 +72,7 @@ import { CODE_MS, linksOf, newLinkCode, NO_LINK_HERE } from "../../games/chat.ts | ||
| 72 | 72 | import type { PaletteEntry } from "./entries.ts"; |
| 73 | 73 | import { gameConfigScreen } from "./game_config.ts"; |
| 74 | 74 | import { gameModsScreen } from "./game_mods.ts"; |
| 75 | import { gameSparkScreen } from "./game_spark.ts"; | |
| 75 | 76 | |
| 76 | 77 | /** "4 online · 19.8 TPS · 3.1 ms tick" from the last hour's numbers, or nothing before any. */ |
| 77 | 78 | function playersTps(f: Session, box: { id: string }, service: string): string[] { |
| @@ -643,7 +644,7 @@ export function gameBoxScreen(f: Session, ctx: Ctx, box: GameBox): Screen { | ||
| 643 | 644 | }; |
| 644 | 645 | return { |
| 645 | 646 | title: `${box.name}: the box`, |
| 646 | keys: [binding(["j", "k"], "scroll"), binding(["l"], "run checks while servers sleep: switch")], | |
| 647 | keys: [binding(["j", "k"], "scroll"), binding(["l"], "run checks while servers sleep: switch"), binding(["p"], "spark profiles")], | |
| 647 | 648 | render(area, s) { |
| 648 | 649 | const c = ctx.theme.c; |
| 649 | 650 | const all = lines(Math.max(10, area.w)); |
| @@ -656,7 +657,10 @@ export function gameBoxScreen(f: Session, ctx: Ctx, box: GameBox): Screen { | ||
| 656 | 657 | if (e.ctrl || e.alt) return false; |
| 657 | 658 | if (e.key === "j" || e.key === "down") top++; |
| 658 | 659 | else if (e.key === "k" || e.key === "up") top = Math.max(0, top - 1); |
| 659 | else if (e.key === "l" && mayDo(roleOn(f.app.db, f.user, box.id), "owner") && f.user !== undefined) { | |
| 660 | else if (e.key === "p") { | |
| 661 | ctx.push(gameSparkScreen(f, ctx, box)); | |
| 662 | return true; | |
| 663 | } else if (e.key === "l" && mayDo(roleOn(f.app.db, f.user, box.id), "owner") && f.user !== undefined) { | |
| 660 | 664 | const b = listBoxes(f.app.db).find((x) => x.id === box.id) ?? box; |
| 661 | 665 | setLend(f.app.db, b, lentRunnerOf(f.app.db, b.id) === undefined, f.user.id); |
| 662 | 666 | } else return false; |
src/web/pages/games.ts +22
| @@ -11,6 +11,7 @@ import { addPluginUrl, commitServiceEnv, composeServices, readCompose, serviceEn | ||
| 11 | 11 | import { offered, SET_PREFIX, SURVIVAL } from "../../games/mod_sets.ts"; |
| 12 | 12 | import { commitPlan, modsOf, packUpdateOf, planInstall, planPack, planPackUpdate, planRemove, planUpdate, updatesOf, type Mods, type Plan } from "../../games/mods.ts"; |
| 13 | 13 | import { search, searchPacks, type Hit, type Result } from "../../games/modrinth.ts"; |
| 14 | import { SPARK_WORDS, hasSparkSecret, profilesOf } from "../../games/spark.ts"; | |
| 14 | 15 | import { packRow } from "../../games/client_pack.ts"; |
| 15 | 16 | import { packCheckLines } from "../../games/pack_check.ts"; |
| 16 | 17 | import { playersBlock } from "./games_players.ts"; |
| @@ -352,6 +353,7 @@ export async function gameBoxPage(ctx: Ctx): Promise<Response> { | ||
| 352 | 353 | ${spareBlock(ctx, box)} |
| 353 | 354 | ${role === "owner" ? boxBlock(box, [...healWords(ctx.app.db, box), ...packCheckLines(ctx.app, box.id)]) : sharedBoxBlock(box, packCheckLines(ctx.app, box.id))} ${role === "owner" ? shellBlock(ctx, box) : null} |
| 354 | 355 | ${role === "owner" ? lendBlock(ctx, box) : null} |
| 356 | ${sparkBlock(ctx, box, role === "owner")} | |
| 355 | 357 | ${role === "owner" ? grantsBlock(ctx, box) : null}`, |
| 356 | 358 | })); |
| 357 | 359 | } |
| @@ -493,6 +495,26 @@ export async function gameLendSubmit(ctx: Ctx): Promise<Response> { | ||
| 493 | 495 | return flashTo(ctx, `/games/${got.box.name}`, { message: on ? "Checks run on this box while its servers sleep." : "Checks no longer run on this box; its runner is revoked." }); |
| 494 | 496 | } |
| 495 | 497 | |
| 498 | /** | |
| 499 | * The profiles spark posted to the box (#18137), for whoever sees the box; an owner makes the | |
| 500 | * upload address. | |
| 501 | */ | |
| 502 | function sparkBlock(ctx: Ctx, box: GameBox, owner: boolean): Html { | |
| 503 | const stored = profilesOf(ctx.app.db, box.id); | |
| 504 | return html`<section class="settings-block" id="spark"> | |
| 505 | <h2>Profiles</h2> | |
| 506 | <p class="muted small">${SPARK_WORDS}</p> | |
| 507 | ${stored.length === 0 | |
| 508 | ? html`<p class="muted small">None stored yet.</p>` | |
| 509 | : rowList(stored.map((p) => row({ href: `/games/${box.name}/@spark/${p.key}`, title: p.type.replace("application/x-spark-", "spark "), meta: html`${p.at.slice(0, 16).replace("T", " ")} · ${Math.ceil(p.size / 1024)} KiB` })))} | |
| 510 | ${owner | |
| 511 | ? html`<form method="post" action="/games/${box.name}/@spark" class="row-fields"> | |
| 512 | ${btn(hasSparkSecret(ctx.app.db, box.id) ? "New upload address" : "Make an upload address", { type: "submit", variant: "secondary" })} | |
| 513 | </form>` | |
| 514 | : null} | |
| 515 | </section>`; | |
| 516 | } | |
| 517 | ||
| 496 | 518 | function grantsBlock(ctx: Ctx, box: GameBox): Html { |
| 497 | 519 | const grants = grantsOf(ctx.app.db, box.id); |
| 498 | 520 | return html`<section class="settings-block"> |
src/web/pages/games_spark.ts added +59
| @@ -0,0 +1,59 @@ | ||
| 1 | /** | |
| 2 | * The spark profile routes (`games/spark.ts`): a box's server posts a profile to its secret | |
| 3 | * address, a person with a grant on the box reads it back, an owner makes a new address (shown | |
| 4 | * once). | |
| 5 | */ | |
| 6 | import { publicOrigin } from "../../core/public_origin.ts"; | |
| 7 | import { BODY_CAPS, readBounded } from "../../http/limits.ts"; | |
| 8 | import type { Ctx } from "../../http/context.ts"; | |
| 9 | import { seesBox } from "../../games/store.ts"; | |
| 10 | import { boxOfSparkSecret, keepProfile, newSparkSecret, profileOf, sparkBase } from "../../games/spark.ts"; | |
| 11 | import { readForm } from "../form.ts"; | |
| 12 | import { flashTo } from "../layout.ts"; | |
| 13 | import { boxOf } from "./games.ts"; | |
| 14 | ||
| 15 | const plain = (text: string, status: number): Response => new Response(text, { status, headers: { "content-type": "text/plain; charset=utf-8", "cache-control": "no-store" } }); | |
| 16 | ||
| 17 | // POST /games/@spark/:secret/post: the box's server posts a profile; 201 and `Location: <key>`, no | |
| 18 | // body. | |
| 19 | export async function gameSparkPost(ctx: Ctx): Promise<Response> { | |
| 20 | const boxId = boxOfSparkSecret(ctx.app.db, ctx.params.secret ?? ""); | |
| 21 | if (boxId === undefined) return plain("this address is not a box's upload address", 403); | |
| 22 | const bytes = await readBounded(ctx.request, BODY_CAPS.gameSpark.bytes); | |
| 23 | if (bytes === "too_large") return plain("a profile is at most 8 MiB", 413); | |
| 24 | const type = (ctx.request.headers.get("content-type") ?? "").trim().toLowerCase(); | |
| 25 | const kept = keepProfile(ctx.app.db, boxId, type, bytes); | |
| 26 | if (!kept.ok) return plain(kept.error, 400); | |
| 27 | return new Response(null, { status: 201, headers: { location: kept.value, "cache-control": "no-store" } }); | |
| 28 | } | |
| 29 | ||
| 30 | const profileResponse = (ctx: Ctx, boxId: string): Response => { | |
| 31 | const got = profileOf(ctx.app.db, boxId, ctx.params.key ?? ""); | |
| 32 | return got === undefined ? plain("not found", 404) : new Response(got.body, { headers: { "content-type": got.type, "content-disposition": "attachment", "cache-control": "private, no-store" } }); | |
| 33 | }; | |
| 34 | ||
| 35 | // GET /games/@spark/:secret/:key: the profile, for a session with a grant on the box. | |
| 36 | export function gameSparkRead(ctx: Ctx): Response { | |
| 37 | const boxId = boxOfSparkSecret(ctx.app.db, ctx.params.secret ?? ""); | |
| 38 | if (boxId === undefined) return plain("refused", 403); | |
| 39 | if (!seesBox(ctx.app.db, ctx.auth.user, boxId)) return plain("refused: sign in as someone with a grant on this box", 403); | |
| 40 | return profileResponse(ctx, boxId); | |
| 41 | } | |
| 42 | ||
| 43 | // GET /games/:box/@spark/:key: the same bytes from the box's page, where the list links, with no | |
| 44 | // secret. | |
| 45 | export function gameSparkOpen(ctx: Ctx): Response { | |
| 46 | const got = boxOf(ctx, "viewer"); | |
| 47 | return got instanceof Response ? got : profileResponse(ctx, got.box.id); | |
| 48 | } | |
| 49 | ||
| 50 | // POST /games/:box/@spark: the owner's new upload address, shown once in the flash; the old one | |
| 51 | // ends. | |
| 52 | export async function gameSparkLink(ctx: Ctx): Promise<Response> { | |
| 53 | const got = boxOf(ctx, "owner"); | |
| 54 | if (got instanceof Response) return got; | |
| 55 | const form = await readForm(ctx, "rw"); | |
| 56 | if (form instanceof Response) return form; | |
| 57 | const base = sparkBase(publicOrigin(ctx.app.config.url, `http://localhost:${String(ctx.app.config.port)}`), newSparkSecret(ctx.app.db, got.box.id)); | |
| 58 | return flashTo(ctx, `/games/${got.box.name}#spark`, { message: "Set this as spark's bytebin-url on the server. It allows uploads only; this is the only time it is shown, and the last address no longer works.", code: base }); | |
| 59 | } |
test/budgets/unfixtured/games-box-spark-key.json added +4
test/budgets/unfixtured/games-spark-secret-key.json added +4
test/data-browser.test.ts +3
| @@ -51,6 +51,9 @@ const AUDITED_CLEAR: string[] = [ | ||
| 51 | 51 | "feed_chip.value", |
| 52 | 52 | "fleet_operation.value", |
| 53 | 53 | "forge_order.code_id", |
| 54 | // A posted spark profile (#18137): a capture of the box's own run, readable with the box's | |
| 55 | // grants; no credential. | |
| 56 | "game_spark_profile.body", | |
| 54 | 57 | "gift_redeem.code_id", |
| 55 | 58 | "issue.body", |
| 56 | 59 | "oauth_flow.detail", |
test/game-spark.test.ts added +104
| @@ -0,0 +1,104 @@ | ||
| 1 | /** | |
| 2 | * A game box stores spark profiles (#18137): a post to the box's secret address answers 201 and a | |
| 3 | * Location; a session with a grant reads it back, anyone else is refused, a wrong secret is a 403. | |
| 4 | */ | |
| 5 | import { afterAll, beforeAll, describe, expect, test } from "bun:test"; | |
| 6 | import { mkdtemp, rm } from "node:fs/promises"; | |
| 7 | import { tmpdir } from "node:os"; | |
| 8 | import { join } from "node:path"; | |
| 9 | import { createApp, type App } from "../src/app.ts"; | |
| 10 | import { createSession } from "../src/core/sessions.ts"; | |
| 11 | import { createUser, getUserByName } from "../src/core/users.ts"; | |
| 12 | import { SPARK_KEEP_COUNT, SPARK_KEEP_DAYS, keepProfile, newSparkSecret, profilesOf } from "../src/games/spark.ts"; | |
| 13 | import { boxNamed, createGameBox, grant, type GameBox } from "../src/games/store.ts"; | |
| 14 | import { forgeHttp, type ForgeHttp } from "../src/http/server.ts"; | |
| 15 | import { BODY_CAPS } from "../src/kernel/body_caps.ts"; | |
| 16 | import { quietLogs } from "./helpers/globals.ts"; | |
| 17 | ||
| 18 | quietLogs(); | |
| 19 | ||
| 20 | const ORIGIN = "http://forge.test"; | |
| 21 | const TYPE = "application/x-spark-sampler"; | |
| 22 | const fixture = new Uint8Array(Bun.gzipSync(new Uint8Array([10, 3, 102, 111, 111, 18, 1, 7]))); | |
| 23 | ||
| 24 | describe("spark profiles in a game box", () => { | |
| 25 | let dir: string; | |
| 26 | let app: App; | |
| 27 | let http: ForgeHttp; | |
| 28 | let box: GameBox; | |
| 29 | let base: string; | |
| 30 | const cookie = (name: string) => ({ cookie: `forge_session=${createSession(app.db, getUserByName(app.db, name)!.id).token}` }); | |
| 31 | const post = (secret: string, body: Uint8Array, type = TYPE) => | |
| 32 | http.handle(new Request(`${ORIGIN}/games/@spark/${secret}/post`, { method: "POST", headers: { "content-type": type }, body })); | |
| 33 | ||
| 34 | beforeAll(async () => { | |
| 35 | dir = await mkdtemp(join(tmpdir(), "forge-spark-")); | |
| 36 | app = createApp({ dataDir: dir, port: 0 }); | |
| 37 | http = forgeHttp(app); | |
| 38 | for (const [username, adminIfFirst] of [["alice", true], ["bob", false], ["carol", false]] as const) { | |
| 39 | const made = await createUser(app.db, { origin: "seed", trusted: true, username, email: `${username}@f.test`, password: "a-good-passphrase", adminIfFirst }); | |
| 40 | if (!made.ok) throw new Error(made.error); | |
| 41 | } | |
| 42 | createGameBox(app.db, { name: "net", repo: "alice/mc-network", path: "net/docker-compose.yml" }); | |
| 43 | box = boxNamed(app.db, "net")!; | |
| 44 | grant(app.db, box.id, getUserByName(app.db, "bob")!.id, "viewer"); | |
| 45 | base = newSparkSecret(app.db, box.id); | |
| 46 | }); | |
| 47 | afterAll(async () => { | |
| 48 | await rm(dir, { recursive: true, force: true }); | |
| 49 | }); | |
| 50 | ||
| 51 | test("a post is a 201 with a Location and no body; a grant reads it back; anyone else is refused", async () => { | |
| 52 | const r = await post(base, fixture); | |
| 53 | expect(r.status).toBe(201); | |
| 54 | expect(await r.text()).toBe(""); | |
| 55 | const key = r.headers.get("location")!; | |
| 56 | expect(key).toMatch(/^[\w-]{16}$/); | |
| 57 | const mine = await http.handle(new Request(`${ORIGIN}/games/@spark/${base}/${key}`, { headers: cookie("bob") })); | |
| 58 | expect(mine.status).toBe(200); | |
| 59 | expect(mine.headers.get("content-type")).toBe(TYPE); | |
| 60 | expect(new Uint8Array(await mine.arrayBuffer())).toEqual(fixture); | |
| 61 | // No session, a session with no grant on the box: refused. The secret alone does not read. | |
| 62 | expect((await http.handle(new Request(`${ORIGIN}/games/@spark/${base}/${key}`))).status).toBe(403); | |
| 63 | expect((await http.handle(new Request(`${ORIGIN}/games/@spark/${base}/${key}`, { headers: cookie("carol") }))).status).toBe(403); | |
| 64 | // A wrong secret is a 403 for the read too. | |
| 65 | expect((await http.handle(new Request(`${ORIGIN}/games/@spark/nope/${key}`, { headers: cookie("bob") }))).status).toBe(403); | |
| 66 | }); | |
| 67 | ||
| 68 | test("a wrong secret cannot post, and the upload secret cannot be told from a read", async () => { | |
| 69 | expect((await post("not-the-secret", fixture)).status).toBe(403); | |
| 70 | expect((await post("", fixture)).status).not.toBe(201); | |
| 71 | expect(profilesOf(app.db, box.id).length).toBe(1); | |
| 72 | }); | |
| 73 | ||
| 74 | test("only gzip with a spark type is kept; past the cap is a 413", async () => { | |
| 75 | expect((await post(base, new Uint8Array([1, 2, 3]))).status).toBe(400); | |
| 76 | expect((await post(base, fixture, "text/html")).status).toBe(400); | |
| 77 | expect((await post(base, fixture, `${TYPE}; x=1`)).status).toBe(400); | |
| 78 | expect((await post(base, new Uint8Array(BODY_CAPS.gameSpark.bytes + 1))).status).toBe(413); | |
| 79 | }); | |
| 80 | ||
| 81 | test("the box's page lists what is stored; the listed link opens it for a grant", async () => { | |
| 82 | const page = await (await http.handle(new Request(`${ORIGIN}/games/net`, { headers: cookie("bob") }))).text(); | |
| 83 | expect(page).toContain("Profiles"); | |
| 84 | const link = /\/games\/net\/@spark\/([\w-]{16})/.exec(page); | |
| 85 | expect(link).not.toBeNull(); | |
| 86 | expect((await http.handle(new Request(`${ORIGIN}/games/net/@spark/${link![1]}`, { headers: cookie("bob") }))).status).toBe(200); | |
| 87 | expect((await http.handle(new Request(`${ORIGIN}/games/net/@spark/${link![1]}`, { headers: cookie("carol") }))).status).toBe(404); | |
| 88 | // Only the owner is offered a new address. | |
| 89 | expect(page).not.toContain("New upload address"); | |
| 90 | }); | |
| 91 | ||
| 92 | test("a new address ends the old one; expired and surplus profiles are dropped", () => { | |
| 93 | const fresh = newSparkSecret(app.db, box.id); | |
| 94 | expect(fresh).not.toBe(base); | |
| 95 | const t0 = Date.now(); | |
| 96 | for (let i = 0; i < SPARK_KEEP_COUNT + 5; i++) keepProfile(app.db, box.id, TYPE, fixture, t0 + i); | |
| 97 | expect(profilesOf(app.db, box.id).length).toBe(SPARK_KEEP_COUNT); | |
| 98 | expect(profilesOf(app.db, box.id, t0 + (SPARK_KEEP_DAYS + 1) * 86_400_000).length).toBe(0); | |
| 99 | }); | |
| 100 | ||
| 101 | test("the old address is a 403 after a new one", async () => { | |
| 102 | expect((await post(base, fixture)).status).toBe(403); | |
| 103 | }); | |
| 104 | }); |
test/no-polling.test.ts +2
| @@ -334,6 +334,8 @@ const NOT_WALKED: Record<string, string> = { | ||
| 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 | 335 | "/games/jar/:id/:name": "a kept plugin jar, a download behind a signed URL, not a page", |
| 336 | 336 | "/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 | "/games/@spark/:secret/:key": "a spark profile download for a session with a grant, behind a secret address, not a page; the seed makes none (test/game-spark.test.ts covers it)", | |
| 338 | "/games/:box/@spark/:key": "a spark profile download from a box page, not a page; the seed stores none (test/game-spark.test.ts covers it)", | |
| 337 | 339 | "/games/head/:uuid": "a player's head, a PNG kept from mc-heads.net, not a page", |
| 338 | 340 | "/:owner/:name/waves/:version": "needs a wave of a milestone", |
| 339 | 341 | "/boards/:slug": "needs a board", |
test/open-routes-floor.test.ts +1
| @@ -42,6 +42,7 @@ const FILL: Readonly<Record<string, string>> = { | ||
| 42 | 42 | // Not seeded: each still has to answer its not-found with the floor. |
| 43 | 43 | team: "core", env: "prod", file: "README.md", label: "v1", chapter: "1", kind: "desktop", machine: "web", |
| 44 | 44 | range: `${"0".repeat(40)}...${"1".repeat(40)}`, op: "x", step: "1", group: "a", version: "1", slug: "board", receipt: "r", token: "t", code: "c", spec: "16", stage: "build", walk: "1", flag: "x", room: "lobby", box: "net", service: "hub", hash: "0".repeat(16), uuid: "069a79f4-44e9-4726-a5be-fca90e38aaf5", |
| 45 | secret: "s".repeat(32), key: "k", | |
| 45 | 46 | }; |
| 46 | 47 | |
| 47 | 48 | /** Open GET routes that cannot be filled in from a seeded public repository, each with why. */ |
test/security-floor-routes.test.ts +2
| @@ -77,6 +77,8 @@ const UNSEEDED: Record<string, string> = { | ||
| 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 | 79 | "/games/@pack/:token/:file": "a client pack behind a link the seed does not make (test/game-client-pack.test.ts covers it)", |
| 80 | "/games/@spark/:secret/:key": "a spark profile behind a secret address the seed does not make (test/game-spark.test.ts covers it)", | |
| 81 | "/games/:box/@spark/:key": "a spark profile of a game box, which the seed does not make (test/game-spark.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", |
| 82 | 84 | "/talk/dev/:token": "a dev cell reached by a one-time token the seed does not mint (test/dev-cell.test.ts covers it)", |
test/tui-games.test.ts +40
| @@ -15,6 +15,7 @@ import { createApp, type App } from "../src/app.ts"; | ||
| 15 | 15 | import { createUser, getUserByName, type User } from "../src/core/users.ts"; |
| 16 | 16 | import { readCompose, serviceEnv } from "../src/games/compose.ts"; |
| 17 | 17 | import { WAKE_GRACE_MS } from "../src/games/heal.ts"; |
| 18 | import { boxOfSparkSecret, keepProfile } from "../src/games/spark.ts"; | |
| 18 | 19 | import { lentRunnerOf } from "../src/games/lend.ts"; |
| 19 | 20 | import { boxNamed, createGameBox, grant, grantsOf, recentCommands, recordSync } from "../src/games/store.ts"; |
| 20 | 21 | import { recordMetrics } from "../src/games/metrics.ts"; |
| @@ -373,6 +374,45 @@ test("the terminal's box screen shows the switch Run checks while servers sleep | ||
| 373 | 374 | } |
| 374 | 375 | }); |
| 375 | 376 | |
| 377 | const newSparkSecretCount = (): string => app.db.query<{ h: string }, []>("SELECT secret_hash AS h FROM game_spark_secret").get()!.h; | |
| 378 | ||
| 379 | test("the terminal's box screen lists stored spark profiles and u makes the upload address, for an owner alone (#18137)", async () => { | |
| 380 | const box = boxNamed(app.db, "net")!; | |
| 381 | const key = keepProfile(app.db, box.id, "application/x-spark-sampler", new Uint8Array(Bun.gzipSync(new Uint8Array([1, 2, 3])))); | |
| 382 | if (!key.ok) throw new Error(key.error); | |
| 383 | const owner = drive(alice, 200); | |
| 384 | try { | |
| 385 | owner.tui.ctx.push(gameBoxScreen(owner.session, owner.tui.ctx, box)); | |
| 386 | await settleApp(owner.tui); | |
| 387 | await owner.type("p"); | |
| 388 | await settleApp(owner.tui); | |
| 389 | expect(owner.tui.screen.toText()).toContain(key.value); | |
| 390 | await owner.type("u"); | |
| 391 | await settleUntil(owner.tui, "bytebin-url: "); | |
| 392 | const secret = /\/games\/@spark\/([\w-]+)\//.exec(owner.tui.screen.toText())?.[1]; | |
| 393 | expect(secret).toBeDefined(); | |
| 394 | expect(boxOfSparkSecret(app.db, secret!)).toBe(box.id); | |
| 395 | } finally { | |
| 396 | owner.tui.stop?.(); | |
| 397 | } | |
| 398 | // Bob (operator) sees the profile, not the address, and u makes none. | |
| 399 | const operator = drive(bob, 200); | |
| 400 | try { | |
| 401 | operator.tui.ctx.push(gameBoxScreen(operator.session, operator.tui.ctx, box)); | |
| 402 | await settleApp(operator.tui); | |
| 403 | await operator.type("p"); | |
| 404 | await settleApp(operator.tui); | |
| 405 | expect(operator.tui.screen.toText()).toContain(key.value); | |
| 406 | const before = newSparkSecretCount(); | |
| 407 | await operator.type("u"); | |
| 408 | await settleApp(operator.tui); | |
| 409 | expect(operator.tui.screen.toText()).not.toContain("bytebin-url: "); | |
| 410 | expect(newSparkSecretCount()).toBe(before); | |
| 411 | } finally { | |
| 412 | operator.tui.stop?.(); | |
| 413 | } | |
| 414 | }); | |
| 415 | ||
| 376 | 416 | test("the Games list says tick time after TPS when a Fabric exporter gave it, and no tick segment when it did not", async () => { |
| 377 | 417 | const box = boxNamed(app.db, "net")!; |
| 378 | 418 | const line = async () => { |
new above
offline