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

Games: what a page draws for an ro token matches what its POST allows #18433

opened this

Merged 9h 38m ago, live in production

scout/forge:scout/18432-games-what-a-page-draws-for-an-ro-token → main 0 commits fork 1 thread · 1 unresolved

  • Merged. scout/18432-games-what-a-page-draws-for-an-ro-token was merged into main as db29dfc.

Review

Sign in to review this change.
6 files changed +44 −19
docs/features/games.md +2
@@ -205,3 +205,5 @@ A game's own refusal is a failure: `op` with a name that does not exist ("That p
205205 **After an agent release** (`src/games/agent_watch.ts`, #18272): when this forge starts answering a game agent script it has not answered before, it watches the boxes that exist at that moment (one made later, or deleted, is not waited for) and posts one comment on the newest release's pull at that moment. That is the release that changed `agent.sh` unless another release landed before a box first synced with the new script; the forge does not work out which commit changed the script, so then the comment goes on the later release's pull. It says: whether each box checked in with the new script, whether the agent stayed near idle between syncs (the median of its first three readings at most 15% of one core; the agent reports `diag.agent.cpuPct`, its own and its children's CPU since the last full sync), and whether the rollback fired (`diag.agent.rolledBackSha` is the new sha). It posts when every judged box has a verdict, or after 30 minutes naming the boxes that did not check in; the forge's one-minute timer settles it, so a release whose boxes are all silent still gets its comment. The first sync a forge ever sees only records a baseline. Nobody asks for it and there is no screen: it is a comment, on every door a pull is.
206206
207207 **Held** (`src/games/hold.ts`): a box whose agent starts nothing until a person has looked at its volume (docs/features/game-box.md) says so first, on `/games/<box>`, on each of its servers' pages, at the top of the terminal's Games and box screens, on its machine in the cloud tree and as `held` in the `games` tool. Its owner reads why, when the agent last looked and the next step; anyone else only that its owner has to look. The agent sends a code (`diag.hold`), never a sentence, and one the forge does not know is said as held without a reason. Held is not stopped: containers that already run are left alone. Start, Restart and Recreate (`src/games/power.ts`), and a world's import, restore and snapshot (`src/games/worlds.ts`: each ends by starting the server), say "held" and are refused at every door, also when an old page or screen asks; Stop and Pull go through, as at the agent. A box that has gone silent is asked, and its agent answers. An older agent sends nothing, and nothing is said.
208
209 A token of scope `ro` opens the box and server pages but is drawn none of their controls (Start/Stop/Restart, the command input, the plugin plan, the new-server form): a page draws what its POST would accept for the credential sent, so an `rw` token sees them.
src/games/game_may.ts +8
@@ -43,3 +43,11 @@ export function seesGameBox(db: Database, asking: Principal, door: string, boxId
4343 askBeside(db, asking, `game ${door}`, "game.view", old, gameResource(db, userOf(asking), boxId));
4444 return old;
4545 }
46
47 /**
48 * Whether a page draws operator controls for `asking`: `mayOnGame` with the credential sent, as
49 * the POSTs ask, so a token of scope `ro` reads the page and is drawn none (`askingFor` reads
50 * with the account behind it, which is not what a page's buttons may promise).
51 */
52 export const drawsOperator = (db: Database, asking: Principal, boxId: string, service = ""): boolean =>
53 mayOnGame(db, asking, boxId, service, "operator");
src/web/pages/games.ts +7 −7
@@ -101,7 +101,7 @@ import { joinAddress, mainPower, NO_ADDRESS, PREVIEW_WORDS, privateWords, SAVE_W
101101 import { metricsSeries, playerEvents, recentErrors, type Point } from "../../games/metrics.ts";
102102 import { daySpark } from "../studio/kpi_row.ts";
103103 import { principalOf } from "../../core/principal.ts";
104 import { mayOnGame, seesGameBox } from "../../games/game_may.ts";
104 import { drawsOperator, mayOnGame, seesGameBox } from "../../games/game_may.ts";
105105
106106 /** A small line of a series (oldest first); nothing when no point is known. */
107107 const sparkOf = (points: readonly Point[], pick: (p: Point) => number | null, label: string): Html | null =>
@@ -291,7 +291,7 @@ export async function gameBoxPage(ctx: Ctx): Promise<Response> {
291291 const machine = role === "owner" ? pinnedOfBox(ctx.app, box) : undefined;
292292 const cloud = machine === undefined ? undefined : cloudFacts(ctx.app, machine);
293293 // A new server asked for in words (?words=…): planned for the preview before anything is written.
294 const operator = mayDo(role, "operator");
294 const operator = drawsOperator(ctx.app.db, principalOf(ctx.auth), box.id);
295295 const words = (ctx.url.searchParams.get("words") ?? "").slice(0, 300);
296296 const preview = operator && words.trim() !== "" ? await planServer(ctx.app, box, await wishOn(ctx.app, box, words)) : undefined;
297297 // A server asked to be taken out (?remove=…): its plan, the same way.
@@ -322,7 +322,7 @@ export async function gameBoxPage(ctx: Ctx): Promise<Response> {
322322 : rowList(
323323 visible.map((n) => {
324324 const s = seen.find((x) => x.name === n);
325 const act = mayDo(roleOn(ctx.app.db, user, box.id, n), "operator");
325 const act = drawsOperator(ctx.app.db, principalOf(ctx.auth), box.id, n);
326326 const day = metricsSeries(ctx.app.db, box, n, "24h");
327327 const tps = lastOf(day, (p) => p.tps);
328328 const players = day.length === 0 ? null : day.at(-1)!.players;
@@ -414,7 +414,7 @@ function chatBlock(ctx: Ctx, box: GameBox, owner: boolean): Html | null {
414414 // Every linked account to an operator of the box; anyone else, of one service too, their own
415415 // links.
416416 const user = ctx.auth.user!;
417 const all = mayDo(roleOn(ctx.app.db, user, box.id), "operator");
417 const all = drawsOperator(ctx.app.db, principalOf(ctx.auth), box.id);
418418 const players = playersOn(ctx.app, box.id).filter((p) => all || p.username === user.username);
419419 const said = owner ? chatLog(ctx.app, box.id, 10) : [];
420420 if (players.length === 0 && said.length === 0) return null;
@@ -543,7 +543,7 @@ export function containerConsole(ctx: Ctx, boxName: string, service: string): {
543543 const box = boxNamed(ctx.app.db, boxName);
544544 if (box === undefined || !SERVICE_NAME.test(service)) return undefined;
545545 if (!mayOnGame(ctx.app.db, askingFor(ctx), box.id, service, "viewer")) return undefined;
546 const act = mayOnGame(ctx.app.db, askingFor(ctx), box.id, service, "operator");
546 const act = drawsOperator(ctx.app.db, principalOf(ctx.auth), box.id, service);
547547 const base = `/games/${box.name}/${service}`;
548548 const blocks = serviceBlocks(ctx.app, box.id, service, act);
549549 const seen = servicesOf(ctx.app.db, box.id).find((s) => s.name === service);
@@ -566,7 +566,7 @@ export async function gameServicePage(ctx: Ctx): Promise<Response> {
566566 if (got instanceof Response) return got;
567567 const { box, role } = got;
568568 if (!SERVICE_NAME.test(service)) return notFoundPage(ctx);
569 const act = mayDo(role, "operator");
569 const act = drawsOperator(ctx.app.db, principalOf(ctx.auth), box.id, service);
570570 const shared = /^[A-Za-z0-9]{1,32}$/.test(ctx.url.searchParams.get("shared") ?? "") ? ctx.url.searchParams.get("shared")! : "";
571571 const compose = await readCompose(ctx.app, box);
572572 const held = await heldNotice(ctx, box, compose);
@@ -1032,7 +1032,7 @@ export function gameServiceStream(ctx: Ctx): Response {
10321032 const said = `${now}\n${age}\n${figures}`;
10331033 if (rows.length > 0 || said !== shown) emit("lines", { now, age, figures, rows, ...(got.gone ? { gone: LOG_GONE } : {}) });
10341034 shown = said;
1035 const changed = changes(serviceBlocks(ctx.app, box.id, service, mayDo(role, "operator")));
1035 const changed = changes(serviceBlocks(ctx.app, box.id, service, drawsOperator(ctx.app.db, principalOf(ctx.auth), box.id, service)));
10361036 if (changed.length > 0) emit("blocks", { blocks: changed.map((b) => blockEvent(b, box)) });
10371037 }),
10381038 );
src/web/pages/games_config.ts +7 −6
@@ -8,7 +8,9 @@
88 */
99
1010 import { commitConfig, configsOf, MAX_BYTES, planConfig, planRevertConfig, type ConfigPlan } from "../../games/plugin_config.ts";
11 import { mayDo, SERVICE_NAME, type GameBox, type Role } from "../../games/store.ts";
11 import { drawsOperator } from "../../games/game_may.ts";
12 import { principalOf } from "../../core/principal.ts";
13 import { SERVICE_NAME, type GameBox } from "../../games/store.ts";
1214 import { boxOf, operatorForm } from "./games.ts";
1315 import type { Ctx } from "../../http/context.ts";
1416 import { emptyLine } from "../empty_words.ts";
@@ -38,9 +40,9 @@ const diffBlock = (plan: ConfigPlan): Html =>
3840 (l) => html`<span data-op="${l.op === " " ? "same" : l.op === "+" ? "add" : "del"}">${l.op} ${l.text}</span>\n`,
3941 )}</pre>`;
4042
41 async function render(ctx: Ctx, box: GameBox, service: string, role: Role, editing: Editing | undefined, status = 200): Promise<Response> {
43 async function render(ctx: Ctx, box: GameBox, service: string, editing: Editing | undefined, status = 200): Promise<Response> {
outdated

role is unused now that act comes from drawsOperator. Remove the parameter, update both callers (got.role and the literal "operator" satisfies Role), and drop the Role import if nothing else needs it.

4244 const base = `/games/${box.name}/${service}`;
43 const act = mayDo(role, "operator");
45 const act = drawsOperator(ctx.app.db, principalOf(ctx.auth), box.id, service);
4446 const got = await configsOf(ctx.app, box, service);
4547 const plugins = got.ok ? got.value.plugins : [];
4648 return page(
@@ -141,15 +143,14 @@ export async function gameConfigPage(ctx: Ctx): Promise<Response> {
141143 if (got instanceof Response) return got;
142144 if (!SERVICE_NAME.test(service)) return notFoundPage(ctx);
143145 const path = ctx.url.searchParams.get("path") ?? "";
144 return render(ctx, got.box, service, got.role, path === "" ? undefined : { path, op: "set" });
146 return render(ctx, got.box, service, path === "" ? undefined : { path, op: "set" });
145147 }
146148 // POST /games/:box/:service/config/preview: plan a change; nothing is written.
147149 export async function gameConfigPreview(ctx: Ctx): Promise<Response> {
148150 const got = await operatorForm(ctx);
149151 if (got instanceof Response) return got;
150152 const p = await planned(ctx, got.box, got.service, got.form);
151 const role = "operator" satisfies Role;
152 return render(ctx, got.box, got.service, role, { path: p.path, ...(p.content === undefined ? {} : { content: p.content }), op: p.op, ...(p.plan.ok ? { plan: p.plan.value } : { error: p.plan.error }) });
153 return render(ctx, got.box, got.service, { path: p.path, ...(p.content === undefined ? {} : { content: p.content }), op: p.op, ...(p.plan.ok ? { plan: p.plan.value } : { error: p.plan.error }) });
153154 }
154155 // POST /games/:box/:service/config/commit: plan again, and commit only on the commit that was
155156 // previewed.
src/web/pages/games_topology.ts +5 −4
@@ -10,7 +10,9 @@ import type { Ctx } from "../../http/context.ts";
1010 import { metricsSeries } from "../../games/metrics.ts";
1111 import { isBedrock, networkOf, peopleOf } from "../../games/people.ts";
1212 import { isGameServer, proxyOf } from "../../games/sleep.ts";
13 import { mayDo, roleOn, servicesOf, type GameBox, type GameService } from "../../games/store.ts";
13 import { drawsOperator } from "../../games/game_may.ts";
14 import { principalOf } from "../../core/principal.ts";
15 import { servicesOf, type GameBox, type GameService } from "../../games/store.ts";
1416 import { html, type Html } from "../html.ts";
1517 import { btn } from "../ui.ts";
1618
@@ -66,7 +68,6 @@ const STATE_WORDS: Record<NetState, string> = { awake: "awake", waking: "waking
6668 export function topologyBlock(ctx: Ctx, box: GameBox, compose: string | undefined, visible: readonly string[]): Html {
6769 const proxy = proxyOf(compose ?? "");
6870 if (compose === undefined || proxy === undefined) return html``;
69 const user = ctx.auth.user!;
7071 const seen = servicesOf(ctx.app.db, box.id);
7172 const servers = visible.filter((n) => isGameServer(compose, n));
7273 const network = networkOf(ctx.app.db, box.id);
@@ -84,7 +85,7 @@ export function topologyBlock(ctx: Ctx, box: GameBox, compose: string | undefine
8485 const uuid = uuidOf.get(name) ?? "";
8586 const face = html`<img src="/games/head/${uuid === "" || isBedrock(name) ? "none" : uuid}" alt="" width="20" height="20" loading="lazy" />`;
8687 // Only to a server this person operates too: the move's own rule (`queuePeople`).
87 const targets = servers.filter((t) => t !== server && netState(seen.find((s) => s.name === t)) !== "stopped" && mayDo(roleOn(ctx.app.db, user, box.id, t), "operator"));
88 const targets = servers.filter((t) => t !== server && netState(seen.find((s) => s.name === t)) !== "stopped" && drawsOperator(ctx.app.db, principalOf(ctx.auth), box.id, t));
8889 if (!act || targets.length === 0) return html`<span class="net-head">${face} ${name}</span>`;
8990 return html`<details class="net-head">
9091 <summary>${face} ${name}</summary>
@@ -107,7 +108,7 @@ export function topologyBlock(ctx: Ctx, box: GameBox, compose: string | undefine
107108 const state = netState(s);
108109 const tps = metricsSeries(ctx.app.db, box, n, "1h").findLast((p) => p.tps !== null)?.tps ?? null;
109110 const list = players.get(n) ?? [];
110 const act = mayDo(roleOn(ctx.app.db, user, box.id, n), "operator");
111 const act = drawsOperator(ctx.app.db, principalOf(ctx.auth), box.id, n);
111112 return html`<div class="net-server" data-state="${state}">
112113 <a class="net-node" href="/games/${box.name}/${n}">
113114 <strong>${n}</strong>
test/game-proxy-jars.test.ts +15 −2
@@ -310,7 +310,7 @@ test("the proxy's page says the same of the AutoStopper the forge pins", async (
310310 expect(kept.ok).toBe(true);
311311 app.db.query("UPDATE game_jar SET sha256 = ?1 WHERE sha256 = ?2").run(stopper.sha256, sha256("PK\u0003\u0004 stands for it"));
312312 await put(setPolicy(COMPOSE, "hub", "sleep"));
313 const tok = createToken(app.db, ada.id, "r", "ro").token;
313 const tok = createToken(app.db, ada.id, "r", "rw").token;
314314 const page = await (await http.handle(new Request(`${ORIGIN}/games/mc/velocity`, { headers: { authorization: `Bearer ${tok}` } }))).text();
315315 expect(page).toContain("moved aside");
316316 expect(page).toContain("put back if the start fails");
@@ -414,7 +414,7 @@ test("the proxy's page shows the gained lines as rows, not in a box", async () =
414414 const stands = "PK\u0003\u0004 stands for the pinned one";
415415 expect((await storeJar(app, box.id, new Blob([stands]), "z.jar")).ok).toBe(true);
416416 app.db.query("UPDATE game_jar SET sha256 = ?1 WHERE sha256 = ?2").run(PINS[0]!.sha256, sha256(stands));
417 const tok = createToken(app.db, ada.id, "r", "ro").token;
417 const tok = createToken(app.db, ada.id, "r", "rw").token;
418418 const html = await (await http.handle(new Request(`${ORIGIN}/games/mc/velocity`, { headers: { authorization: `Bearer ${tok}` } }))).text();
419419 const part = html.slice(html.indexOf("<h2>Forge plugins</h2>")).split("</section>")[0]!;
420420 // One row a plugin, its facts in the row, the lines as plain rows under it.
@@ -482,3 +482,16 @@ test("the box's page says which version of the plugin the proxy loaded, and says
482482 expect(html).toContain("The proxy loaded forge 0.1.0, the pinned version.");
483483 expect(html).not.toContain("not the pinned");
484484 });
485
486 test("an ro token is drawn no power buttons or command input, an rw token is: what the page draws is what its POST allows", async () => {
487 await put(COMPOSE);
488 await sync();
489 const get = async (scope: "ro" | "rw") =>
490 (await http.handle(new Request(`${ORIGIN}/games/mc/velocity`, { headers: { authorization: `Bearer ${createToken(app.db, ada.id, "r", scope).token}` } }))).text();
491 const ro = await get("ro");
492 const rw = await get("rw");
493 expect(rw).toContain("/games/mc/velocity/power");
494 expect(ro).not.toContain("/games/mc/velocity/power");
495 expect(rw).toContain("/games/mc/velocity/command");
496 expect(ro).not.toContain("/games/mc/velocity/command");
497 });

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

Keyboard shortcuts

Docs