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

Spark's config is installed with the mod so a profile uploads to the forge and never elsewhere #18173

opened this

Merged 7h 53m ago, live in production

scout/forge:scout/18138-spark-s-config-is-installed-with-the-mod → main 0 commits fork

  • Merged. scout/18138-spark-s-config-is-installed-with-the-mod was merged into main as 7de2fc0.

Review

Sign in to review this change.
7 files changed +129 −8
docs/features/game-spark.md +4
@@ -7,3 +7,7 @@ row: Game spark profiles
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
99 `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`.
10
11 ## Installed with the mod (#18138)
12
13 Installing spark (`mods_install spark`, or as a plugin of a new server) writes spark's config in the same commit: `config/spark/config.json` on a mod server, `plugins/spark/config.json` on a plugin server. Its `bytebinUrl` is the placeholder `${CFG_SPARK_BYTEBIN_URL}`, which the image fills from the service's environment (`${SPARK_BASE}`), and `SPARK_BASE` is written to the box's sealed `.env` at each check-in: the upload address with its secret, which the repository never holds. Its `viewerUrl` is the box's profile page (`<forge>/games/<box>/@spark/`). No author-hosted address is in the file, so with the placeholder unfilled spark has no address to post to rather than a public paste. The box's `.env` address is the box's upload address: one made by hand on the page works until the box's next check-in, which sets it back. Not done: a spark already installed is not rewritten, and a hand-edited config is replaced on a reinstall.
src/games/mods.ts +32 −3
@@ -22,11 +22,16 @@ import { commitCompose, composeDir, pluginUrls, readCompose, readRepoFile, servi
2222 import { byVersion, latestRelease, newestPack, packUpdate, readPack, resolve, targetOf, updates, type Locked, type LockedPack, type Result, type Target, type Version } from "./modrinth.ts";
2323 import { missing as setMissing, setNamed, SETS, SET_PREFIX, type ModSet } from "./mod_sets.ts";
2424 import { memoryRefusal, type BoxRoom } from "./box_memory.ts";
25 import { withConfig } from "./plugin_config.ts";
26 import { SPARK_CFG, SPARK_VAR, sparkConfig, sparkConfigFile } from "./spark.ts";
27 import { publicOrigin } from "../core/public_origin.ts";
2528 import { AUTOSTOPPER } from "./sleep.ts";
2629 import { servicesOf, type GameBox } from "./store.ts";
2730
2831 /** What a service has, as its repository says at the compose file's commit. */
2932 export interface Mods {
33 /** The box's name: the profile page spark's config points at. */
34 readonly boxName: string;
3035 readonly target: Target;
3136 readonly lock: readonly Locked[];
3237 /** MODRINTH_PROJECTS entries the lock does not pin (written by hand, or before the lock). */
@@ -54,6 +59,8 @@ export interface Plan {
5459 readonly done: string;
5560 /** The modpack the lock holds after it (undefined: as it was). */
5661 readonly pack?: LockedPack;
62 /** A config file written in the same commit (spark's: where its profiles go). */
63 readonly config?: { readonly file: string; readonly content: string };
5764 }
5865
5966 /** The lockfile's path for a service, beside the compose file. */
@@ -130,6 +137,7 @@ export async function modsOf(app: App, box: GameBox, service: string): Promise<R
130137 return {
131138 ok: true,
132139 value: {
140 boxName: box.name,
133141 target: target.value,
134142 lock,
135143 loose: split(env["MODRINTH_PROJECTS"]).filter((e) => !pinned.has(e) && e !== AUTOSTOPPER),
@@ -221,12 +229,17 @@ export async function planInstall(app: App, m: Mods, service: string, ref: strin
221229 got.value.find((l) => !m.lock.some((o) => o.project === l.project));
222230 const deps = got.value.filter((l) => !l.top && !m.lock.some((o) => o.project === l.project)).length;
223231 const title = added === undefined ? wantedRef : `${added.title} ${added.version}`;
232 // spark is written with its config, so a profile goes to this box's store and never to its
233 // author's paste.
234 const spark = added?.slug === "spark" ? sparkInstall(app, m) : undefined;
235 const lines = diffLines(m, got.value, new Set(adopt));
224236 return {
225237 ok: true,
226238 value: {
227 lines: diffLines(m, got.value, new Set(adopt)),
239 lines: spark === undefined ? lines : [...lines.slice(0, -1), spark.line, ...lines.slice(-1)],
228240 lock: got.value,
229 env: envFor(m, got.value, kept),
241 env: { ...envFor(m, got.value, kept), ...spark?.env },
242 ...(spark === undefined ? {} : { config: spark.config }),
230243 message: `games: ${service} mods: add ${title}${deps === 0 ? "" : ` and ${String(deps)} ${deps === 1 ? "dependency" : "dependencies"}`}`,
231244 sha: m.sha,
232245 done: `${title} is installed${deps === 0 ? "" : ` with ${String(deps)} ${deps === 1 ? "dependency" : "dependencies"}`}`,
@@ -234,6 +247,19 @@ export async function planInstall(app: App, m: Mods, service: string, ref: strin
234247 };
235248 }
236249
250 /**
251 * What installing spark adds: its config file, the env that fills it, and the line that says so.
252 */
253 function sparkInstall(app: App, m: Mods): { line: string; env: Record<string, string>; config: { file: string; content: string } } {
254 const file = sparkConfigFile(m.target.kind === "mod");
255 const origin = publicOrigin(app.config.url, `http://localhost:${String(app.config.port)}`);
256 return {
257 line: `Writes ${file} with the mod: profiles upload to this forge (the address, with its secret, comes from the box's .env), never to spark's own paste`,
258 env: { [SPARK_CFG]: "${" + SPARK_VAR + "}" },
259 config: { file, content: sparkConfig(origin, m.boxName) },
260 };
261 }
262
237263 /**
238264 * Install a named set (`mod_sets.ts`) as one plan: each project's newest version for this server
239265 * and everything they require, resolved together so one lock, one env and one commit cover them.
@@ -353,7 +379,10 @@ export async function commitPlan(app: App, user: User, box: GameBox, service: st
353379 const done = await commitCompose(app, user, box, {
354380 message: plan.message,
355381 what: service,
356 edit: (text) => setServiceEnv(text, service, plan.env),
382 edit: (text) => {
383 const env = setServiceEnv(text, service, plan.env);
384 return plan.config === undefined ? env : withConfig(env, service, plan.config.file, plan.config.content);
385 },
357386 extra: [{ path: lockPath(box, service), content: lockText(m.target, plan.lock, plan.pack ?? m.pack) }],
358387 expectTip: plan.sha,
359388 });
src/games/presets.ts +5 −1
@@ -13,6 +13,7 @@ import type { App } from "../app.ts";
1313 import type { User } from "../core/users.ts";
1414 import { commitCompose, composeServices, readCompose, serviceEnv, setTopEntry } from "./compose.ts";
1515 import { heapMiB } from "./box_memory.ts";
16 import { withConfig } from "./plugin_config.ts";
1617 import { lockPath, lockText, planInstall, type Mods } from "./mods.ts";
1718 import { search, targetOf, type Locked, type Result } from "./modrinth.ts";
1819 import { isGameServer, policyOf, proxyOf, setPolicy } from "./sleep.ts";
@@ -239,7 +240,7 @@ export async function planServer(app: App, box: GameBox, wish: Wish): Promise<Re
239240 // Plugins resolved one after another on the same lock, each for this server's loader and version.
240241 const target = targetOf(env, "");
241242 if (!target.ok) return target;
242 let m: Mods = { target: target.value, lock: [], loose: [], urls: [], held: [], sha: compose.sha, env, pack: undefined };
243 let m: Mods = { boxName: box.name, target: target.value, lock: [], loose: [], urls: [], held: [], sha: compose.sha, env, pack: undefined };
243244 const pluginLines: string[] = [];
244245 // Each theme: the most fitting plugin Modrinth finds for it that runs here and is well used.
245246 const chosen = [...wish.plugins];
@@ -254,10 +255,12 @@ export async function planServer(app: App, box: GameBox, wish: Wish): Promise<Re
254255 pluginLines.push(`For "${theme}": ${hit.title} (${hit.downloads.toLocaleString("en-US")} downloads), found on Modrinth.`);
255256 }
256257 let pinned: readonly Locked[] = [];
258 const files: { file: string; content: string }[] = [];
257259 for (const slug of chosen) {
258260 const planned = await planInstall(app, m, wish.name, slug);
259261 if (!planned.ok) return { ok: false, error: `${slug}: ${planned.error}` };
260262 pinned = planned.value.lock;
263 if (planned.value.config !== undefined) files.push(planned.value.config);
261264 pluginLines.push(...planned.value.lines);
262265 const nextEnv = { ...m.env };
263266 for (const [k, v] of Object.entries(planned.value.env))
@@ -283,6 +286,7 @@ export async function planServer(app: App, box: GameBox, wish: Wish): Promise<Re
283286 ];
284287 text = setTopEntry(compose.text, "services", wish.name, block);
285288 text = setTopEntry(text, "volumes", wish.name, []);
289 for (const f of files) text = withConfig(text, wish.name, f.file, f.content);
286290 ({ text, host } = proxyLines(text, wish.name));
287291 text = setPolicy(text, wish.name, "sleep");
288292 if ((Bun.YAML.parse(text) as { services?: Record<string, unknown> }).services?.[wish.name] === undefined)
src/games/spark.ts +42 −1
@@ -29,10 +29,15 @@ export function boxOfSparkSecret(db: Database, given: string): string | undefine
2929 return db.query<{ box_id: string }, [string]>("SELECT box_id FROM game_spark_secret WHERE secret_hash = ?1").get(sha256(given))?.box_id;
3030 }
3131
32 /** `s` is the box's one upload secret from now on (only its hash is kept). */
33 const useSecret = (db: Database, boxId: string, s: string, now: number): void => {
34 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());
35 };
36
3237 /** A new upload secret for the box, shown once; the old one stops working. */
3338 export function newSparkSecret(db: Database, boxId: string, now = Date.now()): string {
3439 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());
40 useSecret(db, boxId, s, now);
3641 return s;
3742 }
3843
@@ -74,3 +79,39 @@ export const SPARK_WORDS = `Profiles from spark: at most 8 MiB each, kept ${Stri
7479
7580 /** The upload address a secret makes: spark's `bytebin-url`. */
7681 export const sparkBase = (origin: string, s: string): string => `${origin}/games/@spark/${s}/`;
82
83 /**
84 * The compose-interpolated variable that holds a box's upload address; `.env` carries it, never the
85 * repository.
86 */
87 export const SPARK_VAR = "SPARK_BASE";
88 /**
89 * The variable the image reads while copying config (`CFG_` is its prefix) to fill the file's
90 * placeholder.
91 */
92 export const SPARK_CFG = "CFG_SPARK_BYTEBIN_URL";
93
94 /**
95 * spark's own config, written with the mod so a profile goes to this forge and nowhere else: its
96 * `bytebinUrl` is a placeholder the image fills from the box's sealed `.env` (the address carries
97 * the upload secret, which the repository never holds), and its `viewerUrl` is the box's profile
98 * page. With the placeholder unfilled the URL is no URL, so spark has no address to post to; it is
99 * never left on spark's default (the author's public paste).
100 */
101 export function sparkConfig(origin: string, boxName: string): string {
102 return `${JSON.stringify({ bytebinUrl: "${" + SPARK_CFG + "}", viewerUrl: `${origin}/games/${boxName}/@spark/` }, null, 2)}\n`;
103 }
104
105 /** Where spark reads its config: a mod's config folder, a plugin's own folder. */
106 export const sparkConfigFile = (mod: boolean): string => (mod ? "config/spark/config.json" : "plugins/spark/config.json");
107
108 /**
109 * The box's sealed upload secret made the one the forge accepts, and the address it makes. The
110 * box's `.env` is written from this at each check-in, so a new address made by hand lasts until the
111 * next one.
112 */
113 export function sealedSparkBase(db: Database, boxId: string, origin: string, sealed: string, now = Date.now()): string {
114 if (boxOfSparkSecret(db, sealed) !== boxId)
115 useSecret(db, boxId, sealed, now);
116 return sparkBase(origin, sealed);
117 }
src/games/store.ts +4 −1
@@ -22,6 +22,7 @@ import { resolveSecrets, setSecret } from "../core/secret_store.ts";
2222 import type { User } from "../core/users.ts";
2323 import { sha256 } from "../kernel/hash.ts";
2424 import { id as newId } from "../kernel/id.ts";
25 import { SPARK_VAR, sealedSparkBase } from "./spark.ts";
2526 import { lendWhyOf } from "./lend_why.ts";
2627
2728 export const BOX_NAME = /^[a-z][a-z0-9-]{0,39}$/;
@@ -485,10 +486,12 @@ export const rconKeys = (compose: string, services: readonly string[] = []): str
485486 * FORWARDING_SECRET (Velocity's modern forwarding) and each RCON_<SERVICE> the compose names. Each
486487 * is generated once a box, sealed, and never committed.
487488 */
488 export function envFiles(app: App, box: GameBox, compose: string, services: readonly string[] = []): Record<string, string> {
489 export function envFiles(app: App, box: GameBox, compose: string, services: readonly string[] = [], origin = ""): Record<string, string> {
489490 const run = `games:${box.name}`;
490491 const lines = [`FORWARDING_SECRET=${sealedOnce(app, forwardingSecretName(box), run)}`];
491492 for (const key of rconKeys(compose, services)) lines.push(`${key}=${sealedOnce(app, envSecretName(box, key), run)}`);
493 // spark's upload address, with its secret: only when a service interpolates it (`spark.ts`).
494 if (compose.includes("${" + SPARK_VAR)) lines.push(`${SPARK_VAR}=${sealedSparkBase(app.db, box.id, origin, sealedOnce(app, envSecretName(box, "SPARK_SECRET"), run))}`);
492495 return { ".env": `${lines.join("\n")}\n` };
493496 }
494497
src/http/games_routes.ts +2 −1
@@ -27,6 +27,7 @@ import { gamePackDownload, gamePackLink, gamePackRevoke } from "../web/pages/gam
2727 import { gameMap, gameMapSlash } from "./games_map.ts";
2828 import { gameSparkLink, gameSparkOpen, gameSparkPost, gameSparkRead } from "../web/pages/games_spark.ts";
2929 import { gameConfigCommit, gameConfigPage, gameConfigPreview } from "../web/pages/games_config.ts";
30 import { publicOrigin } from "../core/public_origin.ts";
3031 import type { Ctx, Handler } from "./context.ts";
3132 import { InvalidJson } from "./json_body.ts";
3233 import { apiError, boundedMachineBody, json } from "./respond.ts";
@@ -94,7 +95,7 @@ export async function gameAgentSync(ctx: Ctx): Promise<Response> {
9495 synced(ctx.app, box.id);
9596 const reply: Record<string, unknown> = {
9697 composeSha: compose?.sha ?? "",
97 env: envFiles(ctx.app, box, compose?.text ?? "", compose === undefined ? [] : composeServices(compose.text)),
98 env: envFiles(ctx.app, box, compose?.text ?? "", compose === undefined ? [] : composeServices(compose.text), publicOrigin(ctx.app.config.url, ctx.url.origin)),
9899 commands,
99100 };
100101 if (compose !== undefined && compose.sha !== (typeof body.composeSha === "string" ? body.composeSha : "")) reply["compose"] = signJarUrls(ctx.app, box, compose.text, ctx.url.origin);
test/game-mods.test.ts +40 −1
@@ -14,9 +14,11 @@ import { createApp, type App } from "../src/app.ts";
1414 import { createToken } from "../src/core/tokens.ts";
1515 import { createUser, getUserByName, type User } from "../src/core/users.ts";
1616 import { readCompose, readRepoFile, serviceEnv } from "../src/games/compose.ts";
17 import { configMounts } from "../src/games/plugin_config.ts";
18 import { boxOfSparkSecret } from "../src/games/spark.ts";
1719 import { search, searchPacks, targetOf } from "../src/games/modrinth.ts";
1820 import { commitPlan, lockPath, modsOf, packUpdateOf, planInstall, planPack, planPackUpdate, planRemove, planUpdate, updatesOf } from "../src/games/mods.ts";
19 import { boxNamed, createGameBox, recordSync, type GameBox } from "../src/games/store.ts";
21 import { boxNamed, createGameBox, envFiles, recordSync, type GameBox } from "../src/games/store.ts";
2022 import { forgeHttp, type ForgeHttp } from "../src/http/server.ts";
2123 import { packVerdict } from "../src/games/pack_check.ts";
2224 import { askPower } from "../src/games/power.ts";
@@ -157,10 +159,12 @@ const PROJECTS = [
157159 { id: "SLid0001", slug: "scalablelux", title: "ScalableLux" },
158160 { id: "NOid0001", slug: "noisium", title: "Noisium" },
159161 { id: "FPid0001", slug: "fabric-api", title: "Fabric API" },
162 { id: "SPid0001", slug: "spark", title: "spark" },
160163 ];
161164 const FABRIC = ["fabric"];
162165 const PAPER = ["paper", "spigot"];
163166 const VERSIONS: V[] = [
167 { id: "SPv00001", project: "SPid0001", number: "1.10.119", date: "2025-03-01", games: ["1.21.4"], loaders: [...PAPER, ...FABRIC], hash: "3a" },
164168 { id: "LPv00001", project: "LPid0001", number: "5.4.100", date: "2024-10-01", games: ["1.21.4"], loaders: PAPER, hash: "1" },
165169 { id: "LPv00002", project: "LPid0001", number: "5.4.145", date: "2024-12-01", games: ["1.21.4"], loaders: PAPER, hash: "2" },
166170 { id: "LPv00003", project: "LPid0001", number: "5.4.150", date: "2025-01-10", games: ["1.21.4"], loaders: PAPER, hash: "3" },
@@ -566,6 +570,41 @@ describe("Modrinth", () => {
566570 });
567571 });
568572
573 describe("spark's config is installed with the mod", () => {
574 test("the plan writes the config in the same commit: this forge's store, never the author's paste, and no secret in git", async () => {
575 const plan = await planInstall(app, await mods(), "hub", "spark");
576 if (!plan.ok) throw new Error(plan.error);
577 expect(plan.value.config?.file).toBe("plugins/spark/config.json");
578 expect(plan.value.lines.some((l) => l.startsWith("Writes plugins/spark/config.json"))).toBe(true);
579 const text = plan.value.config!.content;
580 expect(JSON.parse(text)).toEqual({ bytebinUrl: "${CFG_SPARK_BYTEBIN_URL}", viewerUrl: "http://localhost:0/games/net/@spark/" });
581 expect(text).not.toMatch(/lucko|bytebin\./);
582 expect(plan.value.env["CFG_SPARK_BYTEBIN_URL"]).toBe("${SPARK_BASE}");
583 // A Fabric server reads it from config/.
584 const fabric = await planInstall(app, await mods("smp"), "smp", "spark");
585 if (!fabric.ok) throw new Error(fabric.error);
586 expect(fabric.value.config?.file).toBe("config/spark/config.json");
587 // Another mod writes none.
588 const other = await planInstall(app, await mods(), "hub", "worldedit");
589 if (!other.ok) throw new Error(other.error);
590 expect(other.value.config).toBeUndefined();
591
592 const done = await commitPlan(app, alice, box, "hub", await mods(), plan.value);
593 if (!done.ok) throw new Error(done.error);
594 const compose = (await readCompose(app, box))!;
595 expect(configMounts(compose.text, "hub").find((c) => c.file === "plugins/spark/config.json")?.content).toBe(text);
596 expect(serviceEnv(compose.text, "hub")["CFG_SPARK_BYTEBIN_URL"]).toBe("${SPARK_BASE}");
597 // The repository holds no secret: the box's .env does, and the forge accepts exactly that
598 // address.
599 const env = envFiles(app, box, compose.text, [], "http://forge.test")[".env"]!;
600 const base = /^SPARK_BASE=(.+)$/m.exec(env)![1]!;
601 expect(base).toMatch(/^http:\/\/forge\.test\/games\/@spark\/[0-9a-f]{64}\/$/);
602 expect(compose.text).not.toContain(base.split("/")[5]!);
603 expect(boxOfSparkSecret(app.db, base.split("/")[5]!)).toBe(box.id);
604 expect(envFiles(app, box, compose.text, [], "http://forge.test")[".env"]).toBe(env);
605 });
606 });
607
569608 describe("modpacks", () => {
570609 test("a pack goes on a Fabric server: client-only files left out, overrides then server-overrides, every file locked", async () => {
571610 const hub = await modsOf(app, box, "hub");

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

Keyboard shortcuts

Docs