Public: anyone can read this; the crew can change it.
Games: /forge status and /forge servers #17799
Merged 14h 43m ago, live in production
sold/forge-status-servers → main 0 commits 1 thread · 1 unresolved
4 files
changed +190
−25
docs/features/games.md +4 −2
| @@ -82,7 +82,7 @@ Creating it is one commit to the network's compose file: the service from the Pa | ||
| 82 | 82 | |
| 83 | 83 | ## From in the game |
| 84 | 84 | |
| 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`. 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 and what came of each. The forge's words to a player in game are not in the service's console. | |
| 86 | 86 | |
| 87 | 87 | 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. |
| 88 | 88 | |
| @@ -92,11 +92,13 @@ A linked name that holds operator on the server it types on can also say: | ||
| 92 | 92 | - `!forge help`. |
| 93 | 93 | - `!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. |
| 94 | 94 | |
| 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. | |
| 96 | ||
| 95 | 97 | 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. |
| 96 | 98 | |
| 97 | 99 | The sync only checks and keeps a command (`game_chat_job`); a plan, a commit or a message to the crew runs after it, one at a time for each box, and the next sync takes up what a restart left. The agent sends a batch of chat again under the same `chatId` until a sync is answered, and the forge skips one it has; a yes whose commit landed is not committed again. |
| 98 | 100 | |
| 99 | **Through the proxy (`/forge`, #17610).** The forge's side of a command on the proxy itself (`src/games/door.ts`); the plugin and the agent's part are not on a box yet. A request comes in the sync's `ask` (`{ id, uuid, name, server, words, confirms? }`, at most 20) and its answers go back in `told` (`{ n, id, uuid, text, confirm }`, at most 20, dropped after an hour); a quick poll (`light`) that says `told: true` gets them too. An agent that sends `got`, the numbers `n` it has (an empty list too), is handed each answer until it has it, and skips a number it had; one that never sends it, each once. A question's three minutes count from its first handing out: after the first of them it is handed out again only as words to ask again. It runs the same rules as `!forge`: the link, the role and the limits; the UUID is the proxy's own. Each request is kept once by its `id` for a day, so one sent again does nothing. Whenever the sync carries `ask`, the answer's `asked` lists the ids the forge took, now or before; the agent deletes those and sends the rest again. Not taken: past the first 20, or no compose file could be read. One that names no player cannot be answered: it is taken, and the forge's log counts it. | |
| 101 | **Through the proxy (`/forge`, #17610).** The forge's side of a command on the proxy itself (`src/games/door.ts`); a box has it once its proxy has the plugin. A request comes in the sync's `ask` (`{ id, uuid, name, server, words, confirms? }`, at most 20) and its answers go back in `told` (`{ n, id, uuid, text, confirm }`, at most 20, dropped after an hour); a quick poll (`light`) that says `told: true` gets them too. An agent that sends `got`, the numbers `n` it has (an empty list too), is handed each answer until it has it, and skips a number it had; one that never sends it, each once. A question's three minutes count from its first handing out: after the first of them it is handed out again only as words to ask again. It runs the same rules as `!forge`: the link, the role and the limits; the UUID is the proxy's own. Each request is kept once by its `id` for a day, so one sent again does nothing. Whenever the sync carries `ask`, the answer's `asked` lists the ids the forge took, now or before; the agent deletes those and sends the rest again. Not taken: past the first 20, or no compose file could be read. One that names no player cannot be answered: it is taken, and the forge's log counts it. | |
| 100 | 102 | |
| 101 | 103 | A server can show text whose click runs a command as the player, so a request that links a name, builds or drops a plan, or asks the crew changes nothing: it is answered with `confirm: true`, and the proxy shows the player a one-time code. Only a later request whose `confirms` names it acts, from the same UUID on the same box, once, within three minutes of the answer going to the box (the code itself lives two). A plan is built only at the door it was asked at: a `!forge yes` in chat never builds a plan made through the proxy, nor the other way round. Questions, help and the making of a plan need no code. |
| 102 | 104 |
src/games/chat.ts +52 −22
| @@ -19,7 +19,9 @@ | ||
| 19 | 19 | * /me ("* Name …") and tellraw (never logged) do not match. Every command and its outcome is kept |
| 20 | 20 | * (`game_chat`) and counted: at most five a minute and thirty an hour an account; a refusal is kept |
| 21 | 21 | * and answered once a minute a name. A new server takes operator of the box, not of one server. |
| 22 | * A question (`ask.ts`) only reads, so it takes viewer, not operator. | |
| 22 | * A question (`ask.ts`) only reads, so it takes viewer, not operator. `/forge status` and | |
| 23 | * `/forge servers` (`forge_read.ts`) take the link alone, at the proxy's door only, and have their | |
| 24 | * own limit. | |
| 23 | 25 | */ |
| 24 | 26 | |
| 25 | 27 | import type { App } from "../app.ts"; |
| @@ -32,6 +34,7 @@ import { sha256 } from "../kernel/hash.ts"; | ||
| 32 | 34 | import { answerTo, questionOf, serversSeen } from "./ask.ts"; |
| 33 | 35 | import { composeServices, readCompose, serviceEnv } from "./compose.ts"; |
| 34 | 36 | import { asksIn, keepAsk, say, takeConfirmed, type Confirmed, type Where } from "./door.ts"; |
| 37 | import { readLines, readOf } from "./forge_read.ts"; | |
| 35 | 38 | import { commitServer, planServer, wishOn } from "./presets.ts"; |
| 36 | 39 | import { peopleOf } from "./people.ts"; |
| 37 | 40 | import { proxyOf } from "./sleep.ts"; |
| @@ -43,6 +46,10 @@ export const NO_LINK_HERE = "This forge has no game box to link a name on."; | ||
| 43 | 46 | export const PENDING_MS = 5 * 60_000; |
| 44 | 47 | export const PER_MINUTE = 5; |
| 45 | 48 | export const PER_HOUR = 30; |
| 49 | /** Reads of the forge (kind `read`), counted apart: an account's, and a whole box's. */ | |
| 50 | const READS_PER_MINUTE = 30; | |
| 51 | const READS_PER_HOUR = 600; | |
| 52 | const BOX_READS_PER_MINUTE = 60; | |
| 46 | 53 | const FAILED_LINKS = 5; |
| 47 | 54 | const NAME = "[.]?[A-Za-z0-9_]{1,16}"; |
| 48 | 55 | const CODE_CHARS = "23456789ABCDEFGHJKMNPQRSTUVWXYZ"; |
| @@ -417,35 +424,43 @@ function one( | ||
| 417 | 424 | if (user === undefined) |
| 418 | 425 | return refuse("", "not linked", [...(help ? UNLINKED_HELP : []), "Your Minecraft name is not linked yet.", ...howToLink], "gray"); |
| 419 | 426 | const role = roleOn(db, user, box.id, service); |
| 420 | if (!mayDo(role, "viewer")) { | |
| 427 | // At the proxy's door only, until a Fabric server's log is known not to keep a `tellraw`. | |
| 428 | const read = door === undefined ? undefined : readOf(words); | |
| 429 | if (!mayDo(role, "viewer") && read === undefined && (door === undefined || !help)) { | |
| 421 | 430 | const says = `${user.username} has no role on ${service}.`; |
| 422 | 431 | return refuse(user.id, "no role", blockedText(blockedBy({ says, readerCan: false, who: "an owner of this game box", can: "give you one" }))); |
| 423 | 432 | } |
| 424 | 433 | // A question only reads (`ask.ts`), so a viewer may ask; the rest takes an operator. |
| 425 | 434 | const question = questionOf(words, service, serversSeen(app, user, box, compose)); |
| 426 | if (question === undefined && !help && !mayDo(role, "operator")) return refuse(user.id, "not an operator", `${user.username} is not an operator of ${service}.`); | |
| 435 | if (question === undefined && read === undefined && !help && !mayDo(role, "operator")) return refuse(user.id, "not an operator", `${user.username} is not an operator of ${service}.`); | |
| 427 | 436 | // The commands that ran (not the refusals) in the last minute and hour; full means wait until the |
| 428 | 437 | // oldest of them leaves the window. |
| 429 | const full = ([ms, most]: readonly [number, number]): number | undefined => { | |
| 438 | 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'"; | |
| 430 | 440 | const ran = db |
| 431 | .query<{ at: string }, [string, string]>("SELECT at FROM game_chat WHERE user_id = ?1 AND kind NOT IN ('refused', 'unlink') AND at > ?2 ORDER BY at") | |
| 432 | .all(user.id, new Date(now - ms).toISOString()); | |
| 433 | return ran.length < most ? undefined : Date.parse(ran[ran.length - most]!.at) + ms; | |
| 441 | .query<{ at: string }, [string, string]>(`SELECT at FROM game_chat WHERE ${whose} AND ${kinds} AND at > ?2 ORDER BY at`) | |
| 442 | .all(id, new Date(now - ms).toISOString()); | |
| 443 | return ran.length < most ? 0 : Date.parse(ran[ran.length - most]!.at) + ms; | |
| 434 | 444 | }; |
| 435 | const until = Math.max(full([60_000, PER_MINUTE]) ?? 0, full([3_600_000, PER_HOUR]) ?? 0); | |
| 445 | 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)); | |
| 436 | 449 | if (until > now) { |
| 437 | 450 | const secs = Math.ceil((until - now) / 1000); |
| 438 | 451 | const again = secs < 120 ? `${secs} seconds` : `${Math.ceil(secs / 60)} minutes`; |
| 439 | return refuse(user.id, "rate limited", `At most ${PER_MINUTE} commands a minute and ${PER_HOUR} an hour: try again in ${again}.`); | |
| 452 | const most = read === undefined ? `${PER_MINUTE} commands a minute and ${PER_HOUR}` : `${READS_PER_MINUTE} reads a minute and ${READS_PER_HOUR}`; | |
| 453 | return refuse(user.id, "rate limited", `At most ${most} an hour: try again in ${again}.`); | |
| 440 | 454 | } |
| 441 | 455 | // Kept with its audit row, whose outcome the job writes when it is done. |
| 442 | const later = (kind: "ask" | "plan" | "yes" | "talk", said: string, sha = ""): void => { | |
| 456 | const later = (kind: "ask" | "read" | "plan" | "yes" | "talk", said: string, sha = ""): void => { | |
| 443 | 457 | if (kind === "talk" && door !== undefined && confirmed === undefined) return askFirst(user.id, `Ask the crew: "${said}"?`, { action: "words", words: said }); |
| 444 | 458 | audit(app, box, service, player, user.id, kind, said, "waiting", now); |
| 445 | 459 | db.query( |
| 446 | 460 | "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)", |
| 447 | 461 | ).run(box.id, service, player, user.id, kind, said, sha, origin, new Date(now).toISOString(), at.ask); |
| 448 | 462 | }; |
| 463 | if (read !== undefined) return later("read", read); | |
| 449 | 464 | if (question !== undefined) return later("ask", words); |
| 450 | 465 | if (help) { |
| 451 | 466 | audit(app, box, service, player, user.id, "help", words, "told", now); |
| @@ -454,7 +469,8 @@ function one( | ||
| 454 | 469 | box, |
| 455 | 470 | at, |
| 456 | 471 | [ |
| 457 | "Ask: who is on? why could I not join? what does survival need? is survival asleep? what is the address?", | |
| 472 | ...(door === undefined ? [] : [`!forge status: the forge and its crew.${mayDo(role, "viewer") ? " !forge servers: the servers you may see." : ""}`]), | |
| 473 | ...(mayDo(role, "viewer") ? ["Ask: who is on? why could I not join? what does survival need? is survival asleep? what is the address?"] : []), | |
| 458 | 474 | ...(mayDo(role, "operator") ? OPERATOR_HELP : []), |
| 459 | 475 | ], |
| 460 | 476 | user.id, |
| @@ -507,7 +523,7 @@ interface Job { | ||
| 507 | 523 | readonly service: string; |
| 508 | 524 | readonly player: string; |
| 509 | 525 | readonly user_id: string; |
| 510 | readonly kind: "ask" | "plan" | "yes" | "talk" | "reply"; | |
| 526 | readonly kind: "ask" | "read" | "plan" | "yes" | "talk" | "reply"; | |
| 511 | 527 | readonly words: string; |
| 512 | 528 | readonly sha: string; |
| 513 | 529 | readonly name: string; |
| @@ -519,7 +535,7 @@ interface Job { | ||
| 519 | 535 | readonly ask_id: string; |
| 520 | 536 | } |
| 521 | 537 | |
| 522 | /** Each box's worker, and the jobs whose crew turn this process is waiting on. */ | |
| 538 | /** Each box's two workers (reads, and the rest), and the jobs whose crew turn this process is waiting on. */ | |
| 523 | 539 | const workers = new WeakMap<App, { boxes: Map<string, Promise<void>>; live: Set<number> }>(); |
| 524 | 540 | function workersOf(app: App): { boxes: Map<string, Promise<void>>; live: Set<number> } { |
| 525 | 541 | let w = workers.get(app); |
| @@ -528,14 +544,20 @@ function workersOf(app: App): { boxes: Map<string, Promise<void>>; live: Set<num | ||
| 528 | 544 | } |
| 529 | 545 | |
| 530 | 546 | /** |
| 531 | * Run a box's waiting jobs, one at a time, oldest first; a call while it runs joins it. Every sync | |
| 547 | * Run a box's waiting jobs, one at a time, oldest first, the reads beside the rest so that none | |
| 548 | * waits behind a plan; a call while it runs joins it. Every sync | |
| 532 | 549 | * calls it, so what a restart left is picked up by the next one. A job goes with its answer in one |
| 533 | 550 | * transaction, and each kind is safe to start again: a plan writes nothing but the plan, a talk is |
| 534 | 551 | * sent in the transaction that marks it sent, and a yes commits on its plan's commit or not at all. |
| 535 | 552 | */ |
| 536 | export function runChat(app: App, boxId: string): Promise<void> { | |
| 553 | export async function runChat(app: App, boxId: string): Promise<void> { | |
| 554 | await Promise.all([runLane(app, boxId, false), runLane(app, boxId, true)]); | |
| 555 | } | |
| 556 | ||
| 557 | function runLane(app: App, boxId: string, reads: boolean): Promise<void> { | |
| 537 | 558 | const { boxes } = workersOf(app); |
| 538 | const running = boxes.get(boxId); | |
| 559 | const lane = `${boxId} ${reads ? "reads" : "rest"}`; | |
| 560 | const running = boxes.get(lane); | |
| 539 | 561 | if (running !== undefined) return running; |
| 540 | 562 | const work = (async () => { |
| 541 | 563 | // After the sync's own turn, so its answer never waits on a job's first steps. |
| @@ -543,7 +565,7 @@ export function runChat(app: App, boxId: string): Promise<void> { | ||
| 543 | 565 | try { |
| 544 | 566 | for (;;) { |
| 545 | 567 | if (app.closing.signal.aborted) return; |
| 546 | const job = nextJob(app, boxId); | |
| 568 | const job = nextJob(app, boxId, reads); | |
| 547 | 569 | const box = listBoxes(app.db).find((b) => b.id === boxId); |
| 548 | 570 | if (job === null || box === undefined) return; |
| 549 | 571 | try { |
| @@ -557,17 +579,17 @@ export function runChat(app: App, boxId: string): Promise<void> { | ||
| 557 | 579 | } catch (e) { |
| 558 | 580 | if (!app.closing.signal.aborted) app.log.error("!forge commands stopped until the next check-in", { error: String(e) }); |
| 559 | 581 | } finally { |
| 560 | boxes.delete(boxId); | |
| 582 | boxes.delete(lane); | |
| 561 | 583 | } |
| 562 | 584 | })(); |
| 563 | boxes.set(boxId, work); | |
| 585 | boxes.set(lane, work); | |
| 564 | 586 | return work; |
| 565 | 587 | } |
| 566 | 588 | |
| 567 | 589 | /** The oldest job to run: an answer is due when it is there, or when it was waited for too long. */ |
| 568 | function nextJob(app: App, boxId: string): Job | null { | |
| 590 | function nextJob(app: App, boxId: string, reads: boolean): Job | null { | |
| 569 | 591 | const { live } = workersOf(app); |
| 570 | const jobs = app.db.query<Job, [string]>("SELECT * FROM game_chat_job WHERE box_id = ?1 ORDER BY id").all(boxId); | |
| 592 | const jobs = app.db.query<Job, [string]>(`SELECT * FROM game_chat_job WHERE box_id = ?1 AND kind ${reads ? "=" : "!="} 'read' ORDER BY id`).all(boxId); | |
| 571 | 593 | return ( |
| 572 | 594 | jobs.find( |
| 573 | 595 | (j) => j.kind !== "reply" || (!live.has(j.id) && (replyOf(app, j) !== undefined || Date.now() - Date.parse(j.created_at) > REPLY_MS)), |
| @@ -595,8 +617,16 @@ async function runJob(app: App, box: GameBox, job: Job): Promise<void> { | ||
| 595 | 617 | if (job.kind === "reply") return answer(app, box, job); |
| 596 | 618 | // Asked again here: a grant or an account can go while a job waits. |
| 597 | 619 | const user = getUserById(db, job.user_id); |
| 598 | if (user === undefined || !isActive(user) || !mayDo(roleOn(db, user, box.id, job.service), job.kind === "ask" ? "viewer" : "operator")) | |
| 620 | // A read of the forge takes the account alone: what it may see, the read itself decides. | |
| 621 | if (user === undefined || !isActive(user) || (job.kind !== "read" && !mayDo(roleOn(db, user, box.id, job.service), job.kind === "ask" ? "viewer" : "operator"))) | |
| 599 | 622 | return finish(app, box, job, "no longer allowed", ["Your account may no longer do that here."], "red"); |
| 623 | if (job.kind === "read") { | |
| 624 | const read = readOf(job.words); | |
| 625 | const compose = read === "servers" ? await readCompose(app, box) : undefined; | |
| 626 | if (read === undefined || (read === "servers" && compose === undefined)) | |
| 627 | return finish(app, box, job, "not readable", ["The forge cannot read this network's file now: try again in a minute."], "red"); | |
| 628 | return finish(app, box, job, "told", await readLines(app, user, box, compose?.text ?? "", job.origin, read)); | |
| 629 | } | |
| 600 | 630 | if (job.kind === "ask") { |
| 601 | 631 | const compose = await readCompose(app, box); |
| 602 | 632 | // A file that does not parse has no services: no answer is made from it. |
src/games/forge_read.ts added +68
| @@ -0,0 +1,68 @@ | ||
| 1 | /** | |
| 2 | * What a player can see of the forge from the game (#17610): `/forge status` and `/forge servers`. | |
| 3 | * Each is one more face of a read that exists, as the linked account, printed short. A tool is run | |
| 4 | * with a read-only scope and named by this file alone: nothing typed chooses one. | |
| 5 | */ | |
| 6 | ||
| 7 | import type { App } from "../app.ts"; | |
| 8 | import type { User } from "../core/users.ts"; | |
| 9 | import type { Ctx } from "../http/context.ts"; | |
| 10 | import { loadMcp } from "../http/mcp/load.ts"; | |
| 11 | import { visible } from "../http/mcp/shared.ts"; | |
| 12 | import { peopleOf } from "./people.ts"; | |
| 13 | import { serversSeen } from "./ask.ts"; | |
| 14 | import { servicesOf, type GameBox } from "./store.ts"; | |
| 15 | ||
| 16 | export type Read = "status" | "servers"; | |
| 17 | ||
| 18 | /** The read these words name, whole: anything more is a question or the crew's. */ | |
| 19 | export function readOf(words: string): Read | undefined { | |
| 20 | const w = words.trim().toLowerCase(); | |
| 21 | return w === "status" || w === "servers" ? w : undefined; | |
| 22 | } | |
| 23 | ||
| 24 | /** One line of somebody's text: no control characters, no colour codes, cut. */ | |
| 25 | const line = (text: string, most = 120): string => { | |
| 26 | const flat = text.replace(/§.?/gu, "").replace(/[\p{Cc}\s]+/gu, " ").trim(); | |
| 27 | return flat.length <= most ? flat : `${flat.slice(0, most - 3)}...`; | |
| 28 | }; | |
| 29 | ||
| 30 | /** A read-only tool's answer as `user` gets it at /mcp; undefined when it refuses them. */ | |
| 31 | async function readTool(app: App, user: User, origin: string, name: "now" | "releases", args: Record<string, unknown>): Promise<unknown> { | |
| 32 | const { TOOLS } = await loadMcp(); | |
| 33 | const url = new URL("/mcp", origin); | |
| 34 | const ctx: Ctx = { app, request: new Request(url.href), url, params: {}, auth: { user, scope: "ro", via: "token" }, theme: undefined }; | |
| 35 | const tool = TOOLS.find((t) => t.name === name); | |
| 36 | if (tool === undefined || tool.writes || !visible(tool, ctx, user)) return undefined; | |
| 37 | const answer = await tool.run(ctx, user, args); | |
| 38 | return answer.ok ? answer.value : undefined; | |
| 39 | } | |
| 40 | ||
| 41 | async function statusLines(app: App, user: User, origin: string): Promise<string[]> { | |
| 42 | const [crew, shipped] = await Promise.all([readTool(app, user, origin, "now", { brief: true }), readTool(app, user, origin, "releases", { shipped: true })]); | |
| 43 | const live = (shipped ?? {}) as { release?: unknown; version?: unknown; liveSince?: unknown }; | |
| 44 | const name = typeof live.release === "string" ? live.release : typeof live.version === "string" ? live.version : ""; | |
| 45 | return [ | |
| 46 | name === "" ? "The forge is up." : `The forge is up, on ${line(name, 40)}${typeof live.liveSince === "string" ? `, since ${live.liveSince.slice(0, 16).replace("T", " ")} UTC` : ""}.`, | |
| 47 | ...(typeof crew === "string" ? [line(crew, 190)] : []), | |
| 48 | ]; | |
| 49 | } | |
| 50 | ||
| 51 | /** The box's servers `user` has a role on, and no other. */ | |
| 52 | function serverLines(app: App, user: User, box: GameBox, compose: string): string[] { | |
| 53 | const seen = serversSeen(app, user, box, compose); | |
| 54 | const rows = servicesOf(app.db, box.id).filter((s) => seen.includes(s.name)); | |
| 55 | if (rows.length === 0) return ["You have no role on a server here."]; | |
| 56 | return rows.map((s) => { | |
| 57 | if (s.asleep) return `${s.name}: asleep, wakes when someone joins`; | |
| 58 | if (s.state !== "running") return `${s.name}: ${line(s.state, 20)}`; | |
| 59 | const on = peopleOf(app.db, box.id, s.name).online.length; | |
| 60 | // 0 MiB while running is a reading the agent could not take. | |
| 61 | const memory = s.memMiB > 0 ? `, ${(s.memMiB / 1024).toFixed(1)} GB` : ""; | |
| 62 | return `${s.name}: ${s.health === "starting" ? "starting" : "running"}, ${on === 1 ? "1 player" : `${String(on)} players`}${memory}`; | |
| 63 | }); | |
| 64 | } | |
| 65 | ||
| 66 | /** What the forge says to `read`, as `user`: nothing of the box to someone with no role on it. */ | |
| 67 | export const readLines = (app: App, user: User, box: GameBox, compose: string, origin: string, read: Read): Promise<string[]> => | |
| 68 | read === "status" ? statusLines(app, user, origin) : Promise.resolve(serverLines(app, user, box, compose)); |
test/game-door.test.ts +66 −1
| @@ -17,6 +17,7 @@ import { boxNamed, createGameBox, type GameBox } from "../src/games/store.ts"; | ||
| 17 | 17 | import { forgeHttp } from "../src/http/server.ts"; |
| 18 | 18 | import { chatAged } from "./helpers/game-chat-clock.ts"; |
| 19 | 19 | import { quietLogs } from "./helpers/globals.ts"; |
| 20 | import { pollUntil } from "./helpers/poll.ts"; | |
| 20 | 21 | |
| 21 | 22 | quietLogs(); |
| 22 | 23 | |
| @@ -57,6 +58,8 @@ let box: GameBox; | ||
| 57 | 58 | let other: GameBox; |
| 58 | 59 | let token = ""; |
| 59 | 60 | let now = Date.now(); |
| 61 | /** What Modrinth's answers wait for. */ | |
| 62 | let slow: Promise<void> = Promise.resolve(); | |
| 60 | 63 | |
| 61 | 64 | const request = (words: string, more: Record<string, unknown> = {}) => ({ id: crypto.randomUUID() as string, at: now, uuid: ADA, name: "ada", server: "hub", words, ...more }); |
| 62 | 65 | const send = async (asks: unknown, on = box) => { |
| @@ -70,7 +73,7 @@ const kinds = (n: number): string[] => chatLog(app, box.id, n).map((r) => r.kind | ||
| 70 | 73 | |
| 71 | 74 | beforeAll(async () => { |
| 72 | 75 | dir = await mkdtemp(join(tmpdir(), "forge-game-door-")); |
| 73 | app = createApp({ dataDir: dir, port: 0, host: "forge.test", modrinthFetch: (async () => Response.json([])) as unknown as typeof fetch }); | |
| 76 | app = createApp({ dataDir: dir, port: 0, host: "forge.test", modrinthFetch: (async () => (await slow, Response.json([]))) as unknown as typeof fetch }); | |
| 74 | 77 | const u = await createUser(app.db, { username: "ada", email: "[email protected]", password: "a-good-passphrase", origin: "seed", isAdmin: true, trusted: true }); |
| 75 | 78 | if (!u.ok) throw new Error(u.error); |
| 76 | 79 | ada = u.value; |
| @@ -134,6 +137,68 @@ test("help with no link says what there is and each step to link, with /forge an | ||
| 134 | 137 | expect(other!.text.split("\n")).toEqual(lines.slice(2)); |
| 135 | 138 | }); |
| 136 | 139 | |
| 140 | test("status is the forge's own read, as the linked account; servers names those it has a role on", async () => { | |
| 141 | const [status] = await send([request("status")]); | |
| 142 | expect(status!.text).toStartWith("The forge is up"); | |
| 143 | expect(status!.confirm).toBe(false); | |
| 144 | const [servers] = await send([request("Servers")]); | |
| 145 | expect(servers!.text).toBe("hub: running, 1 player"); | |
| 146 | expect(kinds(2)).toEqual(["read", "read"]); | |
| 147 | // Anything more than the one word is still a question or the crew's. | |
| 148 | expect((await send([request("status of the hub")]))[0]).toMatchObject({ confirm: true }); | |
| 149 | // Never in chat: a server's log may keep what it is told to show. | |
| 150 | gameChat(app, box, { hub: ["[12:00:01] [Async Chat Thread - #3/INFO]: <ada> !forge status"] }, COMPOSE, "http://forge.test", now); | |
| 151 | expect(kinds(1)).toEqual(["talk"]); | |
| 152 | app.db.query("DELETE FROM game_chat_job").run(); | |
| 153 | }); | |
| 154 | ||
| 155 | test("a linked account with no role reads the forge and nothing of the box", async () => { | |
| 156 | const bo = await createUser(app.db, { username: "bo", email: "[email protected]", password: "a-good-passphrase", origin: "seed", trusted: true }); | |
| 157 | if (!bo.ok) throw new Error(bo.error); | |
| 158 | const kit = { uuid: "00000000-0000-4000-8000-00000000000b", name: "bo_mc" }; | |
| 159 | app.db.query("INSERT INTO game_link (box_id, player, user_id, uuid, created_at) VALUES (?1, 'bo_mc', ?2, ?3, '')").run(box.id, bo.value.id, kit.uuid); | |
| 160 | const says = async (words: string) => (await send([request(words, kit)]))[0]!.text; | |
| 161 | expect(await says("status")).toStartWith("The forge is up"); | |
| 162 | const help = await says("help"); | |
| 163 | expect(help).toContain("/forge status"); | |
| 164 | const servers = await says("servers"); | |
| 165 | expect(servers).toBe("You have no role on a server here."); | |
| 166 | for (const text of [help, servers]) for (const word of ["mc", "ada", "survival", "/forge servers", "/forge yes"]) expect(text.replaceAll("bo_mc", "")).not.toContain(word); | |
| 167 | expect(await says("who is on")).toStartWith("bo has no role on hub."); | |
| 168 | // Suspended while the read waits: it is not told. | |
| 169 | gameAsk(app, box, [request("status", kit)], COMPOSE, "http://forge.test", now); | |
| 170 | app.db.query("UPDATE user SET suspended_at = ?2 WHERE id = ?1").run(bo.value.id, new Date().toISOString()); | |
| 171 | await runChat(app, box.id); | |
| 172 | expect(toldTo(app.db, box, now).map((t) => t.text)).toEqual(["Your account may no longer do that here."]); | |
| 173 | }); | |
| 174 | ||
| 175 | test("reads have their own limit: thirty a minute, and none is taken from the five commands", async () => { | |
| 176 | const read = async () => (await send([request("servers")]))[0]!.text; | |
| 177 | for (let i = 0; i < 30; i++) expect(await read()).toStartWith("hub: "); | |
| 178 | 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"); | |
| 180 | }); | |
| 181 | ||
| 182 | test("a read does not wait behind a plan", async () => { | |
| 183 | const add = (kind: string, words: string) => | |
| 184 | app.db | |
| 185 | .query("INSERT INTO game_chat_job (box_id, service, player, user_id, kind, words, origin, audit_id, created_at) VALUES (?1, 'hub', 'ada', ?2, ?3, ?4, '', 0, ?5)") | |
| 186 | .run(box.id, ada.id, kind, words, new Date().toISOString()); | |
| 187 | let release = () => {}; | |
| 188 | slow = new Promise((r) => (release = r)); | |
| 189 | add("plan", "a void world with FAWE"); | |
| 190 | gameAsk(app, box, [request("servers")], COMPOSE, "http://forge.test", now); | |
| 191 | const work = runChat(app, box.id); | |
| 192 | try { | |
| 193 | await pollUntil(() => app.db.query("SELECT 1 FROM game_chat_job WHERE kind = 'read'").get() === null, "the read's answer", 4_000); | |
| 194 | expect(toldTo(app.db, box, now).map((t) => t.text)).toEqual(["hub: running, 1 player"]); | |
| 195 | expect(app.db.query("SELECT kind FROM game_chat_job").all()).toEqual([{ kind: "plan" }]); | |
| 196 | } finally { | |
| 197 | release(); | |
| 198 | await work; | |
| 199 | } | |
| 200 | }); | |
| 201 | ||
| 137 | 202 | test("every request in a sync is answered, a repeated refusal too", async () => { |
| 138 | 203 | const asks = Array.from({ length: 4 }, () => request("help", { uuid: EVE, name: "eve" })); |
| 139 | 204 | expect((await send(asks)).map((a) => a.id)).toEqual(asks.map((a) => a.id)); |
new above
offline
Next: the box-wide read cap (60 a minute) means two busy accounts can starve everyone else's reads, which is a governor where the per-account cap already does the job. Consider removing it.