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

Games: a mod-set install refuses a Modrinth slug that now points at a different project than the lock holds #18200

opened this

Merged 4h 34m ago, live in production

mason/forge:mason/18196-games-a-mod-set-install-refuses-a-modrin → main 0 commits fork

  • Merged. mason/18196-games-a-mod-set-install-refuses-a-modrin was merged into main as fa82fd9.

Review

Sign in to review this change.
4 files changed +151 −11
docs/features/game-mods.md +1
@@ -12,6 +12,7 @@ The server's mods or plugins come from Modrinth, for its loader and game version
1212 - **Sets**: a named set installs in one preview and one commit. `set:survival` is the survival performance set for a Fabric server: Lithium, ScalableLux, Noisium and Chunky, each at its newest release for the server's Minecraft version, with what they require (Chunky needs Fabric API). It adds only what is missing, and a server on another loader is refused with the reason. The web Mods block shows it with a *Preview the set* button until it is installed; the terminal shows the same lines and `s` previews it; MCP `mods_install` takes `project: "set:survival"`.
1313 - **Quality of life**: `set:quality` is graves (Universal Graves), Essential Commands, Styled Chat, Right Click Harvest, Sleep Warp (the night skips while players sleep) and Veinminer (a vein miner) for a Fabric server, installed like the survival set but optional by member: each is resolved alone, and one with no build for the server's Minecraft version (Right Click Harvest on 1.21.6) is left out with the reason ("Left out rightclickharvest: …") while the rest install; if none builds, it is refused. Essential Commands ships every command on; trimming it to /home, /spawn and /tpa is its config, which the owner sets, and the plan says so on a "Before players join" line, on the page and in the terminal. Each set shows a sentence on what it is for, and the web block offers *Preview the Quality of life set*, the terminal's key is `q`, MCP `mods_install` takes `project: "set:quality"`.
1414 - **The admin set**, `set:admin`, is LuckPerms (who may run which command) and Ledger (a block log with rollback) for a Fabric server. Ledger needs Fabric Language Kotlin, so the plan adds it as a dependency and the lock holds all three by sha512; removing Ledger takes that dependency with it, which is the way back. Each is the newest release for the server's Minecraft version; where Ledger has none yet the plan is refused with that reason and nothing is written. The web block offers *Preview the Admin set* and the terminal previews it with `r`.
15 - **A slug that moved** (#18196): the first install of a project records its Modrinth project id and its owner in the lockfile (`author`; trust on first use). When an install or a set names a slug the lock already holds, the forge asks Modrinth afresh what that slug is now; another project, or the same one under another owner, is refused, nothing installed, in the same words on the page, in the terminal and from MCP: "essential-commands is now project ECid0002 by mallory; the lock holds ECid0001 by patbox — nothing installed. If it moved on purpose, remove Essential Commands and add essential-commands again." Removing it and adding it again is how a project that changed hands on purpose comes back.
1516 - **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.
1617 - **Remove** takes a project and what only it required; a dependency something else requires stays.
1718
src/games/modrinth.ts +62 −9
@@ -19,6 +19,8 @@ const BASE = "https://api.modrinth.com";
1919 const MAX_BODY = 4_000_000;
2020 /** Ours: Modrinth's own limit is 300 a minute per address; ten are kept back. */
2121 const PER_MINUTE = 290;
22 /** What `api` says to a 404: the project (or version) is not on Modrinth. */
23 const NO_SUCH_PROJECT = "Modrinth has no such project.";
2224 const CACHE_MOST = 600;
2325
2426 // ---- the server: its loader and game version, from its compose env ----
@@ -120,13 +122,16 @@ const clientOf = (app: App): Client => {
120122
121123 const userAgent = (): string => `forge/${announcedOr()} (open-platform.sh)`;
122124
123 /** One call to Modrinth's API, cached for `ttlMs` (0: not cached), within the minute's budget. */
125 /**
126 * One call to Modrinth's API, cached for `ttlMs` (0: asked fresh and not kept), within the minute's
127 * budget.
128 */
124129 async function api<T>(app: App, path: string, ttlMs: number, body?: unknown): Promise<Result<T>> {
125130 const key = body === undefined ? path : `${path} ${JSON.stringify(body)}`;
126131 const now = Date.now();
127132 const c = clientOf(app);
128133 const { cache, asked } = c;
129 const kept = cache.get(key);
134 const kept = ttlMs > 0 ? cache.get(key) : undefined;
130135 if (kept !== undefined && now - kept.at < kept.ttl) {
131136 // Most recently used last, so the oldest is the one dropped.
132137 cache.delete(key);
@@ -156,7 +161,7 @@ async function api<T>(app: App, path: string, ttlMs: number, body?: unknown): Pr
156161 return { ok: false, error: "Modrinth did not answer in 10 s; try again." };
157162 }
158163 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." };
164 if (res.status === 404) return { ok: false, error: NO_SUCH_PROJECT };
160165 if (res.status === 429) {
161166 c.holdUntil = now + (Number(res.headers.get("x-ratelimit-reset")) || 60) * 1000;
162167 return { ok: false, error: "Modrinth asked this forge to slow down; try again in a minute." };
@@ -347,6 +352,11 @@ export interface Locked {
347352 readonly requires: readonly string[];
348353 /** The projects this version says it cannot run beside. */
349354 readonly incompatible: readonly string[];
355 /**
356 * Who owned it on Modrinth when it was first asked for (trust on first use, #18196); absent for a
357 * dependency, or when Modrinth did not say.
358 */
359 readonly author?: string;
350360 }
351361
352362 /**
@@ -371,8 +381,48 @@ export function playerSide(all: readonly Locked[], projects: readonly Project[])
371381 return [...out.values()];
372382 }
373383
374 const project = (app: App, idOrSlug: string): Promise<Result<Project>> =>
375 api<Project>(app, `/v2/project/${encodeURIComponent(idOrSlug)}`, 30 * MINUTE);
384 const project = (app: App, idOrSlug: string, ttlMs = 30 * MINUTE): Promise<Result<Project>> =>
385 api<Project>(app, `/v2/project/${encodeURIComponent(idOrSlug)}`, ttlMs);
386
387 interface Member {
388 user?: { username?: unknown };
389 role?: unknown;
390 is_owner?: unknown;
391 }
392 /** The username that owns a project on Modrinth; undefined when Modrinth does not say. */
393 async function ownerOf(app: App, projectId: string, ttlMs = 30 * MINUTE): Promise<string | undefined> {
394 const got = await api<Member[]>(app, `/v2/project/${encodeURIComponent(projectId)}/members`, ttlMs);
395 if (!got.ok || !Array.isArray(got.value)) return undefined;
396 const owner = got.value.find((m) => m.is_owner === true) ?? got.value.find((m) => m.role === "Owner");
397 const name = owner?.user?.username;
398 return typeof name === "string" && /^[\w.-]{1,64}$/.test(name) ? name : undefined;
399 }
400
401 /**
402 * Refused when a slug the lock already holds now names another project on Modrinth, or the same
403 * project under another owner (#18196): the lock's first sight of a slug is what it trusts, and a
404 * slug taken over is not followed. A slug Modrinth no longer has is left to the lock's project id.
405 * Asked fresh, never from the cache: the check is of Modrinth as it is now.
406 */
407 export async function slugsHold(app: App, lock: readonly Locked[], slugs: readonly string[]): Promise<Result<undefined>> {
408 for (const slug of slugs) {
409 const held = lock.find((l) => l.slug === slug.toLowerCase());
410 if (held === undefined) continue;
411 const now = await project(app, slug, 0);
412 if (!now.ok) {
413 if (now.error === NO_SUCH_PROJECT) continue;
414 return now;
415 }
416 const by = await ownerOf(app, now.value.id, 0);
417 const owners = by !== undefined && held.author !== undefined && by !== held.author;
418 if (now.value.id === held.project && !owners) continue;
419 return {
420 ok: false,
421 error: `${held.slug} is now project ${now.value.id} by ${by ?? "an owner Modrinth does not name"}; the lock holds ${held.project} by ${held.author ?? "an owner it did not record"} — nothing installed. If it moved on purpose, remove ${held.title} and add ${held.slug} again.`,
422 };
423 }
424 return { ok: true, value: undefined };
425 }
376426 export const versionById = (app: App, id: string): Promise<Result<Version>> =>
377427 api<Version>(app, `/v2/version/${encodeURIComponent(id)}`, 24 * 60 * MINUTE);
378428
@@ -390,7 +440,7 @@ async function newest(app: App, t: Target, projectId: string): Promise<Result<Ve
390440 return { ok: true, value: usable.find((v) => v.version_type === "release") ?? usable[0] };
391441 }
392442
393 function lockedOf(t: Target, p: Project, v: Version, top: boolean): Result<Locked> {
443 function lockedOf(t: Target, p: Project, v: Version, top: boolean, author: string | undefined): Result<Locked> {
394444 const file = v.files.find((f) => f.primary) ?? v.files[0];
395445 if (file === undefined || !file.hashes.sha512 || !/^[a-f0-9]{128}$/.test(file.hashes.sha512))
396446 return { ok: false, error: `${p.title} ${v.version_number} has no file with a sha512 to pin.` };
@@ -413,6 +463,7 @@ function lockedOf(t: Target, p: Project, v: Version, top: boolean): Result<Locke
413463 top,
414464 requires: v.dependencies.filter((d) => d.dependency_type === "required" && d.project_id).map((d) => d.project_id!),
415465 incompatible: v.dependencies.filter((d) => d.dependency_type === "incompatible" && d.project_id).map((d) => d.project_id!),
466 ...(author === undefined ? {} : { author }),
416467 },
417468 };
418469 }
@@ -436,7 +487,7 @@ export async function resolve(
436487 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." };
437488 const w = queue.shift()!;
438489 const p = await project(app, w.project);
439 if (!p.ok) return { ok: false, error: p.error === "Modrinth has no such project." ? `Modrinth has no project ${w.project}.` : p.error };
490 if (!p.ok) return { ok: false, error: p.error === NO_SUCH_PROJECT ? `Modrinth has no project ${w.project}.` : p.error };
440491 if (seen.has(p.value.id)) continue;
441492 seen.add(p.value.id);
442493 if (p.value.server_side === "unsupported") return { ok: false, error: `${p.value.title} is client-only: it does nothing on a server.` };
@@ -454,7 +505,9 @@ export async function resolve(
454505 };
455506 v = n.value;
456507 }
457 const locked = lockedOf(t, p.value, v, w.top || had?.top === true);
508 // The owner seen first is kept; a project asked for is asked who owns it the first time.
509 const author = had?.author ?? (w.top ? await ownerOf(app, p.value.id) : undefined);
510 const locked = lockedOf(t, p.value, v, w.top || had?.top === true, author);
458511 if (!locked.ok) return locked;
459512 out.set(p.value.id, locked.value);
460513 for (const d of v.dependencies) {
@@ -573,7 +626,7 @@ interface PackIndex {
573626 /** The newest release of a modpack for one of these loaders, with an .mrpack to read. */
574627 export async function newestPack(app: App, t: Target, projectRef: string): Promise<Result<{ project: Project; version: Version }>> {
575628 const p = await project(app, projectRef);
576 if (!p.ok) return { ok: false, error: p.error === "Modrinth has no such project." ? `Modrinth has no modpack ${projectRef}.` : p.error };
629 if (!p.ok) return { ok: false, error: p.error === NO_SUCH_PROJECT ? `Modrinth has no modpack ${projectRef}.` : p.error };
577630 const loaders = t.loaders.filter((l) => PACK_LOADERS.includes(l));
578631 const got = await api<Version[]>(app, `/v2/project/${encodeURIComponent(p.value.id)}/version?loaders=${q(loaders)}&include_changelog=false`, 10 * MINUTE);
579632 if (!got.ok) return got;
src/games/mods.ts +8 −2
@@ -19,7 +19,7 @@
1919 import type { App } from "../app.ts";
2020 import type { User } from "../core/users.ts";
2121 import { commitCompose, composeDir, 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";
22 import { byVersion, latestRelease, newestPack, packUpdate, readPack, resolve, slugsHold, targetOf, updates, type Locked, type LockedPack, type Result, type Target, type Version } from "./modrinth.ts";
2323 import { missing as setMissing, setNamed, SETS, SET_PREFIX, type ModSet } from "./mod_sets.ts";
2424 import { memoryRefusal, type BoxRoom } from "./box_memory.ts";
2525 import { withConfig } from "./plugin_config.ts";
@@ -96,8 +96,9 @@ export function parseLock(text: string | undefined): { projects: Locked[]; pack:
9696 (k) => typeof (p as Record<string, unknown>)[k] === "string",
9797 ),
9898 )
99 .map((p) => ({
99 .map(({ author, ...p }) => ({
100100 ...p,
101 ...(typeof author === "string" ? { author } : {}),
101102 top: p.top !== false,
102103 requires: Array.isArray(p.requires) ? p.requires : [],
103104 incompatible: Array.isArray(p.incompatible) ? p.incompatible : [],
@@ -219,6 +220,8 @@ export async function planInstall(app: App, m: Mods, service: string, ref: strin
219220 // A bare slug already in MODRINTH_PROJECTS is taken into the lock, pinned, with this change.
220221 const adopt = m.loose.filter(bareSlug);
221222 const kept = m.loose.filter((e) => !bareSlug(e));
223 const holds = await slugsHold(app, m.lock, [wantedRef]);
224 if (!holds.ok) return holds;
222225 const got = await resolve(app, m.target, m.lock, [
223226 { project: had?.project ?? wantedRef, top: true },
224227 ...adopt.filter((s) => s.toLowerCase() !== wantedRef.toLowerCase()).map((s) => ({ project: s, top: true })),
@@ -271,6 +274,9 @@ async function planSet(app: App, m: Mods, service: string, set: ModSet): Promise
271274 return { ok: false, error: `The ${set.title.toLowerCase()} set is for ${set.loader[0]!.toUpperCase()}${set.loader.slice(1)} servers; ${service} runs ${m.target.label}.` };
272275 const missing = setMissing(set, m.lock);
273276 if (missing.length === 0) return { ok: false, error: `The ${set.title.toLowerCase()} set is installed.` };
277 // A member whose slug moved to another project is a refusal of the set, never a "Left out".
278 const holds = await slugsHold(app, m.lock, missing);
279 if (!holds.ok) return holds;
274280 const adopt = m.loose.filter(bareSlug).filter((s) => !missing.includes(s.toLowerCase()));
275281 const kept = m.loose.filter((e) => !bareSlug(e) || missing.includes(e.toLowerCase()));
276282 const asked = (slugs: readonly string[]) => [
test/game-mods.test.ts +80
@@ -165,6 +165,8 @@ const PROJECTS = [
165165 { id: "LEid0001", slug: "ledger", title: "Ledger" },
166166 { id: "FKid0001", slug: "fabric-language-kotlin", title: "Fabric Language Kotlin" },
167167 ];
168 /** Who owns a project on the stand-in Modrinth, by id (#18196); one not here has no owner said. */
169 const OWNERS: Record<string, string> = { ECid0001: "patbox", SCid0001: "patbox" };
168170 const FABRIC = ["fabric"];
169171 const PAPER = ["paper", "spigot"];
170172 const VERSIONS: V[] = [
@@ -309,6 +311,11 @@ async function modrinth(url: string, init: RequestInit): Promise<Response> {
309311 const x = PROJECTS.find((y) => y.id === proj[1] || y.slug === proj[1]);
310312 return x === undefined ? new Response("{}", { status: 404 }) : json(x);
311313 }
314 const members = /^\/v2\/project\/([^/]+)\/members$/.exec(p);
315 if (members) {
316 const owner = OWNERS[members[1]!];
317 return owner === undefined ? new Response("{}", { status: 404 }) : json([{ role: "Owner", is_owner: true, user: { username: owner } }]);
318 }
312319 const list = /^\/v2\/project\/([^/]+)\/version$/.exec(p);
313320 if (list) {
314321 const games = JSON.parse(u.searchParams.get("game_versions") ?? "null") as string[] | null;
@@ -1075,3 +1082,76 @@ describe("the admin set", () => {
10751082 expect(removed.value.lock.map((l) => l.slug)).not.toContain("fabric-language-kotlin");
10761083 });
10771084 });
1085
1086 describe("a slug the lock holds is not followed to another project (#18196)", () => {
1087 const REFUSED = "essential-commands is now project ECid0002 by mallory; the lock holds ECid0001 by patbox — nothing installed. If it moved on purpose, remove Essential Commands and add essential-commands again.";
1088 const IMPOSTOR = { id: "ECid0002", slug: "essential-commands", title: "Essential Commands" };
1089
1090 test("the first install records the project id and its owner; a dependency records no owner", async () => {
1091 const planned = await planInstall(app, { ...(await mods("smp")), lock: [] }, "smp", "set:quality");
1092 if (!planned.ok) throw new Error(planned.error);
1093 expect(planned.value.lock.find((l) => l.slug === "essential-commands")).toMatchObject({ project: "ECid0001", author: "patbox", top: true });
1094 expect(planned.value.lock.find((l) => l.slug === "fabric-api")!.author).toBeUndefined();
1095 // The lock as committed: Essential Commands held as a dependency, so the set still asks for it.
1096 const held = { ...planned.value, lock: planned.value.lock.map((l) => (l.slug === "essential-commands" ? { ...l, top: false } : l)) };
1097 const done = await commitPlan(app, alice, box, "smp", await mods("smp"), held);
1098 if (!done.ok) throw new Error(done.error);
1099 expect((await mods("smp")).lock.find((l) => l.slug === "essential-commands")).toMatchObject({ project: "ECid0001", author: "patbox", top: false });
1100 });
1101
1102 test("the slug now naming another project is refused in words that name both, on the planner, the page, the MCP tool and the terminal; the lock is unchanged", async () => {
1103 PROJECTS.unshift(IMPOSTOR);
1104 OWNERS["ECid0002"] = "mallory";
1105 try {
1106 const before = await mods("smp");
1107 expect(await planInstall(app, before, "smp", "set:quality")).toEqual({ ok: false, error: REFUSED });
1108 expect(await planInstall(app, before, "smp", "essential-commands")).toEqual({ ok: false, error: REFUSED });
1109 expect(await (await asAlice("/games/net/smp?add=set:quality")).text()).toContain(REFUSED);
1110 const r = await asAlice("/games/net/smp/mods/install", { project: "set:quality", sha: before.sha });
1111 expect(r.status).not.toBe(500);
1112 const res = await http.handle(
1113 new Request(`${ORIGIN}/mcp`, {
1114 method: "POST",
1115 headers: { authorization: `Bearer ${tok}`, "content-type": "application/json", accept: "application/json, text/event-stream" },
1116 body: JSON.stringify({ jsonrpc: "2.0", id: 1, method: "tools/call", params: { name: "games", arguments: { box: "net", service: "smp", action: "mods_install", project: "set:quality", dryRun: false } } }),
1117 }),
1118 );
1119 const body = (await res.json()) as { result: { isError?: boolean; content: { text: string }[] } };
1120 expect(body.result.isError).toBe(true);
1121 expect(body.result.content[0]!.text).toContain(REFUSED);
1122 const terminal = headlessTerminal(240, 30);
1123 const { app: tui, session } = createForgeApp(app, { sshUsername: "alice", remoteAddress: "127.0.0.1", fingerprint: "SHA256:test", user: alice }, { terminal, exitHooks: false });
1124 tui.start();
1125 tui.ctx.push(gameModsScreen(session, tui.ctx, box, "smp"));
1126 await settleUntil(tui, "Quality of life set");
1127 terminal.feed("q");
1128 await settleUntil(tui, "essential-commands is now project ECid0002 by mallory");
1129 tui.stop?.();
1130 const after = await mods("smp");
1131 expect(after.sha).toBe(before.sha);
1132 expect(after.lock).toEqual(before.lock);
1133 } finally {
1134 PROJECTS.shift();
1135 delete OWNERS["ECid0002"];
1136 }
1137 }, 20_000);
1138
1139 test("the same project under another owner is refused too", async () => {
1140 OWNERS["ECid0001"] = "mallory";
1141 try {
1142 expect(await planInstall(app, await mods("smp"), "smp", "set:quality")).toMatchObject({
1143 ok: false,
1144 error: expect.stringContaining("essential-commands is now project ECid0001 by mallory; the lock holds ECid0001 by patbox — nothing installed."),
1145 });
1146 } finally {
1147 OWNERS["ECid0001"] = "patbox";
1148 }
1149 });
1150
1151 test("the same project id and owner installs, keeping the owner first seen", async () => {
1152 const planned = await planInstall(app, await mods("smp"), "smp", "set:quality");
1153 if (!planned.ok) throw new Error(planned.error);
1154 expect(planned.value.lock.find((l) => l.slug === "essential-commands")).toMatchObject({ project: "ECid0001", author: "patbox", top: true });
1155 expect(planned.value.lines.some((l) => l.includes("is now project"))).toBe(false);
1156 });
1157 });

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

Keyboard shortcuts

Docs