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

Games: instruct the crew from inside the game with !forge (link, plan, yes) #17317

opened this

Merged 24h 24m ago, live in production

sold/game-chat → main 0 commits 4 threads · 4 unresolved

  • Merged. sold/game-chat was merged into main as 284b30d.

Review

Sign in to review this change.
27 files changed +1556 −22
docs/features/games.md +18
@@ -65,6 +65,24 @@ Uploading a world file is still to come: a link is how a world comes in today.
6565
6666 Creating it is one commit to the network's compose file: the service from the Paper anchor with its own RCON key, a volume, the proxy's `[servers]` and `[forced-hosts]` lines, sleep's label and waker lists, and its lockfile beside it. Remove on the server's row, `d` on the terminal Games screen, or `remove_server` takes the service and its proxy lines back out by commit, its plan shown first, and keeps its world's volume (`src/games/presets.ts`). The proxy, the waker, and a server the proxy's `try` list or another forced host still names are refused.
6767
68 ## From in the game
69
70 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. 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.
71
72 A linked name that holds operator on the server it types on can say:
73
74 - `!forge give me a new void world with FAWE and bedwars`: planned like `create_server` (see New servers), and the plan's lines and memory math come back in chat, then "type !forge yes within 5 minutes". `!forge yes` commits that plan as the linked account, or says "The box changed since the preview; plan it again." when the repository moved; `!forge no` drops it. A plan answers only the same name on the same server. It changes the whole network, so it takes operator of the box, asked at the plan, at the yes and again right before the commit; operator of one server is refused.
75 - `!forge help`.
76 - `!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.
77
78 Anyone else gets a line saying how to link, and nothing runs. 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.
79
80 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.
81
82 How the forge hears chat: the agent reads each server's `logs/latest.log` and sends only new lines that carry `!forge`. Only the server's own chat line counts: Paper's `[Async Chat Thread - #N/INFO]: <Name> …` and Fabric's `[Server thread/INFO] (Minecraft) <Name> …` (or vanilla's `[Server thread/INFO]: <Name> …`). `/say` (`[Name] …`), `/me` (`* Name …`), tellraw (not logged) and a plugin's broadcast (logged on the server thread or under the plugin's name) do not match.
83
84 A name in chat is trusted only because players reach the backends through Velocity in online mode with modern forwarding, so the proxy has checked the name with Mojang. A box whose compose publishes any port on a service other than the proxy (or runs one with `network_mode: host`) takes no `!forge` at all: a player connecting to that backend directly could use any name. On Fabric, a mod that broadcasts lines in vanilla's chat format (some chat bridges do) can speak as any name; on such a server, link no one who operates it. Each later command runs only while the server lists that name with the bound UUID. The name not listed (not on, or the list not read yet): refused, the link kept. The name listed with another UUID (someone else holds the name now): refused, and the link is dropped, so a name given up cannot speak for the account. A link made before UUIDs were bound has none and goes the same way: link it again.
85
6886 ## Secrets
6987
7088 The Velocity forwarding secret (`forwarding.env`) and an RCON password a service (`rcon-<service>.env`) are generated once, sealed like every forge secret and sent only in the sync's `env`, never committed. A box token is shown once and stored hashed. An uploaded jar is kept by the forge at `/games/jar/<id>/<name>`; the compose a box gets carries it signed for 6 hours, and only for the box that uploaded it. A jar must be a `.jar` (a zip), at most 64 MiB, and a box keeps at most 20 jars and 256 MiB.
src/core/account_purge.ts +2
@@ -52,6 +52,8 @@ export const COVERED: Readonly<Record<string, Coverage>> = {
5252 "access_link.created_by": FORMER,
5353 // Who asked a game box to run a command: the record keeps it, as the former account.
5454 "game_command.by": FORMER,
55 // The !forge audit keeps what was said and what came of it; who said it becomes a former member.
56 "game_chat.user_id": FORMER,
5557 "account_ceiling.set_by": FORMER,
5658 "allocation_entry.actor_id": FORMER,
5759 "allocation_weekly.set_by": FORMER,
src/core/empty_words.ts +1
@@ -135,6 +135,7 @@ export const NOTE_WORDS = {
135135 noFlowLinesMatch: "No flow lines match.",
136136 noModpackMatches: "No modpack matches that.",
137137 nothingOnModrinthMatches: "Nothing on Modrinth matches that.",
138 nobodyLinkedHere: "Nobody linked yet: a name is linked with a code from the account page.",
138139 notSignedInOnAnyBrowser: "Not signed in on any browser.",
139140 noAccessCodesYet: "No access codes yet. Mint one when a script, a CI job, or another machine needs to act as you.",
140141 noComputerKeysYet: "No computer keys yet. Add one and git over SSH stops asking for a password.",
src/core/migration-pins/20261202010000-game-chat.pin added +1
@@ -0,0 +1,1 @@
1 ab0e6f925b7a124c1400b53bed8d9e46e266725449b86f4fa49ffdde1a8b36cd
src/core/migration-pins/20261202172500-game-chat-plan-sha.pin added +1
@@ -0,0 +1,1 @@
1 d4c5a4c8d1f98b1a1d0677ba10e8e676725c94e8c5994bb4dd011b710b9f4ef6
src/core/migration-pins/20261202174500-game-chat-jobs.pin added +1
@@ -0,0 +1,1 @@
1 a89a2abdc3a42eee30efb0745c60cd9524ee3764104c3e0eed50cb459d26448e
src/core/migrations/20261202010000-game-chat.ts added +41
@@ -0,0 +1,41 @@
1 // Commands from in the game (#17284, "!forge" in chat): a forge account linked to a player's name on a
2 // box (by a one-time code the player types in game), the codes themselves (hashed, ten minutes), the
3 // plan a player was shown and may answer "yes" to (five minutes), and every command and its outcome,
4 // kept for the audit and the rate limit.
5 export default `
6 CREATE TABLE IF NOT EXISTS game_link (
7 box_id TEXT NOT NULL,
8 player TEXT NOT NULL,
9 user_id TEXT NOT NULL REFERENCES user(id) ON DELETE CASCADE,
10 created_at TEXT NOT NULL,
11 PRIMARY KEY (box_id, player)
12 );
13 CREATE INDEX IF NOT EXISTS game_link_user ON game_link (user_id);
14 CREATE TABLE IF NOT EXISTS game_link_code (
15 code_hash TEXT PRIMARY KEY,
16 user_id TEXT NOT NULL REFERENCES user(id) ON DELETE CASCADE,
17 expires_at TEXT NOT NULL
18 );
19 CREATE TABLE IF NOT EXISTS game_chat_pending (
20 box_id TEXT NOT NULL,
21 player TEXT NOT NULL,
22 service TEXT NOT NULL,
23 user_id TEXT NOT NULL REFERENCES user(id) ON DELETE CASCADE,
24 words TEXT NOT NULL,
25 created_at TEXT NOT NULL,
26 PRIMARY KEY (box_id, player)
27 );
28 CREATE TABLE IF NOT EXISTS game_chat (
29 id INTEGER PRIMARY KEY,
30 box_id TEXT NOT NULL,
31 service TEXT NOT NULL,
32 player TEXT NOT NULL,
33 user_id TEXT NOT NULL DEFAULT '',
34 kind TEXT NOT NULL,
35 words TEXT NOT NULL,
36 outcome TEXT NOT NULL,
37 at TEXT NOT NULL
38 );
39 CREATE INDEX IF NOT EXISTS game_chat_user ON game_chat (user_id, at);
40 CREATE INDEX IF NOT EXISTS game_chat_player ON game_chat (box_id, player, at);
41 `;
src/core/migrations/20261202172500-game-chat-plan-sha.ts added +6
@@ -0,0 +1,6 @@
1 // The commit a plan shown in game was made on (#17284): `!forge yes` builds on that commit or says
2 // the box changed. Additive: one column; a plan waiting from before it has none and is asked for
3 // again.
4 export default `
5 ALTER TABLE game_chat_pending ADD COLUMN sha TEXT NOT NULL DEFAULT '';
6 `;
src/core/migrations/20261202174500-game-chat-jobs.ts added +25
@@ -0,0 +1,25 @@
1 // What a !forge command still has to do (#17284): a plan, a commit, a message to the crew or its
2 // answer, kept until done so a restart loses none and runs none twice; and the last batch of chat
3 // each box sent, which its agent repeats until a sync is answered.
4 export default `
5 CREATE TABLE IF NOT EXISTS game_chat_job (
6 id INTEGER PRIMARY KEY AUTOINCREMENT,
7 box_id TEXT NOT NULL,
8 service TEXT NOT NULL,
9 player TEXT NOT NULL,
10 user_id TEXT NOT NULL REFERENCES user(id) ON DELETE CASCADE,
11 kind TEXT NOT NULL,
12 words TEXT NOT NULL,
13 sha TEXT NOT NULL DEFAULT '',
14 name TEXT NOT NULL DEFAULT '',
15 conversation TEXT NOT NULL DEFAULT '',
16 origin TEXT NOT NULL DEFAULT '',
17 audit_id INTEGER NOT NULL,
18 created_at TEXT NOT NULL
19 );
20 CREATE INDEX IF NOT EXISTS game_chat_job_box ON game_chat_job (box_id, id);
21 CREATE TABLE IF NOT EXISTS game_chat_batch (
22 box_id TEXT PRIMARY KEY,
23 id TEXT NOT NULL
24 );
25 `;
src/core/settings.ts +12
@@ -27,6 +27,18 @@ export function getUserSetting(
2727 return row?.value;
2828 }
2929
30 /** Several of a person's settings in one statement, by key; an unset one is absent. */
31 export const getUserSettings = (db: Database, userId: string, keys: readonly string[]): ReadonlyMap<string, string> =>
32 new Map(
33 db
34 .query<
35 { key: string; value: string },
36 [string, string]
37 >("SELECT key, value FROM user_setting WHERE user_id = ?1 AND key IN (SELECT value FROM json_each(?2))")
38 .all(userId, JSON.stringify(keys))
39 .map((r) => [r.key, r.value]),
40 );
41
3042 export function setUserSetting(
3143 db: Database,
3244 userId: string,
src/crew/focus.ts +8 −5
@@ -12,7 +12,7 @@ import type { Database } from "bun:sqlite";
1212 import { getUserSetting, setUserSetting } from "../core/settings.ts";
1313 import { err, ok, type Result } from "../kernel/result.ts";
1414
15 const KEY = "focus_until";
15 export const FOCUS_KEY = "focus_until";
1616 const HOUR_MS = 3_600_000;
1717 /** The furthest ahead a focus may be set: a week. */
1818 export const FOCUS_MAX_MS = 7 * 24 * HOUR_MS;
@@ -33,8 +33,11 @@ function tomorrow(now: number): number {
3333 }
3434
3535 /** When the focus ends, or null when none is set or it has lapsed. */
36 export function focusUntil(db: Database, userId: string, now = Date.now()): string | null {
37 const at = getUserSetting(db, userId, KEY);
36 export const focusUntil = (db: Database, userId: string, now = Date.now()): string | null =>
37 liveFocus(getUserSetting(db, userId, FOCUS_KEY), now);
38
39 /** A stored focus value, or null when it is unset or has lapsed. */
40 export function liveFocus(at: string | undefined, now = Date.now()): string | null {
3841 if (at === undefined || at === "") return null;
3942 const ms = Date.parse(at);
4043 return Number.isFinite(ms) && ms > now ? at : null;
@@ -65,8 +68,8 @@ export function parseFocus(raw: string, now = Date.now()): Result<string | null,
6568 export function setFocus(db: Database, userId: string, raw: string, now = Date.now()): Result<string | null, FocusError> {
6669 const parsed = parseFocus(raw, now);
6770 if (!parsed.ok) return parsed;
68 if (parsed.value === null) db.query("DELETE FROM user_setting WHERE user_id = ?1 AND key = ?2").run(userId, KEY);
69 else setUserSetting(db, userId, KEY, parsed.value);
71 if (parsed.value === null) db.query("DELETE FROM user_setting WHERE user_id = ?1 AND key = ?2").run(userId, FOCUS_KEY);
72 else setUserSetting(db, userId, FOCUS_KEY, parsed.value);
7073 return parsed;
7174 }
7275
src/crew/notify.ts +5 −5
@@ -55,7 +55,7 @@ import { askLinesFor } from "../web/studio/asks.ts";
5555 import { inFocus } from "./focus.ts";
5656 import { during } from "../perf/jobs.ts";
5757
58 const KEY = "notify_url";
58 export const NOTIFY_KEY = "notify_url";
5959 export const MAX_URL = 200;
6060 const HOURLY = 10;
6161 const HOUR_MS = 3_600_000;
@@ -129,7 +129,7 @@ export const NOTIFY_ERRORS: Record<NotifyUrlError, string> = {
129129 };
130130
131131 export const notifyUrlOf = (db: Database, userId: string): string | undefined =>
132 getUserSetting(db, userId, KEY) || undefined;
132 getUserSetting(db, userId, NOTIFY_KEY) || undefined;
133133
134134 /** Save a validated URL; an empty string clears it. */
135135 export function setNotifyUrl(
@@ -140,13 +140,13 @@ export function setNotifyUrl(
140140 if (raw.trim() === "") {
141141 db.query("DELETE FROM user_setting WHERE user_id = ?1 AND key = ?2").run(
142142 userId,
143 KEY,
143 NOTIFY_KEY,
144144 );
145145 return ok("cleared");
146146 }
147147 const parsed = parseNotifyUrl(raw);
148148 if (!parsed.ok) return parsed;
149 setUserSetting(db, userId, KEY, parsed.value);
149 setUserSetting(db, userId, NOTIFY_KEY, parsed.value);
150150 return ok("set");
151151 }
152152
@@ -404,7 +404,7 @@ export function startNotifier(app: App, options: NotifyOptions): Notifier {
404404 { user_id: string },
405405 [string]
406406 >("SELECT user_id FROM user_setting WHERE key = ?1 AND value <> ''")
407 .all(KEY)
407 .all(NOTIFY_KEY)
408408 .map((r) => r.user_id);
409409
410410 const drainStart = (): number | null =>
src/games/agent.sh +36 −1
@@ -415,6 +415,38 @@ people() {
415415 cat "$DIR/.people.json"
416416 }
417417
418 # ---- !forge (games/chat.ts): the chat lines that carry a !forge command, from each game server's
419 # logs/latest.log, whose lines name the thread that logged them (the console's do not). Only those
420 # lines leave the box. The first read only marks where the log is: nothing said before is replayed.
421 chat() {
422 local out='{}' name last got total lines marks=''
423 mkdir -p "$DIR/.chat"
424 # A batch the forge has not answered goes again, whole, under its own id: the forge skips one it has.
425 if [ -s "$DIR/.chat.out" ]; then
426 cat "$DIR/.chat.out"
427 return
428 fi
429 while IFS= read -r name; do
430 [[ "$name" =~ $SAFE ]] || continue
431 last="$(cat "$DIR/.chat/$name" 2>/dev/null || echo -1)"
432 # shellcheck disable=SC2016 # the script runs in the container's own shell, $1 its argument
433 got="$(capped 5 "${COMPOSE[@]}" exec -T "$name" sh -c 'f=logs/latest.log; [ -f "$f" ] || exit 3; t=$(wc -l < "$f"); echo "$t"; s=$1; [ "$s" -lt 0 ] && exit 0; [ "$t" -lt "$s" ] && s=0; tail -n "+$((s + 1))" "$f" | head -n "$((t - s))" | grep -F "!forge" | tail -n 20' sh "$last" 2>/dev/null)" || continue
434 total="$(head -n 1 <<<"$got")"
435 [[ "$total" =~ ^[0-9]+$ ]] || continue
436 marks+="$name $total"$'\n'
437 lines="$(tail -n +2 <<<"$got")"
438 [ -n "$lines" ] && out="$(jq -c --arg n "$name" --arg l "${lines:0:8000}" '. + {($n): ($l | split("\n") | map(select(. != "")))}' <<<"$out")"
439 done < <(capped 5 "${COMPOSE[@]}" ps --status running --format '{{.Service}}' 2>/dev/null)
440 # The batch is on disk before its lines count as read.
441 if [ "$out" != '{}' ]; then
442 jq -cn --arg id "$(date +%s)-$RANDOM$RANDOM" --argjson lines "$out" '{id: $id, lines: $lines}' >"$DIR/.chat.tmp" && mv "$DIR/.chat.tmp" "$DIR/.chat.out" || return
443 cat "$DIR/.chat.out"
444 fi
445 while read -r name total; do
446 [ -n "$name" ] && printf '%s' "$total" >"$DIR/.chat/$name"
447 done <<<"$marks"
448 }
449
418450 host() {
419451 local total avail load disk
420452 total="$(awk '/^MemTotal:/ {print int($2/1024)}' /proc/meminfo 2>/dev/null || echo 0)"
@@ -868,6 +900,7 @@ sync() {
868900 people | json_or '{}' >"$DIR/.sync.people"
869901 metrics | json_or '{}' >"$DIR/.sync.metrics"
870902 jq -c 'if type == "object" then . else {} end' "$WORLDS/snapshots.json" 2>/dev/null | json_or '{}' >"$DIR/.sync.snapshots"
903 chat | json_or '{}' >"$DIR/.sync.chat"
871904 # Every string as plain text: real servers print colour escapes and control bytes (itzg's logs,
872905 # rcon-cli's colours), and the forge takes none of them. Colours go first as Minecraft's own
873906 # printable section codes (\u00a7: the sixteen colours, l bold, n underline, r every reset), which
@@ -882,6 +915,7 @@ sync() {
882915 --slurpfile people "$DIR/.sync.people" \
883916 --slurpfile metrics "$DIR/.sync.metrics" \
884917 --slurpfile snapshots "$DIR/.sync.snapshots" \
918 --slurpfile chat "$DIR/.sync.chat" \
885919 'def sect: {"0":"r","1":"l","4":"n","22":"r","24":"r","39":"r","30":"0","31":"4","32":"2","33":"6","34":"1","35":"5","36":"3","37":"7","90":"8","91":"c","92":"a","93":"e","94":"9","95":"d","96":"b","97":"f"} as $t
886920 | ["30","31","32","33","34","35","36","37","90","91","92","93","94","95","96","97"] as $sixteen
887921 # 38;5;n is one of the sixteen colours by its number; a background (48) and the other
@@ -892,11 +926,12 @@ sync() {
892926 else [.[0]] + (.[1:] | codes) end;
893927 (if . == "" then ["0"] else split(";") end) | [codes[] | $t[.] // empty | "\u00a7" + .] | join("");
894928 def plain: gsub("\u001b\\[(?<p>[0-9;]*)m"; (.p // "" | sect)) | gsub("^(\u00a7r)+|(\u00a7r)+$"; "") | gsub("(\u00a7r)+"; "\u00a7r") | gsub("\u001b\\[[0-9;?]*[ -/]*[@-~]"; "") | gsub("\u001b[@-_]?"; "") | gsub("[\u0001-\u0008\u000b\u000c\u000e-\u001f\u007f]"; "");
895 {agent: 1, composeSha: $sha, services: $services[0], logs: $logs[0], results: $results[0], host: $host[0], diag: $diag[0], people: $people[0], metrics: $metrics[0], snapshots: $snapshots[0]}
929 {agent: 1, composeSha: $sha, services: $services[0], logs: $logs[0], results: $results[0], host: $host[0], diag: $diag[0], people: $people[0], metrics: $metrics[0], snapshots: $snapshots[0], chat: $chat[0].lines, chatId: $chat[0].id}
896930 | walk(if type == "string" then plain else . end)' >"$DIR/.sync.body" || return 1
897931 answer="$(curl -fsS -m 20 -H "@$AUTH" -H 'content-type: application/json' --data-binary "@$DIR/.sync.body" "${FORGE_URL%/}/api/v1/games/agent/sync")" || return 1
898932 # Delivered: the results and the log lines are the forge's now.
899933 echo '[]' >"$DIR/.results"
934 : >"$DIR/.chat.out"
900935 since="$next"
901936 # A newer agent first: nothing of this answer is applied by a script the forge has replaced.
902937 self_update "$(jq -r '.agentSha // ""' <<<"$answer")"
src/games/chat.ts added +574
@@ -0,0 +1,574 @@
1 /**
2 * Commands from in the game (#17284): a player types `!forge give me a new void world with FAWE and
3 * bedwars` in chat, and the forge plans it, says the plan back in game, and builds it on `!forge yes`;
4 * anything else goes to the crew as a Talk message whose answer comes back in game.
5 *
6 * Who may: a player whose name on this box is linked to a forge account (`!forge link <code>`, the
7 * code from the forge, one use, ten minutes) and whose account is an operator of the server they
8 * type on. The link binds the player's UUID as the server itself lists it (`list uuids`, kept by
9 * People as who is online), never anything typed in chat: a later command runs only while that name
10 * is online with that UUID. Another player with the name drops the link; the name not online keeps
11 * it. A name in chat is only trusted because the backends are reached only through the proxy
12 * (online mode, modern forwarding): a box whose compose publishes any backend port runs no command
13 * at all.
14 *
15 * What counts as said: only the server's own chat log line, read from logs/latest.log where the
16 * thread is named: Paper's "[Async Chat Thread - #N/INFO]: <Name> …", Fabric's "[Server
17 * thread/INFO] (Minecraft) <Name> …" (or the vanilla "[Server thread/INFO]: <Name> …"). A plugin's
18 * broadcast (Paper logs those on the server thread, or under the plugin's name), /say ("[Name] …"),
19 * /me ("* Name …") and tellraw (never logged) do not match. Every command and its outcome is kept
20 * (`game_chat`) and counted: at most five a minute and thirty an hour an account; a refusal is kept
21 * and answered once a minute a name. A new server takes operator of the box, not of one server.
22 */
23
24 import type { App } from "../app.ts";
25 import { talk } from "../actions/talk.ts";
26 import { createConversation, listTurns } from "../core/conversations.ts";
27 import { getUserById, isActive, type User } from "../core/users.ts";
28 import { sha256 } from "../kernel/hash.ts";
29 import { composeServices, readCompose, serviceEnv } from "./compose.ts";
30 import { commitServer, planServer, wishOn } from "./presets.ts";
31 import { peopleOf } from "./people.ts";
32 import { proxyOf } from "./sleep.ts";
33 import { listBoxes, mayDo, queueCommand, roleOn, SERVICE_NAME, type GameBox } from "./store.ts";
34
35 export const CODE_MS = 10 * 60_000;
36 export const PENDING_MS = 5 * 60_000;
37 export const PER_MINUTE = 5;
38 export const PER_HOUR = 30;
39 const FAILED_LINKS = 5;
40 const NAME = "[.]?[A-Za-z0-9_]{1,16}";
41 const LINES_OUT = 6;
42 const CODE_CHARS = "23456789ABCDEFGHJKMNPQRSTUVWXYZ";
43
44 /**
45 * A chat line the server itself logged, by loader: the thread that logs chat, then
46 * `<Name> !forge …`.
47 */
48 const CHAT: Record<"paper" | "fabric", RegExp> = {
49 paper: new RegExp(
50 `^\\[\\d\\d:\\d\\d:\\d\\d\\] \\[Async Chat Thread - #\\d+/INFO\\]: (?:\\[Not Secure\\] )?<(${NAME})> !forge(?: (.*))?$`,
51 ),
52 fabric: new RegExp(
53 `^\\[\\d\\d:\\d\\d:\\d\\d\\] \\[Server thread/INFO\\](?::| \\(Minecraft\\)) (?:\\[Not Secure\\] )?<(${NAME})> !forge(?: (.*))?$`,
54 ),
55 };
56
57 /**
58 * Which chat format a service logs: Paper and its kin, or Fabric; anything else takes no commands.
59 */
60 function loaderOf(compose: string, service: string): "paper" | "fabric" | undefined {
61 const type = (serviceEnv(compose, service)["TYPE"] ?? "").toUpperCase();
62 if (["PAPER", "PURPUR", "FOLIA", "SPIGOT", "BUKKIT"].includes(type)) return "paper";
63 if (["FABRIC", "QUILT"].includes(type)) return "fabric";
64 return undefined;
65 }
66
67 /**
68 * One `!forge` command out of a log line, or nothing when the line is not the server's own chat.
69 */
70 export function chatCommand(line: string, loader: "paper" | "fabric"): { player: string; words: string } | undefined {
71 const m = CHAT[loader].exec(line.replace(/\r$/, ""));
72 return m === null ? undefined : { player: m[1]!, words: (m[2] ?? "").trim().slice(0, 300) };
73 }
74
75 /**
76 * Why a box takes no commands from chat: a backend reachable without the proxy, which could carry
77 * any name.
78 */
79 export function exposedBackend(compose: string): string | undefined {
80 const proxy = proxyOf(compose);
81 if (proxy === undefined) return "it has no proxy (itzg/mc-proxy) in front of its servers";
82 try {
83 const doc = Bun.YAML.parse(compose) as { services?: Record<string, { ports?: unknown; network_mode?: unknown }> } | null;
84 const open = Object.entries(doc?.services ?? {}).find(
85 ([name, s]) => name !== proxy && ((Array.isArray(s.ports) && s.ports.length > 0) || s.network_mode === "host"),
86 );
87 return open === undefined ? undefined : `${open[0]} is reachable without the proxy, so a name in its chat cannot be trusted`;
88 } catch {
89 return "its compose file does not read";
90 }
91 }
92
93 /** A new one-time link code for `user`: what they type in game as `!forge link <code>`. */
94 export function newLinkCode(app: App, user: User, now = Date.now()): string {
95 const bytes = crypto.getRandomValues(new Uint8Array(6));
96 const code = [...bytes].map((b) => CODE_CHARS[b % CODE_CHARS.length]).join("");
97 app.db.query("DELETE FROM game_link_code WHERE user_id = ?1 OR expires_at < ?2").run(user.id, new Date(now).toISOString());
98 app.db
99 .query("INSERT INTO game_link_code (code_hash, user_id, expires_at) VALUES (?1, ?2, ?3)")
100 .run(sha256(code), user.id, new Date(now + CODE_MS).toISOString());
101 return code;
102 }
103
104 /**
105 * The UUID the server itself gives `player` on `service` (its `list uuids` answer, as People keeps
106 * who is online), or "" when the name is not listed there with one.
107 */
108 export const onlineUuid = (app: App, boxId: string, service: string, player: string): string =>
109 peopleOf(app.db, boxId, service).online.find((p) => p.name === player)?.uuid ?? "";
110
111 /** The player names linked to `userId`, on every box, each with the UUID it is bound to. */
112 export const linksOf = (app: App, userId: string): { boxId: string; player: string; uuid: string; createdAt: string }[] =>
113 app.db
114 .query<
115 { boxId: string; player: string; uuid: string; createdAt: string },
116 [string]
117 >("SELECT box_id AS boxId, player, uuid, created_at AS createdAt FROM game_link WHERE user_id = ?1 ORDER BY created_at")
118 .all(userId);
119
120 /**
121 * The account page's links in one statement, each with its box's name; undefined for a person who
122 * holds none and sees no game box (as `seesBox` says), so the page has nothing to offer them.
123 */
124 export function accountLinks(app: App, user: User): { boxId: string; box: string | null; player: string; uuid: string; createdAt: string }[] | undefined {
125 const rows = app.db
126 .query<
127 { boxId: string; box: string | null; player: string | null; uuid: string; createdAt: string },
128 [string, number]
129 >(
130 `SELECT l.box_id AS boxId, b.name AS box, l.player, l.uuid, l.created_at AS createdAt
131 FROM (SELECT 1) LEFT JOIN game_link l ON l.user_id = ?1 LEFT JOIN game_box b ON b.id = l.box_id
132 WHERE l.player IS NOT NULL
133 OR EXISTS (SELECT 1 FROM game_box g WHERE ?2 = 1 OR EXISTS (SELECT 1 FROM game_grant a WHERE a.box_id = g.id AND a.user_id = ?1))
134 ORDER BY l.created_at`,
135 )
136 .all(user.id, user.isAdmin ? 1 : 0);
137 return rows.length === 0 ? undefined : rows.flatMap((r) => (r.player === null ? [] : [{ ...r, player: r.player }]));
138 }
139
140 /** Who is linked on a box: the player name, the forge account, since when. */
141 export const playersOn = (app: App, boxId: string): { player: string; username: string; createdAt: string }[] =>
142 app.db
143 .query<
144 { player: string; username: string; createdAt: string },
145 [string]
146 >("SELECT l.player, u.username, l.created_at AS createdAt FROM game_link l JOIN user u ON u.id = l.user_id WHERE l.box_id = ?1 ORDER BY l.player")
147 .all(boxId);
148
149 /** Forget one of a person's linked names, kept in the audit as theirs. */
150 export function unlink(app: App, userId: string, boxId: string, player: string): void {
151 const gone = app.db.query("DELETE FROM game_link WHERE user_id = ?1 AND box_id = ?2 AND player = ?3").run(userId, boxId, player);
152 if (gone.changes > 0)
153 app.db
154 .query("INSERT INTO game_chat (box_id, service, player, user_id, kind, words, outcome, at) VALUES (?1, '', ?2, ?3, 'unlink', '', 'unlinked on the forge', ?4)")
155 .run(boxId, player, userId, new Date().toISOString());
156 }
157
158 /** The latest commands said in a box's chat, newest first: who, what, and what came of it. */
159 export const chatLog = (
160 app: App,
161 boxId: string,
162 limit = 20,
163 ): { service: string; player: string; kind: string; words: string; outcome: string; at: string }[] =>
164 app.db
165 .query<
166 { service: string; player: string; kind: string; words: string; outcome: string; at: string },
167 [string, number]
168 >("SELECT service, player, kind, words, outcome, at FROM game_chat WHERE box_id = ?1 ORDER BY id DESC LIMIT ?2")
169 .all(boxId, limit);
170
171 /** Words to a player in game: tellraw on the server they typed on, a line each, bounded. */
172 function tell(app: App, box: GameBox, service: string, player: string, lines: readonly string[], by: string, color = "gray"): void {
173 for (const line of lines.slice(0, LINES_OUT))
174 queueCommand(app.db, box.id, service, "tell", `tellraw ${player} ${JSON.stringify({ text: line.slice(0, 200), color })}`, by);
175 }
176
177 const audit = (
178 app: App,
179 box: GameBox,
180 service: string,
181 player: string,
182 userId: string,
183 kind: string,
184 words: string,
185 outcome: string,
186 now: number,
187 ): void => {
188 app.db
189 .query("INSERT INTO game_chat (box_id, service, player, user_id, kind, words, outcome, at) VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7, ?8)")
190 .run(box.id, service, player, userId, kind, words.slice(0, 300), outcome.slice(0, 300), new Date(now).toISOString());
191 };
192
193 /** Words that ask for a new server: a level, a plugin we know, or the word itself. */
194 const asksForServer = (words: string): boolean => /\b(void|flat|superflat|skyblock|world|server|fawe|worldedit|bedwars)\b/i.test(words);
195
196 /**
197 * One player's part of a sync: past this many commands the rest of their lines are not read, so one
198 * player cannot crowd out another; and so many for the whole sync.
199 */
200 const A_SYNC_EACH = 3;
201 const A_SYNC = 20;
202 /** A refusal is answered, and kept, at most once in this long for a name on a box. */
203 const REFUSE_MS = 60_000;
204 /** How long a crew's answer is waited for after a restart lost sight of its turn. */
205 const REPLY_MS = 30 * 60_000;
206
207 /**
208 * The `!forge` commands in a sync's chat lines, each checked here, in one transaction with nothing
209 * awaited: what needs a plan, a commit or the crew is kept as a job (`game_chat_job`) for
210 * `runChat`. `sent` is the agent's `chat` ({service: [lines]}); `batch` its id: the agent sends
211 * a batch until a sync is answered, so one seen before is skipped whole.
212 */
213 export function gameChat(
214 app: App,
215 box: GameBox,
outdated

MEDIUM: await one(...) runs plan/commit (Modrinth, git) inside the agent sync. Cap commands per sync and run the slow work off the sync response.

216 sent: unknown,
217 compose: string | undefined,
218 origin: string,
219 now = Date.now(),
220 batch: unknown = undefined,
221 ): void {
222 if (compose === undefined || sent === null || typeof sent !== "object") return;
223 const db = app.db;
224 db.transaction(() => {
225 const id = typeof batch === "string" ? batch.slice(0, 64) : "";
226 if (id !== "") {
227 if (db.query("SELECT 1 FROM game_chat_batch WHERE box_id = ?1 AND id = ?2").get(box.id, id) !== null) return;
228 db.query("INSERT OR REPLACE INTO game_chat_batch (box_id, id) VALUES (?1, ?2)").run(box.id, id);
229 }
230 const ran = new Map<string, number>();
231 let all = 0;
232 for (const [service, lines] of Object.entries(sent as Record<string, unknown>).slice(0, 32)) {
233 if (!SERVICE_NAME.test(service) || !Array.isArray(lines)) continue;
234 const loader = loaderOf(compose, service);
235 if (loader === undefined) continue;
236 for (const line of lines.slice(0, 20)) {
237 const said = typeof line === "string" ? chatCommand(line, loader) : undefined;
238 const n = said === undefined ? 0 : (ran.get(said.player) ?? 0);
239 if (said === undefined || n >= A_SYNC_EACH || all >= A_SYNC) continue;
240 ran.set(said.player, n + 1);
241 all++;
242 one(app, box, service, said.player, said.words, compose, origin, now);
243 }
244 }
245 })();
246 }
247
248 function one(
249 app: App,
250 box: GameBox,
251 service: string,
252 player: string,
253 words: string,
254 compose: string,
255 origin: string,
256 now: number,
257 ): void {
258 const db = app.db;
259 // A link code is never kept in clear, typed right or wrong.
260 const shown = /^link\b/i.test(words) ? "link ****" : words;
261 // A refusal is kept and answered once a minute for this name (for a whole box that is off, whose
262 // names mean nothing), however often it is typed: spam costs a read, not a row and a tellraw.
263 const refuse = (by: string, outcome: string, line: string, color = "red", whole = false): void => {
264 const last = db
265 .query(
266 `SELECT 1 FROM game_chat WHERE box_id = ?1 AND (?2 = '' OR player = ?2) AND kind = 'refused' AND at > ?3 AND at <= ?4 LIMIT 1`,
267 )
268 .get(box.id, whole ? "" : player, new Date(now - REFUSE_MS).toISOString(), new Date(now).toISOString());
269 if (last !== null) return;
270 audit(app, box, service, player, by, "refused", shown, outcome, now);
271 tell(app, box, service, player, [line], by, color);
272 };
273 const exposed = exposedBackend(compose);
274 if (exposed !== undefined) return refuse("", `off: ${exposed}`, `!forge is off on this network: ${exposed}.`, "red", true);
275 // Linking: the code from the forge, once, within ten minutes; five wrong codes an hour a name.
276 const link = /^link\s+([A-Za-z0-9]{6})$/i.exec(words);
277 if (link !== null) {
278 const failed = db
279 .query<
280 { n: number },
281 [string, string, string]
282 >("SELECT COUNT(*) AS n FROM game_chat WHERE box_id = ?1 AND player = ?2 AND kind = 'link' AND outcome = 'wrong code' AND at > ?3")
283 .get(box.id, player, new Date(now - 3_600_000).toISOString())!.n;
284 if (failed >= FAILED_LINKS) return refuse("", "too many wrong codes", "Too many wrong codes for this name: try again in an hour.");
285 const code = db
286 .query<{ user_id: string }, [string, string]>("SELECT user_id FROM game_link_code WHERE code_hash = ?1 AND expires_at > ?2")
287 .get(sha256(link[1]!.toUpperCase()), new Date(now).toISOString());
288 if (code === null) {
289 audit(app, box, service, player, "", "link", "link ****", "wrong code", now);
290 return tell(app, box, service, player, ["That code is not one the forge gave, or it ran out: get a new one in your forge settings."], "", "red");
291 }
292 // The UUID the server lists for this name now; not listed, the code stays good for another try.
293 const uuid = onlineUuid(app, box.id, service, player);
294 if (uuid === "") return refuse(code.user_id, "not seen online", `The forge does not see ${player} on ${service} yet: stay on and type it again in a minute.`);
295 db.query("DELETE FROM game_link_code WHERE code_hash = ?1").run(sha256(link[1]!.toUpperCase()));
296 db.query("INSERT OR REPLACE INTO game_link (box_id, player, user_id, uuid, created_at) VALUES (?1, ?2, ?3, ?4, ?5)").run(
297 box.id,
298 player,
299 code.user_id,
300 uuid,
301 new Date(now).toISOString(),
302 );
303 const who = getUserById(db, code.user_id);
304 audit(app, box, service, player, code.user_id, "link", "link ****", "linked", now);
305 return tell(
306 app,
307 box,
308 service,
309 player,
310 [`Linked to ${who?.username ?? "your forge account"}. Type !forge help to see what you can ask.`],
311 code.user_id,
312 "green",
313 );
314 }
outdated

HIGH: service-scoped role gates a network-wide commit. Use roleOn(db, user, box.id) like the page and the MCP tool, so a one-service operator cannot create servers from chat. Add a test.

315 const linked = db
316 .query<{ user_id: string; uuid: string }, [string, string]>("SELECT user_id, uuid FROM game_link WHERE box_id = ?1 AND player = ?2")
317 .get(box.id, player);
318 const user = linked === null ? undefined : getUserById(db, linked.user_id);
319 // The link is a credential like any other: a suspended or removed account's says nothing.
320 if (user !== undefined && !isActive(user)) return refuse(user.id, "account not active", "The forge account this name is linked to cannot act now.");
321 if (linked !== null && user !== undefined) {
322 // The name is only the account's while it is the same player: the UUID the server lists for it
outdated

MEDIUM: refused lines do not count, so unlinked or refused players are unlimited; each costs a game_chat row and a tellraw. Rate limit by (box, player) as well, and cap replies to refusals.

323 // now.
324 const uuid = onlineUuid(app, box.id, service, player);
325 if (uuid === "") return refuse(user.id, "not seen online", `The forge does not see ${player} on ${service} yet: try again in a minute.`);
326 if (uuid !== linked.uuid) {
327 db.query("DELETE FROM game_link WHERE box_id = ?1 AND player = ?2").run(box.id, player);
328 audit(app, box, service, player, user.id, "refused", shown, "another player has the name: link dropped", now);
329 return tell(app, box, service, player, [`${player} was linked as another player, so that link is gone: link again with a new code.`], "", "red");
330 }
331 }
332 if (user === undefined)
333 return refuse("", "not linked", "Link your name first: get a code under Minecraft in your forge settings, then type !forge link <code>.", "gray");
334 if (!mayDo(roleOn(db, user, box.id, service), "operator")) return refuse(user.id, "not an operator", `${user.username} is not an operator of ${service}.`);
335 // The commands that ran (not the refusals) in the last minute and hour; full means wait until the
336 // oldest of them leaves the window.
337 const full = ([ms, most]: readonly [number, number]): number | undefined => {
338 const ran = db
339 .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")
340 .all(user.id, new Date(now - ms).toISOString());
341 return ran.length < most ? undefined : Date.parse(ran[ran.length - most]!.at) + ms;
342 };
343 const until = Math.max(full([60_000, PER_MINUTE]) ?? 0, full([3_600_000, PER_HOUR]) ?? 0);
344 if (until > now) {
345 const secs = Math.ceil((until - now) / 1000);
346 const again = secs < 120 ? `${secs} seconds` : `${Math.ceil(secs / 60)} minutes`;
347 return refuse(user.id, "rate limited", `At most ${PER_MINUTE} commands a minute and ${PER_HOUR} an hour: try again in ${again}.`);
348 }
349 // Kept with its audit row, whose outcome the job writes when it is done.
350 const later = (kind: "plan" | "yes" | "talk", said: string, sha = ""): void => {
351 audit(app, box, service, player, user.id, kind, said, "waiting", now);
352 db.query(
353 "INSERT INTO game_chat_job (box_id, service, player, user_id, kind, words, sha, origin, audit_id, created_at) VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7, ?8, last_insert_rowid(), ?9)",
354 ).run(box.id, service, player, user.id, kind, said, sha, origin, new Date(now).toISOString());
355 };
356 const lower = words.toLowerCase();
357 if (lower === "" || lower === "help") {
358 audit(app, box, service, player, user.id, "help", words, "told", now);
359 return tell(
360 app,
361 box,
362 service,
363 player,
364 [
365 "!forge give me a new void world with FAWE and bedwars: plans it, then !forge yes builds it.",
366 "!forge <anything else>: asks the crew; the answer comes here.",
367 "!forge no: drops a plan. !forge link <code>: links this name (a code from your forge settings).",
368 ],
369 user.id,
370 );
371 }
372 if (lower === "no") {
373 db.query("DELETE FROM game_chat_pending WHERE box_id = ?1 AND player = ?2").run(box.id, player);
374 audit(app, box, service, player, user.id, "no", words, "dropped", now);
375 return tell(app, box, service, player, ["Dropped."], user.id);
376 }
377 if (lower === "yes") {
378 // The same name, on the same server, within five minutes of the plan it answers.
379 const pending = db
380 .query<
381 { words: string; service: string; user_id: string; created_at: string; sha: string },
382 [string, string]
383 >("SELECT words, service, user_id, created_at, sha FROM game_chat_pending WHERE box_id = ?1 AND player = ?2")
384 .get(box.id, player);
385 const expired = pending !== null && now - Date.parse(pending.created_at) > PENDING_MS;
386 // A yes on another server or from another account leaves the plan where it is; an old one goes.
387 if (expired) db.query("DELETE FROM game_chat_pending WHERE box_id = ?1 AND player = ?2").run(box.id, player);
388 if (pending === null || expired || pending.service !== service || pending.user_id !== user.id) {
389 audit(app, box, service, player, user.id, "yes", words, "nothing waiting", now);
390 return tell(app, box, service, player, ["Nothing here is waiting for your yes: ask again with !forge <what you want>."], user.id);
391 }
392 if (!changesNetwork(app, user, box)) return refuse(user.id, "not an operator of the box", notBox(user, box));
393 db.query("DELETE FROM game_chat_pending WHERE box_id = ?1 AND player = ?2").run(box.id, player);
394 return later("yes", pending.words, pending.sha);
395 }
396 if (asksForServer(words)) {
397 if (!changesNetwork(app, user, box)) return refuse(user.id, "not an operator of the box", notBox(user, box));
398 return later("plan", words);
399 }
400 later("talk", words);
401 }
402
403 /**
404 * A new server changes the whole network (its compose file, the proxy, the box's memory), so it
405 * takes operator of the box, as the page's form and create_server do: never of one server alone.
406 */
407 const changesNetwork = (app: App, user: User, box: GameBox): boolean => mayDo(roleOn(app.db, user, box.id), "operator");
408 const notBox = (user: User, box: GameBox): string => `${user.username} is not an operator of ${box.name}: a new server changes the whole network.`;
409
410 interface Job {
411 readonly id: number;
412 readonly service: string;
413 readonly player: string;
414 readonly user_id: string;
415 readonly kind: "plan" | "yes" | "talk" | "reply";
416 readonly words: string;
417 readonly sha: string;
418 readonly name: string;
419 readonly conversation: string;
420 readonly origin: string;
421 readonly audit_id: number;
422 readonly created_at: string;
423 }
424
425 /** Each box's worker, and the jobs whose crew turn this process is waiting on. */
426 const workers = new WeakMap<App, { boxes: Map<string, Promise<void>>; live: Set<number> }>();
427 function workersOf(app: App): { boxes: Map<string, Promise<void>>; live: Set<number> } {
428 let w = workers.get(app);
429 if (w === undefined) workers.set(app, (w = { boxes: new Map(), live: new Set() }));
430 return w;
431 }
432
outdated

LOW: add a .catch so a failed ask does not become an unhandled rejection.

433 /**
434 * Run a box's waiting jobs, one at a time, oldest first; a call while it runs joins it. Every sync
435 * calls it, so what a restart left is picked up by the next one. A job goes with its answer in one
436 * transaction, and each kind is safe to start again: a plan writes nothing but the plan, a talk is
437 * sent in the transaction that marks it sent, and a yes commits on its plan's commit or not at all.
438 */
439 export function runChat(app: App, boxId: string): Promise<void> {
440 const { boxes } = workersOf(app);
441 const running = boxes.get(boxId);
442 if (running !== undefined) return running;
443 const work = (async () => {
444 // After the sync's own turn, so its answer never waits on a job's first steps.
445 await Bun.sleep(0);
446 try {
447 for (;;) {
448 if (app.closing.signal.aborted) return;
449 const job = nextJob(app, boxId);
450 const box = listBoxes(app.db).find((b) => b.id === boxId);
451 if (job === null || box === undefined) return;
452 try {
453 await runJob(app, box, job);
454 } catch (e) {
455 if (app.closing.signal.aborted) return;
456 app.log.error("a !forge command failed", { box: box.name, kind: job.kind, error: String(e) });
457 finish(app, box, job, "failed", ["That did not work: try again, or do it on the forge."], "red");
458 }
459 }
460 } catch (e) {
461 if (!app.closing.signal.aborted) app.log.error("!forge commands stopped until the next sync", { error: String(e) });
462 } finally {
463 boxes.delete(boxId);
464 }
465 })();
466 boxes.set(boxId, work);
467 return work;
468 }
469
470 /** The oldest job to run: an answer is due when it is there, or when it was waited for too long. */
471 function nextJob(app: App, boxId: string): Job | null {
472 const { live } = workersOf(app);
473 const jobs = app.db.query<Job, [string]>("SELECT * FROM game_chat_job WHERE box_id = ?1 ORDER BY id").all(boxId);
474 return (
475 jobs.find(
476 (j) => j.kind !== "reply" || (!live.has(j.id) && (replyOf(app, j) !== undefined || Date.now() - Date.parse(j.created_at) > REPLY_MS)),
477 ) ?? null
478 );
479 }
480
481 /** The job's end: its outcome in the audit, its words in game, and the job gone, all or nothing. */
482 function finish(app: App, box: GameBox, job: Job, outcome: string, lines: readonly string[], color = "gray"): void {
483 app.db.transaction(() => {
484 if (app.db.query("DELETE FROM game_chat_job WHERE id = ?1").run(job.id).changes === 0) return;
485 if (outcome !== "") app.db.query("UPDATE game_chat SET outcome = ?2 WHERE id = ?1").run(job.audit_id, outcome.slice(0, 300));
486 tell(app, box, job.service, job.player, lines, job.user_id, color);
487 })();
488 }
489
490 /** The crew's latest answer in the job's conversation, as its person reads it. */
491 function replyOf(app: App, job: Job): string | undefined {
492 const turns = listTurns(app.db, job.user_id, job.conversation);
493 return turns.ok ? turns.value.filter((t) => t.role === "agent" && !t.replaced && !t.failed).at(-1)?.text : undefined;
494 }
495
496 async function runJob(app: App, box: GameBox, job: Job): Promise<void> {
497 const db = app.db;
498 if (job.kind === "reply") return answer(app, box, job);
499 // Asked again here: a grant or an account can go while a job waits.
500 const user = getUserById(db, job.user_id);
501 if (user === undefined || !isActive(user) || !mayDo(roleOn(db, user, box.id, job.service), "operator"))
502 return finish(app, box, job, "no longer allowed", ["Your account may no longer do that here."], "red");
503 if (job.kind === "talk") return ask(app, box, job, user);
504 if (!changesNetwork(app, user, box)) return finish(app, box, job, "not an operator of the box", [notBox(user, box)], "red");
505 if (job.kind === "plan") {
506 const planned = await planServer(app, box, await wishOn(app, box, job.words));
507 if (!planned.ok) return finish(app, box, job, planned.error, [`Not possible: ${planned.error}`], "red");
508 return db.transaction(() => {
509 // Five minutes from when the plan is shown, however long it took to make.
510 db.query(
511 "INSERT OR REPLACE INTO game_chat_pending (box_id, player, service, user_id, words, created_at, sha) VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7)",
512 ).run(box.id, job.player, job.service, user.id, job.words, new Date(Math.max(Date.now(), Date.parse(job.created_at))).toISOString(), planned.value.sha);
513 finish(app, box, job, "planned", [...planned.value.lines.slice(0, LINES_OUT - 1), "Type !forge yes within 5 minutes to build it, or !forge no."]);
514 })();
515 }
516 // A yes whose commit began before a restart: the server being there says it landed.
517 if (job.name !== "") {
518 const compose = await readCompose(app, box);
519 if (compose !== undefined && compose.sha !== job.sha && composeServices(compose.text).includes(job.name))
520 return finish(app, box, job, `built ${compose.sha.slice(0, 10)}`, [`${job.name} is in the network. The box brings it up on its next sync.`], "green");
521 }
522 const wish = await wishOn(app, box, job.words);
523 const planned = await planServer(app, box, wish);
524 if (!planned.ok) return finish(app, box, job, planned.error, [`Not built: ${planned.error}`], "red");
525 // The plan took a while: the grant is asked for once more, right before the commit.
526 const still = getUserById(db, user.id);
527 if (still === undefined || !isActive(still) || !changesNetwork(app, still, box)) return finish(app, box, job, "not an operator of the box", [notBox(user, box)], "red");
528 db.query("UPDATE game_chat_job SET name = ?2 WHERE id = ?1").run(job.id, wish.name);
529 const done = await commitServer(app, still, box, planned.value, job.sha);
530 if (!done.ok) return finish(app, box, job, done.error, [`Not built: ${done.error}`], "red");
531 finish(app, box, job, `built ${done.sha.slice(0, 10)}`, [`${planned.value.done}. The box brings it up on its next sync.`], "green");
532 }
533
534 /**
535 * Anything else is the crew's, in a conversation of the person's own: they can read it all on the
536 * forge.
537 */
538 function ask(app: App, box: GameBox, job: Job, user: User): void {
539 const db = app.db;
540 db.transaction(() => {
541 const conversation = createConversation(db, user.id);
542 if (!conversation.ok)
543 return finish(app, box, job, "too many conversations", ["You hold the most conversations the forge keeps: archive one on /talk first."], "red");
544 const sent = talk(app, user, job.words, [], "inject", conversation.value.id);
545 if (!sent.ok) return finish(app, box, job, sent.error, [`The crew could not take it: ${sent.error}.`], "red");
546 const waiting: Job = { ...job, kind: "reply", conversation: conversation.value.id };
547 db.query("UPDATE game_chat_job SET kind = 'reply', conversation = ?2 WHERE id = ?1").run(job.id, waiting.conversation);
548 db.query("UPDATE game_chat SET outcome = ?2 WHERE id = ?1").run(job.audit_id, sent.value.how);
549 tell(app, box, job.service, job.player, [`Asked the crew: the answer comes here and at ${job.origin}/talk/${waiting.conversation}`], user.id);
550 const { live } = workersOf(app);
551 if (sent.value.done === undefined) return;
552 live.add(job.id);
553 // Talk logs a turn that crashed; here either end is the same: the next look at the jobs
554 // answers.
555 void sent.value.done
556 .catch(() => undefined)
557 .then(() => {
558 live.delete(job.id);
559 if (!app.closing.signal.aborted) answer(app, box, waiting);
560 })
561 .catch((e: unknown) => app.log.error("a crew's answer did not reach the game", { box: box.name, error: String(e) }));
562 })();
563 }
564
565 /** The crew's answer in game: its first lines, then the link. Without one, the link alone. */
566 function answer(app: App, box: GameBox, job: Job): void {
567 const link = `${job.origin}/talk/${job.conversation}`;
568 const text = (replyOf(app, job) ?? "")
569 .split("\n")
570 .map((l) => l.trim())
571 .filter(Boolean);
572 if (text.length === 0) return finish(app, box, job, "", [`No answer came: see ${link}`]);
573 finish(app, box, job, "", [...text.slice(0, LINES_OUT - 1), ...(text.length > LINES_OUT - 1 ? [`More at ${link}`] : [])], "white");
574 }
src/games/store.ts +11 −4
@@ -25,7 +25,7 @@ export const LOG_KEEP = 2_000;
2525 const LINES_A_SYNC = 200;
2626 /** The most of a command's output kept: a shell's 16 KB (`shell.ts`) and a pack's hash list (`hashes`); the rest say far less. */
2727 const OUTPUT_MAX = 16_384;
28 export const COMMAND_KINDS = ["rcon", "restart", "stop", "start", "recreate", "pull", "shell", "people", "world", "hashes"] as const;
28 export const COMMAND_KINDS = ["rcon", "restart", "stop", "start", "recreate", "pull", "shell", "people", "world", "hashes", "tell"] as const;
2929 export type CommandKind = (typeof COMMAND_KINDS)[number];
3030 export type Role = "owner" | "operator" | "viewer";
3131 const RANK: Record<Role, number> = { viewer: 1, operator: 2, owner: 3 };
@@ -311,8 +311,10 @@ export const commandHistory = (db: Database, boxId: string, service: string, lim
311311 export const recentCommands = (db: Database, boxId: string, service: string, limit = 10): CommandState[] =>
312312 db
313313 .query<{ id: string }, [string, string, number]>(
314 // A pack check (`hashes`) is the forge's own, not a person's; it is said on the box, not here.
315 "SELECT id FROM game_command WHERE box_id = ?1 AND service = ?2 AND kind != 'hashes' ORDER BY created_at DESC LIMIT ?3",
314 // A pack check (`hashes`) is the forge's own, not a person's; it is said on the box, not
315 // here. A `tell` is the forge's words to one player (`chat.ts`): no one else who sees the
316 // service reads it.
317 "SELECT id FROM game_command WHERE box_id = ?1 AND service = ?2 AND kind NOT IN ('hashes', 'tell') ORDER BY created_at DESC LIMIT ?3",
316318 )
317319 .all(boxId, service, limit)
318320 .map((r) => commandOf(db, r.id)!);
@@ -459,6 +461,10 @@ export interface SyncBody {
459461 readonly diag?: unknown;
460462 /** Each service's world snapshots (`worlds.ts`). */
461463 readonly snapshots?: unknown;
464 /** The chat lines that carry a `!forge` command, by service (`chat.ts`). */
465 readonly chat?: unknown;
466 /** The batch those lines are: sent again, under the same id, until a sync is answered. */
467 readonly chatId?: unknown;
462468 }
463469
464470 const str = (v: unknown, max = 200): string => (typeof v === "string" ? v.slice(0, max) : "");
@@ -529,5 +535,6 @@ export function recordSync(
529535 // A world import's link is a secret (a signed URL): it goes to the box once, in this reply, and
530536 // what stays is its host and path (`worlds.ts`).
531537 for (const c of due) if (c.kind === "world") db.query("UPDATE game_command SET text = ?2 WHERE id = ?1").run(c.id, keptWorldText(c.text));
532 return due;
538 // The box runs a `tell` as the rcon command it is.
539 return due.map((c) => (c.kind === "tell" ? { ...c, kind: "rcon" } : c));
533540 }
src/generated/migrations.ts +8
@@ -465,6 +465,10 @@ import m460 from "../core/migrations/20261201200000-cloud-projects.ts";
465465 import m461 from "../core/migrations/20261201230000-game-world-snapshots.ts";
466466 import m462 from "../core/migrations/20261202000000-game-people.ts";
467467 import m463 from "../core/migrations/20261202000000-mail-relay-scope.ts";
468 import m464 from "../core/migrations/20261202010000-game-chat.ts";
469 import m465 from "../core/migrations/20261202073500-game-link-uuid.ts";
470 import m466 from "../core/migrations/20261202172500-game-chat-plan-sha.ts";
471 import m467 from "../core/migrations/20261202174500-game-chat-jobs.ts";
468472
469473 /** Each migration file's name and its default export, in name order. */
470474 export const MIGRATION_MODULES: readonly (readonly [string, unknown])[] = [
@@ -932,4 +936,8 @@ export const MIGRATION_MODULES: readonly (readonly [string, unknown])[] = [
932936 ["20261201230000-game-world-snapshots.ts", m461],
933937 ["20261202000000-game-people.ts", m462],
934938 ["20261202000000-mail-relay-scope.ts", m463],
939 ["20261202010000-game-chat.ts", m464],
940 ["20261202073500-game-link-uuid.ts", m465],
941 ["20261202172500-game-chat-plan-sha.ts", m466],
942 ["20261202174500-game-chat-jobs.ts", m467],
935943 ];
src/http/games_routes.ts +5
@@ -9,6 +9,7 @@ import { synced } from "../games/notify.ts";
99 import { auditShellResults } from "../games/shell.ts";
1010 import { recordMetrics } from "../games/metrics.ts";
1111 import { recordPeople } from "../games/people.ts";
12 import { gameChat, runChat } from "../games/chat.ts";
1213 import { packChecks } from "../games/pack_check.ts";
1314 import { sleeping } from "../games/sleep.ts";
1415 import { boxByToken, envFiles, markAsleep, recordSync, signJarUrls, type SyncBody } from "../games/store.ts";
@@ -48,6 +49,10 @@ export async function gameAgentSync(ctx: Ctx): Promise<Response> {
4849 const compose = await readCompose(ctx.app, box);
4950 // A server its sleep stopped is asleep, not down: the compose file says which sleep.
5051 markAsleep(ctx.app.db, box.id, compose === undefined ? [] : sleeping(compose.text));
52 // `!forge` said in game chat: checked and kept here; a plan, a commit or the crew is never waited
53 // for (`games/chat.ts`).
54 gameChat(ctx.app, box, body.chat, compose?.text, ctx.url.origin, Date.now(), body.chatId);
55 void runChat(ctx.app, box.id);
5156 synced(ctx.app, box.id);
5257 const reply: Record<string, unknown> = {
5358 composeSha: compose?.sha ?? "",
src/http/lazy_lists.ts +2
@@ -28,6 +28,8 @@ export const SETTINGS_ROUTES = [
2828 ["POST", "/settings/dotfiles"],
2929 ["POST", "/settings/edge/link"],
3030 ["POST", "/settings/edge/unlink"],
31 ["POST", "/settings/minecraft/code"],
32 ["POST", "/settings/minecraft/unlink"],
3133 ["POST", "/settings/parent/link"],
3234 ["POST", "/settings/parent/unlink"],
3335 ["POST", "/settings/email/verify"],
src/http/marks/settings.json +2
@@ -17,6 +17,8 @@
1717 "/settings/dotfiles": "open",
1818 "/settings/edge/link": "open",
1919 "/settings/edge/unlink": "open",
20 "/settings/minecraft/code": "open",
21 "/settings/minecraft/unlink": "open",
2022 "/settings/parent/link": "open",
2123 "/settings/parent/unlink": "open",
2224 "/settings/email/verify": "open",
src/http/settings_routes.ts +4
@@ -45,6 +45,7 @@ import {
4545 signInAct,
4646 } from "../web/pages/accounts.ts";
4747 import { giftMake } from "../web/pages/gifts.ts";
48 import { gameLinkCode, gameLinkRemove } from "../web/pages/games.ts";
4849 import { confirmsList, confirmYes } from "../web/pages/confirms.ts";
4950 import { captainAct, captainPage } from "../web/pages/captain.ts";
5051 import { packsSettingsPage, packsSettingsSave } from "../web/pages/packs-settings.ts";
@@ -186,6 +187,9 @@ export function settingsRoutes(router: Router<Handler>, knownPatterns: () => rea
186187 router.add("POST", "/settings/dotfiles", dotfilesUpdate);
187188 router.add("POST", "/settings/edge/link", edgeLink);
188189 router.add("POST", "/settings/edge/unlink", edgeUnlink);
190 // A Minecraft name linked to this account, for !forge in game chat (#17284).
191 router.add("POST", "/settings/minecraft/code", gameLinkCode);
192 router.add("POST", "/settings/minecraft/unlink", gameLinkRemove);
189193 router.add("POST", "/settings/parent/link", parentLinkStart);
190194 router.add("POST", "/settings/parent/unlink", parentUnlink);
191195 router.add("POST", "/settings/email/verify", resendVerifyLink);
src/tui/screens/games.ts +11
@@ -53,6 +53,7 @@ import type { Session } from "../session.ts";
5353 import { fill, len, split } from "../ui/layout.ts";
5454 import { ListState, confirmScreen, drawList, promptScreen, type ListRow } from "./common.ts";
5555 import { commitServer, planRemoveServer, planServer, wishOn, type ServerPlan } from "../../games/presets.ts";
56 import { CODE_MS, linksOf, newLinkCode } from "../../games/chat.ts";
5657 import type { PaletteEntry } from "./entries.ts";
5758 import { gameModsScreen } from "./game_mods.ts";
5859
@@ -114,6 +115,7 @@ export function gamesScreen(f: Session, ctx: Ctx): Screen {
114115 binding(["n"], "new server"),
115116 binding(["d"], "remove a server"),
116117 binding(["z"], "sleep when empty, or keep warm"),
118 binding(["L"], "link your Minecraft name (!forge)"),
117119 ],
118120 render(area, s) {
119121 const c = ctx.theme.c;
@@ -170,6 +172,15 @@ export function gamesScreen(f: Session, ctx: Ctx): Screen {
170172 ctx.invalidate();
171173 return true;
172174 }
175 // A one-time code for !forge link, shown only here, to the person signed in: what to type in
176 // game, and the names already linked (each bound to the UUID its server listed).
177 if (!e.ctrl && !e.alt && e.key === "L" && f.user !== undefined) {
178 const code = newLinkCode(f.app, f.user);
179 const names = linksOf(f.app, f.user.id).map((l) => `${l.player}${l.uuid === "" ? " (link again)" : ""}`);
180 note = `In game, on a server you operate, type: !forge link ${code} (once, within ${CODE_MS / 60_000} minutes).${names.length === 0 ? "" : ` Linked: ${names.join(", ")}.`}`;
181 ctx.invalidate();
182 return true;
183 }
173184 // A new server on the selected box (or the first you run): words in, the plan shown, yes
174185 // commits.
175186 if (!e.ctrl && !e.alt && e.key === "n") {
src/web/pages/account.ts +9 −7
@@ -28,16 +28,18 @@ import {
2828 import {
2929 NOTIFY_ERRORS,
3030 notifyHost,
31 notifyUrlOf,
31 NOTIFY_KEY,
3232 setNotifyUrl,
3333 } from "../../crew/notify.ts";
34 import { FOCUS_ERRORS, focusSentence, focusUntil, setFocus } from "../../crew/focus.ts";
34 import { getUserSettings } from "../../core/settings.ts";
35 import { FOCUS_ERRORS, FOCUS_KEY, focusSentence, liveFocus, setFocus } from "../../crew/focus.ts";
3536 import { forgeHost, noreplyAddress } from "../../core/commit_identity.ts";
3637 import { ABILITIES, roleOf, rowOf, type Ability } from "../../core/roles.ts";
3738 import { linkEdgeLogin, linkedLogin, unlinkEdgeLogin } from "../../core/edge_links.ts";
3839 import { LAST_WAY_IN, linkedParent, parentIssuerOf, unlinkParent } from "../../core/federation.ts";
3940 import { activeEdgeToken, edgeIdentity } from "../../http/edge.ts";
4041 import { listKeys } from "../../core/keys.ts";
42 import { minecraftBlock } from "./games.ts";
4143 import { listTokensWithClients } from "../../core/oauth.ts";
4244 import {
4345 PROFILE_FALLBACK,
@@ -199,11 +201,10 @@ const refusal = (message: string | undefined): Html =>
199201 * Focus (#15721) sits with the pings it holds, in the notify form's own action row: a person's
200202 * only, its buttons posting to `/settings/focus`. Nothing but a word and the choices is added.
201203 */
202 function focusActions(ctx: Ctx): Html | null {
204 function focusActions(ctx: Ctx, until: string | null): Html | null {
203205 const user = ctx.auth.user!;
204206 if (user.kind !== "user") return null;
205207 const to = "/settings/focus";
206 const until = focusUntil(ctx.app.db, user.id);
207208 return html`<span class="small muted" id="focus">${focusSentence(until)}</span>
208209 ${until === null
209210 ? html`${btn("1h", { name: "for", value: "1h", formaction: to })} ${btn("4h", { name: "for", value: "4h", formaction: to })}`
@@ -211,7 +212,8 @@ function focusActions(ctx: Ctx): Html | null {
211212 }
212213
213214 function notifyView(ctx: Ctx, error?: string): Html {
214 const host = notifyHost(notifyUrlOf(ctx.app.db, ctx.auth.user!.id));
215 const saved = getUserSettings(ctx.app.db, ctx.auth.user!.id, [NOTIFY_KEY, FOCUS_KEY]);
216 const host = notifyHost(saved.get(NOTIFY_KEY) || undefined);
215217 return block(
216218 "Phone notifications",
217219 html`<form method="post" action="/settings/notify">
@@ -225,7 +227,7 @@ function notifyView(ctx: Ctx, error?: string): Html {
225227 })}
226228 <div class="form-actions">
227229 ${btn("Save", { variant: "primary" })}
228 ${focusActions(ctx)}
230 ${focusActions(ctx, liveFocus(saved.get(FOCUS_KEY)))}
229231 </div>
230232 ${refusal(error)}
231233 </form>`,
@@ -492,7 +494,7 @@ function profileView(ctx: Ctx, values: ProfileForm): Html {
492494 </div>
493495 ${refusal(values.refused?.errors.form)}
494496 </form>`,
495 )}`;
497 )}${minecraftBlock(ctx)}`;
496498 }
497499
498500 /** A reading the cell may not give: a dash, never a zero that says "idle". */
src/web/pages/games.ts +69
@@ -54,6 +54,7 @@ import { consoleHtml, consoleText, crashOf, shareOnMclogs } from "../../games/co
5454 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";
57 import { accountLinks, chatLog, newLinkCode, playersOn, unlink } from "../../games/chat.ts";
5758 import { commitServer, planRemoveServer, planServer, wishOn } from "../../games/presets.ts";
5859 import { canSleep, commitPolicy, EMPTY_SECONDS, policyOf, proxyOf, STILL_BILLED, stateWords, WAKER } from "../../games/sleep.ts";
5960 import { CLOUD_EVENT, cloudFacts, GAME_CLOUD_EVENT, pinnedOfBox } from "../../actions/cloud_says.ts";
@@ -169,6 +170,50 @@ export function gamesPage(ctx: Ctx): Response {
169170 }));
170171 }
171172
173 /**
174 * The account page's Minecraft block (#17284): the person's linked names with Unlink, and a code to
175 * link another. Shown to anyone who sees a game box or holds a link.
176 */
177 export function minecraftBlock(ctx: Ctx): Html | null {
178 const links = accountLinks(ctx.app, ctx.auth.user!);
179 if (links === undefined) return null;
180 return html`<section class="settings-block" data-from-game>
181 <h2>Minecraft</h2>
182 <p class="muted small">Link your Minecraft name, then type <span class="mono">!forge give me a new void world with FAWE and bedwars</span> in chat on a server you operate: the plan comes back in game, and <span class="mono">!forge yes</span> builds it. Anything else goes to the crew, and their answer comes back in game.</p>
183 ${links.length === 0
184 ? null
185 : rowList(
186 links.map((l) =>
187 row({
188 title: l.player,
189 meta: html`on ${l.box ?? "a box"} · linked ${time(l.createdAt)}${l.uuid === "" ? " · bound to no UUID: link it again" : html` · <span class="mono">${l.uuid}</span>`}`,
190 after: html`<form method="post" action="/settings/minecraft/unlink" class="row-fields"><input type="hidden" name="box" value="${l.boxId}" /><input type="hidden" name="player" value="${l.player}" />${btn("Unlink", { variant: "secondary", size: "sm" })}</form>`,
191 }),
192 ),
193 )}
194 <form method="post" action="/settings/minecraft/code" class="row-fields">${btn("Link your Minecraft name", { variant: "secondary" })}</form>
195 </section>`;
196 }
197
198 // POST /settings/minecraft/code: a one-time code (ten minutes) the person types in game as !forge
199 // link <code>.
200 export async function gameLinkCode(ctx: Ctx): Promise<Response> {
201 if (!ctx.auth.user) return signInFirst(ctx);
202 const form = await readForm(ctx, "rw");
203 if (form instanceof Response) return form;
204 const code = newLinkCode(ctx.app, ctx.auth.user);
205 return flashTo(ctx, "/settings", { message: `In game, on any server of the box, type: !forge link ${code} (within 10 minutes, once).` });
206 }
207
208 // POST /settings/minecraft/unlink: forget one of the person's linked names.
209 export async function gameLinkRemove(ctx: Ctx): Promise<Response> {
210 if (!ctx.auth.user) return signInFirst(ctx);
211 const form = await readForm(ctx, "rw");
212 if (form instanceof Response) return form;
213 unlink(ctx.app, ctx.auth.user.id, field(form, "box"), field(form, "player"));
214 return flashTo(ctx, "/settings", { message: `Unlinked ${field(form, "player")}.` });
215 }
216
172217 const power = (box: GameBox, service: string): Html =>
173218 html`<span class="row-fields"
174219 >${(["start", "stop", "restart"] as const).map(
@@ -243,6 +288,7 @@ export async function gameBoxPage(ctx: Ctx): Promise<Response> {
243288 ${removal === undefined ? null : removeServerBlock(box, leaving, removal)}
244289 ${topologyBlock(ctx, box, compose?.text, visible)}
245290 ${operator ? newServerBlock(box, words, preview) : null}
291 ${chatBlock(ctx, box, role === "owner")}
246292 ${role === "owner" ? boxBlock(box, packCheckLines(ctx.app, box.id)) : sharedBoxBlock(box, packCheckLines(ctx.app, box.id))} ${role === "owner" ? shellBlock(ctx, box) : null}
247293 ${role === "owner" ? grantsBlock(ctx, box) : null}`,
248294 }));
@@ -295,6 +341,29 @@ export function gameShellStream(ctx: Ctx): Response {
295341 );
296342 }
297343
344 /**
345 * Who may speak to the forge from this box's chat, and (to its owner) the last commands and what
346 * came of them.
347 */
348 function chatBlock(ctx: Ctx, box: GameBox, owner: boolean): Html | null {
349 // Every linked account to an operator of the box; anyone else, of one service too, their own
350 // links.
351 const user = ctx.auth.user!;
352 const all = mayDo(roleOn(ctx.app.db, user, box.id), "operator");
353 const players = playersOn(ctx.app, box.id).filter((p) => all || p.username === user.username);
354 const said = owner ? chatLog(ctx.app, box.id, 10) : [];
355 if (players.length === 0 && said.length === 0) return null;
356 return html`<section class="settings-block" data-linked-players>
357 <h2>Linked players</h2>
358 ${players.length === 0
359 ? emptyNote("nobodyLinkedHere")
360 : rowList(players.map((p) => row({ title: p.player, meta: html`${p.username} · linked ${time(p.createdAt)}` })))}
361 ${said.length === 0
362 ? null
363 : rowList(said.map((c) => row({ title: `${c.player} on ${c.service}: !forge ${c.words}`, meta: html`${c.outcome} · ${time(c.at)}` })))}
364 </section>`;
365 }
366
298367 /** What anyone who may see a service is told of the box: what it is doing, never its tails. */
299368 function sharedBoxBlock(box: GameBox, packs: readonly string[]): Html | null {
300369 const lines = [...boxStatusShared(box.diag), ...packs];
test/game-chat.test.ts added +679
@@ -0,0 +1,679 @@
1 /**
2 * Commands from in the game (#17284): `!forge` in a server's chat, read from the log lines the
3 * agent sends. A name is linked by a one-time code; a linked operator plans a server, builds it
4 * with yes, or asks the crew, and hears back by tellraw. Lines a plugin, /say, /me or tellraw can
5 * make never run, a box with a backend reachable past the proxy runs nothing, and an account is
6 * rate limited.
7 */
8 import { afterAll, beforeAll, describe, expect, test } from "bun:test";
9 import { chmodSync, mkdtempSync, writeFileSync } from "node:fs";
10 import { rm } from "node:fs/promises";
11 import { tmpdir } from "node:os";
12 import { join } from "node:path";
13 import { createApp, type App } from "../src/app.ts";
14 import { commitToBranch, createRepo } from "../src/actions/repos.ts";
15 import { createConversation, listTurns } from "../src/core/conversations.ts";
16 import { getRepo } from "../src/core/repos.ts";
17 import { createSession } from "../src/core/sessions.ts";
18 import { createUser, type User } from "../src/core/users.ts";
19 import { mintViaToken } from "../src/core/via_token.ts";
20 import { configureConversation } from "../src/crew/conversation.ts";
21 import { accountLinks, chatCommand, chatLog, exposedBackend, gameChat, linksOf, newLinkCode, PER_MINUTE, playersOn, runChat, unlink } from "../src/games/chat.ts";
22 import { readCompose, serviceEnv } from "../src/games/compose.ts";
23 import { boxNamed, commandHistory, createGameBox, grant, recentCommands, recordSync, type GameBox } from "../src/games/store.ts";
24 import { forgeHttp, type ForgeHttp } from "../src/http/server.ts";
25 import { quietLogs } from "./helpers/globals.ts";
26 import { pollUntil } from "./helpers/poll.ts";
27
28 quietLogs();
29
30 const COMPOSE = `name: game
31
32 configs:
33 velocity_toml:
34 content: |
35 [servers]
36 hub = "hub:25565"
37 mods = "mods:25565"
38 try = ["hub"]
39
40 [forced-hosts]
41 "mc.trevato.dev" = ["hub"]
42
43 services:
44 velocity:
45 image: itzg/mc-proxy:latest
46 ports: ["25565:25565"]
47 configs:
48 - source: velocity_toml
49 target: /config/velocity.toml
50 environment:
51 TYPE: VELOCITY
52 MEMORY: 768M
53 hub:
54 image: itzg/minecraft-server:latest
55 environment:
56 TYPE: PAPER
57 VERSION: "1.21.6"
58 MEMORY: 1G
59 mods:
60 image: itzg/minecraft-server:latest
61 environment:
62 TYPE: FABRIC
63 VERSION: "1.21.6"
64 MEMORY: 1G
65 `;
66
67 // What each server writes to logs/latest.log when a player chats, and what else can look like it.
68 const paper = (who: string, said: string) => `[12:00:01] [Async Chat Thread - #3/INFO]: <${who}> ${said}`;
69 const fabric = (who: string, said: string) => `[12:00:01] [Server thread/INFO] (Minecraft) <${who}> ${said}`;
70
71 /** The compose file's services, each running: a server's `list uuids` is kept on its row. */
72 const SERVICES = [...COMPOSE.matchAll(/^ ([a-z][a-z0-9-]*):$/gm)].map((m) => m[1]!);
73
74 /** A player's UUID for these tests: the same name, the same UUID, unless a test says otherwise. */
75 const uuidOf = (name: string): string => `00000000-0000-4000-8000-${(Bun.hash(name) % 0xffffffffffffn).toString(16).padStart(12, "0")}`;
76 /** What `list uuids` answers on a server, as recorded from Paper. */
77 const listUuids = (players: Record<string, string>): string => {
78 const names = Object.entries(players).map(([n, u]) => `${n} (${u})`);
79 return `There are ${String(names.length)} of a max of 20 players online: ${names.join(", ")}`;
80 };
81
82 describe("the chat line", () => {
83 test("Paper's and Fabric's own chat lines are commands; Bedrock names too", () => {
84 expect(chatCommand(paper("ada", "!forge help"), "paper")).toEqual({ player: "ada", words: "help" });
85 expect(chatCommand("[12:00:01] [Async Chat Thread - #0/INFO]: [Not Secure] <ada> !forge yes", "paper")).toEqual({
86 player: "ada",
87 words: "yes",
88 });
89 expect(chatCommand(paper(".ada_b", "!forge"), "paper")).toEqual({ player: ".ada_b", words: "" });
90 expect(chatCommand(fabric("ada", "!forge a flat world"), "fabric")).toEqual({ player: "ada", words: "a flat world" });
91 expect(chatCommand("[12:00:01] [Server thread/INFO]: <ada> !forge help\r", "fabric")).toEqual({ player: "ada", words: "help" });
92 });
93
94 test("a plugin's broadcast, /say, /me, a quoted line and the console's format are not", () => {
95 const spoofs: [string, "paper" | "fabric"][] = [
96 // A plugin broadcasting in chat's shape: Paper logs it on the server thread.
97 ["[12:00:01] [Server thread/INFO]: <ada> !forge yes", "paper"],
98 // A plugin's own logger on the chat thread names itself.
99 ["[12:00:01] [Async Chat Thread - #3/INFO]: [ChatFormat] <ada> !forge yes", "paper"],
100 // /say and /me.
101 ["[12:00:01] [Server thread/INFO]: [ada] !forge yes", "paper"],
102 ["[12:00:01] [Server thread/INFO]: * ada !forge yes", "paper"],
103 ["[12:00:01] [Server thread/INFO] (Minecraft) [ada] !forge yes", "fabric"],
104 ["[12:00:01] [Server thread/INFO] (Minecraft) * ada !forge yes", "fabric"],
105 // A mod's own logger on Fabric.
106 ["[12:00:01] [Server thread/INFO] (chatbridge) <ada> !forge yes", "fabric"],
107 // Paper's chat line on a Fabric server, and the other way round.
108 [paper("ada", "!forge yes"), "fabric"],
109 [fabric("ada", "!forge yes"), "paper"],
110 // Eve quoting Ada's line in her own chat.
111 [paper("eve", `${paper("ada", "!forge yes")}`), "paper"],
112 // The console's format (docker logs), which tellraw-style tricks could aim at.
113 ["[12:00:01 INFO]: <ada> !forge yes", "paper"],
114 // Not a name a player can have.
115 [paper("ad a", "!forge yes"), "paper"],
116 [paper("ada", "!forgeyes"), "paper"],
117 ];
118 for (const [line, loader] of spoofs) expect([line, chatCommand(line, loader)]).toEqual([line, undefined]);
119 });
120
121 test("a backend reachable without the proxy turns !forge off", () => {
122 expect(exposedBackend(COMPOSE)).toBeUndefined();
123 expect(exposedBackend(COMPOSE.replace(" hub:\n", ' hub:\n ports: ["25566:25565"]\n'))).toBe(
124 "hub is reachable without the proxy, so a name in its chat cannot be trusted",
125 );
126 expect(exposedBackend(COMPOSE.replace(" mods:\n", " mods:\n network_mode: host\n"))).toContain("mods is reachable");
127 expect(exposedBackend(COMPOSE.replace("itzg/mc-proxy", "itzg/bungeecord"))).toContain("no proxy");
128 });
129 });
130
131 describe("the agent", () => {
132 const lacks = ["bash", "curl", "jq"].filter((t) => Bun.which(t) === null);
133 test.skipIf(lacks.length > 0)(`a batch of chat goes again under its own id until a sync is answered${lacks.length > 0 ? ` (skipped: no ${lacks.join(", ")} here)` : ""}`, async () => {
134 const dir = mkdtempSync(join(tmpdir(), "forge-game-chat-agent-"));
135 const docker = join(dir, "docker");
136 writeFileSync(
137 docker,
138 `#!/usr/bin/env bash
139 case "$*" in
140 *" ps --status running --format "*) echo hub ;;
141 *" exec -T hub sh -c "*latest.log*) printf '5\\n%s\\n' '${paper("ada", "!forge help")}' ;;
142 esac
143 `,
144 );
145 chmodSync(docker, 0o755);
146 const bodies: { chat: unknown; chatId: unknown }[] = [];
147 const forge = Bun.serve({
148 port: 0,
149 hostname: "127.0.0.1",
150 async fetch(req) {
151 bodies.push((await req.json()) as (typeof bodies)[number]);
152 return bodies.length === 1 ? new Response("restarting", { status: 502 }) : Response.json({ composeSha: "", commands: [] });
153 },
154 });
155 try {
156 for (let i = 0; i < 3; i++) {
157 const agent = Bun.spawn(["bash", join(import.meta.dir, "../src/games/agent.sh")], {
158 env: {
159 PATH: process.env["PATH"] ?? "",
160 FORGE_URL: `http://127.0.0.1:${String(forge.port)}`,
161 FORGE_GAME_TOKEN: "fgb_abcdefghijklmnopqrstuvwxyz0123456789ABCDEFG",
162 FORGE_GAME_DIR: dir,
163 FORGE_GAME_DOCKER: docker,
164 FORGE_GAME_ONCE: "1",
165 },
166 stdout: "ignore",
167 stderr: "ignore",
168 });
169 await agent.exited;
170 }
171 expect(bodies.map((b) => b.chat)).toEqual(Array(3).fill({ hub: [paper("ada", "!forge help")] }));
172 expect(bodies[0]!.chatId).toMatch(/^\d+-\d+$/);
173 expect(bodies[1]!.chatId).toBe(bodies[0]!.chatId);
174 expect(bodies[2]!.chatId).not.toBe(bodies[0]!.chatId);
175 } finally {
176 forge.stop(true);
177 await rm(dir, { recursive: true, force: true });
178 }
179 }, 60_000);
180 });
181
182 describe("on a forge", () => {
183 /** Modrinth answers nothing is there, when `hold` lets it. */
184 let hold: Promise<void> = Promise.resolve();
185 const modrinth = async () => {
186 await hold;
187 return new Response("{}", { status: 404 });
188 };
189 let dataDir = "";
190 let app: App;
191 let http: ForgeHttp;
192 let ada: User;
193 let bob: User;
194 let token = "";
195 let seen = 0;
196
197 const box = (): GameBox => boxNamed(app.db, "mc")!;
198 /**
199 * One sync with these chat lines. Who is online on each server comes in the same sync, as the
200 * agent's `list uuids` answer: by default everyone who says something there, each with their own
201 * UUID; `online` says otherwise (an impostor's UUID, or nobody).
202 */
203 const sync = async (chat: Record<string, string[]>, online?: Record<string, Record<string, string>>, chatId?: string, settle = true) => {
204 const on =
205 online ??
206 Object.fromEntries(
207 Object.entries(chat).map(([service, lines]) => [
208 service,
209 Object.fromEntries(lines.flatMap((l) => [.../<([.]?[A-Za-z0-9_]{1,16})>/.exec(l)?.slice(1) ?? []]).map((n) => [n, uuidOf(n)])),
210 ]),
211 );
212 const metrics = Object.fromEntries(Object.entries(on).map(([service, players]) => [service, { list: listUuids(players), tps: "", mspt: "" }]));
213 const res = await http.handle(
214 new Request("http://forge.test/api/v1/games/agent/sync", {
215 method: "POST",
216 headers: { authorization: `Bearer ${token}`, "content-type": "application/json" },
217 body: JSON.stringify({ agent: 1, host: { memMiB: 7_900 }, services: SERVICES.map((name) => ({ name, state: "running" })), chat, chatId, metrics }),
218 }),
219 );
220 expect(res.status).toBe(200);
221 // The plans, commits and messages the sync left to its worker.
222 if (settle) await runChat(app, box().id);
223 };
224 /** The tellraws queued since the last look: to whom, on which server, the text and its colour. */
225 const told = (): { service: string; to: string; text: string; color: string }[] => {
226 const rows = app.db
227 .query<
228 { n: number; service: string; kind: string; text: string },
229 [number]
230 >("SELECT rowid AS n, service, kind, text FROM game_command WHERE rowid > ?1 ORDER BY rowid")
231 .all(seen);
232 if (rows.length > 0) seen = rows.at(-1)!.n;
233 return rows.map((r) => {
234 expect(r.kind).toBe("tell");
235 const m = /^tellraw (\S+) (\{.*\})$/.exec(r.text)!;
236 const json = JSON.parse(m[2]!) as { text: string; color: string };
237 expect(json.text.length).toBeLessThanOrEqual(200);
238 return { service: r.service, to: m[1]!, text: json.text, color: json.color };
239 });
240 };
241 /** A minute on, for the refusals: each is answered once a minute a name. */
242 const aMinuteOn = () => {
243 for (const r of app.db.query<{ id: number; at: string }, []>("SELECT id, at FROM game_chat WHERE kind = 'refused'").all())
244 app.db.query("UPDATE game_chat SET at = ?2 WHERE id = ?1").run(r.id, new Date(Date.parse(r.at) - 61_000).toISOString());
245 };
246 const link = async (user: User, player: string, service = "hub") => {
247 const code = newLinkCode(app, user);
248 await sync({ [service]: [paper(player, `!forge link ${code.toLowerCase()}`)] });
249 return code;
250 };
251
252 beforeAll(async () => {
253 dataDir = mkdtempSync(join(tmpdir(), "forge-game-chat-"));
254 app = createApp({ dataDir, port: 0, host: "forge.test", modrinthFetch: modrinth as unknown as typeof fetch });
255 http = forgeHttp(app);
256 const a = await createUser(app.db, {
257 username: "ada",
258 email: "[email protected]",
259 password: "a-good-passphrase",
260 origin: "seed",
261 isAdmin: true,
262 trusted: true,
263 });
264 const b = await createUser(app.db, {
265 username: "bob",
266 email: "[email protected]",
267 password: "a-good-passphrase",
268 origin: "seed",
269 trusted: true,
270 });
271 if (!a.ok || !b.ok) throw new Error("users");
272 ada = a.value;
273 bob = b.value;
274 const repo = await createRepo(app, ada, { name: "mc-network", visibility: "private" });
275 if (!repo.ok) throw new Error(String(repo.error));
276 const seeded = await commitToBranch(app, ada, repo.value, {
277 message: "seed",
278 files: [{ path: "docker-compose.yml", content: COMPOSE }],
279 });
280 if (!seeded.ok) throw new Error(JSON.stringify(seeded.error));
281 token = createGameBox(app.db, { name: "mc", repo: "ada/mc-network" }).token;
282 // The crew answers every message with three lines.
283 const bin = join(dataDir, "claude");
284 writeFileSync(
285 bin,
286 `#!/bin/sh
287 if [ "$1" = "--version" ]; then echo "2.1.0 (fake)"; exit 0; fi
288 IFS= read -r first
289 echo '{"type":"system","subtype":"init","session_id":"s1","model":"fake"}'
290 echo '{"type":"result","subtype":"success","is_error":false,"result":"The hub restarts at 4.\\\\n\\\\nIt takes a minute.","total_cost_usd":0.01,"num_turns":1,"session_id":"s1","terminal_reason":"completed","usage":{"input_tokens":1,"output_tokens":1}}'
291 `,
292 );
293 chmodSync(bin, 0o755);
294 configureConversation(app, {
295 binary: bin,
296 localUrl: "http://forge.test",
297 budgetUsd: 1,
298 timeoutMs: 30_000,
299 signal: new AbortController().signal,
300 });
301 await sync({});
302 told();
303 }, 30_000);
304 afterAll(async () => {
305 app.close();
306 await rm(dataDir, { recursive: true, force: true });
307 });
308
309 test("a name nobody linked is told how, and nothing runs", async () => {
310 await sync({ hub: [paper("eve", "!forge give me a flat world called heist")] });
311 expect(told()).toEqual([
312 {
313 service: "hub",
314 to: "eve",
315 text: "Link your name first: get a code under Minecraft in your forge settings, then type !forge link <code>.",
316 color: "gray",
317 },
318 ]);
319 expect(chatLog(app, box().id, 1)[0]).toMatchObject({ player: "eve", kind: "refused", outcome: "not linked" });
320 });
321
322 test("a code links the name once; a wrong code is counted, and no code is kept in clear", async () => {
323 const code = await link(ada, "ada");
324 expect(told()).toEqual([
325 { service: "hub", to: "ada", text: "Linked to ada. Type !forge help to see what you can ask.", color: "green" },
326 ]);
327 expect(linksOf(app, ada.id)).toMatchObject([{ boxId: box().id, player: "ada" }]);
328 expect(playersOn(app, box().id)).toMatchObject([{ player: "ada", username: "ada" }]);
329 // Used once: the same code from another name does nothing.
330 await sync({ hub: [paper("mallory", `!forge link ${code}`)] });
331 expect(told()[0]!.text).toStartWith("That code is not one the forge gave");
332 for (let i = 0; i < 5; i++) await sync({ hub: [paper("mallory", "!forge link ZZZZZZ")] });
333 told();
334 // Locked out after five, even with a good code.
335 aMinuteOn();
336 await link(bob, "mallory");
337 expect(told()[0]!.text).toBe("Too many wrong codes for this name: try again in an hour.");
338 expect(linksOf(app, bob.id)).toEqual([]);
339 const kept = app.db
340 .query<{ words: string }, []>("SELECT words FROM game_chat")
341 .all()
342 .map((r) => r.words);
343 expect(kept.some((w) => w.includes(code) || w.includes("ZZZZZZ"))).toBe(false);
344 });
345
346 test("the spoofs reach nothing, even for a linked operator", async () => {
347 const before = chatLog(app, box().id, 100).length;
348 await sync({
349 hub: [
350 "[12:00:01] [Server thread/INFO]: <ada> !forge help",
351 "[12:00:01] [Server thread/INFO]: [ada] !forge help",
352 "[12:00:01] [Server thread/INFO]: * ada !forge help",
353 ],
354 mods: ["[12:00:01] [Server thread/INFO] (chatbridge) <ada> !forge help"],
355 velocity: [paper("ada", "!forge help")],
356 });
357 expect(told()).toEqual([]);
358 expect(chatLog(app, box().id, 100).length).toBe(before);
359 });
360
361 test("a linked name without operator is refused", async () => {
362 await link(bob, "bob");
363 told();
364 await sync({ hub: [paper("bob", "!forge help")] });
365 expect(told()).toEqual([{ service: "hub", to: "bob", text: "bob is not an operator of hub.", color: "red" }]);
366 });
367
368 test("a new server is planned in chat, and yes from the same name on the same server builds it", async () => {
369 await sync({ hub: [paper("ada", "!forge give me a flat world called build")] });
370 const plan = told();
371 expect(plan[0]!.text).toStartWith("Adds build: Paper 1.21.6, a flat world");
372 expect(plan.some((l) => l.text.startsWith("Memory: "))).toBe(true);
373 expect(plan.at(-1)!.text).toBe("Type !forge yes within 5 minutes to build it, or !forge no.");
374 // A yes on another server leaves the plan waiting.
375 await link(ada, "ada", "mods");
376 told();
377 await sync({ mods: [fabric("ada", "!forge yes")] });
378 expect(told()[0]!.text).toStartWith("Nothing here is waiting for your yes");
379 await sync({ hub: [paper("ada", "!forge yes")] });
380 const built = told();
381 expect(built).toHaveLength(1);
382 expect(built[0]!.color).toBe("green");
383 expect(built[0]!.text).toContain("The box brings it up on its next sync.");
384 const now = (await readCompose(app, box()))!;
385 expect(serviceEnv(now.text, "build")).toMatchObject({ TYPE: "PAPER", LEVEL_TYPE: "FLAT" });
386 expect(chatLog(app, box().id, 1)[0]).toMatchObject({ kind: "yes", words: "give me a flat world called build" });
387 expect(chatLog(app, box().id, 1)[0]!.outcome).toStartWith("built ");
388 // Nothing is left to say yes to.
389 await sync({ hub: [paper("ada", "!forge yes")] });
390 expect(told()[0]!.text).toStartWith("Nothing here is waiting");
391 }, 30_000);
392
393 test("anything else goes to the crew, and its answer comes back in game", async () => {
394 // Two minutes on: the commands above spent this minute's five.
395 gameChat(app, box(), { hub: [paper("ada", "!forge when does the hub restart?")] }, COMPOSE, "http://forge.test", Date.now() + 120_000);
396 await runChat(app, box().id);
397 const asked = told();
398 expect(asked).toHaveLength(1);
399 const where = /at (http:\/\/forge\.test\/talk\/(\S+))$/.exec(asked[0]!.text)!;
400 expect(where).not.toBeNull();
401 let back: ReturnType<typeof told> = [];
402 await pollUntil(() => (back = [...back, ...told()]).length > 0, "the crew's answer in game");
403 expect(back).toEqual([
404 { service: "hub", to: "ada", text: "The hub restarts at 4.", color: "white" },
405 { service: "hub", to: "ada", text: "It takes a minute.", color: "white" },
406 ]);
407 // The same words the account reads in its own conversation.
408 const turns = listTurns(app.db, ada.id, where[2]!);
409 expect(turns.ok && turns.value.map((t) => t.role)).toEqual(["person", "agent"]);
410 }, 30_000);
411
412 test("five a minute: the sixth is told when to retry, and a box with an open backend runs nothing", async () => {
413 // Two hours ahead of the commands the tests before this one ran: none of them is in its
414 // windows.
415 const t0 = Date.now() + 2 * 3_600_000;
416 for (let i = 0; i < PER_MINUTE; i++)
417 await gameChat(app, box(), { hub: [paper("ada", "!forge help")] }, COMPOSE, "http://forge.test", t0 + i * 1000);
418 told();
419 await gameChat(app, box(), { hub: [paper("ada", "!forge help")] }, COMPOSE, "http://forge.test", t0 + 10_000);
420 expect(told()).toEqual([
421 { service: "hub", to: "ada", text: "At most 5 commands a minute and 30 an hour: try again in 50 seconds.", color: "red" },
422 ]);
423 // A minute after the first, one more runs.
424 await gameChat(app, box(), { hub: [paper("ada", "!forge help")] }, COMPOSE, "http://forge.test", t0 + 61_000);
425 expect(told()[0]!.color).toBe("gray");
426
427 const open = COMPOSE.replace(" hub:\n", ' hub:\n ports: ["25566:25565"]\n');
428 await gameChat(app, box(), { hub: [paper("ada", "!forge link ABCDEF")] }, open, "http://forge.test", t0 + 3_600_000);
429 expect(told()).toEqual([
430 {
431 service: "hub",
432 to: "ada",
433 text: "!forge is off on this network: hub is reachable without the proxy, so a name in its chat cannot be trusted.",
434 color: "red",
435 },
436 ]);
437 expect(chatLog(app, box().id, 1)[0]).toMatchObject({ kind: "refused", words: "link ****" });
438 });
439
440 test("a link binds the UUID the server lists, not the name: another player with the name drops it, the name offline keeps it", async () => {
441 const grace = uuidOf("grace");
442 // bob's links by name (an earlier test linked "bob").
443 const linked = (player: string) => linksOf(app, bob.id).filter((l) => l.player === player);
444 // Not listed when the code is typed: refused, and the code stays good.
445 const code = newLinkCode(app, bob);
446 await sync({ hub: [paper("grace", `!forge link ${code}`)] }, { hub: {} });
447 expect(told()).toEqual([{ service: "hub", to: "grace", text: "The forge does not see grace on hub yet: stay on and type it again in a minute.", color: "red" }]);
448 expect(linked("grace")).toEqual([]);
449 await sync({ hub: [paper("grace", `!forge link ${code}`)] }, { hub: { grace } });
450 expect(told()[0]!.text).toBe("Linked to bob. Type !forge help to see what you can ask.");
451 expect(linked("grace")).toMatchObject([{ player: "grace", uuid: grace }]);
452 // The name not online (the server does not list it): refused, the link kept.
453 aMinuteOn();
454 await sync({ hub: [paper("grace", "!forge help")] }, { hub: { ada: uuidOf("ada") } });
455 expect(told()[0]!.text).toBe("The forge does not see grace on hub yet: try again in a minute.");
456 expect(chatLog(app, box().id, 1)[0]).toMatchObject({ player: "grace", kind: "refused", outcome: "not seen online" });
457 expect(linked("grace")).toHaveLength(1);
458 // The name online as another player (a new owner of the name): refused, and the link dropped.
459 await sync({ hub: [paper("grace", "!forge help")] }, { hub: { grace: "11111111-2222-4333-8444-555555555555" } });
460 expect(told()[0]!).toMatchObject({ to: "grace", text: "grace was linked as another player, so that link is gone: link again with a new code.", color: "red" });
461 expect(linked("grace")).toEqual([]);
462 expect(chatLog(app, box().id, 1)[0]).toMatchObject({ player: "grace", kind: "refused", outcome: "another player has the name: link dropped" });
463 // A link from before UUIDs were bound has none, and goes the same way.
464 app.db.query("INSERT INTO game_link (box_id, player, user_id, created_at) VALUES (?1, 'olden', ?2, ?3)").run(box().id, bob.id, new Date().toISOString());
465 await sync({ hub: [paper("olden", "!forge help")] });
466 expect(told()[0]!.text).toBe("olden was linked as another player, so that link is gone: link again with a new code.");
467 expect(linked("olden")).toEqual([]);
468 // A UUID typed in chat is only words: the binding is the server's list.
469 expect(chatCommand(paper("grace", `!forge link ${code} ${grace}`), "paper")?.words).toBe(`link ${code} ${grace}`);
470 });
471
472 test("yes to a plan made before the network's repository moved builds nothing, and says to plan again", async () => {
473 // Four hours on, past what the tests above spent of the hour (one of them is two hours ahead).
474 const later = Date.now() + 4 * 3_600_000;
475 await sync({}, { hub: { ada: uuidOf("ada") } });
476 const say = async (words: string) => {
477 gameChat(app, box(), { hub: [paper("ada", words)] }, (await readCompose(app, box()))!.text, "http://forge.test", later);
478 await runChat(app, box().id);
479 };
480 await say("!forge give me a flat world called moved");
481 expect(told().some((t) => t.text.startsWith("Adds moved:"))).toBe(true);
482 const repo = getRepo(app.db, "ada", "mc-network")!;
483 const moved = await commitToBranch(app, ada, repo, { message: "a note", files: [{ path: "NOTE.md", content: "x" }] });
484 if (!moved.ok) throw new Error(JSON.stringify(moved.error));
485 await say("!forge yes");
486 expect(told()[0]!.text).toBe("Not built: The box changed since the preview; plan it again.");
487 expect((await readCompose(app, box()))!.text).not.toContain("container_name: moved");
488 });
489
490 test("operator of one server is not operator of the box: no plan, no yes, and a grant lost while a job waits stops it", async () => {
491 const made = await createUser(app.db, { username: "olga", email: "[email protected]", password: "a-good-passphrase", origin: "seed", trusted: true });
492 if (!made.ok) throw new Error(made.error);
493 const olga = made.value;
494 await link(olga, "olga");
495 grant(app.db, box().id, olga.id, "operator", "hub");
496 told();
497 const refused = "olga is not an operator of mc: a new server changes the whole network.";
498 const jobs = () => app.db.query<{ n: number }, []>("SELECT COUNT(*) AS n FROM game_chat_job").get()!.n;
499 await sync({ hub: [paper("olga", "!forge give me a flat world called heist")] });
500 expect(told().map((t) => t.text)).toEqual([refused]);
501 expect(jobs()).toBe(0);
502 // Operator of the box makes the plan; with only the server's grant left, yes builds nothing.
503 grant(app.db, box().id, olga.id, "operator");
504 await sync({ hub: [paper("olga", "!forge give me a flat world called heist")] });
505 expect(told()[0]!.text).toStartWith("Adds heist:");
506 grant(app.db, box().id, olga.id, "none");
507 aMinuteOn();
508 await sync({ hub: [paper("olga", "!forge yes")] });
509 expect(told().map((t) => t.text)).toEqual([refused]);
510 // Still the box's when the yes is said, and not when its job runs.
511 grant(app.db, box().id, olga.id, "operator");
512 gameChat(app, box(), { hub: [paper("olga", "!forge yes")] }, COMPOSE, "http://forge.test");
513 expect(jobs()).toBe(1);
514 grant(app.db, box().id, olga.id, "none");
515 await runChat(app, box().id);
516 expect(told().map((t) => t.text)).toEqual([refused]);
517 expect((await readCompose(app, box()))!.text).not.toContain("container_name: heist");
518 // A suspended account's link says nothing.
519 app.db.query("UPDATE user SET suspended_at = ?2 WHERE id = ?1").run(olga.id, new Date().toISOString());
520 aMinuteOn();
521 await sync({ hub: [paper("olga", "!forge help")] });
522 expect(told().map((t) => t.text)).toEqual(["The forge account this name is linked to cannot act now."]);
523 });
524
525 test("an unlinked spammer costs one row and one answer a minute, and cannot crowd out another player", async () => {
526 const rows = () => app.db.query<{ n: number }, []>("SELECT COUNT(*) AS n FROM game_chat").get()!.n;
527 const before = rows();
528 for (let i = 0; i < 10; i++) await sync({ hub: Array.from({ length: 20 }, () => paper("spam", "!forge hi")) });
529 expect(told()).toHaveLength(1);
530 expect(rows() - before).toBe(1);
531 await sync({ hub: [...Array.from({ length: 19 }, () => paper("spam", "!forge hi")), paper("quiet", "!forge hi")] });
532 expect(told().map((t) => t.to)).toEqual(["quiet"]);
533 aMinuteOn();
534 await sync({ hub: [paper("spam", "!forge hi")] });
535 expect(told()).toHaveLength(1);
536 });
537
538 test("a slow plan does not hold the sync, and a batch sent twice runs once", async () => {
539 const dana = await createUser(app.db, { username: "dana", email: "[email protected]", password: "a-good-passphrase", origin: "seed", trusted: true });
540 if (!dana.ok) throw new Error(dana.error);
541 await link(dana.value, "dana");
542 grant(app.db, box().id, dana.value.id, "operator");
543 told();
544 let release = () => {};
545 hold = new Promise((r) => (release = r));
546 const said = { hub: [paper("dana", "!forge a void world with FAWE")] };
547 await sync(said, undefined, "batch-0001", false);
548 await sync(said, undefined, "batch-0001", false);
549 expect(told()).toEqual([]);
550 expect(app.db.query("SELECT kind FROM game_chat_job").all()).toEqual([{ kind: "plan" }]);
551 release();
552 await runChat(app, box().id);
553 expect(told().map((t) => t.text.slice(0, 13))).toEqual(["Not possible:"]);
554 expect(app.db.query("SELECT kind FROM game_chat_job").all()).toEqual([]);
555 });
556
557 test("what a restart left: a waiting plan is made, and a yes whose commit landed is not committed again", async () => {
558 const job = (kind: string, words: string, sha = "", name = "") =>
559 app.db
560 .query("INSERT INTO game_chat_job (box_id, service, player, user_id, kind, words, sha, name, audit_id, created_at) VALUES (?1, 'hub', 'ada', ?2, ?3, ?4, ?5, ?6, 0, ?7)")
561 .run(box().id, ada.id, kind, words, sha, name, new Date().toISOString());
562 job("plan", "a flat world called later");
563 await sync({});
564 expect(told()[0]!.text).toStartWith("Adds later:");
565 const tip = (await readCompose(app, box()))!.sha;
566 job("yes", "a flat world called build", "0".repeat(40), "build");
567 await sync({});
568 expect(told().map((t) => t.text)).toEqual(["build is in the network. The box brings it up on its next sync."]);
569 expect((await readCompose(app, box()))!.sha).toBe(tip);
570 });
571
572 test("the account page's one read: every link with its box's name and UUID, none for who sees no box", async () => {
573 const people = await Promise.all(
574 ["cleo", "dan"].map((username) =>
575 createUser(app.db, { username, email: `${username}@f.test`, password: "a-good-passphrase", origin: "seed", trusted: true }),
576 ),
577 );
578 const [cleo, dan] = people.map((p) => {
579 if (!p.ok) throw new Error(p.error);
580 return p.value;
581 }) as [User, User];
582 // No grant and no link: nothing to offer. A grant alone: the block, with no link in it.
583 expect(accountLinks(app, cleo)).toBeUndefined();
584 grant(app.db, box().id, cleo.id, "viewer", "hub");
585 expect(accountLinks(app, cleo)).toEqual([]);
586 // Two real links, in the order they were made; no grant needed to see one's own.
587 await link(dan, "dan_one");
588 await link(dan, "dan_two");
589 told();
590 expect(accountLinks(app, dan)).toMatchObject([
591 { boxId: box().id, box: "mc", player: "dan_one", uuid: uuidOf("dan_one") },
592 { boxId: box().id, box: "mc", player: "dan_two", uuid: uuidOf("dan_two") },
593 ]);
594 // Someone else's links are not theirs, and a grant on a box that is gone shows nothing.
595 expect(accountLinks(app, cleo)).toEqual([]);
596 grant(app.db, box().id, cleo.id, "none", "hub");
597 grant(app.db, "gone", cleo.id, "viewer");
598 expect(accountLinks(app, cleo)).toBeUndefined();
599 // The page shows them.
600 const cookie = `forge_session=${createSession(app.db, dan.id).token}`;
601 const page = await (await http.handle(new Request("http://forge.test/settings", { headers: { cookie } }))).text();
602 for (const words of ["dan_one", "dan_two", "on mc", uuidOf("dan_two")]) expect(page).toContain(words);
603 });
604
605 test("who sees one service sees only their own link, and never what the forge told a player in game", async () => {
606 const vera = await createUser(app.db, { username: "vera", email: "[email protected]", password: "a-good-passphrase", origin: "seed", trusted: true });
607 if (!vera.ok) throw new Error(vera.error);
608 const read = async (path: string) =>
609 (await http.handle(new Request(`http://forge.test${path}`, { headers: { cookie: `forge_session=${createSession(app.db, vera.value.id).token}` } }))).text();
610 grant(app.db, box().id, vera.value.id, "viewer", "hub");
611 expect(await read("/games/mc")).not.toContain("data-linked-players");
612 await link(vera.value, "vera_mc");
613 const own = await read("/games/mc");
614 expect(own).toContain("vera_mc");
615 for (const other of ["dan_one", "dan_two"]) expect(own).not.toContain(other);
616 // Operator of one service sees no more of the box; operator of the box sees them all.
617 grant(app.db, box().id, vera.value.id, "operator", "hub");
618 expect(await read("/games/mc")).not.toContain("dan_one");
619 grant(app.db, box().id, vera.value.id, "operator");
620 expect(await read("/games/mc")).toContain("dan_one");
621 grant(app.db, box().id, vera.value.id, "none");
622 // The replies name accounts and carry the crew's answers: not in the service's console, on the
623 // page, or in what a command's history offers.
624 const console = await read("/games/mc/hub");
625 expect(console).not.toContain("tellraw");
626 expect(console).not.toContain("Linked to ");
627 expect(recentCommands(app.db, box().id, "hub", 100).filter((c) => c.text.startsWith("tellraw"))).toEqual([]);
628 expect(commandHistory(app.db, box().id, "hub").filter((c) => c.startsWith("tellraw"))).toEqual([]);
629 // The agent still gets them as the rcon commands they are.
630 await link(vera.value, "vera_two");
631 const handed = recordSync(app.db, box(), { services: [] });
632 expect(handed.filter((c) => c.text.startsWith("tellraw vera_two")).map((c) => c.kind)).toEqual(["rcon"]);
633 told();
634 });
635
636 test("a Talk turn acts as its person: operator of one server gets nothing on another, or on the network", async () => {
637 const tess = await createUser(app.db, { username: "tess", email: "[email protected]", password: "a-good-passphrase", origin: "seed", trusted: true });
638 if (!tess.ok) throw new Error(tess.error);
639 grant(app.db, box().id, tess.value.id, "operator", "hub");
640 const made = createConversation(app.db, tess.value.id);
641 if (!made.ok) throw new Error(made.error);
642 // The token `talk()` gives a turn (crew/conversation.ts): the person's own, by way of it.
643 const minted = mintViaToken(app.db, tess.value.id, `conversation:${made.value.id}`, "stop mods", new Date(Date.now() + 600_000).toISOString());
644 if (!minted.ok) throw new Error(minted.error);
645 const call = async (args: Record<string, unknown>) => {
646 const res = await http.handle(
647 new Request("http://forge.test/mcp", {
648 method: "POST",
649 headers: { "content-type": "application/json", accept: "application/json, text/event-stream", authorization: `Bearer ${minted.value.token}` },
650 body: JSON.stringify({ jsonrpc: "2.0", id: 1, method: "tools/call", params: { name: "games", arguments: { box: "mc", ...args } } }),
651 }),
652 );
653 return JSON.stringify(await res.json());
654 };
655 const queued = () => app.db.query<{ n: number }, [string]>("SELECT COUNT(*) AS n FROM game_command WHERE by = ?1").get(tess.value.id)!.n;
656 const tip = (await readCompose(app, box()))!.sha;
657 expect(await call({ action: "power", service: "mods", kind: "stop" })).toContain("you are not an operator of mods on mc");
658 expect(await call({ action: "env", service: "mods", key: "MOTD", value: "x" })).toContain("you are not an operator of mods on mc");
659 expect(await call({ action: "create_server", words: "a flat world called heist" })).toContain("you are not an operator of mc");
660 expect(queued()).toBe(0);
661 expect((await readCompose(app, box()))!.sha).toBe(tip);
662 // Its own server it may: the refusals above are the grant's, not the token's.
663 expect(await call({ action: "power", service: "hub", kind: "restart" })).not.toContain("not an operator");
664 });
665
666 test("the account page links and unlinks; the box page lists who is linked", async () => {
667 const cookie = `forge_session=${createSession(app.db, ada.id).token}`;
668 const settings = await (await http.handle(new Request("http://forge.test/settings", { headers: { cookie } }))).text();
669 expect(settings).toContain("data-from-game");
670 expect(settings).toContain('action="/settings/minecraft/code"');
671 expect(settings).toContain('action="/settings/minecraft/unlink"');
672 const boxPage = await (await http.handle(new Request("http://forge.test/games/mc", { headers: { cookie } }))).text();
673 expect(boxPage).toContain("data-linked-players");
674 expect(boxPage).toContain("bob");
675 unlink(app, ada.id, box().id, "ada");
676 expect(linksOf(app, ada.id)).toEqual([]);
677 expect(chatLog(app, box().id, 1)[0]).toMatchObject({ kind: "unlink", player: "ada" });
678 });
679 });
test/tui-games.test.ts +18
@@ -17,6 +17,7 @@ import { readCompose, serviceEnv } from "../src/games/compose.ts";
1717 import { boxNamed, createGameBox, grant, grantsOf, recentCommands, recordSync } from "../src/games/store.ts";
1818 import { queueWorld } from "../src/games/worlds.ts";
1919 import { createForgeApp } from "../src/tui/forge.ts";
20 import { sha256 } from "../src/kernel/hash.ts";
2021 import { gameGrantsScreen, gameServiceScreen, gamesScreen } from "../src/tui/screens/games.ts";
2122 import { headlessTerminal } from "../src/tui/term/terminal.ts";
2223 import { quietLogs } from "./helpers/globals.ts";
@@ -244,3 +245,20 @@ test("z on the games list: choosing sleep says the machine is still billed; goin
244245 expect(tui.screen.toText()).not.toContain("still billed");
245246 tui.stop?.();
246247 });
248
249 test("L on the games list shows a one-time !forge link code to the person signed in, kept only as its hash", async () => {
250 const { tui, session, type } = drive(alice);
251 try {
252 tui.ctx.push(gamesScreen(session, tui.ctx));
253 await settleApp(tui);
254 await type("L");
255 const text = tui.screen.toText();
256 const code = /!forge link ([2-9A-Z]{6})/.exec(text)?.[1];
257 expect(code, text).toBeDefined();
258 expect(text).toContain("once, within 10 minutes");
259 const kept = app.db.query<{ code_hash: string; user_id: string }, []>("SELECT code_hash, user_id FROM game_link_code").all();
260 expect(kept).toEqual([{ code_hash: sha256(code!), user_id: alice.id }]);
261 } finally {
262 tui.stop?.();
263 }
264 });

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

Keyboard shortcuts

Docs