Public: anyone can read this; the crew can change it.
Games: host the spark profiler viewer and its uploads in the forge #18096
Merged 5h 24m ago, live in production
scout/forge:scout/18058-games-host-the-spark-profiler-viewer-and → main 0 commits fork 6 threads · 6 unresolved
14 files
changed +184
−20
- docs/features/game-spark.md
- scripts/unreached-allow.json
- src/games/spark.ts
- src/games/spark_profile.ts
- src/http/games_routes.ts
- src/http/lazy_lists.ts
- src/tui/screens/game_spark.ts
- src/web/pages/games.ts
- src/web/pages/games_spark.ts
- test/budgets/unfixtured/games-box-spark-key-view.json
- test/game-spark.test.ts
- test/no-polling.test.ts
- test/security-floor-routes.test.ts
- test/tui-games.test.ts
docs/features/game-spark.md +1 −1
| @@ -6,7 +6,7 @@ row: Game spark profiles | ||
| 6 | 6 | |
| 7 | 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 | 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`. | |
| 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). `/games/<box>/spark/<key>` (#18058) opens a stored sampler profile on the forge for the same grants, a hidden or missing one a `404`: its threads, busiest first, with the time sampled in each, names escaped, read by the one decoder `src/games/spark_profile.ts` (`sparkThreads`). It unpacks at most 8 MiB, builds at most a million fields and reads at most 200 threads, so a hostile profile is refused ("download it"), not inflated. On the terminal, `p` on the box screen opens the profiles; `j`/`k` choose one and `enter` lists its threads, for any grant. Any other kind, or a profile too large to read here, is kept and offered as a download. Nothing is fetched elsewhere. **Not done: spark's viewer is not hosted.** This is a thread list; the call tree and flame graph are still opened in spark's own viewer from the downloaded file (#18208), and the gzip is checked by its magic bytes only. Code: `src/games/spark.ts`, `src/web/pages/games_spark.ts`. | |
| 10 | 10 | |
| 11 | 11 | ## Installed with the mod (#18138) |
| 12 | 12 |
scripts/unreached-allow.json +1 −2
src/games/spark.ts +2 −2
| @@ -61,8 +61,8 @@ export function keepProfile(db: Database, boxId: string, type: string, bytes: Ui | ||
| 61 | 61 | } |
| 62 | 62 | |
| 63 | 63 | /** One stored profile of the box, unless it has expired. */ |
| 64 | export function profileOf(db: Database, boxId: string, key: string, now = Date.now()): { type: string; body: Uint8Array } | undefined { | |
| 65 | 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()); | |
| 64 | export function profileOf(db: Database, boxId: string, key: string, now = Date.now()): { type: string; body: Uint8Array; at: string } | undefined { | |
| 65 | const r = db.query<{ type: string; body: Uint8Array; at: string }, [string, string, string]>("SELECT type, body, created_at AS at FROM game_spark_profile WHERE box_id = ?1 AND key = ?2 AND expires_at > ?3").get(boxId, key, new Date(now).toISOString()); | |
| 66 | 66 | return r ?? undefined; |
| 67 | 67 | } |
| 68 | 68 |
src/games/spark_profile.ts +27 −4
| @@ -20,6 +20,14 @@ export const MAX_PACKED = 32 * 1024 * 1024; | ||
| 20 | 20 | * and bounds what one request parses on the single thread: `fields` holds one object per field. |
| 21 | 21 | */ |
| 22 | 22 | export const MAX_UNPACKED = 64 * 1024 * 1024; |
| 23 | /** Threads read: a profile has a few dozen; the rest of a hostile one is not parsed. */ | |
| 24 | const MAX_THREADS = 200; | |
| 25 | /** | |
| 26 | * Fields one decode may build, in all its messages: each is an object, so a body of millions of | |
| 27 | * 2-byte fields is refused ("too-large") rather than materialised. | |
| 28 | */ | |
| 29 | const MAX_FIELDS = 1_000_000; | |
| 30 | let fieldsLeft = MAX_FIELDS; | |
| 23 | 31 | const MAX_DEPTH = 256; |
| 24 | 32 | const MAX_NODES = 2_000_000; |
| 25 | 33 | /** The summary's own bounds: the tree shows this much of itself. */ |
| @@ -118,6 +126,7 @@ function fields(buf: Uint8Array): Field[] { | ||
| 118 | 126 | const key = varint(); |
| 119 | 127 | const n = Math.floor(key / 8), t = key % 8; |
| 120 | 128 | if (n < 1) throw new Bad("malformed", "a field has number 0"); |
| 129 | if (--fieldsLeft < 0) throw new Bad("too-large", "the profile has more fields than a profile of this size can"); | |
| 121 | 130 | if (t === 0) out.push({ n, t, v: varint(), b: NONE }); |
| 122 | 131 | else if (t === 1) out.push({ n, t, v: 0, b: take(8) }); |
| 123 | 132 | else if (t === 2) out.push({ n, t, v: 0, b: take(varint()) }); |
| @@ -268,7 +277,7 @@ function summarize(root: Field[]): SparkSummary { | ||
| 268 | 277 | const methodSources = new Map(mapOf(root, F.data.methodSources).map(([k, e]) => [k, str(e, 2)] as [string, string])); |
| 269 | 278 | const budget = { left: MAX_NODES }; |
| 270 | 279 | |
| 271 | const threads = subs(root, F.data.threads).map((t) => { | |
| 280 | const threads = all(root, F.data.threads).filter((f) => f.t === 2).slice(0, MAX_THREADS).map((f) => fields(f.b)).map((t) => { | |
| 272 | 281 | const roots = threadTree(t, classSources, methodSources, budget); |
| 273 | 282 | return { name: str(t, F.thread.name), roots, ms: sum(doubles(t, F.thread.times)) || num(t, F.legacy.threadTime) || sum(roots.map((r) => r.ms)) }; |
| 274 | 283 | }); |
| @@ -310,16 +319,17 @@ function summarize(root: Field[]): SparkSummary { | ||
| 310 | 319 | * A spark profile (gzipped protobuf, as `/spark profiler` uploads it) as a summary, or the error |
| 311 | 320 | * that names why not. |
| 312 | 321 | */ |
| 313 | export function decodeSparkProfile(body: Uint8Array): SparkResult { | |
| 322 | export function decodeSparkProfile(body: Uint8Array, unpacked = MAX_UNPACKED): SparkResult { | |
| 323 | fieldsLeft = MAX_FIELDS; | |
| 314 | 324 | const fail = (name: SparkErrorName, message: string): SparkResult => ({ ok: false, error: { name, message } }); |
| 315 | 325 | if (body.length > MAX_PACKED) return fail("too-large", `the body is over ${MAX_PACKED} bytes`); |
| 316 | 326 | if (body.length < 2 || body[0] !== 0x1f || body[1] !== 0x8b) return fail("not-gzip", "the body is not gzip"); |
| 317 | 327 | let raw: Uint8Array; |
| 318 | 328 | try { |
| 319 | raw = gunzipSync(body, { maxOutputLength: MAX_UNPACKED }); | |
| 329 | raw = gunzipSync(body, { maxOutputLength: unpacked }); | |
| 320 | 330 | } catch (e) { |
| 321 | 331 | const code = (e as { code?: string }).code; |
| 322 | if (code === "ERR_BUFFER_TOO_LARGE") return fail("too-large", `the profile expands past ${MAX_UNPACKED} bytes`); | |
| 332 | if (code === "ERR_BUFFER_TOO_LARGE") return fail("too-large", `the profile expands past ${unpacked} bytes`); | |
| 323 | 333 | if (code === "Z_BUF_ERROR" || /unexpected end/i.test(String((e as Error).message))) return fail("truncated", "the gzip stream ends early"); |
| 324 | 334 | return fail("malformed", "the gzip stream is damaged"); |
| 325 | 335 | } |
| @@ -330,3 +340,16 @@ export function decodeSparkProfile(body: Uint8Array): SparkResult { | ||
| 330 | 340 | return fail("malformed", "the profile could not be read"); |
| 331 | 341 | } |
| 332 | 342 | } |
| 343 | ||
| 344 | /** What the forge unpacks to show a profile on a page or in the terminal: the upload cap. */ | |
| 345 | export const READ_UNPACKED = 8 * 1024 * 1024; | |
| 346 | ||
| 347 | /** | |
| 348 | * The threads of a stored sampler profile, busiest first, for the page and the terminal; undefined | |
| 349 | * when it is another kind, or too large or damaged to read here (the bytes are still kept). | |
| 350 | */ | |
| 351 | export function sparkThreads(profile: { type: string; body: Uint8Array }): { name: string; ms: number }[] | undefined { | |
| 352 | if (profile.type !== "application/x-spark-sampler") return undefined; | |
| 353 | const r = decodeSparkProfile(profile.body, READ_UNPACKED); | |
| 354 | return r.ok && r.summary.threads.length > 0 ? r.summary.threads.map((t) => ({ name: t.name.slice(0, 120), ms: t.ms })) : undefined; | |
| 355 | } |
src/http/games_routes.ts +2 −1
| @@ -25,7 +25,7 @@ import { | ||
| 25 | 25 | } from "../web/pages/games.ts"; |
| 26 | 26 | import { gamePackDownload, gamePackLink, gamePackRevoke } from "../web/pages/games_client_pack.ts"; |
| 27 | 27 | import { gameMap, gameMapSlash } from "./games_map.ts"; |
| 28 | import { gameSparkLink, gameSparkOpen, gameSparkPost, gameSparkRead } from "../web/pages/games_spark.ts"; | |
| 28 | import { gameSparkLink, gameSparkOpen, gameSparkPost, gameSparkRead, gameSparkView } from "../web/pages/games_spark.ts"; | |
| 29 | 29 | import { gameConfigCommit, gameConfigPage, gameConfigPreview } from "../web/pages/games_config.ts"; |
| 30 | 30 | import { publicOrigin } from "../core/public_origin.ts"; |
| 31 | 31 | import type { Ctx, Handler } from "./context.ts"; |
| @@ -156,6 +156,7 @@ export function gamesRoutes(router: Router<Handler>): void { | ||
| 156 | 156 | router.add("GET", "/games/:box/@shell/stream", gameShellStream); |
| 157 | 157 | router.add("POST", "/games/:box/@spark", gameSparkLink); |
| 158 | 158 | router.add("GET", "/games/:box/@spark/:key", gameSparkOpen); |
| 159 | router.add("GET", "/games/:box/spark/:key", gameSparkView); | |
| 159 | 160 | router.add("POST", "/games/:box/take-back", gameTakeBackSubmit); |
| 160 | 161 | router.add("POST", "/games/:box/servers", gameServersSubmit); |
| 161 | 162 | router.add("GET", "/games/:box/:service", gameServicePage); |
src/http/lazy_lists.ts +1
| @@ -654,6 +654,7 @@ export const OPERATIONS_ROUTES = [ | ||
| 654 | 654 | ["GET", "/games/:box/@shell/stream"], |
| 655 | 655 | ["POST", "/games/:box/@spark"], |
| 656 | 656 | ["GET", "/games/:box/@spark/:key"], |
| 657 | ["GET", "/games/:box/spark/:key"], | |
| 657 | 658 | ["POST", "/games/:box/take-back"], |
| 658 | 659 | ["POST", "/games/:box/servers"], |
| 659 | 660 | ["GET", "/games/:box/:service"], |
src/tui/screens/game_spark.ts +40 −5
| @@ -1,11 +1,14 @@ | ||
| 1 | 1 | /** |
| 2 | 2 | * A box's stored spark profiles in the terminal (#18137), as /games/<box>'s Profiles block: what is |
| 3 | 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). | |
| 4 | * address (shown once, here, until the screen closes: only its hash is kept). `j`/`k` choose a | |
| 5 | * profile and `enter` lists a sampler profile's threads (#18058), for any grant on the box, as the | |
| 6 | * page does. | |
| 5 | 7 | */ |
| 6 | 8 | |
| 7 | 9 | import { publicOrigin } from "../../core/public_origin.ts"; |
| 8 | import { SPARK_WORDS, newSparkSecret, profilesOf, sparkBase } from "../../games/spark.ts"; | |
| 10 | import { SPARK_WORDS, newSparkSecret, profileOf, profilesOf, sparkBase } from "../../games/spark.ts"; | |
| 11 | import { sparkThreads } from "../../games/spark_profile.ts"; | |
| 9 | 12 | import { mayDo, roleOn, type GameBox } from "../../games/store.ts"; |
| 10 | 13 | import type { Ctx, Screen } from "../app/app.ts"; |
| 11 | 14 | import { binding } from "../app/keys.ts"; |
| @@ -15,6 +18,7 @@ import type { Session } from "../session.ts"; | ||
| 15 | 18 | |
| 16 | 19 | export function gameSparkScreen(f: Session, ctx: Ctx, box: GameBox): Screen { |
| 17 | 20 | let address = ""; |
| 21 | let at = 0; | |
| 18 | 22 | const lines = (w: number): string[] => { |
| 19 | 23 | const stored = profilesOf(f.app.db, box.id); |
| 20 | 24 | return [ |
| @@ -26,16 +30,47 @@ export function gameSparkScreen(f: Session, ctx: Ctx, box: GameBox): Screen { | ||
| 26 | 30 | }; |
| 27 | 31 | return { |
| 28 | 32 | title: `${box.name}: spark profiles`, |
| 29 | keys: [binding(["u"], "new upload address (owner)")], | |
| 33 | keys: [binding(["j", "k"], "choose a profile"), binding(["enter"], "list its threads"), binding(["u"], "new upload address (owner)")], | |
| 30 | 34 | render(area, s) { |
| 31 | 35 | const c = ctx.theme.c; |
| 32 | 36 | 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 | 37 | }, |
| 34 | 38 | 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)); | |
| 39 | if (e.ctrl || e.alt) return false; | |
| 40 | const stored = profilesOf(f.app.db, box.id); | |
| 41 | if (e.key === "j" || e.key === "down" || e.key === "k" || e.key === "up") { | |
| 42 | at = Math.max(0, Math.min(stored.length - 1, at + (e.key === "j" || e.key === "down" ? 1 : -1))); | |
| 43 | } else if (e.key === "enter") { | |
| 44 | const chosen = stored[at]; | |
| 45 | if (chosen === undefined || !mayDo(roleOn(f.app.db, f.user, box.id), "viewer")) return false; | |
| 46 | ctx.push(profileScreen(f, ctx, box, chosen.key)); | |
| 47 | return true; | |
| 48 | } else if (e.key === "u" && mayDo(roleOn(f.app.db, f.user, box.id), "owner")) { | |
| 49 | address = sparkBase(publicOrigin(f.app.config.url, `http://localhost:${String(f.app.config.port)}`), newSparkSecret(f.app.db, box.id)); | |
| 50 | } else return false; | |
| 37 | 51 | ctx.invalidate(); |
| 38 | 52 | return true; |
| 39 | 53 | }, |
| 40 | 54 | }; |
| 41 | 55 | } |
| 56 | ||
| 57 | /** One stored profile's threads, busiest first: the page's list, in the same words. */ | |
| 58 | function profileScreen(f: Session, ctx: Ctx, box: GameBox, key: string): Screen { | |
| 59 | const lines = (w: number): string[] => { | |
| 60 | const profile = profileOf(f.app.db, box.id, key); | |
| 61 | if (profile === undefined) return ["This profile is gone: it is kept 14 days."]; | |
| 62 | const threads = sparkThreads(profile); | |
| 63 | return threads === undefined | |
| 64 | ? wrap("The forge can list the threads of a sampler profile only, and this one is not a readable one: download it from the box's page.", w) | |
| 65 | : ["The threads, busiest first. The call tree and flame graph are not shown here.", "", ...threads.map((t) => `${String(Math.round(t.ms))} ms sampled ${t.name}`)]; | |
| 66 | }; | |
| 67 | return { | |
| 68 | title: `${box.name}: profile ${key}`, | |
| 69 | keys: [], | |
| 70 | render(area, s) { | |
| 71 | const c = ctx.theme.c; | |
| 72 | 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)); | |
| 73 | }, | |
| 74 | key: () => false, | |
| 75 | }; | |
| 76 | } |
src/web/pages/games.ts +1 −1
| @@ -508,7 +508,7 @@ function sparkBlock(ctx: Ctx, box: GameBox, owner: boolean): Html { | ||
| 508 | 508 | <p class="muted small">${SPARK_WORDS}</p> |
| 509 | 509 | ${stored.length === 0 |
| 510 | 510 | ? html`<p class="muted small">None stored yet.</p>` |
| 511 | : 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` })))} | |
| 511 | : 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` })))} | |
| 512 | 512 | ${owner |
| 513 | 513 | ? html`<form method="post" action="/games/${box.name}/@spark" class="row-fields"> |
| 514 | 514 | ${btn(hasSparkSecret(ctx.app.db, box.id) ? "New upload address" : "Make an upload address", { type: "submit", variant: "secondary" })} |
src/web/pages/games_spark.ts +29 −1
| @@ -8,8 +8,12 @@ import { BODY_CAPS, readBounded } from "../../http/limits.ts"; | ||
| 8 | 8 | import type { Ctx } from "../../http/context.ts"; |
| 9 | 9 | import { seesBox } from "../../games/store.ts"; |
| 10 | 10 | import { boxOfSparkSecret, keepProfile, newSparkSecret, profileOf, sparkBase } from "../../games/spark.ts"; |
| 11 | import { sparkThreads } from "../../games/spark_profile.ts"; | |
| 12 | import { notFoundPage, pageHead } from "../chrome.ts"; | |
| 13 | import { html } from "../html.ts"; | |
| 14 | import { flashTo, page } from "../layout.ts"; | |
| 15 | import { row, rowList } from "../ui.ts"; | |
| 11 | 16 | import { readForm } from "../form.ts"; |
| 12 | import { flashTo } from "../layout.ts"; | |
| 13 | 17 | import { boxOf } from "./games.ts"; |
| 14 | 18 | |
| 15 | 19 | const plain = (text: string, status: number): Response => new Response(text, { status, headers: { "content-type": "text/plain; charset=utf-8", "cache-control": "no-store" } }); |
| @@ -57,3 +61,27 @@ export async function gameSparkLink(ctx: Ctx): Promise<Response> { | ||
| 57 | 61 | const base = sparkBase(publicOrigin(ctx.app.config.url, `http://localhost:${String(ctx.app.config.port)}`), newSparkSecret(ctx.app.db, got.box.id)); |
| 58 | 62 | 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 | 63 | } |
| 64 | ||
| 65 | // GET /games/:box/spark/:key: a profile opened on the forge (#18058), decoded here, nothing | |
| 66 | // fetched elsewhere. A sampler profile lists its threads; any other kind is kept and offered as a | |
| 67 | // download. A missing and a hidden profile are alike a 404. | |
| 68 | export function gameSparkView(ctx: Ctx): Response { | |
| 69 | const got = boxOf(ctx, "viewer"); | |
| 70 | if (got instanceof Response) return got; | |
| 71 | const key = ctx.params.key ?? ""; | |
| 72 | const profile = profileOf(ctx.app.db, got.box.id, key); | |
| 73 | if (profile === undefined) return notFoundPage(ctx); | |
| 74 | const threads = sparkThreads(profile); | |
| 75 | const taken = profile.type.replace("application/x-spark-", ""); | |
| 76 | return page({ | |
| 77 | ctx, | |
| 78 | title: `Profile · ${got.box.name}`, | |
| 79 | body: html`${pageHead(`Profile ${key}`, { sub: `A spark ${taken} profile from ${got.box.name}, taken ${profile.at.slice(0, 16).replace("T", " ")} UTC, ${String(Math.ceil(profile.body.length / 1024))} KiB.` })} | |
| 80 | <section class="settings-block"> | |
| 81 | <p class="muted small"><a href="/games/${got.box.name}/@spark/${key}" download="${key}.sparkprofile">Download the profile</a> to open it in spark's own viewer.</p> | |
| 82 | ${threads === undefined | |
| 83 | ? html`<p class="muted">The forge can list the threads of a sampler profile only, and this one is not a readable one: download it.</p>` | |
| 84 | : html`<p class="muted small">The threads, busiest first. The call tree and flame graph are not shown here.</p>${rowList(threads.map((t) => row({ title: html`${t.name}`, meta: html`${String(Math.round(t.ms))} ms sampled` })))}`} | |
| 85 | </section>`, | |
| 86 | }); | |
| 87 | } |
test/budgets/unfixtured/games-box-spark-key-view.json added +4
test/game-spark.test.ts +52 −3
| @@ -9,6 +9,8 @@ import { join } from "node:path"; | ||
| 9 | 9 | import { createApp, type App } from "../src/app.ts"; |
| 10 | 10 | import { createSession } from "../src/core/sessions.ts"; |
| 11 | 11 | import { createUser, getUserByName } from "../src/core/users.ts"; |
| 12 | import { gzipSync } from "node:zlib"; | |
| 13 | import { decodeSparkProfile } from "../src/games/spark_profile.ts"; | |
| 12 | 14 | import { SPARK_KEEP_COUNT, SPARK_KEEP_DAYS, keepProfile, newSparkSecret, profilesOf } from "../src/games/spark.ts"; |
| 13 | 15 | import { boxNamed, createGameBox, grant, type GameBox } from "../src/games/store.ts"; |
| 14 | 16 | import { forgeHttp, type ForgeHttp } from "../src/http/server.ts"; |
| @@ -81,14 +83,61 @@ describe("spark profiles in a game box", () => { | ||
| 81 | 83 | test("the box's page lists what is stored; the listed link opens it for a grant", async () => { |
| 82 | 84 | const page = await (await http.handle(new Request(`${ORIGIN}/games/net`, { headers: cookie("bob") }))).text(); |
| 83 | 85 | expect(page).toContain("Profiles"); |
| 84 | const link = /\/games\/net\/@spark\/([\w-]{16})/.exec(page); | |
| 86 | const link = /\/games\/net\/spark\/([\w-]{16})/.exec(page); | |
| 85 | 87 | 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 | expect((await http.handle(new Request(`${ORIGIN}/games/net/spark/${link![1]}`, { headers: cookie("bob") }))).status).toBe(200); | |
| 89 | expect((await http.handle(new Request(`${ORIGIN}/games/net/spark/${link![1]}`, { headers: cookie("carol") }))).status).toBe(404); | |
| 88 | 90 | // Only the owner is offered a new address. |
| 89 | 91 | expect(page).not.toContain("New upload address"); |
| 90 | 92 | }); |
| 91 | 93 | |
| 94 | // SamplerData.threads is field 2 and ThreadNode.name field 1, per spark's spark_sampler.proto | |
| 95 | // (the field numbers spark_profile.ts checks against that file); the bytes are built here from | |
| 96 | // it. | |
| 97 | const varint = (n: number): number[] => (n < 128 ? [n] : [(n & 127) | 128, ...varint(n >> 7)]); | |
| 98 | const ld = (f: number, b: number[]): number[] => [...varint(f * 8 + 2), ...varint(b.length), ...b]; | |
| 99 | const text = (t: string): number[] => [...new TextEncoder().encode(t)]; | |
| 100 | const thread = (name: string): number[] => ld(2, ld(1, text(name))); | |
| 101 | const sampler = (...names: string[]): Uint8Array => new Uint8Array(gzipSync(new Uint8Array(names.flatMap(thread)))); | |
| 102 | ||
| 103 | test("the viewer page lists a sampler profile's threads, escaped; a non-sampler is offered as a download", async () => { | |
| 104 | const real = sampler("Server thread", "<img src=x onerror=alert(1)>"); | |
| 105 | const key = (await post(base, real)).headers.get("location")!; | |
| 106 | const r = await http.handle(new Request(`${ORIGIN}/games/net/spark/${key}`, { headers: cookie("bob") })); | |
| 107 | expect(r.status).toBe(200); | |
| 108 | const body = await r.text(); | |
| 109 | expect(body).toContain("Server thread"); | |
| 110 | expect(body).toContain("<img src=x"); | |
| 111 | expect(body).not.toContain("<img src=x"); | |
| 112 | expect(body).toContain("The call tree and flame graph are not shown here"); | |
| 113 | expect((await http.handle(new Request(`${ORIGIN}/games/net/spark/${key}`, { headers: cookie("carol") }))).status).toBe(404); | |
| 114 | const out = await http.handle(new Request(`${ORIGIN}/games/net/spark/${key}`)); | |
| 115 | expect(out.status).toBe(303); | |
| 116 | expect(out.headers.get("location")).toContain("/signin"); | |
| 117 | expect((await http.handle(new Request(`${ORIGIN}/games/net/spark/nosuchkey`, { headers: cookie("bob") }))).status).toBe(404); | |
| 118 | const other = (await post(base, fixture, "application/x-spark-heap")).headers.get("location")!; | |
| 119 | expect(await (await http.handle(new Request(`${ORIGIN}/games/net/spark/${other}`, { headers: cookie("bob") }))).text()).toContain("is not a readable one: download it"); | |
| 120 | }); | |
| 121 | ||
| 122 | test("a hostile profile is bounded: a gzip bomb, a flood of fields, and past 200 threads", async () => { | |
| 123 | // 9 MiB of zero bytes gzips small and expands past the 8 MiB the page unpacks. | |
| 124 | const bomb = new Uint8Array(gzipSync(new Uint8Array(9 * 1024 * 1024))); | |
| 125 | expect(bomb.length).toBeLessThan(BODY_CAPS.gameSpark.bytes); | |
| 126 | const bombKey = (await post(base, bomb)).headers.get("location")!; | |
| 127 | const t0 = performance.now(); | |
| 128 | expect(await (await http.handle(new Request(`${ORIGIN}/games/net/spark/${bombKey}`, { headers: cookie("bob") }))).text()).toContain("is not a readable one"); | |
| 129 | expect(performance.now() - t0).toBeLessThan(1000); | |
| 130 | // 1,200,000 two-byte fields (field 15, varint 0) in one message: refused, not built. | |
| 131 | const flood = new Uint8Array(gzipSync(new Uint8Array(2_400_000).fill(0).map((_, i) => (i % 2 === 0 ? 0x78 : 0)))); | |
| 132 | const r = decodeSparkProfile(flood); | |
| 133 | expect(r.ok).toBe(false); | |
| 134 | if (!r.ok) expect(r.error.name).toBe("too-large"); | |
| 135 | const many = decodeSparkProfile(sampler(...Array.from({ length: 300 }, (_, i) => `t${String(i)}`))); | |
| 136 | if (!many.ok) throw new Error(many.error.message); | |
| 137 | expect(many.summary.threads.length).toBe(200); | |
| 138 | }); | |
| 139 | ||
| 140 | ||
| 92 | 141 | test("a new address ends the old one; expired and surplus profiles are dropped", () => { |
| 93 | 142 | const fresh = newSparkSecret(app.db, box.id); |
| 94 | 143 | expect(fresh).not.toBe(base); |
test/no-polling.test.ts +1
| @@ -337,6 +337,7 @@ const NOT_WALKED: Record<string, string> = { | ||
| 337 | 337 | "/games/jar/:id/:name": "a kept plugin jar, a download behind a signed URL, not a page", |
| 338 | 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)", |
| 339 | 339 | "/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)", |
| 340 | "/games/:box/spark/:key": "a stored spark profile read on the forge; the seed stores none (test/game-spark.test.ts covers it)", | |
| 340 | 341 | "/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)", |
| 341 | 342 | "/games/head/:uuid": "a player's head, a PNG kept from mc-heads.net, not a page", |
| 342 | 343 | "/:owner/:name/waves/:version": "needs a wave of a milestone", |
test/security-floor-routes.test.ts +1
| @@ -80,6 +80,7 @@ const UNSEEDED: Record<string, string> = { | ||
| 80 | 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)", |
| 81 | 81 | "/games/@pack/:token/:file": "a client pack behind a link the seed does not make (test/game-client-pack.test.ts covers it)", |
| 82 | 82 | "/games/@spark/:secret/:key": "a spark profile behind a secret address the seed does not make (test/game-spark.test.ts covers it)", |
| 83 | "/games/:box/spark/:key": "a spark profile of a game box, read on the forge, which the seed does not make (test/game-spark.test.ts covers it)", | |
| 83 | 84 | "/games/:box/@spark/:key": "a spark profile of a game box, which the seed does not make (test/game-spark.test.ts covers it)", |
| 84 | 85 | "/games/head/:uuid": "a player's head picture, by a Minecraft UUID only a game box's agent reports", |
| 85 | 86 | "/games/jar/:id/:name": "a kept plugin jar of a game box, behind a signed URL the seed does not make", |
test/tui-games.test.ts +22
| @@ -374,6 +374,28 @@ test("the terminal's box screen shows the switch Run checks while servers sleep | ||
| 374 | 374 | } |
| 375 | 375 | }); |
| 376 | 376 | |
| 377 | test("enter on a stored sampler profile lists its threads, for a viewer (#18058)", async () => { | |
| 378 | const box = boxNamed(app.db, "net")!; | |
| 379 | const varint = (n: number): number[] => (n < 128 ? [n] : [(n & 127) | 128, ...varint(n >> 7)]); | |
| 380 | const ld = (f: number, b: number[]): number[] => [...varint(f * 8 + 2), ...varint(b.length), ...b]; | |
| 381 | const thread = ld(2, ld(1, [...new TextEncoder().encode("Zeta thread")])); | |
| 382 | app.db.query("DELETE FROM game_spark_profile WHERE box_id = ?").run(box.id); | |
| 383 | const key = keepProfile(app.db, box.id, "application/x-spark-sampler", new Uint8Array(Bun.gzipSync(new Uint8Array(thread)))); | |
| 384 | if (!key.ok) throw new Error(key.error); | |
| 385 | const viewer = drive(bob, 200); | |
| 386 | try { | |
| 387 | viewer.tui.ctx.push(gameBoxScreen(viewer.session, viewer.tui.ctx, box)); | |
| 388 | await settleApp(viewer.tui); | |
| 389 | await viewer.type("p"); | |
| 390 | await settleApp(viewer.tui); | |
| 391 | await viewer.type("\r"); | |
| 392 | await settleUntil(viewer.tui, "Zeta thread"); | |
| 393 | expect(viewer.tui.screen.toText()).toContain("The call tree and flame graph are not shown here"); | |
| 394 | } finally { | |
| 395 | viewer.tui.stop?.(); | |
| 396 | } | |
| 397 | }); | |
| 398 | ||
| 377 | 399 | const newSparkSecretCount = (): string => app.db.query<{ h: string }, []>("SELECT secret_hash AS h FROM game_spark_secret").get()!.h; |
| 378 | 400 | |
| 379 | 401 | test("the terminal's box screen lists stored spark profiles and u makes the upload address, for an owner alone (#18137)", async () => { |
new above
offline
Non-blocking: the chosen index
atis never drawn, soj/kgive no feedback. Prefix the chosen row inlines().