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

Games G6: Settings: server.properties and Paper config editors with a preview and one commit (#17284) #17319

opened this

Merged 38h 43m ago, live in production

sold/game-config → main 0 commits 3 threads · 3 unresolved

  • Merged. sold/game-config was merged into main as d297ea6.

Review

Sign in to review this change.
14 files changed +1405 −20
docs/features/game-settings.md added +30
@@ -0,0 +1,30 @@
1 ---
2 topic: Hosting forges for others, and getting paid
3 row: Game settings
4 ---
5 # Game settings
6
7 `/games/<box>/<service>` has a **Settings** block: about 45 `server.properties` keys and, on a server whose `TYPE` is `PAPER`, `PURPUR` or `FOLIA`, about 30 of Paper's own (`paper-global.yml`, `paper-world-defaults.yml`). They are grouped (Players, World, Performance, Network, Paper). Each shows its value, where the value comes from (the compose env, the forge's Paper patch, the network config, or the default) and whether it is changed from the default. The schema, with each key's type, default and the itzg env var that sets it, is `src/games/settings.ts`.
8
9 ## A change
10
11 Change values and press **Preview**. The preview says what each change writes, for example `VIEW_DISTANCE 10 → 12 (env)` or `paper-world-defaults entities.spawning.per-player-mob-spawns true → false (patch)`, and that the server restarts. A value out of range, not one of the choices, or a key that cannot be changed here is refused with the reason. **Commit and restart** makes one commit, `games: <service> settings: <keys>`, on the commit you previewed. If the branch moved since, nothing is committed and the forge asks you to look again. The box applies it on its next sync, as it does an env change. The commit needs write access to the compose repository, as an env change does.
12
13 ## Where a value goes
14
15 The itzg image is what applies a setting, so the forge writes each setting where the image reads it:
16
17 - **A `server.properties` key with an itzg env var** (`files/property-definitions.json` in the image: `VIEW_DISTANCE`, `MODE`, `WHITELIST_PROP`, …) is that env var. The image writes it into `server.properties` at every start.
18 - **A key without one** (`enable-code-of-conduct`) is a `name=value` line of `CUSTOM_SERVER_PROPERTIES`. Lines already there are kept.
19 - **Back to the default** writes the default value. Removing an env var does not reset the property: `server.properties` keeps its last value.
20 - **A Paper key** is a `$set` in the forge's patch set, an inline compose config `<service>_forge_settings` mounted read-only at `/patches/forge-settings.json` and named by `PATCH_DEFINITIONS`. The image applies it to `/data/config/paper-*.yml` before the server starts. The image skips a patch whose file does not exist yet, so a Paper file the network config does not mount is seeded with the keys set (`<service>_forge_paper_world_defaults` at `/config/paper-world-defaults.yml`, which the image copies to `/data/config`). The change then holds from the first start.
21
22 The network's own `paper_global` config is never rewritten. A key it sets (Velocity forwarding, `unsupported-settings.perform-username-validation`) shows as set by the network config and is read-only. So is `online-mode` on a server behind Velocity, where the proxy checks accounts. A service whose `PATCH_DEFINITIONS` already names another patch set is refused Paper changes.
23
24 ## Doors
25
26 - **Web:** the Settings block on `/games/<box>/<service>` (`src/web/pages/games.ts`); the commit is `POST /games/<box>/<service>/settings`.
27 - **Terminal:** `c` on a service opens its settings (`src/tui/screens/games.ts`): `enter` sets one, the preview shows on top, `y` commits it, `x` drops it.
28 - **MCP:** `games` with `action: "config"` lists a service's settings; `action: "config_set"` with `key` and `value` returns the plan, and with `dryRun: false` commits it.
29
30 Ports, RCON, the query and management servers, and the level name are not here: the box and the network depend on them. Set them with the environment editor.
docs/features/games.md +3 −3
@@ -8,9 +8,9 @@ A **game box** is a VM on your own cloud running Docker and `forge-game-agent`,
88
99 ## Where
1010
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 and an RCON input whose answer shows inline), the environment editor (commits `games: <service> env: <keys>`) 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`.
13 - **MCP:** `games` (admin-listed tonight): `list`, `console`, `power`, `env`, `plugin`, 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 and an RCON input whose answer shows inline), the environment editor (commits `games: <service> env: <keys>`), the settings ([Game 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.
13 - **MCP:** `games` (admin-listed tonight): `list`, `console`, `power`, `env`, `plugin`, `config`, `config_set`, with the same grants.
1414 - **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.
1515
1616 ## What a sync carries
src/crew/conversation_ask.ts +1
@@ -327,6 +327,7 @@ export const ASKED_AS: Readonly<Record<string, Form>> = {
327327 if (a["action"] === "power") return `${val(a, "kind") || "Restart"} ${on}`.replace(/^./, (c) => c.toUpperCase());
328328 if (a["action"] === "env") return `Set ${val(a, "key")} on ${on}${clause(" to ", val(a, "value"))}, a commit that redeploys it`;
329329 if (a["action"] === "plugin") return `Add the plugin ${val(a, "modrinth") || val(a, "value")} to ${on}, a commit that redeploys it`;
330 if (a["action"] === "config_set") return `Set the setting ${val(a, "key")} on ${on}${clause(" to ", val(a, "value"))}, a commit that restarts it`;
330331 return `Change ${on}`;
331332 },
332333 crew_accounts: (a) => `Let the crew's runs for ${val(a, "repo") || val(a, "owner") || "your repositories"} spend the account ${val(a, "allow")}`,
src/games/compose.ts +31 −6
@@ -110,12 +110,15 @@ export function setServiceEnv(text: string, service: string, values: Record<stri
110110 listForm ? `${" ".repeat(itemIndent)}- ${quote(`${k}=${v}`)}` : `${" ".repeat(itemIndent)}${k}: ${quote(v)}`;
111111 const left = { ...values };
112112 const next: string[] = [];
113 for (const l of body) {
113 for (let i = 0; i < body.length; i++) {
114 const l = body[i]!;
114115 const k = keyOf(l);
115116 if (k !== undefined && k in left) {
116117 const v = left[k];
117118 delete left[k];
118119 if (v !== null && v !== undefined) next.push(render(k, v));
120 // A value written over several lines (a `|` block) goes with its key.
121 while (i + 1 < body.length && (body[i + 1]!.trim() === "" || indentOf(body[i + 1]!) > itemIndent)) i++;
119122 } else next.push(l);
120123 }
121124 for (const [k, v] of Object.entries(left)) if (v !== null) next.push(render(k, v));
@@ -136,23 +139,45 @@ export async function commitServiceEnv(
136139 ): Promise<{ ok: true; sha: string } | { ok: false; error: string }> {
137140 const secret = Object.keys(values).find((k) => SECRET_KEY.test(k));
138141 if (secret !== undefined)
139 return { ok: false, 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.` };
142 return {
143 ok: false,
144 error: `${secret} looks like a secret, and the repository is no place for one: the forge seals secrets and writes them to the box's .env itself.`,
145 };
146 return commitCompose(app, user, box, {
147 message: `games: ${service} env: ${Object.keys(values).sort().join(", ")}`,
148 what: "env",
149 edit: (text) => setServiceEnv(text, service, values),
150 });
151 }
152
153 /**
154 * One commit of the compose file: `edit` makes the new text from the text at the branch's tip (it
155 * throws to refuse, with the reason), on `expectTip` when given, the commit a change was previewed
156 * on, so two changes never land on each other unseen.
157 */
158 export async function commitCompose(
159 app: App,
160 user: User,
161 box: GameBox,
162 change: { message: string; what: string; edit: (text: string) => string; expectTip?: string },
163 ): Promise<{ ok: true; sha: string } | { ok: false; error: string }> {
140164 const compose = await readCompose(app, box);
141165 if (compose === undefined) return { ok: false, error: `No ${box.path} on ${box.repo}@${box.branch}.` };
166 if (change.expectTip !== undefined && change.expectTip !== compose.sha)
167 return { ok: false, error: `${box.repo}@${box.branch} moved on since this was previewed; look again and redo it.` };
142168 let text: string;
143169 try {
144 text = setServiceEnv(compose.text, service, values);
170 text = change.edit(compose.text);
145171 } catch (e) {
146172 return { ok: false, error: e instanceof Error ? e.message : String(e) };
147173 }
148174 const [owner = "", name = ""] = box.repo.split("/");
149175 const repo = getRepo(app.db, owner, name);
150176 if (repo === undefined || !canWrite(app.db, repo, user))
151 return { ok: false, error: `Changing env needs write access to ${box.repo}, which this account does not have.` };
152 const keys = Object.keys(values).sort().join(", ");
177 return { ok: false, error: `Changing ${change.what} needs write access to ${box.repo}, which this account does not have.` };
153178 const done = await commitToBranch(app, user, repo, {
154179 branch: box.branch,
155 message: `games: ${service} env: ${keys}`,
180 message: change.message,
156181 files: [{ path: box.path, content: text }],
157182 expectTip: compose.sha,
158183 });
src/games/settings.ts added +698
@@ -0,0 +1,698 @@
1 /**
2 * A game server's settings (forge games, G6 of #17284): server.properties and Paper's two config
3 * files, each key typed, defaulted and described, read from and written to the compose file in the
4 * network repo, so what the forge shows is what the box applies at its next start.
5 *
6 * Where it goes, as the itzg image takes it (files/property-definitions.json and its patch sets):
7 * - a server.properties key with an env var (MOTD, VIEW_DISTANCE, …) is that env var, which the
8 * image writes into server.properties at every start; a key with none is a `name=value` line of
9 * CUSTOM_SERVER_PROPERTIES;
10 * - a Paper key is a `$set` in a patch set of the forge's own (an inline compose config,
11 * `<service>_forge_settings`, mounted at /patches/forge-settings.json and named by
12 * PATCH_DEFINITIONS), applied to /data/config/paper-*.yml before the server starts. The image skips
13 * a patch whose file does not exist yet, so a Paper file the network config does not mount is
14 * seeded with the keys set (`<service>_forge_paper_<file>`, at /config/<file>.yml, which the image
15 * copies into /data/config): the change holds from the first start.
16 * A file the network config mounts (paper_global at /config/paper-global.yml) is never rewritten: a
17 * key it sets is shown as set by the network config, and read-only.
18 *
19 * An env var removed leaves its last value in server.properties, so going back to a default writes
20 * the default, never removes the key.
21 */
22
23 import type { App } from "../app.ts";
24 import type { User } from "../core/users.ts";
25 import { commitCompose, readCompose, serviceEnv, setServiceEnv } from "./compose.ts";
26 import type { GameBox } from "./store.ts";
27
28 export type Result<T> = { ok: true; value: T } | { ok: false; error: string };
29
30 type Kind =
31 | { kind: "bool" }
32 | { kind: "int"; min: number; max: number }
33 | { kind: "float"; min: number; max: number }
34 | { kind: "enum"; values: readonly string[] }
35 | { kind: "text"; max: number };
36
37 type File = "server.properties" | "paper-global" | "paper-world-defaults";
38
39 /** One setting a person can change. */
40 export interface Setting {
41 /** Its name here: the property ("view-distance"), or file and path ("paper-global:chunk-system.worker-threads"). */
42 readonly key: string;
43 readonly file: File;
44 /** The property, or the YAML path (dot separated). */
45 readonly path: string;
46 /** The itzg env var that sets it (server.properties); none: a line of CUSTOM_SERVER_PROPERTIES. */
47 readonly env?: string;
48 readonly type: Kind;
49 readonly default: string;
50 readonly group: "World" | "Players" | "Performance" | "Network" | "Paper";
51 readonly about: string;
52 }
53
54 const bool: Kind = { kind: "bool" };
55 const int = (min: number, max: number): Kind => ({ kind: "int", min, max });
56 const prop = (path: string, env: string | undefined, type: Kind, dflt: string, group: Setting["group"], about: string): Setting => ({
57 key: path,
58 file: "server.properties",
59 path,
60 ...(env === undefined ? {} : { env }),
61 type,
62 default: dflt,
63 group,
64 about,
65 });
66 const paper = (file: "paper-global" | "paper-world-defaults", path: string, type: Kind, dflt: string, about: string): Setting => ({
67 key: `${file}:${path}`,
68 file,
69 path,
70 type,
71 default: dflt,
72 group: "Paper",
73 about,
74 });
75
76 /**
77 * The settings, server.properties first (each by the env var itzg maps onto it: files/
78 * property-definitions.json), then Paper's own (each path, type and default as Paper's
79 * GlobalConfiguration and WorldConfiguration declare them). Ports, RCON, the query and management servers and
80 * the level name are left out: the box and the network depend on them.
81 */
82 export const SETTINGS: readonly Setting[] = [
83 prop("motd", "MOTD", { kind: "text", max: 200 }, "A Minecraft Server", "Players", "The line under the server's name in the server list"),
84 prop("max-players", "MAX_PLAYERS", int(1, 1000), "20", "Players", "How many players may be on at once"),
85 prop(
86 "gamemode",
87 "MODE",
88 { kind: "enum", values: ["survival", "creative", "adventure", "spectator"] },
89 "survival",
90 "Players",
91 "The game mode a new player starts in",
92 ),
93 prop("force-gamemode", "FORCE_GAMEMODE", bool, "false", "Players", "Put every player in the default game mode as they join"),
94 prop(
95 "difficulty",
96 "DIFFICULTY",
97 { kind: "enum", values: ["peaceful", "easy", "normal", "hard"] },
98 "easy",
99 "World",
100 "How hard the world is",
101 ),
102 prop("hardcore", "HARDCORE", bool, "false", "World", "One life: a player who dies becomes a spectator"),
103 prop("pvp", "PVP", bool, "true", "Players", "Players can hurt each other"),
104 prop("allow-flight", "ALLOW_FLIGHT", bool, "false", "Players", "Let flying (a mod or a plugin) past the anti-fly kick"),
105 prop("allow-nether", "ALLOW_NETHER", bool, "true", "World", "Players can go to the Nether"),
106 prop("spawn-protection", "SPAWN_PROTECTION", int(0, 1000), "16", "World", "Blocks around spawn only operators can change (0: none)"),
107 prop("enable-command-block", "ENABLE_COMMAND_BLOCK", bool, "false", "World", "Command blocks run"),
108 prop("spawn-monsters", "SPAWN_MONSTERS", bool, "true", "World", "Hostile mobs spawn"),
109 prop("generate-structures", "GENERATE_STRUCTURES", bool, "true", "World", "Villages, temples and the like in new chunks"),
110 prop("level-seed", "SEED", { kind: "text", max: 100 }, "", "World", "The seed of a world not yet made (an existing world keeps its own)"),
111 prop(
112 "level-type",
113 "LEVEL_TYPE",
114 {
115 kind: "enum",
116 values: ["minecraft:normal", "minecraft:flat", "minecraft:large_biomes", "minecraft:amplified", "minecraft:single_biome_surface"],
117 },
118 "minecraft:normal",
119 "World",
120 "The kind of a world not yet made",
121 ),
122 prop("max-world-size", "MAX_WORLD_SIZE", int(1, 29999984), "29999984", "World", "The world border's radius, in blocks"),
123 prop("view-distance", "VIEW_DISTANCE", int(3, 32), "10", "Performance", "How many chunks around a player the server sends"),
124 prop(
125 "simulation-distance",
126 "SIMULATION_DISTANCE",
127 int(3, 32),
128 "10",
129 "Performance",
130 "How many chunks around a player tick (mobs, crops, redstone)",
131 ),
132 prop(
133 "entity-broadcast-range-percentage",
134 "ENTITY_BROADCAST_RANGE_PERCENTAGE",
135 int(10, 1000),
136 "100",
137 "Performance",
138 "How far away entities are sent, as a percentage of the default",
139 ),
140 prop(
141 "max-tick-time",
142 "MAX_TICK_TIME",
143 int(-1, 600000),
144 "60000",
145 "Performance",
146 "Milliseconds one tick may take before the watchdog stops the server (-1: never)",
147 ),
148 prop(
149 "max-chained-neighbor-updates",
150 "MAX_CHAINED_NEIGHBOR_UPDATES",
151 int(-1, 10000000),
152 "1000000",
153 "Performance",
154 "Chained block updates before the rest are skipped",
155 ),
156 prop(
157 "region-file-compression",
158 "REGION_FILE_COMPRESSION",
159 { kind: "enum", values: ["deflate", "lz4", "none"] },
160 "deflate",
161 "Performance",
162 "How chunks are compressed on disk (lz4: faster, larger)",
163 ),
164 prop("sync-chunk-writes", "SYNC_CHUNK_WRITES", bool, "true", "Performance", "Write chunks synchronously (safer, slower)"),
165 prop(
166 "pause-when-empty-seconds",
167 "PAUSE_WHEN_EMPTY_SECONDS",
168 int(-1, 86400),
169 "60",
170 "Performance",
171 "Seconds with nobody on before the server stops ticking (-1: never)",
172 ),
173 prop("player-idle-timeout", "PLAYER_IDLE_TIMEOUT", int(0, 1440), "0", "Players", "Minutes idle before a player is kicked (0: never)"),
174 prop("white-list", "WHITELIST_PROP", bool, "false", "Players", "Only listed players may join"),
175 prop("enforce-whitelist", "ENFORCE_WHITELIST", bool, "false", "Players", "Kick a player taken off the list as the list is reloaded"),
176 prop("hide-online-players", "HIDE_ONLINE_PLAYERS", bool, "false", "Players", "Keep the player list out of the server list"),
177 prop("online-mode", "ONLINE_MODE", bool, "true", "Network", "Check each player's account with Mojang"),
178 prop("enforce-secure-profile", "ENFORCE_SECURE_PROFILE", bool, "true", "Network", "Require signed chat (a Mojang key) to join"),
179 prop(
180 "prevent-proxy-connections",
181 "PREVENT_PROXY_CONNECTIONS",
182 bool,
183 "false",
184 "Network",
185 "Kick a player whose address differs from the one Mojang saw",
186 ),
187 prop(
188 "network-compression-threshold",
189 "NETWORK_COMPRESSION_THRESHOLD",
190 int(-1, 65535),
191 "256",
192 "Network",
193 "Packets from this size up are compressed (-1: none)",
194 ),
195 prop("rate-limit", "RATE_LIMIT", int(0, 100000), "0", "Network", "Packets a second before a player is kicked (0: no limit)"),
196 prop("accepts-transfers", "ACCEPTS_TRANSFERS", bool, "false", "Network", "Take players another server transfers here"),
197 prop("use-native-transport", "USE_NATIVE_TRANSPORT", bool, "true", "Network", "Use Linux's faster networking where it can"),
198 prop("enable-status", "ENABLE_STATUS", bool, "true", "Network", "Show the server as online in the server list"),
199 prop("log-ips", "LOG_IPS", bool, "true", "Network", "Write players' addresses into the log"),
200 prop("resource-pack", "RESOURCE_PACK", { kind: "text", max: 500 }, "", "Players", "A resource pack's URL players are offered"),

Input validation: a resource-pack URL is free text. Accept only empty or an https:// URL, and test the refusal. The same applies to bug-report-link (line 207) and resource-pack-sha1 (40 hex characters).

201 prop("require-resource-pack", "RESOURCE_PACK_ENFORCE", bool, "false", "Players", "Players must take the resource pack"),
202 prop("resource-pack-sha1", "RESOURCE_PACK_SHA1", { kind: "text", max: 40 }, "", "Players", "The resource pack's SHA-1, so players' clients can check it"),
203 prop("resource-pack-prompt", "RESOURCE_PACK_PROMPT", { kind: "text", max: 200 }, "", "Players", "What players are told as the resource pack is offered"),
204 prop("op-permission-level", "OP_PERMISSION_LEVEL", int(0, 4), "4", "Players", "What an operator may do (4: everything)"),
205 prop("broadcast-console-to-ops", "BROADCAST_CONSOLE_TO_OPS", bool, "true", "Players", "Operators see what the console runs"),
206 prop("function-permission-level", "FUNCTION_PERMISSION_LEVEL", int(1, 4), "2", "Players", "What a datapack function may do"),
207 prop("bug-report-link", "BUG_REPORT_LINK", { kind: "text", max: 500 }, "", "Players", "Where the pause menu's bug report link goes"),
208 // No itzg env var: a line of CUSTOM_SERVER_PROPERTIES.
209 prop("enable-code-of-conduct", undefined, bool, "false", "Players", "Show joining players the code of conduct in codeofconduct/"),
210 paper("paper-global", "chunk-system.worker-threads", int(-1, 64), "-1", "Threads that load and generate chunks (-1: Paper decides)"),
211 paper(
212 "paper-global",
213 "chunk-loading-basic.player-max-chunk-load-rate",
214 { kind: "float", min: -1, max: 10000 },
215 "100.0",
216 "Chunks a second one player may load (-1: no limit)",
217 ),
218 paper(
219 "paper-global",
220 "chunk-loading-basic.player-max-chunk-generate-rate",
221 { kind: "float", min: -1, max: 10000 },
222 "-1.0",
223 "Chunks a second one player may make (-1: no limit)",
224 ),
225 paper(
226 "paper-global",
227 "chunk-loading-basic.player-max-chunk-send-rate",
228 { kind: "float", min: -1, max: 10000 },
229 "75.0",
230 "Chunks a second sent to one player (-1: no limit)",
231 ),
232 paper("paper-global", "misc.max-joins-per-tick", int(1, 100), "5", "Players let in each tick"),
233 paper(
234 "paper-global",
235 "packet-limiter.all-packets.max-packet-rate",
236 { kind: "float", min: -1, max: 100000 },
237 "500.0",
238 "Packets a second before a player is kicked",
239 ),
240 paper("paper-global", "spam-limiter.tab-spam-limit", int(1, 10000), "500", "Tab completions before a player is kicked for spam"),
241 paper(
242 "paper-global",
243 "watchdog.early-warning-delay",
244 int(1000, 600000),
245 "10000",
246 "Milliseconds of a stuck tick before Paper says so in the log",
247 ),
248 paper("paper-global", "unsupported-settings.allow-piston-duplication", bool, "false", "Let TNT and carpet duplication with pistons work"),
249 paper("paper-global", "unsupported-settings.allow-headless-pistons", bool, "false", "Let headless pistons be made"),
250 paper("paper-global", "unsupported-settings.perform-username-validation", bool, "true", "Refuse player names Mojang would not allow"),
251 paper("paper-global", "proxies.velocity.enabled", bool, "false", "Take players forwarded by a Velocity proxy"),
252 paper("paper-global", "collisions.enable-player-collisions", bool, "true", "Players push each other"),
253 paper("paper-world-defaults", "entities.spawning.per-player-mob-spawns", bool, "true", "Count the mob cap per player, not per world"),
254 paper("paper-world-defaults", "chunks.max-auto-save-chunks-per-tick", int(1, 10000), "24", "Chunks saved each tick by the autosave"),
255 paper("paper-world-defaults", "chunks.prevent-moving-into-unloaded-chunks", bool, "false", "Stop a player at a chunk not loaded yet"),
256 paper("paper-world-defaults", "collisions.max-entity-collisions", int(0, 1000), "8", "Entities one entity collides with each tick"),
257 paper("paper-world-defaults", "environment.optimize-explosions", bool, "false", "Faster explosions, a little less vanilla"),
258 paper("paper-world-defaults", "environment.treasure-maps.enabled", bool, "true", "Treasure maps find treasure (a costly search)"),
259 paper("paper-world-defaults", "tick-rates.mob-spawner", int(1, 100), "1", "Ticks between mob spawner checks"),
260 paper("paper-world-defaults", "tick-rates.grass-spread", int(1, 100), "1", "Ticks between grass spread checks"),
261 paper("paper-world-defaults", "tick-rates.container-update", int(1, 100), "1", "Ticks between container screen updates"),
262 paper(
263 "paper-world-defaults",
264 "hopper.disable-move-event",
265 bool,
266 "false",
267 "Skip the plugin event for each hopper move (faster; breaks hopper-watching plugins)",
268 ),
269 paper("paper-world-defaults", "hopper.cooldown-when-full", bool, "true", "A full hopper waits before trying again"),
270 paper(
271 "paper-world-defaults",
272 "misc.redstone-implementation",
273 { kind: "enum", values: ["VANILLA", "EIGENCRAFT", "ALTERNATE_CURRENT"] },
274 "VANILLA",
275 "How redstone is computed",
276 ),
277 paper("paper-world-defaults", "anticheat.anti-xray.enabled", bool, "false", "Hide ores from x-ray clients"),
278 paper("paper-world-defaults", "entities.armor-stands.tick", bool, "true", "Armor stands tick (off: faster; breaks armor-stand machines)"),
279 paper(
280 "paper-world-defaults",
281 "entities.armor-stands.do-collision-entity-lookups",
282 bool,
283 "true",
284 "Armor stands look for entities to collide with",
285 ),
286 paper("paper-world-defaults", "entities.behavior.disable-chest-cat-detection", bool, "false", "A cat on a chest does not keep it shut"),
287 paper("paper-world-defaults", "environment.disable-ice-and-snow", bool, "false", "No ice or snow forms in cold weather"),
288 paper("paper-world-defaults", "environment.disable-thunder", bool, "false", "No thunderstorms"),
289 paper("paper-world-defaults", "chunks.delay-chunk-unloads-by", { kind: "text", max: 20 }, "10s", "How long a chunk stays loaded after its last player leaves"),
290 ];
291
292 const PAPERS = new Set(["PAPER", "PURPUR", "FOLIA"]);
293 type PaperFile = Exclude<File, "server.properties">;
294 const PAPER_FILES: readonly PaperFile[] = ["paper-global", "paper-world-defaults"];
295 /** Where the image keeps a Paper file (a patch's target). */
296 const DATA: Readonly<Record<PaperFile, string>> = {
297 "paper-global": "/data/config/paper-global.yml",
298 "paper-world-defaults": "/data/config/paper-world-defaults.yml",
299 };
300 /** Where a mounted Paper file is read from: the network config's, or the forge's seed. */
301 const MOUNT: Readonly<Record<PaperFile, string>> = {
302 "paper-global": "/config/paper-global.yml",
303 "paper-world-defaults": "/config/paper-world-defaults.yml",
304 };
305 const PATCH_TARGET = "/patches/forge-settings.json";
306 const CUSTOM = "CUSTOM_SERVER_PROPERTIES";
307 const configName = (service: string, what: string): string => `${service.replace(/[^A-Za-z0-9_]/g, "_")}_forge_${what}`;
308 const patchName = (service: string): string => configName(service, "settings");
309 const seedName = (service: string, file: PaperFile): string => configName(service, file.replace(/-/g, "_"));
310 /** The names itzg's MODE and DIFFICULTY also take as numbers. */
311 const NUMBERED: Readonly<Record<string, readonly string[]>> = {
312 MODE: ["survival", "creative", "adventure", "spectator"],
313 DIFFICULTY: ["peaceful", "easy", "normal", "hard"],
314 };
315
316 /** A setting as the server has it. */
317 export interface SettingValue {
318 readonly setting: Setting;
319 readonly value: string;
320 /** Where the value comes from: the env, the forge's patch, the network config, or the default. */
321 readonly from: "env" | "patch" | "network" | "default";
322 /** Why a person cannot change it here, when they cannot. */
323 readonly readOnly?: string;
324 }
325
326 interface Doc {
327 services?: Record<string, { environment?: unknown; configs?: unknown }>;
328 configs?: Record<string, { content?: unknown }>;
329 }
330 interface PatchSet {
331 patches: { file: string; ops: { $set: { path: string; value: unknown; "value-type": string } }[] }[];
332 }
333
334 const parse = (text: string): Doc => {
335 try {
336 return (Bun.YAML.parse(text) as Doc | null) ?? {};
337 } catch {
338 return {};
339 }
340 };
341 const dig = (doc: unknown, path: string): unknown =>
342 path.split(".").reduce<unknown>((at, k) => (at !== null && typeof at === "object" ? (at as Record<string, unknown>)[k] : undefined), doc);
343 const jsonPath = (path: string): string =>
344 `$${path
345 .split(".")
346 .map((k) => `['${k}']`)
347 .join("")}`;
348 /** A value read from YAML or JSON as the setting writes it (a float keeps its ".0"). */
349 const shown = (s: Setting, v: unknown): string => (s.type.kind === "float" && typeof v === "number" && Number.isInteger(v) ? `${String(v)}.0` : String(v));
350 /** A value as YAML and the patch's value-type take it. */
351 const typed = (s: Setting, value: string): unknown =>
352 s.type.kind === "bool" ? value === "true" : s.type.kind === "int" || s.type.kind === "float" ? Number(value) : value;
353
354 /** CUSTOM_SERVER_PROPERTIES's `name=value` lines, in order. */
355 const customOf = (raw: string | undefined): [string, string][] =>
356 (raw ?? "")
357 .split("\n")
358 .map((l) => l.trim())
359 .filter((l) => l.includes("="))
360 .map((l) => [l.slice(0, l.indexOf("=")).trim(), l.slice(l.indexOf("=") + 1)]);
361
362 /** The Paper files the network config (anything but the forge's own seeds) mounts for a service, parsed. */
363 function networkFiles(doc: Doc, service: string): Partial<Record<PaperFile, unknown>> {
364 const out: Partial<Record<PaperFile, unknown>> = {};
365 const mounts = doc.services?.[service]?.configs;
366 if (!Array.isArray(mounts)) return out;
367 for (const m of mounts) {
368 const source = typeof m === "string" ? m : typeof m === "object" && m !== null ? String((m as { source?: unknown }).source ?? "") : "";
369 const target =
370 typeof m === "object" && m !== null && typeof (m as { target?: unknown }).target === "string"
371 ? (m as { target: string }).target
372 : `/${source}`;
373 const file = PAPER_FILES.find((f) => MOUNT[f] === target);
374 if (file === undefined || source === seedName(service, file)) continue;
375 const content = doc.configs?.[source]?.content;
376 try {
377 out[file] = typeof content === "string" ? (Bun.YAML.parse(content) ?? {}) : {};
378 } catch {
379 out[file] = {};
380 }
381 }
382 return out;
383 }
384
385 /** The forge's own patch set for a service, if the compose file has one. */
386 function patchOf(doc: Doc, service: string): PatchSet {
387 const content = doc.configs?.[patchName(service)]?.content;
388 try {
389 const set = JSON.parse(typeof content === "string" ? content : "{}") as Partial<PatchSet>;
390 return { patches: Array.isArray(set.patches) ? set.patches : [] };
391 } catch {
392 return { patches: [] };
393 }
394 }
395
396 /** A Paper file's seed: every key the patch sets in it, nested as the YAML file holds them. */
397 function seedOf(set: PatchSet, file: PaperFile): Record<string, unknown> | undefined {
398 const ops = set.patches.find((p) => p.file === DATA[file])?.ops ?? [];
399 if (ops.length === 0) return undefined;
400 const root: Record<string, unknown> = {};
401 for (const { $set } of ops) {
402 const keys = [...$set.path.matchAll(/\['([^']*)'\]/g)].map((m) => m[1]!);
403 let at = root;
404 keys.slice(0, -1).forEach((k) => {
405 if (typeof at[k] !== "object" || at[k] === null) at[k] = {};
406 at = at[k] as Record<string, unknown>;
407 });
408 at[keys[keys.length - 1]!] = $set.value;
409 }
410 return root;
411 }
412
413 const patched = (set: PatchSet, s: Setting): unknown => {
414 if (s.file === "server.properties") return undefined;
415 const file = set.patches.find((p) => p.file === DATA[s.file as PaperFile]);
416 return file?.ops.find((o) => o.$set?.path === jsonPath(s.path))?.$set.value;
417 };
418
419 /** An env value as the setting shows it: true/false and a choice in lower case, a numbered choice by name. */
420 function fromEnv(s: Setting, v: string): string {
421 const numbered = s.env === undefined ? undefined : NUMBERED[s.env];
422 if (numbered !== undefined && /^[0-3]$/.test(v.trim())) return numbered[Number(v.trim())]!;
423 return s.type.kind === "bool" || s.type.kind === "enum" ? v.trim().toLowerCase() : v;
424 }
425
426 /** Every setting a service has, with its value and where it comes from. */
427 export function settingsOf(text: string, service: string, env: Readonly<Record<string, string>>): SettingValue[] {
428 const doc = parse(text);
429 const isPaper = PAPERS.has((env["TYPE"] ?? "").toUpperCase());
430 const network = networkFiles(doc, service);
431 const set = patchOf(doc, service);
432 const custom = new Map(customOf(env[CUSTOM]));
433 const velocity = dig(network["paper-global"], "proxies.velocity.enabled") === true;
434 return SETTINGS.filter((s) => s.file === "server.properties" || isPaper).map((s): SettingValue => {
435 if (s.file === "server.properties") {
436 const v = s.env === undefined ? custom.get(s.path) : env[s.env];
437 const value = v === undefined ? s.default : fromEnv(s, v);
438 const from = v === undefined ? "default" : "env";
439 // Behind Velocity, the proxy checks accounts: this server stays offline-mode.
440 if (s.env === "ONLINE_MODE" && velocity)
441 return { setting: s, value, from, readOnly: "set by the network config: Velocity forwards players here, so this server stays offline-mode" };
442 return { setting: s, value, from };
443 }
444 const fromNetwork = dig(network[s.file as PaperFile], s.path);
445 if (fromNetwork !== undefined)
446 return { setting: s, value: shown(s, fromNetwork), from: "network", readOnly: `set by the network config (${s.file}.yml)` };
447 const fromPatch = patched(set, s);
448 return fromPatch === undefined ? { setting: s, value: s.default, from: "default" } : { setting: s, value: shown(s, fromPatch), from: "patch" };
449 });
450 }
451
452 /** A value as the setting takes it, or why not. */
453 function valueOf(s: Setting, raw: string): Result<string> {
454 const v = raw.trim();
455 const t = s.type;
456 if (t.kind === "bool") {
457 if (/^(true|yes|on)$/i.test(v)) return { ok: true, value: "true" };
458 if (/^(false|no|off)$/i.test(v)) return { ok: true, value: "false" };
459 return { ok: false, error: `${s.key} is true or false.` };
460 }
461 if (t.kind === "int" || t.kind === "float") {
462 const n = Number(v);
463 if (v === "" || !Number.isFinite(n) || (t.kind === "int" && !Number.isInteger(n)) || n < t.min || n > t.max)
464 return {
465 ok: false,
466 error: `${s.key} is ${t.kind === "int" ? "a whole number" : "a number"} from ${String(t.min)} to ${String(t.max)}.`,
467 };
468 return { ok: true, value: t.kind === "float" && Number.isInteger(n) ? `${String(n)}.0` : String(n) };
469 }
470 if (t.kind === "enum") {
471 const hit = t.values.find((x) => x.toLowerCase() === v.toLowerCase());
472 return hit === undefined ? { ok: false, error: `${s.key} is one of ${t.values.join(", ")}.` } : { ok: true, value: hit };
473 }
474 if (v.length > t.max || /[\r\n]/.test(v)) return { ok: false, error: `${s.key} is one line of at most ${String(t.max)} characters.` };
475 return { ok: true, value: v };
476 }
477
478 /** A change, previewed: its lines in words, and the edit that makes the compose file say it. */
479 export interface SettingsPlan {
480 readonly lines: readonly string[];
481 readonly keys: readonly string[];
482 readonly edit: (text: string) => string;
483 }
484
485 const said = (v: string): string => (v === "" ? "(empty)" : v);
486
487 /**
488 * The change `wanted` (setting key → value) makes: each value checked, an unchanged one left out,
489 * a read-only one refused; the env, the patch and the seeds it writes, and lines that say so.
490 */
491 export function planSettings(
492 text: string,
493 service: string,
494 env: Readonly<Record<string, string>>,
495 wanted: Readonly<Record<string, string>>,
496 ): Result<SettingsPlan> {
497 const now = new Map(settingsOf(text, service, env).map((v) => [v.setting.key, v]));
498 const envChanges: Record<string, string> = {};
499 const customChanges: Record<string, string> = {};
500 const patchChanges: { s: Setting; value: string }[] = [];
501 const lines: string[] = [];
502 const keys: string[] = [];
503 for (const [key, raw] of Object.entries(wanted)) {
504 const cur = now.get(key);
505 if (cur === undefined)
506 return {
507 ok: false,
508 error: SETTINGS.some((s) => s.key === key) ? `${key} is a Paper setting, and this server does not run Paper.` : `${key} is not a setting this forge knows.`,
509 };
510 const v = valueOf(cur.setting, raw);
511 if (!v.ok) return v;
512 if (v.value === cur.value) continue;
513 if (cur.readOnly !== undefined) return { ok: false, error: `${key} is ${cur.readOnly}; change it there.` };
514 const s = cur.setting;
515 keys.push(key);
516 if (s.file === "server.properties" && s.env !== undefined) {
517 envChanges[s.env] = v.value;
518 lines.push(`${s.env} ${said(cur.value)} → ${said(v.value)} (env)`);
519 } else if (s.file === "server.properties") {
520 customChanges[s.path] = v.value;
521 lines.push(`${s.path} ${said(cur.value)} → ${said(v.value)} (env ${CUSTOM})`);
522 } else {
523 patchChanges.push({ s, value: v.value });
524 lines.push(`${s.file} ${s.path} ${said(cur.value)} → ${said(v.value)} (patch)`);
525 }
526 }
527 if (lines.length === 0) return { ok: false, error: "Nothing changes: every value is what the server has." };
528 const theirs = env["PATCH_DEFINITIONS"];
529 if (patchChanges.length > 0 && theirs !== undefined && theirs !== PATCH_TARGET)
530 return { ok: false, error: `${service} already takes its patches from ${theirs}; change Paper's settings there.` };
531 lines.push("Restarts the server with the new settings on the box's next sync");
532 const edit = (base: string): string => {
533 const baseEnv = serviceEnv(base, service);
534 const sets: Record<string, string> = { ...envChanges };
535 if (Object.keys(customChanges).length > 0) {
536 const custom = new Map(customOf(baseEnv[CUSTOM]));
537 for (const [k, v] of Object.entries(customChanges)) custom.set(k, v);
538 sets[CUSTOM] = [...custom].map(([k, v]) => `${k}=${v}`).join("\n");
539 }
540 let out = Object.keys(sets).length === 0 ? base : setServiceEnv(base, service, sets);
541 let set: PatchSet | undefined;
542 const seeds: [string, string][] = [];
543 if (patchChanges.length > 0) {
544 set = patchOf(parse(out), service);
545 for (const { s, value } of patchChanges) {
546 const file = DATA[s.file as PaperFile];
547 let entry = set.patches.find((p) => p.file === file);
548 if (entry === undefined) {
549 entry = { file, ops: [] };
550 set.patches.push(entry);
551 }
552 const path = jsonPath(s.path);
553 const op = { $set: { path, value: typed(s, value), "value-type": s.type.kind === "enum" || s.type.kind === "text" ? "string" : s.type.kind } };
554 const at = entry.ops.findIndex((o) => o.$set?.path === path);
555 if (at < 0) entry.ops.push(op);
556 else entry.ops[at] = op;
557 }
558 out = setTopConfig(out, patchName(service), `${JSON.stringify(set, null, 2)}\n`);
559 out = mountConfig(out, service, patchName(service), PATCH_TARGET);
560 // A Paper file the network config does not mount is seeded with the keys set (JSON is YAML),
561 // so the image has a file to patch from the first start.
562 const network = networkFiles(parse(out), service);
563 for (const file of PAPER_FILES) {
564 const seed = seedOf(set, file);
565 if (seed === undefined || network[file] !== undefined) continue;
566 const name = seedName(service, file);
567 seeds.push([name, `${JSON.stringify(seed, null, 2)}\n`]);
568 out = setTopConfig(out, name, seeds[seeds.length - 1]![1]);
569 out = mountConfig(out, service, name, MOUNT[file]);
570 }
571 out = setServiceEnv(out, service, { PATCH_DEFINITIONS: PATCH_TARGET });
572 }
573 // The edit is textual; the file must still say what was meant, or nothing is committed.
574 const doc = parse(out);
575 const outEnv = serviceEnv(out, service);
576 const placed =
577 Object.entries(sets).every(([k, v]) => outEnv[k] === v) &&
578 (set === undefined || (outEnv["PATCH_DEFINITIONS"] === PATCH_TARGET && JSON.stringify(patchOf(doc, service)) === JSON.stringify(set))) &&
579 seeds.every(([name, content]) => doc.configs?.[name]?.content === content);
580 if (!placed) throw new Error("The settings could not be placed in the compose file; nothing was committed.");
581 return out;
582 };
583 // Tried once here, so a compose file the edit cannot place in is refused before any button.
584 try {
585 edit(text);
586 } catch (e) {
587 return { ok: false, error: e instanceof Error ? e.message : String(e) };
588 }
589 return { ok: true, value: { lines, keys, edit } };
590 }
591
592 // ---- the compose file's configs, by text (the rest of the file stays as written) ----
593
594 const indentOf = (l: string): number => l.length - l.trimStart().length;
595
596 /** The compose text with a top-level config `name` holding `content`, added or replaced. */
597 export function setTopConfig(text: string, name: string, content: string): string {
598 const lines = text.replace(/\n*$/, "").split("\n");
599 const block = [
600 ` ${name}:`,
601 " # The forge's settings editor writes this; change it there.",
602 " content: |",
603 ...content
604 .replace(/\n$/, "")
605 .split("\n")
606 .map((l) => ` ${l}`),
607 ];
608 const top = lines.findIndex((l) => /^configs:\s*$/.test(l));
609 if (top < 0) return `${[...lines, "configs:", ...block].join("\n")}\n`;
610 let end = lines.length;
611 for (let i = top + 1; i < lines.length; i++)
612 if (lines[i]!.trim() !== "" && indentOf(lines[i]!) === 0) {
613 end = i;
614 break;
615 }
616 const at = lines.findIndex((l, i) => i > top && i < end && l === ` ${name}:`);
617 if (at < 0) {
618 lines.splice(end, 0, ...block);
619 return `${lines.join("\n")}\n`;
620 }
621 let stop = end;
622 for (let i = at + 1; i < end; i++)
623 if (lines[i]!.trim() !== "" && indentOf(lines[i]!) <= 2) {
624 stop = i;
625 break;
626 }
627 lines.splice(at, stop - at, ...block);
628 return `${lines.join("\n")}\n`;
629 }
630
631 /** The compose text with `source` mounted at `target` in `service`, once. */
632 export function mountConfig(text: string, service: string, source: string, target: string): string {
633 const lines = text.split("\n");
634 const svc = lines.findIndex(
635 (l, i) => new RegExp(`^\\s+${service.replace(/[.]/g, "\\.")}:\\s*$`).test(l) && lines.slice(0, i).some((p) => /^services:\s*$/.test(p)),
636 );
637 if (svc < 0) throw new Error(`${service} is not a service in this compose file`);
638 const svcIndent = indentOf(lines[svc]!);
639 let end = lines.length;
640 for (let i = svc + 1; i < lines.length; i++)
641 if (lines[i]!.trim() !== "" && !lines[i]!.trimStart().startsWith("#") && indentOf(lines[i]!) <= svcIndent) {
642 end = i;
643 break;
644 }
645 const child = lines.slice(svc + 1, end).find((l) => l.trim() !== "" && !l.trimStart().startsWith("#"));
646 const childIndent = child === undefined ? svcIndent + 2 : indentOf(child);
647 const at = lines.findIndex((l, i) => i > svc && i < end && indentOf(l) === childIndent && /^\s*configs:\s*$/.test(l));
648 if (at >= 0) {
649 let stop = end;
650 for (let i = at + 1; i < end; i++)
651 if (lines[i]!.trim() !== "" && indentOf(lines[i]!) <= childIndent) {
652 stop = i;
653 break;
654 }
655 const items = lines.slice(at + 1, stop);
656 if (items.some((l) => new RegExp(`(?:source:\\s*|^\\s*-\\s*)${source}\\s*$`).test(l))) return text;
657 const first = items.find((l) => l.trimStart().startsWith("- "));
658 const dash = first === undefined ? childIndent + 2 : indentOf(first);
659 lines.splice(at + 1, 0, `${" ".repeat(dash)}- source: ${source}`, `${" ".repeat(dash + 2)}target: ${target}`);
660 return lines.join("\n");
661 }
662 lines.splice(
663 svc + 1,
664 0,
665 `${" ".repeat(childIndent)}configs:`,
666 `${" ".repeat(childIndent + 2)}- source: ${source}`,
667 `${" ".repeat(childIndent + 4)}target: ${target}`,
668 );
669 return lines.join("\n");
670 }
671
672 // ---- the doors' one way in ----
673
674 /** A service's settings as its compose file says at the branch's tip, with that commit. */
675 export async function serviceSettings(app: App, box: GameBox, service: string): Promise<Result<{ values: SettingValue[]; sha: string }>> {
676 const compose = await readCompose(app, box);
677 if (compose === undefined) return { ok: false, error: `No ${box.path} on ${box.repo}@${box.branch}.` };
678 return { ok: true, value: { values: settingsOf(compose.text, service, serviceEnv(compose.text, service)), sha: compose.sha } };
679 }
680
681 /** Preview `wanted` on the compose file at the branch's tip: the plan and the commit it is on. */
682 export async function previewSettings(app: App, box: GameBox, service: string, wanted: Readonly<Record<string, string>>): Promise<Result<SettingsPlan & { sha: string }>> {
683 const compose = await readCompose(app, box);
684 if (compose === undefined) return { ok: false, error: `No ${box.path} on ${box.repo}@${box.branch}.` };
685 const plan = planSettings(compose.text, service, serviceEnv(compose.text, service), wanted);
686 return plan.ok ? { ok: true, value: { ...plan.value, sha: compose.sha } } : plan;
687 }
688
689 /** Commit a preview, on the commit it was made on: "games: <service> settings: <keys>". */
690 export async function commitSettings(app: App, user: User, box: GameBox, service: string, plan: SettingsPlan & { sha: string }): Promise<Result<string>> {
691 const done = await commitCompose(app, user, box, {
692 message: `games: ${service} settings: ${plan.keys.join(", ")}`,
693 what: "settings",
694 edit: plan.edit,
695 expectTip: plan.sha,
696 });
697 return done.ok ? { ok: true, value: done.sha } : done;
698 }
src/http/games_routes.ts +2 −1
@@ -8,7 +8,7 @@ import { synced } from "../games/notify.ts";
88 import { boxByToken, envFiles, recordSync, signJarUrls, type SyncBody } from "../games/store.ts";
99 import { BODY_CAPS } from "../kernel/body_caps.ts";
1010 import {
11 gameBoxPage, gameCommandSubmit, gameEnvSubmit, gameGrantSubmit, gameJarDownload, gameJarSubmit, gamePluginSubmit, gamePowerSubmit, gameServicePage, gameServiceStream, gamesPage,
11 gameBoxPage, gameCommandSubmit, gameEnvSubmit, gameGrantSubmit, gameJarDownload, gameJarSubmit, gamePluginSubmit, gamePowerSubmit, gameServicePage, gameSettingsSubmit, gameServiceStream, gamesPage,
1212 } from "../web/pages/games.ts";
1313 import type { Ctx, Handler } from "./context.ts";
1414 import { InvalidJson } from "./json_body.ts";
@@ -60,4 +60,5 @@ export function gamesRoutes(router: Router<Handler>): void {
6060 router.add("POST", "/games/:box/:service/env", gameEnvSubmit);
6161 router.add("POST", "/games/:box/:service/plugin", gamePluginSubmit);
6262 router.add("POST", "/games/:box/:service/jar", gameJarSubmit);
63 router.add("POST", "/games/:box/:service/settings", gameSettingsSubmit);
6364 }
src/http/lazy_lists.ts +1
@@ -607,6 +607,7 @@ export const OPERATIONS_ROUTES = [
607607 ["POST", "/games/:box/:service/env"],
608608 ["POST", "/games/:box/:service/plugin"],
609609 ["POST", "/games/:box/:service/jar"],
610 ["POST", "/games/:box/:service/settings"],
610611 ["GET", "/resilience"],
611612 ["GET", "/maintenance"],
612613 ["GET", "/maintenance.json"],
src/http/mcp/tools/games.ts +33 −5
@@ -1,5 +1,6 @@
11 import { addPlugin, commitServiceEnv } from "../../../games/compose.ts";
22 import { boxStatus, boxStatusShared } from "../../../games/diag.ts";
3 import { commitSettings, previewSettings, serviceSettings } from "../../../games/settings.ts";
34 import { boxNamed, listBoxes, mayDo, queueCommand, roleOn, seesBox, SERVICE_NAME, servicesOf, type CommandKind } from "../../../games/store.ts";
45 import { good, bad, type Tool, str } from "../shared.ts";
56
@@ -8,12 +9,12 @@ const POWER = ["start", "stop", "restart", "recreate", "pull"];
89 export const tool: Tool = {
910 name: "games",
1011 listedTo: "admin",
11 doc: "`{ action, box?, service?, text?, kind?, key?, value?, modrinth? }`: game boxes. `list`; `console` queues `text` as RCON; `power` `kind` (start, stop, restart); `env` commits `key`=`value` (empty removes); `plugin` adds a `modrinth` slug. Grants as on /games",
12 description: "Game boxes: list, console, power, env, plugins.",
12 doc: "`{ action, box?, service?, text?, kind?, key?, value?, modrinth? }`: game boxes. `list`; `console` queues `text` as RCON; `power` `kind` (start, stop, restart); `env` commits `key`=`value` (empty removes); `plugin` adds a `modrinth` slug; `config` lists a service's settings (server.properties, Paper's); `config_set` sets `key` to `value`, planned first (`dryRun: false` commits the plan on the commit it was planned on). Grants as on /games",
13 description: "Game boxes: list, console, power, env, plugins, settings.",
1314 inputSchema: {
1415 type: "object",
1516 properties: {
16 action: { type: "string", enum: ["list", "console", "power", "env", "plugin"] },
17 action: { type: "string", enum: ["list", "console", "power", "env", "plugin", "config", "config_set"] },
1718 box: { type: "string", maxLength: 40 },
1819 service: { type: "string", maxLength: 64 },
1920 text: { type: "string", maxLength: 1000 },
@@ -21,11 +22,12 @@ export const tool: Tool = {
2122 key: { type: "string", maxLength: 100 },
2223 value: { type: "string", maxLength: 2000 },
2324 modrinth: { type: "string", maxLength: 100 },
25 dryRun: { type: "boolean" },
2426 },
2527 required: ["action"],
2628 },
2729 writes: true,
28 heldNotWhen: (args) => args["action"] === "list",
30 heldNotWhen: (args) => args["action"] === "list" || args["action"] === "config" || (args["action"] === "config_set" && args["dryRun"] !== false),
2931 async run(ctx, user, args) {
3032 const action = str(args["action"]);
3133 const db = ctx.app.db;
@@ -48,6 +50,24 @@ export const tool: Tool = {
4850 const box = boxNamed(db, str(args["box"]));
4951 const service = str(args["service"]);
5052 if (box === undefined || !seesBox(db, user, box.id) || !SERVICE_NAME.test(service)) return bad("not_found", "no such box or service here");
53 if (action === "config") {
54 if (!mayDo(roleOn(db, user, box.id, service), "viewer")) return bad("forbidden", `you may not see ${service} on ${box.name}`);
55 const got = await serviceSettings(ctx.app, box, service);
56 if (!got.ok) return bad("refused", got.error);
57 return good({
58 sha: got.value.sha,
59 items: got.value.values.map((v) => ({
60 key: v.setting.key,
61 group: v.setting.group,
62 value: v.value,
63 default: v.setting.default,
64 from: v.from,
65 about: v.setting.about,
66 ...(v.setting.env === undefined ? {} : { env: v.setting.env }),
67 ...(v.readOnly === undefined ? {} : { readOnly: v.readOnly }),
68 })),
69 });
70 }
5171 if (!mayDo(roleOn(db, user, box.id, service), "operator")) return bad("forbidden", `you are not an operator of ${service} on ${box.name}`);
5272 if (action === "console") {
5373 const text = str(args["text"]).trim();
@@ -68,6 +88,14 @@ export const tool: Tool = {
6888 const done = await addPlugin(ctx.app, user, box, service, { modrinth: str(args["modrinth"]) });
6989 return done.ok ? good({ says: `Committed ${done.sha.slice(0, 10)}.`, sha: done.sha }) : bad("refused", done.error);
7090 }
71 return bad("bad_action", "action is list, console, power, env or plugin");
91 if (action === "config_set") {
92 const plan = await previewSettings(ctx.app, box, service, { [str(args["key"])]: str(args["value"]) });
93 if (!plan.ok) return bad("refused", plan.error);
94 if (args["dryRun"] !== false)
95 return good({ lines: plan.value.lines, sha: plan.value.sha, says: "This is the plan; nothing changed. Send dryRun: false to commit it." });
96 const done = await commitSettings(ctx.app, user, box, service, plan.value);
97 return done.ok ? good({ says: `Committed ${done.value.slice(0, 10)}; the server restarts on the box's next sync.`, lines: plan.value.lines, sha: done.value }) : bad("refused", done.error);
98 }
99 return bad("bad_action", "action is list, console, power, env, plugin, config or config_set");
72100 },
73101 };
src/tui/screens/games.ts +129 −2
@@ -5,7 +5,9 @@
55 * opens a service as /games/<box>/<service> does: its console (the log tail, and `:` queues an
66 * rcon command), its env (`e` sets or clears a key, committed through `commitServiceEnv`) and its
77 * plugins (`a` adds a Modrinth slug or a URL through `addPlugin`; uploading a jar is the page's
8 * alone). `G` opens the box's grants, which an owner sets with `a` there, through `grant`.
8 * alone); `c` opens its settings (server.properties and Paper's, as the page's Settings block:
9 * `enter` sets one, the preview shows on top, `y` commits it through `commitSettings`). `G` opens
10 * the box's grants, which an owner sets with `a` there, through `grant`.
911 */
1012
1113 import { movedKey } from "./moved_key.ts";
@@ -13,6 +15,7 @@ import { emptyText } from "../../core/empty_words.ts";
1315 import { boxStatus, boxStatusShared } from "../../games/diag.ts";
1416 import { getUserByName } from "../../core/users.ts";
1517 import { addPlugin, commitServiceEnv, pluginsOf, readCompose, serviceEnv } from "../../games/compose.ts";
18 import { commitSettings, planSettings, settingsOf, type SettingsPlan, type SettingValue } from "../../games/settings.ts";
1619 import {
1720 SERVICE_NAME,
1821 bootTroubled,
@@ -172,7 +175,13 @@ export function gameServiceScreen(f: Session, ctx: Ctx, box: GameBox, service: s
172175 };
173176 const screen: Screen = {
174177 title: `${box.name}/${service}`,
175 keys: [binding(["tab"], "console, env, plugins"), binding([":"], "rcon"), binding(["e"], "set env"), binding(["a"], "add plugin")],
178 keys: [
179 binding(["tab"], "console, env, plugins"),
180 binding([":"], "rcon"),
181 binding(["e"], "set env"),
182 binding(["a"], "add plugin"),
183 binding(["c"], "settings"),
184 ],
176185 render(area, s) {
177186 const c = ctx.theme.c;
178187 const [head, body] = split(area, "v", [len(1), fill(1)]);
@@ -208,6 +217,7 @@ export function gameServiceScreen(f: Session, ctx: Ctx, box: GameBox, service: s
208217 await load();
209218 return `Committed ${done.sha.slice(0, 10)}; the box redeploys on its next sync.`;
210219 });
220 else if (e.key === "c") ctx.push(gameSettingsScreen(f, ctx, box, service));
211221 else if (e.key === "a")
212222 ask("Plugin", "A Modrinth slug, or an https URL to a jar", async (raw) => {
213223 const v = raw.trim();
@@ -224,6 +234,123 @@ export function gameServiceScreen(f: Session, ctx: Ctx, box: GameBox, service: s
224234 return screen;
225235 }
226236
237 /**
238 * A service's settings, as the page's Settings block: each with its value and where it comes from;
239 * `enter` sets one (an operator's), the change so far is previewed on top, and `y` commits it, on the
240 * commit it was previewed on, through `commitSettings`; `x` drops it.
241 */
242 export function gameSettingsScreen(f: Session, ctx: Ctx, box: GameBox, service: string): Screen {
243 const state = new ListState();
244 let note = "";
245 let compose: { text: string; sha: string } | undefined;
246 let loaded = false;
247 let values: SettingValue[] = [];
248 let wanted: Record<string, string> = {};
249 let plan: (SettingsPlan & { sha: string }) | undefined;
250 const operator = () => mayDo(roleOn(f.app.db, f.user, box.id, service), "operator");
251 const load = async (): Promise<void> => {
252 compose = await readCompose(f.app, box);
253 values = compose === undefined ? [] : settingsOf(compose.text, service, serviceEnv(compose.text, service));
254 loaded = true;
255 ctx.invalidate();
256 };
257 void load();
258 const replan = (): string | undefined => {
259 if (compose === undefined) return `No ${box.path} on ${box.repo}@${box.branch}.`;
260 const got = planSettings(compose.text, service, serviceEnv(compose.text, service), wanted);
261 if (!got.ok) return got.error;
262 plan = { ...got.value, sha: compose.sha };
263 return undefined;
264 };
265 const screen: Screen = {
266 title: `${box.name}/${service} settings`,
267 keys: [binding(["j", "k"], "move cursor"), binding(["enter"], "set"), binding(["y"], "commit"), binding(["x"], "drop the change")],
268 render(area, s) {
269 const c = ctx.theme.c;
270 const shown = plan?.lines ?? [];
271 const [head, preview, list] = split(area, "v", [len(1), len(shown.length), fill(1)]);
272 const said =
273 note !== ""
274 ? note
275 : !loaded
276 ? "Reading the compose file…"
277 : compose === undefined
278 ? `No ${box.path} on ${box.repo}@${box.branch}.`
279 : plan !== undefined
280 ? "y commits this change; x drops it."
281 : "server.properties and Paper's settings, as the compose file says.";
282 s.text(head!.x, head!.y, truncate(said, head!.w), style(c.mutedFg, c.bg), head!.x + head!.w);
283 shown.forEach((l, i) => s.text(preview!.x, preview!.y + i, truncate(l, preview!.w), style(c.fg, c.bg), preview!.x + preview!.w));
284 drawList(
285 s,
286 list!,
287 c,
288 state,
289 values.map((v) => ({
290 title: v.setting.file === "server.properties" ? v.setting.key : `${v.setting.file} ${v.setting.path}`,
291 secondary: `${wanted[v.setting.key] ?? v.value}${v.readOnly !== undefined ? ` · ${v.readOnly}` : v.value !== v.setting.default ? ` · changed from ${v.setting.default === "" ? "empty" : v.setting.default}` : ""}`,
292 meta: v.setting.group,
293 })),
294 );
295 },
296 key(e) {
297 if (state.key(e, values.length)) return true;
298 if (e.ctrl || e.alt) return false;
299 const say = (words: string): true => {
300 note = words;
301 ctx.invalidate();
302 return true;
303 };
304 if (e.key === "x") {
305 wanted = {};
306 plan = undefined;
307 return say("Dropped; nothing changed.");
308 }
309 if (e.key === "y") {
310 if (plan === undefined) return say("Set something first (enter).");
311 const going = plan;
312 void commitSettings(f.app, f.user!, box, service, going).then(async (done) => {
313 if (!done.ok) return void say(done.error);
314 wanted = {};
315 plan = undefined;
316 await load();
317 say(`Committed ${done.value.slice(0, 10)}; the server restarts with the new settings on the box's next sync.`);
318 });
319 return say("Committing…");
320 }
321 if (e.key !== "enter") return false;
322 const at = values[state.index];
323 if (at === undefined) return true;
324 if (!operator()) return say(`You are not an operator of ${service}.`);
325 if (at.readOnly !== undefined) return say(`${at.setting.key} is ${at.readOnly}.`);
326 const t = at.setting.type;
327 ctx.push(
328 promptScreen(ctx, screen, {
329 title: at.setting.key,
330 label: at.setting.about,
331 value: wanted[at.setting.key] ?? at.value,
332 hint: t.kind === "bool" ? "true or false" : t.kind === "enum" ? t.values.join(", ") : t.kind === "text" ? `at most ${String(t.max)} characters` : `${String(t.min)} to ${String(t.max)}`,
333 onSubmit: (value) => {
334 const before = wanted;
335 wanted = { ...wanted, [at.setting.key]: value };
336 const refused = replan();
337 if (refused === undefined) {
338 note = "";
339 ctx.invalidate();
340 return undefined;
341 }
342 wanted = before;
343 if (Object.keys(wanted).length === 0) plan = undefined;
344 return refused;
345 },
346 }),
347 );
348 return true;
349 },
350 };
351 return screen;
352 }
353
227354 /** A box's grants, as /games/<box> lists them; an owner sets one with `a` ("user role [service]"). */
228355 export function gameGrantsScreen(f: Session, ctx: Ctx, box: GameBox): Screen {
229356 const state = new ListState();
src/web/pages/games.ts +103
@@ -8,6 +8,7 @@
88
99 import { addPlugin, commitServiceEnv, composeServices, pluginsOf, readCompose, SECRET_KEY, serviceEnv } from "../../games/compose.ts";
1010 import { boxStatus, boxStatusShared } from "../../games/diag.ts";
11 import { commitSettings, planSettings, previewSettings, settingsOf, SETTINGS, type SettingValue, type SettingsPlan } from "../../games/settings.ts";
1112 import {
1213 bootWords,
1314 boxNamed,
@@ -235,6 +236,10 @@ export async function gameServicePage(ctx: Ctx): Promise<Response> {
235236 const plugins = compose === undefined ? { plugins: [], modrinth: [] } : pluginsOf(compose.text, service);
236237 const commands = recentCommands(ctx.app.db, box.id, service, 5);
237238 const base = `/games/${box.name}/${service}`;
239 // Settings: each as the compose file says; a "Preview" (s.<key>=value in the query) planned on it.
240 const settings = compose === undefined ? [] : settingsOf(compose.text, service, env);
241 const wanted = settingsWanted(ctx.url.searchParams);
242 const preview = compose !== undefined && act && Object.keys(wanted).length > 0 ? planSettings(compose.text, service, env, wanted) : undefined;
238243 return timePhase(ctx.request, "render", () => page({
239244 ctx,
240245 title: `${service} · ${box.name}`,
@@ -298,6 +303,7 @@ ${tail.lines.join("\n")}${tail.lines.length > 0 ? "\n" : ""}</pre
298303 </form>`
299304 : null}
300305 </section>
306 ${settingsBlock({ base, act, settings, preview, sha: compose?.sha ?? "", wanted })}
301307 <section class="settings-block">
302308 <h2>Plugins</h2>
303309 ${plugins.plugins.length + plugins.modrinth.length === 0
@@ -379,6 +385,103 @@ export async function gamePowerSubmit(ctx: Ctx): Promise<Response> {
379385 return flashTo(ctx, `/games/${got.box.name}`, { message: `${kind} ${got.service}: asked; the box does it on its next sync.` });
380386 }
381387
388 /** The settings a form or a query asks for: its `s.<key>` fields. */
389 function settingsWanted(fields: Iterable<[string, unknown]>): Record<string, string> {
390 const out: Record<string, string> = {};
391 for (const [k, v] of fields) if (k.startsWith("s.") && typeof v === "string" && SETTINGS.some((x) => x.key === k.slice(2))) out[k.slice(2)] = v;
392 return out;
393 }
394
395 const GROUPS = ["Players", "World", "Performance", "Network", "Paper"] as const;
396
397 /** One setting's control: a select for true/false and a choice, a number or a line otherwise. */
398 function settingControl(v: SettingValue, act: boolean, shown: string): Html {
399 const s = v.setting;
400 const name = `s.${s.key}`;
401 const off = !act || v.readOnly !== undefined;
402 const label = `${s.key}: ${s.about}`;
403 if (s.type.kind === "bool" || s.type.kind === "enum") {
404 const options = s.type.kind === "bool" ? ["true", "false"] : s.type.kind === "enum" ? s.type.values : [];
405 return html`<select class="input" name="${name}" aria-label="${label}" ${off ? html`disabled` : null}>
406 ${options.map((o) => html`<option value="${o}" ${o === shown ? html`selected` : null}>${o}</option>`)}
407 </select>`;
408 }
409 return s.type.kind === "int" || s.type.kind === "float"
410 ? html`<input class="input mono" type="number" name="${name}" value="${shown}" min="${String(s.type.min)}" max="${String(s.type.max)}" step="${s.type.kind === "int" ? "1" : "any"}" aria-label="${label}" ${off ? html`disabled` : null} />`
411 : html`<input class="input" name="${name}" value="${shown}" maxlength="${String(s.type.max)}" aria-label="${label}" ${off ? html`disabled` : null} />`;
412 }
413
414 /**
415 * A server's settings, grouped, each with its value, where it comes from and why it may not be
416 * changed here; Preview says what a change does (env or patch, the restart) before one button
417 * commits it.
418 */
419 function settingsBlock(o: {
420 base: string;
421 act: boolean;
422 settings: readonly SettingValue[];
423 preview: { ok: true; value: SettingsPlan } | { ok: false; error: string } | undefined;
424 sha: string;
425 wanted: Readonly<Record<string, string>>;
426 }): Html | null {
427 if (o.settings.length === 0) return null;
428 const from: Record<SettingValue["from"], string> = { env: "set in the compose env", patch: "set by the forge's Paper patch", network: "set by the network config", default: "the default" };
429 const groups = GROUPS.filter((g) => o.settings.some((v) => v.setting.group === g));
430 return html`<section class="settings-block" id="settings">
431 <h2>Settings</h2>
432 ${o.preview === undefined
433 ? null
434 : o.preview.ok
435 ? html`<div class="card" aria-label="What this change does">

Principles 6 and 7: a card is a box around a thing. Render the preview lines as rows (or a dl) with the buttons under them, no card.

436 <div class="card-body stack">
437 ${o.preview.value.lines.map((l) => html`<p>${l}</p>`)}
438 <form method="post" action="${o.base}/settings" class="row-fields">
439 ${o.preview.value.keys.map((k) => html`<input type="hidden" name="s.${k}" value="${o.wanted[k] ?? ""}" />`)}
440 <input type="hidden" name="sha" value="${o.sha}" />
441 ${btn("Commit and restart", { variant: "primary" })} ${btn("Cancel", { variant: "ghost", href: `${o.base}#settings` })}
442 </form>
443 </div>
444 </div>`
445 : html`<p class="notice danger" role="alert">${o.preview.error}</p>`}
446 <form method="get" action="${o.base}#settings" class="stack">
447 ${groups.map((g, i) =>
448 disclosure(
449 g,
450 rowList(
451 o.settings
452 .filter((v) => v.setting.group === g)
453 .map((v) =>
454 row({
455 title: html`<span class="mono">${v.setting.file === "server.properties" ? v.setting.key : `${v.setting.file} ${v.setting.path}`}</span>`,
456 meta: html`${v.setting.about} · ${v.readOnly ?? from[v.from]}${v.value !== v.setting.default ? ` · changed from the default, ${v.setting.default === "" ? "empty" : v.setting.default}` : ""}`,

Principle 1: about + source + 'changed from the default' on every row, and the same about text again in the aria-label, says the same things repeatedly across ~75 rows. Say the source and default only when they differ from the default or the row is read-only.

457 after: settingControl(v, o.act, o.wanted[v.setting.key] ?? v.value),
458 }),
459 ),
460 ),
461 { open: i === 0 },
462 ),
463 )}
464 ${o.act ? btn("Preview", { variant: "secondary" }) : null}
465 </form>
466 </section>`;
467 }
468
469 // POST /games/:box/:service/settings: a previewed change, on the commit it was previewed on.
470 export async function gameSettingsSubmit(ctx: Ctx): Promise<Response> {
471 const got = await operatorForm(ctx);
472 if (got instanceof Response) return got;
473 const back = `/games/${got.box.name}/${got.service}#settings`;
474 const plan = await previewSettings(ctx.app, got.box, got.service, settingsWanted(got.form.entries()));
475 if (!plan.ok) return flashTo(ctx, back, { tone: "danger", message: plan.error });
476 if (field(got.form, "sha") !== plan.value.sha) return flashTo(ctx, back, { tone: "danger", message: "The network changed since that preview; look at it again." });
477 const done = await commitSettings(ctx.app, ctx.auth.user!, got.box, got.service, plan.value);
478 return flashTo(
479 ctx,
480 back,
481 done.ok ? { message: `Committed ${done.value.slice(0, 10)}; the server restarts with the new settings on the box's next sync.` } : { tone: "danger", message: done.error },
482 );
483 }
484
382485 // POST /games/:box/:service/env: one key, committed to the compose file.
383486 export async function gameEnvSubmit(ctx: Ctx): Promise<Response> {
384487 const got = await operatorForm(ctx);
test/conversation-ask.test.ts +1
@@ -521,6 +521,7 @@ const SAID: readonly (readonly [string, Record<string, unknown>, string])[] = [
521521 ["games", { action: "console", box: "net", service: "hub", text: "say hi" }, 'Run "say hi" in the console of hub on net.'],
522522 ["games", { action: "env", box: "net", service: "hub", key: "MOTD", value: "Hello" }, "Set MOTD on hub on net to Hello, a commit that redeploys it."],
523523 ["games", { action: "plugin", box: "net", service: "survival", modrinth: "waystones" }, "Add the plugin waystones to survival on net, a commit that redeploys it."],
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."],
524525 ["crew_accounts", { repo: "marin/cakes", allow: "espo-corp" }, "Let the crew's runs for marin/cakes spend the account espo-corp."],
525526 ["subscriptions", { everywhere: "espo-corp" }, "Put the account espo-corp in the pool, so the crew uses it by default on every repository a forge admin owns."],
526527 ["subscriptions", { limit: "espo-corp" }, "Keep the account espo-corp to where it is allowed."],
test/game-settings.test.ts added +346
@@ -0,0 +1,346 @@
1 /**
2 * A game server's settings (G6 of #17284): server.properties by itzg's env vars, Paper's files by a
3 * patch set of the forge's own in the compose file (never the file the network config mounts),
4 * each value checked against its type, a key the network config sets shown read-only.
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 { createToken } from "../src/core/tokens.ts";
13 import { createUser, getUserByName, type User } from "../src/core/users.ts";
14 import { readCompose, serviceEnv } from "../src/games/compose.ts";
15 import { commitSettings, mountConfig, planSettings, previewSettings, setTopConfig, settingsOf } from "../src/games/settings.ts";
16 import { boxNamed, createGameBox } from "../src/games/store.ts";
17 import { forgeHttp, type ForgeHttp } from "../src/http/server.ts";
18 import { quietLogs } from "./helpers/globals.ts";
19
20 quietLogs();
21
22 const COMPOSE = `services:
23 hub:
24 image: itzg/minecraft-server
25 environment:
26 TYPE: PAPER
27 VIEW_DISTANCE: "10"
28 ONLINE_MODE: "false"
29 configs:
30 - source: paper_global
31 target: /config/paper-global.yml
32 survival:
33 image: itzg/minecraft-server
34 environment:
35 TYPE: FABRIC
36
37 configs:
38 paper_global:
39 content: |
40 proxies:
41 velocity:
42 enabled: true
43 online-mode: true
44 unsupported-settings:
45 perform-username-validation: false
46 `;
47
48 const doc = (text: string) =>
49 Bun.YAML.parse(text) as {
50 services: Record<string, { environment: Record<string, string>; configs: unknown[] }>;
51 configs: Record<string, { content: string }>;
52 };
53
54 describe("what a server has", () => {
55 test("env values, defaults, and what the network config sets, read-only", () => {
56 const got = new Map(settingsOf(COMPOSE, "hub", serviceEnv(COMPOSE, "hub")).map((v) => [v.setting.key, v]));
57 expect(got.get("view-distance")).toMatchObject({ value: "10", from: "env" });
58 expect(got.get("max-players")).toMatchObject({ value: "20", from: "default" });
59 expect(got.get("online-mode")?.readOnly).toContain("Velocity forwards players here");
60 expect(got.get("paper-global:unsupported-settings.perform-username-validation")).toMatchObject({
61 value: "false",
62 from: "network",
63 readOnly: "set by the network config (paper-global.yml)",
64 });
65 expect(got.get("paper-world-defaults:entities.spawning.per-player-mob-spawns")).toMatchObject({ value: "true", from: "default" });
66 // A server that does not run Paper has no Paper settings.
67 expect(settingsOf(COMPOSE, "survival", serviceEnv(COMPOSE, "survival")).some((v) => v.setting.file !== "server.properties")).toBe(
68 false,
69 );
70 });
71 });
72
73 describe("a change", () => {
74 test("server.properties goes to its env var, Paper to the forge's patch, the network's file untouched", () => {
75 const plan = planSettings(COMPOSE, "hub", serviceEnv(COMPOSE, "hub"), {
76 "view-distance": "12",
77 "paper-world-defaults:entities.spawning.per-player-mob-spawns": "false",
78 "paper-global:misc.max-joins-per-tick": "10",
79 "max-players": "20",
80 });
81 if (!plan.ok) throw new Error(plan.error);
82 expect(plan.value.lines).toEqual([
83 "VIEW_DISTANCE 10 → 12 (env)",
84 "paper-world-defaults entities.spawning.per-player-mob-spawns true → false (patch)",
85 "paper-global misc.max-joins-per-tick 5 → 10 (patch)",
86 "Restarts the server with the new settings on the box's next sync",
87 ]);
88 const text = plan.value.edit(COMPOSE);
89 const d = doc(text);
90 expect(d.services["hub"]!.environment).toMatchObject({ VIEW_DISTANCE: "12", PATCH_DEFINITIONS: "/patches/forge-settings.json" });
91 expect(d.services["hub"]!.configs).toEqual([
92 { source: "hub_forge_paper_world_defaults", target: "/config/paper-world-defaults.yml" },
93 { source: "hub_forge_settings", target: "/patches/forge-settings.json" },
94 { source: "paper_global", target: "/config/paper-global.yml" },
95 ]);
96 // paper-world-defaults.yml is not mounted by the network, so it is seeded with the keys set
97 // (the image skips a patch whose file is missing); paper-global.yml is the network's.
98 expect(Bun.YAML.parse(d.configs["hub_forge_paper_world_defaults"]!.content)).toEqual({ entities: { spawning: { "per-player-mob-spawns": false } } });
99 expect(d.configs["hub_forge_paper_global"]).toBeUndefined();
100 expect(d.configs["paper_global"]!.content).toBe(doc(COMPOSE).configs["paper_global"]!.content);
101 expect(JSON.parse(d.configs["hub_forge_settings"]!.content)).toEqual({
102 patches: [
103 {
104 file: "/data/config/paper-world-defaults.yml",
105 ops: [{ $set: { path: "$['entities']['spawning']['per-player-mob-spawns']", value: false, "value-type": "bool" } }],
106 },
107 {
108 file: "/data/config/paper-global.yml",
109 ops: [{ $set: { path: "$['misc']['max-joins-per-tick']", value: 10, "value-type": "int" } }],
110 },
111 ],
112 });
113 // Read back, then changed again: the op is replaced, the mount stays one.
114 const after = new Map(settingsOf(text, "hub", serviceEnv(text, "hub")).map((v) => [v.setting.key, v]));
115 expect(after.get("paper-global:misc.max-joins-per-tick")).toMatchObject({ value: "10", from: "patch" });
116 const again = planSettings(text, "hub", serviceEnv(text, "hub"), { "paper-global:misc.max-joins-per-tick": "7" });
117 if (!again.ok) throw new Error(again.error);
118 const twice = doc(again.value.edit(text));
119 expect(twice.services["hub"]!.configs).toHaveLength(3);
120 expect(JSON.parse(twice.configs["hub_forge_settings"]!.content).patches[1].ops).toEqual([
121 { $set: { path: "$['misc']['max-joins-per-tick']", value: 7, "value-type": "int" } },
122 ]);
123 });
124
125 test("a bad value, a read-only key, an unknown one, Paper on Fabric and no change at all are each refused", () => {
126 const env = serviceEnv(COMPOSE, "hub");
127 expect(planSettings(COMPOSE, "hub", env, { "view-distance": "64" })).toEqual({
128 ok: false,
129 error: "view-distance is a whole number from 3 to 32.",
130 });
131 expect(planSettings(COMPOSE, "hub", env, { difficulty: "brutal" })).toEqual({
132 ok: false,
133 error: "difficulty is one of peaceful, easy, normal, hard.",
134 });
135 expect(planSettings(COMPOSE, "hub", env, { "online-mode": "true" })).toEqual({
136 ok: false,
137 error:
138 "online-mode is set by the network config: Velocity forwards players here, so this server stays offline-mode; change it there.",
139 });
140 expect(planSettings(COMPOSE, "hub", env, { "paper-global:unsupported-settings.perform-username-validation": "true" })).toEqual({
141 ok: false,
142 error:
143 "paper-global:unsupported-settings.perform-username-validation is set by the network config (paper-global.yml); change it there.",
144 });
145 expect(planSettings(COMPOSE, "hub", env, { "rcon.password": "x" })).toEqual({
146 ok: false,
147 error: "rcon.password is not a setting this forge knows.",
148 });
149 expect(planSettings(COMPOSE, "survival", serviceEnv(COMPOSE, "survival"), { "paper-global:misc.max-joins-per-tick": "9" })).toEqual({
150 ok: false,
151 error: "paper-global:misc.max-joins-per-tick is a Paper setting, and this server does not run Paper.",
152 });
153 expect(planSettings(COMPOSE, "hub", env, { "view-distance": "10", difficulty: "EASY" })).toEqual({
154 ok: false,
155 error: "Nothing changes: every value is what the server has.",
156 });
157 });
158
159 test("a config block and a mount are placed by text, the rest of the file as written", () => {
160 const bare = "services:\n hub:\n image: x\n environment:\n TYPE: PAPER\n";
161 const placed = mountConfig(
162 setTopConfig(bare, "hub_forge_settings", '{"patches":[]}\n'),
163 "hub",
164 "hub_forge_settings",
165 "/patches/forge-settings.json",
166 );
167 expect(placed).toStartWith(
168 "services:\n hub:\n configs:\n - source: hub_forge_settings\n target: /patches/forge-settings.json\n image: x\n",
169 );
170 expect(doc(placed).configs["hub_forge_settings"]!.content).toBe('{"patches":[]}\n');
171 });
172 });
173
174 describe("server.properties without an env var, and the image's other ways", () => {
175 const LOBBY = `services:
176 lobby:
177 image: itzg/minecraft-server
178 environment:
179 TYPE: PURPUR
180 DIFFICULTY: "2"
181 WHITELIST_PROP: "TRUE"
182 CUSTOM_SERVER_PROPERTIES: |
183 text-filtering-version=0
184 MOTD: hi
185 `;
186
187 test("a key with no env var is a line of CUSTOM_SERVER_PROPERTIES, the others kept; a block value is replaced whole", () => {
188 const env = serviceEnv(LOBBY, "lobby");
189 const now = new Map(settingsOf(LOBBY, "lobby", env).map((v) => [v.setting.key, v]));
190 // itzg's numbered difficulty reads as its name; true in any case reads as true.
191 expect(now.get("difficulty")).toMatchObject({ value: "normal", from: "env" });
192 expect(now.get("white-list")).toMatchObject({ value: "true", from: "env" });
193 expect(now.get("enable-code-of-conduct")).toMatchObject({ value: "false", from: "default" });
194 const plan = planSettings(LOBBY, "lobby", env, { "enable-code-of-conduct": "true", difficulty: "normal", "white-list": "false" });
195 if (!plan.ok) throw new Error(plan.error);
196 expect(plan.value.lines).toEqual([
197 "enable-code-of-conduct false → true (env CUSTOM_SERVER_PROPERTIES)",
198 "WHITELIST_PROP true → false (env)",
199 "Restarts the server with the new settings on the box's next sync",
200 ]);
201 expect(plan.value.keys).toEqual(["enable-code-of-conduct", "white-list"]);
202 const text = plan.value.edit(LOBBY);
203 expect(serviceEnv(text, "lobby")).toEqual({
204 TYPE: "PURPUR",
205 DIFFICULTY: "2",
206 WHITELIST_PROP: "false",
207 CUSTOM_SERVER_PROPERTIES: "text-filtering-version=0\nenable-code-of-conduct=true",
208 MOTD: "hi",
209 });
210 expect(new Map(settingsOf(text, "lobby", serviceEnv(text, "lobby")).map((v) => [v.setting.key, v])).get("enable-code-of-conduct")).toMatchObject({
211 value: "true",
212 from: "env",
213 });
214 });
215
216 test("back to the default writes the default (a removed env var leaves its value in server.properties)", () => {
217 const plan = planSettings(LOBBY, "lobby", serviceEnv(LOBBY, "lobby"), { difficulty: "easy" });
218 if (!plan.ok) throw new Error(plan.error);
219 expect(serviceEnv(plan.value.edit(LOBBY), "lobby")["DIFFICULTY"]).toBe("easy");
220 });
221
222 test("a Paper server seeds both files when the network mounts neither; patches the network set elsewhere are not overwritten", () => {
223 const plan = planSettings(LOBBY, "lobby", serviceEnv(LOBBY, "lobby"), { "paper-global:misc.max-joins-per-tick": "3" });
224 if (!plan.ok) throw new Error(plan.error);
225 const d = doc(plan.value.edit(LOBBY));
226 expect(d.services["lobby"]!.configs).toContainEqual({ source: "lobby_forge_paper_global", target: "/config/paper-global.yml" });
227 expect(Bun.YAML.parse(d.configs["lobby_forge_paper_global"]!.content)).toEqual({ misc: { "max-joins-per-tick": 3 } });
228 expect(d.configs["lobby_forge_paper_world_defaults"]).toBeUndefined();
229 const theirs = LOBBY.replace(" MOTD: hi\n", " MOTD: hi\n PATCH_DEFINITIONS: /patches/mine.json\n");
230 expect(planSettings(theirs, "lobby", serviceEnv(theirs, "lobby"), { "paper-global:misc.max-joins-per-tick": "3" })).toEqual({
231 ok: false,
232 error: "lobby already takes its patches from /patches/mine.json; change Paper's settings there.",
233 });
234 });
235 });
236
237 describe("on the service page, one commit on the commit previewed", () => {
238 const ORIGIN = "http://forge.test";
239 let dir = "";
240 let app: App;
241 let http: ForgeHttp;
242 let alice: User;
243 let tok = "";
244 const as = (path: string, form?: Record<string, string>) =>
245 http.handle(
246 new Request(
247 ORIGIN + path,
248 form === undefined
249 ? { headers: { authorization: `Bearer ${tok}` } }
250 : {
251 method: "POST",
252 headers: { authorization: `Bearer ${tok}`, origin: ORIGIN, "content-type": "application/x-www-form-urlencoded" },
253 body: new URLSearchParams(form),
254 },
255 ),
256 );
257
258 beforeAll(async () => {
259 dir = await mkdtemp(join(tmpdir(), "forge-game-settings-"));
260 app = createApp({ dataDir: dir, port: 0 });
261 http = forgeHttp(app);
262 const made = await createUser(app.db, {
263 origin: "seed",
264 trusted: true,
265 username: "alice",
266 email: "[email protected]",
267 password: "a-good-passphrase",
268 adminIfFirst: true,
269 });
270 if (!made.ok) throw new Error(made.error);
271 alice = getUserByName(app.db, "alice")!;
272 tok = createToken(app.db, alice.id, "rw", "rw").token;
273 const repo = await createRepo(app, alice, { name: "mc-network", visibility: "private" });
274 if (!repo.ok) throw new Error(String(repo.error));
275 const seeded = await commitToBranch(app, alice, repo.value, { message: "network", files: [{ path: "docker-compose.yml", content: COMPOSE }] });
276 if (!seeded.ok) throw new Error(JSON.stringify(seeded.error));
277 createGameBox(app.db, { name: "net", repo: "alice/mc-network" });
278 }, 30_000);
279
280 afterAll(async () => {
281 app.close();
282 await rm(dir, { recursive: true, force: true });
283 });
284
285 test("the page lists the settings, previews a change, refuses a bad one, and commits the preview", async () => {
286 const page = await (await as("/games/net/hub")).text();
287 expect(page).toContain("<h2>Settings</h2>");
288 expect(page).toContain("set by the network config (paper-global.yml)");
289 const bad = await (await as("/games/net/hub?s.view-distance=99")).text();
290 expect(bad).toContain("view-distance is a whole number from 3 to 32.");
291 const shown = await (await as("/games/net/hub?s.view-distance=12")).text();
292 expect(shown).toContain("VIEW_DISTANCE 10 → 12 (env)");
293 const box = boxNamed(app.db, "net")!;
294 const before = (await readCompose(app, box))!;
295 expect(shown).toContain(`name="sha" value="${before.sha}"`);
296 const done = await as("/games/net/hub/settings", { "s.view-distance": "12", sha: before.sha });
297 expect(done.status).toBe(303);
298 const after = (await readCompose(app, box))!;
299 expect(serviceEnv(after.text, "hub")["VIEW_DISTANCE"]).toBe("12");
300 const log = Bun.spawnSync(["git", "log", "-1", "--format=%s", "main"], { cwd: join(app.reposRoot, "alice", "mc-network.git") });
301 expect(log.stdout.toString().trim()).toBe("games: hub settings: view-distance");
302 // The same form again, on the commit it was previewed on (now behind): nothing is committed.
303 await as("/games/net/hub/settings", { "s.view-distance": "14", sha: before.sha });
304 expect((await readCompose(app, box))!.sha).toBe(after.sha);
305 });
306
307 test("MCP: `config` lists, `config_set` plans until dryRun: false, then commits", async () => {
308 const call = async (args: Record<string, unknown>) => {
309 const res = await http.handle(
310 new Request(`${ORIGIN}/mcp`, {
311 method: "POST",
312 headers: { "content-type": "application/json", accept: "application/json, text/event-stream", authorization: `Bearer ${tok}` },
313 body: JSON.stringify({ jsonrpc: "2.0", id: 1, method: "tools/call", params: { name: "games", arguments: { box: "net", service: "hub", ...args } } }),
314 }),
315 );
316 const text = ((await res.json()) as { result: { content: { text: string }[] } }).result.content[0]!.text;
317 return text.startsWith("{") ? (JSON.parse(text) as Record<string, unknown>) : { refused: text };
318 };
319 const listed = (await call({ action: "config" }))["items"] as { key: string; value: string; from: string; readOnly?: string }[];
320 expect(listed.find((i) => i.key === "simulation-distance")).toMatchObject({ value: "10", from: "default" });
321 expect(listed.find((i) => i.key === "online-mode")?.readOnly).toContain("Velocity");
322 const box = boxNamed(app.db, "net")!;
323 const before = (await readCompose(app, box))!.sha;
324 const plan = await call({ action: "config_set", key: "simulation-distance", value: "8" });
325 expect(plan).toMatchObject({ lines: ["SIMULATION_DISTANCE 10 → 8 (env)", "Restarts the server with the new settings on the box's next sync"] });
326 expect((await readCompose(app, box))!.sha).toBe(before);
327 expect(await call({ action: "config_set", key: "simulation-distance", value: "99", dryRun: false })).toEqual({
328 refused: expect.stringContaining("simulation-distance is a whole number from 3 to 32."),
329 });
330 const done = await call({ action: "config_set", key: "simulation-distance", value: "8", dryRun: false });
331 expect(String(done["says"])).toStartWith("Committed ");
332 expect(serviceEnv((await readCompose(app, box))!.text, "hub")["SIMULATION_DISTANCE"]).toBe("8");
333 });
334
335 test("a preview made before the branch moved is refused", async () => {
336 const box = boxNamed(app.db, "net")!;
337 const plan = await previewSettings(app, box, "hub", { "max-players": "50" });
338 if (!plan.ok) throw new Error(plan.error);
339 expect(await commitSettings(app, alice, box, "hub", { ...plan.value, sha: "0".repeat(40) })).toEqual({
340 ok: false,
341 error: "alice/mc-network@main moved on since this was previewed; look again and redo it.",
342 });
343 const done = await commitSettings(app, alice, box, "hub", plan.value);
344 expect(done.ok).toBe(true);
345 });
346 });
test/mixed-actions-held.test.ts +1 −1
@@ -49,7 +49,7 @@ const MIXED: Readonly<
4949 restore_drill: { key: "action", reads: [{ action: "status" }] },
5050 egress_grants: { key: "op", reads: [{ repo: "o/r", op: "list" }] },
5151 infra: { key: "action", reads: [{ action: "list" }, { action: "show", id: "x" }, { action: "plan" }, { action: "keep" }] },
52 games: { key: "action", reads: [{ action: "list" }] },
52 games: { key: "action", reads: [{ action: "list" }, { action: "config" }, { action: "config_set" }] },
5353 pinned_forge: { key: "verb", reads: [{ verb: "list" }] },
5454 proposal_tokens: { key: "verb", reads: [{ verb: "list" }] },
5555 app_flags: { key: "action", reads: [{ repo: "o/r", action: "list" }] },
test/tui-games.test.ts +26 −2
@@ -2,8 +2,9 @@
22 * Games in the terminal, both doors (review of #16913): from the Games screen, `enter` opens a
33 * service's console (its log tail, and `:` queues an rcon command), env (`e` commits a key through
44 * 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), and `G` opens the
6 * box's grants, which only an owner sets.
5 * through `addPlugin`; a jar upload is the page's alone, and the screen says so), `c` its settings
6 * (a value previewed, then committed with `y`), and `G` opens the box's grants, which only an owner
7 * sets.
78 */
89 import { afterAll, beforeAll, expect, test } from "bun:test";
910 import { mkdtemp, rm } from "node:fs/promises";
@@ -165,3 +166,26 @@ test("on the games list, the old g, before its date, says G opens the grants and
165166 tui.stop?.();
166167 }
167168 });
169
170 test("settings: `c` from a service lists them; a value is previewed, a bad one refused, and `y` commits it", async () => {
171 const { tui, session, terminal, type } = drive(alice);
172 const box = boxNamed(app.db, "net")!;
173 tui.ctx.push(gameServiceScreen(session, tui.ctx, box, "hub"));
174 await settleApp(tui);
175 await type("c");
176 await settleUntil(tui, "max-players");
177 // The second row, max-players (20): "0" makes it 200, "0" again 2000, past its 1000.
178 await type("j");
179 terminal.feed("\r");
180 await settleApp(tui);
181 await type("00");
182 terminal.feed("\r");
183 await settleUntil(tui, "max-players is a whole number from 1 to 1000.");
184 await type("\x7f");
185 terminal.feed("\r");
186 await settleUntil(tui, "MAX_PLAYERS 20 → 200 (env)");
187 await type("y");
188 await settleUntil(tui, "Committed ");
189 expect(serviceEnv((await readCompose(app, box))!.text, "hub")["MAX_PLAYERS"]).toBe("200");
190 tui.stop?.();
191 });

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

Keyboard shortcuts

Docs