Public: anyone can read this; the crew can change it.
Games: the proxy's own plugins, pinned by sha256 and committed by the owner from a plan #17693
Merged 16h 57m ago, live in production
sold/proxy-jars → main 0 commits 3 threads · 3 unresolved
9 files
changed +701
−5
docs/features/games.md +25
| @@ -112,6 +112,31 @@ The Velocity forwarding secret (`forwarding.env`) and an RCON password a service | ||
| 112 | 112 | |
| 113 | 113 | The environment editor refuses a key that looks like a secret (`PASSWORD`, `SECRET`, `TOKEN`, `KEY` in its name): a secret belongs in the sealed `.env` the forge writes to the box, never in the repository. An env or plugin change is a commit by the person who asks, so it needs write access to the compose repository; without it the forge says to ask the repository's owner. |
| 114 | 114 | |
| 115 | ### The proxy's own plugins | |
| 116 | ||
| 117 | Today there is one: forge-velocity, which adds `/forge`. The forge knows each one's sha256 and refuses a file with another. It also refuses a second AutoStopper. | |
| 118 | ||
| 119 | To add one, on the proxy's page, under Forge plugins: | |
| 120 | ||
| 121 | 1. Upload the jar. Nothing changes on the proxy yet. | |
| 122 | 2. Read the lines the compose file gains. The proxy will restart, so everyone is disconnected. | |
| 123 | 3. An owner of the box presses **Save and restart the proxy**. That is a commit. | |
| 124 | ||
| 125 | If the page says the proxy is left as it is: | |
| 126 | ||
| 127 | 1. Upload the jar, if the page says nobody did. Take out a jar the page says is refused. | |
| 128 | 2. Commit a change to the compose file; a comment is enough. The box does not try the same commit twice. | |
| 129 | ||
| 130 | The other servers come up as usual meanwhile. This also happens when the box waited more than 6 hours to fetch the jar, because its address had run out. The next full sync brings a new one. | |
| 131 | ||
| 132 | If the page says that no change reaches the box until its agent updates, wait: nothing is lost. The agent updates itself when it syncs, and the box then takes the newest commit. | |
| 133 | ||
| 134 | How it works (`src/games/proxy_jars.ts`): | |
| 135 | ||
| 136 | - A full sync's `jars` gives each file's name, signed address and sha256. The address is signed for 6 hours and is new with each full sync. An empty sha256 is a refusal. | |
| 137 | - The box fetches and checks each jar before it recreates the proxy. It keeps them in `jars/`, mounted as `./jars:/forge-jars:ro`. | |
| 138 | - An agent that does this says `jars: true` in a full sync. Until it has, the plan cannot be saved, and a compose file that names such a jar is not sent to that box. | |
| 139 | ||
| 115 | 140 | A plugin or jar runs code on the game server; give operator only to people you trust. |
| 116 | 141 | |
| 117 | 142 | ## Numbers |
src/core/migration-pins/20261202214550-game-jars.pin added +1
| @@ -0,0 +1,1 @@ | ||
| 1 | feaf634380d9bbe7da851ec7c275462f645a612e0021f6db4dd32c579de0712b |
src/core/migrations/20261202214550-game-jars.ts added +5
src/games/proxy_jars.ts added +227
| @@ -0,0 +1,227 @@ | ||
| 1 | /** | |
| 2 | * The proxy's own plugins (#17610): jars the forge builds, each pinned here by its sha256. An | |
| 3 | * uploaded plugin's address goes in PLUGINS and the image downloads it unchecked once the proxy has | |
| 4 | * already stopped, so these go another way on the same jar store: the owner uploads the jar, the | |
| 5 | * bytes are matched to the pin, and the owner commits the change to the compose file after seeing it. | |
| 6 | * The sync then names each jar (`jars`), and the box has it, checked, before it recreates the proxy. | |
| 7 | * The agent keeps them in `jars/` beside the compose file, mounted read-only outside `/server`, whose | |
| 8 | * files the image's start changes owner of; PLUGINS names each, so the image copies it in. | |
| 9 | */ | |
| 10 | import type { App } from "../app.ts"; | |
| 11 | import type { User } from "../core/users.ts"; | |
| 12 | import { | |
| 13 | commitCompose, | |
| 14 | pluginUrls, | |
| 15 | readCompose, | |
| 16 | serviceEnv, | |
| 17 | setServiceEnv, | |
| 18 | setServiceListItem, | |
| 19 | } from "./compose.ts"; | |
| 20 | import { proxyOf } from "./sleep.ts"; | |
| 21 | import { keptJar, signedJarHref, type GameBox } from "./store.ts"; | |
| 22 | ||
| 23 | export interface Pin { | |
| 24 | readonly title: string; | |
| 25 | /** The file's name on the box. The image skips a file of the same name and size, so it holds the sha256's start. */ | |
| 26 | readonly name: string; | |
| 27 | readonly sha256: string; | |
| 28 | /** What it adds, for the owner. */ | |
| 29 | readonly does: string; | |
| 30 | } | |
| 31 | ||
| 32 | /** Built twice on the forge's Linux runner with the same bytes. */ | |
| 33 | export const PINS: readonly Pin[] = [ | |
| 34 | { | |
| 35 | title: "forge-velocity 0.1.0", | |
| 36 | name: "forge-velocity-0.1.0-b1cc4d0cfabf.jar", | |
| 37 | sha256: "b1cc4d0cfabf771ae1c85956148a83a352bc3271c1317fc08cbf67d9ad76da5f", | |
| 38 | does: "Players type /forge on any server of the network, and only they see the answer.", | |
| 39 | }, | |
| 40 | ]; | |
| 41 | export const pinOf = (sha256: string): Pin | undefined => | |
| 42 | PINS.find((p) => p.sha256 === sha256); | |
| 43 | /** A plugin that only comes pinned: an upload by this name with other bytes is refused. */ | |
| 44 | export const ONLY_PINNED = /^(?:forge-velocity|autostopper)/i; | |
| 45 | ||
| 46 | /** A jar the box must have, checked, before it recreates the proxy. */ | |
| 47 | export interface BoxJar { | |
| 48 | readonly name: string; | |
| 49 | /** Signed; "" when nobody uploaded it. */ | |
| 50 | readonly url: string; | |
| 51 | /** The forge's pin; "" is refused: no file satisfies it. */ | |
| 52 | readonly sha256: string; | |
| 53 | } | |
| 54 | ||
| 55 | const AT = "/forge-jars/"; | |
| 56 | /** The agent's own rule for a name (`jars_ready`). */ | |
| 57 | const NAME = /^[A-Za-z0-9][A-Za-z0-9._-]{0,99}\.jar$/; | |
| 58 | /** The one mount, for every jar. */ | |
| 59 | const MOUNT = "./jars:/forge-jars:ro"; | |
| 60 | /** The service the agent leaves as it is when a jar is missing or wrong. */ | |
| 61 | const HELD = "velocity"; | |
| 62 | ||
| 63 | /** How many AutoStoppers the proxy would be given: Velocity loads one of two, whichever is first. */ | |
| 64 | const autoStoppers = (text: string, proxy: string): number => | |
| 65 | [ | |
| 66 | ...pluginUrls(text, proxy), | |
| 67 | ...(serviceEnv(text, proxy)["MODRINTH_PROJECTS"] ?? "").split(/[\s,]+/), | |
| 68 | ].filter((p) => /autostopper|PG4gqnzX/i.test(p)).length; | |
| 69 | ||
| 70 | /** | |
| 71 | * Why a compose change does not reach `box`, or not its proxy: an agent that does not check the jars | |
| 72 | * is sent no change at all; one that does leaves the proxy as it is when a jar is refused or was | |
| 73 | * never uploaded, and tries again only when the file changes. "" when nothing is held back. | |
| 74 | */ | |
| 75 | export function heldWords( | |
| 76 | app: App, | |
| 77 | box: GameBox, | |
| 78 | compose: { sha: string; text: string } | undefined, | |
| 79 | pins: readonly Pin[] = PINS, | |
| 80 | ): string { | |
| 81 | if (compose === undefined || box.composeSha === compose.sha) return ""; | |
| 82 | const proxy = proxyOf(compose.text); | |
| 83 | if (proxy === undefined || !pluginUrls(compose.text, proxy).some((p) => p.startsWith(AT))) return ""; | |
| 84 | if (box.holdsJars) { | |
| 85 | const bad = jarsOf(app, box, compose.text, "", pins).find((j) => j.sha256 === "" || j.url === ""); | |
| 86 | if (bad === undefined) return ""; | |
| 87 | const why = | |
| 88 | autoStoppers(compose.text, proxy) > 1 | |
| 89 | ? "two AutoStoppers, and Velocity loads only one of them. Take one out of PLUGINS or MODRINTH_PROJECTS." | |
| 90 | : bad.sha256 === "" | |
| 91 | ? `${bad.name}, which this forge does not pin. Take it out of PLUGINS.` | |
| 92 | : `${bad.name}, which nobody uploaded to ${box.name}. Upload it under Forge plugins on ${proxy}'s page, then commit a change to ${box.path}, a comment is enough: the box tries again only when there is a new commit.`; | |
| 93 | return `${proxy} is left as it is, and the other servers come up: ${box.path} names ${why}`; | |
| 94 | } | |
| 95 | return `No change to ${box.path} reaches ${box.name} until its agent updates: the file names a forge plugin, and this agent is older than the one that checks it. Nothing is lost: the agent updates itself when it syncs, and then the box takes the newest commit.`; | |
| 96 | } | |
| 97 | ||
| 98 | /** The pinned jars the compose file's proxy names, for the sync. */ | |
| 99 | export function jarsOf( | |
| 100 | app: App, | |
| 101 | box: Pick<GameBox, "id">, | |
| 102 | text: string, | |
| 103 | origin: string, | |
| 104 | pins: readonly Pin[] = PINS, | |
| 105 | ): BoxJar[] { | |
| 106 | const proxy = proxyOf(text); | |
| 107 | if (proxy === undefined) return []; | |
| 108 | const refused = autoStoppers(text, proxy) > 1; | |
| 109 | return pluginUrls(text, proxy) | |
| 110 | .filter((p) => p.startsWith(AT)) | |
| 111 | .map((p) => { | |
| 112 | const said = p.slice(AT.length); | |
| 113 | const name = NAME.test(said) ? said : "refused.jar"; | |
| 114 | const pin = refused ? undefined : pins.find((one) => one.name === name); | |
| 115 | const kept = | |
| 116 | pin === undefined ? undefined : keptJar(app.db, box.id, pin.sha256); | |
| 117 | return { | |
| 118 | name, | |
| 119 | url: kept === undefined ? "" : `${origin}${signedJarHref(app, kept)}`, | |
| 120 | sha256: pin?.sha256 ?? "", | |
| 121 | }; | |
| 122 | }); | |
| 123 | } | |
| 124 | ||
| 125 | const volumesOf = (text: string, service: string): unknown[] => { | |
| 126 | const doc = Bun.YAML.parse(text) as { | |
| 127 | services?: Record<string, { volumes?: unknown }>; | |
| 128 | } | null; | |
| 129 | const volumes = doc?.services?.[service]?.volumes; | |
| 130 | return Array.isArray(volumes) ? volumes : []; | |
| 131 | }; | |
| 132 | ||
| 133 | /** The compose text with the proxy given `pin`; throws with the reason when it cannot be. */ | |
| 134 | function withJar(text: string, pin: Pin): string { | |
| 135 | const proxy = proxyOf(text); | |
| 136 | if (proxy === undefined) | |
| 137 | throw new Error( | |
| 138 | "This network has no proxy (itzg/mc-proxy) in its compose file.", | |
| 139 | ); | |
| 140 | if (proxy !== HELD) throw new Error(`The proxy's service must be called ${HELD}: the box holds back that one when a jar is wrong, and this one is ${proxy}.`); | |
| 141 | const plugins = pluginUrls(text, proxy); | |
| 142 | if (plugins.includes(AT + pin.name)) | |
| 143 | throw new Error(`${pin.title} is already there.`); | |
| 144 | const before = volumesOf(text, proxy); | |
| 145 | const mounted = before.includes(MOUNT); | |
| 146 | if (before.some((v) => v !== MOUNT && JSON.stringify(v).includes("/forge-jars"))) throw new Error(`${proxy} mounts something else at /forge-jars: it must be ${MOUNT}.`); | |
| 147 | const named = setServiceEnv(text, proxy, { PLUGINS: [...plugins, AT + pin.name].join(",") }); | |
| 148 | const out = mounted ? named : setServiceListItem(named, proxy, "volumes", MOUNT, [`- ${MOUNT}`]); | |
| 149 | if (autoStoppers(out, proxy) > 1) | |
| 150 | throw new Error( | |
| 151 | "The proxy would have two AutoStoppers, and Velocity loads only one of them. Nothing was changed.", | |
| 152 | ); | |
| 153 | // Read back: a list in a form the edit does not know is refused, never broken. | |
| 154 | let after: unknown[] = []; | |
| 155 | try { | |
| 156 | after = volumesOf(out, proxy); | |
| 157 | } catch {} | |
| 158 | if (!Bun.deepEquals(after, mounted ? before : [...before, MOUNT])) | |
| 159 | throw new Error( | |
| 160 | `${proxy}'s volumes are not a list the forge can add to: write them one to a line, then look again.`, | |
| 161 | ); | |
| 162 | return out; | |
| 163 | } | |
| 164 | ||
| 165 | export interface JarPlan { | |
| 166 | /** The commit it was planned on; the change lands on that one only. */ | |
| 167 | readonly sha: string; | |
| 168 | /** Each line the compose file gains. */ | |
| 169 | readonly lines: readonly string[]; | |
| 170 | readonly restart: string; | |
| 171 | /** Why it cannot be committed yet; "" when it can. */ | |
| 172 | readonly wait: string; | |
| 173 | } | |
| 174 | ||
| 175 | /** What giving the proxy `pin` changes. Nothing is committed. */ | |
| 176 | export async function planJar( | |
| 177 | app: App, | |
| 178 | box: GameBox, | |
| 179 | pin: Pin, | |
| 180 | ): Promise<{ ok: true; value: JarPlan } | { ok: false; error: string }> { | |
| 181 | const compose = await readCompose(app, box); | |
| 182 | if (compose === undefined) | |
| 183 | return { ok: false, error: `No ${box.path} on ${box.repo}@${box.branch}.` }; | |
| 184 | if (keptJar(app.db, box.id, pin.sha256) === undefined) | |
| 185 | return { | |
| 186 | ok: false, | |
| 187 | error: `Upload ${pin.title} first: the forge keeps no jar of this box with the sha256 it pins, ${pin.sha256}.`, | |
| 188 | }; | |
| 189 | try { | |
| 190 | const proxy = proxyOf(compose.text) ?? ""; | |
| 191 | const was = new Set(compose.text.split("\n")); | |
| 192 | const lines = withJar(compose.text, pin) | |
| 193 | .split("\n") | |
| 194 | .filter((l) => !was.has(l)) | |
| 195 | .map((l) => l.trim()); | |
| 196 | return { | |
| 197 | ok: true, | |
| 198 | value: { | |
| 199 | sha: compose.sha, | |
| 200 | lines, | |
| 201 | restart: `${proxy} restarts, so everyone on the network is disconnected and can join again once it is up.`, | |
| 202 | wait: box.holdsJars ? "" : `This cannot be applied yet: ${box.name}'s agent is older than the one that checks these jars. It updates itself when it syncs; then this can be committed.`, | |
| 203 | }, | |
| 204 | }; | |
| 205 | } catch (e) { | |
| 206 | return { ok: false, error: e instanceof Error ? e.message : String(e) }; | |
| 207 | } | |
| 208 | } | |
| 209 | ||
| 210 | /** Commit it as the person, on the commit the plan was shown for. */ | |
| 211 | export async function commitJar( | |
| 212 | app: App, | |
| 213 | user: User, | |
| 214 | box: GameBox, | |
| 215 | pin: Pin, | |
| 216 | sha: string, | |
| 217 | ): Promise<{ ok: true; sha: string } | { ok: false; error: string }> { | |
| 218 | const plan = await planJar(app, box, pin); | |
| 219 | if (!plan.ok) return plan; | |
| 220 | if (plan.value.wait !== "") return { ok: false, error: plan.value.wait }; | |
| 221 | return commitCompose(app, user, box, { | |
| 222 | message: `games: the proxy runs ${pin.title}`, | |
| 223 | what: "the proxy's plugins", | |
| 224 | edit: (text) => withJar(text, pin), | |
| 225 | expectTip: sha, | |
| 226 | }); | |
| 227 | } |
src/games/store.ts +15 −1
| @@ -55,6 +55,8 @@ export interface GameBox { | ||
| 55 | 55 | readonly snapshots: Record<string, Snapshot[]>; |
| 56 | 56 | /** The id of the box whose snapshot it was made from; empty for none. */ |
| 57 | 57 | readonly restoredFrom: string; |
| 58 | /** Its agent holds the proxy's pinned jars and checks them (`proxy_jars.ts`), as it last said. */ | |
| 59 | readonly holdsJars: boolean; | |
| 58 | 60 | } |
| 59 | 61 | |
| 60 | 62 | export interface GameService { |
| @@ -86,6 +88,7 @@ interface BoxRow { | ||
| 86 | 88 | diag_json: string; |
| 87 | 89 | snapshots_json: string; |
| 88 | 90 | restored_from: string; |
| 91 | jars: number; | |
| 89 | 92 | } |
| 90 | 93 | const toBox = (r: BoxRow): GameBox => { |
| 91 | 94 | let host: Record<string, number> = {}; |
| @@ -109,6 +112,7 @@ const toBox = (r: BoxRow): GameBox => { | ||
| 109 | 112 | diag: readDiag(r.diag_json), |
| 110 | 113 | snapshots: readSnapshots(r.snapshots_json), |
| 111 | 114 | restoredFrom: r.restored_from, |
| 115 | holdsJars: r.jars === 1, | |
| 112 | 116 | }; |
| 113 | 117 | }; |
| 114 | 118 | |
| @@ -548,6 +552,13 @@ const mayFetch = (db: Database, boxId: string, owner: string): boolean => | ||
| 548 | 552 | ) |
| 549 | 553 | .get(boxId, owner) !== null; |
| 550 | 554 | |
| 555 | /** The newest jar with these bytes that `boxId` may fetch. */ | |
| 556 | export const keptJar = (db: Database, boxId: string, sha256: string): { id: string; name: string } | undefined => | |
| 557 | db | |
| 558 | .query<{ id: string; name: string; box_id: string }, [string]>("SELECT id, name, box_id FROM game_jar WHERE sha256 = ?1 ORDER BY created_at DESC, id DESC") | |
| 559 | .all(sha256) | |
| 560 | .find((j) => mayFetch(db, boxId, j.box_id)); | |
| 561 | ||
| 551 | 562 | /** Compose text with each forge jar URL signed for the box that will fetch it. */ |
| 552 | 563 | export function signJarUrls(app: App, box: Pick<GameBox, "id">, compose: string, origin: string): string { |
| 553 | 564 | return compose.replace( |
| @@ -584,6 +595,8 @@ export interface SyncBody { | ||
| 584 | 595 | readonly lend?: unknown; |
| 585 | 596 | /** The box's word about its boot, sent without jq when a tool is missing or by the boot's report. */ |
| 586 | 597 | readonly boot?: string; |
| 598 | /** The agent holds the answer's `jars`, checked, before it recreates the proxy. */ | |
| 599 | readonly jars?: unknown; | |
| 587 | 600 | /** The sha256 of the token the box made for itself, until the forge has taken it. */ |
| 588 | 601 | readonly tokenSha?: unknown; |
| 589 | 602 | /** What the box sees of itself, about 8 KB (`diag.ts`): kept, replacing the last. */ |
| @@ -666,12 +679,13 @@ export function recordSync( | ||
| 666 | 679 | db.query("UPDATE game_box SET seen_at = ?2, boot = ?3 WHERE id = ?1").run(box.id, at, str(body.boot, 2_000)); |
| 667 | 680 | return; |
| 668 | 681 | } |
| 669 | db.query("UPDATE game_box SET seen_at = ?2, host_json = ?3, compose_sha = ?4, boot = '', diag_json = ?5 WHERE id = ?1").run( | |
| 682 | db.query("UPDATE game_box SET seen_at = ?2, host_json = ?3, compose_sha = ?4, boot = '', diag_json = ?5, jars = ?6 WHERE id = ?1").run( | |
| 670 | 683 | box.id, |
| 671 | 684 | at, |
| 672 | 685 | JSON.stringify(host), |
| 673 | 686 | str(body.composeSha, 80), |
| 674 | 687 | keptDiag(body.diag), |
| 688 | body.jars === true ? 1 : 0, | |
| 675 | 689 | ); |
| 676 | 690 | // An agent from before world snapshots sends none: the last list stays. |
| 677 | 691 | if (body.snapshots !== undefined) db.query("UPDATE game_box SET snapshots_json = ?2 WHERE id = ?1").run(box.id, keptSnapshots(body.snapshots)); |
src/http/games_routes.ts +11
| @@ -15,6 +15,7 @@ import { packChecks } from "../games/pack_check.ts"; | ||
| 15 | 15 | import { lendAnswer } from "../games/lend.ts"; |
| 16 | 16 | import { recordProxyEvents, tellRefused } from "../games/player_events.ts"; |
| 17 | 17 | import { proxyOf, sleeping } from "../games/sleep.ts"; |
| 18 | import { jarsOf } from "../games/proxy_jars.ts"; | |
| 18 | 19 | import { boxByToken, envFiles, markAsleep, recordSync, signJarUrls, swapGameBoxToken, type SyncBody } from "../games/store.ts"; |
| 19 | 20 | import { BODY_CAPS } from "../kernel/body_caps.ts"; |
| 20 | 21 | import { |
| @@ -79,6 +80,16 @@ export async function gameAgentSync(ctx: Ctx): Promise<Response> { | ||
| 79 | 80 | commands, |
| 80 | 81 | }; |
| 81 | 82 | if (compose !== undefined && compose.sha !== (typeof body.composeSha === "string" ? body.composeSha : "")) reply["compose"] = signJarUrls(ctx.app, box, compose.text, ctx.url.origin); |
| 83 | // The proxy's pinned plugins: the box has each, checked, before it recreates the proxy. | |
| 84 | const jars = compose === undefined ? [] : jarsOf(ctx.app, box, compose.text, ctx.url.origin); | |
| 85 | if (jars.length > 0) reply["jars"] = jars; | |
| 86 | // An agent that does not hold them is answered as if its file had not changed. Only leaving out | |
| 87 | // the file is not enough: a new `.env` would have the agent record a commit it never got. | |
| 88 | if (jars.length > 0 && body.jars !== true && reply["compose"] !== undefined) { | |
| 89 | delete reply["compose"]; | |
| 90 | reply["composeSha"] = typeof body.composeSha === "string" ? body.composeSha : ""; | |
| 91 | reply["env"] = {}; | |
| 92 | } | |
| 82 | 93 | // Which requests it took, whenever the box sent any: it deletes those and no other. |
| 83 | 94 | if (Array.isArray(body.ask)) reply["asked"] = asked; |
| 84 | 95 | const told = toldTo(ctx.app.db, box, Date.now(), body.got); |
src/web/pages/games.ts +67 −3
| @@ -29,6 +29,7 @@ import { | ||
| 29 | 29 | jarOf, |
| 30 | 30 | jarPath, |
| 31 | 31 | jarSignatureGood, |
| 32 | keptJar, | |
| 32 | 33 | listBoxes, |
| 33 | 34 | logsOf, |
| 34 | 35 | mayDo, |
| @@ -61,7 +62,8 @@ import { avatar, badge, btn, disclosure, field as input, row, rowList, time } fr | ||
| 61 | 62 | import { watchBox } from "../../games/notify.ts"; |
| 62 | 63 | import { accountLinks, chatLog, newLinkCode, playersOn, unlink } from "../../games/chat.ts"; |
| 63 | 64 | import { commitServer, planRemoveServer, planServer, wishOn } from "../../games/presets.ts"; |
| 64 | import { canSleep, commitPolicy, EMPTY_SECONDS, isGameServer, policyOf, proxyPort, STILL_BILLED } from "../../games/sleep.ts"; | |
| 65 | import { commitJar, heldWords, ONLY_PINNED, pinOf, PINS, planJar } from "../../games/proxy_jars.ts"; | |
| 66 | import { canSleep, commitPolicy, EMPTY_SECONDS, isGameServer, policyOf, proxyOf, proxyPort, STILL_BILLED } from "../../games/sleep.ts"; | |
| 65 | 67 | import { CLOUD_EVENT, cloudFacts, GAME_CLOUD_EVENT, pinnedOfBox } from "../../actions/cloud_says.ts"; |
| 66 | 68 | import { topologyBlock, TOPOLOGY_CSS } from "./games_topology.ts"; |
| 67 | 69 | import { defaultHeadResponse, headResponse } from "../../games/heads.ts"; |
| @@ -299,6 +301,7 @@ export async function gameBoxPage(ctx: Ctx): Promise<Response> { | ||
| 299 | 301 | ${cloud === undefined |
| 300 | 302 | ? null |
| 301 | 303 | : html`<div id="game-machine" data-live="${CLOUD_EVENT},${GAME_CLOUD_EVENT}">${rowList([row({ title: "Its machine", facts: [cloud] })])}</div>`} |
| 304 | ${heldNotice(ctx, box, compose)} | |
| 302 | 305 | ${joinBlock(ctx, box, visible, compose?.text)} |
| 303 | 306 | ${visible.length === 0 |
| 304 | 307 | ? emptyLine("gameServices") |
| @@ -553,9 +556,10 @@ export async function gameServicePage(ctx: Ctx): Promise<Response> { | ||
| 553 | 556 | act && packing !== "" ? planPack(ctx.app, mods.value, service, packing) : undefined, |
| 554 | 557 | ]) |
| 555 | 558 | : [undefined, undefined, undefined, undefined, undefined, undefined]; |
| 559 | const base = `/games/${box.name}/${service}`; | |
| 560 | const pinned = compose !== undefined && act && proxyOf(compose.text) === service ? await pinnedBlock(ctx, box, base, mayDo(role, "owner")) : undefined; | |
| 556 | 561 | const commands = recentCommands(ctx.app.db, box.id, service, 5); |
| 557 | 562 | const seen = servicesOf(ctx.app.db, box.id).find((s) => s.name === service); |
| 558 | const base = `/games/${box.name}/${service}`; | |
| 559 | 563 | const findings = findingsOf(ctx.app.db, box.id, service); |
| 560 | 564 | // Settings: each as the compose file says; a "Preview" (s.<key>=value in the query) planned on it. |
| 561 | 565 | const settings = compose === undefined ? [] : settingsOf(compose.text, service, env); |
| @@ -568,6 +572,7 @@ export async function gameServicePage(ctx: Ctx): Promise<Response> { | ||
| 568 | 572 | scriptJs: gamesConsoleJs, |
| 569 | 573 | body: html`${pageHead(service, { sub: `on ${box.name}`, actions: act ? power(box, service, seen) : undefined })} |
| 570 | 574 | <p class="game-now" id="game-now" aria-live="polite">${nowWords(seen, powerNow(ctx.app.db, box.id, service))}</p> |
| 575 | ${heldNotice(ctx, box, compose)} | |
| 571 | 576 | ${findingsBlock(findings)} |
| 572 | 577 | ${joinTrouble(ctx, box, service)} |
| 573 | 578 | ${peopleBlock(ctx, box, service, act)} |
| @@ -631,6 +636,7 @@ ${rawView ? tail.lines.join("\n") : raw(consoleHtml(tail.lines).join("\n"))}${ta | ||
| 631 | 636 | </section>`)} |
| 632 | 637 | ${numbersBlock(ctx, box, service)} |
| 633 | 638 | ${compose === undefined || !canSleep(compose.text, service) ? null : fold("Sleep", "sleep", false, sleepBlock(box, service, compose.text, seen?.asleep === true, act))} |
| 639 | ${pinned === undefined ? null : fold("Forge plugins", "forge-plugins", false, pinned)} | |
| 634 | 640 | ${fold("World", "world", commands.some((c) => c.kind === "world" && !c.done), worldBlock(box, service, act, commands))} |
| 635 | 641 | ${fold("Environment", "environment", false, html`<section class="settings-block"> |
| 636 | 642 | <h2>Environment</h2> |
| @@ -1318,18 +1324,76 @@ export const gameModPack = (ctx: Ctx): Promise<Response> => modsSubmit(ctx, (m, | ||
| 1318 | 1324 | // POST /games/:box/:service/mods/remove: a project, and what only it required. |
| 1319 | 1325 | export const gameModRemove = (ctx: Ctx): Promise<Response> => modsSubmit(ctx, (m, service, project) => planRemove(m, service, project)); |
| 1320 | 1326 | |
| 1321 | // POST /games/:box/:service/jar: an uploaded plugin jar, kept here and added to PLUGINS. | |
| 1327 | /** Why a compose change has not come to the box or its proxy, while one is held back. */ | |
| 1328 | const heldNotice = (ctx: Ctx, box: GameBox, compose: { sha: string; text: string } | undefined): Html | null => { | |
| 1329 | const words = heldWords(ctx.app, box, compose); | |
| 1330 | return words === "" ? null : html`<p class="notice" role="status">${words}</p>`; | |
| 1331 | }; | |
| 1332 | ||
| 1333 | /** The plugins the forge pins for the proxy: what each would change, and the owner's button that commits it. */ | |
| 1334 | async function pinnedBlock(ctx: Ctx, box: GameBox, base: string, owner: boolean): Promise<Html> { | |
| 1335 | const plans = await Promise.all(PINS.map(async (pin) => ({ pin, plan: await planJar(ctx.app, box, pin) }))); | |
| 1336 | return html`<section class="settings-block"> | |
| 1337 | <h2>Forge plugins</h2> | |
| 1338 | ${plans.map( | |
| 1339 | ({ pin, plan }) => html`<h3>${pin.title}</h3> | |
| 1340 | <p>${pin.does}</p> | |
| 1341 | ${plan.ok | |
| 1342 | ? html`${rowList([row({ title: `${box.path} gains` }), ...plan.value.lines.map((l) => row({ title: html`<span class="mono">${l}</span>` }))], { bare: true, label: `What ${box.path} gains` })} | |
| 1343 | <p>${plan.value.restart}</p> | |
| 1344 | ${plan.value.wait === "" ? null : html`<p class="notice">${plan.value.wait}</p>`} | |
| 1345 | ${owner && plan.value.wait === "" | |
| 1346 | ? html`<form method="post" action="${base}/jar" class="row-fields"> | |
| 1347 | <input type="hidden" name="pin" value="${pin.sha256}" /> | |
| 1348 | <input type="hidden" name="sha" value="${plan.value.sha}" /> | |
| 1349 | ${btn("Save and restart the proxy", { variant: "secondary" })} | |
| 1350 | </form>` | |
| 1351 | : null}` | |
| 1352 | : html`<p class="muted">${plan.error}</p>`}`, | |
| 1353 | )} | |
| 1354 | <form method="post" action="${base}/jar" enctype="multipart/form-data" class="row-fields"> | |
| 1355 | <input class="input" type="file" name="jar" accept=".jar" required aria-label="Forge plugin jar" /> | |
| 1356 | ${btn("Upload jar", { variant: "secondary" })} | |
| 1357 | </form> | |
| 1358 | </section>`; | |
| 1359 | } | |
| 1360 | ||
| 1361 | // POST /games/:box/:service/jar: an uploaded plugin jar, kept here and added to PLUGINS; on the | |
| 1362 | // proxy, one the forge pins is only kept, and `pin` with `sha` is the owner's commit of its plan. | |
| 1322 | 1363 | export async function gameJarSubmit(ctx: Ctx): Promise<Response> { |
| 1323 | 1364 | const service = ctx.params.service ?? ""; |
| 1324 | 1365 | const got = boxOf(ctx, "operator", service); |
| 1325 | 1366 | if (got instanceof Response) return got; |
| 1326 | 1367 | const form = await readForm(ctx, "rw", BODY_CAPS.gameJar.bytes); |
| 1327 | 1368 | if (form instanceof Response) return form; |
| 1369 | const compose = await readCompose(ctx.app, got.box); | |
| 1370 | const onProxy = compose !== undefined && proxyOf(compose.text) === service; | |
| 1371 | const plugins = `/games/${got.box.name}/${service}#forge-plugins`; | |
| 1372 | if (field(form, "pin") !== "") { | |
| 1373 | const owner = boxOf(ctx, "owner", service); | |
| 1374 | if (owner instanceof Response) return owner; | |
| 1375 | const pin = pinOf(field(form, "pin")); | |
| 1376 | if (pin === undefined || !onProxy) return notFoundPage(ctx); | |
| 1377 | const put = await commitJar(ctx.app, ctx.auth.user!, got.box, pin, field(form, "sha")); | |
| 1378 | return flashTo( | |
| 1379 | ctx, | |
| 1380 | plugins, | |
| 1381 | put.ok ? { message: `Committed ${put.sha.slice(0, 10)}; the proxy restarts with ${pin.title} once the box has checked the jar.` } : { tone: "danger", message: put.error }, | |
| 1382 | ); | |
| 1383 | } | |
| 1328 | 1384 | const file = form.get("jar"); |
| 1329 | 1385 | if (!(file instanceof File) || file.size === 0) |
| 1330 | 1386 | return flashTo(ctx, `/games/${got.box.name}/${service}`, { tone: "danger", message: "Choose a .jar file." }); |
| 1331 | 1387 | const jar = await storeJar(ctx.app, got.box.id, file, file.name); |
| 1332 | 1388 | if (!jar.ok) return flashTo(ctx, `/games/${got.box.name}/${service}`, { tone: "danger", message: jar.error }); |
| 1389 | if (onProxy) { | |
| 1390 | const pin = PINS.find((p) => keptJar(ctx.app.db, got.box.id, p.sha256)?.id === jar.id); | |
| 1391 | if (pin !== undefined) return flashTo(ctx, plugins, { message: `${pin.title} is kept here, its sha256 the one the forge pins. Nothing has changed on the proxy yet.` }); | |
| 1392 | if (ONLY_PINNED.test(jar.name)) { | |
| 1393 | await dropJar(ctx.app, jar.id); | |
| 1394 | return flashTo(ctx, plugins, { tone: "danger", message: `${jar.name} is not a build the forge pins, so it was not kept. Nothing has changed on the proxy.` }); | |
| 1395 | } | |
| 1396 | } | |
| 1333 | 1397 | const done = await addPluginUrl(ctx.app, ctx.auth.user!, got.box, service, `${ctx.url.origin}${jarHref(jar)}`); |
| 1334 | 1398 | if (!done.ok) await dropJar(ctx.app, jar.id); |
| 1335 | 1399 | return flashTo( |
test/game-proxy-jars.test.ts added +349
| @@ -0,0 +1,349 @@ | ||
| 1 | /** | |
| 2 | * The proxy's pinned plugins (#17610): the sha256 is the forge's, never the upload's. A jar with | |
| 3 | * other bytes, one nobody uploaded and a second AutoStopper are each refused before the running | |
| 4 | * proxy is touched: the upload, the plan and the sync's `jars` (which the box checks before it | |
| 5 | * recreates the proxy) each say no. | |
| 6 | */ | |
| 7 | import { afterAll, beforeAll, expect, test } from "bun:test"; | |
| 8 | import { mkdtemp, rm } from "node:fs/promises"; | |
| 9 | import { tmpdir } from "node:os"; | |
| 10 | import { join } from "node:path"; | |
| 11 | import { commitToBranch, createRepo } from "../src/actions/repos.ts"; | |
| 12 | import { createApp, type App } from "../src/app.ts"; | |
| 13 | import { createToken } from "../src/core/tokens.ts"; | |
| 14 | import { createUser, getUserByName, type User } from "../src/core/users.ts"; | |
| 15 | import { readCompose, serviceEnv } from "../src/games/compose.ts"; | |
| 16 | import { commitJar, heldWords, jarsOf, PINS, planJar, type Pin } from "../src/games/proxy_jars.ts"; | |
| 17 | import { AGENT_SH } from "../src/games/boot.ts"; | |
| 18 | import { AUTOSTOPPER } from "../src/games/sleep.ts"; | |
| 19 | import { boxNamed, createGameBox, grant, storeJar, type GameBox } from "../src/games/store.ts"; | |
| 20 | import { sha256 } from "../src/kernel/hash.ts"; | |
| 21 | import { forgeHttp, type ForgeHttp } from "../src/http/server.ts"; | |
| 22 | import { quietLogs } from "./helpers/globals.ts"; | |
| 23 | ||
| 24 | quietLogs(); | |
| 25 | ||
| 26 | const ORIGIN = "http://forge.test"; | |
| 27 | const GOOD = "PK\u0003\u0004 the plugin"; | |
| 28 | const pin = (title: string, body: string): Pin => ({ | |
| 29 | title, | |
| 30 | name: `${title}-${sha256(body).slice(0, 12)}.jar`, | |
| 31 | sha256: sha256(body), | |
| 32 | does: "Answers /forge.", | |
| 33 | }); | |
| 34 | const TALK = pin("forge-velocity", GOOD); | |
| 35 | const STOPPER = pin("AutoStopper", "PK\u0003\u0004 ours"); | |
| 36 | const pins = [TALK, STOPPER]; | |
| 37 | const COMPOSE = `services: | |
| 38 | velocity: | |
| 39 | image: itzg/mc-proxy:latest | |
| 40 | environment: | |
| 41 | TYPE: VELOCITY | |
| 42 | PLUGINS: "https://example.test/a.jar" | |
| 43 | volumes: | |
| 44 | - velocity:/server | |
| 45 | hub: | |
| 46 | image: itzg/minecraft-server:latest | |
| 47 | environment: | |
| 48 | TYPE: PAPER | |
| 49 | volumes: | |
| 50 | velocity: | |
| 51 | `; | |
| 52 | ||
| 53 | let dir = ""; | |
| 54 | let app: App; | |
| 55 | let http: ForgeHttp; | |
| 56 | let ada: User; | |
| 57 | let token = ""; | |
| 58 | let box: GameBox; | |
| 59 | const sync = async (more: object = { jars: true }): Promise<Record<string, unknown>> => | |
| 60 | (await ( | |
| 61 | await http.handle( | |
| 62 | new Request(`${ORIGIN}/api/v1/games/agent/sync`, { | |
| 63 | method: "POST", | |
| 64 | headers: { authorization: `Bearer ${token}`, "content-type": "application/json" }, | |
| 65 | body: JSON.stringify({ agent: 1, ...more }), | |
| 66 | }), | |
| 67 | ) | |
| 68 | ).json()) as Record<string, unknown>; | |
| 69 | const put = async (content: string) => { | |
| 70 | const repo = (await import("../src/core/repos.ts")).getRepo(app.db, "ada", "net")!; | |
| 71 | const done = await commitToBranch(app, ada, repo, { message: "net", files: [{ path: "docker-compose.yml", content }] }); | |
| 72 | if (!done.ok) throw new Error(JSON.stringify(done.error)); | |
| 73 | }; | |
| 74 | // git show's output is read without its last newline. | |
| 75 | const text = async () => `${(await readCompose(app, box))!.text}\n`; | |
| 76 | ||
| 77 | beforeAll(async () => { | |
| 78 | dir = await mkdtemp(join(tmpdir(), "forge-proxy-jars-")); | |
| 79 | app = createApp({ dataDir: dir, port: 0, modrinthFetch: (async () => Response.json([])) as unknown as typeof fetch }); | |
| 80 | http = forgeHttp(app); | |
| 81 | for (const username of ["ada", "bob"]) { | |
| 82 | const u = await createUser(app.db, { | |
| 83 | username, | |
| 84 | email: `${username}@f.test`, | |
| 85 | password: "a-good-passphrase", | |
| 86 | origin: "seed", | |
| 87 | isAdmin: username === "ada", | |
| 88 | trusted: true, | |
| 89 | }); | |
| 90 | if (!u.ok) throw new Error(u.error); | |
| 91 | } | |
| 92 | ada = getUserByName(app.db, "ada")!; | |
| 93 | const repo = await createRepo(app, ada, { name: "net", visibility: "private" }); | |
| 94 | if (!repo.ok) throw new Error(JSON.stringify(repo)); | |
| 95 | await put(COMPOSE); | |
| 96 | token = createGameBox(app.db, { name: "mc", repo: "ada/net" }).token; | |
| 97 | await sync(); | |
| 98 | box = boxNamed(app.db, "mc")!; | |
| 99 | }, 30_000); | |
| 100 | afterAll(async () => { | |
| 101 | app.close(); | |
| 102 | await rm(dir, { recursive: true, force: true }); | |
| 103 | }); | |
| 104 | ||
| 105 | test("no jar is named: the sync says nothing of jars", async () => { | |
| 106 | expect("jars" in (await sync())).toBe(false); | |
| 107 | expect(jarsOf(app, box, COMPOSE, ORIGIN, pins)).toEqual([]); | |
| 108 | }); | |
| 109 | ||
| 110 | test("a jar nobody uploaded, or with other bytes, has no plan; the sync names the pin and no address", async () => { | |
| 111 | expect(await planJar(app, box, TALK)).toMatchObject({ ok: false, error: expect.stringContaining("Upload") }); | |
| 112 | // Its name is right and its bytes are not: the pin is the forge's own. | |
| 113 | const other = await storeJar(app, box.id, new Blob(["PK\u0003\u0004 other bytes"]), TALK.name); | |
| 114 | expect(other.ok).toBe(true); | |
| 115 | expect(await planJar(app, box, TALK)).toMatchObject({ ok: false, error: expect.stringContaining("Upload") }); | |
| 116 | expect(await commitJar(app, ada, box, TALK, (await readCompose(app, box))!.sha)).toMatchObject({ ok: false }); | |
| 117 | expect(await text()).toBe(COMPOSE); | |
| 118 | const named = COMPOSE.replace("a.jar", `a.jar,/forge-jars/${TALK.name}`); | |
| 119 | expect(jarsOf(app, box, named, ORIGIN, pins)).toEqual([{ name: TALK.name, url: "", sha256: TALK.sha256 }]); | |
| 120 | }); | |
| 121 | ||
| 122 | test("a file the forge does not pin is refused in the sync, whatever its name", () => { | |
| 123 | const named = COMPOSE.replace("a.jar", "a.jar,/forge-jars/mine.jar,/forge-jars/../../etc/x.jar"); | |
| 124 | expect(jarsOf(app, box, named, ORIGIN, pins)).toEqual([ | |
| 125 | { name: "mine.jar", url: "", sha256: "" }, | |
| 126 | { name: "refused.jar", url: "", sha256: "" }, | |
| 127 | ]); | |
| 128 | }); | |
| 129 | ||
| 130 | test("a box whose agent does not hold jars: the plan says so, nothing is committed, and the sync sends it no such file", async () => { | |
| 131 | expect((await storeJar(app, box.id, new Blob([GOOD]), "early.jar")).ok).toBe(true); | |
| 132 | await sync({}); | |
| 133 | box = boxNamed(app.db, "mc")!; | |
| 134 | const plan = await planJar(app, box, TALK); | |
| 135 | if (!plan.ok) throw new Error(plan.error); | |
| 136 | expect(plan.value.lines.length).toBeGreaterThan(0); | |
| 137 | expect(plan.value.wait).toContain("agent"); | |
| 138 | expect(await commitJar(app, ada, box, TALK, plan.value.sha)).toEqual({ ok: false, error: plan.value.wait }); | |
| 139 | expect(await text()).toBe(COMPOSE); | |
| 140 | // Committed by hand all the same: an older agent is answered as if its file had not changed. | |
| 141 | await put(COMPOSE.replace("a.jar", `a.jar,/forge-jars/${TALK.name}`)); | |
| 142 | const old = await sync({ composeSha: "the-one-it-runs" }); | |
| 143 | expect(old["composeSha"]).toBe("the-one-it-runs"); | |
| 144 | expect("compose" in old).toBe(false); | |
| 145 | expect(old["env"]).toEqual({}); | |
| 146 | // Its pages say why the change has not come, and only while it has not. | |
| 147 | const tok = createToken(app.db, ada.id, "r", "ro").token; | |
| 148 | const page = async (path: string) => (await http.handle(new Request(`${ORIGIN}/games/mc${path}`, { headers: { authorization: `Bearer ${tok}` } }))).text(); | |
| 149 | const says = "No change to docker-compose.yml reaches mc until its agent updates"; | |
| 150 | for (const path of ["", "/velocity", "/hub"]) expect(await page(path)).toContain(says); | |
| 151 | const held = await sync({ composeSha: "the-one-it-runs", jars: true }); | |
| 152 | for (const path of ["", "/velocity", "/hub"]) expect(await page(path)).not.toContain(says); | |
| 153 | expect(held["compose"]).toContain(TALK.name); | |
| 154 | expect(Object.keys(held["env"] as object)).toEqual([".env"]); | |
| 155 | // Running it already, or a file that names no jar: nothing is held back. | |
| 156 | await sync({ composeSha: (await readCompose(app, box))!.sha }); | |
| 157 | expect(await page("")).not.toContain(says); | |
| 158 | await put(COMPOSE); | |
| 159 | await sync({ composeSha: "the-one-it-runs" }); | |
| 160 | expect(await page("")).not.toContain(says); | |
| 161 | await sync(); | |
| 162 | box = boxNamed(app.db, "mc")!; | |
| 163 | }); | |
| 164 | ||
| 165 | test("a proxy left as it is for a jar nobody uploaded, one the forge does not pin or two AutoStoppers: its pages say which and what to do", async () => { | |
| 166 | const pinned = PINS[0]!; | |
| 167 | await put(COMPOSE.replace("a.jar", `a.jar,/forge-jars/${pinned.name}`)); | |
| 168 | await sync({ composeSha: "the-one-it-runs", jars: true }); | |
| 169 | box = boxNamed(app.db, "mc")!; | |
| 170 | const tok = createToken(app.db, ada.id, "r", "ro").token; | |
| 171 | const page = async (path: string) => (await http.handle(new Request(`${ORIGIN}/games/mc${path}`, { headers: { authorization: `Bearer ${tok}` } }))).text(); | |
| 172 | for (const path of ["", "/velocity"]) { | |
| 173 | const html = await page(path); | |
| 174 | expect(html).toContain(`names ${pinned.name}, which nobody uploaded to mc. Upload it under Forge plugins`); | |
| 175 | expect(html).toContain("then commit a change to docker-compose.yml"); | |
| 176 | } | |
| 177 | const words = (names: string[], more = "") => { | |
| 178 | const t = COMPOSE.replace("a.jar", ["a.jar", ...names.map((n) => `/forge-jars/${n}`)].join(",")).replace(" TYPE: VELOCITY\n", ` TYPE: VELOCITY\n${more}`); | |
| 179 | return heldWords(app, box, { sha: "new", text: t }, pins); | |
| 180 | }; | |
| 181 | expect(words(["mine.jar"])).toContain("names mine.jar, which this forge does not pin. Take it out of PLUGINS"); | |
| 182 | expect(words([STOPPER.name], ` MODRINTH_PROJECTS: "${AUTOSTOPPER}"\n`)).toContain("names two AutoStoppers"); | |
| 183 | // A jar the forge keeps, or the commit the box already runs: nothing to say. | |
| 184 | expect((await storeJar(app, box.id, new Blob([GOOD]), "kept.jar")).ok).toBe(true); | |
| 185 | expect(words([TALK.name])).toBe(""); | |
| 186 | await sync({ composeSha: (await readCompose(app, box))!.sha, jars: true }); | |
| 187 | expect(await page("/velocity")).not.toContain("which nobody uploaded"); | |
| 188 | app.db.query("DELETE FROM game_jar").run(); | |
| 189 | await put(COMPOSE); | |
| 190 | await sync(); | |
| 191 | box = boxNamed(app.db, "mc")!; | |
| 192 | }); | |
| 193 | ||
| 194 | test("the plan shows each line and the restart, commits nothing by itself, and lands only on the file it showed", async () => { | |
| 195 | const kept = await storeJar(app, box.id, new Blob([GOOD]), "whatever.jar"); | |
| 196 | expect(kept.ok).toBe(true); | |
| 197 | const plan = await planJar(app, box, TALK); | |
| 198 | if (!plan.ok) throw new Error(plan.error); | |
| 199 | expect(plan.value.lines.join("\n")).toContain("./jars:/forge-jars:ro"); | |
| 200 | expect(plan.value.lines.join("\n")).toContain("PLUGINS"); | |
| 201 | expect(plan.value.restart).toContain("disconnected"); | |
| 202 | expect(await text()).toBe(COMPOSE); | |
| 203 | ||
| 204 | await put(`${COMPOSE}# later\n`); | |
| 205 | expect(plan.value.wait).toBe(""); | |
| 206 | expect(await commitJar(app, ada, box, TALK, plan.value.sha)).toMatchObject({ ok: false }); | |
| 207 | expect(await text()).toBe(`${COMPOSE}# later\n`); | |
| 208 | ||
| 209 | expect(await commitJar(app, ada, box, TALK, (await readCompose(app, box))!.sha)).toMatchObject({ ok: true }); | |
| 210 | const now = await text(); | |
| 211 | expect(serviceEnv(now, "velocity")["PLUGINS"]).toBe(`https://example.test/a.jar,/forge-jars/${TALK.name}`); | |
| 212 | const doc = Bun.YAML.parse(now) as { services: { velocity: { volumes: string[] } } }; | |
| 213 | expect(doc.services.velocity.volumes).toEqual([ | |
| 214 | "velocity:/server", | |
| 215 | "./jars:/forge-jars:ro", | |
| 216 | ]); | |
| 217 | expect(await planJar(app, box, TALK)).toMatchObject({ ok: false, error: expect.stringContaining("already") }); | |
| 218 | ||
| 219 | // The box's address for it is signed, and serves the pinned bytes. | |
| 220 | const [jar] = jarsOf(app, box, now, ORIGIN, pins); | |
| 221 | expect(jar).toMatchObject({ name: TALK.name, sha256: TALK.sha256 }); | |
| 222 | const got = await http.handle(new Request(jar!.url)); | |
| 223 | expect(got.status).toBe(200); | |
| 224 | expect(sha256(await got.text())).toBe(TALK.sha256); | |
| 225 | // Another box's sync gets no address for it. | |
| 226 | expect(jarsOf(app, { id: "another-box" }, now, ORIGIN, pins)[0]!.url).toBe(""); | |
| 227 | // This forge pins other bytes, so its own sync refuses the file this test pinned. | |
| 228 | expect((await sync())["jars"]).toEqual([{ name: TALK.name, url: "", sha256: "" }]); | |
| 229 | }); | |
| 230 | ||
| 231 | test("a second AutoStopper: no plan, and every jar of the proxy refused in the sync", async () => { | |
| 232 | const sleeps = COMPOSE.replace(" TYPE: VELOCITY\n", ` TYPE: VELOCITY\n MODRINTH_PROJECTS: "${AUTOSTOPPER}"\n`); | |
| 233 | await put(sleeps); | |
| 234 | expect((await storeJar(app, box.id, new Blob(["PK\u0003\u0004 ours"]), "x.jar")).ok).toBe(true); | |
| 235 | expect(await planJar(app, box, STOPPER)).toMatchObject({ ok: false, error: expect.stringContaining("AutoStopper") }); | |
| 236 | const both = sleeps.replace("a.jar", `a.jar,/forge-jars/${TALK.name},/forge-jars/${STOPPER.name}`); | |
| 237 | expect(jarsOf(app, box, both, ORIGIN, pins).map((j) => j.sha256)).toEqual(["", ""]); | |
| 238 | // One AutoStopper beside forge-velocity is fine. | |
| 239 | expect(jarsOf(app, box, sleeps.replace("a.jar", `a.jar,/forge-jars/${TALK.name}`), ORIGIN, pins).map((j) => j.sha256)).toEqual([ | |
| 240 | TALK.sha256, | |
| 241 | ]); | |
| 242 | }); | |
| 243 | ||
| 244 | test("the mount is added once: a second jar changes PLUGINS alone, and another mount there is refused", async () => { | |
| 245 | const mounted = COMPOSE.replace(" - velocity:/server\n", " - velocity:/server\n - ./jars:/forge-jars:ro\n"); | |
| 246 | await put(mounted); | |
| 247 | const plan = await planJar(app, box, TALK); | |
| 248 | if (!plan.ok) throw new Error(plan.error); | |
| 249 | expect(plan.value.lines).toEqual([`PLUGINS: "https://example.test/a.jar,/forge-jars/${TALK.name}"`]); | |
| 250 | for (const other of ["./mine:/forge-jars:ro", "./jars:/forge-jars"]) { | |
| 251 | await put(mounted.replace("./jars:/forge-jars:ro", other)); | |
| 252 | expect(await planJar(app, box, TALK)).toMatchObject({ ok: false, error: expect.stringContaining("/forge-jars") }); | |
| 253 | } | |
| 254 | }); | |
| 255 | ||
| 256 | test("a proxy the box's agent would not hold back is refused: it knows the service velocity", async () => { | |
| 257 | await put(COMPOSE.replace(" velocity:\n image", " proxy:\n image")); | |
| 258 | expect(await planJar(app, box, TALK)).toMatchObject({ ok: false, error: expect.stringContaining("velocity") }); | |
| 259 | }); | |
| 260 | ||
| 261 | test("the agent's own check takes what the sync names, and refuses an empty sha256 or address", async () => { | |
| 262 | const program = /jq -e '(type == "array" and length <= 8[^']+)'/.exec(AGENT_SH)?.[1]; | |
| 263 | expect(program).toBeDefined(); | |
| 264 | const takes = async (jars: unknown): Promise<boolean> => | |
| 265 | (await Bun.spawn(["jq", "-e", program!], { stdin: new Blob([JSON.stringify(jars)]), stdout: "ignore", stderr: "ignore" }).exited) === 0; | |
| 266 | const named = (name: string) => COMPOSE.replace("a.jar", `a.jar,/forge-jars/${name}`); | |
| 267 | const good = jarsOf(app, box, named(TALK.name), ORIGIN, pins); | |
| 268 | expect(good[0]!.url).toStartWith(ORIGIN); | |
| 269 | expect(await takes(good)).toBe(true); | |
| 270 | expect(await takes(jarsOf(app, box, named("mine.jar"), ORIGIN, pins))).toBe(false); | |
| 271 | expect(await takes(jarsOf(app, { id: "another-box" }, named(TALK.name), ORIGIN, pins))).toBe(false); | |
| 272 | // What the forge pins passes by name and number too. | |
| 273 | expect(await takes(PINS.map((p) => ({ name: p.name, url: `${ORIGIN}/x`, sha256: p.sha256 })))).toBe(true); | |
| 274 | }); | |
| 275 | ||
| 276 | test("volumes written on one line are refused, not broken", async () => { | |
| 277 | await put(COMPOSE.replace(" volumes:\n - velocity:/server\n", ` volumes: ["velocity:/server"]\n`)); | |
| 278 | const before = await text(); | |
| 279 | expect(await planJar(app, box, TALK)).toMatchObject({ ok: false, error: expect.stringContaining("volumes") }); | |
| 280 | expect(await text()).toBe(before); | |
| 281 | }); | |
| 282 | ||
| 283 | test("the upload form on the proxy keeps no forge-velocity or AutoStopper the forge does not pin", async () => { | |
| 284 | await put(COMPOSE); | |
| 285 | const tok = createToken(app.db, ada.id, "rw", "rw").token; | |
| 286 | const upload = (name: string) => { | |
| 287 | const form = new FormData(); | |
| 288 | form.set("jar", new File([GOOD], name)); | |
| 289 | return http.handle( | |
| 290 | new Request(`${ORIGIN}/games/mc/velocity/jar`, { | |
| 291 | method: "POST", | |
| 292 | headers: { authorization: `Bearer ${tok}`, origin: ORIGIN }, | |
| 293 | body: form, | |
| 294 | }), | |
| 295 | ); | |
| 296 | }; | |
| 297 | const jars = () => app.db.query<{ n: number }, []>("SELECT COUNT(*) AS n FROM game_jar").get()!.n; | |
| 298 | const before = jars(); | |
| 299 | for (const name of ["forge-velocity-0.1.0.jar", "AutoStopper-3.0.0-forge.1.jar"]) { | |
| 300 | expect((await upload(name)).status).toBe(303); | |
| 301 | expect(jars()).toBe(before); | |
| 302 | expect(await text()).toBe(COMPOSE); | |
| 303 | } | |
| 304 | // The proxy's page names what is missing; a game server's has no such part. | |
| 305 | const page = async (service: string) => (await http.handle(new Request(`${ORIGIN}/games/mc/${service}`, { headers: { authorization: `Bearer ${tok}` } }))).text(); | |
| 306 | expect(await page("velocity")).toContain("Upload forge-velocity 0.1.0 first"); | |
| 307 | expect(await page("hub")).not.toContain("Forge plugins"); | |
| 308 | // Another plugin goes the way it always did. | |
| 309 | expect((await upload("other.jar")).status).toBe(303); | |
| 310 | expect(jars()).toBe(before + 1); | |
| 311 | expect(serviceEnv(await text(), "velocity")["PLUGINS"]).toContain("/games/jar/"); | |
| 312 | }); | |
| 313 | ||
| 314 | test("the proxy's page shows the gained lines as rows, not in a box", async () => { | |
| 315 | await put(COMPOSE); | |
| 316 | await sync(); | |
| 317 | const stands = "PK\u0003\u0004 stands for the pinned one"; | |
| 318 | expect((await storeJar(app, box.id, new Blob([stands]), "z.jar")).ok).toBe(true); | |
| 319 | app.db.query("UPDATE game_jar SET sha256 = ?1 WHERE sha256 = ?2").run(PINS[0]!.sha256, sha256(stands)); | |
| 320 | const tok = createToken(app.db, ada.id, "r", "ro").token; | |
| 321 | const html = await (await http.handle(new Request(`${ORIGIN}/games/mc/velocity`, { headers: { authorization: `Bearer ${tok}` } }))).text(); | |
| 322 | const part = html.slice(html.indexOf("<h2>Forge plugins</h2>")).split("</section>")[0]!; | |
| 323 | expect(part).toContain('aria-label="What docker-compose.yml gains"'); | |
| 324 | expect(part).toContain('<span class="mono">- ./jars:/forge-jars:ro</span>'); | |
| 325 | expect(part).toContain("Save and restart the proxy"); | |
| 326 | expect(part).not.toContain("<pre"); | |
| 327 | app.db.query("DELETE FROM game_jar WHERE sha256 = ?1").run(PINS[0]!.sha256); | |
| 328 | }); | |
| 329 | ||
| 330 | test("only an owner of the box commits a pinned plugin", async () => { | |
| 331 | await put(COMPOSE); | |
| 332 | const bob = getUserByName(app.db, "bob")!; | |
| 333 | grant(app.db, box.id, bob.id, "operator", ""); | |
| 334 | const tok = createToken(app.db, bob.id, "rw", "rw").token; | |
| 335 | const r = await http.handle( | |
| 336 | new Request(`${ORIGIN}/games/mc/velocity/jar`, { | |
| 337 | method: "POST", | |
| 338 | headers: { authorization: `Bearer ${tok}`, origin: ORIGIN, "content-type": "application/x-www-form-urlencoded" }, | |
| 339 | body: new URLSearchParams({ pin: PINS[0]!.sha256, sha: (await readCompose(app, box))!.sha }), | |
| 340 | }), | |
| 341 | ); | |
| 342 | expect(r.status).toBe(404); | |
| 343 | expect(await text()).toBe(COMPOSE); | |
| 344 | }); | |
| 345 | ||
| 346 | test("what the forge pins today: forge-velocity alone, its file named by its sha256", () => { | |
| 347 | expect(PINS.map((p) => p.title)).toEqual(["forge-velocity 0.1.0"]); | |
| 348 | for (const p of PINS) expect(p.name).toContain(p.sha256.slice(0, 12)); | |
| 349 | }); |
test/game-spare.test.ts +1 −1
| @@ -150,7 +150,7 @@ test("the row is two label/value facts, and kept a minute per box so a redraw re | ||
| 150 | 150 | db.exec((await import("../src/core/migrations/20261201050000-game-metrics.ts")).default); |
| 151 | 151 | db.exec((await import("../src/core/migrations/20261202000000-game-people.ts")).default.replace(/^.*game_box.*$/m, "")); |
| 152 | 152 | const dataDir = mkdtempSync(join(tmpdir(), "spare-row-")); |
| 153 | const box: GameBox = { id: "b", name: "b", repo: "a/b", branch: "main", path: "", pinnedId: "", place: "", monthlyCents: 0, host: {}, composeSha: "", seenAt: "", createdAt: "", boot: "", diag: {} as GameBox["diag"], snapshots: {}, restoredFrom: "" }; | |
| 153 | const box: GameBox = { id: "b", name: "b", repo: "a/b", branch: "main", path: "", pinnedId: "", place: "", monthlyCents: 0, host: {}, composeSha: "", seenAt: "", createdAt: "", boot: "", diag: {} as GameBox["diag"], snapshots: {}, restoredFrom: "", holdsJars: false, }; | |
| 154 | 154 | const now = Date.parse("2026-12-02T00:00:00Z"); |
| 155 | 155 | const first = spareRow(db, dataDir, box, now); |
| 156 | 156 | expect(first[1]).toEqual(["Forge checks, last 7 days", "not measured"]); |
new above
offline
Principle 8: one dense paragraph mixes the owner's steps with the agent's internals. Split it and use plain words.