Public: anyone can read this; the crew can change it.
Games console: a Minecraft network experience better than playing it (Modrinth, worlds, people, health) #17342
Merged 31h 56m ago, live in production
scout/forge:scout/17284-games-console-a-minecraft-network-experi → main 0 commits fork 4 threads · 4 unresolved
10 files
changed +582
−26
docs/features/games.md +4
| @@ -13,6 +13,10 @@ A **game box** is a VM on your own cloud running Docker and `forge-game-agent`, | ||
| 13 | 13 | - **MCP:** `games` (admin-listed tonight): `list`, `console`, `power`, `env`, `plugin`, `config`, `config_set`, with the same grants. |
| 14 | 14 | - **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. |
| 15 | 15 | |
| 16 | ## Modrinth | |
| 17 | ||
| 18 | Adding a Modrinth slug to a service whose `TYPE` and `VERSION` are set (Paper, Fabric, Forge and the like, a numbered version) is planned first (`src/games/modrinth.ts`): the newest version for that loader and Minecraft version, plus every required dependency, as "adds fabric-api 0.x, sodium 0.x". A client-only project, an unknown one or one with no compatible version is refused with the reason, and nothing is committed. The commit sets `MODRINTH_PROJECTS` and writes `<service>.modrinth-lock.json` beside the compose file (project, version id, sha512, url, path). Every door can preview: the page's Preview button beside Add, `?` before the slug in the terminal's `a` prompt, and `games` `plugin` with `preview: true` over MCP all say "Would commit: adds …" and commit nothing; a jar URL previews the same way ("adds the jar at …"). Enter in the slug field adds. The newest stable release wins over a newer beta or alpha; a dependency whose slug is not plain letters, digits, `_`, `.` or `-` is refused rather than written to env; a Modrinth that does not answer in 5 seconds is refused with that reason. Without `TYPE` and `VERSION` the slug is appended as before and the image picks the version. Requests carry a real User-Agent, are cached an hour and stay under 240 a minute; `api.modrinth.com` and `cdn.modrinth.com` are in `forge.json` `egress`. Not yet: search, updates, modpacks, the box verifying the hashes (the rest of G1, #17284). | |
| 19 | ||
| 16 | 20 | ## What a sync carries |
| 17 | 21 | |
| 18 | 22 | The agent sends every string plain: terminal colour escapes and control bytes (which itzg images and `rcon-cli` print) are taken out, and every part is checked as JSON and passed through a file, never a command line, so a large sync still goes. The forge cleans the same from what an older agent sends (`boundedMachineBody`), and refuses only a body that is not JSON, with where it broke; its log holds the first 200 bytes. |
forge.json +2
src/games/compose.ts +63 −10
| @@ -11,6 +11,7 @@ import { canWrite, getRepo } from "../core/repos.ts"; | ||
| 11 | 11 | import type { User } from "../core/users.ts"; |
| 12 | 12 | import { runGit } from "../git/env.ts"; |
| 13 | 13 | import { repoDir } from "../git/repos.ts"; |
| 14 | import { lockText, planInstall, previewOf, SLUG, targetOf, type Fetcher } from "./modrinth.ts"; | |
| 14 | 15 | import type { GameBox } from "./store.ts"; |
| 15 | 16 | |
| 16 | 17 | export interface Compose { |
| @@ -136,7 +137,9 @@ export async function commitServiceEnv( | ||
| 136 | 137 | box: GameBox, |
| 137 | 138 | service: string, |
| 138 | 139 | values: Record<string, string | null>, |
| 139 | ): Promise<{ ok: true; sha: string } | { ok: false; error: string }> { | |
| 140 | extra: { path: string; content: string }[] = [], | |
| 141 | say = "", | |
| 142 | ): Promise<{ ok: true; sha: string; says?: string } | { ok: false; error: string }> { | |
| 140 | 143 | const secret = Object.keys(values).find((k) => SECRET_KEY.test(k)); |
| 141 | 144 | if (secret !== undefined) |
| 142 | 145 | return { |
| @@ -144,9 +147,11 @@ export async function commitServiceEnv( | ||
| 144 | 147 | error: `${secret} looks like a secret, and the repository is no place for one: the forge seals secrets and writes them to the box's .env itself.`, |
| 145 | 148 | }; |
| 146 | 149 | return commitCompose(app, user, box, { |
| 147 | message: `games: ${service} env: ${Object.keys(values).sort().join(", ")}`, | |
| 150 | message: `games: ${service} env: ${Object.keys(values).sort().join(", ")}${say === "" ? "" : ` (${say})`}`, | |
| 148 | 151 | what: "env", |
| 149 | 152 | edit: (text) => setServiceEnv(text, service, values), |
| 153 | extra, | |
| 154 | say, | |
| 150 | 155 | }); |
| 151 | 156 | } |
| 152 | 157 | |
| @@ -159,8 +164,16 @@ export async function commitCompose( | ||
| 159 | 164 | app: App, |
| 160 | 165 | user: User, |
| 161 | 166 | box: GameBox, |
| 162 | change: { message: string; what: string; edit: (text: string) => string; expectTip?: string }, | |
| 163 | ): Promise<{ ok: true; sha: string } | { ok: false; error: string }> { | |
| 167 | change: { | |
| 168 | message: string; | |
| 169 | what: string; | |
| 170 | edit: (text: string) => string; | |
| 171 | expectTip?: string; | |
| 172 | /** Files committed beside the compose file (a lockfile), and what to say of the change. */ | |
| 173 | extra?: { path: string; content: string }[]; | |
| 174 | say?: string; | |
| 175 | }, | |
| 176 | ): Promise<{ ok: true; sha: string; says?: string } | { ok: false; error: string }> { | |
| 164 | 177 | const compose = await readCompose(app, box); |
| 165 | 178 | if (compose === undefined) return { ok: false, error: `No ${box.path} on ${box.repo}@${box.branch}.` }; |
| 166 | 179 | if (change.expectTip !== undefined && change.expectTip !== compose.sha) |
| @@ -178,11 +191,11 @@ export async function commitCompose( | ||
| 178 | 191 | const done = await commitToBranch(app, user, repo, { |
| 179 | 192 | branch: box.branch, |
| 180 | 193 | message: change.message, |
| 181 | files: [{ path: box.path, content: text }], | |
| 194 | files: [{ path: box.path, content: text }, ...(change.extra ?? [])], | |
| 182 | 195 | expectTip: compose.sha, |
| 183 | 196 | }); |
| 184 | 197 | return done.ok |
| 185 | ? { ok: true, sha: done.value.commitOid } | |
| 198 | ? { ok: true, sha: done.value.commitOid, ...(change.say === undefined || change.say === "" ? {} : { says: change.say }) } | |
| 186 | 199 | : { ok: false, error: `The commit was refused: ${JSON.stringify(done.error).slice(0, 200)}` }; |
| 187 | 200 | } |
| 188 | 201 | |
| @@ -193,24 +206,64 @@ export function pluginsOf(text: string, service: string): { plugins: string[]; m | ||
| 193 | 206 | return { plugins: split(env["PLUGINS"]), modrinth: split(env["MODRINTH_PROJECTS"]) }; |
| 194 | 207 | } |
| 195 | 208 | |
| 196 | /** Add a plugin URL or a Modrinth slug to a service, by commit. */ | |
| 209 | /** A service's Modrinth lockfile, beside the compose file: project, version id, sha512, path. */ | |
| 210 | export const lockPath = (box: GameBox, service: string): string => `${box.path.replace(/[^/]*$/, "")}${service}.modrinth-lock.json`; | |
| 211 | ||
| 212 | /** | |
| 213 | * What a door tells a person after `addPlugin`: the preview ("Would commit") or the commit, in one | |
| 214 | * wording. | |
| 215 | */ | |
| 216 | export function pluginSays(done: { ok: true; sha: string; says?: string }, dry: boolean): string { | |
| 217 | const tail = done.says === undefined ? "" : `: ${done.says}`; | |
| 218 | return dry ? `Would commit${tail}. Nothing is changed yet.` : `Committed ${done.sha.slice(0, 10)}${tail}.`; | |
| 219 | } | |
| 220 | ||
| 221 | /** | |
| 222 | * Add a plugin URL or a Modrinth slug to a service, by commit. A slug on a server whose TYPE and | |
| 223 | * VERSION are set is planned first (newest compatible version, required dependencies) and refused | |
| 224 | * with the reason when none runs here; the commit carries the lockfile. `dry` stops at the preview. | |
| 225 | */ | |
| 197 | 226 | export async function addPlugin( |
| 198 | 227 | app: App, |
| 199 | 228 | user: User, |
| 200 | 229 | box: GameBox, |
| 201 | 230 | service: string, |
| 202 | 231 | add: { url?: string; modrinth?: string }, |
| 203 | ): Promise<{ ok: true; sha: string } | { ok: false; error: string }> { | |
| 232 | opts: { fetcher?: Fetcher; dry?: boolean } = {}, | |
| 233 | ): Promise<{ ok: true; sha: string; says?: string } | { ok: false; error: string }> { | |
| 204 | 234 | const compose = await readCompose(app, box); |
| 205 | 235 | if (compose === undefined) return { ok: false, error: `No ${box.path} on ${box.repo}@${box.branch}.` }; |
| 206 | 236 | const now = pluginsOf(compose.text, service); |
| 207 | 237 | if (add.modrinth !== undefined) { |
| 208 | if (!/^[a-z0-9][a-z0-9_.:-]{0,99}$/i.test(add.modrinth)) return { ok: false, error: "A Modrinth project is its slug, like luckperms." }; | |
| 238 | if (!SLUG.test(add.modrinth)) return { ok: false, error: "A Modrinth project is its slug, like luckperms." }; | |
| 209 | 239 | if (now.modrinth.includes(add.modrinth)) return { ok: false, error: `${add.modrinth} is already there.` }; |
| 210 | return commitServiceEnv(app, user, box, service, { MODRINTH_PROJECTS: [...now.modrinth, add.modrinth].join(",") }); | |
| 240 | const target = targetOf(serviceEnv(compose.text, service)); | |
| 241 | if (target === undefined) { | |
| 242 | if (opts.dry === true) return { ok: true, sha: "", says: `adds ${add.modrinth}; this server's TYPE and VERSION are not set, so its image picks the version` }; | |
| 243 | return commitServiceEnv(app, user, box, service, { MODRINTH_PROJECTS: [...now.modrinth, add.modrinth].join(",") }); | |
| 244 | } | |
| 245 | const plan = await planInstall(add.modrinth, target, now.modrinth, opts.fetcher); | |
| 246 | if (!plan.ok) return { ok: false, error: `${add.modrinth} is not installed on ${target.loader} ${target.version}: ${plan.reason}` }; | |
| 247 | const says = previewOf(plan.adds); | |
| 248 | if (opts.dry === true) return { ok: true, sha: "", says }; | |
| 249 | const [owner = "", name = ""] = box.repo.split("/"); | |
| 250 | const repo = getRepo(app.db, owner, name); | |
| 251 | const at = lockPath(box, service); | |
| 252 | const had = repo === undefined ? undefined : await runGit(["show", `${compose.sha}:${at}`], { cwd: repoDir(app.reposRoot, repo.ownerName, repo.name) }); | |
| 253 | const slugs = plan.adds.map((a) => a.slug).filter((s) => !now.modrinth.includes(s)); | |
| 254 | return commitServiceEnv( | |
| 255 | app, | |
| 256 | user, | |
| 257 | box, | |
| 258 | service, | |
| 259 | { MODRINTH_PROJECTS: [...now.modrinth, ...slugs].join(",") }, | |
| 260 | [{ path: at, content: lockText(had?.ok ? had.value : undefined, plan.adds) }], | |
| 261 | says, | |
| 262 | ); | |
| 211 | 263 | } |
| 212 | 264 | if (add.url !== undefined) { |
| 213 | 265 | if (now.plugins.includes(add.url)) return { ok: false, error: "That plugin is already there." }; |
| 266 | if (opts.dry === true) return { ok: true, sha: "", says: `adds the jar at ${add.url}` }; | |
| 214 | 267 | return commitServiceEnv(app, user, box, service, { PLUGINS: [...now.plugins, add.url].join(",") }); |
| 215 | 268 | } |
| 216 | 269 | return { ok: false, error: "Name a plugin." }; |
src/games/modrinth.ts added +207
| @@ -0,0 +1,207 @@ | ||
| 1 | /** | |
| 2 | * Modrinth for a game server (#17284, G1): which version of a project runs on this server's loader | |
| 3 | * and game version, which required dependencies come with it, and what the lockfile records | |
| 4 | * (project, version id, sha512, path). Plain data in, plain data out: the HTTP is a `Fetcher` the | |
| 5 | * caller may replace, with a real User-Agent, a one-hour cache and at most 240 requests a minute | |
| 6 | * (Modrinth allows 300). | |
| 7 | */ | |
| 8 | ||
| 9 | export type Fetcher = (url: string, init: { headers: Record<string, string>; signal?: AbortSignal }) => Promise<{ ok: boolean; status: number; json(): Promise<unknown> }>; | |
| 10 | ||
| 11 | /** What a server runs: the loader Modrinth knows it by and its Minecraft version. */ | |
| 12 | export interface Target { | |
| 13 | readonly loader: string; | |
| 14 | readonly version: string; | |
| 15 | } | |
| 16 | ||
| 17 | /** One file to download and verify, as the lockfile keeps it. */ | |
| 18 | export interface Locked { | |
| 19 | readonly project: string; | |
| 20 | readonly slug: string; | |
| 21 | readonly name: string; | |
| 22 | readonly versionId: string; | |
| 23 | readonly versionNumber: string; | |
| 24 | readonly sha512: string; | |
| 25 | readonly url: string; | |
| 26 | readonly path: string; | |
| 27 | } | |
| 28 | ||
| 29 | export type Plan = { readonly ok: true; readonly adds: Locked[] } | { readonly ok: false; readonly reason: string }; | |
| 30 | ||
| 31 | const API = "https://api.modrinth.com/v2"; | |
| 32 | const USER_AGENT = "trevato/forge games console (https://forge.open-platform.sh)"; | |
| 33 | const TTL_MS = 3_600_000; | |
| 34 | const PER_MINUTE = 240; | |
| 35 | const MAX_ADDS = 20; | |
| 36 | const TIMEOUT_MS = 5000; | |
| 37 | ||
| 38 | /** | |
| 39 | * A Modrinth slug or id: what may be typed, and what a dependency may be named, before it is | |
| 40 | * written to env. | |
| 41 | */ | |
| 42 | export const SLUG = /^[a-z0-9][a-z0-9_.-]{0,99}$/i; | |
| 43 | ||
| 44 | /** itzg's TYPE (and a Velocity proxy) as the loaders Modrinth files its versions under. */ | |
| 45 | const LOADERS: Record<string, readonly string[]> = { | |
| 46 | PAPER: ["paper", "spigot", "bukkit"], | |
| 47 | PURPUR: ["purpur", "paper", "spigot", "bukkit"], | |
| 48 | SPIGOT: ["spigot", "bukkit"], | |
| 49 | BUKKIT: ["bukkit"], | |
| 50 | FOLIA: ["folia", "paper", "spigot", "bukkit"], | |
| 51 | FABRIC: ["fabric"], | |
| 52 | QUILT: ["quilt", "fabric"], | |
| 53 | FORGE: ["forge"], | |
| 54 | NEOFORGE: ["neoforge"], | |
| 55 | VELOCITY: ["velocity"], | |
| 56 | }; | |
| 57 | ||
| 58 | /** | |
| 59 | * The target a service's env names, or why none can be named (then the image resolves it itself). | |
| 60 | */ | |
| 61 | export function targetOf(env: Record<string, string>): Target | undefined { | |
| 62 | const loaders = LOADERS[(env["TYPE"] ?? "").toUpperCase()]; | |
| 63 | const version = env["VERSION"] ?? ""; | |
| 64 | if (loaders === undefined || !/^\d+\.\d+(\.\d+)?$/.test(version)) return undefined; | |
| 65 | return { loader: loaders[0]!, version }; | |
| 66 | } | |
| 67 | ||
| 68 | type Memory = { calls: number[]; cache: Map<string, { at: number; body: unknown }> }; | |
| 69 | /** | |
| 70 | * Per fetcher, not per process: the default `fetch` shares one memory, a test's own fetcher gets | |
| 71 | * its own. | |
| 72 | */ | |
| 73 | const memories = new WeakMap<Fetcher, Memory>(); | |
| 74 | const memoryOf = (f: Fetcher): Memory => { | |
| 75 | let m = memories.get(f); | |
| 76 | if (m === undefined) memories.set(f, (m = { calls: [], cache: new Map() })); | |
| 77 | return m; | |
| 78 | }; | |
| 79 | ||
| 80 | async function get(url: string, fetcher: Fetcher, now: number): Promise<unknown> { | |
| 81 | const { calls, cache } = memoryOf(fetcher); | |
| 82 | const hit = cache.get(url); | |
| 83 | if (hit !== undefined && now - hit.at < TTL_MS) return hit.body; | |
| 84 | while (calls.length > 0 && now - calls[0]! > 60_000) calls.shift(); | |
| 85 | if (calls.length >= PER_MINUTE) throw new Error("Modrinth is asked too often just now; try again in a minute."); | |
| 86 | calls.push(now); | |
| 87 | let res; | |
| 88 | try { | |
| 89 | res = await fetcher(url, { headers: { "user-agent": USER_AGENT, accept: "application/json" }, signal: AbortSignal.timeout(TIMEOUT_MS) }); | |
| 90 | } catch (e) { | |
| 91 | if (e instanceof Error && (e.name === "TimeoutError" || e.name === "AbortError")) throw new Error("Modrinth did not answer in 5 seconds; try again shortly."); | |
| 92 | throw e; | |
| 93 | } | |
| 94 | if (res.status === 404) return undefined; | |
| 95 | if (!res.ok) throw new Error(`Modrinth answered ${res.status}.`); | |
| 96 | const body = await res.json(); | |
| 97 | cache.set(url, { at: now, body }); | |
| 98 | if (cache.size > 500) cache.delete(cache.keys().next().value!); | |
| 99 | return body; | |
| 100 | } | |
| 101 | ||
| 102 | const obj = (v: unknown): Record<string, unknown> => (v !== null && typeof v === "object" ? (v as Record<string, unknown>) : {}); | |
| 103 | const text = (v: unknown): string => (typeof v === "string" ? v : ""); | |
| 104 | const list = (v: unknown): unknown[] => (Array.isArray(v) ? v : []); | |
| 105 | ||
| 106 | /** | |
| 107 | * The newest version of `ref` (slug or id) that runs on `target`, as a lock entry; or why none | |
| 108 | * does. | |
| 109 | */ | |
| 110 | async function newest(ref: string, target: Target, fetcher: Fetcher, now: number): Promise<Locked | string> { | |
| 111 | const q = `loaders=${encodeURIComponent(JSON.stringify(LOADERS_FOR(target)))}&game_versions=${encodeURIComponent(JSON.stringify([target.version]))}`; | |
| 112 | const project = obj(await get(`${API}/project/${encodeURIComponent(ref)}`, fetcher, now)); | |
| 113 | if (text(project["id"]) === "") return `${ref} is not on Modrinth.`; | |
| 114 | const side = text(project["server_side"]); | |
| 115 | if (side === "unsupported") return `${text(project["title"]) || ref} is client-only: it does nothing on a server.`; | |
| 116 | const versions = list(await get(`${API}/project/${encodeURIComponent(ref)}/version?${q}`, fetcher, now)); | |
| 117 | // Modrinth lists newest first; a stable release beats a newer beta, and a beta a newer alpha. | |
| 118 | const kinds = ["release", "beta", "alpha"]; | |
| 119 | const v = obj(kinds.map((k) => versions.find((x) => text(obj(x)["version_type"]) === k)).find((x) => x !== undefined)); | |
| 120 | if (text(v["id"]) === "") | |
| 121 | return `${text(project["title"]) || ref} has no version for ${target.loader} on Minecraft ${target.version}.`; | |
| 122 | const files = list(v["files"]).map(obj); | |
| 123 | const file = files.find((f) => f["primary"] === true) ?? files[0] ?? {}; | |
| 124 | const sha512 = text(obj(file["hashes"])["sha512"]); | |
| 125 | const filename = text(file["filename"]); | |
| 126 | const url = text(file["url"]); | |
| 127 | if (!/^[a-f0-9]{128}$/.test(sha512) || !/^[\w.+() -]{1,120}\.jar$/.test(filename) || !url.startsWith("https://cdn.modrinth.com/")) | |
| 128 | return `${text(project["title"]) || ref}'s file cannot be verified, so it is not offered.`; | |
| 129 | if (!SLUG.test(text(project["slug"]))) return `${text(project["title"]) || ref} has a name that cannot be written safely, so it is not offered.`; | |
| 130 | return { | |
| 131 | project: text(project["id"]), | |
| 132 | slug: text(project["slug"]), | |
| 133 | name: text(project["title"]) || ref, | |
| 134 | versionId: text(v["id"]), | |
| 135 | versionNumber: text(v["version_number"]), | |
| 136 | sha512, | |
| 137 | url, | |
| 138 | path: `mods/${filename}`, | |
| 139 | }; | |
| 140 | } | |
| 141 | ||
| 142 | // The loaders to try for a target: its own, plus what it is compatible with. | |
| 143 | const LOADERS_FOR = (t: Target): string[] => { | |
| 144 | const all = Object.values(LOADERS).find((l) => l[0] === t.loader) ?? [t.loader]; | |
| 145 | return [...all]; | |
| 146 | }; | |
| 147 | ||
| 148 | /** | |
| 149 | * What installing `slug` adds on `target`: the newest compatible version and every required | |
| 150 | * dependency, in install order; or the reason it is refused. | |
| 151 | */ | |
| 152 | export async function planInstall(slug: string, target: Target, have: readonly string[], fetcher: Fetcher = fetch as unknown as Fetcher, now = Date.now()): Promise<Plan> { | |
| 153 | const adds: Locked[] = []; | |
| 154 | const seen = new Set(have); | |
| 155 | const queue = [slug]; | |
| 156 | try { | |
| 157 | while (queue.length > 0) { | |
| 158 | const ref = queue.shift()!; | |
| 159 | if (seen.has(ref)) continue; | |
| 160 | seen.add(ref); | |
| 161 | const got = await newest(ref, target, fetcher, now); | |
| 162 | if (typeof got === "string") return { ok: false, reason: ref === slug ? got : `its dependency ${ref} cannot run here: ${got}` }; | |
| 163 | if (seen.has(got.slug) && ref !== got.slug) continue; | |
| 164 | seen.add(got.slug); | |
| 165 | adds.unshift(got); | |
| 166 | if (adds.length > MAX_ADDS) return { ok: false, reason: `it pulls in more than ${MAX_ADDS} projects.` }; | |
| 167 | const v = obj(await get(`${API}/version/${encodeURIComponent(got.versionId)}`, fetcher, now)); | |
| 168 | for (const d of list(v["dependencies"]).map(obj)) | |
| 169 | if (d["dependency_type"] === "required" && SLUG.test(text(d["project_id"]))) queue.push(text(d["project_id"])); | |
| 170 | } | |
| 171 | } catch (e) { | |
| 172 | return { ok: false, reason: e instanceof Error ? e.message : String(e) }; | |
| 173 | } | |
| 174 | return { ok: true, adds }; | |
| 175 | } | |
| 176 | ||
| 177 | /** "adds fabric-api 0.100.0, cloth-config 15.0.1": the preview line. */ | |
| 178 | export function previewOf(adds: readonly Locked[]): string { | |
| 179 | return `adds ${adds.map((a) => `${a.slug} ${a.versionNumber}`).join(", ")}`; | |
| 180 | } | |
| 181 | ||
| 182 | /** | |
| 183 | * A lock entry read back from a lockfile, or nothing when it lacks what the merge sorts and keys | |
| 184 | * on. | |
| 185 | */ | |
| 186 | function entryOf(x: unknown): Locked | undefined { | |
| 187 | const o = obj(x); | |
| 188 | const keys = ["project", "slug", "name", "versionId", "versionNumber", "sha512", "url", "path"] as const; | |
| 189 | return keys.every((k) => text(o[k]) !== "") ? (o as unknown as Locked) : undefined; | |
| 190 | } | |
| 191 | ||
| 192 | /** | |
| 193 | * The lockfile text with `adds` merged in (one entry a project, newest wins), stable order. Entries | |
| 194 | * of a hand-edited file that are not whole are dropped; a file that is not JSON is replaced. | |
| 195 | */ | |
| 196 | export function lockText(current: string | undefined, adds: readonly Locked[]): string { | |
| 197 | let parsed: unknown = []; | |
| 198 | try { | |
| 199 | parsed = JSON.parse(current ?? "[]"); | |
| 200 | } catch (e) { | |
| 201 | console.warn(`modrinth lockfile is not JSON, rewritten: ${e instanceof Error ? e.message : String(e)}`); | |
| 202 | } | |
| 203 | const by = new Map<string, Locked>(); | |
| 204 | for (const l of list(parsed).map(entryOf)) if (l !== undefined) by.set(l.project, l); | |
| 205 | for (const a of adds) by.set(a.project, a); | |
| 206 | return `${JSON.stringify([...by.values()].sort((a, b) => a.slug.localeCompare(b.slug)), null, 2)}\n`; | |
| 207 | } |
src/http/mcp/tools/games.ts +5 −4
| @@ -1,4 +1,4 @@ | ||
| 1 | import { addPlugin, commitServiceEnv } from "../../../games/compose.ts"; | |
| 1 | import { addPlugin, pluginSays, commitServiceEnv } from "../../../games/compose.ts"; | |
| 2 | 2 | import { boxStatus, boxStatusShared } from "../../../games/diag.ts"; |
| 3 | 3 | import { commitSettings, previewSettings, serviceSettings } from "../../../games/settings.ts"; |
| 4 | 4 | import { boxNamed, listBoxes, mayDo, queueCommand, roleOn, seesBox, SERVICE_NAME, servicesOf, type CommandKind } from "../../../games/store.ts"; |
| @@ -9,7 +9,7 @@ const POWER = ["start", "stop", "restart", "recreate", "pull"]; | ||
| 9 | 9 | export const tool: Tool = { |
| 10 | 10 | name: "games", |
| 11 | 11 | listedTo: "admin", |
| 12 | doc: "`{ action, box?, service?, text?, kind?, key?, value?, modrinth? }`: game boxes. `list`; `console` queues `text` as RCON; `power` `kind` (start, stop, restart); `env` commits `key`=`value` (empty removes); `plugin` adds a `modrinth` slug; `config` lists a service's settings (server.properties, Paper's); `config_set` sets `key` to `value`, planned first (`dryRun: false` commits the plan on the commit it was planned on). Grants as on /games", | |
| 12 | doc: "`{ action, box?, service?, text?, kind?, key?, value?, modrinth?, preview?, dryRun? }`: game boxes. `list`; `console` queues `text` as RCON; `power` `kind` (start, stop, restart); `env` commits `key`=`value` (empty removes); `plugin` adds a `modrinth` slug (`preview` true only says what it would add: the newest compatible version and its required dependencies; incompatible is refused with the reason, a lockfile with sha512 is committed); `config` lists a service's settings (server.properties, Paper's); `config_set` sets `key` to `value`, planned first (`dryRun: false` commits the plan on the commit it was planned on). Grants as on /games", | |
| 13 | 13 | description: "Game boxes: list, console, power, env, plugins, settings.", |
| 14 | 14 | inputSchema: { |
| 15 | 15 | type: "object", |
| @@ -22,6 +22,7 @@ export const tool: Tool = { | ||
| 22 | 22 | key: { type: "string", maxLength: 100 }, |
| 23 | 23 | value: { type: "string", maxLength: 2000 }, |
| 24 | 24 | modrinth: { type: "string", maxLength: 100 }, |
| 25 | preview: { type: "boolean" }, | |
| 25 | 26 | dryRun: { type: "boolean" }, |
| 26 | 27 | }, |
| 27 | 28 | required: ["action"], |
| @@ -85,8 +86,8 @@ export const tool: Tool = { | ||
| 85 | 86 | return done.ok ? good({ says: `Committed ${done.sha.slice(0, 10)}.`, sha: done.sha }) : bad("refused", done.error); |
| 86 | 87 | } |
| 87 | 88 | if (action === "plugin") { |
| 88 | const done = await addPlugin(ctx.app, user, box, service, { modrinth: str(args["modrinth"]) }); | |
| 89 | return done.ok ? good({ says: `Committed ${done.sha.slice(0, 10)}.`, sha: done.sha }) : bad("refused", done.error); | |
| 89 | const done = await addPlugin(ctx.app, user, box, service, { modrinth: str(args["modrinth"]) }, { dry: args["preview"] === true }); | |
| 90 | return done.ok ? good({ says: pluginSays(done, args["preview"] === true), sha: done.sha }) : bad("refused", done.error); | |
| 90 | 91 | } |
| 91 | 92 | if (action === "config_set") { |
| 92 | 93 | const plan = await previewSettings(ctx.app, box, service, { [str(args["key"])]: str(args["value"]) }); |
src/tui/screens/games.ts +7 −5
| @@ -16,7 +16,7 @@ import { SHELL_SERVICE, queueShell } from "../../games/shell.ts"; | ||
| 16 | 16 | import { onSync } from "../../games/notify.ts"; |
| 17 | 17 | import { boxStatus, boxStatusShared } from "../../games/diag.ts"; |
| 18 | 18 | import { getUserByName } from "../../core/users.ts"; |
| 19 | import { addPlugin, commitServiceEnv, pluginsOf, readCompose, serviceEnv } from "../../games/compose.ts"; | |
| 19 | import { addPlugin, commitServiceEnv, pluginSays, pluginsOf, readCompose, serviceEnv } from "../../games/compose.ts"; | |
| 20 | 20 | import { commitSettings, planSettings, settingsOf, type SettingsPlan, type SettingValue } from "../../games/settings.ts"; |
| 21 | 21 | import { |
| 22 | 22 | SERVICE_NAME, |
| @@ -228,13 +228,15 @@ export function gameServiceScreen(f: Session, ctx: Ctx, box: GameBox, service: s | ||
| 228 | 228 | }); |
| 229 | 229 | else if (e.key === "c") ctx.push(gameSettingsScreen(f, ctx, box, service)); |
| 230 | 230 | else if (e.key === "a") |
| 231 | ask("Plugin", "A Modrinth slug, or an https URL to a jar", async (raw) => { | |
| 232 | const v = raw.trim(); | |
| 233 | const done = await addPlugin(f.app, f.user!, box, service, /^https?:\/\//.test(v) ? { url: v } : { modrinth: v }); | |
| 231 | ask("Plugin", "A Modrinth slug (start with ? to preview it), or an https URL to a jar", async (raw) => { | |
| 232 | const dry = raw.trim().startsWith("?"); | |
| 233 | const v = raw.trim().replace(/^\?\s*/, ""); | |
| 234 | const done = await addPlugin(f.app, f.user!, box, service, /^https?:\/\//.test(v) ? { url: v } : { modrinth: v }, { dry }); | |
| 234 | 235 | if (!done.ok) return done.error; |
| 236 | if (dry) return pluginSays(done, true); | |
| 235 | 237 | part = "plugins"; |
| 236 | 238 | await load(); |
| 237 | return `Committed ${done.sha.slice(0, 10)}.`; | |
| 239 | return pluginSays(done, false); | |
| 238 | 240 | }); |
| 239 | 241 | else return false; |
| 240 | 242 | return true; |
src/web/pages/games.ts +5 −4
| @@ -6,7 +6,7 @@ | ||
| 6 | 6 | * compose repository, so a merge redeploys and the crew can propose them too. |
| 7 | 7 | */ |
| 8 | 8 | |
| 9 | import { addPlugin, commitServiceEnv, composeServices, pluginsOf, readCompose, SECRET_KEY, serviceEnv } from "../../games/compose.ts"; | |
| 9 | import { addPlugin, pluginSays, commitServiceEnv, composeServices, pluginsOf, readCompose, SECRET_KEY, serviceEnv } from "../../games/compose.ts"; | |
| 10 | 10 | import { SHELL_SERVICE, queueShell } from "../../games/shell.ts"; |
| 11 | 11 | import { boxStatus, boxStatusShared } from "../../games/diag.ts"; |
| 12 | 12 | import { commitSettings, planSettings, previewSettings, settingsOf, SETTINGS, type SettingValue, type SettingsPlan } from "../../games/settings.ts"; |
| @@ -365,7 +365,7 @@ ${tail.lines.join("\n")}${tail.lines.length > 0 ? "\n" : ""}</pre | ||
| 365 | 365 | ])} |
| 366 | 366 | ${act |
| 367 | 367 | ? html`<form method="post" action="${base}/plugin" class="row-fields"> |
| 368 | ${input({ name: "modrinth", label: "Modrinth slug", required: true, mono: true })} ${btn("Add", { variant: "secondary" })} | |
| 368 | ${input({ name: "modrinth", label: "Modrinth slug", required: true, mono: true })} ${btn("Add", { variant: "secondary" })} ${btn("Preview", { variant: "secondary", name: "preview", value: "1", formnovalidate: false })} | |
| 369 | 369 | </form> |
| 370 | 370 | <form method="post" action="${base}/jar" enctype="multipart/form-data" class="row-fields"> |
| 371 | 371 | <input class="input" type="file" name="jar" accept=".jar" required aria-label="Plugin jar" /> |
| @@ -553,11 +553,12 @@ export async function gameEnvSubmit(ctx: Ctx): Promise<Response> { | ||
| 553 | 553 | export async function gamePluginSubmit(ctx: Ctx): Promise<Response> { |
| 554 | 554 | const got = await operatorForm(ctx); |
| 555 | 555 | if (got instanceof Response) return got; |
| 556 | const done = await addPlugin(ctx.app, ctx.auth.user!, got.box, got.service, { modrinth: field(got.form, "modrinth").trim() }); | |
| 556 | const dry = field(got.form, "preview") === "1"; | |
| 557 | const done = await addPlugin(ctx.app, ctx.auth.user!, got.box, got.service, { modrinth: field(got.form, "modrinth").trim() }, { dry }); | |
| 557 | 558 | return flashTo( |
| 558 | 559 | ctx, |
| 559 | 560 | `/games/${got.box.name}/${got.service}`, |
| 560 | done.ok ? { message: `Committed ${done.sha.slice(0, 10)}.` } : { tone: "danger", message: done.error }, | |
| 561 | done.ok ? { message: pluginSays(done, dry) } : { tone: "danger", message: done.error }, | |
| 561 | 562 | ); |
| 562 | 563 | } |
| 563 | 564 |
test/games.test.ts +76 −2
| @@ -13,7 +13,7 @@ import { createApp, type App } from "../src/app.ts"; | ||
| 13 | 13 | import { getRepo } from "../src/core/repos.ts"; |
| 14 | 14 | import { createToken } from "../src/core/tokens.ts"; |
| 15 | 15 | import { createUser, getUserByName, type User } from "../src/core/users.ts"; |
| 16 | import { commitServiceEnv, readCompose, serviceEnv, setServiceEnv } from "../src/games/compose.ts"; | |
| 16 | import { commitServiceEnv, pluginSays, readCompose, serviceEnv, setServiceEnv } from "../src/games/compose.ts"; | |
| 17 | 17 | import { |
| 18 | 18 | boxNamed, |
| 19 | 19 | commandOf, |
| @@ -31,8 +31,9 @@ import { | ||
| 31 | 31 | rotateGameBoxToken, |
| 32 | 32 | setGameBoxMachine, |
| 33 | 33 | } from "../src/games/store.ts"; |
| 34 | import { forgeHttp, type ForgeHttp } from "../src/http/server.ts"; | |
| 34 | import { forgeHttp, serve, type ForgeHttp } from "../src/http/server.ts"; | |
| 35 | 35 | import { quietLogs } from "./helpers/globals.ts"; |
| 36 | import { mcpTool } from "./helpers/mcp.ts"; | |
| 36 | 37 | |
| 37 | 38 | quietLogs(); |
| 38 | 39 | |
| @@ -237,3 +238,76 @@ describe("forge games", () => { | ||
| 237 | 238 | expect(queued.commands).toEqual([expect.objectContaining({ service: "hub", text: "say from bob" })]); |
| 238 | 239 | }); |
| 239 | 240 | }); |
| 241 | ||
| 242 | describe("plugin preview at every door", () => { | |
| 243 | let dataDir = ""; | |
| 244 | let app: App; | |
| 245 | let http: ForgeHttp; | |
| 246 | let alice: User; | |
| 247 | let tok = ""; | |
| 248 | const SAY = "Would commit: adds luckperms; this server's TYPE and VERSION are not set, so its image picks the version. Nothing is changed yet."; | |
| 249 | ||
| 250 | beforeAll(async () => { | |
| 251 | dataDir = await mkdtemp(join(tmpdir(), "forge-games-preview-")); | |
| 252 | app = createApp({ dataDir, port: 0 }); | |
| 253 | http = forgeHttp(app); | |
| 254 | const made = await createUser(app.db, { origin: "seed", trusted: true, username: "alice", email: "[email protected]", password: "a-good-passphrase", adminIfFirst: true }); | |
| 255 | if (!made.ok) throw new Error(made.error); | |
| 256 | alice = getUserByName(app.db, "alice")!; | |
| 257 | tok = createToken(app.db, alice.id, "admin", "admin").token; | |
| 258 | const repo = await createRepo(app, alice, { name: "mc-network", visibility: "private" }); | |
| 259 | if (!repo.ok) throw new Error(String(repo.error)); | |
| 260 | const seeded = await commitToBranch(app, alice, repo.value, { message: "network", files: [{ path: "docker-compose.yml", content: COMPOSE }] }); | |
| 261 | if (!seeded.ok) throw new Error(JSON.stringify(seeded.error)); | |
| 262 | createGameBox(app.db, { name: "net", repo: "alice/mc-network" }); | |
| 263 | }, 30_000); | |
| 264 | ||
| 265 | afterAll(async () => { | |
| 266 | app.close(); | |
| 267 | await rm(dataDir, { recursive: true, force: true }); | |
| 268 | }); | |
| 269 | ||
| 270 | const tip = async () => (await readCompose(app, boxNamed(app.db, "net")!))!.sha; | |
| 271 | const post = (form: Record<string, string>) => | |
| 272 | http.handle( | |
| 273 | new Request(`${ORIGIN}/games/net/hub/plugin`, { | |
| 274 | method: "POST", | |
| 275 | headers: { authorization: `Bearer ${tok}`, origin: ORIGIN, "content-type": "application/x-www-form-urlencoded" }, | |
| 276 | body: new URLSearchParams(form), | |
| 277 | }), | |
| 278 | ); | |
| 279 | ||
| 280 | test("pluginSays words a preview and a commit apart", () => { | |
| 281 | expect(pluginSays({ ok: true, sha: "", says: "adds x 1" }, true)).toBe("Would commit: adds x 1. Nothing is changed yet."); | |
| 282 | expect(pluginSays({ ok: true, sha: "0123456789abcdef", says: "adds x 1" }, false)).toBe("Committed 0123456789: adds x 1."); | |
| 283 | }); | |
| 284 | ||
| 285 | test("the page's Preview button says what would land and commits nothing; Add commits", async () => { | |
| 286 | const before = await tip(); | |
| 287 | const res = await post({ modrinth: "luckperms", preview: "1" }); | |
| 288 | expect(res.status).toBe(303); | |
| 289 | expect(decodeURIComponent((res.headers.get("set-cookie") ?? "").replace(/\+/g, " "))).toContain(SAY); | |
| 290 | expect(await tip()).toBe(before); | |
| 291 | await post({ modrinth: "luckperms" }); | |
| 292 | expect(await tip()).not.toBe(before); | |
| 293 | }); | |
| 294 | ||
| 295 | test("Enter in the slug field adds: Add is the form's first submit button, Preview after it", async () => { | |
| 296 | const res = await http.handle(new Request(`${ORIGIN}/games/net/hub`, { headers: { authorization: `Bearer ${tok}` } })); | |
| 297 | const form = (await res.text()).split(`action="/games/net/hub/plugin"`)[1]!.split("</form>")[0]!; | |
| 298 | const labels = [...form.matchAll(/<button[^>]*>\s*([^<]*?)\s*</g)].map((m) => m[1]); | |
| 299 | expect(labels).toEqual(["Add", "Preview"]); | |
| 300 | }); | |
| 301 | ||
| 302 | test("MCP preview commits nothing and says the same words", async () => { | |
| 303 | const servers = await serve(app); | |
| 304 | try { | |
| 305 | const before = await tip(); | |
| 306 | const got = await mcpTool(servers.url, tok, "games", { action: "plugin", box: "net", service: "lobby", modrinth: "worldedit", preview: true }); | |
| 307 | expect(got.value.says).toBe(SAY.replace("luckperms", "worldedit")); | |
| 308 | expect(await tip()).toBe(before); | |
| 309 | } finally { | |
| 310 | servers.stop(); | |
| 311 | } | |
| 312 | }); | |
| 313 | }); |
test/modrinth.test.ts added +198
| @@ -0,0 +1,198 @@ | ||
| 1 | /** | |
| 2 | * Modrinth on a game server (#17284): the newest compatible version and its required dependencies | |
| 3 | * are planned before a commit, an incompatible pair is refused with the reason, and the commit | |
| 4 | * carries a lockfile with each sha512. A fake Modrinth stands in for the network. | |
| 5 | */ | |
| 6 | import { afterAll, beforeAll, describe, expect, test } from "bun:test"; | |
| 7 | import { mkdtemp, rm } from "node:fs/promises"; | |
| 8 | import { tmpdir } from "node:os"; | |
| 9 | import { join } from "node:path"; | |
| 10 | import { commitToBranch, createRepo } from "../src/actions/repos.ts"; | |
| 11 | import { createApp, type App } from "../src/app.ts"; | |
| 12 | import { createUser, getUserByName, type User } from "../src/core/users.ts"; | |
| 13 | import { addPlugin, lockPath, readCompose } from "../src/games/compose.ts"; | |
| 14 | import { lockText, planInstall, previewOf, targetOf, type Fetcher } from "../src/games/modrinth.ts"; | |
| 15 | import { boxNamed, createGameBox } from "../src/games/store.ts"; | |
| 16 | import { runGit } from "../src/git/env.ts"; | |
| 17 | import { repoDir } from "../src/git/repos.ts"; | |
| 18 | import { quietLogs } from "./helpers/globals.ts"; | |
| 19 | ||
| 20 | quietLogs(); | |
| 21 | ||
| 22 | const hash = (c: string): string => c.repeat(128); | |
| 23 | const seen: string[] = []; | |
| 24 | const project = (id: string, slug: string, server = "required") => ({ id, slug, title: slug, server_side: server }); | |
| 25 | const version = (id: string, project_id: string, file: string, deps: unknown[] = []) => ({ | |
| 26 | id, | |
| 27 | project_id, | |
| 28 | version_number: `${id}.0`, | |
| 29 | version_type: "release", | |
| 30 | dependencies: deps, | |
| 31 | files: [{ primary: true, filename: file, url: `https://cdn.modrinth.com/data/${project_id}/${file}`, hashes: { sha512: hash("a") } }], | |
| 32 | }); | |
| 33 | const fake: Fetcher = async (url, init) => { | |
| 34 | seen.push(init.headers["user-agent"] ?? ""); | |
| 35 | const u = new URL(url); | |
| 36 | const path = u.pathname.replace("/v2/", ""); | |
| 37 | const loaders = u.searchParams.get("loaders") ?? ""; | |
| 38 | const body: Record<string, unknown> = { | |
| 39 | "project/sodium": project("P1", "sodium"), | |
| 40 | "project/P1": project("P1", "sodium"), | |
| 41 | "project/P2": project("P2", "fabric-api"), | |
| 42 | "project/shader-only": project("P3", "shader-only", "unsupported"), | |
| 43 | "project/paperonly": project("P4", "paperonly"), | |
| 44 | "version/V1": version("V1", "P1", "sodium.jar", [ | |
| 45 | { project_id: "P2", dependency_type: "required" }, | |
| 46 | { project_id: "P9", dependency_type: "optional" }, | |
| 47 | ]), | |
| 48 | "version/V2": version("V2", "P2", "fabric-api.jar"), | |
| 49 | }; | |
| 50 | if (path === "project/sodium/version") return ok(loaders.includes("fabric") ? [version("V1", "P1", "sodium.jar")] : []); | |
| 51 | if (path === "project/P2/version") return ok([version("V2", "P2", "fabric-api.jar")]); | |
| 52 | if (path === "project/paperonly/version") return ok(loaders.includes("paper") ? [version("V4", "P4", "p.jar")] : []); | |
| 53 | return body[path] === undefined ? { ok: false, status: 404, json: async () => ({}) } : ok(body[path]); | |
| 54 | }; | |
| 55 | const ok = (v: unknown) => ({ ok: true, status: 200, json: async () => v }); | |
| 56 | const FABRIC = { loader: "fabric", version: "1.21.1" }; | |
| 57 | ||
| 58 | describe("modrinth plan", () => { | |
| 59 | test("the target is the loader and version the env names, or none", () => { | |
| 60 | expect(targetOf({ TYPE: "FABRIC", VERSION: "1.21.1" })).toEqual(FABRIC); | |
| 61 | expect(targetOf({ TYPE: "PAPER", VERSION: "LATEST" })).toBeUndefined(); | |
| 62 | expect(targetOf({ VERSION: "1.21" })).toBeUndefined(); | |
| 63 | }); | |
| 64 | ||
| 65 | test("the newest compatible version comes with its required dependencies only, in install order", async () => { | |
| 66 | const plan = await planInstall("sodium", FABRIC, [], fake); | |
| 67 | if (!plan.ok) throw new Error(plan.reason); | |
| 68 | expect(plan.adds.map((a) => a.slug)).toEqual(["fabric-api", "sodium"]); | |
| 69 | expect(previewOf(plan.adds)).toBe("adds fabric-api V2.0, sodium V1.0"); | |
| 70 | expect(plan.adds[1]).toMatchObject({ project: "P1", versionId: "V1", sha512: hash("a"), path: "mods/sodium.jar" }); | |
| 71 | expect(seen.every((ua) => ua.includes("forge"))).toBe(true); | |
| 72 | }); | |
| 73 | ||
| 74 | test("an incompatible pair, a client-only mod and an unknown project are refused with the reason", async () => { | |
| 75 | expect(await planInstall("paperonly", FABRIC, [], fake)).toEqual({ ok: false, reason: "paperonly has no version for fabric on Minecraft 1.21.1." }); | |
| 76 | expect(await planInstall("shader-only", FABRIC, [], fake)).toMatchObject({ ok: false, reason: expect.stringContaining("client-only") }); | |
| 77 | expect(await planInstall("nope", FABRIC, [], fake)).toEqual({ ok: false, reason: "nope is not on Modrinth." }); | |
| 78 | }); | |
| 79 | ||
| 80 | test("a lockfile keeps one entry a project, sorted, the newest winning", async () => { | |
| 81 | const plan = await planInstall("sodium", FABRIC, [], fake); | |
| 82 | if (!plan.ok) throw new Error(plan.reason); | |
| 83 | const once = lockText(undefined, plan.adds); | |
| 84 | const twice = JSON.parse(lockText(once, plan.adds)); | |
| 85 | expect(twice.map((l: { slug: string }) => l.slug)).toEqual(["fabric-api", "sodium"]); | |
| 86 | }); | |
| 87 | }); | |
| 88 | ||
| 89 | describe("modrinth hardening", () => { | |
| 90 | const withSlug = (slug: string): Fetcher => async (url, init) => { | |
| 91 | const path = new URL(url).pathname.replace("/v2/", ""); | |
| 92 | if (path === "project/sodium") return ok(project("P1", "sodium")); | |
| 93 | if (path === "project/P2") return ok(project("P2", slug)); | |
| 94 | if (path === "project/sodium/version") return ok([version("V1", "P1", "sodium.jar")]); | |
| 95 | if (path === "project/P2/version") return ok([version("V2", "P2", "evil.jar")]); | |
| 96 | if (path === "version/V1") return ok(version("V1", "P1", "sodium.jar", [{ project_id: "P2", dependency_type: "required" }])); | |
| 97 | void init; | |
| 98 | return { ok: false, status: 404, json: async () => ({}) }; | |
| 99 | }; | |
| 100 | ||
| 101 | test("a dependency named with a comma or quote is refused, never written to env", async () => { | |
| 102 | for (const slug of ["x,evil", 'a"b', "a b", ""]) { | |
| 103 | const plan = await planInstall("sodium", FABRIC, [], withSlug(slug)); | |
| 104 | expect(plan).toMatchObject({ ok: false, reason: expect.stringContaining("cannot run here") }); | |
| 105 | } | |
| 106 | expect((await planInstall("sodium", FABRIC, [], withSlug("fine-dep")))).toMatchObject({ ok: true }); | |
| 107 | }); | |
| 108 | ||
| 109 | test("a stalled Modrinth is asked with a timeout and refused with a reason", async () => { | |
| 110 | let signal: AbortSignal | undefined; | |
| 111 | const stalled: Fetcher = (_url, init) => { | |
| 112 | signal = init.signal; | |
| 113 | return init.signal?.aborted === true ? Promise.reject(init.signal.reason) : new Promise(() => {}); | |
| 114 | }; | |
| 115 | const real = AbortSignal.timeout; | |
| 116 | AbortSignal.timeout = () => AbortSignal.abort(new DOMException("timed out", "TimeoutError")); | |
| 117 | try { | |
| 118 | const plan = await planInstall("slow", FABRIC, [], stalled); | |
| 119 | expect(plan).toEqual({ ok: false, reason: "Modrinth did not answer in 5 seconds; try again shortly." }); | |
| 120 | expect(signal).toBeDefined(); | |
| 121 | } finally { | |
| 122 | AbortSignal.timeout = real; | |
| 123 | } | |
| 124 | }); | |
| 125 | ||
| 126 | test("a stable release beats a newer alpha and beta", async () => { | |
| 127 | const typed = (id: string, kind: string) => ({ ...version(id, "P1", `${id}.jar`), version_type: kind }); | |
| 128 | const f: Fetcher = async (url) => { | |
| 129 | const path = new URL(url).pathname.replace("/v2/", ""); | |
| 130 | if (path === "project/mixed") return ok(project("P1", "mixed")); | |
| 131 | if (path === "project/mixed/version") return ok([typed("A1", "alpha"), typed("B1", "beta"), typed("R1", "release"), typed("R0", "release")]); | |
| 132 | return path === "version/R1" ? ok(typed("R1", "release")) : { ok: false, status: 404, json: async () => ({}) }; | |
| 133 | }; | |
| 134 | const plan = await planInstall("mixed", FABRIC, [], f); | |
| 135 | if (!plan.ok) throw new Error(plan.reason); | |
| 136 | expect(plan.adds[0]!.versionId).toBe("R1"); | |
| 137 | const onlyAlpha: Fetcher = async (url) => (new URL(url).pathname.endsWith("/version") ? ok([typed("A1", "alpha")]) : ok(project("P1", "mixed"))); | |
| 138 | const alpha = await planInstall("mixed", FABRIC, [], onlyAlpha); | |
| 139 | expect(alpha.ok && alpha.adds[0]!.versionId).toBe("A1"); | |
| 140 | }); | |
| 141 | ||
| 142 | test("a hand-edited lockfile with a whole entry kept, a broken one dropped, and junk replaced", async () => { | |
| 143 | const plan = await planInstall("sodium", FABRIC, [], fake); | |
| 144 | if (!plan.ok) throw new Error(plan.reason); | |
| 145 | const whole = { ...plan.adds[1]!, project: "OLD", slug: "zzz" }; | |
| 146 | const merged = JSON.parse(lockText(JSON.stringify([whole, { project: "NOSLUG" }, 7, null]), plan.adds)); | |
| 147 | expect(merged.map((l: { slug: string }) => l.slug)).toEqual(["fabric-api", "sodium", "zzz"]); | |
| 148 | expect(JSON.parse(lockText("{not json", plan.adds))).toHaveLength(2); | |
| 149 | }); | |
| 150 | }); | |
| 151 | ||
| 152 | describe("addPlugin with Modrinth", () => { | |
| 153 | let dataDir = ""; | |
| 154 | let app: App; | |
| 155 | let alice: User; | |
| 156 | const compose = (type: string) => `services:\n hub:\n image: itzg/minecraft-server\n environment:\n TYPE: ${type}\n VERSION: "1.21.1"\n`; | |
| 157 | ||
| 158 | beforeAll(async () => { | |
| 159 | dataDir = await mkdtemp(join(tmpdir(), "forge-modrinth-")); | |
| 160 | app = createApp({ dataDir, port: 0 }); | |
| 161 | const made = await createUser(app.db, { origin: "seed", trusted: true, username: "alice", email: "[email protected]", password: "a-good-passphrase", adminIfFirst: true }); | |
| 162 | if (!made.ok) throw new Error(made.error); | |
| 163 | alice = getUserByName(app.db, "alice")!; | |
| 164 | const repo = await createRepo(app, alice, { name: "mc-network", visibility: "private" }); | |
| 165 | if (!repo.ok) throw new Error(String(repo.error)); | |
| 166 | const seeded = await commitToBranch(app, alice, repo.value, { message: "network", files: [{ path: "docker-compose.yml", content: compose("FABRIC") }] }); | |
| 167 | if (!seeded.ok) throw new Error(JSON.stringify(seeded.error)); | |
| 168 | createGameBox(app.db, { name: "net", repo: "alice/mc-network" }); | |
| 169 | }, 30_000); | |
| 170 | ||
| 171 | afterAll(async () => { | |
| 172 | await app.close(); | |
| 173 | await rm(dataDir, { recursive: true, force: true }); | |
| 174 | }); | |
| 175 | ||
| 176 | test("a preview commits nothing; an install commits the slugs and a lockfile with the hash", async () => { | |
| 177 | const box = boxNamed(app.db, "net")!; | |
| 178 | const before = (await readCompose(app, box))!.sha; | |
| 179 | const dry = await addPlugin(app, alice, box, "hub", { modrinth: "sodium" }, { fetcher: fake, dry: true }); | |
| 180 | expect(dry).toEqual({ ok: true, sha: "", says: "adds fabric-api V2.0, sodium V1.0" }); | |
| 181 | expect((await readCompose(app, box))!.sha).toBe(before); | |
| 182 | const done = await addPlugin(app, alice, box, "hub", { modrinth: "sodium" }, { fetcher: fake }); | |
| 183 | expect(done).toMatchObject({ ok: true, says: "adds fabric-api V2.0, sodium V1.0" }); | |
| 184 | const after = (await readCompose(app, box))!; | |
| 185 | expect(after.text).toContain('MODRINTH_PROJECTS: "fabric-api,sodium"'); | |
| 186 | const cwd = repoDir(app.reposRoot, "alice", "mc-network"); | |
| 187 | const lock = await runGit(["show", `${after.sha}:${lockPath(box, "hub")}`], { cwd }); | |
| 188 | expect(lock.ok && JSON.parse(lock.value)[1]).toMatchObject({ slug: "sodium", sha512: hash("a") }); | |
| 189 | }); | |
| 190 | ||
| 191 | test("an incompatible mod is refused and nothing is committed", async () => { | |
| 192 | const box = boxNamed(app.db, "net")!; | |
| 193 | const before = (await readCompose(app, box))!.sha; | |
| 194 | const done = await addPlugin(app, alice, box, "hub", { modrinth: "paperonly" }, { fetcher: fake }); | |
| 195 | expect(done).toEqual({ ok: false, error: "paperonly is not installed on fabric 1.21.1: paperonly has no version for fabric on Minecraft 1.21.1." }); | |
| 196 | expect((await readCompose(app, box))!.sha).toBe(before); | |
| 197 | }); | |
| 198 | }); |
test/tui-games.test.ts +15 −1
| @@ -13,7 +13,7 @@ import { join } from "node:path"; | ||
| 13 | 13 | import { commitToBranch, createRepo } from "../src/actions/repos.ts"; |
| 14 | 14 | import { createApp, type App } from "../src/app.ts"; |
| 15 | 15 | import { createUser, getUserByName, type User } from "../src/core/users.ts"; |
| 16 | import { readCompose, serviceEnv } from "../src/games/compose.ts"; | |
| 16 | import { pluginsOf, readCompose, serviceEnv } from "../src/games/compose.ts"; | |
| 17 | 17 | import { boxNamed, createGameBox, grantsOf, recentCommands, recordSync } from "../src/games/store.ts"; |
| 18 | 18 | import { createForgeApp } from "../src/tui/forge.ts"; |
| 19 | 19 | import { gameGrantsScreen, gameServiceScreen, gamesScreen } from "../src/tui/screens/games.ts"; |
| @@ -123,6 +123,20 @@ test("a service's console shows its log and queues an rcon command; env and plug | ||
| 123 | 123 | await type("not a slug!"); |
| 124 | 124 | terminal.feed("\r"); |
| 125 | 125 | await settleUntil(tui, "A Modrinth project is its slug"); |
| 126 | // `?` previews: the same dry run as the page's Preview button, nothing committed. | |
| 127 | const tip = (await readCompose(app, box))!.sha; | |
| 128 | await type("a"); | |
| 129 | await type("?luckperms"); | |
| 130 | terminal.feed("\r"); | |
| 131 | await settleUntil(tui, "Would commit: adds luckperms"); | |
| 132 | expect((await readCompose(app, box))!.sha).toBe(tip); | |
| 133 | // A URL previews too, and is not committed either (#17284). | |
| 134 | await type("a"); | |
| 135 | await type("?https://example.com/x.jar"); | |
| 136 | terminal.feed("\r"); | |
| 137 | await settleUntil(tui, "Would commit: adds the jar at https://example.com/x.jar"); | |
| 138 | expect((await readCompose(app, box))!.sha).toBe(tip); | |
| 139 | expect(pluginsOf((await readCompose(app, box))!.text, "hub").plugins).toEqual([]); | |
| 126 | 140 | await type("a"); |
| 127 | 141 | await type("luckperms"); |
| 128 | 142 | terminal.feed("\r"); |
new above
offline
Slugs of dependencies come from Modrinth and are not validated here. A slug with a comma splits into extra projects in MODRINTH_PROJECTS, outside the preview and the lockfile. Validate with the slug regex in
newestor write the project id.