Public: anyone can read this; the crew can change it.
Games G1: Modrinth, done properly: search with a compatibility badge, dependency preview, a locked install, updates (#17284) #17293
Merged 18h 51m ago, live in production
sold/game-modrinth → main 0 commits 2 threads · 2 unresolved
25 files
changed +2430
−663
- docs/features/game-mods.md
- docs/features/games.md
- src/app.ts
- src/core/empty_words.ts
- src/crew/conversation_ask.ts
- src/engine/crossing.ts
- src/games/agent.sh
- src/games/compose.ts
- src/games/modrinth.ts
- src/games/mods.ts
- src/games/pack_check.ts
- src/games/store.ts
- src/http/games_routes.ts
- src/http/lazy_lists.ts
- src/http/mcp/tools/games.ts
- src/tui/screens/game_mods.ts
- src/tui/screens/games.ts
- src/web/pages/games.ts
- test/conversation-ask.test.ts
- test/egress-literals.test.ts
- test/engine-crossing.test.ts
- test/game-mods.test.ts
- test/games.test.ts
- test/modrinth.test.ts
- test/tui-games.test.ts
docs/features/game-mods.md added +33
| @@ -0,0 +1,33 @@ | ||
| 1 | --- | |
| 2 | topic: Hosting forges for others, and getting paid | |
| 3 | row: Game mods | |
| 4 | --- | |
| 5 | # Game mods | |
| 6 | ||
| 7 | The server's mods or plugins come from Modrinth, for its loader and game version: `TYPE` names the loader (PAPER, PURPUR, SPIGOT and kin take plugins; FABRIC, QUILT, FORGE and NEOFORGE take mods; VELOCITY is a proxy), `VERSION` the game version (`MINECRAFT_VERSION` on a proxy; LATEST means the newest release, and the preview says to pin it). | |
| 8 | ||
| 9 | - **Search** shows each result with a badge before any click: *Runs on 1.21.4*, or why not (*1.20.1 and older*, *Client only*). Mod searches use Modrinth's `environment` facet, so client-only mods stay out. | |
| 10 | - **Preview** picks the newest compatible version (a release when there is one) and resolves what it requires, recursively: "Adds Chunky 1.4.28; Adds ChunkyLib 1.0.2 (required by Chunky)". A project with no version for the server, a requirement with none, or two projects that say they are incompatible are refused with the reason. A bare slug already in `MODRINTH_PROJECTS` is pinned by the same change. | |
| 11 | - **Install and restart** is one commit on the commit you previewed: the lockfile `<compose dir>/modrinth/<service>.lock.json` (each project's version id, file path, url and sha512, and whether it was asked for or is a dependency) and the compose env made from it: `MODRINTH_PROJECTS` lists `slug:versionId` for every project and `MODRINTH_DOWNLOAD_DEPENDENCIES=none`, so the image fetches exactly the locked set. A proxy also gets `MINECRAFT_VERSION`, which its Modrinth step needs. On a proxy whose servers sleep, `MODRINTH_PROJECTS` also holds AutoStopper (`PG4gqnzX:EclCtvWk`, see [](games.md)): it is sleep's, so a Modrinth change carries it over as it is and never lists it as the proxy's own, and Warm again takes only that entry. | |
| 12 | - **Updates** post the locked sha512s to Modrinth's `/v2/version_files/update` (releases for the loader and version) and show "2 updates" as from → to, one click each or all. | |
| 13 | - **Remove** takes a project and what only it required; a dependency something else requires stays. | |
| 14 | ||
| 15 | The image's helper checks every download against the sha512 Modrinth publishes for the pinned version (it fetches again, then fails the start, on a mismatch). A version's files never change, so that is the hash in the lockfile; the image cannot be handed a hash of the forge's own. | |
| 16 | ||
| 17 | The forge calls Modrinth as `forge/<version> (open-platform.sh)`, keeps answers (a version for a day, a search or version list for minutes) and stays under 300 requests a minute, waiting when Modrinth's `X-Ratelimit` headers say so. | |
| 18 | ||
| 19 | ## Modpacks | |
| 20 | ||
| 21 | On a mod server (Fabric, Quilt, Forge, NeoForge), **Search packs** finds Modrinth modpacks for its loader. Preview reads the pack's newest release: the forge downloads its `.mrpack` from Modrinth's CDN, checks it against the sha512 Modrinth publishes (a mismatch is refused, nothing installed), reads `modrinth.index.json`, and lists what changes: the pack's Minecraft and loader, how many files the server gets (every file whose `env.server` is not `unsupported`; client-only ones are left out), the override files (`overrides/`, then `server-overrides/` over them; `client-overrides/` is not the server's), a Minecraft version change (a downgrade says a newer world may not open), and the pinned projects and MODRINTH_PROJECTS entries a pack replaces. | |
| 22 | ||
| 23 | **Install pack and restart** commits the lockfile, now holding `pack` (the `.mrpack`'s url and sha512, Minecraft, the loader and its version, every file's path, url and sha512, the overrides as they land, and the files left out), and the env: `TYPE=MODRINTH`, `MODRINTH_MODPACK=<slug>`, `MODRINTH_VERSION=<version id>`, `MODRINTH_LOADER` and `VERSION` from the pack. The image installs the pack's loader, its files and overrides, and cleans up the previous pack's files on an update by its own manifest. A newer release shows as an update on the pack's row, one click. | |
| 24 | ||
| 25 | The image does not check a pack's file hashes (its Modrinth project path does; its modpack path does not), so the lockfile is what keeps them: any change to the pack's files shows as a diff in review. The box checks them instead: once a pack server is up and healthy on the compose it was given, the forge asks its agent once (a `hashes` command: a fresh container of the service's own image and volumes lists a sha512 prefix of each jar under `/data/mods`) and compares the list with the lockfile at that commit. The box page, the service's Modpack block and the MCP tool's `list` say "Pack files: 212 verified, 1 differs (sodium.jar)", with any missing and any jar not in the lock; an agent older than the check says so and checks once it updates. It may also leave out mods on its own list of known client-only mods. A pack server takes its mods from the pack: installing a project on top of one is refused for now, with that reason. | |
| 26 | ||
| 27 | ## Where | |
| 28 | ||
| 29 | - **Web:** `/games/<box>/<service>`, the Mods (or Plugins) block: updates, what is installed, Search, Preview, Install and restart; on a mod server, the Modpack block: the pack, its locked files, Search packs, Preview, Install pack and restart. | |
| 30 | - **Terminal:** a service's screen, `m`: `/` search, `a` install by a result's number or a slug, `u` update all, `d` remove, `p` a modpack by slug; `y` commits the preview shown, `n` drops it (`src/tui/screens/game_mods.ts`). | |
| 31 | - **MCP:** `games` with `mods`, `mods_search`, `mods_pack_search`, `mods_install`, `mods_update`, `mods_remove`, `mods_pack`; a change is planned until `dryRun: false`. | |
| 32 | ||
| 33 | All three read and write through `src/games/mods.ts`, over the client in `src/games/modrinth.ts`. |
docs/features/games.md +7 −8
| @@ -8,15 +8,11 @@ A **game box** is a VM on your own cloud running Docker and `forge-game-agent`, | ||
| 8 | 8 | |
| 9 | 9 | ## Where |
| 10 | 10 | |
| 11 | - **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; an RCON input whose answer shows inline, 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.md)) and the plugins (`PLUGINS`, `MODRINTH_PROJECTS`, Upload jar). Pages: `src/web/pages/games.ts`. | |
| 12 | - **Terminal:** the Games screen (`src/tui/screens/games.ts`): each service, `s`, `x`, `r`; `enter` opens a service, and `c` there its settings; a service's console reads its log with the colour codes gone, a crash first in one line, and `:`'s prompt walks earlier commands with up and down. | |
| 13 | - **MCP:** `games` (admin-listed tonight): `list`, `console`, `power`, `env`, `plugin`, `config`, `config_set`, with the same grants. | |
| 11 | - **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; an RCON input whose answer shows inline, 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.md)) and its mods or plugins (Modrinth, below; Upload jar for `PLUGINS`). Pages: `src/web/pages/games.ts`. | |
| 12 | - **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 reads its log with the colour codes gone, a crash first in one line, and `:`'s prompt walks earlier commands with up and down. | |
| 13 | - **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. | |
| 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 | ||
| 20 | 16 | ## What a sync carries |
| 21 | 17 | |
| 22 | 18 | 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. |
| @@ -44,6 +40,9 @@ A service page has a People block (#17284), with no plugin on the game servers: | ||
| 44 | 40 | `/games/<box>` draws **the network**: the proxy on top and each game server under it, awake, waking (running while its health check starts), asleep (stopped by its sleep) or stopped, with its TPS and the heads of who is on it, every player by server as the proxy says (Velocircon, an RCON console on Velocity that only the compose network reaches; the agent sends its password through stdin, never a command line), with **Move**: an operator opens a player's head and picks a server that is up. A move goes only to a server of the same box that the person also operates, on the page, in the terminal and in the `games` tool alike. A server's card opens its page (`src/web/pages/games_topology.ts`). In the terminal, the Games screen (`src/tui/screens/games.ts`) lists the same servers with their state, players and TPS. |
| 45 | 41 | |
| 46 | 42 | 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. 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. |
| 43 | ## Modrinth | |
| 44 | ||
| 45 | A server's mods and plugins come from Modrinth, searched, previewed and pinned in a lockfile: see [](game-mods.md). | |
| 47 | 46 | |
| 48 | 47 | ## Worlds |
| 49 | 48 | |
| @@ -71,4 +70,4 @@ Each sync, the agent asks every running server with `rcon-cli` for `list`, `tps` | ||
| 71 | 70 | |
| 72 | 71 | ## Who may do what |
| 73 | 72 | |
| 74 | Grants per box, optionally for one service: **owner** (everything and grants), **operator** (console, power, env, plugins), **viewer** (read). Forge admins own every box; owners grant on the box page. | |
| 73 | Grants per box, optionally for one service: **owner** (everything and grants), **operator** (console, power, env, mods), **viewer** (read). Forge admins own every box; owners grant on the box page. |
src/app.ts +2
| @@ -264,6 +264,8 @@ export interface ForgeConfig { | ||
| 264 | 264 | releaseSend?: (url: string, body: string, headers: Record<string, string>) => Promise<boolean>; |
| 265 | 265 | /** The fetch a crash is shared to mclo.gs through (`games/console.ts`); the real one unless a test says. */ |
| 266 | 266 | mclogsFetch?: (url: string, init: RequestInit) => Promise<Response>; |
| 267 | /** The fetch Modrinth's API is called through (`games/modrinth.ts`); the real one unless a test says. */ | |
| 268 | modrinthFetch?: (url: string, init: RequestInit) => Promise<Response>; | |
| 267 | 269 | } |
| 268 | 270 | |
| 269 | 271 | export interface App { |
src/core/empty_words.ts +3 −1
| @@ -98,7 +98,7 @@ const TABLE = { | ||
| 98 | 98 | regValues: { sentence: "No values." }, |
| 99 | 99 | gameBoxes: { sentence: "Nothing runs here yet.", reason: "A game box is a machine on your cloud running a compose project; an admin makes one from Infra." }, |
| 100 | 100 | gameServices: { sentence: "Nothing has reported yet.", reason: "The box shows its services once its agent first syncs." }, |
| 101 | gamePlugins: { sentence: "Nothing is installed.", reason: "Add a URL, a Modrinth project or a jar below." }, | |
| 101 | gamePlugins: { sentence: "Nothing is installed.", reason: "Search Modrinth below, or upload a jar." }, | |
| 102 | 102 | cloudProjects: { sentence: "Nothing read yet.", reason: "Each DigitalOcean and Hetzner account is read into its projects every 5 minutes; Read now reads them at once." }, |
| 103 | 103 | gameSnapshots: { sentence: "No snapshot yet.", reason: "One is taken before every import or restore." }, |
| 104 | 104 | } as const satisfies Readonly<Record<string, EmptyWords>>; |
| @@ -133,6 +133,8 @@ export const NOTE_WORDS = { | ||
| 133 | 133 | nothingOpenAndRanked: "Nothing is open and ranked.", |
| 134 | 134 | nothingOpenAndRankedHere: "Nothing is open and ranked in those repositories.", |
| 135 | 135 | noFlowLinesMatch: "No flow lines match.", |
| 136 | noModpackMatches: "No modpack matches that.", | |
| 137 | nothingOnModrinthMatches: "Nothing on Modrinth matches that.", | |
| 136 | 138 | notSignedInOnAnyBrowser: "Not signed in on any browser.", |
| 137 | 139 | noAccessCodesYet: "No access codes yet. Mint one when a script, a CI job, or another machine needs to act as you.", |
| 138 | 140 | noComputerKeysYet: "No computer keys yet. Add one and git over SSH stops asking for a password.", |
src/crew/conversation_ask.ts +4 −1
| @@ -335,7 +335,10 @@ export const ASKED_AS: Readonly<Record<string, Form>> = { | ||
| 335 | 335 | if (a["action"] === "console") return `Run ${quote(a, "text") || "a command"} in the console of ${on}`; |
| 336 | 336 | if (a["action"] === "power") return `${val(a, "kind") || "Restart"} ${on}`.replace(/^./, (c) => c.toUpperCase()); |
| 337 | 337 | if (a["action"] === "env") return `Set ${val(a, "key")} on ${on}${clause(" to ", val(a, "value"))}, a commit that redeploys it`; |
| 338 | if (a["action"] === "plugin") return `Add the plugin ${val(a, "modrinth") || val(a, "value")} to ${on}, a commit that redeploys it`; | |
| 338 | if (a["action"] === "mods_install") return `Install ${val(a, "project") || "a Modrinth project"} and what it requires on ${on}, a commit that restarts it`; | |
| 339 | if (a["action"] === "mods_update") return `Update ${val(a, "project") || "every Modrinth project"} on ${on}, a commit that restarts it`; | |
| 340 | if (a["action"] === "mods_pack") return `Make ${val(a, "project") || "a Modrinth modpack"} the modpack of ${on}, a commit that restarts it`; | |
| 341 | if (a["action"] === "mods_remove") return `Remove ${val(a, "project") || "a Modrinth project"} from ${on}, a commit that restarts it`; | |
| 339 | 342 | if (a["action"] === "config_set") return `Set the setting ${val(a, "key")} on ${on}${clause(" to ", val(a, "value"))}, a commit that restarts it`; |
| 340 | 343 | if (a["action"] === "sleep") return a["value"] === "warm" ? `Keep ${on} warm, a commit that redeploys it` : `Let ${on} sleep when empty and wake on join, a commit that redeploys it`; |
| 341 | 344 | if (a["action"] === "people") { |
src/engine/crossing.ts +2
| @@ -76,6 +76,8 @@ export const STAYS = { | ||
| 76 | 76 | "a function: a test's stand-in for the notify sender, used where a release is cut on the serving thread", |
| 77 | 77 | mclogsFetch: |
| 78 | 78 | "a function: a test's stand-in for mclo.gs, asked when a person shares a crash from the games page on the serving thread", |
| 79 | modrinthFetch: | |
| 80 | "a function: a test's stand-in for Modrinth's API, asked from the games pages and tools on the serving thread", | |
| 79 | 81 | verifyHuman: |
| 80 | 82 | "a function: a test's stand-in for Turnstile, asked at sign-up on the serving thread only", |
| 81 | 83 | } as const satisfies { readonly [K in keyof ForgeConfig]?: string }; |
src/games/agent.sh +10 −2
| @@ -427,7 +427,7 @@ host() { | ||
| 427 | 427 | |
| 428 | 428 | # Run one command from the forge and keep its result for the next sync (output at most 4 KB). |
| 429 | 429 | run() { |
| 430 | local cmd="$1" id kind service text out ok=true | |
| 430 | local cmd="$1" id kind service text out ok=true max=4096 | |
| 431 | 431 | id="$(jq -r '.id // ""' <<<"")" |
| 432 | 432 | kind="$(jq -r '.kind // ""' <<<"")" |
| 433 | 433 | service="$(jq -r '.service // ""' <<<"")" |
| @@ -498,13 +498,21 @@ run() { | ||
| 498 | 498 | return |
| 499 | 499 | fi |
| 500 | 500 | ;; |
| 501 | # A modpack's jars on the box, for the forge to check against its lockfile (the image checks | |
| 502 | # none): a fresh container of the service's own image and volumes, so it runs even when the | |
| 503 | # server does not, prints a 32-hex prefix of each jar's sha512 under /data/mods. | |
| 504 | hashes) | |
| 505 | # shellcheck disable=SC2016 # the script runs in the container, single-quoted on purpose | |
| 506 | out="$(capped 45 "" run --rm --no-deps -T --entrypoint sh "" -c 'cd /data && for f in mods/*.jar; do [ -f "" ] && sha512sum ""; done | cut -c1-32,129-' 2>&1)" || ok=false | |
| 507 | max=16000 | |
| 508 | ;; | |
| 501 | 509 | *) |
| 502 | 510 | out="refused: is not a command this agent runs" |
| 503 | 511 | ok=false |
| 504 | 512 | ;; |
| 505 | 513 | esac |
| 506 | 514 | fi |
| 507 | jq -c --arg id "" --argjson ok "" --arg out "" '. + [{id: $id, ok: $ok, output: $out}]' "/.results" >"/.results.next" && | |
| 515 | jq -c --arg id "" --argjson ok "" --arg out "" '. + [{id: $id, ok: $ok, output: $out}]' "/.results" >"/.results.next" && | |
| 508 | 516 | mv "/.results.next" "/.results" |
| 509 | 517 | } |
| 510 | 518 |
src/games/compose.ts +33 −89
| @@ -11,7 +11,6 @@ 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"; | |
| 15 | 14 | import type { GameBox } from "./store.ts"; |
| 16 | 15 | |
| 17 | 16 | export interface Compose { |
| @@ -21,14 +20,19 @@ export interface Compose { | ||
| 21 | 20 | |
| 22 | 21 | /** The compose file at the box's branch HEAD, with that commit's sha; undefined when missing. */ |
| 23 | 22 | export async function readCompose(app: App, box: GameBox): Promise<Compose | undefined> { |
| 24 | const [owner = "", name = ""] = box.repo.split("/"); | |
| 25 | const repo = getRepo(app.db, owner, name); | |
| 26 | if (repo === undefined) return undefined; | |
| 27 | const cwd = repoDir(app.reposRoot, repo.ownerName, repo.name); | |
| 23 | const cwd = boxRepoDir(app, box); | |
| 24 | if (cwd === undefined) return undefined; | |
| 28 | 25 | const sha = await runGit(["rev-parse", "--verify", `refs/heads/${box.branch}`], { cwd }); |
| 29 | 26 | if (!sha.ok) return undefined; |
| 30 | const text = await runGit(["show", `${sha.value.trim()}:${box.path}`], { cwd }); | |
| 31 | return text.ok ? { sha: sha.value.trim(), text: text.value } : undefined; | |
| 27 | const text = await readRepoFile(app, box, sha.value.trim(), box.path); | |
| 28 | return text === undefined ? undefined : { sha: sha.value.trim(), text }; | |
| 29 | } | |
| 30 | ||
| 31 | /** The box's compose repository on disk; undefined when it is gone. */ | |
| 32 | function boxRepoDir(app: App, box: GameBox): string | undefined { | |
| 33 | const [owner = "", name = ""] = box.repo.split("/"); | |
| 34 | const repo = getRepo(app.db, owner, name); | |
| 35 | return repo === undefined ? undefined : repoDir(app.reposRoot, repo.ownerName, repo.name); | |
| 32 | 36 | } |
| 33 | 37 | |
| 34 | 38 | /** The services the compose file names. */ |
| @@ -246,6 +250,14 @@ export function setTopEntry(text: string, section: string, name: string, block: | ||
| 246 | 250 | /** A key that names a secret: it belongs in the sealed `.env` the forge writes, never in the repository. */ |
| 247 | 251 | export const SECRET_KEY = /PASSWORD|SECRET|TOKEN|KEY/i; |
| 248 | 252 | |
| 253 | /** A file of the box's repository at `sha` (the compose file's commit); undefined when missing. */ | |
| 254 | export async function readRepoFile(app: App, box: GameBox, sha: string, path: string): Promise<string | undefined> { | |
| 255 | const cwd = boxRepoDir(app, box); | |
| 256 | if (cwd === undefined) return undefined; | |
| 257 | const text = await runGit(["show", `${sha}:${path}`], { cwd }); | |
| 258 | return text.ok ? text.value : undefined; | |
| 259 | } | |
| 260 | ||
| 249 | 261 | /** Commit `values` into the service's environment: "games: <service> env: <keys>". */ |
| 250 | 262 | export async function commitServiceEnv( |
| 251 | 263 | app: App, |
| @@ -253,9 +265,7 @@ export async function commitServiceEnv( | ||
| 253 | 265 | box: GameBox, |
| 254 | 266 | service: string, |
| 255 | 267 | values: Record<string, string | null>, |
| 256 | extra: { path: string; content: string }[] = [], | |
| 257 | say = "", | |
| 258 | ): Promise<{ ok: true; sha: string; says?: string } | { ok: false; error: string }> { | |
| 268 | ): Promise<{ ok: true; sha: string } | { ok: false; error: string }> { | |
| 259 | 269 | const secret = Object.keys(values).find((k) => SECRET_KEY.test(k)); |
| 260 | 270 | if (secret !== undefined) |
| 261 | 271 | return { |
| @@ -263,33 +273,23 @@ export async function commitServiceEnv( | ||
| 263 | 273 | 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.`, |
| 264 | 274 | }; |
| 265 | 275 | return commitCompose(app, user, box, { |
| 266 | message: `games: ${service} env: ${Object.keys(values).sort().join(", ")}${say === "" ? "" : ` (${say})`}`, | |
| 276 | message: `games: ${service} env: ${Object.keys(values).sort().join(", ")}`, | |
| 267 | 277 | what: "env", |
| 268 | 278 | edit: (text) => setServiceEnv(text, service, values), |
| 269 | extra, | |
| 270 | say, | |
| 271 | 279 | }); |
| 272 | 280 | } |
| 273 | 281 | |
| 274 | 282 | /** |
| 275 | 283 | * One commit of the compose file: `edit` makes the new text from the text at the branch's tip (it |
| 276 | 284 | * throws to refuse, with the reason), on `expectTip` when given, the commit a change was previewed |
| 277 | * on, so two changes never land on each other unseen. | |
| 285 | * on, so two changes never land on each other unseen. `extra` files (a lockfile) go in beside it. | |
| 278 | 286 | */ |
| 279 | 287 | export async function commitCompose( |
| 280 | 288 | app: App, |
| 281 | 289 | user: User, |
| 282 | 290 | box: GameBox, |
| 283 | change: { | |
| 284 | message: string; | |
| 285 | what: string; | |
| 286 | edit: (text: string) => string; | |
| 287 | expectTip?: string; | |
| 288 | /** Files committed beside the compose file (a lockfile), and what to say of the change. */ | |
| 289 | extra?: { path: string; content: string }[]; | |
| 290 | say?: string; | |
| 291 | }, | |
| 292 | ): Promise<{ ok: true; sha: string; says?: string } | { ok: false; error: string }> { | |
| 291 | change: { message: string; what: string; edit: (text: string) => string; expectTip?: string; extra?: readonly { path: string; content: string }[] }, | |
| 292 | ): Promise<{ ok: true; sha: string } | { ok: false; error: string }> { | |
| 293 | 293 | const compose = await readCompose(app, box); |
| 294 | 294 | if (compose === undefined) return { ok: false, error: `No ${box.path} on ${box.repo}@${box.branch}.` }; |
| 295 | 295 | if (change.expectTip !== undefined && change.expectTip !== compose.sha) |
| @@ -311,76 +311,20 @@ export async function commitCompose( | ||
| 311 | 311 | expectTip: compose.sha, |
| 312 | 312 | }); |
| 313 | 313 | return done.ok |
| 314 | ? { ok: true, sha: done.value.commitOid, ...(change.say === undefined || change.say === "" ? {} : { says: change.say }) } | |
| 314 | ? { ok: true, sha: done.value.commitOid } | |
| 315 | 315 | : { ok: false, error: `The commit was refused: ${JSON.stringify(done.error).slice(0, 200)}` }; |
| 316 | 316 | } |
| 317 | 317 | |
| 318 | /** PLUGINS (comma or newline separated URLs) and MODRINTH_PROJECTS of a service. */ | |
| 319 | export function pluginsOf(text: string, service: string): { plugins: string[]; modrinth: string[] } { | |
| 320 | const env = serviceEnv(text, service); | |
| 321 | const split = (v: string | undefined): string[] => (v ?? "").split(/[\s,]+/).filter(Boolean); | |
| 322 | return { plugins: split(env["PLUGINS"]), modrinth: split(env["MODRINTH_PROJECTS"]) }; | |
| 318 | /** The jar URLs in a service's PLUGINS (comma or newline separated). */ | |
| 319 | export function pluginUrls(text: string, service: string): string[] { | |
| 320 | return (serviceEnv(text, service)["PLUGINS"] ?? "").split(/[\s,]+/).filter(Boolean); | |
| 323 | 321 | } |
| 324 | 322 | |
| 325 | /** A service's Modrinth lockfile, beside the compose file: project, version id, sha512, path. */ | |
| 326 | export const lockPath = (box: GameBox, service: string): string => `${box.path.replace(/[^/]*$/, "")}${service}.modrinth-lock.json`; | |
| 327 | ||
| 328 | /** | |
| 329 | * What a door tells a person after `addPlugin`: the preview ("Would commit") or the commit, in one | |
| 330 | * wording. | |
| 331 | */ | |
| 332 | export function pluginSays(done: { ok: true; sha: string; says?: string }, dry: boolean): string { | |
| 333 | const tail = done.says === undefined ? "" : `: ${done.says}`; | |
| 334 | return dry ? `Would commit${tail}. Nothing is changed yet.` : `Committed ${done.sha.slice(0, 10)}${tail}.`; | |
| 335 | } | |
| 336 | ||
| 337 | /** | |
| 338 | * Add a plugin URL or a Modrinth slug to a service, by commit. A slug on a server whose TYPE and | |
| 339 | * VERSION are set is planned first (newest compatible version, required dependencies) and refused | |
| 340 | * with the reason when none runs here; the commit carries the lockfile. `dry` stops at the preview. | |
| 341 | */ | |
| 342 | export async function addPlugin( | |
| 343 | app: App, | |
| 344 | user: User, | |
| 345 | box: GameBox, | |
| 346 | service: string, | |
| 347 | add: { url?: string; modrinth?: string }, | |
| 348 | opts: { fetcher?: Fetcher; dry?: boolean } = {}, | |
| 349 | ): Promise<{ ok: true; sha: string; says?: string } | { ok: false; error: string }> { | |
| 323 | /** Add a jar URL (an uploaded jar's signed link) to a service's PLUGINS, by commit. */ | |
| 324 | export async function addPluginUrl(app: App, user: User, box: GameBox, service: string, url: string): Promise<{ ok: true; sha: string } | { ok: false; error: string }> { | |
| 350 | 325 | const compose = await readCompose(app, box); |
| 351 | 326 | if (compose === undefined) return { ok: false, error: `No ${box.path} on ${box.repo}@${box.branch}.` }; |
| 352 | const now = pluginsOf(compose.text, service); | |
| 353 | if (add.modrinth !== undefined) { | |
| 354 | if (!SLUG.test(add.modrinth)) return { ok: false, error: "A Modrinth project is its slug, like luckperms." }; | |
| 355 | if (now.modrinth.includes(add.modrinth)) return { ok: false, error: `${add.modrinth} is already there.` }; | |
| 356 | const target = targetOf(serviceEnv(compose.text, service)); | |
| 357 | if (target === undefined) { | |
| 358 | 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` }; | |
| 359 | return commitServiceEnv(app, user, box, service, { MODRINTH_PROJECTS: [...now.modrinth, add.modrinth].join(",") }); | |
| 360 | } | |
| 361 | const plan = await planInstall(add.modrinth, target, now.modrinth, opts.fetcher); | |
| 362 | if (!plan.ok) return { ok: false, error: `${add.modrinth} is not installed on ${target.loader} ${target.version}: ${plan.reason}` }; | |
| 363 | const says = previewOf(plan.adds); | |
| 364 | if (opts.dry === true) return { ok: true, sha: "", says }; | |
| 365 | const [owner = "", name = ""] = box.repo.split("/"); | |
| 366 | const repo = getRepo(app.db, owner, name); | |
| 367 | const at = lockPath(box, service); | |
| 368 | const had = repo === undefined ? undefined : await runGit(["show", `${compose.sha}:${at}`], { cwd: repoDir(app.reposRoot, repo.ownerName, repo.name) }); | |
| 369 | const slugs = plan.adds.map((a) => a.slug).filter((s) => !now.modrinth.includes(s)); | |
| 370 | return commitServiceEnv( | |
| 371 | app, | |
| 372 | user, | |
| 373 | box, | |
| 374 | service, | |
| 375 | { MODRINTH_PROJECTS: [...now.modrinth, ...slugs].join(",") }, | |
| 376 | [{ path: at, content: lockText(had?.ok ? had.value : undefined, plan.adds) }], | |
| 377 | says, | |
| 378 | ); | |
| 379 | } | |
| 380 | if (add.url !== undefined) { | |
| 381 | if (now.plugins.includes(add.url)) return { ok: false, error: "That plugin is already there." }; | |
| 382 | if (opts.dry === true) return { ok: true, sha: "", says: `adds the jar at ${add.url}` }; | |
| 383 | return commitServiceEnv(app, user, box, service, { PLUGINS: [...now.plugins, add.url].join(",") }); | |
| 384 | } | |
| 385 | return { ok: false, error: "Name a plugin." }; | |
| 327 | const now = pluginUrls(compose.text, service); | |
| 328 | if (now.includes(url)) return { ok: false, error: "That plugin is already there." }; | |
| 329 | return commitServiceEnv(app, user, box, service, { PLUGINS: [...now, url].join(",") }); | |
| 386 | 330 | } |
src/games/modrinth.ts +605 −175
| @@ -1,207 +1,637 @@ | ||
| 1 | 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). | |
| 2 | * Modrinth for a game server (forge games, G1 of #17284): search filtered by the server's loader, | |
| 3 | * the newest compatible version of a project with its required dependencies resolved, and updates | |
| 4 | * by file hash. The server's loader and game version come from its compose env (`targetOf`). | |
| 5 | * | |
| 6 | * One client for all of it: a real User-Agent with no personal data, answers cached (a version is | |
| 7 | * immutable, so kept for good; a search or a version list for minutes), and a budget under | |
| 8 | * Modrinth's 300 requests a minute that also obeys its `X-Ratelimit-*` headers. | |
| 7 | 9 | */ |
| 8 | 10 | |
| 9 | export type Fetcher = (url: string, init: { headers: Record<string, string>; signal?: AbortSignal }) => Promise<{ ok: boolean; status: number; json(): Promise<unknown> }>; | |
| 11 | import type { App } from "../app.ts"; | |
| 12 | import { announcedOr } from "../kernel/version.ts"; | |
| 13 | import { readCapped } from "../spawn/bounded_read.ts"; | |
| 14 | import { listArchive, zipEntry } from "../web/render/archive.ts"; | |
| 10 | 15 | |
| 11 | /** What a server runs: the loader Modrinth knows it by and its Minecraft version. */ | |
| 16 | export type Result<T> = { ok: true; value: T } | { ok: false; error: string }; | |
| 17 | ||
| 18 | const BASE = "https://api.modrinth.com"; | |
| 19 | const MAX_BODY = 4_000_000; | |
| 20 | /** Ours: Modrinth's own limit is 300 a minute per address; ten are kept back. */ | |
| 21 | const PER_MINUTE = 290; | |
| 22 | const CACHE_MOST = 600; | |
| 23 | ||
| 24 | // ---- the server: its loader and game version, from its compose env ---- | |
| 25 | ||
| 26 | /** What a server runs, as Modrinth sees it. */ | |
| 12 | 27 | export interface Target { |
| 13 | readonly loader: string; | |
| 14 | readonly version: string; | |
| 28 | /** Modrinth loaders whose projects run here, the server's own first. */ | |
| 29 | readonly loaders: readonly string[]; | |
| 30 | /** "plugin" (Paper, Velocity and kin) or "mod" (Fabric, Forge and kin). */ | |
| 31 | readonly kind: "plugin" | "mod"; | |
| 32 | /** Where the image puts the files. */ | |
| 33 | readonly dir: "plugins" | "mods"; | |
| 34 | /** The game version projects must support. */ | |
| 35 | readonly gameVersion: string; | |
| 36 | /** The server's own word for it when that is not a version (LATEST, or nothing). */ | |
| 37 | readonly versionSaid: string; | |
| 38 | /** A proxy (itzg/mc-proxy): its Modrinth step needs MINECRAFT_VERSION set. */ | |
| 39 | readonly proxy: boolean; | |
| 40 | /** "Paper 1.21.4": how the page names it. */ | |
| 41 | readonly label: string; | |
| 42 | /** It runs a Modrinth modpack (TYPE=MODRINTH): its mods are the pack's. */ | |
| 43 | readonly pack: boolean; | |
| 15 | 44 | } |
| 16 | 45 | |
| 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"], | |
| 46 | const LOADERS: Readonly<Record<string, { loaders: string[]; name: string; proxy?: true }>> = { | |
| 47 | PAPER: { loaders: ["paper", "bukkit", "spigot"], name: "Paper" }, | |
| 48 | PURPUR: { loaders: ["purpur", "paper", "bukkit", "spigot"], name: "Purpur" }, | |
| 49 | FOLIA: { loaders: ["folia"], name: "Folia" }, | |
| 50 | SPIGOT: { loaders: ["spigot", "bukkit"], name: "Spigot" }, | |
| 51 | BUKKIT: { loaders: ["bukkit"], name: "Bukkit" }, | |
| 52 | FABRIC: { loaders: ["fabric"], name: "Fabric" }, | |
| 53 | QUILT: { loaders: ["quilt", "fabric"], name: "Quilt" }, | |
| 54 | FORGE: { loaders: ["forge"], name: "Forge" }, | |
| 55 | NEOFORGE: { loaders: ["neoforge"], name: "NeoForge" }, | |
| 56 | VELOCITY: { loaders: ["velocity"], name: "Velocity", proxy: true }, | |
| 57 | BUNGEECORD: { loaders: ["bungeecord"], name: "BungeeCord", proxy: true }, | |
| 58 | WATERFALL: { loaders: ["waterfall", "bungeecord"], name: "Waterfall", proxy: true }, | |
| 56 | 59 | }; |
| 60 | const PLUGIN_LOADERS = new Set(["paper", "purpur", "folia", "spigot", "bukkit", "velocity", "bungeecord", "waterfall"]); | |
| 61 | const RELEASE = /^\d+\.\d+(?:\.\d+)?$/; | |
| 57 | 62 | |
| 58 | 63 | /** |
| 59 | * The target a service's env names, or why none can be named (then the image resolves it itself). | |
| 64 | * The server's target from its env: TYPE names the loader (the image's default, VANILLA, takes no | |
| 65 | * mods), VERSION (MINECRAFT_VERSION on a proxy) the game version; LATEST or nothing is the newest | |
| 66 | * release Modrinth knows, which `latest` answers. | |
| 60 | 67 | */ |
| 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.`; | |
| 68 | export function targetOf(env: Readonly<Record<string, string>>, latest: string): Result<Target> { | |
| 69 | const said0 = (env["TYPE"] ?? "VANILLA").trim().toUpperCase() || "VANILLA"; | |
| 70 | // A modpack server (TYPE=MODRINTH): the pack's loader, which MODRINTH_LOADER names. | |
| 71 | const pack = said0 === "MODRINTH"; | |
| 72 | const type = pack ? (env["MODRINTH_LOADER"] ?? "FABRIC").trim().toUpperCase() || "FABRIC" : said0; | |
| 73 | const l = LOADERS[type]; | |
| 74 | if (l === undefined) | |
| 75 | return { | |
| 76 | ok: false, | |
| 77 | error: `This server's TYPE is ${type}, which takes no Modrinth projects: set TYPE to PAPER or FABRIC (or another loader) first.`, | |
| 78 | }; | |
| 79 | const said = (l.proxy ? env["MINECRAFT_VERSION"] : env["VERSION"])?.trim() ?? ""; | |
| 80 | const gameVersion = RELEASE.test(said) ? said : latest; | |
| 81 | if (gameVersion === "") return { ok: false, error: "Modrinth did not say which Minecraft release is the newest; try again in a moment." }; | |
| 82 | const kind = PLUGIN_LOADERS.has(l.loaders[0]!) ? "plugin" : "mod"; | |
| 130 | 83 | 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}`, | |
| 84 | ok: true, | |
| 85 | value: { | |
| 86 | loaders: l.loaders, | |
| 87 | kind, | |
| 88 | dir: kind === "plugin" ? "plugins" : "mods", | |
| 89 | gameVersion, | |
| 90 | versionSaid: RELEASE.test(said) ? "" : said || "LATEST", | |
| 91 | proxy: l.proxy === true, | |
| 92 | label: `${l.name} ${gameVersion}`, | |
| 93 | pack, | |
| 94 | }, | |
| 139 | 95 | }; |
| 140 | 96 | } |
| 141 | 97 | |
| 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]; | |
| 98 | // ---- the client ---- | |
| 99 | ||
| 100 | interface Kept { | |
| 101 | readonly at: number; | |
| 102 | readonly ttl: number; | |
| 103 | readonly value: unknown; | |
| 104 | } | |
| 105 | /** Each forge's own cache and minute budget. */ | |
| 106 | interface Client { | |
| 107 | readonly cache: Map<string, Kept>; | |
| 108 | readonly asked: number[]; | |
| 109 | holdUntil: number; | |
| 110 | } | |
| 111 | const clients = new WeakMap<App, Client>(); | |
| 112 | const clientOf = (app: App): Client => { | |
| 113 | let c = clients.get(app); | |
| 114 | if (c === undefined) { | |
| 115 | c = { cache: new Map(), asked: [], holdUntil: 0 }; | |
| 116 | clients.set(app, c); | |
| 117 | } | |
| 118 | return c; | |
| 119 | }; | |
| 120 | ||
| 121 | const userAgent = (): string => `forge/${announcedOr()} (open-platform.sh)`; | |
| 122 | ||
| 123 | /** One call to Modrinth's API, cached for `ttlMs` (0: not cached), within the minute's budget. */ | |
| 124 | async function api<T>(app: App, path: string, ttlMs: number, body?: unknown): Promise<Result<T>> { | |
| 125 | const key = body === undefined ? path : `${path} ${JSON.stringify(body)}`; | |
| 126 | const now = Date.now(); | |
| 127 | const c = clientOf(app); | |
| 128 | const { cache, asked } = c; | |
| 129 | const kept = cache.get(key); | |
| 130 | if (kept !== undefined && now - kept.at < kept.ttl) { | |
| 131 | // Most recently used last, so the oldest is the one dropped. | |
| 132 | cache.delete(key); | |
| 133 | cache.set(key, kept); | |
| 134 | return { ok: true, value: kept.value as T }; | |
| 135 | } | |
| 136 | while (asked.length > 0 && now - asked[0]! > 60_000) asked.shift(); | |
| 137 | if (now < c.holdUntil || asked.length >= PER_MINUTE) { | |
| 138 | const wait = Math.max(1, Math.ceil(((now < c.holdUntil ? c.holdUntil : asked[0]! + 60_000) - now) / 1000)); | |
| 139 | return { ok: false, error: `Modrinth takes 300 requests a minute and this forge has used them; try again in ${String(wait)} s.` }; | |
| 140 | } | |
| 141 | asked.push(now); | |
| 142 | const f = app.config.modrinthFetch ?? fetch; | |
| 143 | let res: Response; | |
| 144 | try { | |
| 145 | res = await f(`${BASE}${path}`, { | |
| 146 | method: body === undefined ? "GET" : "POST", | |
| 147 | headers: { | |
| 148 | "user-agent": userAgent(), | |
| 149 | accept: "application/json", | |
| 150 | ...(body === undefined ? {} : { "content-type": "application/json" }), | |
| 151 | }, | |
| 152 | ...(body === undefined ? {} : { body: JSON.stringify(body) }), | |
| 153 | signal: AbortSignal.timeout(10_000), | |
| 154 | }); | |
| 155 | } catch { | |
| 156 | return { ok: false, error: "Modrinth did not answer in 10 s; try again." }; | |
| 157 | } | |
| 158 | if (res.headers.get("x-ratelimit-remaining") === "0") c.holdUntil = now + (Number(res.headers.get("x-ratelimit-reset")) || 60) * 1000; | |
| 159 | if (res.status === 404) return { ok: false, error: "Modrinth has no such project." }; | |
| 160 | if (res.status === 429) { | |
| 161 | c.holdUntil = now + (Number(res.headers.get("x-ratelimit-reset")) || 60) * 1000; | |
| 162 | return { ok: false, error: "Modrinth asked this forge to slow down; try again in a minute." }; | |
| 163 | } | |
| 164 | if (!res.ok) return { ok: false, error: `Modrinth answered ${String(res.status)}; try again.` }; | |
| 165 | const bytes = await readCapped(res, MAX_BODY); | |
| 166 | if (bytes === undefined) return { ok: false, error: "Modrinth's answer was too large to read." }; | |
| 167 | let value: T; | |
| 168 | try { | |
| 169 | value = JSON.parse(new TextDecoder().decode(bytes)) as T; | |
| 170 | } catch { | |
| 171 | return { ok: false, error: "Modrinth's answer was not JSON." }; | |
| 172 | } | |
| 173 | if (ttlMs > 0) { | |
| 174 | cache.set(key, { at: now, ttl: ttlMs, value }); | |
| 175 | while (cache.size > CACHE_MOST) cache.delete(cache.keys().next().value!); | |
| 176 | } | |
| 177 | return { ok: true, value }; | |
| 178 | } | |
| 179 | ||
| 180 | const q = (v: unknown): string => encodeURIComponent(JSON.stringify(v)); | |
| 181 | const MINUTE = 60_000; | |
| 182 | ||
| 183 | /** The newest release Minecraft version Modrinth knows ("" when it does not answer). */ | |
| 184 | export async function latestRelease(app: App): Promise<string> { | |
| 185 | const got = await api<{ version: string; version_type: string; date: string }[]>(app, "/v2/tag/game_version", 60 * MINUTE); | |
| 186 | if (!got.ok) return ""; | |
| 187 | return got.value.filter((v) => v.version_type === "release").sort((a, b) => b.date.localeCompare(a.date))[0]?.version ?? ""; | |
| 188 | } | |
| 189 | ||
| 190 | // ---- search ---- | |
| 191 | ||
| 192 | /** One search result, with whether it runs on this server. */ | |
| 193 | export interface Hit { | |
| 194 | readonly project: string; | |
| 195 | readonly slug: string; | |
| 196 | readonly title: string; | |
| 197 | readonly author: string; | |
| 198 | readonly description: string; | |
| 199 | readonly downloads: number; | |
| 200 | /** Runs on this server's loader and game version, server-side. */ | |
| 201 | readonly fits: boolean; | |
| 202 | /** Why not, in words, when it does not: "1.20.1 and older", "Client only". */ | |
| 203 | readonly why: string; | |
| 204 | } | |
| 205 | ||
| 206 | interface SearchHit { | |
| 207 | project_id: string; | |
| 208 | slug: string; | |
| 209 | title: string; | |
| 210 | author: string; | |
| 211 | description: string; | |
| 212 | downloads: number; | |
| 213 | versions?: string[]; | |
| 214 | categories?: string[]; | |
| 215 | server_side?: string; | |
| 216 | } | |
| 217 | ||
| 218 | /** Game versions newest first, as numbers compare: positive when `b` is the newer. */ | |
| 219 | export const byVersion = (a: string, b: string): number => { | |
| 220 | const pa = a.split(".").map(Number); | |
| 221 | const pb = b.split(".").map(Number); | |
| 222 | for (let i = 0; i < 3; i++) if ((pa[i] ?? 0) !== (pb[i] ?? 0)) return (pb[i] ?? 0) - (pa[i] ?? 0); | |
| 223 | return 0; | |
| 146 | 224 | }; |
| 147 | 225 | |
| 148 | 226 | /** |
| 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. | |
| 227 | * Environments a server runs (the `environment` facet; client_side and server_side are deprecated). | |
| 228 | * Plugins are server-side by nature, so a plugin search leaves it out. | |
| 151 | 229 | */ |
| 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"])); | |
| 230 | const SERVER_ENVIRONMENTS = [ | |
| 231 | "server_only", | |
| 232 | "server_only_client_optional", | |
| 233 | "dedicated_server_only", | |
| 234 | "client_and_server", | |
| 235 | "client_or_server", | |
| 236 | "client_or_server_prefers_both", | |
| 237 | ].map((e) => `environment:${e}`); | |
| 238 | ||
| 239 | /** | |
| 240 | * Projects for this server's loader matching `query` (the most downloaded when empty). The game | |
| 241 | * version is not a facet: a result for another version is shown, marked, so a search for | |
| 242 | * something that exists says why it will not run instead of finding nothing. | |
| 243 | */ | |
| 244 | export async function search(app: App, t: Target, query: string): Promise<Result<Hit[]>> { | |
| 245 | const facets = [t.loaders.map((l) => `categories:${l}`), ...(t.kind === "mod" ? [SERVER_ENVIRONMENTS] : [])]; | |
| 246 | const index = query.trim() === "" ? "downloads" : "relevance"; | |
| 247 | const got = await api<{ hits: SearchHit[] }>( | |
| 248 | app, | |
| 249 | `/v2/search?query=${encodeURIComponent(query.trim())}&facets=${q(facets)}&index=${index}&limit=20`, | |
| 250 | 5 * MINUTE, | |
| 251 | ); | |
| 252 | if (!got.ok) return got; | |
| 253 | return { | |
| 254 | ok: true, | |
| 255 | value: got.value.hits.map((h) => { | |
| 256 | const versions = (h.versions ?? []).filter((v) => RELEASE.test(v)).sort(byVersion); | |
| 257 | const clientOnly = h.server_side === "unsupported"; | |
| 258 | const fits = !clientOnly && (h.versions ?? []).includes(t.gameVersion); | |
| 259 | const newest = versions[0] ?? ""; | |
| 260 | const why = clientOnly | |
| 261 | ? "Client only" | |
| 262 | : fits | |
| 263 | ? "" | |
| 264 | : newest === "" | |
| 265 | ? `Not for ${t.gameVersion}` | |
| 266 | : byVersion(newest, t.gameVersion) > 0 | |
| 267 | ? `${newest} and older` | |
| 268 | : `Not for ${t.gameVersion}`; | |
| 269 | return { | |
| 270 | project: h.project_id, | |
| 271 | slug: h.slug, | |
| 272 | title: h.title, | |
| 273 | author: h.author, | |
| 274 | description: h.description, | |
| 275 | downloads: h.downloads, | |
| 276 | fits, | |
| 277 | why, | |
| 278 | }; | |
| 279 | }), | |
| 280 | }; | |
| 281 | } | |
| 282 | ||
| 283 | // ---- versions and the lock ---- | |
| 284 | ||
| 285 | interface VersionFile { | |
| 286 | url: string; | |
| 287 | filename: string; | |
| 288 | primary: boolean; | |
| 289 | hashes: { sha512?: string; sha1?: string }; | |
| 290 | } | |
| 291 | interface Dependency { | |
| 292 | version_id: string | null; | |
| 293 | project_id: string | null; | |
| 294 | dependency_type: "required" | "optional" | "incompatible" | "embedded"; | |
| 295 | } | |
| 296 | export interface Version { | |
| 297 | id: string; | |
| 298 | project_id: string; | |
| 299 | version_number: string; | |
| 300 | version_type: "release" | "beta" | "alpha"; | |
| 301 | date_published: string; | |
| 302 | game_versions: string[]; | |
| 303 | loaders: string[]; | |
| 304 | files: VersionFile[]; | |
| 305 | dependencies: Dependency[]; | |
| 306 | } | |
| 307 | export interface Project { | |
| 308 | id: string; | |
| 309 | slug: string; | |
| 310 | title: string; | |
| 311 | server_side?: string; | |
| 312 | } | |
| 313 | ||
| 314 | /** One pinned project: what the lockfile holds for it. */ | |
| 315 | export interface Locked { | |
| 316 | readonly project: string; | |
| 317 | readonly slug: string; | |
| 318 | readonly title: string; | |
| 319 | readonly version: string; | |
| 320 | readonly versionId: string; | |
| 321 | /** Where the image puts the file: plugins/<file> or mods/<file>. */ | |
| 322 | readonly path: string; | |
| 323 | readonly url: string; | |
| 324 | readonly sha512: string; | |
| 325 | /** Installed on purpose (false: there because another project requires it). */ | |
| 326 | readonly top: boolean; | |
| 327 | /** The projects this version requires. */ | |
| 328 | readonly requires: readonly string[]; | |
| 329 | /** The projects this version says it cannot run beside. */ | |
| 330 | readonly incompatible: readonly string[]; | |
| 331 | } | |
| 332 | ||
| 333 | const project = (app: App, idOrSlug: string): Promise<Result<Project>> => | |
| 334 | api<Project>(app, `/v2/project/${encodeURIComponent(idOrSlug)}`, 30 * MINUTE); | |
| 335 | const versionById = (app: App, id: string): Promise<Result<Version>> => | |
| 336 | api<Version>(app, `/v2/version/${encodeURIComponent(id)}`, 24 * 60 * MINUTE); | |
| 337 | ||
| 338 | /** The newest version of a project for this server: a release when there is one, else the newest. */ | |
| 339 | async function newest(app: App, t: Target, projectId: string): Promise<Result<Version | undefined>> { | |
| 340 | const got = await api<Version[]>( | |
| 341 | app, | |
| 342 | `/v2/project/${encodeURIComponent(projectId)}/version?loaders=${q(t.loaders)}&game_versions=${q([t.gameVersion])}&include_changelog=false`, | |
| 343 | 10 * MINUTE, | |
| 344 | ); | |
| 345 | if (!got.ok) return got; | |
| 346 | const usable = got.value | |
| 347 | .filter((v) => v.files.some((f) => f.hashes.sha512)) | |
| 348 | .sort((a, b) => b.date_published.localeCompare(a.date_published)); | |
| 349 | return { ok: true, value: usable.find((v) => v.version_type === "release") ?? usable[0] }; | |
| 350 | } | |
| 351 | ||
| 352 | function lockedOf(t: Target, p: Project, v: Version, top: boolean): Result<Locked> { | |
| 353 | const file = v.files.find((f) => f.primary) ?? v.files[0]; | |
| 354 | if (file === undefined || !file.hashes.sha512 || !/^[a-f0-9]{128}$/.test(file.hashes.sha512)) | |
| 355 | return { ok: false, error: `${p.title} ${v.version_number} has no file with a sha512 to pin.` }; | |
| 356 | // What goes into env and a path stays plain: a slug a comma or quote could split, a file name | |
| 357 | // that leaves its folder, or a download from anywhere but Modrinth's CDN is not offered. | |
| 358 | if (!/^[a-z0-9][a-z0-9_.-]{0,99}$/i.test(p.slug)) return { ok: false, error: `${p.title} has a name that cannot be written safely, so it is not offered.` }; | |
| 359 | if (!/^[\w.+() -]{1,120}\.jar$/.test(file.filename) || !file.url.startsWith("https://cdn.modrinth.com/")) | |
| 360 | return { ok: false, error: `${p.title} ${v.version_number}'s file cannot be verified, so it is not offered.` }; | |
| 361 | return { | |
| 362 | ok: true, | |
| 363 | value: { | |
| 364 | project: p.id, | |
| 365 | slug: p.slug, | |
| 366 | title: p.title, | |
| 367 | version: v.version_number, | |
| 368 | versionId: v.id, | |
| 369 | path: `${t.dir}/${file.filename}`, | |
| 370 | url: file.url, | |
| 371 | sha512: file.hashes.sha512, | |
| 372 | top, | |
| 373 | requires: v.dependencies.filter((d) => d.dependency_type === "required" && d.project_id).map((d) => d.project_id!), | |
| 374 | incompatible: v.dependencies.filter((d) => d.dependency_type === "incompatible" && d.project_id).map((d) => d.project_id!), | |
| 375 | }, | |
| 376 | }; | |
| 377 | } | |
| 378 | ||
| 379 | /** | |
| 380 | * The lock with `wanted` (project id or slug → a version, or undefined for the newest compatible) | |
| 381 | * in it, each with its required dependencies, recursively; what is already locked and not wanted | |
| 382 | * stays as it is. Refused, with the reason, when a project has no version for this server, a | |
| 383 | * required dependency has none, or two projects say they are incompatible. | |
| 384 | */ | |
| 385 | export async function resolve( | |
| 386 | app: App, | |
| 387 | t: Target, | |
| 388 | lock: readonly Locked[], | |
| 389 | wanted: readonly { project: string; version?: Version; top: boolean }[], | |
| 390 | ): Promise<Result<Locked[]>> { | |
| 391 | const out = new Map(lock.map((l) => [l.project, l])); | |
| 392 | const queue = [...wanted]; | |
| 393 | const seen = new Set<string>(); | |
| 394 | while (queue.length > 0) { | |
| 395 | if (seen.size > 60) return { ok: false, error: "The dependencies go deeper than 60 projects; that is not a set to install in one go." }; | |
| 396 | const w = queue.shift()!; | |
| 397 | const p = await project(app, w.project); | |
| 398 | if (!p.ok) return { ok: false, error: p.error === "Modrinth has no such project." ? `Modrinth has no project ${w.project}.` : p.error }; | |
| 399 | if (seen.has(p.value.id)) continue; | |
| 400 | seen.add(p.value.id); | |
| 401 | if (p.value.server_side === "unsupported") return { ok: false, error: `${p.value.title} is client-only: it does nothing on a server.` }; | |
| 402 | const had = out.get(p.value.id); | |
| 403 | // A dependency already locked stays as it is; a project asked for gets its newest. | |
| 404 | if (had !== undefined && w.version === undefined && !w.top) continue; | |
| 405 | let v = w.version; | |
| 406 | if (v === undefined) { | |
| 407 | const n = await newest(app, t, p.value.id); | |
| 408 | if (!n.ok) return n; | |
| 409 | if (n.value === undefined) | |
| 410 | return { | |
| 411 | ok: false, | |
| 412 | error: `${p.value.title} has no version for ${t.label}${w.top ? "" : `, and another project here requires it`}.`, | |
| 413 | }; | |
| 414 | v = n.value; | |
| 415 | } | |
| 416 | const locked = lockedOf(t, p.value, v, w.top || had?.top === true); | |
| 417 | if (!locked.ok) return locked; | |
| 418 | out.set(p.value.id, locked.value); | |
| 419 | for (const d of v.dependencies) { | |
| 420 | if (d.dependency_type !== "required") continue; | |
| 421 | if (d.version_id) { | |
| 422 | const dv = await versionById(app, d.version_id); | |
| 423 | if (!dv.ok) return dv; | |
| 424 | // A pinned dependency for another game version or loader: its newest that fits instead. | |
| 425 | const fits = dv.value.game_versions.includes(t.gameVersion) && dv.value.loaders.some((l) => t.loaders.includes(l)); | |
| 426 | queue.push({ project: dv.value.project_id, ...(fits ? { version: dv.value } : {}), top: false }); | |
| 427 | } else if (d.project_id) queue.push({ project: d.project_id, top: false }); | |
| 170 | 428 | } |
| 171 | } catch (e) { | |
| 172 | return { ok: false, reason: e instanceof Error ? e.message : String(e) }; | |
| 173 | 429 | } |
| 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(", ")}`; | |
| 430 | const all = [...out.values()]; | |
| 431 | for (const a of all) | |
| 432 | for (const b of a.incompatible) { | |
| 433 | const other = out.get(b); | |
| 434 | if (other !== undefined) | |
| 435 | return { ok: false, error: `${a.title} will not run beside ${other.title}: ${a.title} says they are incompatible.` }; | |
| 436 | } | |
| 437 | return { ok: true, value: all.sort((a, b) => a.slug.localeCompare(b.slug)) }; | |
| 180 | 438 | } |
| 181 | 439 | |
| 182 | 440 | /** |
| 183 | * A lock entry read back from a lockfile, or nothing when it lacks what the merge sorts and keys | |
| 184 | * on. | |
| 441 | * The newer versions Modrinth has for the locked files, by their sha512 (`POST | |
| 442 | * /v2/version_files/update`): releases for this server's loader and game version. | |
| 185 | 443 | */ |
| 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; | |
| 444 | export async function updates(app: App, t: Target, lock: readonly Locked[]): Promise<Result<{ from: Locked; to: Version }[]>> { | |
| 445 | if (lock.length === 0) return { ok: true, value: [] }; | |
| 446 | const got = await api<Record<string, Version>>(app, "/v2/version_files/update", 10 * MINUTE, { | |
| 447 | hashes: lock.map((l) => l.sha512), | |
| 448 | algorithm: "sha512", | |
| 449 | loaders: t.loaders, | |
| 450 | game_versions: [t.gameVersion], | |
| 451 | version_types: ["release"], | |
| 452 | }); | |
| 453 | if (!got.ok) return got; | |
| 454 | return { | |
| 455 | ok: true, | |
| 456 | value: lock.flatMap((l) => { | |
| 457 | const to = got.value[l.sha512]; | |
| 458 | return to !== undefined && to.id !== l.versionId ? [{ from: l, to }] : []; | |
| 459 | }), | |
| 460 | }; | |
| 190 | 461 | } |
| 191 | 462 | |
| 463 | // ---- modpacks (.mrpack) ---- | |
| 464 | ||
| 465 | /** Loaders a modpack can bring (the image installs the pack's own). */ | |
| 466 | const PACK_LOADERS = ["fabric", "quilt", "forge", "neoforge"]; | |
| 467 | ||
| 192 | 468 | /** |
| 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. | |
| 469 | * Modpacks for this server's loader matching `query`. A pack names its own game version, so none | |
| 470 | * is a facet; the image installs the pack's loader and Minecraft. | |
| 195 | 471 | */ |
| 196 | export function lockText(current: string | undefined, adds: readonly Locked[]): string { | |
| 197 | let parsed: unknown = []; | |
| 472 | export async function searchPacks(app: App, t: Target, query: string): Promise<Result<Hit[]>> { | |
| 473 | if (t.kind !== "mod") return { ok: false, error: `A modpack needs a mod server (Fabric, Quilt, Forge or NeoForge); this one is ${t.label}.` }; | |
| 474 | const loaders = t.loaders.filter((l) => PACK_LOADERS.includes(l)); | |
| 475 | const facets = [["project_type:modpack"], loaders.map((l) => `categories:${l}`)]; | |
| 476 | const got = await api<{ hits: SearchHit[] }>( | |
| 477 | app, | |
| 478 | `/v2/search?query=${encodeURIComponent(query.trim())}&facets=${q(facets)}&index=${query.trim() === "" ? "downloads" : "relevance"}&limit=20`, | |
| 479 | 5 * MINUTE, | |
| 480 | ); | |
| 481 | if (!got.ok) return got; | |
| 482 | return { | |
| 483 | ok: true, | |
| 484 | value: got.value.hits.map((h) => { | |
| 485 | const newest = (h.versions ?? []).filter((v) => RELEASE.test(v)).sort(byVersion)[0] ?? ""; | |
| 486 | return { project: h.project_id, slug: h.slug, title: h.title, author: h.author, description: h.description, downloads: h.downloads, fits: true, why: newest === "" ? "" : `Minecraft ${newest}` }; | |
| 487 | }), | |
| 488 | }; | |
| 489 | } | |
| 490 | ||
| 491 | /** One file of a pack, as the lock keeps it. */ | |
| 492 | export interface PackFile { | |
| 493 | readonly path: string; | |
| 494 | readonly url: string; | |
| 495 | readonly sha512: string; | |
| 496 | readonly server: string; | |
| 497 | } | |
| 498 | ||
| 499 | /** A modpack version, read from its .mrpack, as the lock keeps it. */ | |
| 500 | export interface LockedPack { | |
| 501 | readonly project: string; | |
| 502 | readonly slug: string; | |
| 503 | readonly title: string; | |
| 504 | readonly version: string; | |
| 505 | readonly versionId: string; | |
| 506 | /** The .mrpack itself. */ | |
| 507 | readonly url: string; | |
| 508 | readonly sha512: string; | |
| 509 | readonly minecraft: string; | |
| 510 | /** Modrinth's loader name (fabric, quilt, forge, neoforge) and its version. */ | |
| 511 | readonly loader: string; | |
| 512 | readonly loaderVersion: string; | |
| 513 | /** The files the server gets: every file whose env.server is not "unsupported". */ | |
| 514 | readonly files: readonly PackFile[]; | |
| 515 | /** The client-only files left out. */ | |
| 516 | readonly skipped: readonly string[]; | |
| 517 | /** Override files, as they land: overrides/ first, then server-overrides/ over them. */ | |
| 518 | readonly overrides: readonly { readonly path: string; readonly from: "overrides" | "server-overrides" }[]; | |
| 519 | } | |
| 520 | ||
| 521 | const PACK_MOST = 256 * 1024 * 1024; | |
| 522 | const INDEX_MOST = 16 * 1024 * 1024; | |
| 523 | const DEP_LOADERS: Readonly<Record<string, string>> = { "fabric-loader": "fabric", "quilt-loader": "quilt", forge: "forge", neoforge: "neoforge" }; | |
| 524 | ||
| 525 | interface PackIndex { | |
| 526 | formatVersion?: number; | |
| 527 | game?: string; | |
| 528 | files?: { path?: string; hashes?: { sha512?: string; sha1?: string }; env?: { server?: string }; downloads?: string[] }[]; | |
| 529 | dependencies?: Record<string, string>; | |
| 530 | } | |
| 531 | ||
| 532 | /** The newest release of a modpack for one of these loaders, with an .mrpack to read. */ | |
| 533 | export async function newestPack(app: App, t: Target, projectRef: string): Promise<Result<{ project: Project; version: Version }>> { | |
| 534 | const p = await project(app, projectRef); | |
| 535 | if (!p.ok) return { ok: false, error: p.error === "Modrinth has no such project." ? `Modrinth has no modpack ${projectRef}.` : p.error }; | |
| 536 | const loaders = t.loaders.filter((l) => PACK_LOADERS.includes(l)); | |
| 537 | const got = await api<Version[]>(app, `/v2/project/${encodeURIComponent(p.value.id)}/version?loaders=${q(loaders)}&include_changelog=false`, 10 * MINUTE); | |
| 538 | if (!got.ok) return got; | |
| 539 | const usable = got.value | |
| 540 | .filter((v) => v.files.some((f) => f.filename.endsWith(".mrpack") && f.hashes.sha512)) | |
| 541 | .sort((a, b) => b.date_published.localeCompare(a.date_published)); | |
| 542 | const v = usable.find((x) => x.version_type === "release") ?? usable[0]; | |
| 543 | if (v === undefined) return { ok: false, error: `${p.value.title} has no modpack version for ${loaders.join(" or ")}.` }; | |
| 544 | return { ok: true, value: { project: p.value, version: v } }; | |
| 545 | } | |
| 546 | ||
| 547 | const packs = new WeakMap<App, Map<string, LockedPack>>(); | |
| 548 | ||
| 549 | /** | |
| 550 | * Read a pack version's .mrpack (from Modrinth's CDN, checked against its sha512) into what the | |
| 551 | * lock keeps: the server's files, the client-only ones left out, and the overrides as they land. | |
| 552 | */ | |
| 553 | export async function readPack(app: App, p: { id: string; slug: string; title: string }, v: Version): Promise<Result<LockedPack>> { | |
| 554 | const file = v.files.find((f) => f.filename.endsWith(".mrpack") && f.primary) ?? v.files.find((f) => f.filename.endsWith(".mrpack")); | |
| 555 | if (file === undefined || !file.hashes.sha512) return { ok: false, error: `${p.title} ${v.version_number} has no .mrpack with a sha512.` }; | |
| 556 | const kept = packs.get(app)?.get(file.hashes.sha512); | |
| 557 | if (kept !== undefined) return { ok: true, value: kept }; | |
| 558 | if (!file.url.startsWith("https://cdn.modrinth.com/")) return { ok: false, error: `${p.title}'s .mrpack is not on Modrinth's CDN, so it is not read here.` }; | |
| 559 | let bytes: Uint8Array | undefined; | |
| 198 | 560 | 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)}`); | |
| 561 | const res = await (app.config.modrinthFetch ?? fetch)(file.url, { headers: { "user-agent": userAgent() }, signal: AbortSignal.timeout(120_000) }); | |
| 562 | if (!res.ok) return { ok: false, error: `Modrinth's CDN answered ${String(res.status)} for ${file.filename}.` }; | |
| 563 | bytes = await readCapped(res, PACK_MOST); | |
Medium (DoS): a whole .mrpack, up to 256 MB, is buffered in memory and sha512-hashed on the serving thread, and the web page triggers it from a GET ( |
||
| 564 | } catch { | |
| 565 | return { ok: false, error: `${file.filename} did not download in two minutes; try again.` }; | |
| 202 | 566 | } |
| 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`; | |
| 567 | if (bytes === undefined) return { ok: false, error: `${file.filename} is over 256 MB, too large to read here.` }; | |
| 568 | if (new Bun.CryptoHasher("sha512").update(bytes).digest("hex") !== file.hashes.sha512) | |
| 569 | return { ok: false, error: `${file.filename} does not match the sha512 Modrinth publishes for it; nothing was installed.` }; | |
| 570 | const indexBytes = zipEntry(bytes, "modrinth.index.json", INDEX_MOST); | |
| 571 | if (indexBytes === null) return { ok: false, error: `${file.filename} has no modrinth.index.json this forge can read.` }; | |
| 572 | let index: PackIndex; | |
| 573 | try { | |
| 574 | index = JSON.parse(new TextDecoder().decode(indexBytes)) as PackIndex; | |
| 575 | } catch { | |
| 576 | return { ok: false, error: `${file.filename}'s modrinth.index.json is not JSON.` }; | |
| 577 | } | |
| 578 | if (index.game !== "minecraft" || !Array.isArray(index.files)) return { ok: false, error: `${file.filename} is not a Minecraft modpack.` }; | |
| 579 | const deps = index.dependencies ?? {}; | |
| 580 | const minecraft = deps["minecraft"] ?? ""; | |
| 581 | const loaderKey = Object.keys(DEP_LOADERS).find((k) => deps[k] !== undefined); | |
| 582 | if (minecraft === "" || loaderKey === undefined) return { ok: false, error: `${file.filename} names no Minecraft version or no loader.` }; | |
| 583 | const files: PackFile[] = []; | |
| 584 | const skipped: string[] = []; | |
| 585 | for (const f of index.files) { | |
| 586 | const path = f.path ?? ""; | |
| 587 | if (path === "" || path.startsWith("/") || path.split("/").includes("..")) return { ok: false, error: `${file.filename} has a file outside the server (${path}); it is refused.` }; | |
| 588 | if (f.env?.server === "unsupported") { | |
| 589 | skipped.push(path); | |
| 590 | continue; | |
| 591 | } | |
| 592 | const url = f.downloads?.[0] ?? ""; | |
| 593 | if (!f.hashes?.sha512 || url === "") return { ok: false, error: `${path} in ${file.filename} has no download or no sha512.` }; | |
| 594 | files.push({ path, url, sha512: f.hashes.sha512, server: f.env?.server ?? "required" }); | |
| 595 | } | |
| 596 | const listing = listArchive(bytes, { entries: 50_000 }); | |
| 597 | if ("error" in listing) return { ok: false, error: listing.error }; | |
| 598 | const landed = new Map<string, "overrides" | "server-overrides">(); | |
| 599 | for (const from of ["overrides", "server-overrides"] as const) | |
| 600 | for (const e of listing.entries) if (!e.dir && e.path.startsWith(`${from}/`)) landed.set(e.path.slice(from.length + 1), from); | |
| 601 | const pack: LockedPack = { | |
| 602 | project: p.id, | |
| 603 | slug: p.slug, | |
| 604 | title: p.title, | |
| 605 | version: v.version_number, | |
| 606 | versionId: v.id, | |
| 607 | url: file.url, | |
| 608 | sha512: file.hashes.sha512, | |
| 609 | minecraft, | |
| 610 | loader: DEP_LOADERS[loaderKey]!, | |
| 611 | loaderVersion: deps[loaderKey]!, | |
| 612 | files: files.sort((a, b) => a.path.localeCompare(b.path)), | |
| 613 | skipped: skipped.sort(), | |
| 614 | overrides: [...landed].map(([path, from]) => ({ path, from })).sort((a, b) => a.path.localeCompare(b.path)), | |
| 615 | }; | |
| 616 | let mine = packs.get(app); | |
| 617 | if (mine === undefined) { | |
| 618 | mine = new Map(); | |
| 619 | packs.set(app, mine); | |
| 620 | } | |
| 621 | mine.set(pack.sha512, pack); | |
| 622 | if (mine.size > 20) mine.delete(mine.keys().next().value!); | |
| 623 | return { ok: true, value: pack }; | |
| 624 | } | |
| 625 | ||
| 626 | /** A newer release of the locked pack, by the .mrpack's sha512 (any game version: the pack picks). */ | |
| 627 | export async function packUpdate(app: App, pack: LockedPack): Promise<Result<Version | undefined>> { | |
| 628 | const got = await api<Record<string, Version>>(app, "/v2/version_files/update", 10 * MINUTE, { | |
| 629 | hashes: [pack.sha512], | |
| 630 | algorithm: "sha512", | |
| 631 | loaders: [pack.loader], | |
| 632 | version_types: ["release"], | |
| 633 | }); | |
| 634 | if (!got.ok) return got; | |
| 635 | const to = got.value[pack.sha512]; | |
| 636 | return { ok: true, value: to !== undefined && to.id !== pack.versionId ? to : undefined }; | |
| 207 | 637 | } |
src/games/mods.ts added +370
| @@ -0,0 +1,370 @@ | ||
| 1 | /** | |
| 2 | * A server's Modrinth projects (forge games, G1 of #17284), one model for the page, the terminal | |
| 3 | * and the games MCP tool: what is installed (a lockfile per service in the network repo), what | |
| 4 | * would change (a plan: install, update or remove, previewed in words), and the one commit that | |
| 5 | * makes it so (the lockfile and the compose env together). | |
| 6 | * | |
| 7 | * The lockfile, `<compose dir>/modrinth/<service>.lock.json`, pins each project to a version id | |
| 8 | * with its file's url, path and sha512. The compose env feeds the itzg image from it: | |
| 9 | * MODRINTH_PROJECTS lists `slug:versionId` for every project, dependencies included, and | |
| 10 | * MODRINTH_DOWNLOAD_DEPENDENCIES=none, so the image fetches exactly what is locked and nothing it | |
| 11 | * resolves itself. The image's helper checks each download against the sha512 Modrinth publishes | |
| 12 | * for that version (and fetches again, then fails, on a mismatch); a version's files never change, | |
| 13 | * so that is the hash locked here. It cannot be handed a hash of our own. | |
| 14 | * | |
| 15 | * Sleep (`sleep.ts`) keeps AutoStopper in the proxy's MODRINTH_PROJECTS, pinned and checked there: | |
| 16 | * a change here carries it over untouched and never lists it as one of the server's own. | |
| 17 | */ | |
| 18 | ||
| 19 | import type { App } from "../app.ts"; | |
| 20 | import type { User } from "../core/users.ts"; | |
| 21 | import { commitCompose, pluginUrls, readCompose, readRepoFile, serviceEnv, setServiceEnv } from "./compose.ts"; | |
| 22 | import { byVersion, latestRelease, newestPack, packUpdate, readPack, resolve, targetOf, updates, type Locked, type LockedPack, type Result, type Target, type Version } from "./modrinth.ts"; | |
| 23 | import { AUTOSTOPPER } from "./sleep.ts"; | |
| 24 | import type { GameBox } from "./store.ts"; | |
| 25 | ||
| 26 | /** What a service has, as its repository says at the compose file's commit. */ | |
| 27 | export interface Mods { | |
| 28 | readonly target: Target; | |
| 29 | readonly lock: readonly Locked[]; | |
| 30 | /** MODRINTH_PROJECTS entries the lock does not pin (written by hand, or before the lock). */ | |
| 31 | readonly loose: readonly string[]; | |
| 32 | /** MODRINTH_PROJECTS entries another part of the forge writes (sleep's AutoStopper), kept as they are. */ | |
| 33 | readonly held: readonly string[]; | |
| 34 | /** Jar URLs in PLUGINS (uploaded jars among them). */ | |
| 35 | readonly urls: readonly string[]; | |
| 36 | /** The commit it was read at: a plan commits on top of it or not at all. */ | |
| 37 | readonly sha: string; | |
| 38 | readonly env: Readonly<Record<string, string>>; | |
| 39 | /** The modpack the server runs (TYPE=MODRINTH), every file of it locked. */ | |
| 40 | readonly pack: LockedPack | undefined; | |
| 41 | } | |
| 42 | ||
| 43 | /** A change, previewed: its lines in words, and what the commit writes. */ | |
| 44 | export interface Plan { | |
| 45 | readonly lines: readonly string[]; | |
| 46 | readonly lock: readonly Locked[]; | |
| 47 | readonly env: Readonly<Record<string, string | null>>; | |
| 48 | readonly message: string; | |
| 49 | readonly sha: string; | |
| 50 | readonly done: string; | |
| 51 | /** The modpack the lock holds after it (undefined: as it was). */ | |
| 52 | readonly pack?: LockedPack; | |
| 53 | } | |
| 54 | ||
| 55 | /** The lockfile's path for a service, beside the compose file. */ | |
| 56 | export function lockPath(box: GameBox, service: string): string { | |
| 57 | const dir = box.path.includes("/") ? box.path.slice(0, box.path.lastIndexOf("/") + 1) : ""; | |
| 58 | return `${dir}modrinth/${service}.lock.json`; | |
| 59 | } | |
| 60 | ||
| 61 | const split = (v: string | undefined): string[] => (v ?? "").split(/[\s,]+/).filter(Boolean); | |
| 62 | const pin = (l: Locked): string => `${l.slug}:${l.versionId}`; | |
| 63 | ||
| 64 | /** The pack a lockfile holds, when its shape is the forge's. */ | |
| 65 | function parsePack(doc: { pack?: unknown }): LockedPack | undefined { | |
| 66 | const p = doc.pack as Record<string, unknown> | undefined; | |
| 67 | if (typeof p !== "object" || p === null) return undefined; | |
| 68 | const strings = ["project", "slug", "title", "version", "versionId", "url", "sha512", "minecraft", "loader", "loaderVersion"]; | |
| 69 | if (!strings.every((k) => typeof p[k] === "string") || !Array.isArray(p["files"])) return undefined; | |
| 70 | return { ...(p as unknown as LockedPack), skipped: Array.isArray(p["skipped"]) ? (p["skipped"] as string[]) : [], overrides: Array.isArray(p["overrides"]) ? (p["overrides"] as LockedPack["overrides"]) : [] }; | |
| 71 | } | |
| 72 | ||
| 73 | /** A lockfile's projects and pack; empty when it is missing or not the forge's. */ | |
| 74 | export function parseLock(text: string | undefined): { projects: Locked[]; pack: LockedPack | undefined } { | |
| 75 | if (text === undefined) return { projects: [], pack: undefined }; | |
| 76 | try { | |
| 77 | const doc = JSON.parse(text) as { projects?: unknown; pack?: unknown }; | |
| 78 | const pack = parsePack(doc); | |
| 79 | if (!Array.isArray(doc.projects)) return { projects: [], pack }; | |
| 80 | const projects = doc.projects | |
| 81 | .filter( | |
| 82 | (p): p is Locked => | |
| 83 | typeof p === "object" && | |
| 84 | p !== null && | |
| 85 | ["project", "slug", "title", "version", "versionId", "path", "url", "sha512"].every( | |
| 86 | (k) => typeof (p as Record<string, unknown>)[k] === "string", | |
| 87 | ), | |
| 88 | ) | |
| 89 | .map((p) => ({ | |
| 90 | ...p, | |
| 91 | top: p.top !== false, | |
| 92 | requires: Array.isArray(p.requires) ? p.requires : [], | |
| 93 | incompatible: Array.isArray(p.incompatible) ? p.incompatible : [], | |
| 94 | })); | |
| 95 | return { projects, pack }; | |
| 96 | } catch { | |
| 97 | return { projects: [], pack: undefined }; | |
| 98 | } | |
| 99 | } | |
| 100 | ||
| 101 | function lockText(t: Target, lock: readonly Locked[], pack: LockedPack | undefined): string { | |
| 102 | return `${JSON.stringify( | |
| 103 | { | |
| 104 | about: | |
| 105 | "Modrinth projects for this server, written by the forge: each pinned to a version and its file's sha512. MODRINTH_PROJECTS in the compose file is made from it; a modpack's every file is listed under pack, and MODRINTH_MODPACK and MODRINTH_VERSION pin it.", | |
| 106 | server: pack === undefined ? t.label : `${pack.title} ${pack.version} (Minecraft ${pack.minecraft}, ${pack.loader} ${pack.loaderVersion})`, | |
| 107 | loaders: pack === undefined ? t.loaders : [pack.loader], | |
| 108 | gameVersion: pack === undefined ? t.gameVersion : pack.minecraft, | |
| 109 | projects: lock, | |
| 110 | ...(pack === undefined ? {} : { pack }), | |
| 111 | }, | |
| 112 | null, | |
| 113 | 2, | |
| 114 | )}\n`; | |
| 115 | } | |
| 116 | ||
| 117 | /** The service's Modrinth state; refused with the reason when it takes no projects. */ | |
| 118 | export async function modsOf(app: App, box: GameBox, service: string): Promise<Result<Mods>> { | |
| 119 | const compose = await readCompose(app, box); | |
| 120 | if (compose === undefined) return { ok: false, error: `No ${box.path} on ${box.repo}@${box.branch}.` }; | |
| 121 | const env = serviceEnv(compose.text, service); | |
| 122 | const said = env["VERSION"] ?? env["MINECRAFT_VERSION"] ?? ""; | |
| 123 | const target = targetOf(env, /^\d+\.\d+/.test(said) ? "" : await latestRelease(app)); | |
| 124 | if (!target.ok) return target; | |
| 125 | const { projects: lock, pack } = parseLock(await readRepoFile(app, box, compose.sha, lockPath(box, service))); | |
| 126 | const pinned = new Set(lock.map(pin)); | |
| 127 | return { | |
| 128 | ok: true, | |
| 129 | value: { | |
| 130 | target: target.value, | |
| 131 | lock, | |
| 132 | loose: split(env["MODRINTH_PROJECTS"]).filter((e) => !pinned.has(e) && e !== AUTOSTOPPER), | |
| 133 | held: split(env["MODRINTH_PROJECTS"]).filter((e) => e === AUTOSTOPPER), | |
| 134 | urls: pluginUrls(compose.text, service), | |
| 135 | sha: compose.sha, | |
| 136 | env, | |
| 137 | pack: target.value.pack ? pack : undefined, | |
| 138 | }, | |
| 139 | }; | |
| 140 | } | |
| 141 | ||
| 142 | /** A loose entry that is a bare slug (no loader prefix, version, list file or optional mark). */ | |
| 143 | const bareSlug = (e: string): boolean => /^[a-z0-9][a-z0-9_.-]{0,99}$/i.test(e); | |
| 144 | ||
| 145 | /** The env a lock makes, keeping the loose entries it did not take over. */ | |
| 146 | function envFor(m: Mods, lock: readonly Locked[], kept: readonly string[]): Record<string, string | null> { | |
| 147 | const projects = [...lock.map(pin), ...kept, ...m.held]; | |
| 148 | return { | |
| 149 | MODRINTH_PROJECTS: projects.length === 0 ? null : projects.join(","), | |
| 150 | MODRINTH_DOWNLOAD_DEPENDENCIES: lock.length === 0 ? null : "none", | |
| 151 | // A proxy's Modrinth step will not run without MINECRAFT_VERSION. | |
| 152 | ...(m.target.proxy && !/^\d+\.\d+/.test(m.env["MINECRAFT_VERSION"] ?? "") && lock.length > 0 | |
| 153 | ? { MINECRAFT_VERSION: m.target.gameVersion } | |
| 154 | : {}), | |
| 155 | }; | |
| 156 | } | |
| 157 | ||
| 158 | /** The lines that say how `next` differs from `m.lock`, newest first in the order a person reads. */ | |
| 159 | function diffLines(m: Mods, next: readonly Locked[], adopted: ReadonlySet<string>): string[] { | |
| 160 | const was = new Map(m.lock.map((l) => [l.project, l])); | |
| 161 | const now = new Map(next.map((l) => [l.project, l])); | |
| 162 | const by = (l: Locked): string => { | |
| 163 | const needs = next.filter((o) => o.requires.includes(l.project)).map((o) => o.title); | |
| 164 | return needs.length === 0 ? "" : ` (required by ${needs.join(", ")})`; | |
| 165 | }; | |
| 166 | const lines: string[] = []; | |
| 167 | for (const l of next) { | |
| 168 | const before = was.get(l.project); | |
| 169 | if (before === undefined) | |
| 170 | lines.push( | |
| 171 | adopted.has(l.slug) | |
| 172 | ? `Pins ${l.title} ${l.version} (it was in MODRINTH_PROJECTS unpinned)` | |
| 173 | : `Adds ${l.title} ${l.version}${l.top ? "" : by(l)}`, | |
| 174 | ); | |
| 175 | else if (before.versionId !== l.versionId) lines.push(`Updates ${l.title} ${before.version} → ${l.version}`); | |
| 176 | } | |
| 177 | for (const l of m.lock) | |
| 178 | if (!now.has(l.project)) lines.push(`Removes ${l.title} ${l.version}${l.top ? "" : " (nothing left requires it)"}`); | |
| 179 | if (m.target.proxy && !/^\d+\.\d+/.test(m.env["MINECRAFT_VERSION"] ?? "") && next.length > 0) | |
| 180 | lines.push(`Sets MINECRAFT_VERSION=${m.target.gameVersion}: the proxy's Modrinth step needs it`); | |
| 181 | if (m.target.versionSaid !== "" && !m.target.proxy) | |
| 182 | lines.push( | |
| 183 | `VERSION is ${m.target.versionSaid}: these are for ${m.target.gameVersion}; set VERSION=${m.target.gameVersion} so the next Minecraft release does not outrun them`, | |
| 184 | ); | |
| 185 | lines.push(`Restarts the server with the new set on the box's next sync`); | |
| 186 | return lines; | |
| 187 | } | |
| 188 | ||
| 189 | const find = (lock: readonly Locked[], ref: string): Locked | undefined => | |
| 190 | lock.find((l) => l.project === ref || l.slug === ref.toLowerCase()); | |
| 191 | ||
| 192 | /** Install `ref` (a project id or slug): its newest version for this server and what it requires. */ | |
| 193 | export async function planInstall(app: App, m: Mods, service: string, ref: string): Promise<Result<Plan>> { | |
| 194 | if (m.target.pack) | |
| 195 | return { ok: false, error: `This server runs ${m.pack === undefined ? "a modpack" : `the modpack ${m.pack.title}`}; its mods are the pack's, and extra mods on top of a pack come later.` }; | |
| 196 | const wantedRef = ref.trim(); | |
| 197 | if (!/^[A-Za-z0-9][A-Za-z0-9_.-]{0,99}$/.test(wantedRef)) | |
| 198 | return { ok: false, error: "Name a Modrinth project by its slug or id, like luckperms." }; | |
| 199 | const had = find(m.lock, wantedRef); | |
| 200 | if (had?.top) return { ok: false, error: `${had.title} ${had.version} is installed.` }; | |
| 201 | // A bare slug already in MODRINTH_PROJECTS is taken into the lock, pinned, with this change. | |
| 202 | const adopt = m.loose.filter(bareSlug); | |
| 203 | const kept = m.loose.filter((e) => !bareSlug(e)); | |
| 204 | const got = await resolve(app, m.target, m.lock, [ | |
| 205 | { project: had?.project ?? wantedRef, top: true }, | |
| 206 | ...adopt.filter((s) => s.toLowerCase() !== wantedRef.toLowerCase()).map((s) => ({ project: s, top: true })), | |
| 207 | ]); | |
| 208 | if (!got.ok) return got; | |
| 209 | const added = | |
| 210 | got.value.find((l) => l.project === had?.project || l.slug === wantedRef.toLowerCase() || l.project === wantedRef) ?? | |
| 211 | got.value.find((l) => !m.lock.some((o) => o.project === l.project)); | |
| 212 | const deps = got.value.filter((l) => !l.top && !m.lock.some((o) => o.project === l.project)).length; | |
| 213 | const title = added === undefined ? wantedRef : `${added.title} ${added.version}`; | |
| 214 | return { | |
| 215 | ok: true, | |
| 216 | value: { | |
| 217 | lines: diffLines(m, got.value, new Set(adopt)), | |
| 218 | lock: got.value, | |
| 219 | env: envFor(m, got.value, kept), | |
| 220 | message: `games: ${service} mods: add ${title}${deps === 0 ? "" : ` and ${String(deps)} ${deps === 1 ? "dependency" : "dependencies"}`}`, | |
| 221 | sha: m.sha, | |
| 222 | done: `${title} is installed${deps === 0 ? "" : ` with ${String(deps)} ${deps === 1 ? "dependency" : "dependencies"}`}`, | |
| 223 | }, | |
| 224 | }; | |
| 225 | } | |
| 226 | ||
| 227 | /** The updates Modrinth has for the locked projects, as from → to. */ | |
| 228 | export async function updatesOf(app: App, m: Mods): Promise<Result<{ from: Locked; to: Version }[]>> { | |
| 229 | return updates(app, m.target, m.lock); | |
| 230 | } | |
| 231 | ||
| 232 | /** Update `ref` (or every project, for "all") to the newest release, with any new requirement. */ | |
| 233 | export async function planUpdate(app: App, m: Mods, service: string, ref: string): Promise<Result<Plan>> { | |
| 234 | const ups = await updatesOf(app, m); | |
| 235 | if (!ups.ok) return ups; | |
| 236 | const picked = ref === "all" ? ups.value : ups.value.filter((u) => u.from.project === ref || u.from.slug === ref.toLowerCase()); | |
| 237 | if (picked.length === 0) | |
| 238 | return { ok: false, error: ref === "all" ? "Everything is up to date." : `${ref} is up to date, or not installed here.` }; | |
| 239 | const got = await resolve( | |
| 240 | app, | |
| 241 | m.target, | |
| 242 | m.lock, | |
| 243 | picked.map((u) => ({ project: u.from.project, version: u.to, top: u.from.top })), | |
| 244 | ); | |
| 245 | if (!got.ok) return got; | |
| 246 | const what = picked.length === 1 ? `${picked[0]!.from.title} ${picked[0]!.to.version_number}` : `${String(picked.length)} projects`; | |
| 247 | return { | |
| 248 | ok: true, | |
| 249 | value: { | |
| 250 | lines: diffLines(m, got.value, new Set()), | |
| 251 | lock: got.value, | |
| 252 | env: envFor(m, got.value, m.loose), | |
| 253 | message: `games: ${service} mods: update ${what}`, | |
| 254 | sha: m.sha, | |
| 255 | done: `Updated ${what}`, | |
| 256 | }, | |
| 257 | }; | |
| 258 | } | |
| 259 | ||
| 260 | /** Remove `ref`, and what it alone required. A dependency something else requires stays. */ | |
| 261 | export async function planRemove(m: Mods, service: string, ref: string): Promise<Result<Plan>> { | |
| 262 | const gone = find(m.lock, ref.trim()); | |
| 263 | if (gone === undefined) return { ok: false, error: `${ref} is not installed here.` }; | |
| 264 | const needs = m.lock.filter((o) => o.project !== gone.project && o.requires.includes(gone.project)).map((o) => o.title); | |
| 265 | if (needs.length > 0) | |
| 266 | return { | |
| 267 | ok: false, | |
| 268 | error: `${gone.title} is there because ${needs.join(" and ")} ${needs.length === 1 ? "requires" : "require"} it; remove that first.`, | |
| 269 | }; | |
| 270 | let next = m.lock.filter((l) => l.project !== gone.project); | |
| 271 | // Then whatever only it required, until nothing else drops out. | |
| 272 | for (;;) { | |
| 273 | const orphan = next.find((l) => !l.top && !next.some((o) => o.requires.includes(l.project))); | |
| 274 | if (orphan === undefined) break; | |
| 275 | next = next.filter((l) => l !== orphan); | |
| 276 | } | |
| 277 | return { | |
| 278 | ok: true, | |
| 279 | value: { | |
| 280 | lines: diffLines(m, next, new Set()), | |
| 281 | lock: next, | |
| 282 | env: envFor(m, next, m.loose), | |
| 283 | message: `games: ${service} mods: remove ${gone.title}`, | |
| 284 | sha: m.sha, | |
| 285 | done: `${gone.title} is removed`, | |
| 286 | }, | |
| 287 | }; | |
| 288 | } | |
| 289 | ||
| 290 | /** Commit a plan: the lockfile and the compose env together, on the commit it was planned on. */ | |
| 291 | export async function commitPlan(app: App, user: User, box: GameBox, service: string, m: Mods, plan: Plan): Promise<Result<string>> { | |
| 292 | const done = await commitCompose(app, user, box, { | |
| 293 | message: plan.message, | |
| 294 | what: service, | |
| 295 | edit: (text) => setServiceEnv(text, service, plan.env), | |
| 296 | extra: [{ path: lockPath(box, service), content: lockText(m.target, plan.lock, plan.pack ?? m.pack) }], | |
| 297 | expectTip: plan.sha, | |
| 298 | }); | |
| 299 | return done.ok ? { ok: true, value: done.sha } : done; | |
| 300 | } | |
| 301 | ||
| 302 | const LOADER_NAMES: Readonly<Record<string, string>> = { fabric: "Fabric Loader", quilt: "Quilt Loader", forge: "Forge", neoforge: "NeoForge" }; | |
| 303 | ||
| 304 | /** The plan that puts `pack` on the server: the image installs its loader, files and overrides. */ | |
| 305 | function packPlan(m: Mods, service: string, pack: LockedPack, verb: "install" | "update"): Plan { | |
| 306 | const before = m.pack; | |
| 307 | const was = before?.minecraft ?? m.target.gameVersion; | |
| 308 | const lines = [ | |
| 309 | before === undefined | |
| 310 | ? `Installs the modpack ${pack.title} ${pack.version}: Minecraft ${pack.minecraft} with ${LOADER_NAMES[pack.loader] ?? pack.loader} ${pack.loaderVersion}` | |
| 311 | : before.versionId === pack.versionId | |
| 312 | ? `Keeps the modpack ${pack.title} ${pack.version}` | |
| 313 | : `${before.project === pack.project ? "Updates" : "Replaces"} the modpack ${before.title} ${before.version} → ${pack.title} ${pack.version}`, | |
| 314 | `${String(pack.files.length)} ${pack.files.length === 1 ? "file" : "files"} from the pack, each locked with its sha512${pack.skipped.length === 0 ? "" : ` (${String(pack.skipped.length)} client-only left out)`}`, | |
| 315 | ...(pack.overrides.length === 0 ? [] : [`${String(pack.overrides.length)} override ${pack.overrides.length === 1 ? "file" : "files"}: overrides/, then server-overrides/ over them`]), | |
| 316 | ...(was === pack.minecraft | |
| 317 | ? [] | |
| 318 | : [`Changes Minecraft ${was} → ${pack.minecraft}${byVersion(pack.minecraft, was) > 0 ? ": a world saved by a newer Minecraft may not open in an older one" : ""}`]), | |
| 319 | ...(m.lock.length === 0 ? [] : [`Removes ${m.lock.map((l) => l.title).join(", ")}: a modpack server takes its mods from the pack`]), | |
| 320 | ...(m.loose.length === 0 ? [] : [`Drops ${m.loose.join(", ")} from MODRINTH_PROJECTS`]), | |
| 321 | "The image does not check a pack's file hashes; the lockfile keeps each one, so any change shows in review", | |
| 322 | "Restarts the server with the pack on the box's next sync", | |
| 323 | ]; | |
| 324 | return { | |
| 325 | lines, | |
| 326 | lock: [], | |
| 327 | pack, | |
| 328 | env: { | |
| 329 | TYPE: "MODRINTH", | |
| 330 | MODRINTH_MODPACK: pack.slug, | |
| 331 | MODRINTH_VERSION: pack.versionId, | |
| 332 | MODRINTH_LOADER: pack.loader, | |
| 333 | VERSION: pack.minecraft, | |
| 334 | MODRINTH_PROJECTS: null, | |
| 335 | MODRINTH_DOWNLOAD_DEPENDENCIES: null, | |
| 336 | FABRIC_LOADER_VERSION: null, | |
| 337 | QUILT_LOADER_VERSION: null, | |
| 338 | }, | |
| 339 | message: `games: ${service} modpack: ${verb} ${pack.title} ${pack.version}`, | |
| 340 | sha: m.sha, | |
| 341 | done: `${pack.title} ${pack.version} is the server's modpack`, | |
| 342 | }; | |
| 343 | } | |
| 344 | ||
| 345 | /** Put a modpack (its newest release for the server's loader) on a mod server, every file locked. */ | |
| 346 | export async function planPack(app: App, m: Mods, service: string, ref: string): Promise<Result<Plan>> { | |
| 347 | if (!/^[A-Za-z0-9][A-Za-z0-9_.-]{0,99}$/.test(ref.trim())) return { ok: false, error: "Name a Modrinth modpack by its slug or id." }; | |
| 348 | const found = await newestPack(app, m.target, ref.trim()); | |
| 349 | if (!found.ok) return found; | |
| 350 | if (m.pack?.versionId === found.value.version.id) return { ok: false, error: `${m.pack.title} ${m.pack.version} is the server's modpack.` }; | |
| 351 | const pack = await readPack(app, found.value.project, found.value.version); | |
| 352 | if (!pack.ok) return pack; | |
| 353 | return { ok: true, value: packPlan(m, service, pack.value, "install") }; | |
| 354 | } | |
| 355 | ||
| 356 | /** The newer release of the server's modpack, if Modrinth has one. */ | |
| 357 | export async function packUpdateOf(app: App, m: Mods): Promise<Result<Version | undefined>> { | |
| 358 | return m.pack === undefined ? { ok: true, value: undefined } : packUpdate(app, m.pack); | |
| 359 | } | |
| 360 | ||
| 361 | /** Update the server's modpack to its newest release. */ | |
| 362 | export async function planPackUpdate(app: App, m: Mods, service: string): Promise<Result<Plan>> { | |
| 363 | if (m.pack === undefined) return { ok: false, error: "This server runs no modpack." }; | |
| 364 | const to = await packUpdateOf(app, m); | |
| 365 | if (!to.ok) return to; | |
| 366 | if (to.value === undefined) return { ok: false, error: `${m.pack.title} ${m.pack.version} is the newest release.` }; | |
| 367 | const pack = await readPack(app, { id: m.pack.project, slug: m.pack.slug, title: m.pack.title }, to.value); | |
| 368 | if (!pack.ok) return pack; | |
| 369 | return { ok: true, value: packPlan(m, service, pack.value, "update") }; | |
| 370 | } |
src/games/pack_check.ts added +103
| @@ -0,0 +1,103 @@ | ||
| 1 | /** | |
| 2 | * A modpack's files, checked on the box (forge games, G1 of #17284). The image installs a pack | |
| 3 | * without checking any file's hash, so once a pack server is up and healthy on the compose it was | |
| 4 | * given, the forge asks its agent once (`hashes`: a sha512 prefix of each jar under /data/mods) | |
| 5 | * and compares the answer with the lockfile at that commit. The verdict replaces the raw list as | |
| 6 | * the command's output: "Pack files: 212 verified, 1 differs (sodium.jar)". | |
| 7 | */ | |
| 8 | ||
| 9 | import type { App } from "../app.ts"; | |
| 10 | import { composeServices, readCompose, readRepoFile, serviceEnv } from "./compose.ts"; | |
| 11 | import { lockPath, parseLock } from "./mods.ts"; | |
| 12 | import { queueCommand, type GameBox, type SyncBody } from "./store.ts"; | |
| 13 | ||
| 14 | /** Boxes and compose commits whose pack servers all have their check queued. */ | |
| 15 | const asked = new WeakMap<App, Set<string>>(); | |
| 16 | ||
| 17 | const HASH = /^([0-9a-f]{32})\s+(\S.*)$/; | |
| 18 | const names = (paths: readonly string[]): string => { | |
| 19 | const base = paths.map((p) => p.split("/").at(-1)!); | |
| 20 | return base.length <= 5 ? base.join(", ") : `${base.slice(0, 5).join(", ")} and ${String(base.length - 5)} more`; | |
| 21 | }; | |
| 22 | ||
| 23 | /** The verdict on one answer: the lock's mods/ jars against what the box listed. */ | |
| 24 | export function packVerdict(expected: readonly { path: string; sha512: string }[], ok: boolean, output: string): string { | |
| 25 | if (!ok) | |
| 26 | return /not a command this agent runs/.test(output) | |
| 27 | ? "Pack files are not checked: the box's agent is older than this check, and checks them once it updates." | |
| 28 | : `Pack files could not be checked: ${output.split("\n").find((l) => l.trim() !== "")?.slice(0, 200) ?? "no answer"}`; | |
| 29 | const seen = new Map<string, string>(); | |
| 30 | for (const line of output.split("\n")) { | |
| 31 | const m = HASH.exec(line.trim()); | |
| 32 | if (m) seen.set(m[2]!, m[1]!); | |
| 33 | } | |
| 34 | const jars = expected.filter((f) => f.path.startsWith("mods/") && f.path.endsWith(".jar")); | |
| 35 | const differ = jars.filter((f) => seen.has(f.path) && seen.get(f.path) !== f.sha512.slice(0, 32)).map((f) => f.path); | |
| 36 | const missing = jars.filter((f) => !seen.has(f.path)).map((f) => f.path); | |
| 37 | const extra = [...seen.keys()].filter((p) => !jars.some((f) => f.path === p)); | |
| 38 | const verified = jars.length - differ.length - missing.length; | |
| 39 | return [ | |
| 40 | `Pack files: ${String(verified)} verified`, | |
| 41 | differ.length === 0 ? "" : `, ${String(differ.length)} ${differ.length === 1 ? "differs" : "differ"} (${names(differ)})`, | |
| 42 | missing.length === 0 ? "" : `, ${String(missing.length)} missing (${names(missing)})`, | |
| 43 | extra.length === 0 ? "" : `, ${String(extra.length)} not in the lock (${names(extra)})`, | |
| 44 | output.length >= 15_900 ? "; the list was cut short" : "", | |
| 45 | ].join(""); | |
| 46 | } | |
| 47 | ||
| 48 | /** | |
| 49 | * After a sync: turn each pack check the box answered into its verdict, and ask for one where a | |
| 50 | * pack server is up and healthy on the current compose and has none yet. | |
| 51 | */ | |
| 52 | export async function packChecks(app: App, box: GameBox, body: SyncBody): Promise<void> { | |
| 53 | const ids = (body.results ?? []).map((r) => (typeof r.id === "string" ? r.id : "")).filter((id) => id !== "").slice(0, 64); | |
| 54 | const answered = ids | |
| 55 | .map((id) => | |
| 56 | app.db | |
| 57 | .query<{ id: string; service: string; text: string; ok: number | null; output: string }, [string, string]>( | |
| 58 | "SELECT id, service, text, ok, output FROM game_command WHERE id = ?1 AND box_id = ?2 AND kind = 'hashes' AND done_at != ''", | |
| 59 | ) | |
| 60 | .get(id, box.id), | |
| 61 | ) | |
| 62 | .filter((r) => r !== null); | |
| 63 | for (const r of answered) { | |
| 64 | const sha = /^compose (\S+)$/.exec(r.text)?.[1] ?? ""; | |
| 65 | const lock = parseLock(await readRepoFile(app, box, sha, lockPath(box, r.service))); | |
| 66 | app.db.query("UPDATE game_command SET output = ?2 WHERE id = ?1").run(r.id, packVerdict(lock.pack?.files ?? [], r.ok === 1, r.output)); | |
| 67 | } | |
| 68 | const running = typeof body.composeSha === "string" ? body.composeSha : ""; | |
| 69 | if (running === "") return; | |
| 70 | const key = `${box.id}:${running}`; | |
| 71 | let mine = asked.get(app); | |
| 72 | if (mine === undefined) { | |
| 73 | mine = new Set(); | |
| 74 | asked.set(app, mine); | |
| 75 | } | |
| 76 | if (mine.has(key)) return; | |
| 77 | const compose = await readCompose(app, box); | |
| 78 | if (compose === undefined || compose.sha !== running) return; | |
| 79 | const packs = composeServices(compose.text).filter((s) => (serviceEnv(compose.text, s)["TYPE"] ?? "").toUpperCase() === "MODRINTH"); | |
| 80 | let waiting = false; | |
| 81 | for (const service of packs) { | |
| 82 | const had = app.db.query<{ n: number }, [string, string, string]>("SELECT count(*) AS n FROM game_command WHERE box_id = ?1 AND service = ?2 AND kind = 'hashes' AND text = ?3").get(box.id, service, `compose ${running}`); | |
| 83 | if ((had?.n ?? 0) > 0) continue; | |
| 84 | // Up and healthy: the image installs the pack before the server starts answering. | |
| 85 | const s = (body.services ?? []).find((x) => x.name === service); | |
| 86 | if (s?.state !== "running" || (s.health !== "healthy" && s.health !== "" && s.health !== undefined)) { | |
| 87 | waiting = true; | |
| 88 | continue; | |
| 89 | } | |
| 90 | queueCommand(app.db, box.id, service, "hashes", `compose ${running}`, ""); | |
| 91 | } | |
| 92 | if (!waiting) mine.add(key); | |
| 93 | } | |
| 94 | ||
| 95 | /** The latest verdict for each pack server of a box: "survival: Pack files: 212 verified". */ | |
| 96 | export function packCheckLines(app: App, boxId: string): string[] { | |
| 97 | return app.db | |
| 98 | .query<{ service: string; output: string }, [string]>( | |
| 99 | "SELECT service, output FROM game_command c WHERE box_id = ?1 AND kind = 'hashes' AND done_at != '' AND done_at = (SELECT max(done_at) FROM game_command d WHERE d.box_id = c.box_id AND d.kind = 'hashes' AND d.service = c.service AND d.done_at != '') ORDER BY service", | |
| 100 | ) | |
| 101 | .all(boxId) | |
| 102 | .map((r) => `${r.service}: ${r.output}`); | |
| 103 | } |
src/games/store.ts +4 −3
| @@ -23,9 +23,9 @@ export const SERVICE_NAME = /^[a-z0-9][a-z0-9_.-]{0,63}$/; | ||
| 23 | 23 | /** The most log lines kept a service; the oldest go first. */ |
| 24 | 24 | export const LOG_KEEP = 2_000; |
| 25 | 25 | const LINES_A_SYNC = 200; |
| 26 | /** The most of a command's output kept: a shell's 16 KB (`shell.ts`); the rest say far less. */ | |
| 26 | /** The most of a command's output kept: a shell's 16 KB (`shell.ts`) and a pack's hash list (`hashes`); the rest say far less. */ | |
| 27 | 27 | const OUTPUT_MAX = 16_384; |
| 28 | export const COMMAND_KINDS = ["rcon", "restart", "stop", "start", "recreate", "pull", "shell", "people", "world"] as const; | |
| 28 | export const COMMAND_KINDS = ["rcon", "restart", "stop", "start", "recreate", "pull", "shell", "people", "world", "hashes"] as const; | |
| 29 | 29 | export type CommandKind = (typeof COMMAND_KINDS)[number]; |
| 30 | 30 | export type Role = "owner" | "operator" | "viewer"; |
| 31 | 31 | const RANK: Record<Role, number> = { viewer: 1, operator: 2, owner: 3 }; |
| @@ -311,7 +311,8 @@ export const commandHistory = (db: Database, boxId: string, service: string, lim | ||
| 311 | 311 | export const recentCommands = (db: Database, boxId: string, service: string, limit = 10): CommandState[] => |
| 312 | 312 | db |
| 313 | 313 | .query<{ id: string }, [string, string, number]>( |
| 314 | "SELECT id FROM game_command WHERE box_id = ?1 AND service = ?2 ORDER BY created_at DESC LIMIT ?3", | |
| 314 | // A pack check (`hashes`) is the forge's own, not a person's; it is said on the box, not here. | |
| 315 | "SELECT id FROM game_command WHERE box_id = ?1 AND service = ?2 AND kind != 'hashes' ORDER BY created_at DESC LIMIT ?3", | |
| 315 | 316 | ) |
| 316 | 317 | .all(boxId, service, limit) |
| 317 | 318 | .map((r) => commandOf(db, r.id)!); |
src/http/games_routes.ts +8 −2
| @@ -9,11 +9,12 @@ import { synced } from "../games/notify.ts"; | ||
| 9 | 9 | import { auditShellResults } from "../games/shell.ts"; |
| 10 | 10 | import { recordMetrics } from "../games/metrics.ts"; |
| 11 | 11 | import { recordPeople } from "../games/people.ts"; |
| 12 | import { packChecks } from "../games/pack_check.ts"; | |
| 12 | 13 | import { sleeping } from "../games/sleep.ts"; |
| 13 | 14 | import { boxByToken, envFiles, markAsleep, recordSync, signJarUrls, type SyncBody } from "../games/store.ts"; |
| 14 | 15 | import { BODY_CAPS } from "../kernel/body_caps.ts"; |
| 15 | 16 | import { |
| 16 | gameBoxPage, gameCommandSubmit, gameCrashShare, gameEnvSubmit, gameGrantSubmit, gameJarDownload, gameJarSubmit, gamePluginSubmit, gamePeopleSubmit, gameHead, gameWorldSubmit, gamePowerSubmit, gameSleepSubmit, gameServicePage, gameSettingsSubmit, gameServiceStream, gameShellStream, gameShellSubmit, gamesPage, | |
| 17 | gameBoxPage, gameCommandSubmit, gameCrashShare, gameEnvSubmit, gameGrantSubmit, gameJarDownload, gameJarSubmit, gameModInstall, gameModPack, gameModRemove, gameModUpdate, gamePeopleSubmit, gameHead, gameWorldSubmit, gamePowerSubmit, gameSleepSubmit, gameServicePage, gameSettingsSubmit, gameServiceStream, gameShellStream, gameShellSubmit, gamesPage, | |
| 17 | 18 | } from "../web/pages/games.ts"; |
| 18 | 19 | import type { Ctx, Handler } from "./context.ts"; |
| 19 | 20 | import { InvalidJson } from "./json_body.ts"; |
| @@ -42,6 +43,8 @@ export async function gameAgentSync(ctx: Ctx): Promise<Response> { | ||
| 42 | 43 | auditShellResults(ctx.app, box, (body.results ?? []).map((r) => r.id)); |
| 43 | 44 | recordMetrics(ctx.app.db, box, body); |
| 44 | 45 | recordPeople(ctx.app.db, box, body.people); |
| 46 | // A pack server's files against its lockfile: the answers judged, a check asked where one is due. | |
| 47 | if (body.boot === undefined) await packChecks(ctx.app, box, body); | |
| 45 | 48 | const compose = await readCompose(ctx.app, box); |
| 46 | 49 | // A server its sleep stopped is asleep, not down: the compose file says which sleep. |
| 47 | 50 | markAsleep(ctx.app.db, box.id, compose === undefined ? [] : sleeping(compose.text)); |
| @@ -85,7 +88,10 @@ export function gamesRoutes(router: Router<Handler>): void { | ||
| 85 | 88 | router.add("POST", "/games/:box/:service/command", gameCommandSubmit); |
| 86 | 89 | router.add("POST", "/games/:box/:service/power", gamePowerSubmit); |
| 87 | 90 | router.add("POST", "/games/:box/:service/env", gameEnvSubmit); |
| 88 | router.add("POST", "/games/:box/:service/plugin", gamePluginSubmit); | |
| 91 | router.add("POST", "/games/:box/:service/mods/install", gameModInstall); | |
| 92 | router.add("POST", "/games/:box/:service/mods/update", gameModUpdate); | |
| 93 | router.add("POST", "/games/:box/:service/mods/remove", gameModRemove); | |
| 94 | router.add("POST", "/games/:box/:service/mods/pack", gameModPack); | |
| 89 | 95 | router.add("POST", "/games/:box/:service/sleep", gameSleepSubmit); |
| 90 | 96 | router.add("POST", "/games/:box/:service/people", gamePeopleSubmit); |
| 91 | 97 | router.add("POST", "/games/:box/:service/world", gameWorldSubmit); |
src/http/lazy_lists.ts +4 −1
| @@ -617,7 +617,10 @@ export const OPERATIONS_ROUTES = [ | ||
| 617 | 617 | ["POST", "/games/:box/:service/command"], |
| 618 | 618 | ["POST", "/games/:box/:service/power"], |
| 619 | 619 | ["POST", "/games/:box/:service/env"], |
| 620 | ["POST", "/games/:box/:service/plugin"], | |
| 620 | ["POST", "/games/:box/:service/mods/install"], | |
| 621 | ["POST", "/games/:box/:service/mods/update"], | |
| 622 | ["POST", "/games/:box/:service/mods/remove"], | |
| 623 | ["POST", "/games/:box/:service/mods/pack"], | |
| 621 | 624 | ["POST", "/games/:box/:service/sleep"], |
| 622 | 625 | ["POST", "/games/:box/:service/people"], |
| 623 | 626 | ["POST", "/games/:box/:service/world"], |
src/http/mcp/tools/games.ts +71 −14
| @@ -1,5 +1,8 @@ | ||
| 1 | 1 | import { cloudLineFresh, pinnedOfBox } from "../../../actions/cloud_says.ts"; |
| 2 | import { addPlugin, pluginSays, commitServiceEnv } from "../../../games/compose.ts"; | |
| 2 | import { commitServiceEnv } from "../../../games/compose.ts"; | |
| 3 | import { search, searchPacks } from "../../../games/modrinth.ts"; | |
| 4 | import { packCheckLines } from "../../../games/pack_check.ts"; | |
| 5 | import { commitPlan, modsOf, packUpdateOf, planInstall, planPack, planPackUpdate, planRemove, planUpdate, updatesOf } from "../../../games/mods.ts"; | |
| 3 | 6 | import { boxStatus, boxStatusShared } from "../../../games/diag.ts"; |
| 4 | 7 | import { commitSettings, previewSettings, serviceSettings } from "../../../games/settings.ts"; |
| 5 | 8 | import { compactMetrics, compactSeries } from "../../../games/metrics_answer.ts"; |
| @@ -16,12 +19,12 @@ const POWER = ["start", "stop", "restart", "recreate", "pull"]; | ||
| 16 | 19 | export const tool: Tool = { |
| 17 | 20 | name: "games", |
| 18 | 21 | listedTo: "admin", |
| 19 | doc: "`{ action, box?, service?, text?, kind?, key?, value?, modrinth?, preview?, dryRun?, window?, url?, snapshot? }`: game boxes. `list` (with each service's world snapshots); `metrics` per service (now, 1h, 24h), or one `service` over `window` (1h to 30d); `sleep` sets a `service` to `value` warm or sleep (stops when empty, starts on join), a commit; `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); `world` `op` import (a world from `url`, a .zip or .tar.gz with level.dat; the world it had is kept first), restore (`snapshot`) or snapshot, a job whose steps the box reports; `people` with `op` list (online, whitelist, ops, bans, who is where, the latest joins, deaths and chat) or op, deop, whitelist-add, whitelist-remove, whitelist-on, whitelist-off, ban, pardon, kick for `player`, or move `player` to `to`; `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", | |
| 20 | description: "Game boxes: list, metrics, console, power, env, plugins, people, settings, sleep, worlds.", | |
| 22 | doc: "`{ action, box?, service?, text?, kind?, key?, value?, query?, project?, dryRun?, window?, url?, snapshot? }`: game boxes. `list` (with each service's world snapshots); `metrics` per service (now, 1h, 24h), or one `service` over `window` (1h to 30d); `sleep` sets a `service` to `value` warm or sleep (stops when empty, starts on join), a commit; `console` queues `text` as RCON; `power` `kind` (start, stop, restart); `env` commits `key`=`value` (empty removes); `mods` lists a server's Modrinth projects and updates; `mods_search` searches `query` for its loader (each says whether it runs there); `mods_pack_search` searches modpacks; `mods_install`, `mods_update` (`project` or all; the modpack on a pack server), `mods_remove` and `mods_pack` (a modpack, every file locked) plan first (the lines it would change, dependencies included) and commit with `dryRun: false`; `world` `op` import (a world from `url`, a .zip or .tar.gz with level.dat; the world it had is kept first), restore (`snapshot`) or snapshot, a job whose steps the box reports; `people` with `op` list (online, whitelist, ops, bans, who is where, the latest joins, deaths and chat) or op, deop, whitelist-add, whitelist-remove, whitelist-on, whitelist-off, ban, pardon, kick for `player`, or move `player` to `to`; `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", | |
| 23 | description: "Game boxes: list, metrics, console, power, env, Modrinth mods, people, settings, sleep, worlds.", | |
| 21 | 24 | inputSchema: { |
| 22 | 25 | type: "object", |
| 23 | 26 | properties: { |
| 24 | action: { type: "string", enum: ["list", "metrics", "console", "power", "env", "plugin", "people", "config", "config_set", "sleep", "world"] }, | |
| 27 | action: { type: "string", enum: ["list", "metrics", "console", "power", "env", "mods", "mods_search", "mods_pack_search", "mods_install", "mods_update", "mods_remove", "mods_pack", "people", "config", "config_set", "sleep", "world"] }, | |
| 25 | 28 | op: { type: "string", enum: ["list", ...PEOPLE_OPS, "import", "restore", "snapshot"] }, |
| 26 | 29 | player: { type: "string", maxLength: 17 }, |
| 27 | 30 | to: { type: "string", maxLength: 64 }, |
| @@ -34,19 +37,17 @@ export const tool: Tool = { | ||
| 34 | 37 | kind: { type: "string", enum: POWER }, |
| 35 | 38 | key: { type: "string", maxLength: 100 }, |
| 36 | 39 | value: { type: "string", maxLength: 2000 }, |
| 37 | modrinth: { type: "string", maxLength: 100 }, | |
| 38 | preview: { type: "boolean" }, | |
| 40 | query: { type: "string", maxLength: 200 }, | |
| 41 | project: { type: "string", maxLength: 100 }, | |
| 39 | 42 | dryRun: { type: "boolean" }, |
| 40 | 43 | }, |
| 41 | 44 | required: ["action"], |
| 42 | 45 | }, |
| 43 | 46 | writes: true, |
| 44 | 47 | heldNotWhen: (args) => |
| 45 | args["action"] === "list" || | |
| 46 | args["action"] === "metrics" || | |
| 48 | ["list", "metrics", "mods", "mods_search", "mods_pack_search", "config"].includes(String(args["action"])) || | |
| 47 | 49 | (args["action"] === "people" && args["op"] === "list") || |
| 48 | args["action"] === "config" || | |
| 49 | (args["action"] === "config_set" && args["dryRun"] !== false), | |
| 50 | ((String(args["action"]).startsWith("mods_") || args["action"] === "config_set") && args["dryRun"] !== false), | |
| 50 | 51 | async run(ctx, user, args) { |
| 51 | 52 | const action = str(args["action"]); |
| 52 | 53 | const db = ctx.app.db; |
| @@ -69,6 +70,7 @@ export const tool: Tool = { | ||
| 69 | 70 | // The box's state in words, at most three lines: the owner's own, anyone else's naming |
| 70 | 71 | // no container, image, error or journal. |
| 71 | 72 | status: (mayDo(roleOn(db, user, b.id), "owner") ? boxStatus(b.diag) : boxStatusShared(b.diag)).slice(0, 3), |
| 73 | packFiles: packCheckLines(ctx.app, b.id), | |
| 72 | 74 | ...(cloud[i] === undefined ? {} : { cloud: cloud[i] }), |
| 73 | 75 | services: servicesOf(db, b.id).filter((s) => mayDo(roleOn(db, user, b.id, s.name), "viewer")), |
| 74 | 76 | snapshots: Object.fromEntries(Object.entries(b.snapshots).filter(([s]) => mayDo(roleOn(db, user, b.id, s), "viewer")).map(([s, list]) => [s, list.slice(0, 10)])), |
| @@ -120,9 +122,64 @@ export const tool: Tool = { | ||
| 120 | 122 | const done = await commitServiceEnv(ctx.app, user, box, service, { [str(args["key"])]: value === "" ? null : value }); |
| 121 | 123 | return done.ok ? good({ says: `Committed ${done.sha.slice(0, 10)}.`, sha: done.sha }) : bad("refused", done.error); |
| 122 | 124 | } |
| 123 | if (action === "plugin") { | |
| 124 | const done = await addPlugin(ctx.app, user, box, service, { modrinth: str(args["modrinth"]) }, { dry: args["preview"] === true }); | |
| 125 | return done.ok ? good({ says: pluginSays(done, args["preview"] === true), sha: done.sha }) : bad("refused", done.error); | |
| 125 | if (action.startsWith("mods")) { | |
| 126 | const mods = await modsOf(ctx.app, box, service); | |
| 127 | if (!mods.ok) return bad("refused", mods.error); | |
| 128 | const m = mods.value; | |
| 129 | if (action === "mods") { | |
| 130 | const [ups, packUp] = await Promise.all([updatesOf(ctx.app, m), packUpdateOf(ctx.app, m)]); | |
| 131 | return good({ | |
| 132 | ...(m.pack === undefined | |
| 133 | ? {} | |
| 134 | : { | |
| 135 | modpack: { | |
| 136 | project: m.pack.slug, | |
| 137 | title: m.pack.title, | |
| 138 | version: m.pack.version, | |
| 139 | minecraft: m.pack.minecraft, | |
| 140 | loader: `${m.pack.loader} ${m.pack.loaderVersion}`, | |
| 141 | files: m.pack.files.length, | |
| 142 | overrides: m.pack.overrides.length, | |
| 143 | skipped: m.pack.skipped.length, | |
| 144 | ...(packUp.ok && packUp.value !== undefined ? { update: packUp.value.version_number } : {}), | |
| 145 | }, | |
| 146 | }), | |
| 147 | server: m.target.label, | |
| 148 | installed: m.lock.map((l) => ({ project: l.slug, title: l.title, version: l.version, path: l.path, sha512: l.sha512, dependency: !l.top })), | |
| 149 | unpinned: m.loose, | |
| 150 | jars: m.urls, | |
| 151 | updates: ups.ok ? ups.value.map((u) => ({ project: u.from.slug, from: u.from.version, to: u.to.version_number })) : [], | |
| 152 | ...(ups.ok ? {} : { updatesError: ups.error }), | |
| 153 | }); | |
| 154 | } | |
| 155 | if (action === "mods_pack_search") { | |
| 156 | const got = await searchPacks(ctx.app, m.target, str(args["query"])); | |
| 157 | return got.ok ? good({ server: m.target.label, items: got.value }) : bad("refused", got.error); | |
| 158 | } | |
| 159 | if (action === "mods_search") { | |
| 160 | const got = await search(ctx.app, m.target, str(args["query"])); | |
| 161 | return got.ok ? good({ server: m.target.label, items: got.value }) : bad("refused", got.error); | |
| 162 | } | |
| 163 | const project = str(args["project"]); | |
| 164 | const planned = | |
| 165 | action === "mods_install" | |
| 166 | ? await planInstall(ctx.app, m, service, project) | |
| 167 | : action === "mods_update" | |
| 168 | ? m.target.pack && (project === "" || project === "all" || project === "pack") | |
| 169 | ? await planPackUpdate(ctx.app, m, service) | |
| 170 | : await planUpdate(ctx.app, m, service, project || "all") | |
| 171 | : action === "mods_pack" | |
| 172 | ? await planPack(ctx.app, m, service, project) | |
| 173 | : action === "mods_remove" | |
| 174 | ? await planRemove(m, service, project) | |
| 175 | : undefined; | |
| 176 | if (planned === undefined) return bad("bad_action", "action is mods, mods_search, mods_pack_search, mods_install, mods_update, mods_remove or mods_pack"); | |
| 177 | if (!planned.ok) return bad("refused", planned.error); | |
| 178 | if (args["dryRun"] !== false) return good({ planned: true, says: "This is the plan; send dryRun: false to commit it.", lines: planned.value.lines }); | |
| 179 | const done = await commitPlan(ctx.app, user, box, service, m, planned.value); | |
| 180 | return done.ok | |
| 181 | ? good({ says: `${planned.value.done} (${done.value.slice(0, 10)}); the server restarts with it on the box's next sync.`, sha: done.value, lines: planned.value.lines }) | |
| 182 | : bad("refused", done.error); | |
| 126 | 183 | } |
| 127 | 184 | if (action === "people") { |
| 128 | 185 | const op = str(args["op"]); |
| @@ -162,6 +219,6 @@ export const tool: Tool = { | ||
| 162 | 219 | ? good({ says: "Queued; the box runs it on its next sync and reports each step.", id: queued.id, ...(op === "import" ? { from: linkShown(str(args["url"])) } : {}) }) |
| 163 | 220 | : bad("refused", queued.error); |
| 164 | 221 | } |
| 165 | return bad("bad_action", "action is list, metrics, console, power, env, plugin, people, config, config_set, sleep or world"); | |
| 222 | return bad("bad_action", "action is list, metrics, console, power, env, mods, mods_search, mods_pack_search, mods_install, mods_update, mods_remove, mods_pack, people, config, config_set, sleep or world"); | |
| 166 | 223 | }, |
| 167 | 224 | }; |
src/tui/screens/game_mods.ts added +144
| @@ -0,0 +1,144 @@ | ||
| 1 | /** | |
| 2 | * A game server's Modrinth projects in the terminal (forge games, G1 of #17284), the page's model | |
| 3 | * (`games/mods.ts`): updates as from → to, what is installed, and a search for the server's loader | |
| 4 | * where each result says whether it runs here. `/` searches, `a` previews an install (what it | |
| 5 | * adds and what that requires) by a result's number or a slug, `u` previews updating everything, | |
| 6 | * `d` previews a removal, `p` previews a modpack (every file locked); `y` commits the preview | |
| 7 | * shown and `n` drops it. | |
| 8 | */ | |
| 9 | ||
| 10 | import { search, type Hit, type Result } from "../../games/modrinth.ts"; | |
| 11 | import { commitPlan, modsOf, packUpdateOf, planInstall, planPack, planPackUpdate, planRemove, planUpdate, updatesOf, type Mods, type Plan } from "../../games/mods.ts"; | |
| 12 | import { mayDo, roleOn, type GameBox } from "../../games/store.ts"; | |
| 13 | import type { Ctx, Screen } from "../app/app.ts"; | |
| 14 | import { binding } from "../app/keys.ts"; | |
| 15 | import { style } from "../term/style.ts"; | |
| 16 | import { truncate } from "../term/width.ts"; | |
| 17 | import type { Session } from "../session.ts"; | |
| 18 | import { fill, len, split } from "../ui/layout.ts"; | |
| 19 | import { promptScreen } from "./common.ts"; | |
| 20 | ||
| 21 | export function gameModsScreen(f: Session, ctx: Ctx, box: GameBox, service: string): Screen { | |
| 22 | let note = ""; | |
| 23 | let mods: Result<Mods> | undefined; | |
| 24 | let ups: string[] = []; | |
| 25 | let hits: Hit[] = []; | |
| 26 | // The preview on screen, which `y` commits. | |
| 27 | let pending: Plan | undefined; | |
| 28 | const operator = () => mayDo(roleOn(f.app.db, f.user, box.id, service), "operator"); | |
| 29 | const say = (words: string): void => { | |
| 30 | note = words; | |
| 31 | ctx.invalidate(); | |
| 32 | }; | |
| 33 | const load = async (): Promise<void> => { | |
| 34 | mods = await modsOf(f.app, box, service); | |
| 35 | ctx.invalidate(); | |
| 36 | const u = mods.ok ? await updatesOf(f.app, mods.value) : undefined; | |
| 37 | const pu = mods.ok ? await packUpdateOf(f.app, mods.value) : undefined; | |
| 38 | ups = [ | |
| 39 | ...(u?.ok ? u.value.map((x) => `update: ${x.from.title} ${x.from.version} → ${x.to.version_number}`) : []), | |
| 40 | ...(pu?.ok && pu.value !== undefined && mods.ok && mods.value.pack !== undefined ? [`update: the modpack ${mods.value.pack.title} ${mods.value.pack.version} → ${pu.value.version_number}`] : []), | |
| 41 | ]; | |
| 42 | ctx.invalidate(); | |
| 43 | }; | |
| 44 | void load(); | |
| 45 | ||
| 46 | const lines = (): string[] => { | |
| 47 | if (mods === undefined) return ["Reading the lockfile…"]; | |
| 48 | if (!mods.ok) return [mods.error]; | |
| 49 | const m = mods.value; | |
| 50 | if (pending !== undefined) return [`Preview (${m.target.label}): y commits it, n drops it`, ...pending.lines.map((l) => ` ${l}`)]; | |
| 51 | return [ | |
| 52 | `Modrinth for ${m.target.label}`, | |
| 53 | ...ups, | |
| 54 | ...(m.pack === undefined | |
| 55 | ? [] | |
| 56 | : [`modpack: ${m.pack.title} ${m.pack.version} · Minecraft ${m.pack.minecraft} · ${m.pack.loader} ${m.pack.loaderVersion} · ${String(m.pack.files.length)} files locked · ${String(m.pack.overrides.length)} overrides`]), | |
| 57 | ...m.lock.map((l) => `${l.top ? "" : "dependency: "}${l.title} ${l.version} ${l.path}`), | |
| 58 | ...m.loose.map((e) => `unpinned: ${e}`), | |
| 59 | ...m.urls.map((u) => `unpinned jar: ${u}`), | |
| 60 | ...(m.lock.length + m.loose.length + m.urls.length === 0 ? ["Nothing is installed."] : []), | |
| 61 | ...hits.map((h, i) => `${String(i + 1)}. ${h.title} (${h.slug}) ${h.fits ? `runs on ${m.target.gameVersion}` : h.why}`), | |
| 62 | `Uploading a jar is on the web only: /games/${box.name}/${service}.`, | |
| 63 | ]; | |
| 64 | }; | |
| 65 | ||
| 66 | /** Plan with `make` on the state as read; the preview replaces the list until `y` or `n`. */ | |
| 67 | const preview = async (make: (m: Mods) => Promise<Result<Plan>>): Promise<string> => { | |
| 68 | if (!mods?.ok) return mods?.error ?? "Reading the lockfile…"; | |
| 69 | const got = await make(mods.value); | |
| 70 | if (!got.ok) return got.error; | |
| 71 | pending = got.value; | |
| 72 | return "y commits it, n drops it."; | |
| 73 | }; | |
| 74 | const ask = (title: string, label: string, run: (value: string) => Promise<string>): void => { | |
| 75 | if (!operator()) return say(`You are not an operator of ${service}.`); | |
| 76 | ctx.push(promptScreen(ctx, screen, { title, label, onSubmit: async (value) => say(await run(value)) })); | |
| 77 | }; | |
| 78 | ||
| 79 | const screen: Screen = { | |
| 80 | title: `${box.name}/${service} mods`, | |
| 81 | keys: [ | |
| 82 | binding(["/"], "search Modrinth"), | |
| 83 | binding(["a"], "install"), | |
| 84 | binding(["u"], "update all"), | |
| 85 | binding(["d"], "remove"), | |
| 86 | binding(["p"], "modpack"), | |
| 87 | binding(["y"], "commit the preview"), | |
| 88 | binding(["n"], "drop the preview"), | |
| 89 | ], | |
| 90 | render(area, s) { | |
| 91 | const c = ctx.theme.c; | |
| 92 | const [head, body] = split(area, "v", [len(1), fill(1)]); | |
| 93 | s.text( | |
| 94 | head!.x, | |
| 95 | head!.y, | |
| 96 | truncate(note === "" ? "/ search · a install · u update all · d remove" : note, head!.w), | |
| 97 | style(c.mutedFg, c.bg), | |
| 98 | head!.x + head!.w, | |
| 99 | ); | |
| 100 | lines() | |
| 101 | .slice(0, body!.h) | |
| 102 | .forEach((l, i) => s.text(body!.x, body!.y + i, truncate(l, body!.w), style(c.fg, c.bg), body!.x + body!.w)); | |
| 103 | }, | |
| 104 | key(e) { | |
| 105 | if (e.ctrl || e.alt) return false; | |
| 106 | if (e.key === "/") | |
| 107 | ask("Search Modrinth", "What to look for (empty: the most downloaded)", async (text) => { | |
| 108 | if (!mods?.ok) return mods?.error ?? "Reading the lockfile…"; | |
| 109 | const got = await search(f.app, mods.value.target, text); | |
| 110 | if (!got.ok) return got.error; | |
| 111 | hits = got.value; | |
| 112 | return hits.length === 0 | |
| 113 | ? `Nothing for ${mods.value.target.label} matches that.` | |
| 114 | : `${String(hits.length)} results; a installs one by its number or slug.`; | |
| 115 | }); | |
| 116 | else if (e.key === "a") | |
| 117 | ask("Install", "A result's number, or a Modrinth slug", (raw) => { | |
| 118 | const v = raw.trim(); | |
| 119 | const ref = /^\d+$/.test(v) ? (hits[Number(v) - 1]?.slug ?? v) : v; | |
| 120 | return preview((m) => planInstall(f.app, m, service, ref)); | |
| 121 | }); | |
| 122 | else if (e.key === "d") ask("Remove", "The slug of what to remove", (raw) => preview((m) => planRemove(m, service, raw.trim()))); | |
| 123 | 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") { | |
| 125 | if (!operator()) say(`You are not an operator of ${service}.`); | |
| 126 | else void preview((m) => (m.target.pack ? planPackUpdate(f.app, m, service) : planUpdate(f.app, m, service, "all"))).then(say); | |
| 127 | } else if ((e.key === "y" || e.key === "n") && pending !== undefined) { | |
| 128 | const plan = pending; | |
| 129 | pending = undefined; | |
| 130 | if (e.key === "n" || !mods?.ok) say("Dropped."); | |
| 131 | else | |
| 132 | void commitPlan(f.app, f.user!, box, service, mods.value, plan).then(async (done) => { | |
| 133 | if (done.ok) { | |
| 134 | hits = []; | |
| 135 | await load(); | |
| 136 | } | |
| 137 | say(done.ok ? `${plan.done} (${done.value.slice(0, 10)}); the server restarts with it on the box's next sync.` : done.error); | |
| 138 | }); | |
| 139 | } else return false; | |
| 140 | return true; | |
| 141 | }, | |
| 142 | }; | |
| 143 | return screen; | |
| 144 | } |
src/tui/screens/games.ts +13 −31
| @@ -4,8 +4,8 @@ | ||
| 4 | 4 | * box's next sync through `games/store.ts`, the same queue the page and the MCP tool use. `enter` |
| 5 | 5 | * opens a service as /games/<box>/<service> does: its console (the log tail, and `:` queues an |
| 6 | 6 | * rcon command), its env (`e` sets or clears a key, committed through `commitServiceEnv`) and its |
| 7 | * plugins (`a` adds a Modrinth slug or a URL through `addPlugin`; uploading a jar is the page's | |
| 8 | * alone); `c` opens its settings (server.properties and Paper's, as the page's Settings block: | |
| 7 | * Modrinth projects (`m` opens them: `game_mods.ts`, the page's model; uploading a jar is the | |
| 8 | * page's alone); `c` opens its settings (server.properties and Paper's, as the page's Settings block: | |
| 9 | 9 | * `enter` sets one, the preview shows on top, `y` commits it through `commitSettings`). `G` opens |
| 10 | 10 | * the box's grants, which an owner sets with `a` there, through `grant`; `b` the box itself, as |
| 11 | 11 | * /games/<box>'s Box block (its diagnosis, the volume's device and log among it). |
| @@ -22,7 +22,7 @@ import { queueWorld, worldWords, type WorldOp } from "../../games/worlds.ts"; | ||
| 22 | 22 | import { boxStatus, boxStatusShared, boxTails } from "../../games/diag.ts"; |
| 23 | 23 | import { cloudLine, pinnedOfBox } from "../../actions/cloud_says.ts"; |
| 24 | 24 | import { getUserByName } from "../../core/users.ts"; |
| 25 | import { addPlugin, commitServiceEnv, pluginSays, pluginsOf, readCompose, serviceEnv } from "../../games/compose.ts"; | |
| 25 | import { commitServiceEnv, readCompose, serviceEnv } from "../../games/compose.ts"; | |
| 26 | 26 | import { commitSettings, planSettings, settingsOf, type SettingsPlan, type SettingValue } from "../../games/settings.ts"; |
| 27 | 27 | import { |
| 28 | 28 | SERVICE_NAME, |
| @@ -53,6 +53,7 @@ import type { Session } from "../session.ts"; | ||
| 53 | 53 | import { fill, len, split } from "../ui/layout.ts"; |
| 54 | 54 | import { ListState, drawList, promptScreen, type ListRow } from "./common.ts"; |
| 55 | 55 | import type { PaletteEntry } from "./entries.ts"; |
| 56 | import { gameModsScreen } from "./game_mods.ts"; | |
| 56 | 57 | |
| 57 | 58 | /** "4 online · 19.8 TPS · " from the last hour's numbers, or nothing before any. */ |
| 58 | 59 | function playersTps(f: Session, box: { id: string }, service: string): string { |
| @@ -79,7 +80,7 @@ export function gamesScreen(f: Session, ctx: Ctx): Screen { | ||
| 79 | 80 | title: "Games", |
| 80 | 81 | keys: [ |
| 81 | 82 | binding(["j", "k"], "move cursor"), |
| 82 | binding(["enter"], "console, env, plugins"), | |
| 83 | binding(["enter"], "console, env, mods"), | |
| 83 | 84 | binding(["G"], "grants"), |
| 84 | 85 | binding(["!"], "console (the box's owner)"), |
| 85 | 86 | binding(["b"], "the box"), |
| @@ -173,12 +174,12 @@ export function gamesScreen(f: Session, ctx: Ctx): Screen { | ||
| 173 | 174 | return screen; |
| 174 | 175 | } |
| 175 | 176 | |
| 176 | const PARTS = ["console", "env", "plugins", "people", "world"] as const; | |
| 177 | const PARTS = ["console", "env", "people", "world"] as const; | |
| 177 | 178 | type Part = (typeof PARTS)[number]; |
| 178 | 179 | |
| 179 | 180 | /** |
| 180 | * One service, as /games/<box>/<service>: `tab` moves between its console, env and plugins. Each | |
| 181 | * change goes through the action the page's form calls, with the page's refusals in its words. | |
| 181 | * One service, as /games/<box>/<service>: `tab` moves between its console and env, `m` opens its | |
| 182 | * Modrinth projects. Each change goes through the action the page's form calls, with the page's refusals in its words. | |
| 182 | 183 | */ |
| 183 | 184 | export function gameServiceScreen(f: Session, ctx: Ctx, box: GameBox, service: string): Screen { |
| 184 | 185 | let part: Part = "console"; |
| @@ -231,17 +232,8 @@ export function gameServiceScreen(f: Session, ctx: Ctx, box: GameBox, service: s | ||
| 231 | 232 | } |
| 232 | 233 | if (!loaded) return ["Reading the compose file…"]; |
| 233 | 234 | if (compose === undefined) return [`No ${box.path} on ${box.repo}@${box.branch}.`]; |
| 234 | if (part === "env") { | |
| 235 | const env = Object.entries(serviceEnv(compose, service)); | |
| 236 | return env.length === 0 ? ["No environment set for this service."] : env.map(([k, v]) => `${k}=${v}`); | |
| 237 | } | |
| 238 | const p = pluginsOf(compose, service); | |
| 239 | return [ | |
| 240 | ...p.modrinth.map((m) => `modrinth: ${m}`), | |
| 241 | ...p.plugins.map((u) => `plugin: ${u}`), | |
| 242 | ...(p.modrinth.length + p.plugins.length === 0 ? ["No plugins yet."] : []), | |
| 243 | `Uploading a jar is on the web only: /games/${box.name}/${service}.`, | |
| 244 | ]; | |
| 235 | const env = Object.entries(serviceEnv(compose, service)); | |
| 236 | return env.length === 0 ? ["No environment set for this service."] : env.map(([k, v]) => `${k}=${v}`); | |
| 245 | 237 | }; |
| 246 | 238 | const ask = (title: string, label: string, run: (value: string) => Promise<string>, history?: readonly string[]): void => { |
| 247 | 239 | if (!operator()) return say(`You are not an operator of ${service}.`); |
| @@ -260,10 +252,10 @@ export function gameServiceScreen(f: Session, ctx: Ctx, box: GameBox, service: s | ||
| 260 | 252 | const screen: Screen = { |
| 261 | 253 | title: `${box.name}/${service}`, |
| 262 | 254 | keys: [ |
| 263 | binding(["tab"], "console, env, plugins, people, world"), | |
| 255 | binding(["tab"], "console, env, people, world"), | |
| 264 | 256 | binding([":"], "rcon"), |
| 265 | 257 | binding(["e"], "set env"), |
| 266 | binding(["a"], "add plugin"), | |
| 258 | binding(["m"], "mods"), | |
| 267 | 259 | binding(["c"], "settings"), |
| 268 | 260 | binding(["p"], "a player: op, ban, kick, move…"), |
| 269 | 261 | binding(["i"], "import a world"), |
| @@ -313,17 +305,7 @@ export function gameServiceScreen(f: Session, ctx: Ctx, box: GameBox, service: s | ||
| 313 | 305 | part = "people"; |
| 314 | 306 | return queued.ok ? `Asked: ${peopleWords(JSON.stringify({ op, player, server: to }))}; the box does it on its next sync.` : queued.error; |
| 315 | 307 | }); |
| 316 | else if (e.key === "a") | |
| 317 | ask("Plugin", "A Modrinth slug (start with ? to preview it), or an https URL to a jar", async (raw) => { | |
| 318 | const dry = raw.trim().startsWith("?"); | |
| 319 | const v = raw.trim().replace(/^\?\s*/, ""); | |
| 320 | const done = await addPlugin(f.app, f.user!, box, service, /^https?:\/\//.test(v) ? { url: v } : { modrinth: v }, { dry }); | |
| 321 | if (!done.ok) return done.error; | |
| 322 | if (dry) return pluginSays(done, true); | |
| 323 | part = "plugins"; | |
| 324 | await load(); | |
| 325 | return pluginSays(done, false); | |
| 326 | }); | |
| 308 | else if (e.key === "m") ctx.push(gameModsScreen(f, ctx, box, service)); | |
| 327 | 309 | else if (e.key === "i" || e.key === "u" || e.key === "n") { |
| 328 | 310 | const world = (op: WorldOp): string => { |
| 329 | 311 | const queued = queueWorld(f.app.db, boxNamed(f.app.db, box.name) ?? box, service, op, f.user); |
src/web/pages/games.ts +301 −35
| @@ -1,12 +1,15 @@ | ||
| 1 | 1 | /** |
| 2 | 2 | * `/games` (forge games): the game boxes a person may see, each box's network (one row a service, |
| 3 | 3 | * with Start, Stop and Restart), and a service's console (a live log over SSE and an RCON input), |
| 4 | * environment editor and plugins. Every route asks `roleOn` first: viewer reads, operator acts, | |
| 4 | * environment editor and its Modrinth projects (search, a preview, then one commit; `games/mods.ts`). Every route asks `roleOn` first: viewer reads, operator acts, | |
| 5 | 5 | * owner (and every forge admin) also grants. Env and plugin changes are commits to the box's |
| 6 | 6 | * compose repository, so a merge redeploys and the crew can propose them too. |
| 7 | 7 | */ |
| 8 | 8 | |
| 9 | import { addPlugin, pluginSays, commitServiceEnv, composeServices, pluginsOf, readCompose, SECRET_KEY, serviceEnv } from "../../games/compose.ts"; | |
| 9 | import { addPluginUrl, commitServiceEnv, composeServices, readCompose, SECRET_KEY, serviceEnv } from "../../games/compose.ts"; | |
| 10 | import { commitPlan, modsOf, packUpdateOf, planInstall, planPack, planPackUpdate, planRemove, planUpdate, updatesOf, type Mods, type Plan } from "../../games/mods.ts"; | |
| 11 | import { search, searchPacks, type Hit, type Result } from "../../games/modrinth.ts"; | |
| 12 | import { packCheckLines } from "../../games/pack_check.ts"; | |
| 10 | 13 | import { SHELL_SERVICE, queueShell } from "../../games/shell.ts"; |
| 11 | 14 | import { boxStatus, boxStatusShared, boxTails } from "../../games/diag.ts"; |
| 12 | 15 | import { commitSettings, planSettings, previewSettings, settingsOf, SETTINGS, type SettingValue, type SettingsPlan } from "../../games/settings.ts"; |
| @@ -48,7 +51,7 @@ import { field, readForm, type Form } from "../form.ts"; | ||
| 48 | 51 | import { html, raw, type Html } from "../html.ts"; |
| 49 | 52 | import { consoleHtml, consoleText, crashOf, shareOnMclogs } from "../../games/console.ts"; |
| 50 | 53 | import { flashTo, page } from "../layout.ts"; |
| 51 | import { badge, btn, disclosure, field as input, row, rowList, time } from "../ui.ts"; | |
| 54 | import { avatar, badge, btn, disclosure, field as input, row, rowList, time } from "../ui.ts"; | |
| 52 | 55 | import { onSync } from "../../games/notify.ts"; |
| 53 | 56 | import { canSleep, commitPolicy, EMPTY_SECONDS, policyOf, stateWords } from "../../games/sleep.ts"; |
| 54 | 57 | import { CLOUD_EVENT, cloudFacts, GAME_CLOUD_EVENT, pinnedOfBox } from "../../actions/cloud_says.ts"; |
| @@ -56,7 +59,7 @@ import { topologyBlock, TOPOLOGY_CSS } from "./games_topology.ts"; | ||
| 56 | 59 | import { defaultHeadResponse, headResponse } from "../../games/heads.ts"; |
| 57 | 60 | import { eventsOf, isBedrock, knowsPlayer, peopleOf, peopleWords, queuePeople, UNDO, type PeopleOp } from "../../games/people.ts"; |
| 58 | 61 | import { queueWorld, undoOf, worldWords } from "../../games/worlds.ts"; |
| 59 | import { emptyLine } from "../empty_words.ts"; | |
| 62 | import { emptyLine, emptyNote } from "../empty_words.ts"; | |
| 60 | 63 | import { metricsSeries, playerEvents, recentErrors, type Point } from "../../games/metrics.ts"; |
| 61 | 64 | import { daySpark } from "../studio/kpi_row.ts"; |
| 62 | 65 | |
| @@ -178,7 +181,7 @@ export async function gameBoxPage(ctx: Ctx): Promise<Response> { | ||
| 178 | 181 | }), |
| 179 | 182 | )} |
| 180 | 183 | ${topologyBlock(ctx, box, compose?.text, visible)} |
| 181 | ${role === "owner" ? boxBlock(box) : sharedBoxBlock(box)} ${role === "owner" ? shellBlock(ctx, box) : null} | |
| 184 | ${role === "owner" ? boxBlock(box, packCheckLines(ctx.app, box.id)) : sharedBoxBlock(box, packCheckLines(ctx.app, box.id))} ${role === "owner" ? shellBlock(ctx, box) : null} | |
| 182 | 185 | ${role === "owner" ? grantsBlock(ctx, box) : null}`, |
| 183 | 186 | })); |
| 184 | 187 | } |
| @@ -231,15 +234,15 @@ export function gameShellStream(ctx: Ctx): Response { | ||
| 231 | 234 | } |
| 232 | 235 | |
| 233 | 236 | /** What anyone who may see a service is told of the box: what it is doing, never its tails. */ |
| 234 | function sharedBoxBlock(box: GameBox): Html | null { | |
| 235 | const lines = boxStatusShared(box.diag); | |
| 237 | function sharedBoxBlock(box: GameBox, packs: readonly string[]): Html | null { | |
| 238 | const lines = [...boxStatusShared(box.diag), ...packs]; | |
| 236 | 239 | return lines.length === 0 ? null : html`<section class="settings-block"><h2>Box</h2>${lines.map((l) => html`<p>${l}</p>`)}</section>`; |
| 237 | 240 | } |
| 238 | 241 | |
| 239 | 242 | /** The box itself, from its latest diagnosis: plain lines first, the raw tails folded under them. The owner's. */ |
| 240 | function boxBlock(box: GameBox): Html { | |
| 243 | function boxBlock(box: GameBox, packs: readonly string[]): Html { | |
| 241 | 244 | const d = box.diag; |
| 242 | const lines = boxStatus(d); | |
| 245 | const lines = [...boxStatus(d), ...packs]; | |
| 243 | 246 | const raw = boxTails(d); |
| 244 | 247 | return html`<section class="settings-block"> |
| 245 | 248 | <h2>Box</h2> |
| @@ -334,7 +337,21 @@ export async function gameServicePage(ctx: Ctx): Promise<Response> { | ||
| 334 | 337 | const shared = /^[A-Za-z0-9]{1,32}$/.test(ctx.url.searchParams.get("shared") ?? "") ? ctx.url.searchParams.get("shared")! : ""; |
| 335 | 338 | const compose = await readCompose(ctx.app, box); |
| 336 | 339 | const env = compose === undefined ? {} : serviceEnv(compose.text, service); |
| 337 | const plugins = compose === undefined ? { plugins: [], modrinth: [] } : pluginsOf(compose.text, service); | |
| 340 | const query = ctx.url.searchParams.get("q"); | |
| 341 | const adding = ctx.url.searchParams.get("add") ?? ""; | |
| 342 | const mods = compose === undefined ? undefined : await modsOf(ctx.app, box, service); | |
| 343 | const packQuery = ctx.url.searchParams.get("pq"); | |
| 344 | const packing = ctx.url.searchParams.get("pack") ?? ""; | |
| 345 | const [hits, ups, modPreview, packHits, packUp, packPreview] = mods?.ok | |
| 346 | ? await Promise.all([ | |
| 347 | query === null ? undefined : search(ctx.app, mods.value.target, query), | |
| 348 | updatesOf(ctx.app, mods.value), | |
| 349 | act && adding !== "" ? planInstall(ctx.app, mods.value, service, adding) : undefined, | |
| 350 | packQuery === null ? undefined : searchPacks(ctx.app, mods.value.target, packQuery), | |
| 351 | packUpdateOf(ctx.app, mods.value), | |
| 352 | act && packing !== "" ? planPack(ctx.app, mods.value, service, packing) : undefined, | |
| 353 | ]) | |
| 354 | : [undefined, undefined, undefined, undefined, undefined, undefined]; | |
| 338 | 355 | const commands = recentCommands(ctx.app.db, box.id, service, 5); |
| 339 | 356 | const seen = servicesOf(ctx.app.db, box.id).find((s) => s.name === service); |
| 340 | 357 | const base = `/games/${box.name}/${service}`; |
| @@ -428,24 +445,20 @@ ${rawView ? tail.lines.join("\n") : raw(consoleHtml(tail.lines).join("\n"))}${ta | ||
| 428 | 445 | : null} |
| 429 | 446 | </section> |
| 430 | 447 | ${settingsBlock({ base, act, settings, preview, sha: compose?.sha ?? "", wanted })} |
| 431 | <section class="settings-block"> | |
| 432 | <h2>Plugins</h2> | |
| 433 | ${plugins.plugins.length + plugins.modrinth.length === 0 | |
| 434 | ? emptyLine("gamePlugins") | |
| 435 | : rowList([ | |
| 436 | ...plugins.modrinth.map((m) => row({ title: m, meta: html`Modrinth` })), | |
| 437 | ...plugins.plugins.map((p) => row({ title: html`<span class="mono">${p}</span>`, meta: html`jar URL` })), | |
| 438 | ])} | |
| 439 | ${act | |
| 440 | ? html`<form method="post" action="${base}/plugin" class="row-fields"> | |
| 441 | ${input({ name: "modrinth", label: "Modrinth slug", required: true, mono: true })} ${btn("Add", { variant: "secondary" })} ${btn("Preview", { variant: "secondary", name: "preview", value: "1", formnovalidate: false })} | |
| 442 | </form> | |
| 443 | <form method="post" action="${base}/jar" enctype="multipart/form-data" class="row-fields"> | |
| 444 | <input class="input" type="file" name="jar" accept=".jar" required aria-label="Plugin jar" /> | |
| 445 | ${btn("Upload jar", { variant: "secondary" })} | |
| 446 | </form>` | |
| 447 | : null} | |
| 448 | </section>`, | |
| 448 | ${modsBlock({ base, act, mods, hits, ups, preview: modPreview, query, adding })} | |
| 449 | ${mods?.ok && mods.value.target.kind === "mod" | |
| 450 | ? packBlock({ | |
| 451 | base, | |
| 452 | act, | |
| 453 | m: mods.value, | |
| 454 | hits: packHits, | |
| 455 | up: packUp, | |
| 456 | preview: packPreview, | |
| 457 | query: packQuery, | |
| 458 | packing, | |
| 459 | checked: packCheckLines(ctx.app, box.id).find((l) => l.startsWith(`${service}: `))?.slice(service.length + 2), | |
| 460 | }) | |
| 461 | : null}`, | |
| 449 | 462 | })); |
| 450 | 463 | } |
| 451 | 464 | |
| @@ -467,6 +480,243 @@ function numbersBlock(ctx: Ctx, box: GameBox, service: string): Html { | ||
| 467 | 480 | </section>`; |
| 468 | 481 | } |
| 469 | 482 | |
| 483 | /** What a change does, line by line, with the one button that commits it on the commit shown. */ | |
| 484 | const previewCard = (plan: Plan, action: string, project: string, label: string, cancel: string): Html => | |
| 485 | html`<div class="card" aria-label="What this does"> | |
| 486 | <div class="card-body stack"> | |
| 487 | ${rowList(plan.lines.map((l) => row({ title: l })))} | |
| 488 | <form method="post" action="${action}" class="row-fields"> | |
| 489 | <input type="hidden" name="project" value="${project}" /> | |
| 490 | <input type="hidden" name="sha" value="${plan.sha}" /> | |
| 491 | ${btn(label, { variant: "primary" })} ${btn("Cancel", { variant: "ghost", href: cancel })} | |
| 492 | </form> | |
| 493 | </div> | |
| 494 | </div>`; | |
| 495 | ||
| 496 | /** | |
| 497 | * A mod server's modpack: the one it runs (every file locked; its update, one click), and a search | |
| 498 | * for packs of its loader, each previewed (Minecraft and loader, files, overrides, what it | |
| 499 | * replaces) before one button puts it on the server. | |
| 500 | */ | |
| 501 | function packBlock(o: { | |
| 502 | base: string; | |
| 503 | act: boolean; | |
| 504 | m: Mods; | |
| 505 | hits: Result<Hit[]> | undefined; | |
| 506 | up: Awaited<ReturnType<typeof packUpdateOf>> | undefined; | |
| 507 | preview: Result<Plan> | undefined; | |
| 508 | query: string | null; | |
| 509 | packing: string; | |
| 510 | /** What the box's files said against the lock, when it has been asked. */ | |
| 511 | checked: string | undefined; | |
| 512 | }): Html { | |
| 513 | const p = o.m.pack; | |
| 514 | const href = (more: string): string => `${o.base}?pq=${encodeURIComponent(o.query ?? "")}${more}`; | |
| 515 | const up = o.up?.ok ? o.up.value : undefined; | |
| 516 | return html`<section class="settings-block" id="modpack"> | |
| 517 | <h2>Modpack</h2> | |
| 518 | ${p === undefined | |
| 519 | ? html`<p class="muted small">None: a modpack brings its own Minecraft, loader, mods and config, every file locked here.</p>` | |
| 520 | : rowList([ | |
| 521 | row({ | |
| 522 | lead: avatar(p.title), | |
| 523 | title: html`<a href="https://modrinth.com/modpack/${p.slug}" rel="noreferrer noopener" target="_blank">${p.title}</a>`, | |
| 524 | meta: html`<span class="mono">${p.version}</span> · Minecraft ${p.minecraft} · ${p.loader} ${p.loaderVersion} · ${String(p.files.length)} files locked · ${String(p.overrides.length)} overrides${p.skipped.length === 0 ? "" : ` · ${String(p.skipped.length)} client-only left out`}`, | |
| 525 | ...(up === undefined | |
| 526 | ? {} | |
| 527 | : { | |
| 528 | trail: badge(`${up.version_number} is out`, { tone: "attn" }), | |
| 529 | ...(o.act | |
| 530 | ? { | |
| 531 | after: html`<form method="post" action="${o.base}/mods/update"> | |
| 532 | <input type="hidden" name="project" value="pack" />${btn("Update", { size: "sm", variant: "secondary", label: `Update ${p.title} to ${up.version_number}` })} | |
| 533 | </form>`, | |
| 534 | } | |
| 535 | : {}), | |
| 536 | }), | |
| 537 | }), | |
| 538 | ])} | |
| 539 | ${p === undefined ? null : html`<p class="small">${o.checked ?? "Pack files are checked on the box once the server is up and healthy."}</p>`} | |
| 540 | ${p === undefined | |
| 541 | ? null | |
| 542 | : disclosure( | |
| 543 | "Locked files", | |
| 544 | html`<pre class="run-log mono" tabindex="0" aria-label="The files of ${p.title}">${[ | |
| 545 | ...p.files.map((f) => `${f.path} sha512 ${f.sha512.slice(0, 16)}…`), | |
| 546 | ...p.overrides.map((f) => `${f.path} from ${f.from}/`), | |
| 547 | ...p.skipped.map((f) => `${f} left out: client only`), | |
| 548 | ].join("\n")}</pre>`, | |
| 549 | { small: true }, | |
| 550 | )} | |
| 551 | ${o.preview === undefined | |
| 552 | ? null | |
| 553 | : o.preview.ok | |
| 554 | ? previewCard(o.preview.value, `${o.base}/mods/pack`, o.packing, "Install pack and restart", href("")) | |
| 555 | : html`<p class="notice danger" role="alert">${o.preview.error}</p>`} | |
| 556 | ${o.act | |
| 557 | ? html`<form method="get" action="${o.base}#modpack" class="row-fields" role="search"> | |
| 558 | <input class="input" type="search" name="pq" value="${o.query ?? ""}" placeholder="Search Modrinth modpacks for ${o.m.target.loaders[0]!}" aria-label="Search Modrinth modpacks" autocomplete="off" /> | |
| 559 | ${btn("Search packs", { variant: "secondary" })} | |
| 560 | </form>` | |
| 561 | : null} | |
| 562 | ${o.hits === undefined | |
| 563 | ? null | |
| 564 | : !o.hits.ok | |
| 565 | ? html`<p class="notice danger" role="alert">${o.hits.error}</p>` | |
| 566 | : o.hits.value.length === 0 | |
| 567 | ? emptyNote("noModpackMatches") | |
| 568 | : rowList( | |
| 569 | o.hits.value.map((h) => | |
| 570 | row({ | |
| 571 | lead: avatar(h.title), | |
| 572 | title: html`<a href="https://modrinth.com/modpack/${h.slug}" rel="noreferrer noopener" target="_blank">${h.title}</a>`, | |
| 573 | meta: html`${h.author} · ${downloads(h.downloads)} downloads · ${h.description}`, | |
| 574 | ...(p?.project === h.project ? { trail: badge("Installed", { tone: "merged" }) } : h.why === "" ? {} : { trail: badge(h.why) }), | |
| 575 | ...(o.act && p?.project !== h.project | |
| 576 | ? { after: btn("Preview", { size: "sm", variant: "secondary", href: href(`&pack=${encodeURIComponent(h.slug)}`), label: `Preview the modpack ${h.title}` }) } | |
| 577 | : {}), | |
| 578 | }), | |
| 579 | ), | |
| 580 | )} | |
| 581 | </section>`; | |
| 582 | } | |
| 583 | ||
| 584 | const downloads = (n: number): string => (n >= 1e6 ? `${(n / 1e6).toFixed(1)}M` : n >= 1e3 ? `${Math.round(n / 1e3)}k` : String(n)); | |
| 585 | ||
| 586 | /** | |
| 587 | * A server's Modrinth projects: updates first (each a from → to, one click each or all), then what | |
| 588 | * is installed, then the search. A result says before any click whether it runs here; Preview | |
| 589 | * shows what an install adds (its dependencies, a pin, the restart) and one button commits it. | |
| 590 | */ | |
| 591 | function modsBlock(o: { | |
| 592 | base: string; | |
| 593 | act: boolean; | |
| 594 | mods: { ok: true; value: Mods } | { ok: false; error: string } | undefined; | |
| 595 | hits: { ok: true; value: Hit[] } | { ok: false; error: string } | undefined; | |
| 596 | ups: Awaited<ReturnType<typeof updatesOf>> | undefined; | |
| 597 | preview: { ok: true; value: Plan } | { ok: false; error: string } | undefined; | |
| 598 | query: string | null; | |
| 599 | adding: string; | |
| 600 | }): Html { | |
| 601 | if (o.mods === undefined || !o.mods.ok) | |
| 602 | return html`<section class="settings-block" id="mods"> | |
| 603 | <h2>Mods and plugins</h2> | |
| 604 | <p class="muted">${o.mods?.error ?? "The compose file is not there to read."}</p> | |
| 605 | </section>`; | |
| 606 | const m = o.mods.value; | |
| 607 | const t = m.target; | |
| 608 | const noun = t.kind === "plugin" ? "plugins" : "mods"; | |
| 609 | const installed = new Set(m.lock.map((l) => l.project)); | |
| 610 | const ups = o.ups?.ok ? o.ups.value : []; | |
| 611 | const searchHref = (more: string): string => `${o.base}?q=${encodeURIComponent(o.query ?? "")}${more}#mods`; | |
| 612 | const update = (project: string, label: string): Html => | |
| 613 | html`<form method="post" action="${o.base}/mods/update"> | |
| 614 | <input type="hidden" name="project" value="${project}" />${btn(label, { size: "sm", variant: "secondary" })} | |
| 615 | </form>`; | |
| 616 | return html`<section class="settings-block" id="mods"> | |
| 617 | <h2>${t.kind === "plugin" ? "Plugins" : "Mods"} ${badge(`Modrinth · ${t.label}`, { variant: "outline" })}</h2> | |
| 618 | ${ups.length === 0 | |
| 619 | ? o.ups !== undefined && !o.ups.ok | |
| 620 | ? html`<p class="muted small">${o.ups.error}</p>` | |
| 621 | : null | |
| 622 | : html`<h3>${String(ups.length)} ${ups.length === 1 ? "update" : "updates"}</h3> | |
| 623 | ${rowList( | |
| 624 | ups.map((u) => | |
| 625 | row({ | |
| 626 | lead: avatar(u.from.title), | |
| 627 | title: u.from.title, | |
| 628 | meta: html`<span class="mono">${u.from.version} → ${u.to.version_number}</span>`, | |
| 629 | ...(o.act ? { after: update(u.from.project, "Update") } : {}), | |
| 630 | }), | |
| 631 | ), | |
| 632 | )} | |
| 633 | ${o.act && ups.length > 1 ? update("all", `Update all ${String(ups.length)}`) : null}`} | |
| 634 | ${m.lock.length + m.loose.length + m.urls.length === 0 | |
| 635 | ? emptyLine("gamePlugins") | |
| 636 | : rowList([ | |
| 637 | ...m.lock.map((l) => { | |
| 638 | const needs = m.lock.filter((x) => x.requires.includes(l.project)).map((x) => x.title); | |
| 639 | return row({ | |
| 640 | lead: avatar(l.title), | |
| 641 | title: html`<a href="https://modrinth.com/project/${l.slug}" rel="noreferrer noopener" target="_blank">${l.title}</a>`, | |
| 642 | meta: html`<span class="mono">${l.version}</span> · <span class="mono">${l.path}</span>${needs.length === 0 ? "" : ` · required by ${needs.join(", ")}`}`, | |
| 643 | ...(l.top ? {} : { trail: badge("dependency") }), | |
| 644 | ...(o.act && l.top | |
| 645 | ? { | |
| 646 | after: html`<form method="post" action="${o.base}/mods/remove"> | |
| 647 | <input type="hidden" name="project" value="${l.project}" />${btn("Remove", { size: "sm", variant: "ghost", label: `Remove ${l.title}` })} | |
| 648 | </form>`, | |
| 649 | } | |
| 650 | : {}), | |
| 651 | }); | |
| 652 | }), | |
| 653 | ...m.loose.map((e) => | |
| 654 | row({ | |
| 655 | title: html`<span class="mono">${e}</span>`, | |
| 656 | meta: html`in MODRINTH_PROJECTS, not pinned: the image picks a version at each start${o.act ? "; installing anything pins it" : ""}`, | |
| 657 | trail: badge("unpinned", { tone: "attn" }), | |
| 658 | }), | |
| 659 | ), | |
| 660 | ...m.urls.map((u) => | |
| 661 | row({ | |
| 662 | title: html`<span class="mono">${u.split("/").at(-1) || u}</span>`, | |
| 663 | meta: html`<span class="mono">${u}</span> · a jar URL in PLUGINS: fetched as it is at each start, with no hash to check`, | |
| 664 | trail: badge("unpinned", { tone: "attn" }), | |
| 665 | }), | |
| 666 | ), | |
| 667 | ])} | |
| 668 | ${o.preview === undefined | |
| 669 | ? null | |
| 670 | : o.preview.ok | |
| 671 | ? previewCard(o.preview.value, `${o.base}/mods/install`, o.adding, "Install and restart", searchHref("")) | |
| 672 | : html`<p class="notice danger" role="alert">${o.preview.error}</p>`} | |
| 673 | ${o.act && !t.pack | |
| 674 | ? html`<form method="get" action="${o.base}#mods" class="row-fields" role="search"> | |
| 675 | <input | |
| 676 | class="input" | |
| 677 | type="search" | |
| 678 | name="q" | |
| 679 | value="${o.query ?? ""}" | |
| 680 | placeholder="Search Modrinth for ${t.label} ${noun}" | |
| 681 | aria-label="Search Modrinth" | |
| 682 | autocomplete="off" | |
| 683 | /> | |
| 684 | ${btn("Search", { variant: "secondary" })} | |
| 685 | </form>` | |
| 686 | : null} | |
| 687 | ${o.hits === undefined | |
| 688 | ? null | |
| 689 | : !o.hits.ok | |
| 690 | ? html`<p class="notice danger" role="alert">${o.hits.error}</p>` | |
| 691 | : o.hits.value.length === 0 | |
| 692 | ? emptyNote("nothingOnModrinthMatches") | |
| 693 | : rowList( | |
| 694 | o.hits.value.map((h) => | |
| 695 | row({ | |
| 696 | lead: avatar(h.title), | |
| 697 | title: html`<a href="https://modrinth.com/project/${h.slug}" rel="noreferrer noopener" target="_blank">${h.title}</a>`, | |
| 698 | meta: html`${h.author} · ${downloads(h.downloads)} downloads · ${h.description}`, | |
| 699 | trail: installed.has(h.project) | |
| 700 | ? badge("Installed", { tone: "merged" }) | |
| 701 | : h.fits | |
| 702 | ? badge(`Runs on ${t.gameVersion}`, { tone: "success" }) | |
| 703 | : badge(h.why), | |
| 704 | ...(o.act && h.fits && !installed.has(h.project) | |
| 705 | ? { after: btn("Preview", { size: "sm", variant: "secondary", href: searchHref(`&add=${encodeURIComponent(h.slug)}`), label: `Preview installing ${h.title}` }) } | |
| 706 | : {}), | |
| 707 | }), | |
| 708 | ), | |
| 709 | )} | |
| 710 | ${o.act | |
| 711 | ? html`<form method="post" action="${o.base}/jar" enctype="multipart/form-data" class="row-fields"> | |
| 712 | <input class="input" type="file" name="jar" accept=".jar" required aria-label="Plugin jar" /> | |
| 713 | ${btn("Upload jar", { variant: "secondary" })} | |
| 714 | </form>` | |
| 715 | : null} | |
| 716 | </section>`; | |
| 717 | } | |
| 718 | ||
| 719 | ||
| 470 | 720 | // GET /games/:box/:service/stream: new log lines and command results after each sync. |
| 471 | 721 | export function gameServiceStream(ctx: Ctx): Response { |
| 472 | 722 | const service = ctx.params.service ?? ""; |
| @@ -740,7 +990,6 @@ export async function gameSleepSubmit(ctx: Ctx): Promise<Response> { | ||
| 740 | 990 | ); |
| 741 | 991 | } |
| 742 | 992 | |
| 743 | // POST /games/:box/:service/plugin: a Modrinth slug. | |
| 744 | 993 | /** A player's head and name, with a Bedrock badge for a Floodgate player. */ |
| 745 | 994 | const who = (name: string, uuid: string): Html => |
| 746 | 995 | html`<img src="/games/head/${uuid === "" || isBedrock(name) ? "none" : uuid}" alt="" width="20" height="20" loading="lazy" /> ${name}${isBedrock(name) ? html` ${badge("Bedrock", { tone: "default" })}` : null}`; |
| @@ -813,18 +1062,35 @@ export function gameHead(ctx: Ctx): Promise<Response> | Response { | ||
| 813 | 1062 | return headResponse(ctx.app, uuid); |
| 814 | 1063 | } |
| 815 | 1064 | |
| 816 | export async function gamePluginSubmit(ctx: Ctx): Promise<Response> { | |
| 1065 | /** A mods change from a form: planned again on the commit the person saw, then committed. */ | |
| 1066 | async function modsSubmit(ctx: Ctx, plan: (m: Mods, service: string, project: string) => Promise<{ ok: true; value: Plan } | { ok: false; error: string }>): Promise<Response> { | |
| 817 | 1067 | const got = await operatorForm(ctx); |
| 818 | 1068 | if (got instanceof Response) return got; |
| 819 | const dry = field(got.form, "preview") === "1"; | |
| 820 | const done = await addPlugin(ctx.app, ctx.auth.user!, got.box, got.service, { modrinth: field(got.form, "modrinth").trim() }, { dry }); | |
| 1069 | const back = `/games/${got.box.name}/${got.service}`; | |
| 1070 | const mods = await modsOf(ctx.app, got.box, got.service); | |
| 1071 | if (!mods.ok) return flashTo(ctx, back, { tone: "danger", message: mods.error }); | |
| 1072 | const seen = field(got.form, "sha"); | |
| 1073 | if (seen !== "" && seen !== mods.value.sha) return flashTo(ctx, `${back}#mods`, { tone: "danger", message: "The network changed since that preview; look at it again." }); | |
| 1074 | const planned = await plan(mods.value, got.service, field(got.form, "project").trim()); | |
| 1075 | if (!planned.ok) return flashTo(ctx, `${back}#mods`, { tone: "danger", message: planned.error }); | |
| 1076 | const done = await commitPlan(ctx.app, ctx.auth.user!, got.box, got.service, mods.value, planned.value); | |
| 821 | 1077 | return flashTo( |
| 822 | 1078 | ctx, |
| 823 | `/games/${got.box.name}/${got.service}`, | |
| 824 | done.ok ? { message: pluginSays(done, dry) } : { tone: "danger", message: done.error }, | |
| 1079 | `${back}#mods`, | |
| 1080 | done.ok ? { message: `${planned.value.done} (${done.value.slice(0, 10)}); the server restarts with it on the box's next sync.` } : { tone: "danger", message: done.error }, | |
| 825 | 1081 | ); |
| 826 | 1082 | } |
| 827 | 1083 | |
| 1084 | // POST /games/:box/:service/mods/install: a Modrinth project, its newest compatible version and what it requires. | |
| 1085 | export const gameModInstall = (ctx: Ctx): Promise<Response> => modsSubmit(ctx, (m, service, project) => planInstall(ctx.app, m, service, project)); | |
| 1086 | // POST /games/:box/:service/mods/update: one project, "all", or "pack" (the modpack), to its newest release. | |
| 1087 | export const gameModUpdate = (ctx: Ctx): Promise<Response> => | |
| 1088 | modsSubmit(ctx, (m, service, project) => (project === "pack" ? planPackUpdate(ctx.app, m, service) : planUpdate(ctx.app, m, service, project))); | |
| 1089 | // POST /games/:box/:service/mods/pack: a Modrinth modpack, every file locked. | |
| 1090 | export const gameModPack = (ctx: Ctx): Promise<Response> => modsSubmit(ctx, (m, service, project) => planPack(ctx.app, m, service, project)); | |
| 1091 | // POST /games/:box/:service/mods/remove: a project, and what only it required. | |
| 1092 | export const gameModRemove = (ctx: Ctx): Promise<Response> => modsSubmit(ctx, (m, service, project) => planRemove(m, service, project)); | |
| 1093 | ||
| 828 | 1094 | // POST /games/:box/:service/jar: an uploaded plugin jar, kept here and added to PLUGINS. |
| 829 | 1095 | export async function gameJarSubmit(ctx: Ctx): Promise<Response> { |
| 830 | 1096 | const service = ctx.params.service ?? ""; |
| @@ -837,7 +1103,7 @@ export async function gameJarSubmit(ctx: Ctx): Promise<Response> { | ||
| 837 | 1103 | return flashTo(ctx, `/games/${got.box.name}/${service}`, { tone: "danger", message: "Choose a .jar file." }); |
| 838 | 1104 | const jar = await storeJar(ctx.app, got.box.id, file, file.name); |
| 839 | 1105 | if (!jar.ok) return flashTo(ctx, `/games/${got.box.name}/${service}`, { tone: "danger", message: jar.error }); |
| 840 | const done = await addPlugin(ctx.app, ctx.auth.user!, got.box, service, { url: `${ctx.url.origin}${jarHref(jar)}` }); | |
| 1106 | const done = await addPluginUrl(ctx.app, ctx.auth.user!, got.box, service, `${ctx.url.origin}${jarHref(jar)}`); | |
| 841 | 1107 | if (!done.ok) await dropJar(ctx.app, jar.id); |
| 842 | 1108 | return flashTo( |
| 843 | 1109 | ctx, |
test/conversation-ask.test.ts +1 −1
| @@ -520,7 +520,7 @@ const SAID: readonly (readonly [string, Record<string, unknown>, string])[] = [ | ||
| 520 | 520 | ["games", { action: "power", box: "net", service: "hub", kind: "restart" }, "Restart hub on net."], |
| 521 | 521 | ["games", { action: "console", box: "net", service: "hub", text: "say hi" }, 'Run "say hi" in the console of hub on net.'], |
| 522 | 522 | ["games", { action: "env", box: "net", service: "hub", key: "MOTD", value: "Hello" }, "Set MOTD on hub on net to Hello, a commit that redeploys it."], |
| 523 | ["games", { action: "plugin", box: "net", service: "survival", modrinth: "waystones" }, "Add the plugin waystones to survival on net, a commit that redeploys it."], | |
| 523 | ["games", { action: "mods_install", box: "net", service: "survival", project: "waystones" }, "Install waystones and what it requires on survival on net, a commit that restarts it."], | |
| 524 | 524 | ["games", { action: "config_set", box: "net", service: "hub", key: "view-distance", value: "12", dryRun: false }, "Set the setting view-distance on hub on net to 12, a commit that restarts it."], |
| 525 | 525 | ["games", { action: "sleep", box: "net", service: "hunting", value: "sleep" }, "Let hunting on net sleep when empty and wake on join, a commit that redeploys it."], |
| 526 | 526 | ["games", { action: "sleep", box: "net", service: "hub", value: "warm" }, "Keep hub on net warm, a commit that redeploys it."], |
test/egress-literals.test.ts +1
| @@ -36,6 +36,7 @@ const NOT_CALLED: Record<string, string> = { | ||
| 36 | 36 | "git.open-platform.sh": "placeholder in the follow-upstream form", |
| 37 | 37 | "jsonfeed.org": "the JSON Feed version URI, a name and not a request", |
| 38 | 38 | "mclo.gs": "a shared crash log's page, linked for a person on /games; the forge posts to api.mclo.gs", |
| 39 | "modrinth.com": "a project's page, linked for a person on /games; the forge calls api.modrinth.com and cdn.modrinth.com", | |
| 39 | 40 | "ui.shadcn.com": "the registry schema URIs in registry/items.ts, names the shadcn CLI reads and the forge never requests", |
| 40 | 41 | "aka.ms": "the Minecraft EULA link in the games design text, shown to the user and never requested", |
| 41 | 42 | "ntfy.sh": "placeholder in the account notification field", |
test/engine-crossing.test.ts +2
| @@ -179,6 +179,7 @@ describe("every setting is on one list, and what crosses is data", () => { | ||
| 179 | 179 | "mclogsFetch", |
| 180 | 180 | "memory", |
| 181 | 181 | "memoryWatch", |
| 182 | "modrinthFetch", | |
| 182 | 183 | "releaseSend", |
| 183 | 184 | "verifyHuman", |
| 184 | 185 | ]); |
| @@ -210,6 +211,7 @@ const whole = (dataDir: string): Required<ForgeConfig> => ({ | ||
| 210 | 211 | memoryWatch: { grown: () => undefined }, |
| 211 | 212 | releaseSend: async () => true, |
| 212 | 213 | mclogsFetch: async () => new Response("{}"), |
| 214 | modrinthFetch: async () => new Response("{}"), | |
| 213 | 215 | memory: () => 1, |
| 214 | 216 | codeBudgetMs: 30, |
| 215 | 217 | port: 8080, |
test/game-mods.test.ts added +693
| @@ -0,0 +1,693 @@ | ||
| 1 | /** | |
| 2 | * Modrinth on a game server (G1 of #17284), against a stand-in for Modrinth's API: search for the | |
| 3 | * server's loader with each result marked runs-here or why not, an install that resolves required | |
| 4 | * dependencies and pins them in a lockfile with the compose env made from it, refusals for no | |
| 5 | * compatible version and for incompatible pairs, removal of what only it required, updates by | |
| 6 | * hash, and the same model through the page, its forms and the games MCP tool. | |
| 7 | */ | |
| 8 | import { afterAll, beforeAll, describe, expect, test } from "bun:test"; | |
| 9 | import { mkdtemp, rm } from "node:fs/promises"; | |
| 10 | import { tmpdir } from "node:os"; | |
| 11 | import { join } from "node:path"; | |
| 12 | import { commitToBranch, createRepo } from "../src/actions/repos.ts"; | |
| 13 | import { createApp, type App } from "../src/app.ts"; | |
| 14 | import { createToken } from "../src/core/tokens.ts"; | |
| 15 | import { createUser, getUserByName, type User } from "../src/core/users.ts"; | |
| 16 | import { readCompose, readRepoFile, serviceEnv } from "../src/games/compose.ts"; | |
| 17 | import { search, searchPacks, targetOf } from "../src/games/modrinth.ts"; | |
| 18 | import { commitPlan, lockPath, modsOf, packUpdateOf, planInstall, planPack, planPackUpdate, planRemove, planUpdate, updatesOf } from "../src/games/mods.ts"; | |
| 19 | import { boxNamed, createGameBox, type GameBox } from "../src/games/store.ts"; | |
| 20 | import { forgeHttp, type ForgeHttp } from "../src/http/server.ts"; | |
| 21 | import { packVerdict } from "../src/games/pack_check.ts"; | |
| 22 | import { AUTOSTOPPER, commitPolicy } from "../src/games/sleep.ts"; | |
| 23 | import { quietLogs } from "./helpers/globals.ts"; | |
| 24 | ||
| 25 | quietLogs(); | |
| 26 | ||
| 27 | const ORIGIN = "http://forge.test"; | |
| 28 | const COMPOSE = `services: | |
| 29 | hub: | |
| 30 | image: itzg/minecraft-server | |
| 31 | environment: | |
| 32 | TYPE: PAPER | |
| 33 | VERSION: "1.21.4" | |
| 34 | MODRINTH_PROJECTS: "essentialsx" | |
| 35 | survival: | |
| 36 | image: itzg/minecraft-server | |
| 37 | environment: | |
| 38 | TYPE: FABRIC | |
| 39 | VERSION: "1.21.4" | |
| 40 | proxy: | |
| 41 | image: itzg/mc-proxy | |
| 42 | environment: | |
| 43 | TYPE: VELOCITY | |
| 44 | PLUGINS: "https://download.geysermc.org/v2/projects/geyser/versions/latest/builds/latest/downloads/velocity,https://hangarcdn.papermc.io/plugins/ViaVersion/ViaVersion/versions/5.2.1/VELOCITY/ViaVersion-5.2.1.jar" | |
| 45 | `; | |
| 46 | ||
| 47 | // ---- a stand-in Modrinth ---- | |
| 48 | ||
| 49 | const sha = (c: string): string => c.repeat(128); | |
| 50 | const sha512Prefix = (c: string): string => sha(c).slice(0, 32); | |
| 51 | interface V { | |
| 52 | id: string; | |
| 53 | project: string; | |
| 54 | number: string; | |
| 55 | date: string; | |
| 56 | games: string[]; | |
| 57 | loaders: string[]; | |
| 58 | hash: string; | |
| 59 | mrpack?: Uint8Array; | |
| 60 | filename?: string; | |
| 61 | deps?: { project_id: string | null; version_id: string | null; dependency_type: string }[]; | |
| 62 | } | |
| 63 | /** A stored (uncompressed) zip of `entries`, as an .mrpack is a zip. */ | |
| 64 | function zip(entries: Record<string, string>): Uint8Array { | |
| 65 | const enc = new TextEncoder(); | |
| 66 | const parts: Uint8Array[] = []; | |
| 67 | const central: Uint8Array[] = []; | |
| 68 | let at = 0; | |
| 69 | for (const [name, text] of Object.entries(entries)) { | |
| 70 | const n = enc.encode(name); | |
| 71 | const d = enc.encode(text); | |
| 72 | const crc = Bun.hash.crc32(d); | |
| 73 | const local = new DataView(new ArrayBuffer(30)); | |
| 74 | local.setUint32(0, 0x04034b50, true); | |
| 75 | local.setUint16(4, 20, true); | |
| 76 | local.setUint32(14, crc, true); | |
| 77 | local.setUint32(18, d.length, true); | |
| 78 | local.setUint32(22, d.length, true); | |
| 79 | local.setUint16(26, n.length, true); | |
| 80 | parts.push(new Uint8Array(local.buffer), n, d); | |
| 81 | const c = new DataView(new ArrayBuffer(46)); | |
| 82 | c.setUint32(0, 0x02014b50, true); | |
| 83 | c.setUint16(4, 20, true); | |
| 84 | c.setUint16(6, 20, true); | |
| 85 | c.setUint32(16, crc, true); | |
| 86 | c.setUint32(20, d.length, true); | |
| 87 | c.setUint32(24, d.length, true); | |
| 88 | c.setUint16(28, n.length, true); | |
| 89 | c.setUint32(42, at, true); | |
| 90 | central.push(new Uint8Array(c.buffer), n); | |
| 91 | at += 30 + n.length + d.length; | |
| 92 | } | |
| 93 | const size = central.reduce((a, b) => a + b.length, 0); | |
| 94 | const end = new DataView(new ArrayBuffer(22)); | |
| 95 | end.setUint32(0, 0x06054b50, true); | |
| 96 | end.setUint16(8, Object.keys(entries).length, true); | |
| 97 | end.setUint16(10, Object.keys(entries).length, true); | |
| 98 | end.setUint32(12, size, true); | |
| 99 | end.setUint32(16, at, true); | |
| 100 | return Buffer.concat([...parts, ...central, new Uint8Array(end.buffer)]); | |
| 101 | } | |
| 102 | const packIndex = (minecraft: string) => | |
| 103 | JSON.stringify({ | |
| 104 | formatVersion: 1, | |
| 105 | game: "minecraft", | |
| 106 | versionId: "1.0.0", | |
| 107 | name: "Cozy Pack", | |
| 108 | files: [ | |
| 109 | { path: "mods/fabric-api.jar", hashes: { sha1: "a", sha512: sha("d") }, env: { client: "required", server: "required" }, downloads: ["https://cdn.modrinth.com/data/P7dR8mSH/versions/x/fabric-api.jar"] }, | |
| 110 | { path: "mods/sodium.jar", hashes: { sha1: "b", sha512: sha("e") }, env: { client: "required", server: "unsupported" }, downloads: ["https://cdn.modrinth.com/data/AANobbMI/versions/y/sodium.jar"] }, | |
| 111 | { path: "mods/lithium.jar", hashes: { sha1: "c", sha512: sha("f") }, downloads: ["https://cdn.modrinth.com/data/gvQqBUqZ/versions/z/lithium.jar"] }, | |
| 112 | ], | |
| 113 | dependencies: { minecraft, "fabric-loader": "0.16.9" }, | |
| 114 | }); | |
| 115 | const PACK1 = zip({ | |
| 116 | "modrinth.index.json": packIndex("1.21.1"), | |
| 117 | "overrides/config/a.toml": "a = 1", | |
| 118 | "overrides/config/b.toml": "b = 1", | |
| 119 | "server-overrides/config/b.toml": "b = 2", | |
| 120 | "client-overrides/options.txt": "fov = 90", | |
| 121 | }); | |
| 122 | const PACK2 = zip({ "modrinth.index.json": packIndex("1.21.1"), "overrides/config/a.toml": "a = 2" }); | |
| 123 | const sha512 = (b: Uint8Array): string => new Bun.CryptoHasher("sha512").update(b).digest("hex"); | |
| 124 | ||
| 125 | const PROJECTS = [ | |
| 126 | { id: "LPid0001", slug: "luckperms", title: "LuckPerms" }, | |
| 127 | { id: "CHid0001", slug: "chunky", title: "Chunky" }, | |
| 128 | { id: "CLid0001", slug: "chunkylib", title: "ChunkyLib" }, | |
| 129 | { id: "EXid0001", slug: "essentialsx", title: "EssentialsX" }, | |
| 130 | { id: "WEid0001", slug: "worldedit", title: "WorldEdit" }, | |
| 131 | { id: "FAid0001", slug: "fawe", title: "FastAsyncWorldEdit" }, | |
| 132 | { id: "OMid0001", slug: "oldmod", title: "OldMod" }, | |
| 133 | { id: "NGid0001", slug: "needsghost", title: "NeedsGhost" }, | |
| 134 | { id: "GHid0001", slug: "ghost", title: "Ghost" }, | |
| 135 | { id: "VPid0001", slug: "vanish", title: "Vanish" }, | |
| 136 | { id: "PKid0001", slug: "cozy", title: "Cozy Pack", pack: true }, | |
| 137 | { id: "BPid0001", slug: "badpack", title: "Bad Pack", pack: true }, | |
| 138 | { id: "COid0001", slug: "clientonly", title: "ClientOnly", server_side: "unsupported" }, | |
| 139 | { id: "QTid0001", slug: "bad,slug", title: "Comma" }, | |
| 140 | { id: "FNid0001", slug: "farfile", title: "FarFile" }, | |
| 141 | ]; | |
| 142 | const PAPER = ["paper", "spigot"]; | |
| 143 | const VERSIONS: V[] = [ | |
| 144 | { id: "LPv00001", project: "LPid0001", number: "5.4.100", date: "2024-10-01", games: ["1.21.4"], loaders: PAPER, hash: "1" }, | |
| 145 | { id: "LPv00002", project: "LPid0001", number: "5.4.145", date: "2024-12-01", games: ["1.21.4"], loaders: PAPER, hash: "2" }, | |
| 146 | { id: "LPv00003", project: "LPid0001", number: "5.4.150", date: "2025-01-10", games: ["1.21.4"], loaders: PAPER, hash: "3" }, | |
| 147 | { | |
| 148 | id: "CHv00001", | |
| 149 | project: "CHid0001", | |
| 150 | number: "1.4.28", | |
| 151 | date: "2024-12-01", | |
| 152 | games: ["1.21.4"], | |
| 153 | loaders: PAPER, | |
| 154 | hash: "4", | |
| 155 | deps: [ | |
| 156 | { project_id: "CLid0001", version_id: null, dependency_type: "required" }, | |
| 157 | { project_id: "LPid0001", version_id: null, dependency_type: "optional" }, | |
| 158 | ], | |
| 159 | }, | |
| 160 | { id: "CLv00001", project: "CLid0001", number: "1.0.2", date: "2024-11-01", games: ["1.21.4"], loaders: PAPER, hash: "5" }, | |
| 161 | { id: "EXv00001", project: "EXid0001", number: "2.21.0", date: "2024-12-02", games: ["1.21.4"], loaders: PAPER, hash: "6" }, | |
| 162 | { id: "WEv00001", project: "WEid0001", number: "7.3.9", date: "2024-12-03", games: ["1.21.4"], loaders: PAPER, hash: "7" }, | |
| 163 | { | |
| 164 | id: "FAv00001", | |
| 165 | project: "FAid0001", | |
| 166 | number: "2.12.3", | |
| 167 | date: "2024-12-04", | |
| 168 | games: ["1.21.4"], | |
| 169 | loaders: PAPER, | |
| 170 | hash: "8", | |
| 171 | deps: [{ project_id: "WEid0001", version_id: null, dependency_type: "incompatible" }], | |
| 172 | }, | |
| 173 | { id: "OMv00001", project: "OMid0001", number: "0.9", date: "2023-06-01", games: ["1.20.1"], loaders: PAPER, hash: "9" }, | |
| 174 | { | |
| 175 | id: "NGv00001", | |
| 176 | project: "NGid0001", | |
| 177 | number: "1.0", | |
| 178 | date: "2024-12-05", | |
| 179 | games: ["1.21.4"], | |
| 180 | loaders: PAPER, | |
| 181 | hash: "a", | |
| 182 | deps: [{ project_id: "GHid0001", version_id: null, dependency_type: "required" }], | |
| 183 | }, | |
| 184 | { id: "GHv00001", project: "GHid0001", number: "1.0", date: "2023-01-01", games: ["1.19.2"], loaders: PAPER, hash: "b" }, | |
| 185 | { id: "QTv00001", project: "QTid0001", number: "1.0", date: "2024-12-07", games: ["1.21.4"], loaders: PAPER, hash: "d" }, | |
| 186 | { id: "FNv00001", project: "FNid0001", number: "1.0", date: "2024-12-08", games: ["1.21.4"], loaders: PAPER, hash: "e", filename: "../x.jar" }, | |
| 187 | { id: "VPv00001", project: "VPid0001", number: "3.1", date: "2024-12-06", games: ["1.21.4", "1.21.3"], loaders: ["velocity"], hash: "c" }, | |
| 188 | { id: "PKv00001", project: "PKid0001", number: "1.0.0", date: "2024-11-01", games: ["1.21.1"], loaders: ["fabric"], hash: sha512(PACK1), mrpack: PACK1 }, | |
| 189 | // Its bytes are not the ones its sha512 names. | |
| 190 | { id: "BPv00001", project: "BPid0001", number: "1.0.0", date: "2024-11-01", games: ["1.21.1"], loaders: ["fabric"], hash: sha512(PACK2), mrpack: PACK1 }, | |
| 191 | ]; | |
| 192 | /** A newer Cozy Pack, published during the test. */ | |
| 193 | const PACK_V2: V = { id: "PKv00002", project: "PKid0001", number: "1.1.0", date: "2025-01-01", games: ["1.21.1"], loaders: ["fabric"], hash: sha512(PACK2), mrpack: PACK2 }; | |
| 194 | const fileHash = (v: V): string => (v.mrpack === undefined ? sha(v.hash) : v.hash); | |
| 195 | const wire = (v: V) => ({ | |
| 196 | id: v.id, | |
| 197 | project_id: v.project, | |
| 198 | version_number: v.number, | |
| 199 | version_type: "release", | |
| 200 | date_published: `${v.date}T00:00:00Z`, | |
| 201 | game_versions: v.games, | |
| 202 | loaders: v.loaders, | |
| 203 | files: [ | |
| 204 | { | |
| 205 | url: `https://cdn.modrinth.com/data/${v.project}/versions/${v.id}/${v.id}.${v.mrpack === undefined ? "jar" : "mrpack"}`, | |
| 206 | filename: v.filename ?? `${v.id}.${v.mrpack === undefined ? "jar" : "mrpack"}`, | |
| 207 | primary: true, | |
| 208 | hashes: { sha512: fileHash(v), sha1: "x" }, | |
| 209 | }, | |
| 210 | ], | |
| 211 | dependencies: v.deps ?? [], | |
| 212 | }); | |
| 213 | const asked: { path: string; ua: string; body: string }[] = []; | |
| 214 | ||
| 215 | async function modrinth(url: string, init: RequestInit): Promise<Response> { | |
| 216 | const u = new URL(url); | |
| 217 | const body = typeof init.body === "string" ? init.body : ""; | |
| 218 | asked.push({ path: u.pathname + u.search, ua: new Headers(init.headers).get("user-agent") ?? "", body }); | |
| 219 | const json = (v: unknown) => Response.json(v); | |
| 220 | const p = u.pathname; | |
| 221 | if (u.host === "cdn.modrinth.com") { | |
| 222 | const v = VERSIONS.find((x) => p.endsWith(`/${x.id}.mrpack`)); | |
| 223 | return v?.mrpack === undefined ? new Response("", { status: 404 }) : new Response(v.mrpack); | |
| 224 | } | |
| 225 | if (p === "/v2/tag/game_version") | |
| 226 | return json([ | |
| 227 | { version: "1.21.4", version_type: "release", date: "2024-12-03T00:00:00Z" }, | |
| 228 | { version: "1.21.3", version_type: "release", date: "2024-10-23T00:00:00Z" }, | |
| 229 | ]); | |
| 230 | if (p === "/v2/search") { | |
| 231 | const query = u.searchParams.get("query") ?? ""; | |
| 232 | const packs = (u.searchParams.get("facets") ?? "").includes("project_type:modpack"); | |
| 233 | return json({ | |
| 234 | hits: PROJECTS.filter((x) => x.slug.includes(query) && (x.pack === true) === packs).map((x) => ({ | |
| 235 | project_id: x.id, | |
| 236 | slug: x.slug, | |
| 237 | title: x.title, | |
| 238 | author: "someone", | |
| 239 | description: `${x.title} for servers`, | |
| 240 | downloads: 123_456, | |
| 241 | versions: [...new Set(VERSIONS.filter((v) => v.project === x.id).flatMap((v) => v.games))], | |
| 242 | categories: ["paper"], | |
| 243 | })), | |
| 244 | }); | |
| 245 | } | |
| 246 | const proj = /^\/v2\/project\/([^/]+)$/.exec(p); | |
| 247 | if (proj) { | |
| 248 | const x = PROJECTS.find((y) => y.id === proj[1] || y.slug === proj[1]); | |
| 249 | return x === undefined ? new Response("{}", { status: 404 }) : json(x); | |
| 250 | } | |
| 251 | const list = /^\/v2\/project\/([^/]+)\/version$/.exec(p); | |
| 252 | if (list) { | |
| 253 | const games = JSON.parse(u.searchParams.get("game_versions") ?? "null") as string[] | null; | |
| 254 | const loaders = JSON.parse(u.searchParams.get("loaders") ?? "[]") as string[]; | |
| 255 | return json( | |
| 256 | VERSIONS.filter( | |
| 257 | (v) => v.project === list[1] && (games === null || v.games.some((g) => games.includes(g))) && v.loaders.some((l) => loaders.includes(l)), | |
| 258 | ).map(wire), | |
| 259 | ); | |
| 260 | } | |
| 261 | const one = /^\/v2\/version\/([^/]+)$/.exec(p); | |
| 262 | if (one) { | |
| 263 | const v = VERSIONS.find((x) => x.id === one[1]); | |
| 264 | return v === undefined ? new Response("{}", { status: 404 }) : json(wire(v)); | |
| 265 | } | |
| 266 | if (p === "/v2/version_files/update") { | |
| 267 | const { hashes } = JSON.parse(body) as { hashes: string[] }; | |
| 268 | const out: Record<string, unknown> = {}; | |
| 269 | for (const h of hashes) { | |
| 270 | const v = VERSIONS.find((x) => fileHash(x) === h); | |
| 271 | if (v === undefined) continue; | |
| 272 | const newest = VERSIONS.filter((x) => x.project === v.project).sort((a, b) => b.date.localeCompare(a.date))[0]!; | |
| 273 | out[h] = wire(newest); | |
| 274 | } | |
| 275 | return json(out); | |
| 276 | } | |
| 277 | return new Response("{}", { status: 404 }); | |
| 278 | } | |
| 279 | ||
| 280 | // ---- the forge ---- | |
| 281 | ||
| 282 | let dir = ""; | |
| 283 | let app: App; | |
| 284 | let http: ForgeHttp; | |
| 285 | let alice: User; | |
| 286 | let box: GameBox; | |
| 287 | let tok = ""; | |
| 288 | let boxToken = ""; | |
| 289 | ||
| 290 | beforeAll(async () => { | |
| 291 | dir = await mkdtemp(join(tmpdir(), "forge-game-mods-")); | |
| 292 | app = createApp({ dataDir: dir, port: 0, modrinthFetch: modrinth }); | |
| 293 | http = forgeHttp(app); | |
| 294 | const made = await createUser(app.db, { | |
| 295 | origin: "seed", | |
| 296 | trusted: true, | |
| 297 | username: "alice", | |
| 298 | email: "[email protected]", | |
| 299 | password: "a-good-passphrase", | |
| 300 | adminIfFirst: true, | |
| 301 | }); | |
| 302 | if (!made.ok) throw new Error(made.error); | |
| 303 | alice = getUserByName(app.db, "alice")!; | |
| 304 | tok = createToken(app.db, alice.id, "admin", "admin").token; | |
| 305 | const repo = await createRepo(app, alice, { name: "mc-network", visibility: "private" }); | |
| 306 | if (!repo.ok) throw new Error(String(repo.error)); | |
| 307 | const seeded = await commitToBranch(app, alice, repo.value, { | |
| 308 | message: "network", | |
| 309 | files: [{ path: "net/docker-compose.yml", content: COMPOSE }], | |
| 310 | }); | |
| 311 | if (!seeded.ok) throw new Error(JSON.stringify(seeded.error)); | |
| 312 | boxToken = createGameBox(app.db, { name: "net", repo: "alice/mc-network", path: "net/docker-compose.yml" }).token; | |
| 313 | box = boxNamed(app.db, "net")!; | |
| 314 | }, 30_000); | |
| 315 | ||
| 316 | afterAll(async () => { | |
| 317 | app.close(); | |
| 318 | await rm(dir, { recursive: true, force: true }); | |
| 319 | }); | |
| 320 | ||
| 321 | const mods = async (service = "hub") => { | |
| 322 | const m = await modsOf(app, box, service); | |
| 323 | if (!m.ok) throw new Error(m.error); | |
| 324 | return m.value; | |
| 325 | }; | |
| 326 | const asAlice = (path: string, form?: Record<string, string>) => | |
| 327 | http.handle( | |
| 328 | new Request( | |
| 329 | ORIGIN + path, | |
| 330 | form === undefined | |
| 331 | ? { headers: { authorization: `Bearer ${tok}` } } | |
| 332 | : { | |
| 333 | method: "POST", | |
| 334 | headers: { authorization: `Bearer ${tok}`, origin: ORIGIN, "content-type": "application/x-www-form-urlencoded" }, | |
| 335 | body: new URLSearchParams(form), | |
| 336 | }, | |
| 337 | ), | |
| 338 | ); | |
| 339 | ||
| 340 | describe("the server's target", () => { | |
| 341 | test("TYPE names the loader, VERSION the game version; LATEST is the newest release; VANILLA takes none", () => { | |
| 342 | expect(targetOf({ TYPE: "PAPER", VERSION: "1.21.4" }, "")).toMatchObject({ | |
| 343 | ok: true, | |
| 344 | value: { loaders: ["paper", "bukkit", "spigot"], kind: "plugin", dir: "plugins", gameVersion: "1.21.4", label: "Paper 1.21.4" }, | |
| 345 | }); | |
| 346 | expect(targetOf({ TYPE: "FABRIC", VERSION: "LATEST" }, "1.21.4")).toMatchObject({ | |
| 347 | ok: true, | |
| 348 | value: { loaders: ["fabric"], kind: "mod", dir: "mods", gameVersion: "1.21.4", versionSaid: "LATEST" }, | |
| 349 | }); | |
| 350 | expect(targetOf({ TYPE: "VELOCITY" }, "1.21.4")).toMatchObject({ | |
| 351 | ok: true, | |
| 352 | value: { loaders: ["velocity"], proxy: true, dir: "plugins" }, | |
| 353 | }); | |
| 354 | const vanilla = targetOf({}, "1.21.4"); | |
| 355 | expect(vanilla.ok).toBe(false); | |
| 356 | if (!vanilla.ok) expect(vanilla.error).toContain("TYPE is VANILLA"); | |
| 357 | }); | |
| 358 | }); | |
| 359 | ||
| 360 | describe("Modrinth", () => { | |
| 361 | test("a search asks for the loader's categories with a real User-Agent, marks what runs here and why not, and is kept", async () => { | |
| 362 | const m = await mods(); | |
| 363 | asked.length = 0; | |
| 364 | const got = await search(app, m.target, "mod"); | |
| 365 | if (!got.ok) throw new Error(got.error); | |
| 366 | expect(asked).toHaveLength(1); | |
| 367 | expect(asked[0]!.ua).toMatch(/^forge\/\S+ \(open-platform\.sh\)$/); | |
| 368 | const facets = JSON.parse(new URL(`https://x${asked[0]!.path}`).searchParams.get("facets")!) as string[][]; | |
| 369 | // A plugin search: the loaders as one OR, and no environment (plugins run on the server). | |
| 370 | expect(facets).toEqual([["categories:paper", "categories:bukkit", "categories:spigot"]]); | |
| 371 | expect(got.value.find((h) => h.slug === "oldmod")).toMatchObject({ fits: false, why: "1.20.1 and older" }); | |
| 372 | await search(app, m.target, "mod"); | |
| 373 | expect(asked).toHaveLength(1); | |
| 374 | // A mod server asks for server-side environments. | |
| 375 | const fabric = targetOf({ TYPE: "FABRIC", VERSION: "1.21.4" }, ""); | |
| 376 | if (!fabric.ok) throw new Error(fabric.error); | |
| 377 | await search(app, fabric.value, "luck"); | |
| 378 | const modFacets = JSON.parse(new URL(`https://x${asked.at(-1)!.path}`).searchParams.get("facets")!) as string[][]; | |
| 379 | expect(modFacets[1]).toContain("environment:server_only"); | |
| 380 | expect(modFacets[1]).not.toContain("environment:client_only"); | |
| 381 | }); | |
| 382 | ||
| 383 | test("an install previews its dependency and the pin it takes over, then commits the lockfile and the env together", async () => { | |
| 384 | const m = await mods(); | |
| 385 | expect(m.loose).toEqual(["essentialsx"]); | |
| 386 | const plan = await planInstall(app, m, "hub", "chunky"); | |
| 387 | if (!plan.ok) throw new Error(plan.error); | |
| 388 | expect(plan.value.lines).toEqual([ | |
| 389 | "Adds Chunky 1.4.28", | |
| 390 | "Adds ChunkyLib 1.0.2 (required by Chunky)", | |
| 391 | "Pins EssentialsX 2.21.0 (it was in MODRINTH_PROJECTS unpinned)", | |
| 392 | "Restarts the server with the new set on the box's next sync", | |
| 393 | ]); | |
| 394 | const done = await commitPlan(app, alice, box, "hub", m, plan.value); | |
| 395 | if (!done.ok) throw new Error(done.error); | |
| 396 | const compose = (await readCompose(app, box))!; | |
| 397 | const env = serviceEnv(compose.text, "hub"); | |
| 398 | expect(env["MODRINTH_PROJECTS"]).toBe("chunky:CHv00001,chunkylib:CLv00001,essentialsx:EXv00001"); | |
| 399 | expect(env["MODRINTH_DOWNLOAD_DEPENDENCIES"]).toBe("none"); | |
| 400 | expect(lockPath(box, "hub")).toBe("net/modrinth/hub.lock.json"); | |
| 401 | const lock = JSON.parse((await readRepoFile(app, box, compose.sha, "net/modrinth/hub.lock.json"))!) as { | |
| 402 | gameVersion: string; | |
| 403 | projects: { slug: string; sha512: string; path: string; top: boolean }[]; | |
| 404 | }; | |
| 405 | expect(lock.gameVersion).toBe("1.21.4"); | |
| 406 | expect(lock.projects.map((p) => [p.slug, p.top, p.path])).toEqual([ | |
| 407 | ["chunky", true, "plugins/CHv00001.jar"], | |
| 408 | ["chunkylib", false, "plugins/CLv00001.jar"], | |
| 409 | ["essentialsx", true, "plugins/EXv00001.jar"], | |
| 410 | ]); | |
| 411 | expect(lock.projects[0]!.sha512).toBe(sha("4")); | |
| 412 | expect((await mods()).loose).toEqual([]); | |
| 413 | }); | |
| 414 | ||
| 415 | test("no compatible version, a requirement with none, and an incompatible pair are each refused with the reason", async () => { | |
| 416 | const no = await planInstall(app, await mods(), "hub", "oldmod"); | |
| 417 | expect(no).toEqual({ ok: false, error: "OldMod has no version for Paper 1.21.4." }); | |
| 418 | const ghost = await planInstall(app, await mods(), "hub", "needsghost"); | |
| 419 | expect(ghost).toEqual({ ok: false, error: "Ghost has no version for Paper 1.21.4, and another project here requires it." }); | |
| 420 | const we = await planInstall(app, await mods(), "hub", "worldedit"); | |
| 421 | if (!we.ok) throw new Error(we.error); | |
| 422 | const m = await mods(); | |
| 423 | expect((await commitPlan(app, alice, box, "hub", m, we.value)).ok).toBe(true); | |
| 424 | expect(await planInstall(app, await mods(), "hub", "fawe")).toEqual({ | |
| 425 | ok: false, | |
| 426 | error: "FastAsyncWorldEdit will not run beside WorldEdit: FastAsyncWorldEdit says they are incompatible.", | |
| 427 | }); | |
| 428 | expect(await planInstall(app, await mods(), "hub", "chunky")).toEqual({ ok: false, error: "Chunky 1.4.28 is installed." }); | |
| 429 | }); | |
| 430 | ||
| 431 | test("a client-only project, a name that is not plain, and a file outside its folder are refused before anything is written", async () => { | |
| 432 | expect(await planInstall(app, await mods(), "hub", "clientonly")).toEqual({ ok: false, error: "ClientOnly is client-only: it does nothing on a server." }); | |
| 433 | expect(await planInstall(app, await mods(), "hub", "QTid0001")).toEqual({ ok: false, error: "Comma has a name that cannot be written safely, so it is not offered." }); | |
| 434 | expect(await planInstall(app, await mods(), "hub", "farfile")).toEqual({ ok: false, error: "FarFile 1.0's file cannot be verified, so it is not offered." }); | |
| 435 | }); | |
| 436 | ||
| 437 | test("a dependency something requires is not removed; removing what required it takes it too", async () => { | |
| 438 | expect(await planRemove(await mods(), "hub", "chunkylib")).toEqual({ | |
| 439 | ok: false, | |
| 440 | error: "ChunkyLib is there because Chunky requires it; remove that first.", | |
| 441 | }); | |
| 442 | const plan = await planRemove(await mods(), "hub", "chunky"); | |
| 443 | if (!plan.ok) throw new Error(plan.error); | |
| 444 | expect(plan.value.lines.slice(0, 2)).toEqual(["Removes Chunky 1.4.28", "Removes ChunkyLib 1.0.2 (nothing left requires it)"]); | |
| 445 | expect((await commitPlan(app, alice, box, "hub", await mods(), plan.value)).ok).toBe(true); | |
| 446 | expect((await mods()).lock.map((l) => l.slug)).toEqual(["essentialsx", "worldedit"]); | |
| 447 | }); | |
| 448 | ||
| 449 | test("updates come from the locked hashes, as from → to, and one commit takes them", async () => { | |
| 450 | // An older LuckPerms, locked by hand, so Modrinth has a newer one. | |
| 451 | const m = await mods(); | |
| 452 | const old = await planInstall(app, m, "hub", "luckperms"); | |
| 453 | if (!old.ok) throw new Error(old.error); | |
| 454 | const lp = old.value.lock.find((l) => l.slug === "luckperms")!; | |
| 455 | const pinned = { | |
| 456 | ...old.value, | |
| 457 | lock: old.value.lock.map((l) => (l === lp ? { ...lp, versionId: "LPv00001", version: "5.4.100", sha512: sha("1") } : l)), | |
| 458 | }; | |
| 459 | expect((await commitPlan(app, alice, box, "hub", m, pinned)).ok).toBe(true); | |
| 460 | const ups = await updatesOf(app, await mods()); | |
| 461 | if (!ups.ok) throw new Error(ups.error); | |
| 462 | expect(ups.value.map((u) => `${u.from.slug} ${u.from.version} → ${u.to.version_number}`)).toEqual(["luckperms 5.4.100 → 5.4.150"]); | |
| 463 | expect(JSON.parse(asked.findLast((a) => a.path === "/v2/version_files/update")!.body)).toMatchObject({ | |
| 464 | algorithm: "sha512", | |
| 465 | loaders: ["paper", "bukkit", "spigot"], | |
| 466 | game_versions: ["1.21.4"], | |
| 467 | }); | |
| 468 | const plan = await planUpdate(app, await mods(), "hub", "all"); | |
| 469 | if (!plan.ok) throw new Error(plan.error); | |
| 470 | expect(plan.value.lines[0]).toBe("Updates LuckPerms 5.4.100 → 5.4.150"); | |
| 471 | expect((await commitPlan(app, alice, box, "hub", await mods(), plan.value)).ok).toBe(true); | |
| 472 | expect(serviceEnv((await readCompose(app, box))!.text, "hub")["MODRINTH_PROJECTS"]).toContain("luckperms:LPv00003"); | |
| 473 | }); | |
| 474 | ||
| 475 | test("a proxy's install sets MINECRAFT_VERSION, which its Modrinth step needs", async () => { | |
| 476 | const m = await mods("proxy"); | |
| 477 | const plan = await planInstall(app, m, "proxy", "vanish"); | |
| 478 | if (!plan.ok) throw new Error(plan.error); | |
| 479 | expect(plan.value.lines).toContain("Sets MINECRAFT_VERSION=1.21.4: the proxy's Modrinth step needs it"); | |
| 480 | expect((await commitPlan(app, alice, box, "proxy", m, plan.value)).ok).toBe(true); | |
| 481 | const env = serviceEnv((await readCompose(app, box))!.text, "proxy"); | |
| 482 | expect(env).toMatchObject({ MINECRAFT_VERSION: "1.21.4", MODRINTH_PROJECTS: "vanish:VPv00001" }); | |
| 483 | // The jar URLs in PLUGINS (Geyser, Via) are left exactly as they were, and shown as unpinned. | |
| 484 | expect(env["PLUGINS"]).toBe(serviceEnv(COMPOSE, "proxy")["PLUGINS"]); | |
| 485 | expect((await mods("proxy")).urls).toHaveLength(2); | |
| 486 | const page = await (await asAlice("/games/net/proxy")).text(); | |
| 487 | expect(page).toContain("ViaVersion-5.2.1.jar"); | |
| 488 | expect(page).toContain("unpinned"); | |
| 489 | }); | |
| 490 | ||
| 491 | test("on the proxy, sleep's AutoStopper and Modrinth's pins share MODRINTH_PROJECTS; neither change takes the other's", async () => { | |
| 492 | const proxyEnv = async () => serviceEnv((await readCompose(app, box))!.text, "proxy"); | |
| 493 | const slept = await commitPolicy(app, alice, box, "hub", "sleep"); | |
| 494 | if (!slept.ok) throw new Error(slept.error); | |
| 495 | expect(await proxyEnv()).toMatchObject({ MODRINTH_PROJECTS: `vanish:VPv00001,${AUTOSTOPPER}`, MINECRAFT_VERSION: "1.21.4" }); | |
| 496 | // AutoStopper is sleep's: not the proxy's own project, nor an unpinned one to adopt or drop. | |
| 497 | const m = await mods("proxy"); | |
| 498 | expect(m.loose).toEqual([]); | |
| 499 | expect(m.held).toEqual([AUTOSTOPPER]); | |
| 500 | const rm1 = await planRemove(m, "proxy", "vanish"); | |
| 501 | if (!rm1.ok) throw new Error(rm1.error); | |
| 502 | expect((await commitPlan(app, alice, box, "proxy", m, rm1.value)).ok).toBe(true); | |
| 503 | expect(await proxyEnv()).toMatchObject({ MODRINTH_PROJECTS: AUTOSTOPPER, MINECRAFT_VERSION: "1.21.4" }); | |
| 504 | const again = await planInstall(app, await mods("proxy"), "proxy", "vanish"); | |
| 505 | if (!again.ok) throw new Error(again.error); | |
| 506 | expect((await commitPlan(app, alice, box, "proxy", await mods("proxy"), again.value)).ok).toBe(true); | |
| 507 | expect((await proxyEnv())["MODRINTH_PROJECTS"]).toBe(`vanish:VPv00001,${AUTOSTOPPER}`); | |
| 508 | // Warm again: sleep takes only its own entry, and the version the pins still need stays. | |
| 509 | const warm = await commitPolicy(app, alice, box, "hub", "warm"); | |
| 510 | if (!warm.ok) throw new Error(warm.error); | |
| 511 | expect(await proxyEnv()).toMatchObject({ MODRINTH_PROJECTS: "vanish:VPv00001", MINECRAFT_VERSION: "1.21.4" }); | |
| 512 | }); | |
| 513 | ||
| 514 | test("a plan made on an older commit is refused rather than landing over a newer one", async () => { | |
| 515 | const stale = await mods(); | |
| 516 | const plan = await planInstall(app, stale, "hub", "fawe"); | |
| 517 | expect(plan.ok).toBe(false); | |
| 518 | const rm1 = await planRemove(stale, "hub", "worldedit"); | |
| 519 | if (!rm1.ok) throw new Error(rm1.error); | |
| 520 | const other = await planRemove(stale, "hub", "essentialsx"); | |
| 521 | if (!other.ok) throw new Error(other.error); | |
| 522 | expect((await commitPlan(app, alice, box, "hub", stale, rm1.value)).ok).toBe(true); | |
| 523 | expect(await commitPlan(app, alice, box, "hub", stale, other.value)).toEqual({ | |
| 524 | ok: false, | |
| 525 | error: "alice/mc-network@main moved on since this was previewed; look again and redo it.", | |
| 526 | }); | |
| 527 | }); | |
| 528 | }); | |
| 529 | ||
| 530 | describe("modpacks", () => { | |
| 531 | test("a pack goes on a Fabric server: client-only files left out, overrides then server-overrides, every file locked", async () => { | |
| 532 | const hub = await modsOf(app, box, "hub"); | |
| 533 | if (!hub.ok) throw new Error(hub.error); | |
| 534 | expect(await searchPacks(app, hub.value.target, "")).toEqual({ ok: false, error: "A modpack needs a mod server (Fabric, Quilt, Forge or NeoForge); this one is Paper 1.21.4." }); | |
| 535 | const m = await mods("survival"); | |
| 536 | const found = await searchPacks(app, m.target, ""); | |
| 537 | if (!found.ok) throw new Error(found.error); | |
| 538 | expect(found.value.map((h) => h.slug)).toEqual(["cozy", "badpack"]); | |
| 539 | expect(await planPack(app, m, "survival", "badpack")).toEqual({ ok: false, error: "BPv00001.mrpack does not match the sha512 Modrinth publishes for it; nothing was installed." }); | |
| 540 | const plan = await planPack(app, m, "survival", "cozy"); | |
| 541 | if (!plan.ok) throw new Error(plan.error); | |
| 542 | expect(plan.value.lines).toEqual([ | |
| 543 | "Installs the modpack Cozy Pack 1.0.0: Minecraft 1.21.1 with Fabric Loader 0.16.9", | |
| 544 | "2 files from the pack, each locked with its sha512 (1 client-only left out)", | |
| 545 | "2 override files: overrides/, then server-overrides/ over them", | |
| 546 | "Changes Minecraft 1.21.4 → 1.21.1: a world saved by a newer Minecraft may not open in an older one", | |
| 547 | "The image does not check a pack's file hashes; the lockfile keeps each one, so any change shows in review", | |
| 548 | "Restarts the server with the pack on the box's next sync", | |
| 549 | ]); | |
| 550 | expect((await commitPlan(app, alice, box, "survival", m, plan.value)).ok).toBe(true); | |
| 551 | const compose = (await readCompose(app, box))!; | |
| 552 | expect(serviceEnv(compose.text, "survival")).toEqual({ TYPE: "MODRINTH", VERSION: "1.21.1", MODRINTH_MODPACK: "cozy", MODRINTH_VERSION: "PKv00001", MODRINTH_LOADER: "fabric" }); | |
| 553 | const lock = JSON.parse((await readRepoFile(app, box, compose.sha, "net/modrinth/survival.lock.json"))!) as { pack: { files: { path: string; sha512: string }[]; skipped: string[]; overrides: { path: string; from: string }[]; sha512: string } }; | |
| 554 | expect(lock.pack.files.map((f) => [f.path, f.sha512])).toEqual([ | |
| 555 | ["mods/fabric-api.jar", sha("d")], | |
| 556 | ["mods/lithium.jar", sha("f")], | |
| 557 | ]); | |
| 558 | expect(lock.pack.skipped).toEqual(["mods/sodium.jar"]); | |
| 559 | expect(lock.pack.overrides).toEqual([ | |
| 560 | { path: "config/a.toml", from: "overrides" }, | |
| 561 | { path: "config/b.toml", from: "server-overrides" }, | |
| 562 | ]); | |
| 563 | expect(lock.pack.sha512).toBe(sha512(PACK1)); | |
| 564 | // The server is a pack server now: it reads as Fabric 1.21.1, takes no extra mods yet. | |
| 565 | const after = await mods("survival"); | |
| 566 | expect(after.target).toMatchObject({ pack: true, label: "Fabric 1.21.1", loaders: ["fabric"] }); | |
| 567 | expect(after.pack?.files).toHaveLength(2); | |
| 568 | expect(await planInstall(app, after, "survival", "luckperms")).toEqual({ ok: false, error: "This server runs the modpack Cozy Pack; its mods are the pack's, and extra mods on top of a pack come later." }); | |
| 569 | }); | |
| 570 | ||
| 571 | test("a newer pack release shows as an update and one commit takes it", async () => { | |
| 572 | VERSIONS.push(PACK_V2); | |
| 573 | const m = await mods("survival"); | |
| 574 | const up = await packUpdateOf(app, m); | |
| 575 | expect(up.ok && up.value?.id).toBe("PKv00002"); | |
| 576 | const plan = await planPackUpdate(app, m, "survival"); | |
| 577 | if (!plan.ok) throw new Error(plan.error); | |
| 578 | expect(plan.value.lines[0]).toBe("Updates the modpack Cozy Pack 1.0.0 → Cozy Pack 1.1.0"); | |
| 579 | expect((await commitPlan(app, alice, box, "survival", m, plan.value)).ok).toBe(true); | |
| 580 | expect(serviceEnv((await readCompose(app, box))!.text, "survival")["MODRINTH_VERSION"]).toBe("PKv00002"); | |
| 581 | const page = await (await asAlice("/games/net/survival")).text(); | |
| 582 | expect(page).toContain("Cozy Pack"); | |
| 583 | expect(page).toContain("2 files locked"); | |
| 584 | }); | |
| 585 | }); | |
| 586 | ||
| 587 | describe("the box checks a pack's files", () => { | |
| 588 | const sync = async (body: Record<string, unknown>) => | |
| 589 | (await ( | |
| 590 | await http.handle( | |
| 591 | new Request(`${ORIGIN}/api/v1/games/agent/sync`, { | |
| 592 | method: "POST", | |
| 593 | headers: { authorization: `Bearer ${boxToken}`, "content-type": "application/json" }, | |
| 594 | body: JSON.stringify({ agent: 1, ...body }), | |
| 595 | }), | |
| 596 | ) | |
| 597 | ).json()) as { commands: { id: string; kind: string; service: string; text: string }[] }; | |
| 598 | ||
| 599 | test("once the pack server is up and healthy, the agent is asked once, and its list is judged against the lock", async () => { | |
| 600 | const sha = (await readCompose(app, box))!.sha; | |
| 601 | const svc = (health: string) => [{ name: "survival", state: "running", health, startedAt: "", cpuPct: 1, memMiB: 900 }]; | |
| 602 | await sync({ composeSha: sha, services: svc("starting") }); | |
| 603 | expect((await sync({ composeSha: sha, services: svc("starting") })).commands).toEqual([]); | |
| 604 | await sync({ composeSha: sha, services: svc("healthy") }); | |
| 605 | const asked = (await sync({ composeSha: sha, services: svc("healthy") })).commands; | |
| 606 | expect(asked).toEqual([expect.objectContaining({ kind: "hashes", service: "survival", text: `compose ${sha}` })]); | |
| 607 | expect((await sync({ composeSha: sha, services: svc("healthy") })).commands).toEqual([]); | |
| 608 | const output = [`${sha512Prefix("d")} mods/fabric-api.jar`, `${"0".repeat(32)} mods/lithium.jar`, `${"1".repeat(32)} mods/old.jar`].join("\n"); | |
| 609 | await sync({ composeSha: sha, services: svc("healthy"), results: [{ id: asked[0]!.id, ok: true, output }] }); | |
| 610 | const page = await (await asAlice("/games/net")).text(); | |
| 611 | expect(page).toContain("survival: Pack files: 1 verified, 1 differs (lithium.jar), 1 not in the lock (old.jar)"); | |
| 612 | expect(await (await asAlice("/games/net/survival")).text()).toContain("Pack files: 1 verified, 1 differs (lithium.jar)"); | |
| 613 | }); | |
| 614 | ||
| 615 | test.skipIf(["bash", "curl", "jq"].some((t) => Bun.which(t) === null))("the agent lists the jars by a fresh container of the service's image and sends the list back", async () => { | |
| 616 | const root = await mkdtemp(join(tmpdir(), "forge-agent-hashes-")); | |
| 617 | const fake = join(root, "docker"); | |
| 618 | // compose run --rm --no-deps -T --entrypoint sh survival -c '<script>': the script's answer. | |
| 619 | await Bun.write(fake, `#!/usr/bin/env bash\ncase " $* " in *" run --rm --no-deps -T --entrypoint sh survival -c "*) printf '%s mods/fabric-api.jar\\n' ${sha512Prefix("d")} ;; esac\n`); | |
| 620 | await Bun.$`chmod +x ${fake}`; | |
| 621 | const bodies: { results?: { id: string; ok: boolean; output: string }[] }[] = []; | |
| 622 | const forge = Bun.serve({ | |
| 623 | port: 0, | |
| 624 | hostname: "127.0.0.1", | |
| 625 | async fetch(req) { | |
| 626 | bodies.push((await req.json()) as (typeof bodies)[number]); | |
| 627 | return Response.json({ composeSha: "", commands: bodies.length === 1 ? [{ id: "h1", kind: "hashes", service: "survival", text: "compose x" }] : [] }); | |
| 628 | }, | |
| 629 | }); | |
| 630 | try { | |
| 631 | const env = { PATH: process.env["PATH"] ?? "", HOME: root, FORGE_URL: `http://127.0.0.1:${String(forge.port)}`, FORGE_GAME_TOKEN: boxToken, FORGE_GAME_DIR: join(root, "game"), FORGE_GAME_DOCKER: fake, FORGE_GAME_ONCE: "1", FORGE_GAME_DIAG_S: "0" }; | |
| 632 | for (let i = 0; i < 2; i++) await Bun.$`bash ${join(import.meta.dir, "../src/games/agent.sh")}`.env(env).quiet().nothrow(); | |
| 633 | expect(bodies[1]!.results).toEqual([{ id: "h1", ok: true, output: `${sha512Prefix("d")} mods/fabric-api.jar` }]); | |
| 634 | } finally { | |
| 635 | forge.stop(true); | |
| 636 | await rm(root, { recursive: true, force: true }); | |
| 637 | } | |
| 638 | }); | |
| 639 | ||
| 640 | test("an agent older than the check, and a failed check, say so", () => { | |
| 641 | expect(packVerdict([], false, "refused: hashes is not a command this agent runs")).toBe( | |
| 642 | "Pack files are not checked: the box's agent is older than this check, and checks them once it updates.", | |
| 643 | ); | |
| 644 | expect(packVerdict([], false, "\nno such service: survival")).toBe("Pack files could not be checked: no such service: survival"); | |
| 645 | expect(packVerdict([{ path: "mods/a.jar", sha512: sha("a") }], true, "")).toBe("Pack files: 0 verified, 1 missing (a.jar)"); | |
| 646 | }); | |
| 647 | }); | |
| 648 | ||
| 649 | describe("the page and the MCP tool", () => { | |
| 650 | test("search shows the badge before any click, Preview shows the plan, and one button installs", async () => { | |
| 651 | const searched = await (await asAlice("/games/net/hub?q=fawe")).text(); | |
| 652 | expect(searched).toContain("Runs on 1.21.4"); | |
| 653 | expect(searched).toContain("Preview"); | |
| 654 | const old = await (await asAlice("/games/net/hub?q=oldmod")).text(); | |
| 655 | expect(old).toContain("1.20.1 and older"); | |
| 656 | expect(old).not.toContain("Preview installing OldMod"); | |
| 657 | const preview = await (await asAlice("/games/net/hub?q=fawe&add=fawe")).text(); | |
| 658 | expect(preview).toContain("Adds FastAsyncWorldEdit 2.12.3"); | |
| 659 | expect(preview).toContain("Install and restart"); | |
| 660 | const r = await asAlice("/games/net/hub/mods/install", { project: "fawe", sha: (await mods()).sha }); | |
| 661 | expect(r.status).toBe(303); | |
| 662 | expect(serviceEnv((await readCompose(app, box))!.text, "hub")["MODRINTH_PROJECTS"]).toContain("fawe:FAv00001"); | |
| 663 | const page = await (await asAlice("/games/net/hub")).text(); | |
| 664 | expect(page).toContain("FastAsyncWorldEdit"); | |
| 665 | expect(page).toContain("plugins/FAv00001.jar"); | |
| 666 | }); | |
| 667 | ||
| 668 | test("the MCP tool plans first and commits with dryRun false", async () => { | |
| 669 | const call = async (args: Record<string, unknown>) => { | |
| 670 | const res = await http.handle( | |
| 671 | new Request(`${ORIGIN}/mcp`, { | |
| 672 | method: "POST", | |
| 673 | headers: { authorization: `Bearer ${tok}`, "content-type": "application/json", accept: "application/json, text/event-stream" }, | |
| 674 | body: JSON.stringify({ | |
| 675 | jsonrpc: "2.0", | |
| 676 | id: 1, | |
| 677 | method: "tools/call", | |
| 678 | params: { name: "games", arguments: { box: "net", service: "hub", ...args } }, | |
| 679 | }), | |
| 680 | }), | |
| 681 | ); | |
| 682 | const body = (await res.json()) as { result: { isError?: boolean; content: { text: string }[] } }; | |
| 683 | return { error: body.result.isError === true, value: JSON.parse(body.result.content[0]!.text) as Record<string, unknown> }; | |
| 684 | }; | |
| 685 | const planned = await call({ action: "mods_install", project: "chunky" }); | |
| 686 | expect(planned.value).toMatchObject({ planned: true, lines: expect.arrayContaining(["Adds ChunkyLib 1.0.2 (required by Chunky)"]) }); | |
| 687 | expect(serviceEnv((await readCompose(app, box))!.text, "hub")["MODRINTH_PROJECTS"]).not.toContain("chunky"); | |
| 688 | const done = await call({ action: "mods_install", project: "chunky", dryRun: false }); | |
| 689 | expect(done.error).toBe(false); | |
| 690 | const listed = await call({ action: "mods" }); | |
| 691 | expect((listed.value["installed"] as { project: string }[]).map((p) => p.project)).toContain("chunkylib"); | |
| 692 | }); | |
| 693 | }); |
test/games.test.ts +4 −77
| @@ -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, pluginSays, readCompose, serviceEnv, setServiceEnv } from "../src/games/compose.ts"; | |
| 16 | import { commitServiceEnv, readCompose, serviceEnv, setServiceEnv } from "../src/games/compose.ts"; | |
| 17 | 17 | import { |
| 18 | 18 | boxNamed, |
| 19 | 19 | commandOf, |
| @@ -31,9 +31,8 @@ import { | ||
| 31 | 31 | rotateGameBoxToken, |
| 32 | 32 | setGameBoxMachine, |
| 33 | 33 | } from "../src/games/store.ts"; |
| 34 | import { forgeHttp, serve, type ForgeHttp } from "../src/http/server.ts"; | |
| 34 | import { forgeHttp, type ForgeHttp } from "../src/http/server.ts"; | |
| 35 | 35 | import { quietLogs } from "./helpers/globals.ts"; |
| 36 | import { mcpTool } from "./helpers/mcp.ts"; | |
| 37 | 36 | |
| 38 | 37 | quietLogs(); |
| 39 | 38 | |
| @@ -90,7 +89,8 @@ describe("forge games", () => { | ||
| 90 | 89 | |
| 91 | 90 | beforeAll(async () => { |
| 92 | 91 | dataDir = await mkdtemp(join(tmpdir(), "forge-games-")); |
| 93 | app = createApp({ dataDir, port: 0 }); | |
| 92 | // Modrinth stands in as an empty answer: the service page reads it, and a test never dials out. | |
| 93 | app = createApp({ dataDir, port: 0, modrinthFetch: async () => Response.json([]) }); | |
| 94 | 94 | http = forgeHttp(app); |
| 95 | 95 | for (const [username, adminIfFirst] of [ |
| 96 | 96 | ["alice", true], |
| @@ -238,76 +238,3 @@ describe("forge games", () => { | ||
| 238 | 238 | expect(queued.commands).toEqual([expect.objectContaining({ service: "hub", text: "say from bob" })]); |
| 239 | 239 | }); |
| 240 | 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 deleted −198
| @@ -1,198 +0,0 @@ | ||
| 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 +12 −25
| @@ -1,8 +1,8 @@ | ||
| 1 | 1 | /** |
| 2 | 2 | * Games in the terminal, both doors (review of #16913): from the Games screen, `enter` opens a |
| 3 | 3 | * service's console (its log tail, and `:` queues an rcon command), env (`e` commits a key through |
| 4 | * the page's own `commitServiceEnv`, refusals in its words) and plugins (`a` adds a Modrinth slug | |
| 5 | * through `addPlugin`; a jar upload is the page's alone, and the screen says so), `c` its settings | |
| 4 | * the page's own `commitServiceEnv`, refusals in its words) and mods (`games/mods.ts`, as the page; `a` previews a Modrinth install | |
| 5 | * with what it requires; a jar upload is the page's alone, and the screen says so), `c` its settings | |
| 6 | 6 | * (a value previewed, then committed with `y`), and `G` opens the box's grants, which only an owner |
| 7 | 7 | * sets. |
| 8 | 8 | */ |
| @@ -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 { pluginsOf, readCompose, serviceEnv } from "../src/games/compose.ts"; | |
| 16 | import { readCompose, serviceEnv } from "../src/games/compose.ts"; | |
| 17 | 17 | import { boxNamed, createGameBox, grant, grantsOf, recentCommands, recordSync } from "../src/games/store.ts"; |
| 18 | 18 | import { queueWorld } from "../src/games/worlds.ts"; |
| 19 | 19 | import { createForgeApp } from "../src/tui/forge.ts"; |
| @@ -29,6 +29,7 @@ const COMPOSE = `services: | ||
| 29 | 29 | image: itzg/minecraft-server |
| 30 | 30 | environment: |
| 31 | 31 | TYPE: PAPER |
| 32 | VERSION: "1.21.4" | |
| 32 | 33 | MOTD: "hello" |
| 33 | 34 | `; |
| 34 | 35 | |
| @@ -40,7 +41,8 @@ let carol: User; | ||
| 40 | 41 | |
| 41 | 42 | beforeAll(async () => { |
| 42 | 43 | dir = await mkdtemp(join(tmpdir(), "forge-tui-games-")); |
| 43 | app = createApp({ dataDir: dir, port: 0 }); | |
| 44 | // Modrinth stands in as an empty answer: nothing here dials out. | |
| 45 | app = createApp({ dataDir: dir, port: 0, modrinthFetch: async () => Response.json([]) }); | |
| 44 | 46 | for (const [username, adminIfFirst] of [ |
| 45 | 47 | ["alice", true], |
| 46 | 48 | ["bob", false], |
| @@ -103,7 +105,7 @@ const drive = (user: User) => { | ||
| 103 | 105 | }; |
| 104 | 106 | }; |
| 105 | 107 | |
| 106 | test("a service's console shows its log and queues an rcon command; env and plugins commit through the page's actions", async () => { | |
| 108 | test("a service's console shows its log and queues an rcon command; env commits through the page's action; mods read the same model", async () => { | |
| 107 | 109 | const { tui, session, terminal, type } = drive(alice); |
| 108 | 110 | const box = boxNamed(app.db, "net")!; |
| 109 | 111 | tui.ctx.push(gameServiceScreen(session, tui.ctx, box, "hub")); |
| @@ -122,29 +124,14 @@ test("a service's console shows its log and queues an rcon command; env and plug | ||
| 122 | 124 | await settleUntil(tui, "Committed "); |
| 123 | 125 | expect(serviceEnv((await readCompose(app, box))!.text, "hub")["MOTD"]).toBe("welcome"); |
| 124 | 126 | expect(tui.screen.toText()).toContain("MOTD=welcome"); |
| 125 | // A refusal comes back in the action's words. | |
| 127 | // Mods: the page's model, its refusals in its words. | |
| 128 | await type("m"); | |
| 129 | await settleUntil(tui, "Modrinth for Paper 1.21.4"); | |
| 130 | expect(tui.screen.toText()).toContain("Nothing is installed."); | |
| 126 | 131 | await type("a"); |
| 127 | 132 | await type("not a slug!"); |
| 128 | 133 | terminal.feed("\r"); |
| 129 | await settleUntil(tui, "A Modrinth project is its slug"); | |
| 130 | // `?` previews: the same dry run as the page's Preview button, nothing committed. | |
| 131 | const tip = (await readCompose(app, box))!.sha; | |
| 132 | await type("a"); | |
| 133 | await type("?luckperms"); | |
| 134 | terminal.feed("\r"); | |
| 135 | await settleUntil(tui, "Would commit: adds luckperms"); | |
| 136 | expect((await readCompose(app, box))!.sha).toBe(tip); | |
| 137 | // A URL previews too, and is not committed either (#17284). | |
| 138 | await type("a"); | |
| 139 | await type("?https://example.com/x.jar"); | |
| 140 | terminal.feed("\r"); | |
| 141 | await settleUntil(tui, "Would commit: adds the jar at https://example.com/x.jar"); | |
| 142 | expect((await readCompose(app, box))!.sha).toBe(tip); | |
| 143 | expect(pluginsOf((await readCompose(app, box))!.text, "hub").plugins).toEqual([]); | |
| 144 | await type("a"); | |
| 145 | await type("luckperms"); | |
| 146 | terminal.feed("\r"); | |
| 147 | await settleUntil(tui, "modrinth: luckperms"); | |
| 134 | await settleUntil(tui, "Name a Modrinth project by its slug or id, like luckperms."); | |
| 148 | 135 | expect(tui.screen.toText()).toContain("Uploading a jar is on the web only: /games/net/hub."); |
| 149 | 136 | tui.stop?.(); |
| 150 | 137 | }); |
new above
offline
Medium (memory/DoS): this per-app Map of read packs is never trimmed, and each LockedPack holds every file's url and hash (thousands of entries for a big pack). Anyone with operator on any box can grow it by previewing many packs. Bound it like the API cache (CACHE_MOST, drop the oldest) or keep a few entries.