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

forge-waker is no game server: no row, no place in the picture, no Move target #17557

opened this

Merged 24h 4m ago, live in production

sold/game-waker-row → main 0 commits 2 threads · 2 unresolved

  • Merged. sold/game-waker-row was merged into main as a570e06.

Review

Sign in to review this change.
11 files changed +200 −47
src/games/people.ts +9 −5
@@ -11,8 +11,11 @@
1111 */
1212
1313 import type { Database } from "bun:sqlite";
14 import type { App } from "../app.ts";
15 import { readCompose } from "./compose.ts";
1416 import { PLAYER } from "./metrics.ts";
1517 import type { User } from "../core/users.ts";
18 import { isGameServer } from "./sleep.ts";
1619 import { mayDo, queueCommand, roleOn, SERVICE_NAME, servicesOf, type GameBox } from "./store.ts";
1720
1821 export interface Player {
@@ -191,25 +194,26 @@ export const UNDO: Partial<Record<PeopleOp, PeopleOp>> = {
191194
192195 /**
193196 * Queue a change to a player on `service` (for a move, the server they are on now; `to` where they
194 * go, a server of this box that `by` may operate too): the command's id, or why not. The caller has
197 * go, a game server of this box that `by` may operate too): the command's id, or why not. The caller has
195198 * checked `by` operates `service`.
196199 */
197 export function queuePeople(
198 db: Database,
200 export async function queuePeople(
201 app: App,
199202 box: GameBox,
200203 service: string,
201204 op: string,
202205 player: string,
203206 by: User | undefined,
204207 to = "",
205 ): { ok: true; id: string } | { ok: false; error: string } {
208 ): Promise<{ ok: true; id: string } | { ok: false; error: string }> {
209 const { db } = app;
206210 if (!(PEOPLE_OPS as readonly string[]).includes(op)) return { ok: false, error: `Choose one of: ${PEOPLE_OPS.join(", ")}.` };
207211 const whole = op === "whitelist-on" || op === "whitelist-off";
208212 if (!whole && !PLAYER.test(player)) return { ok: false, error: "That is not a player's name." };
209213 if (op === "move") {
210214 if (to === "" || to === service) return { ok: false, error: "Name the server to move them to." };
211215 const theirs = servicesOf(db, box.id).some((s) => s.name === to);
212 if (!theirs || !mayDo(roleOn(db, by, box.id, to), "operator"))
216 if (!theirs || !mayDo(roleOn(db, by, box.id, to), "operator") || !isGameServer((await readCompose(app, box))?.text ?? "", to))
213217 return { ok: false, error: `Move people only to a server of ${box.name} you operate; ${to} is not one.` };
214218 }
215219 return {
src/games/presets.ts +7 −5
@@ -14,8 +14,8 @@ import type { User } from "../core/users.ts";
1414 import { commitCompose, composeServices, readCompose, serviceEnv, setTopEntry } from "./compose.ts";
1515 import { lockPath, lockText, planInstall, type Mods } from "./mods.ts";
1616 import { targetOf, type Locked, type Result } from "./modrinth.ts";
17 import { policyOf, proxyOf, setPolicy, WAKER } from "./sleep.ts";
18 import { SERVICE_NAME, servicesOf, type GameBox } from "./store.ts";
17 import { isGameServer, policyOf, proxyOf, setPolicy } from "./sleep.ts";
18 import { isWaker, SERVICE_NAME, servicesOf, WAKER, type GameBox } from "./store.ts";
1919
2020 export const LEVELS = ["void", "flat", "normal"] as const;
2121 export type Level = (typeof LEVELS)[number];
@@ -93,7 +93,7 @@ export function memoryMath(
9393 boxMiB: number,
9494 ): { fits: boolean; line: string } {
9595 // Sleep's waker is a socket proxy with no heap, not a server.
96 const parts = composeServices(text).filter((s) => s !== WAKER).map((s) => ({
96 const parts = composeServices(text).filter((s) => !isWaker(s)).map((s) => ({
9797 name: s,
9898 mib: heapMiB(serviceEnv(text, s)["MEMORY"]),
9999 sleeps: policyOf(text, s) === "sleep",
@@ -201,6 +201,8 @@ export async function planServer(app: App, box: GameBox, wish: Wish): Promise<Re
201201 const services = composeServices(compose.text);
202202 if (!SERVICE_NAME.test(wish.name) || !/^[a-z0-9][a-z0-9-]{0,30}$/.test(wish.name))
203203 return { ok: false, error: "A server's name is lowercase letters, digits and dashes." };
204 // Sleep writes its own service under that name the first time a server sleeps.
205 if (isWaker(wish.name)) return { ok: false, error: `${WAKER} is the name of the forge's own helper; choose another.` };
204206 if (services.includes(wish.name)) return { ok: false, error: `The network already has a server called ${wish.name}.` };
205207 if (proxyOf(compose.text) === undefined)
206208 return { ok: false, error: "This compose file has no proxy (itzg/mc-proxy) for a new server to sit behind." };
@@ -295,8 +297,8 @@ export async function planRemoveServer(app: App, box: GameBox, name: string): Pr
295297 const compose = await readCompose(app, box);
296298 if (compose === undefined) return { ok: false, error: `No ${box.path} on ${box.repo}@${box.branch}.` };
297299 if (!composeServices(compose.text).includes(name)) return { ok: false, error: `The network has no server called ${name}.` };
298 if (proxyOf(compose.text) === name) return { ok: false, error: "The proxy is the way in; it stays." };
299 if (name === WAKER) return { ok: false, error: `${WAKER} wakes the sleeping servers; it stays.` };
300 if (isWaker(name)) return { ok: false, error: `${WAKER} wakes the sleeping servers; it stays.` };
301 if (!isGameServer(compose.text, name)) return { ok: false, error: "The proxy is the way in; it stays." };
300302 let text: string;
301303 try {
302304 // Warm first, so sleep's lists drop it; then the service and its proxy lines.
src/games/sleep.ts +9 −4
@@ -31,7 +31,7 @@ import {
3131 setServiceListItem,
3232 setTopEntry,
3333 } from "./compose.ts";
34 import type { GameBox } from "./store.ts";
34 import { isWaker, WAKER, type GameBox } from "./store.ts";
3535
3636 export const SLEEP_LABEL = "forge.sleep";
3737 /**
@@ -41,8 +41,8 @@ export const SLEEP_LABEL = "forge.sleep";
4141 export const STILL_BILLED = "Sleep frees the server's memory; the machine it runs on is still billed in full.";
4242 /** Ten minutes empty before a sleeping server stops. */
4343 export const EMPTY_SECONDS = 600;
44 /** The socket proxy the forge adds while any server sleeps. */
45 export const WAKER = "forge-waker";
44 /** The socket proxy the forge adds while any server sleeps; its name is `store.ts`'s, where roles are. */
45 export { WAKER };
4646 /** The compose config that holds AutoStopper's settings. */
4747 export const WAKER_CONFIG = "forge_sleep";
4848 /**
@@ -96,12 +96,17 @@ const imageOf = (doc: Doc, service: string): string => {
9696 /** Whether a service is a game server that can sleep: itzg's minecraft-server image. */
9797 export const canSleep = (text: string, service: string): boolean => /(^|\/)itzg\/minecraft-server(:|$)/.test(imageOf(parse(text), service));
9898
99 const isProxy = (doc: Doc, service: string): boolean => /(^|\/)itzg\/mc-proxy(:|$)/.test(imageOf(doc, service));
100
99101 /** The proxy players come in through: the service running itzg's mc-proxy. */
100102 export function proxyOf(text: string): string | undefined {
101103 const doc = parse(text);
102 return Object.keys(doc.services ?? {}).find((s) => /(^|\/)itzg\/mc-proxy(:|$)/.test(imageOf(doc, s)));
104 return Object.keys(doc.services ?? {}).find((s) => isProxy(doc, s));
103105 }
104106
107 /** Whether a service is a game server, on any image: one a player can be on, so neither the waker nor the proxy. */
108 export const isGameServer = (text: string, service: string): boolean => !isWaker(service) && !isProxy(parse(text), service);
109
105110 /** The policy the compose file says: sleep when it is labelled and not restarted by Docker. */
106111 export function policyOf(text: string, service: string): Policy {
107112 const restart = parse(text).services?.[service]?.restart;
src/games/store.ts +9 −2
@@ -202,9 +202,16 @@ export function logsOf(db: Database, boxId: string, service: string, limit = 200
202202
203203 // ---- grants -----------------------------------------------------------------------------------
204204
205 /** What `user` may do on a box, or on one service of it: forge admins own every box. */
205 /** Sleep's socket proxy (`sleep.ts`): the forge's own helper beside the servers, never one of them. */
206 export const WAKER = "forge-waker";
207 export const isWaker = (service: string): boolean => service === WAKER;
208
209 /**
210 * What `user` may do on a box, or on one service of it: forge admins own every box, and nobody has a
211 * role on the waker, so no page, tool action or screen shows or changes it (the box's diag names it).
212 */
206213 export function roleOn(db: Database, user: User | undefined, boxId: string, service = ""): Role | undefined {
207 if (user === undefined) return undefined;
214 if (user === undefined || isWaker(service)) return undefined;
208215 if (user.isAdmin) return "owner";
209216 const rows = db
210217 .query<
src/http/mcp/tools/games.ts +1 −1
@@ -214,7 +214,7 @@ export const tool: Tool = {
214214 const { online, lists } = peopleOf(db, box.id, service);
215215 return good({ service, online, ...lists, network: networkOf(db, box.id), latest: eventsOf(db, box.id, service, 50) });
216216 }
217 const queued = queuePeople(db, box, service, op, str(args["player"]), user, str(args["to"]));
217 const queued = await queuePeople(ctx.app, box, service, op, str(args["player"]), user, str(args["to"]));
218218 return queued.ok ? good({ says: `Queued: ${peopleWords(JSON.stringify({ op, player: str(args["player"]), server: str(args["to"]) }))}; the box does it on its next sync.`, id: queued.id }) : bad("refused", queued.error);
219219 }
220220 if (action === "config_set") {
src/tui/screens/games.ts +1 −1
@@ -353,7 +353,7 @@ export function gameServiceScreen(f: Session, ctx: Ctx, box: GameBox, service: s
353353 else if (e.key === "p")
354354 ask("Player", "op | deop | whitelist-add | whitelist-remove | ban | pardon | kick <player>, or move <player> <server>", async (raw) => {
355355 const [op = "", player = "", to = ""] = raw.trim().split(/\s+/);
356 const queued = queuePeople(f.app.db, box, service, op, player, f.user, to);
356 const queued = await queuePeople(f.app, box, service, op, player, f.user, to);
357357 part = "people";
358358 return queued.ok ? `Asked: ${peopleWords(JSON.stringify({ op, player, server: to }))}; the box does it on its next sync.` : queued.error;
359359 });
src/web/pages/games.ts +3 −4
@@ -55,7 +55,7 @@ import { flashTo, page } from "../layout.ts";
5555 import { avatar, badge, btn, disclosure, field as input, row, rowList, time } from "../ui.ts";
5656 import { onSync } from "../../games/notify.ts";
5757 import { commitServer, planRemoveServer, planServer, wishOn } from "../../games/presets.ts";
58 import { canSleep, commitPolicy, EMPTY_SECONDS, policyOf, proxyOf, STILL_BILLED, stateWords, WAKER } from "../../games/sleep.ts";
58 import { canSleep, commitPolicy, EMPTY_SECONDS, isGameServer, policyOf, STILL_BILLED, stateWords } from "../../games/sleep.ts";
5959 import { CLOUD_EVENT, cloudFacts, GAME_CLOUD_EVENT, pinnedOfBox } from "../../actions/cloud_says.ts";
6060 import { topologyBlock, TOPOLOGY_CSS } from "./games_topology.ts";
6161 import { defaultHeadResponse, headResponse } from "../../games/heads.ts";
@@ -204,8 +204,7 @@ export async function gameBoxPage(ctx: Ctx): Promise<Response> {
204204 // A server asked to be taken out (?remove=…): its plan, the same way.
205205 const leaving = operator ? (ctx.url.searchParams.get("remove") ?? "").slice(0, 64) : "";
206206 const removal = leaving === "" ? undefined : await planRemoveServer(ctx.app, box, leaving);
207 const stays = compose === undefined ? undefined : proxyOf(compose.text);
208 const removable = (n: string): boolean => operator && compose !== undefined && composeServices(compose.text).includes(n) && n !== stays && n !== WAKER;
207 const removable = (n: string): boolean => operator && compose !== undefined && composeServices(compose.text).includes(n) && isGameServer(compose.text, n);
209208 return timePhase(ctx.request, "render", () => page({
210209 ctx,
211210 title: `Games · ${box.name}`,
@@ -1104,7 +1103,7 @@ export async function gamePeopleSubmit(ctx: Ctx): Promise<Response> {
11041103 if (got instanceof Response) return got;
11051104 const op = field(got.form, "op");
11061105 const player = field(got.form, "player").trim();
1107 const queued = queuePeople(ctx.app.db, got.box, got.service, op, player, ctx.auth.user, field(got.form, "to"));
1106 const queued = await queuePeople(ctx.app, got.box, got.service, op, player, ctx.auth.user, field(got.form, "to"));
11081107 const undo = UNDO[op as PeopleOp];
11091108 return flashTo(
11101109 ctx,
src/web/pages/games_topology.ts +4 −14
@@ -9,6 +9,7 @@
99 import type { Ctx } from "../../http/context.ts";
1010 import { metricsSeries } from "../../games/metrics.ts";
1111 import { isBedrock, networkOf, peopleOf } from "../../games/people.ts";
12 import { isGameServer, proxyOf } from "../../games/sleep.ts";
outdated

This file keeps its own proxyOf (a second YAML parse) while sleep.ts now has isProxy/proxyOf. Import sleep.ts's and delete the local one: one way to find the proxy.

1213 import { mayDo, roleOn, servicesOf, type GameBox, type GameService } from "../../games/store.ts";
1314 import { html, type Html } from "../html.ts";
1415 import { btn } from "../ui.ts";
@@ -56,24 +57,13 @@ export function netState(s: GameService | undefined): NetState {
5657 }
5758 const STATE_WORDS: Record<NetState, string> = { awake: "awake", waking: "waking up", asleep: "asleep, wakes on join", stopped: "stopped" };
5859
59 /** The proxy players come in through: the compose service running itzg's mc-proxy. */
60 export function proxyOf(compose: string | undefined): string | undefined {
61 if (compose === undefined) return undefined;
62 try {
63 const doc = Bun.YAML.parse(compose) as { services?: Record<string, { image?: unknown }> } | null;
64 return Object.entries(doc?.services ?? {}).find(([, s]) => typeof s.image === "string" && /(^|\/)itzg\/mc-proxy(:|$)/.test(s.image))?.[0];
65 } catch {
66 return undefined;
67 }
68 }
69
7060 /** The network block, or nothing when the box has no proxy in its compose file. */
7161 export function topologyBlock(ctx: Ctx, box: GameBox, compose: string | undefined, visible: readonly string[]): Html {
72 const proxy = proxyOf(compose);
73 if (proxy === undefined) return html``;
62 const proxy = proxyOf(compose ?? "");
63 if (compose === undefined || proxy === undefined) return html``;
7464 const user = ctx.auth.user!;
7565 const seen = servicesOf(ctx.app.db, box.id);
76 const servers = visible.filter((n) => n !== proxy);
66 const servers = visible.filter((n) => isGameServer(compose, n));
7767 const network = networkOf(ctx.app.db, box.id);
7868 // Each player's UUID from the server they are on (its `list uuids`), for their head.
7969 const uuidOf = new Map<string, string>();
test/game-people.test.ts +7 −7
@@ -198,12 +198,12 @@ describe("on a forge", () => {
198198 const banned = recentCommands(app.db, boxNamed(app.db, "mc")!.id, "hub", 1)[0]!;
199199 expect([banned.kind, JSON.parse(banned.text)]).toEqual(["people", { op: "ban", player: "Griefer2" }]);
200200 const box = boxNamed(app.db, "mc")!;
201 expect(queuePeople(app.db, box, "hub", "op", "not a name", ada)).toEqual({ ok: false, error: "That is not a player's name." });
202 expect(queuePeople(app.db, box, "hub", "move", "Alice", ada, "hub")).toEqual({
201 expect(await queuePeople(app, box, "hub", "op", "not a name", ada)).toEqual({ ok: false, error: "That is not a player's name." });
202 expect(await queuePeople(app, box, "hub", "move", "Alice", ada, "hub")).toEqual({
203203 ok: false,
204204 error: "Name the server to move them to.",
205205 });
206 expect(queuePeople(app.db, box, "hub", "whitelist-on", "", ada).ok).toBe(true);
206 expect((await queuePeople(app, box, "hub", "whitelist-on", "", ada)).ok).toBe(true);
207207 expect(peopleWords(JSON.stringify({ op: "move", player: ".Steve", server: "survival" }))).toBe("move .Steve to survival");
208208 const said = async (args: Record<string, unknown>) => {
209209 const res = await http.handle(
@@ -229,7 +229,7 @@ describe("on a forge", () => {
229229 expect(JSON.parse(commandOf(app.db, moved["id"])!.text)).toEqual({ op: "move", player: ".Steve", server: "survival" });
230230 // A move only to a server of this box: a name the box has no service for is refused.
231231 expect(await said({ action: "people", box: "mc", service: "hub", op: "move", player: ".Steve", to: "elsewhere" })).toContain("you operate; elsewhere is not one");
232 expect(queuePeople(app.db, box, "hub", "move", ".Steve", ada, "elsewhere")).toEqual({ ok: false, error: "Move people only to a server of mc you operate; elsewhere is not one." });
232 expect(await queuePeople(app, box, "hub", "move", ".Steve", ada, "elsewhere")).toEqual({ ok: false, error: "Move people only to a server of mc you operate; elsewhere is not one." });
233233 });
234234
235235 test("a move goes only to a server the person operates too, from the page, the tool and the terminal alike", async () => {
@@ -238,9 +238,9 @@ describe("on a forge", () => {
238238 const bo = made.value;
239239 const box = boxNamed(app.db, "mc")!;
240240 grant(app.db, box.id, bo.id, "operator", "hub");
241 const refused = queuePeople(app.db, box, "hub", "move", "Alice", bo, "survival");
241 const refused = await queuePeople(app, box, "hub", "move", "Alice", bo, "survival");
242242 expect(refused).toEqual({ ok: false, error: "Move people only to a server of mc you operate; survival is not one." });
243 expect(queuePeople(app.db, box, "hub", "move", "Alice", undefined, "survival").ok).toBe(false);
243 expect((await queuePeople(app, box, "hub", "move", "Alice", undefined, "survival")).ok).toBe(false);
244244 // The page refuses it the same way (one function behind the page, the tool and the terminal).
245245 const before = recentCommands(app.db, box.id, "hub", 50).length;
246246 const res = await http.handle(
@@ -253,7 +253,7 @@ describe("on a forge", () => {
253253 expect(res.status).toBe(303);
254254 expect(recentCommands(app.db, box.id, "hub", 50).length).toBe(before);
255255 grant(app.db, box.id, bo.id, "operator", "survival");
256 expect(queuePeople(app.db, box, "hub", "move", "Alice", bo, "survival").ok).toBe(true);
256 expect((await queuePeople(app, box, "hub", "move", "Alice", bo, "survival")).ok).toBe(true);
257257 });
258258
259259 test("a head is served only for a player the forge has seen on a server the person sees", async () => {
test/game-presets.test.ts +12 −1
@@ -18,7 +18,7 @@ import { createToken } from "../src/core/tokens.ts";
1818 import { createUser, type User } from "../src/core/users.ts";
1919 import { readCompose, readRepoFile, serviceEnv, serviceLabels } from "../src/games/compose.ts";
2020 import { lockPath } from "../src/games/mods.ts";
21 import { commitServer, heapMiB, memoryMath, parseWish, planRemoveServer, planServer, proxyLines } from "../src/games/presets.ts";
21 import { commitServer, heapMiB, memoryMath, parseWish, planRemoveServer, planServer, wishOn, proxyLines } from "../src/games/presets.ts";
2222 import { policyOf, WAKER } from "../src/games/sleep.ts";
2323 import { boxNamed, createGameBox, recordSync } from "../src/games/store.ts";
2424 import { forgeHttp, type ForgeHttp } from "../src/http/server.ts";
@@ -222,6 +222,14 @@ describe("on a forge", () => {
222222 await rm(dataDir, { recursive: true, force: true });
223223 });
224224
225 test("no server takes forge-waker's name, though no server sleeps yet and the name is free in the compose file", async () => {
226 const box = boxNamed(app.db, "mc")!;
227 expect(await planServer(app, box, await wishOn(app, box, "a flat world called forge-waker"))).toEqual({
228 ok: false,
229 error: `${WAKER} is the name of the forge's own helper; choose another.`,
230 });
231 });
232
225233 test("a void world with FAWE and bedwars: planned, then one commit with its lock, its proxy lines and sleep on", async () => {
226234 const box = boxNamed(app.db, "mc")!;
227235 const planned = await planServer(app, box, parseWish("give me a new void world with FAWE and bedwars"));
@@ -254,6 +262,9 @@ describe("on a forge", () => {
254262 const lock = await readRepoFile(app, box, now.sha, lockPath(box, "bedwars"));
255263 expect(lock).toContain("fastasyncworldedit");
256264 expect(lock).toContain("screamingbedwars");
265 // The waker is there now: it stays, and its name is taken.
266 expect(await planRemoveServer(app, box, WAKER)).toEqual({ ok: false, error: `${WAKER} wakes the sleeping servers; it stays.` });
267 expect((await wishOn(app, box, "a flat world called forge-waker")).name).toBe(`${WAKER}-2`);
257268 });
258269
259270 test("a plugin that does not run there, a name taken, or too little memory is refused before anything is written", async () => {
test/game-topology.test.ts +138 −3
@@ -11,11 +11,18 @@ import { join } from "node:path";
1111 import { createApp, type App } from "../src/app.ts";
1212 import { commitToBranch, createRepo } from "../src/actions/repos.ts";
1313 import { createSession } from "../src/core/sessions.ts";
14 import { createToken } from "../src/core/tokens.ts";
1415 import { createUser, type User } from "../src/core/users.ts";
15 import { createGameBox, grant, boxNamed } from "../src/games/store.ts";
16 import { queuePeople } from "../src/games/people.ts";
17 import { proxyOf, WAKER } from "../src/games/sleep.ts";
18 import { createGameBox, grant, boxNamed, recentCommands } from "../src/games/store.ts";
1619 import { forgeHttp, type ForgeHttp } from "../src/http/server.ts";
17 import { netState, proxyOf } from "../src/web/pages/games_topology.ts";
20 import { netState } from "../src/web/pages/games_topology.ts";
21 import { createForgeApp } from "../src/tui/forge.ts";
22 import { gamesScreen } from "../src/tui/screens/games.ts";
23 import { headlessTerminal } from "../src/tui/term/terminal.ts";
1824 import { quietLogs } from "./helpers/globals.ts";
25 import { settleApp } from "./helpers/tui.ts";
1926
2027 quietLogs();
2128
@@ -29,6 +36,10 @@ const COMPOSE = `services:
2936 image: itzg/minecraft-server:latest
3037 hunting:
3138 image: itzg/minecraft-server:latest
39 minigames:
40 image: ghcr.io/acme/paper:1
41 forge-waker:
42 image: wollomatic/socket-proxy:1.14.0
3243 `;
3344 const svc = (state: string, health = "") => ({ name: "x", state, health, startedAt: "", cpuPct: 0, memMiB: 0, seenAt: "", asleep: false });
3445
@@ -44,7 +55,7 @@ describe("the pieces", () => {
4455 test("the proxy is the mc-proxy service; no proxy, no picture", () => {
4556 expect(proxyOf(COMPOSE)).toBe("velocity");
4657 expect(proxyOf("services:\n hub:\n image: itzg/minecraft-server\n")).toBeUndefined();
47 expect(proxyOf(undefined)).toBeUndefined();
58 expect(proxyOf("services: [")).toBeUndefined();
4859 });
4960 });
5061
@@ -78,7 +89,10 @@ describe("on /games/<box>", () => {
7889 { name: "hub", state: "running", health: "healthy" },
7990 { name: "survival", state: "running", health: "starting" },
8091 { name: "hunting", state: "exited", health: "" },
92 { name: "minigames", state: "running", health: "" },
93 { name: WAKER, state: "running", health: "" },
8194 ],
95 diag: { ps: [{ name: "game-forge-waker-1", state: "running", status: "Up 2 hours", image: "wollomatic/socket-proxy:1.14.0" }] },
8296 metrics: { hub: { list: `There are 2 of a max of 20 players online: Alice (${ALICE}), .Steve (00000000-0000-0000-0009-01f64f65c7c3)`, tps: "TPS from last 1m, 5m, 15m: 19.8, 20, 20", mspt: "" } },
8397 people: { servers: {}, network: "[hub] (2): Alice, .Steve\n2 players are currently connected to the proxy." },
8498 });
@@ -113,4 +127,125 @@ describe("on /games/<box>", () => {
113127 expect(viewer).toContain("data-topology");
114128 expect(viewer).not.toContain('<details class="net-head">');
115129 });
130
131 test("forge-waker is no server in the picture; a server on another image is", async () => {
132 const text = await page(ada);
133 const net = text.slice(text.indexOf("data-topology"));
134 expect(net).not.toContain(`href="/games/mc/${WAKER}"`);
135 expect(net).toContain('href="/games/mc/minigames"');
136 });
137
138 test("forge-waker is no Move target; a server on another image is", async () => {
139 const net = await page(ada);
140 expect(net).not.toMatch(new RegExp(`name="to"\\s+value="${WAKER}"`));
141 expect(net).toMatch(/name="to"\s+value="minigames"/);
142 });
143
144 test.each([WAKER, "velocity"])("a move to %s is refused", async (to) => {
145 const box = boxNamed(app.db, "mc")!;
146 expect(await queuePeople(app, box, "hub", "move", "Alice", ada, to)).toEqual({ ok: false, error: `Move people only to a server of mc you operate; ${to} is not one.` });
147 });
148
149 test("a move to a server on another image is queued", async () => {
150 expect((await queuePeople(app, boxNamed(app.db, "mc")!, "hub", "move", "Alice", ada, "minigames")).ok).toBe(true);
151 });
152
153 test("the box page has no row for forge-waker, keeps the proxy's, and its Run log still names the container", async () => {
154 const text = await page(ada);
155 expect(text).not.toContain(`href="/games/mc/${WAKER}"`);
156 expect(text).not.toContain(`action="/games/mc/${WAKER}/power"`);
157 expect(text).toContain('action="/games/mc/velocity/power"');
158 expect(text).toContain("game-forge-waker-1");
159 });
160
161 test("the games tool's list leaves forge-waker out and keeps the proxy", async () => {
162 const res = await http.handle(
163 new Request("http://forge.test/mcp", {
164 method: "POST",
165 headers: { "content-type": "application/json", accept: "application/json, text/event-stream", authorization: `Bearer ${createToken(app.db, ada.id, "t", "admin").token}` },
166 body: JSON.stringify({ jsonrpc: "2.0", id: 1, method: "tools/call", params: { name: "games", arguments: { action: "list" } } }),
167 }),
168 );
169 const said = (await res.json()) as { result: { content: { text: string }[] } };
170 const listed = JSON.parse(said.result.content[0]!.text) as { items: { services: { name: string }[] }[] };
171 expect(listed.items[0]!.services.map((s) => s.name)).toEqual(["hub", "hunting", "minigames", "survival", "velocity"]);
172 });
173
174 test("the terminal's Games leaves forge-waker out and keeps the proxy", async () => {
175 const { app: tui, session } = createForgeApp(
176 app,
177 { sshUsername: "ada", remoteAddress: "127.0.0.1", fingerprint: "SHA256:test", user: ada },
178 { terminal: headlessTerminal(140, 40), exitHooks: false },
179 );
180 tui.start();
181 tui.ctx.push(gamesScreen(session, tui.ctx));
182 await settleApp(tui);
183 const text = tui.screen.toText();
184 tui.stop?.();
185 expect(text).toContain("mc/velocity");
186 expect(text).toContain("mc/minigames");
187 expect(text).not.toContain(`mc/${WAKER}`);
188 });
189
190 test.each(["", "/stream"])("forge-waker has no page: GET %p is not found", async (path) => {
191 const res = await http.handle(new Request(`http://forge.test/games/mc/${WAKER}${path}`, { headers: { cookie: `forge_session=${createSession(app.db, ada.id).token}` } }));
192 await res.body?.cancel();
193 expect(res.status).toBe(404);
194 });
195
196 // Every per-service write the page has.
197 test.each([
198 ["power", { kind: "stop" }],
199 ["people", { op: "op", player: "Alice" }],
200 ["command", { text: "stop" }],
201 ["env", { key: "A", value: "b" }],
202 ["settings", { key: "motd", value: "x" }],
203 ["sleep", { policy: "sleep" }],
204 ["world", { op: "snapshot" }],
205 ["mods/install", { slug: "luckperms" }],
206 ["mods/update", {}],
207 ["mods/remove", { project: "luckperms" }],
208 ["mods/pack", { slug: "x" }],
209 ["jar", {}],
210 ["crash/share", {}],
211 ] as [string, Record<string, string>][])("forge-waker takes no write: POST %s is not found and queues nothing", async (path, form) => {
212 const res = await http.handle(
213 new Request(`http://forge.test/games/mc/${WAKER}/${path}`, {
214 method: "POST",
215 headers: { cookie: `forge_session=${createSession(app.db, ada.id).token}`, origin: "http://forge.test" },
216 body: new URLSearchParams(form),
217 }),
218 );
219 expect(res.status).toBe(404);
220 expect(recentCommands(app.db, boxNamed(app.db, "mc")!.id, WAKER)).toEqual([]);
221 });
222
223 test.each([
224 { action: "metrics" },
225 { action: "config" },
226 { action: "mods" },
227 { action: "power", kind: "stop" },
228 { action: "console", text: "stop" },
229 { action: "people", op: "op", player: "Alice" },
230 { action: "env", key: "A", value: "b" },
231 { action: "config_set", key: "motd", value: "x", dryRun: false },
232 { action: "mods_install", project: "luckperms", dryRun: false },
233 { action: "sleep", value: "sleep" },
234 { action: "world", op: "snapshot" },
235 ])(
236 "the games tool refuses %j on forge-waker",
237 async (args) => {
238 const res = await http.handle(
239 new Request("http://forge.test/mcp", {
240 method: "POST",
241 headers: { "content-type": "application/json", accept: "application/json, text/event-stream", authorization: `Bearer ${createToken(app.db, ada.id, "w", "admin").token}` },
242 body: JSON.stringify({ jsonrpc: "2.0", id: 1, method: "tools/call", params: { name: "games", arguments: { ...args, box: "mc", service: WAKER } } }),
243 }),
244 );
245 const said = (await res.json()) as { result: { isError?: boolean; content: { text: string }[] } };
246 expect(said.result.isError).toBe(true);
247 expect(said.result.content[0]!.text).toMatch(/no such service here|you may not see forge-waker|you are not an operator of forge-waker/);
248 expect(recentCommands(app.db, boxNamed(app.db, "mc")!.id, WAKER)).toEqual([]);
249 },
250 );
116251 });

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

Keyboard shortcuts

Docs