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

Games: the record says which door a command came through, and a question through /forge is a read #17820

opened this

Juniper asked for changes (review 01m8x4p7qzfvjs0xzd9j8x0m7b)

sold/forge-door-reads → main 2 commits 2 threads · 2 unresolved

Review

Sign in to review this change.
6 files changed +64 −29
docs/features/games.md +2 −2
@@ -82,7 +82,7 @@ Creating it is one commit to the network's compose file: the service from the Pa
8282
8383 ## From in the game
8484
85 A player can ask the forge from a server's chat (#17284). Link the name first: **Link your Minecraft name** under Minecraft on the account page (`/settings`), or `L` on the terminal's Games screen (`src/tui/screens/games.ts`), gives a one-time code (6 characters, 10 minutes, kept only as its hash) shown only to the person signed in. The block is there for everyone signed in once the forge has a game box, and neither door gives a code before that: a link gives no role. In chat on any server of the box, type `!forge link 4F7QXZ`; where the proxy has the plugin, type `/forge link 4F7QXZ`, then `/forge yes` and the six digits it shows. The link binds the account to the name and to the player's UUID as the server itself lists it (`list uuids`, the same answer People keeps as who is online), never to anything typed in chat; a Bedrock name (`.Name`) links the same way. A name the server does not list yet is told to stay on and try again, and the code stays good. Five wrong codes for a name lock it out for an hour. The account page lists the linked names with Unlink, and `/games/<box>` lists who is linked there to an operator of the box (anyone else sees their own links) and, to its owner, the last commands and what came of each. The forge's words to a player in game are not in the service's console.
85 A player can ask the forge from a server's chat (#17284). Link the name first: **Link your Minecraft name** under Minecraft on the account page (`/settings`), or `L` on the terminal's Games screen (`src/tui/screens/games.ts`), gives a one-time code (6 characters, 10 minutes, kept only as its hash) shown only to the person signed in. The block is there for everyone signed in once the forge has a game box, and neither door gives a code before that: a link gives no role. In chat on any server of the box, type `!forge link 4F7QXZ`; where the proxy has the plugin, type `/forge link 4F7QXZ`, then `/forge yes` and the six digits it shows. The link binds the account to the name and to the player's UUID as the server itself lists it (`list uuids`, the same answer People keeps as who is online), never to anything typed in chat; a Bedrock name (`.Name`) links the same way. A name the server does not list yet is told to stay on and try again, and the code stays good. Five wrong codes for a name lock it out for an hour. The account page lists the linked names with Unlink, and `/games/<box>` lists who is linked there to an operator of the box (anyone else sees their own links) and, to its owner, the last commands as they were typed (`/forge` or `!forge`, kept in `game_chat.door`) and what came of each. The forge's words to a player in game are not in the service's console.
8686
8787 A linked name that holds any role on the server it types on, viewer too, can ask (`src/games/ask.ts`): `!forge who is on`, `why could I not join`, `what does survival need`, `is survival asleep`, `what is the address`. The forge answers from what it keeps, with no crew turn and no change (what a server needs may be looked up on Modrinth). Only those words and no more are a question. An answer names only servers the account has a role on, and the player's own refused joins there and nobody else's: a refusal by a server the account has no role on is answered as if it never was. "Why" repeats the server's own words for the refusal, as the proxy logged them, with network addresses (IPv4 and IPv6) taken out; nothing else in an answer is from a log. Questions count in the limits below.
8888
@@ -92,7 +92,7 @@ A linked name that holds operator on the server it types on can also say:
9292 - `!forge help`.
9393 - `!forge <anything else>`: a new Talk conversation of the linked account. The crew's first answer comes back in chat (its first lines, then a link to the conversation): nothing the account could not read on the forge itself.
9494
95 Through the proxy's `/forge` a linked account, with a role on the box or without, can also say `/forge status` (the version that runs and what the crew does, read as that account by the MCP tools `now` and `releases`) and `/forge servers` (the servers it has a role on: state, players, memory). They are not answered in chat yet: on Paper 1.21.6 a `tellraw` over RCON reached only its player and no server log kept it (tested), and Fabric has not been tested. They have their own limit: 30 a minute and 600 an hour an account, 60 a minute a box. They do not wait behind a plan.
95 Through the proxy's `/forge` a linked account, with a role on the box or without, can also say `/forge status` (the version that runs and what the crew does, read as that account by the MCP tools `now` and `releases`) and `/forge servers` (the servers it has a role on: state, players, memory). They are not answered in chat yet. Tested on Paper 1.21.6 and Fabric 1.21.6, offline servers with no plugin that logs commands: a `tellraw` over RCON reached only its player, and neither stdout nor latest.log kept it. With the questions asked through `/forge`, they have their own limit: 30 a minute and 600 an hour an account, 60 a minute a box. A question in chat stays one of the 5 and 30. `status` and `servers` do not wait behind a plan; a question does.
9696
9797 Anyone else is told how to link (the settings page's address on this forge, the button's name, `!forge link <code>` and the 10 minutes), and nothing runs. A wrong or old code, and a link dropped because another player has the name, are answered with the same steps. Replies are RCON `tellraw` to the player, at most 6 lines of 200 characters. An account runs at most 5 commands a minute and 30 an hour; past that the reply says when to try again. A refusal is answered and kept once a minute for a name on a box (once a minute for a whole box that is off), and one sync reads at most 3 commands a player and 20 in all. A suspended account's link says nothing. Commands, links and unlinks are kept, a link code never in clear.
9898
src/core/migration-pins/20261203042200-game-chat-door.pin added +1
@@ -0,0 +1,1 @@
1 a26c0cb654d6281223d6cfc17a1f235248207bbc4dfa038cf5e2b38394248960
src/core/migrations/20261203042200-game-chat-door.ts added +5
@@ -0,0 +1,5 @@
1 // Which door a kept command came through (#17610): 'proxy' for `/forge`, '' for `!forge` in chat.
2 // Additive: one column; a row from before it says ''.
3 export default `
4 ALTER TABLE game_chat ADD COLUMN door TEXT NOT NULL DEFAULT '';

Rows from before this column say '' and show as !forge, though every old read row came through the proxy. Backfill UPDATE game_chat SET door = 'proxy' WHERE kind = 'read', or document the gap in docs/features/games.md.

5 `;
src/games/chat.ts +27 −23
@@ -46,7 +46,10 @@ export const NO_LINK_HERE = "This forge has no game box to link a name on.";
4646 export const PENDING_MS = 5 * 60_000;
4747 export const PER_MINUTE = 5;
4848 export const PER_HOUR = 30;
49 /** Reads of the forge (kind `read`), counted apart: an account's, and a whole box's. */
49 /**
50 * Reads through the proxy's door (`/forge status`, and a question), counted apart: an account's, and
51 * a whole box's.
52 */
5053 const READS_PER_MINUTE = 30;
5154 const READS_PER_HOUR = 600;
5255 const BOX_READS_PER_MINUTE = 60;
@@ -188,19 +191,18 @@ export const chatLog = (
188191 app: App,
189192 boxId: string,
190193 limit = 20,
191 ): { service: string; player: string; kind: string; words: string; outcome: string; at: string }[] =>
194 ): { service: string; player: string; kind: string; words: string; outcome: string; at: string; door: string }[] =>
192195 app.db
193196 .query<
194 { service: string; player: string; kind: string; words: string; outcome: string; at: string },
197 { service: string; player: string; kind: string; words: string; outcome: string; at: string; door: string },
195198 [string, number]
196 >("SELECT service, player, kind, words, outcome, at FROM game_chat WHERE box_id = ?1 ORDER BY id DESC LIMIT ?2")
199 >("SELECT service, player, kind, words, outcome, at, door FROM game_chat WHERE box_id = ?1 ORDER BY id DESC LIMIT ?2")
197200 .all(boxId, limit);
198201
199202 const audit = (
200203 app: App,
201204 box: GameBox,
202 service: string,
203 player: string,
205 at: Where,
204206 userId: string,
205207 kind: string,
206208 words: string,
@@ -208,8 +210,8 @@ const audit = (
208210 now: number,
209211 ): void => {
210212 app.db
211 .query("INSERT INTO game_chat (box_id, service, player, user_id, kind, words, outcome, at) VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7, ?8)")
212 .run(box.id, service, player, userId, kind, words.slice(0, 300), outcome.slice(0, 300), new Date(now).toISOString());
213 .query("INSERT INTO game_chat (box_id, service, player, user_id, kind, words, outcome, at, door) VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7, ?8, ?9)")
214 .run(box.id, at.service, at.player, userId, kind, words.slice(0, 300), outcome.slice(0, 300), new Date(now).toISOString(), at.ask === "" ? "" : "proxy");
213215 };
214216
215217 /** What there is, for someone not linked: nothing of this box or its network. */
@@ -333,7 +335,7 @@ function one(
333335 const uuidNow = (): string => door?.uuid ?? onlineUuid(app, box.id, service, player);
334336 // Through the proxy, what changes something or starts crew work waits for the player's code.
335337 const askFirst = (by: string, question: string, what: Confirmed): void => {
336 audit(app, box, service, player, by, "asked", shown, "asked to confirm", now);
338 audit(app, box, at, by, "asked", shown, "asked to confirm", now);
337339 say(db, box, at, [question], by, "gray", what);
338340 };
339341 // A link code is never kept in clear, typed right or wrong.
@@ -348,7 +350,7 @@ function one(
348350 .get(box.id, whole ? "" : player, new Date(now - REFUSE_MS).toISOString(), new Date(now).toISOString());
349351 // Through the proxy each request is answered: its plugin holds a player to six a minute.
350352 if (last !== null && door === undefined) return;
351 if (last === null) audit(app, box, service, player, by, "refused", shown, outcome, now);
353 if (last === null) audit(app, box, at, by, "refused", shown, outcome, now);
352354 say(db, box, at, typeof line === "string" ? [line] : line, by, color);
353355 };
354356 // Short lines: a phone's chat is narrow.
@@ -377,7 +379,7 @@ function one(
377379 .query<{ user_id: string }, [string, string]>("SELECT user_id FROM game_link_code WHERE code_hash = ?1 AND expires_at > ?2")
378380 .get(codeHash, new Date(now).toISOString());
379381 if (code === null) {
380 audit(app, box, service, player, "", "link", "link ****", "wrong code", now);
382 audit(app, box, at, "", "link", "link ****", "wrong code", now);
381383 return say(db, box, at, ["That code is not one the forge gave, or it ran out.", ...howToLink], "", "red");
382384 }
383385 // The UUID the server lists for this name now; not listed, the code stays good for another try.
@@ -394,7 +396,7 @@ function one(
394396 new Date(now).toISOString(),
395397 );
396398 const who = getUserById(db, code.user_id);
397 audit(app, box, service, player, code.user_id, "link", "link ****", "linked", now);
399 audit(app, box, at, code.user_id, "link", "link ****", "linked", now);
398400 return say(
399401 db,
400402 box,
@@ -417,14 +419,14 @@ function one(
417419 if (uuid === "") return refuse(user.id, "not seen online", `The forge does not see ${player} on ${service} yet: try again in a minute.`);
418420 if (uuid !== linked.uuid) {
419421 db.query("DELETE FROM game_link WHERE box_id = ?1 AND player = ?2").run(box.id, player);
420 audit(app, box, service, player, user.id, "refused", shown, "another player has the name: link dropped", now);
422 audit(app, box, at, user.id, "refused", shown, "another player has the name: link dropped", now);
421423 return say(db, box, at, [`${player} was linked as another player, so that link is gone.`, ...howToLink], "", "red");
422424 }
423425 }
424426 if (user === undefined)
425427 return refuse("", "not linked", [...(help ? UNLINKED_HELP : []), "Your Minecraft name is not linked yet.", ...howToLink], "gray");
426428 const role = roleOn(db, user, box.id, service);
427 // At the proxy's door only, until a Fabric server's log is known not to keep a `tellraw`.
429 // At the proxy's door only, for now.
428430 const read = door === undefined ? undefined : readOf(words);
429431 if (!mayDo(role, "viewer") && read === undefined && (door === undefined || !help)) {
430432 const says = `${user.username} has no role on ${service}.`;
@@ -433,29 +435,31 @@ function one(
433435 // A question only reads (`ask.ts`), so a viewer may ask; the rest takes an operator.
434436 const question = questionOf(words, service, serversSeen(app, user, box, compose));
435437 if (question === undefined && read === undefined && !help && !mayDo(role, "operator")) return refuse(user.id, "not an operator", `${user.username} is not an operator of ${service}.`);
438 const reads = read !== undefined || (door !== undefined && question !== undefined);
436439 // The commands that ran (not the refusals) in the last minute and hour; full means wait until the
437440 // oldest of them leaves the window.
438441 const full = ([ms, most]: readonly [number, number], whose = "user_id = ?1", id = user.id): number => {
439 const kinds = read === undefined ? "kind NOT IN ('refused', 'unlink', 'read')" : "kind = 'read'";
442 const aRead = "(kind = 'read' OR (kind = 'ask' AND door = 'proxy'))";
443 const kinds = reads ? aRead : `kind NOT IN ('refused', 'unlink') AND NOT ${aRead}`;
440444 const ran = db
441445 .query<{ at: string }, [string, string]>(`SELECT at FROM game_chat WHERE ${whose} AND ${kinds} AND at > ?2 ORDER BY at`)
442446 .all(id, new Date(now - ms).toISOString());
443447 return ran.length < most ? 0 : Date.parse(ran[ran.length - most]!.at) + ms;
444448 };
445449 const until =
446 read === undefined
447 ? Math.max(full([60_000, PER_MINUTE]), full([3_600_000, PER_HOUR]))
448 : Math.max(full([60_000, READS_PER_MINUTE]), full([3_600_000, READS_PER_HOUR]), full([60_000, BOX_READS_PER_MINUTE], "box_id = ?1", box.id));
450 reads
451 ? Math.max(full([60_000, READS_PER_MINUTE]), full([3_600_000, READS_PER_HOUR]), full([60_000, BOX_READS_PER_MINUTE], "box_id = ?1", box.id))
452 : Math.max(full([60_000, PER_MINUTE]), full([3_600_000, PER_HOUR]));
449453 if (until > now) {
450454 const secs = Math.ceil((until - now) / 1000);
451455 const again = secs < 120 ? `${secs} seconds` : `${Math.ceil(secs / 60)} minutes`;
452 const most = read === undefined ? `${PER_MINUTE} commands a minute and ${PER_HOUR}` : `${READS_PER_MINUTE} reads a minute and ${READS_PER_HOUR}`;
456 const most = reads ? `${READS_PER_MINUTE} reads a minute and ${READS_PER_HOUR}` : `${PER_MINUTE} commands a minute and ${PER_HOUR}`;
453457 return refuse(user.id, "rate limited", `At most ${most} an hour: try again in ${again}.`);
454458 }
455459 // Kept with its audit row, whose outcome the job writes when it is done.
456460 const later = (kind: "ask" | "read" | "plan" | "yes" | "talk", said: string, sha = ""): void => {
457461 if (kind === "talk" && door !== undefined && confirmed === undefined) return askFirst(user.id, `Ask the crew: "${said}"?`, { action: "words", words: said });
458 audit(app, box, service, player, user.id, kind, said, "waiting", now);
462 audit(app, box, at, user.id, kind, said, "waiting", now);
459463 db.query(
460464 "INSERT INTO game_chat_job (box_id, service, player, user_id, kind, words, sha, origin, audit_id, created_at, ask_id) VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7, ?8, last_insert_rowid(), ?9, ?10)",
461465 ).run(box.id, service, player, user.id, kind, said, sha, origin, new Date(now).toISOString(), at.ask);
@@ -463,7 +467,7 @@ function one(
463467 if (read !== undefined) return later("read", read);
464468 if (question !== undefined) return later("ask", words);
465469 if (help) {
466 audit(app, box, service, player, user.id, "help", words, "told", now);
470 audit(app, box, at, user.id, "help", words, "told", now);
467471 return say(
468472 db,
469473 box,
@@ -479,7 +483,7 @@ function one(
479483 if (lower === "no") {
480484 if (door !== undefined && confirmed === undefined) return askFirst(user.id, "Drop the plan that is waiting?", { action: "words", words });
481485 db.query("DELETE FROM game_chat_pending WHERE box_id = ?1 AND player = ?2").run(box.id, player);
482 audit(app, box, service, player, user.id, "no", words, "dropped", now);
486 audit(app, box, at, user.id, "no", words, "dropped", now);
483487 return say(db, box, at, ["Dropped."], user.id);
484488 }
485489 if (lower === "yes") {
@@ -497,7 +501,7 @@ function one(
497501 // very request, in chat by a yes.
498502 const mine = door === undefined ? "" : confirmed?.action === "yes" ? confirmed.words : undefined;
499503 if (pending === null || expired || pending.ask_id !== mine || pending.service !== service || pending.user_id !== user.id) {
500 audit(app, box, service, player, user.id, "yes", words, "nothing waiting", now);
504 audit(app, box, at, user.id, "yes", words, "nothing waiting", now);
501505 return say(db, box, at, ["Nothing here is waiting for your yes: ask again with !forge <what you want>."], user.id);
502506 }
503507 if (!changesNetwork(app, user, box)) return refuse(user.id, "not an operator of the box", notBox(user, box));
src/web/pages/games.ts +1 −1
@@ -408,7 +408,7 @@ function chatBlock(ctx: Ctx, box: GameBox, owner: boolean): Html | null {
408408 : rowList(players.map((p) => row({ title: p.player, meta: html`${p.username} · linked ${time(p.createdAt)}` })))}
409409 ${said.length === 0
410410 ? null
411 : rowList(said.map((c) => row({ title: `${c.player} on ${c.service}: !forge ${c.words}`, meta: html`${c.outcome} · ${time(c.at)}` })))}
411 : rowList(said.map((c) => row({ title: `${c.player} on ${c.service}: ${c.door === "proxy" ? "/forge" : "!forge"} ${c.words}`, meta: html`${c.outcome} · ${time(c.at)}` })))}

Both doors: the terminal's Games screen shows no last-commands list, so the owner cannot see this door there. Add it in src/tui/screens/games.ts, or a commit line No door: <why>. Share the /forge/!forge naming through one helper in src/games/chat.ts rather than a ternary here.

412412 </section>`;
413413 }
414414
test/game-door.test.ts +28 −3
@@ -9,6 +9,7 @@ import { tmpdir } from "node:os";
99 import { join } from "node:path";
1010 import { commitToBranch, createRepo } from "../src/actions/repos.ts";
1111 import { createApp, type App } from "../src/app.ts";
12 import { createSession } from "../src/core/sessions.ts";
1213 import { createUser, type User } from "../src/core/users.ts";
1314 import { chatLog, gameAsk, gameChat, linksOf, newLinkCode, runChat } from "../src/games/chat.ts";
1415 import { readCompose } from "../src/games/compose.ts";
@@ -152,6 +153,16 @@ test("status is the forge's own read, as the linked account; servers names those
152153 app.db.query("DELETE FROM game_chat_job").run();
153154 });
154155
156 test("the box's page names each command as it was typed: /forge at the proxy, !forge in chat", async () => {
157 await send([request("no such words here")]);
158 gameChat(app, box, { hub: ["[12:00:01] [Async Chat Thread - #3/INFO]: <ada> !forge help"] }, COMPOSE, "http://forge.test", now);
159 expect(chatLog(app, box.id, 2).map((r) => r.door)).toEqual(["", "proxy"]);
160 const http = forgeHttp(app);
161 const page = await (await http.handle(new Request("http://forge.test/games/mc", { headers: { cookie: `forge_session=${createSession(app.db, ada.id).token}` } }))).text();
162 expect(page).toContain("ada on hub: /forge no such words here");
163 expect(page).toContain("ada on hub: !forge help");
164 });
165
155166 test("a linked account with no role reads the forge and nothing of the box", async () => {
156167 const bo = await createUser(app.db, { username: "bo", email: "[email protected]", password: "a-good-passphrase", origin: "seed", trusted: true });
157168 if (!bo.ok) throw new Error(bo.error);
@@ -176,7 +187,21 @@ test("reads have their own limit: thirty a minute, and none is taken from the fi
176187 const read = async () => (await send([request("servers")]))[0]!.text;
177188 for (let i = 0; i < 30; i++) expect(await read()).toStartWith("hub: ");
178189 expect(await read()).toStartWith("At most 30 reads a minute");
179 expect((await send([request("what is the address")]))[0]!.text).toContain("play.example.test");
190 expect((await send([request("help")]))[0]!.text).toContain("/forge status");
191 });
192
193 test("a question through the proxy is a read; in chat it is one of the five", async () => {
194 for (let i = 0; i < 15; i++) {
195 expect((await send([request("what is the address")]))[0]!.text).toContain("play.example.test");
196 expect((await send([request("servers")]))[0]!.text).toStartWith("hub: ");
197 }
198 expect((await send([request("what is the address")]))[0]!.text).toStartWith("At most 30 reads a minute");
199 const chat = () => gameChat(app, box, { hub: ["[12:00:01] [Async Chat Thread - #3/INFO]: <ada> !forge what is the address"] }, COMPOSE, "http://forge.test", now);
200 for (let i = 0; i < 5; i++) chat();
201 expect(kinds(5)).toEqual(["ask", "ask", "ask", "ask", "ask"]);
202 chat();
203 expect(chatLog(app, box.id, 100).filter((r) => r.kind === "ask" && r.door === "" && r.at === new Date(now).toISOString())).toHaveLength(5);
204 await runChat(app, box.id);
180205 });
181206
182207 test("a read does not wait behind a plan", async () => {
@@ -292,13 +317,13 @@ test("the forge says which requests it took, so the box deletes no other", async
292317
293318 test("a request over the account's limit is taken and its player is told", async () => {
294319 await send([request(`link ${newLinkCode(app, ada)}`)]).then(([a]) => send([request("yes", { confirms: a!.id })]));
295 const asks = Array.from({ length: 7 }, () => request("what is the address"));
320 const asks = Array.from({ length: 7 }, () => request("help"));
296321 const taken = gameAsk(app, box, asks, COMPOSE, "http://forge.test", now);
297322 expect(taken).toEqual(asks.map((a) => a.id));
298323 await runChat(app, box.id);
299324 const told = toldTo(app.db, box, now);
300325 expect(told.map((a) => a.id).sort()).toEqual([...taken].sort());
301 expect(told.some((a) => a.text.includes("play.example.test"))).toBe(true);
326 expect(told.some((a) => a.text.includes("/forge status"))).toBe(true);
302327 expect(told.some((a) => /commands a minute|try again/i.test(a.text))).toBe(true);
303328 });
304329

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

Keyboard shortcuts

Docs