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

Games: a client pack, one .mrpack a player opens in a launcher to join a mod server #17815

opened this

Sentinel asked for changes (review 01m8x3h37qbfnmkft6n7s09gab)

sold/client-pack → main 3 commits

Review

Sign in to review this change.
18 files changed +741 −11
docs/features/games.md +4 −2
@@ -10,8 +10,8 @@ A **game box** is a VM on your own cloud running Docker and `forge-game-agent`,
1010
1111 - **In the navigation:** Games is in the top bar, at `g p` (`g P` inside a repository), in Cmd/Ctrl K and in the terminal's palette, for a forge admin and anyone with a grant on a box. With no box, an admin's `/games` has Start a game box: it asks Talk for a plan, which builds nothing until approved. In the terminal `n` on an empty Games screen sends the same words.
1212 - **Web:** `/games` lists the boxes you may see; `/games/<box>` is the network, one row a service with Start, Stop and Restart; `/games/<box>/<service>` is the console (a live log over SSE in the game's own colours: the agent and the sync route turn each colour escape into its § code before they drop every other escape, and the page draws § codes through the one renderer, with Raw for the lines as kept, through the [log reader](log-reader.md); an RCON input under it, each command a block whose state and answer come in place over the log's one stream, with the service's earlier commands on up and down; a crash found in the log leads in one line, "Crashed: Fabric could not load the mods: Install fabric-api", with the crash folded under it and a Share on mclo.gs button that says it publishes the log where anyone with the link can read it, and posts only on that click), the environment editor (commits `games: <service> env: <keys>`), the settings ([Game settings](game-settings.md)) and its mods or plugins (Modrinth, below; Upload jar for `PLUGINS`). Pages: `src/web/pages/games.ts`.
13 - **Terminal:** the Games screen (`src/tui/screens/games.ts`): each service, `s`, `x`, `r`; `enter` opens its console and env, `c` there its settings, and `m` its mods (`/` search, `a` install, `u` update all, `d` remove, then `y` commits the preview shown); a service's console is the [log reader](log-reader.md) with the colour codes gone, a crash first in one line, and `:`'s prompt walks earlier commands with up and down.
14 - **MCP:** `games` (admin-listed): `list`, `console`, `power`, `env`, `config`, `config_set`, and `mods`, `mods_search`, `mods_install`, `mods_update`, `mods_remove` (each change planned first; `dryRun: false` commits), with the same grants.
13 - **Terminal:** the Games screen (`src/tui/screens/games.ts`): each service, `s`, `x`, `r`; `enter` opens its console and env, `c` there its settings, and `m` its mods (`/` search, `a` install, `u` update all, `d` remove, then `y` commits the preview shown; `l` makes a link for players to the client pack, `x` ends every link); a service's console is the [log reader](log-reader.md) with the colour codes gone, a crash first in one line, and `:`'s prompt walks earlier commands with up and down.
14 - **MCP:** `games` (admin-listed): `list`, `console`, `power`, `env`, `config`, `config_set`, and `mods`, `mods_search`, `mods_install`, `mods_update`, `mods_remove` (each change planned first; `dryRun: false` commits), `pack`, `pack_link`, `pack_end` (the client pack, below), with the same grants.
1515 - **Agent:** `POST /api/v1/games/agent/sync` with the box token as bearer (`src/http/games_routes.ts`, `src/games/store.ts`): status, a log tail (2,000 lines a service), command results in; the compose (only when its sha differs), env files and queued commands (each handed out once) out.
1616
1717 ## What a sync carries
@@ -57,6 +57,8 @@ A refused player is told why in game, once (`tellRefused`): the server, the reas
5757 The agent reads `list uuids` each sync, and each server's whitelist.json, ops.json and banned-players.json and the proxy's `glist all` every 60 s or right after a change. A change that a list does not show yet (a server writes its file a moment late) is read again on the next syncs, up to five, so a successful `op` shows in the ops (#17617). Heads come from the player's UUID through the forge (`/games/head/<uuid>`), fetched once from mc-heads.net and kept on the forge's disk a week, so a page never calls out. Only a player the forge has seen on a server the person sees (on it now, or in its whitelist, ops or bans) has a head fetched; any other UUID gets the default head. A failed fetch is not tried again for 15 minutes, and at most four fetches are out at once. The terminal's service screen has a people tab (`p` takes "op Alice", "move Alice survival"), and the `games` tool has `people` with `op` list or a change.
5858 ## Modrinth
5959
60 **Client pack.** A mod server's page has a Players row: "Make a link for players" makes an address that gives a player's launcher (Prism, Modrinth App) one .mrpack of the mods their game needs, for the server's Minecraft and loader (`src/games/client_pack.ts`). The mods are the one list the refusal words use (a client-required mod and what it requires, never a server-only mod); every file is Modrinth's own, checked against the hashes in the pack. The loader version is the compose file's `FABRIC_LOADER_VERSION` (`QUILT_LOADER_VERSION`, `FORGE_VERSION`, `NEOFORGE_VERSION`), else the server's newest start in the log lines the forge holds ("Loading Minecraft X with Fabric Loader Y") when it is of the same Minecraft; the row says which. With neither, it says why and offers no button. A server that runs a modpack gets that pack's own link. A link works 30 days, shows once (in the cookie that carries the page's notice, one minute), is kept only as a hash, and "End all links" ends every one; it is never listed and the refusal words never carry it. Only an operator makes or ends links. The pages are `src/web/pages/games_players.ts` (the Players row) and `src/web/pages/games_client_pack.ts` (the link and its download); the terminal's door is `l` and `x` on the mods screen (`src/tui/screens/game_mods.ts`).
61
6062 A server's mods and plugins come from Modrinth, searched, previewed and pinned in a lockfile: see [Game mods](game-mods.md).
6163
6264 ## Worlds
src/core/account_purge.ts +2
@@ -52,6 +52,8 @@ export const COVERED: Readonly<Record<string, Coverage>> = {
5252 "access_link.created_by": FORMER,
5353 // Who asked a game box to run a command: the record keeps it, as the former account.
5454 "game_command.by": FORMER,
55 // The link a person made to a game box's client pack ends with the person: it is theirs to give, and the row goes.
56 "game_client_link.created_by": DELETE,
5557 // The !forge audit keeps what was said and what came of it; who said it becomes a former member.
5658 "game_chat.user_id": FORMER,
5759 "account_ceiling.set_by": FORMER,
src/crew/conversation_ask.ts +2
@@ -360,6 +360,8 @@ export const ASKED_AS: Readonly<Record<string, Form>> = {
360360 };
361361 return words[val(a, "op")] ?? `Change ${p} on ${on}`;
362362 }
363 if (a["action"] === "pack_link") return `Make a link for players to download the client pack of ${on}, good for 30 days, shown once`;
364 if (a["action"] === "pack_end") return `End every link for players to download the client pack of ${on}`;
363365 if (a["action"] === "world")
364366 return a["op"] === "restore"
365367 ? `Put back the world snapshot ${val(a, "snapshot")} on ${on}, keeping the world it has first`
src/games/client_pack.ts added +226
@@ -0,0 +1,226 @@
1 /**
2 * A client pack: the mods a player's own game needs to join a mod server, as one Modrinth modpack
3 * (.mrpack) that a launcher installs with the right loader and game version.
4 *
5 * It is made from what the forge already holds, nothing new: the server's lockfile (or, for mods
6 * named but not pinned, what Modrinth resolves them to), the mods Modrinth says a player's game
7 * requires, and everything those require (Fabric API and Balm are "optional" on their own pages,
8 * yet a mod that requires them does not start without them). Every file is Modrinth's, fetched by
9 * the player's launcher from Modrinth's own CDN and checked against the hashes here; no config,
10 * world or secret can be in it. A server that runs a modpack gets that pack's own link instead.
11 *
12 * The link is an unguessable token whose hash is kept, good for `LINK_DAYS` or until an operator
13 * revokes it; it is made by an operator of the server and listed nowhere.
14 */
15
16 import { publicOrigin } from "../core/public_origin.ts";
17 import type { Database } from "bun:sqlite";
18 import type { App } from "../app.ts";
19 import { id as newId, secret } from "../kernel/id.ts";
20 import { sha256 } from "../kernel/hash.ts";
21 import { versionById, type Result } from "./modrinth.ts";
22 import { playerMods } from "./player_events.ts";
23 import { modsOf, type Mods } from "./mods.ts";
24 import { LOG_KEEP, logsOf, type GameBox } from "./store.ts";
25
26 export const LINK_DAYS = 30;
27
28 /** Whether `url` is Modrinth's own CDN over https: the only place a pack's files and links may point. */
29 export function onModrinthCdn(url: string): boolean {
30 try {
31 const u = new URL(url);
32 return u.protocol === "https:" && u.hostname === "cdn.modrinth.com" && u.username === "" && u.password === "";
33 } catch {
34 return false;
35 }
36 }
37
38 /** One file of the pack, as its index says it. */
39 export interface PackEntry {
40 readonly path: string;
41 readonly url: string;
42 readonly sha1: string;
43 readonly sha512: string;
44 readonly size: number;
45 }
46
47 /** The compose env key that pins each loader's version, and the name a pack gives that loader. */
48 const LOADERS: Readonly<Record<string, { env: string; dep: string; name: string }>> = {
49 fabric: { env: "FABRIC_LOADER_VERSION", dep: "fabric-loader", name: "Fabric Loader" },
50 quilt: { env: "QUILT_LOADER_VERSION", dep: "quilt-loader", name: "Quilt Loader" },
51 forge: { env: "FORGE_VERSION", dep: "forge", name: "Forge" },
52 neoforge: { env: "NEOFORGE_VERSION", dep: "neoforge", name: "NeoForge" },
53 };
54
55 /** The server's own start line, which says the game and loader it runs. */
56 const STARTED = /Loading Minecraft (\S+) with (Fabric|Quilt) Loader (\S+)/;
57
58 /**
59 * The loader and the version the server runs: its compose env says so, else its newest start in
60 * the log lines the forge holds ("Loading Minecraft 1.21.6 with Fabric Loader 0.16.14"), when that
61 * start is of the Minecraft version the server is set to. `from` says which, for the owner. A
62 * sentence when neither does.
63 */
64 export function loaderOf(m: Pick<Mods, "target" | "env">, logs: readonly string[] = []): Result<{ dep: string; version: string; from: string }> {
65 const loader = m.target.loaders[0] ?? "";
66 const l = LOADERS[loader];
67 if (l === undefined || m.target.kind !== "mod") return { ok: false, error: `A client pack is for a mod server (Fabric, Quilt, Forge or NeoForge); this one is ${m.target.label}.` };
68 const said = (m.env[l.env] ?? "").trim();
69 if (/^\d[\w.+-]*$/.test(said)) return { ok: true, value: { dep: l.dep, version: said, from: `${l.env} in the compose file` } };
70 const start = [...logs].reverse().map((x) => STARTED.exec(x)).find((x) => x !== null);
71 if (start !== null && start !== undefined && start[1] === m.target.gameVersion && start[2]!.toLowerCase() === loader) return { ok: true, value: { dep: l.dep, version: start[3]!, from: `the server's last start in its log (Minecraft ${start[1]!})` } };
72 return { ok: false, error: `The pack needs the ${l.name} version the server runs: ${l.env} does not say one (it is empty or "latest"), and the server's last start in its log does not name ${l.name} for Minecraft ${m.target.gameVersion}. Set ${l.env} under Settings, or start the server once, then ask again.` };
73 }
74
75 /** The server's log lines a start is looked for in. */
76 const startLines = (db: Database, boxId: string, service: string): string[] => logsOf(db, boxId, service, LOG_KEEP).lines;
77
78 /** The pack's index: Modrinth's modpack format 1, every file for the player's game only. */
79 export function packIndex(p: { name: string; versionId: string; minecraft: string; dep: string; loaderVersion: string; files: readonly PackEntry[] }): object {
80 return {
81 formatVersion: 1,
82 game: "minecraft",
83 versionId: p.versionId,
84 name: p.name,
85 dependencies: { minecraft: p.minecraft, [p.dep]: p.loaderVersion },
86 files: p.files.map((f) => ({
87 path: f.path,
88 hashes: { sha1: f.sha1, sha512: f.sha512 },
89 env: { client: "required", server: "optional" },
90 downloads: [f.url],
91 fileSize: f.size,
92 })),
93 };
94 }
95
96 /** A zip of one stored (uncompressed) entry: all an .mrpack needs when its files are downloads. */
97 export function zipOne(name: string, content: Uint8Array): Uint8Array {
98 const n = new TextEncoder().encode(name);
99 const crc = Bun.hash.crc32(content);
100 const local = 30 + n.length;
101 const out = new Uint8Array(local + content.length + 46 + n.length + 22);
102 const v = new DataView(out.buffer);
103 // Local header.
104 v.setUint32(0, 0x04034b50, true);
105 v.setUint16(4, 20, true);
106 v.setUint16(6, 0x0800, true); // UTF-8 names
107 v.setUint32(14, crc, true);
108 v.setUint32(18, content.length, true);
109 v.setUint32(22, content.length, true);
110 v.setUint16(26, n.length, true);
111 out.set(n, 30);
112 out.set(content, local);
113 // Central directory.
114 const c = local + content.length;
115 v.setUint32(c, 0x02014b50, true);
116 v.setUint16(c + 4, 20, true);
117 v.setUint16(c + 6, 20, true);
118 v.setUint16(c + 8, 0x0800, true);
119 v.setUint32(c + 16, crc, true);
120 v.setUint32(c + 20, content.length, true);
121 v.setUint32(c + 24, content.length, true);
122 v.setUint16(c + 28, n.length, true);
123 out.set(n, c + 46);
124 // End of central directory.
125 const e = c + 46 + n.length;
126 v.setUint32(e, 0x06054b50, true);
127 v.setUint16(e + 8, 1, true);
128 v.setUint16(e + 10, 1, true);
129 v.setUint32(e + 12, 46 + n.length, true);
130 v.setUint32(e + 16, c, true);
131 return out;
132 }
133
134 /** A pack made, or the link of the modpack the server runs. */
135 export type Made = { kind: "pack"; name: string; bytes: Uint8Array } | { kind: "link"; url: string };
136
137 /** The client pack of `service` at the compose file's commit. */
138 export async function clientPack(app: App, box: GameBox, service: string): Promise<Result<Made>> {
139 const got = await modsOf(app, box, service);
140 if (!got.ok) return got;
141 const m = got.value;
142 if (m.pack !== undefined)
143 return onModrinthCdn(m.pack.url)
144 ? { ok: true, value: { kind: "link", url: m.pack.url } }
145 : { ok: false, error: `The lockfile's address for ${m.pack.title} is not on Modrinth's own download server, so the forge hands no one a link to it. Install the pack again from the Mods list.` };
146 const loader = loaderOf(m, startLines(app.db, box.id, service));
147 if (!loader.ok) return loader;
148 const need = await playerMods(app, m);
149 if (!need.ok) return need;
150 const mine = need.value.locked.filter((l) => l.path.startsWith("mods/"));
151 if (need.value.unpinned.length > 0) return { ok: false, error: `Modrinth could not pin ${need.value.unpinned.map((p) => p.title).join(", ")} to a version, so they cannot go in a pack; pin them under Mods first.` };
152 if (mine.length === 0) return { ok: false, error: "None of this server's mods needs a player's game, so there is no pack to make." };
153 const strange = mine.find((l) => !onModrinthCdn(l.url));
154 if (strange !== undefined) return { ok: false, error: `The lockfile's address for ${strange.title} is not on Modrinth's own download server, so it cannot go in a pack. Install it again from the Mods list.` };
155 const files: PackEntry[] = [];
156 for (const l of mine) {
157 const v = await versionById(app, l.versionId);
158 if (!v.ok) return v;
159 const f = v.value.files.find((x) => x.url === l.url) ?? v.value.files.find((x) => x.hashes.sha512 === l.sha512);
160 if (f?.hashes.sha1 === undefined || f.size === undefined) return { ok: false, error: `Modrinth does not give ${l.title} ${l.version} a sha1 and a size, so it cannot go in a pack.` };
161 files.push({ path: l.path, url: l.url, sha1: f.hashes.sha1, sha512: l.sha512, size: f.size });
162 }
163 files.sort((a, b) => a.path.localeCompare(b.path));
164 const name = `${service} (Minecraft ${m.target.gameVersion})`;
165 const index = packIndex({ name, versionId: m.sha.slice(0, 12), minecraft: m.target.gameVersion, dep: loader.value.dep, loaderVersion: loader.value.version, files });
166 return { ok: true, value: { kind: "pack", name: `${service}-${m.target.gameVersion}.mrpack`, bytes: zipOne("modrinth.index.json", new TextEncoder().encode(JSON.stringify(index))) } };
167 }
168
169 /** A new link for a service: its token, shown once; only the token's hash is kept. */
170 export function makeLink(db: Database, box: Pick<GameBox, "id">, service: string, by: string, now = Date.now()): string {
171 const token = secret();
172 db.query("INSERT INTO game_client_link (id, box_id, service, token_hash, created_by, created_at, expires_at) VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7)").run(
173 newId(now), box.id, service, sha256(token), by, new Date(now).toISOString(), new Date(now + LINK_DAYS * 86_400_000).toISOString(),
174 );
175 return token;
176 }
177
178 /** The service a token opens now: not expired, not revoked, and of a box that has not ended. */
179 export function linkOf(db: Database, token: string, now = Date.now()): { boxId: string; service: string } | undefined {
180 const r = db
181 .query<{ box_id: string; service: string }, [string, string]>(
182 `SELECT l.box_id, l.service FROM game_client_link l JOIN game_box b ON b.id = l.box_id
183 WHERE l.token_hash = ?1 AND l.revoked_at = '' AND l.expires_at > ?2
184 AND NOT EXISTS (SELECT 1 FROM pinned_forge p WHERE p.state = 'retired' AND (p.id = b.pinned_id OR (b.pinned_id = '' AND p.name = b.name)))`,
185 )
186 .get(sha256(token), new Date(now).toISOString());
187 return r === null ? undefined : { boxId: r.box_id, service: r.service };
188 }
189
190 /** Every open link of a service, ended. How many there were. */
191 export function revokeLinks(db: Database, box: Pick<GameBox, "id">, service: string, now = Date.now()): number {
192 return db.query("UPDATE game_client_link SET revoked_at = ?3 WHERE box_id = ?1 AND service = ?2 AND revoked_at = ''").run(box.id, service, new Date(now).toISOString()).changes;
193 }
194
195 /** How many links of a service are open now. */
196 export function openLinks(db: Database, box: Pick<GameBox, "id">, service: string, now = Date.now()): number {
197 return db
198 .query<{ n: number }, [string, string, string]>("SELECT count(*) AS n FROM game_client_link WHERE box_id = ?1 AND service = ?2 AND revoked_at = '' AND expires_at > ?3")
199 .get(box.id, service, new Date(now).toISOString())!.n;
200 }
201
202 /** What the service's row says: whether a pack can be made now, and why in words. */
203 export interface PackRow {
204 readonly can: boolean;
205 readonly words: string;
206 readonly open: number;
207 }
208
209 /** The row's facts, read from what the forge holds (no call to Modrinth or the box). */
210 export async function packRow(app: App, box: GameBox, service: string): Promise<PackRow | undefined> {
211 const got = await modsOf(app, box, service);
212 if (!got.ok || got.value.target.kind !== "mod") return undefined;
213 const open = openLinks(app.db, box, service);
214 if (got.value.pack !== undefined) return { can: true, open, words: `The server runs ${got.value.pack.title} ${got.value.pack.version}: players get that modpack's own link.` };
215 const loader = loaderOf(got.value, startLines(app.db, box.id, service));
216 return loader.ok
217 ? { can: true, open, words: `One .mrpack of the mods a player's game needs, for Minecraft ${got.value.target.gameVersion} with ${loader.value.dep === "fabric-loader" ? "Fabric Loader" : loader.value.dep} ${loader.value.version} (from ${loader.value.from}).` }
218 : { can: false, open, words: loader.error };
219 }
220
221 /** A new link for the pack, after checking that the pack can be made: its address, shown once. */
222 export async function makePackLink(app: App, box: GameBox, service: string, by: string): Promise<Result<string>> {
223 const made = await clientPack(app, box, service);
224 if (!made.ok) return made;
225 return { ok: true, value: `${publicOrigin(app.config.url, `http://localhost:${String(app.config.port)}`)}/games/@pack/${makeLink(app.db, box, service, by)}/${service}.mrpack` };
226 }
src/games/modrinth.ts +3 −2
@@ -282,8 +282,9 @@ export async function search(app: App, t: Target, query: string): Promise<Result
282282
283283 // ---- versions and the lock ----
284284
285 interface VersionFile {
285 export interface VersionFile {
286286 url: string;
287 size?: number;
287288 filename: string;
288289 primary: boolean;
289290 hashes: { sha512?: string; sha1?: string };
@@ -372,7 +373,7 @@ export function playerSide(all: readonly Locked[], projects: readonly Project[])
372373
373374 const project = (app: App, idOrSlug: string): Promise<Result<Project>> =>
374375 api<Project>(app, `/v2/project/${encodeURIComponent(idOrSlug)}`, 30 * MINUTE);
375 const versionById = (app: App, id: string): Promise<Result<Version>> =>
376 export const versionById = (app: App, id: string): Promise<Result<Version>> =>
376377 api<Version>(app, `/v2/version/${encodeURIComponent(id)}`, 24 * 60 * MINUTE);
377378
378379 /** The newest version of a project for this server: a release when there is one, else the newest. */
src/http/games_routes.ts +5
@@ -22,6 +22,7 @@ import { BODY_CAPS } from "../kernel/body_caps.ts";
2222 import {
2323 gameBoxPage, gameCommandSubmit, gameCrashShare, gameEnvSubmit, gameGrantSubmit, gameLendSubmit, gameServersSubmit, gameJarDownload, gameJarSubmit, gameModInstall, gameModPack, gameModRemove, gameModUpdate, gamePeopleSubmit, gameHead, gameWorldSubmit, gamePowerSubmit, gameSleepSubmit, gameServicePage, gameSettingsSubmit, gameServiceStream, gameShellStream, gameShellSubmit, gamesPage,
2424 } from "../web/pages/games.ts";
25 import { gamePackDownload, gamePackLink, gamePackRevoke } from "../web/pages/games_client_pack.ts";
2526 import { gameConfigCommit, gameConfigPage, gameConfigPreview } from "../web/pages/games_config.ts";
2627 import type { Ctx, Handler } from "./context.ts";
2728 import { InvalidJson } from "./json_body.ts";
@@ -126,6 +127,8 @@ export function gamesApiRoutes(router: Router<Handler>): void {
126127 export function gamesRoutes(router: Router<Handler>): void {
127128 router.add("GET", "/games", gamesPage);
128129 router.add("GET", "/games/jar/:id/:name", gameJarDownload);
130 // "@pack" is no box name, so a box named "pack" keeps its /games/pack/<service>/stream.
131 router.add("GET", "/games/@pack/:token/:file", gamePackDownload);
129132 router.add("GET", "/games/head/:uuid", gameHead);
130133 router.add("GET", "/games/:box", gameBoxPage);
131134 router.add("POST", "/games/:box/grant", gameGrantSubmit);
@@ -150,6 +153,8 @@ export function gamesRoutes(router: Router<Handler>): void {
150153 router.add("POST", "/games/:box/:service/people", gamePeopleSubmit);
151154 router.add("POST", "/games/:box/:service/world", gameWorldSubmit);
152155 router.add("POST", "/games/:box/:service/jar", gameJarSubmit);
156 router.add("POST", "/games/:box/:service/pack/link", gamePackLink);
157 router.add("POST", "/games/:box/:service/pack/revoke", gamePackRevoke);
153158 router.add("POST", "/games/:box/:service/settings", gameSettingsSubmit);
154159 router.add("POST", "/games/:box/:service/crash/share", gameCrashShare);
155160 }
src/http/lazy_lists.ts +3
@@ -624,6 +624,7 @@ export const OPERATIONS_ROUTES = [
624624 ["POST", "/infra/:name/:act"],
625625 ["GET", "/games"],
626626 ["GET", "/games/jar/:id/:name"],
627 ["GET", "/games/@pack/:token/:file"],
627628 ["GET", "/games/head/:uuid"],
628629 ["GET", "/games/:box"],
629630 ["POST", "/games/:box/grant"],
@@ -647,6 +648,8 @@ export const OPERATIONS_ROUTES = [
647648 ["POST", "/games/:box/:service/people"],
648649 ["POST", "/games/:box/:service/world"],
649650 ["POST", "/games/:box/:service/jar"],
651 ["POST", "/games/:box/:service/pack/link"],
652 ["POST", "/games/:box/:service/pack/revoke"],
650653 ["POST", "/games/:box/:service/settings"],
651654 ["POST", "/games/:box/:service/crash/share"],
652655 ["GET", "/resilience"],
src/http/mcp/tools/games.ts +14 −4

Diff not shown — a line 2,749 characters wide (limit 2,000). +14 −4

View file
src/tui/screens/game_mods.ts +21 −2
@@ -4,11 +4,12 @@
44 * where each result says whether it runs here. `/` searches, `a` previews an install (what it
55 * adds and what that requires) by a result's number or a slug, `u` previews updating everything,
66 * `d` previews a removal, `p` previews a modpack (every file locked); `y` commits the preview
7 * shown and `n` drops it.
7 * shown and `n` drops it; `l` makes a link to the client pack for players and `x` ends every link.
88 */
99
1010 import { search, type Hit, type Result } from "../../games/modrinth.ts";
1111 import { commitPlan, modsOf, packUpdateOf, planInstall, planPack, planPackUpdate, planRemove, planUpdate, updatesOf, type Mods, type Plan } from "../../games/mods.ts";
12 import { makePackLink, packRow, revokeLinks, type PackRow } from "../../games/client_pack.ts";
1213 import { mayDo, roleOn, type GameBox } from "../../games/store.ts";
1314 import type { Ctx, Screen } from "../app/app.ts";
1415 import { binding } from "../app/keys.ts";
@@ -25,6 +26,9 @@ export function gameModsScreen(f: Session, ctx: Ctx, box: GameBox, service: stri
2526 let hits: Hit[] = [];
2627 // The preview on screen, which `y` commits.
2728 let pending: Plan | undefined;
29 // The pack row, and a link just made (shown here once, then gone with the next key).
30 let players: PackRow | undefined;
31 let link = "";
2832 const operator = () => mayDo(roleOn(f.app.db, f.user, box.id, service), "operator");
2933 const say = (words: string): void => {
3034 note = words;
@@ -32,6 +36,7 @@ export function gameModsScreen(f: Session, ctx: Ctx, box: GameBox, service: stri
3236 };
3337 const load = async (): Promise<void> => {
3438 mods = await modsOf(f.app, box, service);
39 players = await packRow(f.app, box, service);
3540 ctx.invalidate();
3641 const u = mods.ok ? await updatesOf(f.app, mods.value) : undefined;
3742 const pu = mods.ok ? await packUpdateOf(f.app, mods.value) : undefined;
@@ -58,6 +63,8 @@ export function gameModsScreen(f: Session, ctx: Ctx, box: GameBox, service: stri
5863 ...m.loose.map((e) => `unpinned: ${e}`),
5964 ...m.urls.map((u) => `unpinned jar: ${u}`),
6065 ...(m.lock.length + m.loose.length + m.urls.length === 0 ? ["Nothing is installed."] : []),
66 ...(players === undefined ? [] : [`players: ${players.open > 0 ? `${String(players.open)} link(s) open; x ends all. ` : ""}${players.can ? "l makes a link. " : ""}${players.words}`]),
67 ...(link === "" ? [] : [`link (30 days, shown once): ${link}`]),
6168 ...hits.map((h, i) => `${String(i + 1)}. ${h.title} (${h.slug}) ${h.fits ? `runs on ${m.target.gameVersion}` : h.why}`),
6269 `Uploading a jar is on the web only: /games/${box.name}/${service}.`,
6370 ];
@@ -84,6 +91,8 @@ export function gameModsScreen(f: Session, ctx: Ctx, box: GameBox, service: stri
8491 binding(["u"], "update all"),
8592 binding(["d"], "remove"),
8693 binding(["p"], "modpack"),
94 binding(["l"], "a link to the client pack for players"),
95 binding(["x"], "end all links for players"),
8796 binding(["y"], "commit the preview"),
8897 binding(["n"], "drop the preview"),
8998 ],
@@ -121,7 +130,17 @@ export function gameModsScreen(f: Session, ctx: Ctx, box: GameBox, service: stri
121130 });
122131 else if (e.key === "d") ask("Remove", "The slug of what to remove", (raw) => preview((m) => planRemove(m, service, raw.trim())));
123132 else if (e.key === "p") ask("Modpack", "A Modrinth modpack's slug", (raw) => preview((m) => planPack(f.app, m, service, raw.trim())));
124 else if (e.key === "u") {
133 else if (e.key === "l" || e.key === "x") {
134 link = "";
135 if (!operator()) say(`You are not an operator of ${service}.`);
136 else if (e.key === "x") say(`${String(revokeLinks(f.app.db, box, service))} link(s) ended.`);
137 else
138 void makePackLink(f.app, box, service, f.user!.id).then((r) => {
139 link = r.ok ? r.value : "";
140 say(r.ok ? "A link for players: shown below, once." : r.error);
141 });
142 void load();
143 } else if (e.key === "u") {
125144 if (!operator()) say(`You are not an operator of ${service}.`);
126145 else void preview((m) => (m.target.pack ? planPackUpdate(f.app, m, service) : planUpdate(f.app, m, service, "all"))).then(say);
127146 } else if ((e.key === "y" || e.key === "n") && pending !== undefined) {
src/web/pages/games.ts +5 −1
@@ -10,7 +10,9 @@
1010 import { addPluginUrl, commitServiceEnv, composeServices, readCompose, serviceEnv } from "../../games/compose.ts";
1111 import { commitPlan, modsOf, packUpdateOf, planInstall, planPack, planPackUpdate, planRemove, planUpdate, updatesOf, type Mods, type Plan } from "../../games/mods.ts";
1212 import { search, searchPacks, type Hit, type Result } from "../../games/modrinth.ts";
13 import { packRow } from "../../games/client_pack.ts";
1314 import { packCheckLines } from "../../games/pack_check.ts";
15 import { playersBlock } from "./games_players.ts";
1416 import { queueShell } from "../../games/shell.ts";
1517 import { getUserById, getUserByName } from "../../core/users.ts";
1618 import { blockChanges, serviceBlocks, shellBlocks, shellSays } from "../../terminal/blocks.ts";
@@ -535,6 +537,7 @@ export async function gameServicePage(ctx: Ctx): Promise<Response> {
535537 const after = answerAfter(ctx.app.db, box.id, service, b);
536538 return after === null ? [] : [{ ...b, after }];
537539 });
540 const players = mods?.ok && mods.value.target.kind === "mod" ? await packRow(ctx.app, box, service) : undefined;
538541 const findings = findingsOf(ctx.app.db, box.id, service);
539542 // Settings: each as the compose file says; a "Preview" (s.<key>=value in the query) planned on it.
540543 const settings = compose === undefined ? [] : settingsOf(compose.text, service, env);
@@ -618,7 +621,8 @@ export async function gameServicePage(ctx: Ctx): Promise<Response> {
618621 packing,
619622 checked: packCheckLines(ctx.app, box.id).find((l) => l.startsWith(`${service}: `))?.slice(service.length + 2),
620623 })
621 : null}`)}`,
624 : null}
625 ${players === undefined ? null : playersBlock(base, players, act)}`)}`,
622626 }));
623627 }
624628
src/web/pages/games_client_pack.ts added +53
@@ -0,0 +1,53 @@
1 /**
2 * The client pack's three routes (`games/client_pack.ts`): an operator makes a link or ends every
3 * link, and anyone holding a link downloads the pack. The link is shown once, in the flash.
4 */
5 import { LINK_DAYS, clientPack, linkOf, makePackLink, revokeLinks } from "../../games/client_pack.ts";
6 import { boxById } from "../../games/store.ts";
7 import type { Ctx } from "../../http/context.ts";
8 import { readForm } from "../form.ts";
9 import { flashTo } from "../layout.ts";
10 import { boxOf } from "./games.ts";
11
12 // POST /games/:box/:service/pack/link: a link for the service's pack, 30 days, shown once.
13 export async function gamePackLink(ctx: Ctx): Promise<Response> {
14 const service = ctx.params.service ?? "";
15 const got = boxOf(ctx, "operator", service);
16 if (got instanceof Response) return got;
17 const form = await readForm(ctx, "rw");
18 if (form instanceof Response) return form;
19 const back = `/games/${got.box.name}/${service}`;
20 // A pack that cannot be made gets no link: say why now, not when a player opens it.
21 const url = await makePackLink(ctx.app, got.box, service, ctx.auth.user!.id);
22 if (!url.ok) return flashTo(ctx, back, { tone: "danger", message: url.error });
23 // The address rides the flash cookie (HttpOnly, a minute, shown once): nothing keeps it.
24 return flashTo(ctx, back, { message: `Players open this in a launcher (Prism, Modrinth App). It works for ${LINK_DAYS} days; this is the only time it is shown.`, code: url.value });
25 }
26
27 // POST /games/:box/:service/pack/revoke: every link of the service ends.
28 export async function gamePackRevoke(ctx: Ctx): Promise<Response> {
29 const service = ctx.params.service ?? "";
30 const got = boxOf(ctx, "operator", service);
31 if (got instanceof Response) return got;
32 const form = await readForm(ctx, "rw");
33 if (form instanceof Response) return form;
34 const n = revokeLinks(ctx.app.db, got.box, service);
35 return flashTo(ctx, `/games/${got.box.name}/${service}`, { message: n === 0 ? "No link was open." : `${n} link${n === 1 ? "" : "s"} ended.` });
36 }
37
38 // GET /games/@pack/:token/:file: the pack, for whoever holds the link.
39 export async function gamePackDownload(ctx: Ctx): Promise<Response> {
40 const link = linkOf(ctx.app.db, ctx.params.token ?? "");
41 const box = link === undefined ? undefined : boxById(ctx.app.db, link.boxId);
42 if (link === undefined || box === undefined) return new Response("not found", { status: 404 });
43 const made = await clientPack(ctx.app, box, link.service);
44 if (!made.ok) return new Response(made.error, { status: 409, headers: { "cache-control": "private, no-store" } });
45 if (made.value.kind === "link") return new Response(null, { status: 302, headers: { location: made.value.url, "cache-control": "private, no-store" } });
46 return new Response(made.value.bytes, {
47 headers: {
48 "content-type": "application/x-modrinth-modpack+zip",
49 "content-disposition": `attachment; filename="${made.value.name}"`,
50 "cache-control": "private, no-store",
51 },
52 });
53 }
src/web/pages/games_players.ts added +26
@@ -0,0 +1,26 @@
1 /**
2 * The service page's row for the client pack (`games/client_pack.ts`): what it is and where its
3 * loader version came from, how many links are open, and an operator's two buttons.
4 */
5 import { LINK_DAYS, type PackRow } from "../../games/client_pack.ts";
6 import { html, type Html } from "../html.ts";
7 import { btn, row, rowList } from "../ui.ts";
8
9 export function playersBlock(base: string, r: PackRow, act: boolean): Html {
10 return html`<section class="settings-block" id="players">
11 <h2>Players</h2>
12 ${rowList([
13 row({
14 title: "Client pack",
15 meta: html`${r.words}${r.can ? ` Links work for ${String(LINK_DAYS)} days.` : ""}${r.open > 0 ? ` ${String(r.open)} open.` : ""}`,
16 ...(act && (r.can || r.open > 0)
17 ? {
18 after: html`${r.can ? html`<form method="post" action="${base}/pack/link">${btn("Make a link for players", { size: "sm", variant: "secondary" })}</form>` : null}${r.open > 0
19 ? html`<form method="post" action="${base}/pack/revoke">${btn("End all links", { size: "sm", variant: "secondary" })}</form>`
20 : null}`,
21 }
22 : {}),
23 }),
24 ])}
25 </section>`;
26 }
test/budgets/unfixtured/games-pack-token-file.json added +4
@@ -0,0 +1,4 @@
1 {
2 "pattern": "/games/@pack/:token/:file",
3 "why": "a client pack for whoever holds a link, a download, not a page; no fixture makes a link"
4 }
test/game-client-pack.test.ts added +354
@@ -0,0 +1,354 @@
1 /**
2 * The client pack (`games/client_pack.ts`): the mods a player's game needs to join a mod server, as
3 * one .mrpack, from the server's lockfile and a stand-in for Modrinth. What goes in it, what a
4 * launcher reads (a zip that stock tools open, hashes equal to the lock's), when it is refused, and
5 * the link: unguessable, 30 days, revocable, made by an operator, shown once.
6 */
7 import { afterAll, beforeAll, describe, expect, test } from "bun:test";
8 import { mkdtemp, rm } from "node:fs/promises";
9 import { tmpdir } from "node:os";
10 import { join } from "node:path";
11 import { commitToBranch, createRepo } from "../src/actions/repos.ts";
12 import { createApp, type App } from "../src/app.ts";
13 import { getRepo } from "../src/core/repos.ts";
14 import { createToken } from "../src/core/tokens.ts";
15 import { createUser, getUserByName, type User } from "../src/core/users.ts";
16 import { keptPath } from "../src/http/access_log.ts";
17 import { LINK_DAYS, clientPack, linkOf, loaderOf, makeLink, openLinks, packRow, revokeLinks, zipOne } from "../src/games/client_pack.ts";
18 import { createSession } from "../src/core/sessions.ts";
19 import type { Locked } from "../src/games/modrinth.ts";
20 import { boxNamed, createGameBox, grant, type GameBox } from "../src/games/store.ts";
21 import { forgeHttp, type ForgeHttp } from "../src/http/server.ts";
22 import { createForgeApp } from "../src/tui/forge.ts";
23 import { gameModsScreen } from "../src/tui/screens/game_mods.ts";
24 import { headlessTerminal } from "../src/tui/term/terminal.ts";
25 import { quietLogs } from "./helpers/globals.ts";
26 import { settleUntil } from "./helpers/tui.ts";
27
28 quietLogs();
29
30 const ORIGIN = "http://forge.test";
31 const env = (loader: string) => ` TYPE: FABRIC
32 VERSION: "1.21.6"${loader}`;
33 const COMPOSE = (survivalLoader: string) => `services:
34 survival:
35 image: itzg/minecraft-server
36 environment:
37 ${env(survivalLoader)}
38 hub:
39 image: itzg/minecraft-server
40 environment:
41 TYPE: PAPER
42 VERSION: "1.21.6"
43 cozy:
44 image: itzg/minecraft-server
45 environment:
46 TYPE: MODRINTH
47 MODRINTH_MODPACK: cozy
48 MODRINTH_LOADER: fabric
49 VERSION: "1.21.6"
50 `;
51
52 const hex = (c: string, n: number) => c.repeat(n);
53 const lock = (project: string, slug: string, title: string, requires: string[], c: string): Locked => ({
54 project,
55 slug,
56 title,
57 version: "1.0",
58 versionId: `v-${project}`,
59 path: `mods/${slug}.jar`,
60 url: `https://cdn.modrinth.com/data/${project}/versions/v-${project}/${slug}.jar`,
61 sha512: hex(c, 128),
62 top: true,
63 requires,
64 incompatible: [],
65 });
66 // Waystones needs the player's game; Balm and Fabric API are "optional" on their pages yet required by it.
67 const LOCK: Locked[] = [
68 lock("WAYS", "waystones", "Waystones", ["BALM", "FAPI", "SRVO"], "a"),
69 lock("BALM", "balm", "Balm", ["FAPI"], "b"),
70 lock("FAPI", "fabric-api", "Fabric API", [], "c"),
71 lock("FERR", "ferrite-core", "FerriteCore", [], "d"),
72 lock("SRVO", "server-lib", "ServerLib", [], "g"),
73 lock("PROX", "fabricproxy-lite", "FabricProxy-Lite", [], "e"),
74 ];
75 const SIDE: Record<string, string> = { WAYS: "required", BALM: "optional", FAPI: "optional", FERR: "unsupported", PROX: "unsupported", SRVO: "unsupported" };
76
77 const modrinth = async (url: string | URL | Request): Promise<Response> => {
78 const u = new URL(typeof url === "string" ? url : url instanceof URL ? url.href : url.url);
79 if (u.pathname === "/v2/projects") {
80 const ids = JSON.parse(u.searchParams.get("ids") ?? "[]") as string[];
81 return Response.json(ids.map((id) => ({ id, slug: id.toLowerCase(), title: id, client_side: SIDE[id] ?? "optional", server_side: "required" })));
82 }
83 const v = /^\/v2\/version\/v-(\w+)$/.exec(u.pathname);
84 if (v !== null) {
85 const l = LOCK.find((x) => x.project === v[1])!;
86 return Response.json({
87 id: l.versionId, project_id: l.project, version_number: "1.0", version_type: "release", date_published: "2025-06-18T00:00:00Z",
88 game_versions: ["1.21.6"], loaders: ["fabric"], dependencies: [],
89 files: [{ url: l.url, filename: `${l.slug}.jar`, primary: true, size: 1000 + l.slug.length, hashes: { sha1: hex(l.sha512[0]!, 40), sha512: l.sha512 } }],
90 });
91 }
92 return new Response("{}", { status: 404 });
93 };
94
95 describe("the client pack", () => {
96 let dir = "";
97 let app: App;
98 let http: ForgeHttp;
99 let alice: User;
100 let box: GameBox;
101 let bobTok = "";
102 const commit = async (path: string, content: string) => {
103 const repo = getRepo(app.db, "alice", "mc-network")!;
104 const done = await commitToBranch(app, alice, repo, { message: "x", files: [{ path, content }] });
105 if (!done.ok) throw new Error(JSON.stringify(done.error));
106 };
107 const as = (token: string, path: string, form?: Record<string, string>) =>
108 http.handle(
109 new Request(
110 ORIGIN + path,
111 form === undefined
112 ? { headers: { authorization: `Bearer ${token}` } }
113 : { method: "POST", headers: { authorization: `Bearer ${token}`, origin: ORIGIN, "content-type": "application/x-www-form-urlencoded" }, body: new URLSearchParams(form) },
114 ),
115 );
116
117 beforeAll(async () => {
118 dir = await mkdtemp(join(tmpdir(), "forge-client-pack-"));
119 app = createApp({ dataDir: dir, port: 0, modrinthFetch: modrinth });
120 http = forgeHttp(app);
121 for (const [username, adminIfFirst] of [["alice", true], ["bob", false]] as const) {
122 const made = await createUser(app.db, { origin: "seed", trusted: true, username, email: `${username}@f.test`, password: "a-good-passphrase", adminIfFirst });
123 if (!made.ok) throw new Error(made.error);
124 }
125 alice = getUserByName(app.db, "alice")!;
126 bobTok = createToken(app.db, getUserByName(app.db, "bob")!.id, "rw", "rw").token;
127 const repo = await createRepo(app, alice, { name: "mc-network", visibility: "private" });
128 if (!repo.ok) throw new Error(String(repo.error));
129 const seeded = await commitToBranch(app, alice, repo.value, {
130 message: "network",
131 files: [
132 { path: "net/docker-compose.yml", content: COMPOSE("\n FABRIC_LOADER_VERSION: \"0.16.14\"") },
133 { path: "net/modrinth/survival.lock.json", content: JSON.stringify({ projects: LOCK }) },
134 ],
135 });
136 if (!seeded.ok) throw new Error(JSON.stringify(seeded.error));
137 createGameBox(app.db, { name: "net", repo: "alice/mc-network", path: "net/docker-compose.yml" });
138 box = boxNamed(app.db, "net")!;
139 }, 30_000);
140
141 afterAll(async () => {
142 app.close();
143 await rm(dir, { recursive: true, force: true });
144 });
145
146 const made = async () => {
147 const r = await clientPack(app, box, "survival");
148 if (!r.ok) throw new Error(r.error);
149 if (r.value.kind !== "pack") throw new Error("a link");
150 return r.value;
151 };
152 const indexOf = (bytes: Uint8Array) => JSON.parse(Buffer.from(bytes.subarray(30 + "modrinth.index.json".length, bytes.length - 22 - 46 - "modrinth.index.json".length)).toString()) as {
153 dependencies: Record<string, string>;
154 files: { path: string; hashes: { sha1: string; sha512: string }; env: { client: string }; downloads: string[]; fileSize: number }[];
155 versionId: string;
156 };
157
158 test("a player's pack has what a client requires and what those require, and no server-only mod", async () => {
159 const p = await made();
160 expect(p.name).toBe("survival-1.21.6.mrpack");
161 const ix = indexOf(p.bytes);
162 expect(ix.files.map((f) => f.path)).toEqual(["mods/balm.jar", "mods/fabric-api.jar", "mods/waystones.jar"]);
163 expect(ix.dependencies).toEqual({ minecraft: "1.21.6", "fabric-loader": "0.16.14" });
164 for (const f of ix.files) {
165 const l = LOCK.find((x) => `mods/${x.slug}.jar` === f.path)!;
166 expect(f.hashes.sha512).toBe(l.sha512);
167 expect(f.downloads).toEqual([l.url]);
168 expect(f.env.client).toBe("required");
169 expect(f.fileSize).toBeGreaterThan(1000);
170 }
171 expect(ix.versionId).toMatch(/^[0-9a-f]{12}$/);
172 });
173
174 test("the zip is well formed: one entry, its CRC the one Bun computes, its size and name as the headers say", async () => {
175 const b = (await made()).bytes;
176 const v = new DataView(b.buffer, b.byteOffset, b.byteLength);
177 const name = "modrinth.index.json";
178 const size = v.getUint32(18, true);
179 expect(v.getUint32(0, true)).toBe(0x04034b50);
180 expect(v.getUint16(26, true)).toBe(name.length);
181 expect(Buffer.from(b.subarray(30, 30 + name.length)).toString()).toBe(name);
182 const body = b.subarray(30 + name.length, 30 + name.length + size);
183 expect(v.getUint32(14, true)).toBe(Bun.hash.crc32(body));
184 const c = 30 + name.length + size;
185 expect(v.getUint32(c, true)).toBe(0x02014b50);
186 expect(v.getUint32(c + 16, true)).toBe(Bun.hash.crc32(body));
187 const e = b.length - 22;
188 expect(v.getUint32(e, true)).toBe(0x06054b50);
189 expect(v.getUint16(e + 10, true)).toBe(1);
190 expect(v.getUint32(e + 16, true)).toBe(c);
191 expect(JSON.parse(Buffer.from(body).toString()).game).toBe("minecraft");
192 // Headers 30 + 46 + 22, the name twice, the content once.
193 expect(zipOne("a.txt", new TextEncoder().encode("hi")).length).toBe(30 + 46 + 22 + 5 * 2 + 2);
194 if (Bun.which("unzip") !== null) {
195 const file = join(dir, "p.mrpack");
196 await Bun.write(file, b);
197 expect(Bun.spawnSync(["unzip", "-t", file]).exitCode).toBe(0);
198 }
199 });
200
201 test("no loader version in the compose is refused with a sentence; so is a server with no client mod and a proxy-less Paper one", async () => {
202 await commit("net/docker-compose.yml", COMPOSE(""));
203 const none = await clientPack(app, box, "survival");
204 expect(none).toEqual({ ok: false, error: expect.stringContaining("FABRIC_LOADER_VERSION") });
205 await commit("net/docker-compose.yml", COMPOSE("\n FABRIC_LOADER_VERSION: LATEST"));
206 expect((await clientPack(app, box, "survival")).ok).toBe(false);
207 const paper = await clientPack(app, box, "hub");
208 expect(paper).toEqual({ ok: false, error: expect.stringContaining("mod server") });
209 await commit("net/docker-compose.yml", COMPOSE("\n FABRIC_LOADER_VERSION: \"0.16.14\""));
210 });
211
212 test("the loader version: the compose's word first, else the server's newest start when it is of the same Minecraft; else a sentence", () => {
213 const target = { loaders: ["fabric"], kind: "mod", gameVersion: "1.21.6", label: "Fabric 1.21.6" } as unknown as Parameters<typeof loaderOf>[0]["target"];
214 const start = (mc: string, v: string) => `[00:09:00] [main/INFO]: Loading Minecraft ${mc} with Fabric Loader ${v}`;
215 expect(loaderOf({ target, env: { FABRIC_LOADER_VERSION: "0.16.9" } }, [start("1.21.6", "0.16.14")])).toEqual({ ok: true, value: { dep: "fabric-loader", version: "0.16.9", from: "FABRIC_LOADER_VERSION in the compose file" } });
216 const log = loaderOf({ target, env: {} }, [start("1.21.5", "0.16.0"), start("1.21.6", "0.16.14")]);
217 expect(log.ok && log.value.version).toBe("0.16.14");
218 expect(log.ok && log.value.from).toContain("last start in its log");
219 // The newest start is of another Minecraft: the older one does not count.
220 expect(loaderOf({ target, env: {} }, [start("1.21.6", "0.16.14"), start("1.21.5", "0.16.0")]).ok).toBe(false);
221 expect(loaderOf({ target, env: { FABRIC_LOADER_VERSION: "latest" } }, []).ok).toBe(false);
222 expect(loaderOf({ target, env: {} }, ["[x]: Loading Minecraft 1.21.6 with Quilt Loader 0.26.0"]).ok).toBe(false);
223 });
224
225 test("the page row: a button for an operator with the source of the version, End all links once one is open, nothing for a viewer", async () => {
226 await commit("net/docker-compose.yml", COMPOSE("\n FABRIC_LOADER_VERSION: \"0.16.14\""));
227 const bob = getUserByName(app.db, "bob")!;
228 const cookie = (u: User) => ({ cookie: `forge_session=${createSession(app.db, u.id).token}` });
229 grant(app.db, box.id, bob.id, "operator", "survival");
230 const open = await (await http.handle(new Request(`${ORIGIN}/games/net/survival`, { headers: cookie(bob) }))).text();
231 expect(open).toContain("Make a link for players");
232 expect(open).toContain("FABRIC_LOADER_VERSION in the compose file");
233 const row = await packRow(app, box, "survival");
234 expect(row?.can).toBe(true);
235 makeLink(app.db, box, "survival", bob.id);
236 expect(await (await http.handle(new Request(`${ORIGIN}/games/net/survival`, { headers: cookie(bob) }))).text()).toContain("End all links");
237 grant(app.db, box.id, bob.id, "viewer", "survival");
238 expect(await (await http.handle(new Request(`${ORIGIN}/games/net/survival`, { headers: cookie(bob) }))).text()).not.toContain("Make a link for players");
239 grant(app.db, box.id, bob.id, "operator", "survival");
240 // With no word in the compose and no start in the log, the row says why instead of offering a button.
241 await commit("net/docker-compose.yml", COMPOSE(""));
242 const none = await (await http.handle(new Request(`${ORIGIN}/games/net/survival`, { headers: cookie(bob) }))).text();
243 expect(none).not.toContain("Make a link for players");
244 // Links already made can be ended whether or not a new one can be made, and the row counts them.
245 expect(none).toContain("End all links");
246 expect(none).toMatch(/\d+ open/);
247 expect(none).toContain("FABRIC_LOADER_VERSION does not say one");
248 app.db.query("INSERT INTO game_log (box_id, service, line, at) VALUES (?1, 'survival', ?2, '2026-12-03T00:00:00Z')").run(box.id, "Loading Minecraft 1.21.6 with Fabric Loader 0.16.14");
249 expect(await (await http.handle(new Request(`${ORIGIN}/games/net/survival`, { headers: cookie(bob) }))).text()).toContain("last start in its log");
250 await commit("net/docker-compose.yml", COMPOSE("\n FABRIC_LOADER_VERSION: \"0.16.14\""));
251 });
252
253 test("nothing keeps the address: it rides a one-minute cookie and the log keeps no token", async () => {
254 const r = await as(bobTok, "/games/net/survival/pack/link", {});
255 const cookie = decodeURIComponent(r.headers.get("set-cookie") ?? "");
256 const url = /\/games\/@pack\/[\w-]+\/survival\.mrpack/.exec(cookie)?.[0];
257 expect(url).toBeDefined();
258 const token = url!.split("/")[3]!;
259 expect(r.headers.get("set-cookie")).toMatch(/HttpOnly/i);
260 for (const t of ["game_client_link", "game_command", "game_log"])
261 expect(JSON.stringify(app.db.query(`SELECT * FROM ${t}`).all())).not.toContain(token);
262 expect(keptPath(`/games/@pack/${token}/survival.mrpack`)).toBe("/games/@pack/:redacted/survival.mrpack");
263 });
264
265 test("an operator makes a link; the link downloads the pack, and the secret is not kept", async () => {
266 grant(app.db, box.id, getUserByName(app.db, "bob")!.id, "operator", "survival");
267 const before = openLinks(app.db, box, "survival");
268 const r = await as(bobTok, "/games/net/survival/pack/link", {});
269 expect(r.status).toBe(303);
270 expect(openLinks(app.db, box, "survival")).toBe(before + 1);
271 const stored = app.db.query<{ token_hash: string }, []>("SELECT token_hash FROM game_client_link ORDER BY created_at DESC, rowid DESC").get()!.token_hash;
272 expect(stored).toMatch(/^[0-9a-f]{64}$/);
273 const token = makeLink(app.db, box, "survival", "t");
274 const ok = await http.handle(new Request(`${ORIGIN}/games/@pack/${token}/survival.mrpack`));
275 expect(ok.status).toBe(200);
276 expect(ok.headers.get("content-type")).toBe("application/x-modrinth-modpack+zip");
277 expect(new Uint8Array(await ok.arrayBuffer()).length).toBeGreaterThan(200);
278 expect((await http.handle(new Request(`${ORIGIN}/games/@pack/${token}x/survival.mrpack`))).status).toBe(404);
279 });
280
281 test("a link of 30 days ends at its time and when revoked; a viewer, and a server not theirs, cannot make one", async () => {
282 const token = makeLink(app.db, box, "survival", "t", Date.now());
283 expect(linkOf(app.db, token)).toEqual({ boxId: box.id, service: "survival" });
284 expect(linkOf(app.db, token, Date.now() + (LINK_DAYS * 86_400_000 + 1000))).toBeUndefined();
285 expect(revokeLinks(app.db, box, "survival")).toBeGreaterThan(0);
286 expect(linkOf(app.db, token)).toBeUndefined();
287 expect((await http.handle(new Request(`${ORIGIN}/games/@pack/${token}/survival.mrpack`))).status).toBe(404);
288 // Bob is operator of survival only.
289 expect((await as(bobTok, "/games/net/hub/pack/link", {})).status).toBe(404);
290 expect((await as(bobTok, "/games/net/hub/pack/revoke", {})).status).toBe(404);
291 });
292
293 test("a server that runs a modpack hands out that pack's own link", async () => {
294 await commit(
295 "net/modrinth/cozy.lock.json",
296 JSON.stringify({ projects: [], pack: { project: "PK", slug: "cozy", title: "Cozy", version: "1", versionId: "pv", url: "https://cdn.modrinth.com/data/PK/versions/pv/cozy.mrpack", sha512: hex("f", 128), minecraft: "1.21.6", loader: "fabric", loaderVersion: "0.16.14", files: [], skipped: [], overrides: [] } }),
297 );
298 const r = await clientPack(app, box, "cozy");
299 expect(r).toEqual({ ok: true, value: { kind: "link", url: "https://cdn.modrinth.com/data/PK/versions/pv/cozy.mrpack" } });
300 });
301
302 test("an address that is not Modrinth's own CDN is never handed on: not a modpack's link, not a file of the index", async () => {
303 const pack = (url: string) =>
304 JSON.stringify({ projects: [], pack: { project: "PK", slug: "cozy", title: "Cozy", version: "1", versionId: "pv", url, sha512: hex("f", 128), minecraft: "1.21.6", loader: "fabric", loaderVersion: "0.16.14", files: [], skipped: [], overrides: [] } });
305 for (const bad of ["http://cdn.modrinth.com/x.mrpack", "https://evil.test/cdn.modrinth.com/x.mrpack", "https://[email protected]/x.mrpack", "javascript:alert(1)"]) {
306 await commit("net/modrinth/cozy.lock.json", pack(bad));
307 const r = await clientPack(app, box, "cozy");
308 expect(r).toEqual({ ok: false, error: expect.stringContaining("not on Modrinth's own download server") });
309 }
310 // The download answers 409 in words, and no link is made for it.
311 const token = makeLink(app.db, box, "cozy", "t");
312 const down = await http.handle(new Request(`${ORIGIN}/games/@pack/${token}/cozy.mrpack`));
313 expect([down.status, await down.text()]).toEqual([409, expect.stringContaining("Modrinth's own download server")]);
314 // A file of the lock on another host stays out of the index: the pack is refused.
315 await commit("net/modrinth/survival.lock.json", JSON.stringify({ projects: LOCK.map((l) => (l.project === "BALM" ? { ...l, url: "https://evil.test/balm.jar" } : l)) }));
316 const strange = await clientPack(app, box, "survival");
317 expect(strange).toEqual({ ok: false, error: expect.stringContaining("Balm") });
318 await commit("net/modrinth/survival.lock.json", JSON.stringify({ projects: LOCK }));
319 });
320
321 test("a link of a box that has ended answers 404", async () => {
322 const token = makeLink(app.db, box, "survival", "t");
323 expect(linkOf(app.db, token)).toBeDefined();
324 app.db.query("INSERT INTO pinned_forge (id, name, target, account, app, source, version, config, change_id, created_at, state) VALUES ('p-net', 'net', 'digitalocean', 'main', 'a/b', 's', 'v', '{}', 0, '2026-11-30', 'retired')").run();
325 expect(linkOf(app.db, token)).toBeUndefined();
326 expect((await http.handle(new Request(`${ORIGIN}/games/@pack/${token}/survival.mrpack`))).status).toBe(404);
327 app.db.query("DELETE FROM pinned_forge WHERE id = 'p-net'").run();
328 expect(linkOf(app.db, token)).toBeDefined();
329 });
330
331 test("the terminal's mods screen: links already open can be ended when none can be made, and l is offered only when one can", async () => {
332 const open = async (): Promise<string> => {
333 const terminal = headlessTerminal(160, 30);
334 const { app: tui, session } = createForgeApp(app, { sshUsername: "alice", remoteAddress: "127.0.0.1", fingerprint: "SHA256:test", user: alice }, { terminal, exitHooks: false });
335 tui.start();
336 tui.ctx.push(gameModsScreen(session, tui.ctx, box, "survival"));
337 await settleUntil(tui, "players:");
338 const text = tui.screen.toText();
339 tui.stop?.();
340 return text;
341 };
342 makeLink(app.db, box, "survival", "t");
343 // An earlier test left a start line in the log, which would name a loader: none here, so no pack can be made.
344 app.db.query("DELETE FROM game_log WHERE box_id = ?1 AND service = 'survival'").run(box.id);
345 await commit("net/docker-compose.yml", COMPOSE(""));
346 const none = await open();
347 expect(none).toMatch(/\d+ link\(s\) open; x ends all\./);
348 expect(none).not.toContain("l makes a link.");
349 await commit("net/docker-compose.yml", COMPOSE("\n FABRIC_LOADER_VERSION: \"0.16.14\""));
350 const can = await open();
351 expect(can).toMatch(/\d+ link\(s\) open; x ends all\./);
352 expect(can).toContain("l makes a link.");
353 });
354 });
test/no-polling.test.ts +1
@@ -333,6 +333,7 @@ const NOT_WALKED: Record<string, string> = {
333333 "/games/:box/:service/stream": "a game box, which the seed does not make (test/games.test.ts covers it)",
334334 "/games/:box/:service/config": "a game box, which the seed does not make (test/game-plugin-config-doors.test.ts covers it)",
335335 "/games/jar/:id/:name": "a kept plugin jar, a download behind a signed URL, not a page",
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)",
336337 "/games/head/:uuid": "a player's head, a PNG kept from mc-heads.net, not a page",
337338 "/:owner/:name/waves/:version": "needs a wave of a milestone",
338339 "/boards/:slug": "needs a board",
test/security-floor-routes.test.ts +1
@@ -76,6 +76,7 @@ const UNSEEDED: Record<string, string> = {
7676 "/games/:box/@shell/stream": "a game box's shell output for its owner, which the seed does not make (test/game-console.test.ts covers it)",
7777 "/games/:box/:service/stream": "a game box, which the seed does not make (test/games.test.ts covers it)",
7878 "/games/:box/:service/config": "a game box, which the seed does not make (test/game-plugin-config-doors.test.ts covers it)",
79 "/games/@pack/:token/:file": "a client pack behind a link the seed does not make (test/game-client-pack.test.ts covers it)",
7980 "/games/head/:uuid": "a player's head picture, by a Minecraft UUID only a game box's agent reports",
8081 "/games/jar/:id/:name": "a kept plugin jar of a game box, behind a signed URL the seed does not make",
8182 "/talk/dev/:token": "a dev cell reached by a one-time token the seed does not mint (test/dev-cell.test.ts covers it)",

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

Keyboard shortcuts

Docs