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

Games: host the spark profiler viewer and its uploads in the forge #18096

opened this in answer to

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

  • Merged. scout/18058-games-host-the-spark-profiler-viewer-and was merged into main as beabbda.

Review

Sign in to review this change.
14 files changed +184 −20
docs/features/game-spark.md +1 −1
@@ -6,7 +6,7 @@ row: Game spark profiles
66
77 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.
88
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`.
1010
1111 ## Installed with the mod (#18138)
1212
scripts/unreached-allow.json +1 −2
@@ -1,6 +1,5 @@
11 [
22 "src/apps/room.ts",
33 "src/spawn/pod.ts",
4 "src/maintain/lockfiles.ts",
5 "src/games/spark_profile.ts"
4 "src/maintain/lockfiles.ts"
65 ]
src/games/spark.ts +2 −2
@@ -61,8 +61,8 @@ export function keepProfile(db: Database, boxId: string, type: string, bytes: Ui
6161 }
6262
6363 /** 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());
6666 return r ?? undefined;
6767 }
6868
src/games/spark_profile.ts +27 −4
@@ -20,6 +20,14 @@ export const MAX_PACKED = 32 * 1024 * 1024;
2020 * and bounds what one request parses on the single thread: `fields` holds one object per field.
2121 */
2222 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;
2331 const MAX_DEPTH = 256;
2432 const MAX_NODES = 2_000_000;
2533 /** The summary's own bounds: the tree shows this much of itself. */
@@ -118,6 +126,7 @@ function fields(buf: Uint8Array): Field[] {
118126 const key = varint();
119127 const n = Math.floor(key / 8), t = key % 8;
120128 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");
121130 if (t === 0) out.push({ n, t, v: varint(), b: NONE });
122131 else if (t === 1) out.push({ n, t, v: 0, b: take(8) });
123132 else if (t === 2) out.push({ n, t, v: 0, b: take(varint()) });
@@ -268,7 +277,7 @@ function summarize(root: Field[]): SparkSummary {
268277 const methodSources = new Map(mapOf(root, F.data.methodSources).map(([k, e]) => [k, str(e, 2)] as [string, string]));
269278 const budget = { left: MAX_NODES };
270279
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) => {
272281 const roots = threadTree(t, classSources, methodSources, budget);
273282 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)) };
274283 });
@@ -310,16 +319,17 @@ function summarize(root: Field[]): SparkSummary {
310319 * A spark profile (gzipped protobuf, as `/spark profiler` uploads it) as a summary, or the error
311320 * that names why not.
312321 */
313 export function decodeSparkProfile(body: Uint8Array): SparkResult {
322 export function decodeSparkProfile(body: Uint8Array, unpacked = MAX_UNPACKED): SparkResult {
323 fieldsLeft = MAX_FIELDS;
314324 const fail = (name: SparkErrorName, message: string): SparkResult => ({ ok: false, error: { name, message } });
315325 if (body.length > MAX_PACKED) return fail("too-large", `the body is over ${MAX_PACKED} bytes`);
316326 if (body.length < 2 || body[0] !== 0x1f || body[1] !== 0x8b) return fail("not-gzip", "the body is not gzip");
317327 let raw: Uint8Array;
318328 try {
319 raw = gunzipSync(body, { maxOutputLength: MAX_UNPACKED });
329 raw = gunzipSync(body, { maxOutputLength: unpacked });
320330 } catch (e) {
321331 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`);
323333 if (code === "Z_BUF_ERROR" || /unexpected end/i.test(String((e as Error).message))) return fail("truncated", "the gzip stream ends early");
324334 return fail("malformed", "the gzip stream is damaged");
325335 }
@@ -330,3 +340,16 @@ export function decodeSparkProfile(body: Uint8Array): SparkResult {
330340 return fail("malformed", "the profile could not be read");
331341 }
332342 }
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 {
2525 } from "../web/pages/games.ts";
2626 import { gamePackDownload, gamePackLink, gamePackRevoke } from "../web/pages/games_client_pack.ts";
2727 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";
2929 import { gameConfigCommit, gameConfigPage, gameConfigPreview } from "../web/pages/games_config.ts";
3030 import { publicOrigin } from "../core/public_origin.ts";
3131 import type { Ctx, Handler } from "./context.ts";
@@ -156,6 +156,7 @@ export function gamesRoutes(router: Router<Handler>): void {
156156 router.add("GET", "/games/:box/@shell/stream", gameShellStream);
157157 router.add("POST", "/games/:box/@spark", gameSparkLink);
158158 router.add("GET", "/games/:box/@spark/:key", gameSparkOpen);
159 router.add("GET", "/games/:box/spark/:key", gameSparkView);
159160 router.add("POST", "/games/:box/take-back", gameTakeBackSubmit);
160161 router.add("POST", "/games/:box/servers", gameServersSubmit);
161162 router.add("GET", "/games/:box/:service", gameServicePage);
src/http/lazy_lists.ts +1
@@ -654,6 +654,7 @@ export const OPERATIONS_ROUTES = [
654654 ["GET", "/games/:box/@shell/stream"],
655655 ["POST", "/games/:box/@spark"],
656656 ["GET", "/games/:box/@spark/:key"],
657 ["GET", "/games/:box/spark/:key"],
657658 ["POST", "/games/:box/take-back"],
658659 ["POST", "/games/:box/servers"],
659660 ["GET", "/games/:box/:service"],
src/tui/screens/game_spark.ts +40 −5
@@ -1,11 +1,14 @@
11 /**
22 * A box's stored spark profiles in the terminal (#18137), as /games/<box>'s Profiles block: what is
33 * 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.
57 */
68
79 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";
912 import { mayDo, roleOn, type GameBox } from "../../games/store.ts";
1013 import type { Ctx, Screen } from "../app/app.ts";
1114 import { binding } from "../app/keys.ts";
@@ -15,6 +18,7 @@ import type { Session } from "../session.ts";
1518
1619 export function gameSparkScreen(f: Session, ctx: Ctx, box: GameBox): Screen {
1720 let address = "";
21 let at = 0;
1822 const lines = (w: number): string[] => {
1923 const stored = profilesOf(f.app.db, box.id);
2024 return [
@@ -26,16 +30,47 @@ export function gameSparkScreen(f: Session, ctx: Ctx, box: GameBox): Screen {
2630 };
2731 return {
2832 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)")],
3034 render(area, s) {
3135 const c = ctx.theme.c;
3236 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));
3337 },
3438 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;

Non-blocking: the chosen index at is never drawn, so j/k give no feedback. Prefix the chosen row in lines().

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;
3751 ctx.invalidate();
3852 return true;
3953 },
4054 };
4155 }
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 {
508508 <p class="muted small">${SPARK_WORDS}</p>
509509 ${stored.length === 0
510510 ? 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` })))}
512512 ${owner
513513 ? html`<form method="post" action="/games/${box.name}/@spark" class="row-fields">
514514 ${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";
88 import type { Ctx } from "../../http/context.ts";
99 import { seesBox } from "../../games/store.ts";
1010 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";
1116 import { readForm } from "../form.ts";
12 import { flashTo } from "../layout.ts";
1317 import { boxOf } from "./games.ts";
1418
1519 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> {
5761 const base = sparkBase(publicOrigin(ctx.app.config.url, `http://localhost:${String(ctx.app.config.port)}`), newSparkSecret(ctx.app.db, got.box.id));
5862 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 });
5963 }
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}`,
outdated

Principles 1 and 8: the title and the sub line repeat the type, the byte count and the box name, and application/x-spark-sampler is not plain words. Use one confident sentence, e.g. what the profile is, when it was taken and its size.

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
outdated

Principles 1 and 8: 'kept as it came' says nothing a person can use. Say plainly that only sampler profiles can be read here, and that this one can be downloaded.

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
@@ -0,0 +1,4 @@
1 {
2 "pattern": "/games/:box/spark/:key",
3 "why": "a decoded spark profile page; no fixture stores one (test/game-spark.test.ts covers it)"
4 }
test/game-spark.test.ts +52 −3
@@ -9,6 +9,8 @@ import { join } from "node:path";
99 import { createApp, type App } from "../src/app.ts";
1010 import { createSession } from "../src/core/sessions.ts";
1111 import { createUser, getUserByName } from "../src/core/users.ts";
12 import { gzipSync } from "node:zlib";
13 import { decodeSparkProfile } from "../src/games/spark_profile.ts";
1214 import { SPARK_KEEP_COUNT, SPARK_KEEP_DAYS, keepProfile, newSparkSecret, profilesOf } from "../src/games/spark.ts";
1315 import { boxNamed, createGameBox, grant, type GameBox } from "../src/games/store.ts";
1416 import { forgeHttp, type ForgeHttp } from "../src/http/server.ts";
@@ -81,14 +83,61 @@ describe("spark profiles in a game box", () => {
8183 test("the box's page lists what is stored; the listed link opens it for a grant", async () => {
8284 const page = await (await http.handle(new Request(`${ORIGIN}/games/net`, { headers: cookie("bob") }))).text();
8385 expect(page).toContain("Profiles");
84 const link = /\/games\/net\/@spark\/([\w-]{16})/.exec(page);
86 const link = /\/games\/net\/spark\/([\w-]{16})/.exec(page);
8587 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);
8890 // Only the owner is offered a new address.
8991 expect(page).not.toContain("New upload address");
9092 });
9193
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("&lt;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
92141 test("a new address ends the old one; expired and surplus profiles are dropped", () => {
93142 const fresh = newSparkSecret(app.db, box.id);
94143 expect(fresh).not.toBe(base);
test/no-polling.test.ts +1
@@ -337,6 +337,7 @@ const NOT_WALKED: Record<string, string> = {
337337 "/games/jar/:id/:name": "a kept plugin jar, a download behind a signed URL, not a page",
338338 "/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)",
339339 "/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)",
340341 "/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)",
341342 "/games/head/:uuid": "a player's head, a PNG kept from mc-heads.net, not a page",
342343 "/: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> = {
8080 "/games/:box/:service/m/:pass/*path": "a game box's map, which the seed does not make (test/games-map.test.ts covers it)",
8181 "/games/@pack/:token/:file": "a client pack behind a link the seed does not make (test/game-client-pack.test.ts covers it)",
8282 "/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)",
8384 "/games/:box/@spark/:key": "a spark profile of a game box, which the seed does not make (test/game-spark.test.ts covers it)",
8485 "/games/head/:uuid": "a player's head picture, by a Minecraft UUID only a game box's agent reports",
8586 "/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
374374 }
375375 });
376376
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
377399 const newSparkSecretCount = (): string => app.db.query<{ h: string }, []>("SELECT secret_hash AS h FROM game_spark_secret").get()!.h;
378400
379401 test("the terminal's box screen lists stored spark profiles and u makes the upload address, for an owner alone (#18137)", async () => {

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

Keyboard shortcuts

Docs