Public: anyone can read this; the crew can change it.
Games: the forge's side of /forge through the proxy #17663
Merged 11h 25m ago, live in production
sold/game-door → main 0 commits 2 threads · 2 unresolved
11 files
changed +523
−43
- docs/features/games.md
- src/contract/openapi/routes/postApiV1GamesAgentSync.ts
- src/core/migration-pins/20261202203738-game-ask.pin
- src/core/migrations/20261202203738-game-ask.ts
- src/games/chat.ts
- src/games/door.ts
- src/games/store.ts
- src/http/games_routes.ts
- test/game-chat.test.ts
- test/game-door.test.ts
- test/helpers/game-chat-clock.ts
docs/features/games.md +4
| @@ -87,6 +87,10 @@ Anyone else gets a line saying how to link, and nothing runs. Replies are RCON ` | ||
| 87 | 87 | |
| 88 | 88 | 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. |
| 89 | 89 | |
| 90 | **Through the proxy (`/forge`, #17610).** The forge's side of a command on the proxy itself (`src/games/door.ts`); the plugin and the agent's part are not on a box yet. A request comes in the sync's `ask` (`{ id, uuid, name, server, words, confirms? }`, at most 20) and its answers go back in `told` (`{ id, uuid, text, confirm }`, at most 20, each handed out once, dropped after an hour); a quick poll (`light`) that says `told: true` gets them too. It runs the same rules as `!forge`: the link, the role and the limits; the UUID is the proxy's own. Each request is kept once by its `id` for a day, so one sent again does nothing. Whenever the sync carries `ask`, the answer's `asked` lists the ids the forge took, now or before; the agent deletes those and sends the rest again. Not taken: past the first 20, or no compose file could be read. One that names no player cannot be answered: it is taken, and the forge's log counts it. | |
| 91 | ||
| 92 | A server can show text whose click runs a command as the player, so a request that links a name, builds or drops a plan, or asks the crew changes nothing: it is answered with `confirm: true`, and the proxy shows the player a one-time code. Only a later request whose `confirms` names it acts, from the same UUID on the same box, once, within three minutes of the answer going to the box (the code itself lives two). A plan is built only at the door it was asked at: a `!forge yes` in chat never builds a plan made through the proxy, nor the other way round. Questions, help and the making of a plan need no code. | |
| 93 | ||
| 90 | 94 | 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. |
| 91 | 95 | |
| 92 | 96 | 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. |
src/contract/openapi/routes/postApiV1GamesAgentSync.ts +1 −1
| @@ -4,7 +4,7 @@ export const route: Route = { | ||
| 4 | 4 | method: "post", |
| 5 | 5 | path: "/api/v1/games/agent/sync", |
| 6 | 6 | summary: "A game box agent's sync: status, logs and results in; compose, .env and commands out", |
| 7 | detail: "The bearer is the game box's token. Send `{ agent, composeSha, services, logs, results, host }`; the answer is `{ composeSha, compose? (only when the sha differs), env, commands, agentSha }`, each command handed out once; agentSha is the sha256 of the agent this forge runs, which a box whose own differs fetches from GET /api/v1/games/agent/script", | |
| 7 | detail: "The bearer is the game box's token. Send `{ agent, composeSha, services, logs, results, host, ask? (the proxy's /forge requests) }`; the answer is `{ composeSha, compose? (only when the sha differs), env, commands, told? (answers to those requests), agentSha }`, each command handed out once; agentSha is the sha256 of the agent this forge runs, which a box whose own differs fetches from GET /api/v1/games/agent/script", | |
| 8 | 8 | auth: false, |
| 9 | 9 | role: "anonymous", |
| 10 | 10 | refuses: [401], |
src/core/migration-pins/20261202203738-game-ask.pin added +1
| @@ -0,0 +1,1 @@ | ||
| 1 | 9ae2e2ae2491dfee36276b637db9ebd37c080813d8922512768e93542604082b |
src/core/migrations/20261202203738-game-ask.ts added +30
| @@ -0,0 +1,30 @@ | ||
| 1 | // `/forge` typed on the proxy (#17610): each request once, by its own id, with what its player may | |
| 2 | // still confirm (a link code only as its hash); the answers on their way back to the box; and the | |
| 3 | // request a waiting command answers or a waiting plan was made for. | |
| 4 | export default ` | |
| 5 | CREATE TABLE IF NOT EXISTS game_ask ( | |
| 6 | box_id TEXT NOT NULL, | |
| 7 | id TEXT NOT NULL, | |
| 8 | uuid TEXT NOT NULL, | |
| 9 | player TEXT NOT NULL, | |
| 10 | service TEXT NOT NULL, | |
| 11 | action TEXT NOT NULL DEFAULT '', | |
| 12 | words TEXT NOT NULL DEFAULT '', | |
| 13 | shown_at TEXT NOT NULL DEFAULT '', | |
| 14 | created_at TEXT NOT NULL, | |
| 15 | PRIMARY KEY (box_id, id) | |
| 16 | ); | |
| 17 | CREATE INDEX IF NOT EXISTS game_ask_created ON game_ask (created_at); | |
| 18 | CREATE TABLE IF NOT EXISTS game_told ( | |
| 19 | id INTEGER PRIMARY KEY AUTOINCREMENT, | |
| 20 | box_id TEXT NOT NULL, | |
| 21 | ask_id TEXT NOT NULL, | |
| 22 | uuid TEXT NOT NULL, | |
| 23 | text TEXT NOT NULL, | |
| 24 | confirm INTEGER NOT NULL DEFAULT 0, | |
| 25 | created_at TEXT NOT NULL | |
| 26 | ); | |
| 27 | CREATE INDEX IF NOT EXISTS game_told_box ON game_told (box_id, id); | |
| 28 | ALTER TABLE game_chat_job ADD COLUMN ask_id TEXT NOT NULL DEFAULT ''; | |
| 29 | ALTER TABLE game_chat_pending ADD COLUMN ask_id TEXT NOT NULL DEFAULT ''; | |
| 30 | `; |
src/games/chat.ts +95 −36
| @@ -30,10 +30,11 @@ import { blockedBy, blockedText } from "../kernel/blocked.ts"; | ||
| 30 | 30 | import { sha256 } from "../kernel/hash.ts"; |
| 31 | 31 | import { answerTo, questionOf, serversSeen } from "./ask.ts"; |
| 32 | 32 | import { composeServices, readCompose, serviceEnv } from "./compose.ts"; |
| 33 | import { asksIn, keepAsk, say, takeConfirmed, type Confirmed, type Where } from "./door.ts"; | |
| 33 | 34 | import { commitServer, planServer, wishOn } from "./presets.ts"; |
| 34 | 35 | import { peopleOf } from "./people.ts"; |
| 35 | 36 | import { proxyOf } from "./sleep.ts"; |
| 36 | import { LINES_OUT, listBoxes, mayDo, roleOn, SERVICE_NAME, tell, type GameBox } from "./store.ts"; | |
| 37 | import { LINES_OUT, listBoxes, mayDo, roleOn, SERVICE_NAME, type GameBox } from "./store.ts"; | |
| 37 | 38 | |
| 38 | 39 | export const CODE_MS = 10 * 60_000; |
| 39 | 40 | export const PENDING_MS = 5 * 60_000; |
| @@ -252,23 +253,70 @@ export function gameChat( | ||
| 252 | 253 | if (said === undefined || n >= A_SYNC_EACH || all >= A_SYNC) continue; |
| 253 | 254 | ran.set(said.player, n + 1); |
| 254 | 255 | all++; |
| 255 | one(app, box, service, said.player, said.words, compose, origin, now); | |
| 256 | one(app, box, { service, player: said.player, ask: "" }, said.words, compose, origin, now); | |
| 256 | 257 | } |
| 257 | 258 | } |
| 258 | 259 | })(); |
| 259 | 260 | } |
| 260 | 261 | |
| 262 | /** | |
| 263 | * The `/forge` requests in a sync (`door.ts`), each once: the same rules as chat, the same jobs. | |
| 264 | * The name and UUID are the proxy's own, so the link is held to that UUID and no server is asked | |
| 265 | * who is on. Answers the ids it took, now or before: the box deletes those and sends the rest | |
| 266 | * again. One that names no player is taken too, or it would hold those behind it. | |
| 267 | */ | |
| 268 | export function gameAsk(app: App, box: GameBox, sent: unknown, compose: string | undefined, origin: string, now = Date.now()): string[] { | |
| 269 | const { asks, nobody } = asksIn(sent); | |
| 270 | if (compose === undefined) return []; | |
| 271 | if (nobody.length > 0) app.log.warn(`game box ${box.name}: ${String(nobody.length)} /forge request(s) named no player and were dropped`); | |
| 272 | if (asks.length === 0) return nobody; | |
| 273 | const proxy = proxyOf(compose); | |
| 274 | const servers = composeServices(compose).filter((s) => s !== proxy); | |
| 275 | app.db.transaction(() => { | |
| 276 | for (const ask of asks) { | |
| 277 | const service = servers.includes(ask.server) ? ask.server : ""; | |
| 278 | if (!keepAsk(app.db, box, ask, service, now)) continue; | |
| 279 | const at: Where = { service, player: ask.player, ask: ask.id }; | |
| 280 | if (ask.confirms === "") { | |
| 281 | if (service === "") say(app.db, box, at, ["Join a server of this network first, then ask again."], ""); | |
| 282 | else one(app, box, at, ask.words, compose, origin, now, { uuid: ask.uuid, confirmed: undefined }); | |
| 283 | continue; | |
| 284 | } | |
| 285 | const confirmed = takeConfirmed(app.db, box, ask, now); | |
| 286 | if (confirmed === undefined) say(app.db, box, at, ["That is no longer waiting for your yes: ask again."], ""); | |
| 287 | else | |
| 288 | one(app, box, { ...at, service: confirmed.service }, confirmed.action === "words" ? confirmed.words : confirmed.action, compose, origin, now, { | |
| 289 | uuid: ask.uuid, | |
| 290 | confirmed, | |
| 291 | }); | |
| 292 | } | |
| 293 | })(); | |
| 294 | return [...asks.map((ask) => ask.id), ...nobody]; | |
| 295 | } | |
| 296 | ||
| 297 | /** | |
| 298 | * One command. `door` is there when it came through the proxy: the player's UUID as the proxy has | |
| 299 | * it, and what they confirmed. | |
| 300 | */ | |
| 261 | 301 | function one( |
| 262 | 302 | app: App, |
| 263 | 303 | box: GameBox, |
| 264 | service: string, | |
| 265 | player: string, | |
| 304 | at: Where, | |
| 266 | 305 | words: string, |
| 267 | 306 | compose: string, |
| 268 | 307 | origin: string, |
| 269 | 308 | now: number, |
| 309 | door?: { readonly uuid: string; readonly confirmed: Confirmed | undefined }, | |
| 270 | 310 | ): void { |
| 271 | 311 | const db = app.db; |
| 312 | const { service, player } = at; | |
| 313 | const confirmed = door?.confirmed; | |
| 314 | const uuidNow = (): string => door?.uuid ?? onlineUuid(app, box.id, service, player); | |
| 315 | // Through the proxy, what changes something or starts crew work waits for the player's code. | |
| 316 | const askFirst = (by: string, question: string, what: Confirmed): void => { | |
| 317 | audit(app, box, service, player, by, "asked", shown, "asked to confirm", now); | |
| 318 | say(db, box, at, [question], by, "gray", what); | |
| 319 | }; | |
| 272 | 320 | // A link code is never kept in clear, typed right or wrong. |
| 273 | 321 | const shown = /^link\b/i.test(words) ? "link ****" : words; |
| 274 | 322 | // A refusal is kept and answered once a minute for this name (for a whole box that is off, whose |
| @@ -279,15 +327,17 @@ function one( | ||
| 279 | 327 | `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`, |
| 280 | 328 | ) |
| 281 | 329 | .get(box.id, whole ? "" : player, new Date(now - REFUSE_MS).toISOString(), new Date(now).toISOString()); |
| 282 | if (last !== null) return; | |
| 283 | audit(app, box, service, player, by, "refused", shown, outcome, now); | |
| 284 | tell(app.db, box, service, player, [line], by, color); | |
| 330 | // Through the proxy each request is answered: its plugin holds a player to six a minute. | |
| 331 | if (last !== null && door === undefined) return; | |
| 332 | if (last === null) audit(app, box, service, player, by, "refused", shown, outcome, now); | |
| 333 | say(db, box, at, [line], by, color); | |
| 285 | 334 | }; |
| 286 | 335 | const exposed = exposedBackend(compose); |
| 287 | 336 | if (exposed !== undefined) return refuse("", `off: ${exposed}`, `!forge is off on this network: ${exposed}.`, "red", true); |
| 288 | 337 | // Linking: the code from the forge, once, within ten minutes; five wrong codes an hour a name. |
| 289 | const link = /^link\s+([A-Za-z0-9]{6})$/i.exec(words); | |
| 290 | if (link !== null) { | |
| 338 | const typed = /^link\s+([A-Za-z0-9]{6})$/i.exec(words)?.[1]; | |
| 339 | const codeHash = confirmed?.action === "link" ? confirmed.words : typed === undefined ? undefined : sha256(typed.toUpperCase()); | |
| 340 | if (codeHash !== undefined) { | |
| 291 | 341 | const failed = db |
| 292 | 342 | .query< |
| 293 | 343 | { n: number }, |
| @@ -297,15 +347,17 @@ function one( | ||
| 297 | 347 | if (failed >= FAILED_LINKS) return refuse("", "too many wrong codes", "Too many wrong codes for this name: try again in an hour."); |
| 298 | 348 | const code = db |
| 299 | 349 | .query<{ user_id: string }, [string, string]>("SELECT user_id FROM game_link_code WHERE code_hash = ?1 AND expires_at > ?2") |
| 300 | .get(sha256(link[1]!.toUpperCase()), new Date(now).toISOString()); | |
| 350 | .get(codeHash, new Date(now).toISOString()); | |
| 301 | 351 | if (code === null) { |
| 302 | 352 | audit(app, box, service, player, "", "link", "link ****", "wrong code", now); |
| 303 | return tell(app.db, box, service, player, ["That code is not one the forge gave, or it ran out: get a new one in your forge settings."], "", "red"); | |
| 353 | return say(db, box, at, ["That code is not one the forge gave, or it ran out: get a new one in your forge settings."], "", "red"); | |
| 304 | 354 | } |
| 305 | 355 | // The UUID the server lists for this name now; not listed, the code stays good for another try. |
| 306 | const uuid = onlineUuid(app, box.id, service, player); | |
| 356 | const uuid = uuidNow(); | |
| 307 | 357 | 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.`); |
| 308 | db.query("DELETE FROM game_link_code WHERE code_hash = ?1").run(sha256(link[1]!.toUpperCase())); | |
| 358 | if (door !== undefined && confirmed === undefined) | |
| 359 | return askFirst(code.user_id, `Link ${player} to the forge account ${getUserById(db, code.user_id)?.username ?? "this code is for"}?`, { action: "link", words: codeHash }); | |
| 360 | db.query("DELETE FROM game_link_code WHERE code_hash = ?1").run(codeHash); | |
| 309 | 361 | db.query("INSERT OR REPLACE INTO game_link (box_id, player, user_id, uuid, created_at) VALUES (?1, ?2, ?3, ?4, ?5)").run( |
| 310 | 362 | box.id, |
| 311 | 363 | player, |
| @@ -315,11 +367,10 @@ function one( | ||
| 315 | 367 | ); |
| 316 | 368 | const who = getUserById(db, code.user_id); |
| 317 | 369 | audit(app, box, service, player, code.user_id, "link", "link ****", "linked", now); |
| 318 | return tell( | |
| 319 | app.db, | |
| 370 | return say( | |
| 371 | db, | |
| 320 | 372 | box, |
| 321 | service, | |
| 322 | player, | |
| 373 | at, | |
| 323 | 374 | [`Linked to ${who?.username ?? "your forge account"}. Type !forge help to see what you can ask.`], |
| 324 | 375 | code.user_id, |
| 325 | 376 | "green", |
| @@ -334,12 +385,12 @@ function one( | ||
| 334 | 385 | if (linked !== null && user !== undefined) { |
| 335 | 386 | // The name is only the account's while it is the same player: the UUID the server lists for it |
| 336 | 387 | // now. |
| 337 | const uuid = onlineUuid(app, box.id, service, player); | |
| 388 | const uuid = uuidNow(); | |
| 338 | 389 | if (uuid === "") return refuse(user.id, "not seen online", `The forge does not see ${player} on ${service} yet: try again in a minute.`); |
| 339 | 390 | if (uuid !== linked.uuid) { |
| 340 | 391 | db.query("DELETE FROM game_link WHERE box_id = ?1 AND player = ?2").run(box.id, player); |
| 341 | 392 | audit(app, box, service, player, user.id, "refused", shown, "another player has the name: link dropped", now); |
| 342 | return tell(app.db, box, service, player, [`${player} was linked as another player, so that link is gone: link again with a new code.`], "", "red"); | |
| 393 | return say(db, box, at, [`${player} was linked as another player, so that link is gone: link again with a new code.`], "", "red"); | |
| 343 | 394 | } |
| 344 | 395 | } |
| 345 | 396 | if (user === undefined) |
| @@ -370,19 +421,19 @@ function one( | ||
| 370 | 421 | } |
| 371 | 422 | // Kept with its audit row, whose outcome the job writes when it is done. |
| 372 | 423 | const later = (kind: "ask" | "plan" | "yes" | "talk", said: string, sha = ""): void => { |
| 424 | if (kind === "talk" && door !== undefined && confirmed === undefined) return askFirst(user.id, `Ask the crew: "${said}"?`, { action: "words", words: said }); | |
| 373 | 425 | audit(app, box, service, player, user.id, kind, said, "waiting", now); |
| 374 | 426 | db.query( |
| 375 | "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)", | |
| 376 | ).run(box.id, service, player, user.id, kind, said, sha, origin, new Date(now).toISOString()); | |
| 427 | "INSERT INTO game_chat_job (box_id, service, player, user_id, kind, words, sha, origin, audit_id, created_at, ask_id) VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7, ?8, last_insert_rowid(), ?9, ?10)", | |
| 428 | ).run(box.id, service, player, user.id, kind, said, sha, origin, new Date(now).toISOString(), at.ask); | |
| 377 | 429 | }; |
| 378 | 430 | if (question !== undefined) return later("ask", words); |
| 379 | 431 | if (help) { |
| 380 | 432 | audit(app, box, service, player, user.id, "help", words, "told", now); |
| 381 | return tell( | |
| 382 | app.db, | |
| 433 | return say( | |
| 434 | db, | |
| 383 | 435 | box, |
| 384 | service, | |
| 385 | player, | |
| 436 | at, | |
| 386 | 437 | [ |
| 387 | 438 | "Ask: who is on? why could I not join? what does survival need? is survival asleep? what is the address?", |
| 388 | 439 | ...(mayDo(role, "operator") ? OPERATOR_HELP : []), |
| @@ -391,24 +442,28 @@ function one( | ||
| 391 | 442 | ); |
| 392 | 443 | } |
| 393 | 444 | if (lower === "no") { |
| 445 | if (door !== undefined && confirmed === undefined) return askFirst(user.id, "Drop the plan that is waiting?", { action: "words", words }); | |
| 394 | 446 | db.query("DELETE FROM game_chat_pending WHERE box_id = ?1 AND player = ?2").run(box.id, player); |
| 395 | 447 | audit(app, box, service, player, user.id, "no", words, "dropped", now); |
| 396 | return tell(app.db, box, service, player, ["Dropped."], user.id); | |
| 448 | return say(db, box, at, ["Dropped."], user.id); | |
| 397 | 449 | } |
| 398 | 450 | if (lower === "yes") { |
| 399 | 451 | // The same name, on the same server, within five minutes of the plan it answers. |
| 400 | 452 | const pending = db |
| 401 | 453 | .query< |
| 402 | { words: string; service: string; user_id: string; created_at: string; sha: string }, | |
| 454 | { words: string; service: string; user_id: string; created_at: string; sha: string; ask_id: string }, | |
| 403 | 455 | [string, string] |
| 404 | >("SELECT words, service, user_id, created_at, sha FROM game_chat_pending WHERE box_id = ?1 AND player = ?2") | |
| 456 | >("SELECT words, service, user_id, created_at, sha, ask_id FROM game_chat_pending WHERE box_id = ?1 AND player = ?2") | |
| 405 | 457 | .get(box.id, player); |
| 406 | 458 | const expired = pending !== null && now - Date.parse(pending.created_at) > PENDING_MS; |
| 407 | 459 | // A yes on another server or from another account leaves the plan where it is; an old one goes. |
| 408 | 460 | if (expired) db.query("DELETE FROM game_chat_pending WHERE box_id = ?1 AND player = ?2").run(box.id, player); |
| 409 | if (pending === null || expired || pending.service !== service || pending.user_id !== user.id) { | |
| 461 | // A plan is built by the door it was asked at: through the proxy by the confirmation of that | |
| 462 | // very request, in chat by a yes. | |
| 463 | const mine = door === undefined ? "" : confirmed?.action === "yes" ? confirmed.words : undefined; | |
| 464 | if (pending === null || expired || pending.ask_id !== mine || pending.service !== service || pending.user_id !== user.id) { | |
| 410 | 465 | audit(app, box, service, player, user.id, "yes", words, "nothing waiting", now); |
| 411 | return tell(app.db, box, service, player, ["Nothing here is waiting for your yes: ask again with !forge <what you want>."], user.id); | |
| 466 | return say(db, box, at, ["Nothing here is waiting for your yes: ask again with !forge <what you want>."], user.id); | |
| 412 | 467 | } |
| 413 | 468 | if (!changesNetwork(app, user, box)) return refuse(user.id, "not an operator of the box", notBox(user, box)); |
| 414 | 469 | db.query("DELETE FROM game_chat_pending WHERE box_id = ?1 AND player = ?2").run(box.id, player); |
| @@ -441,6 +496,8 @@ interface Job { | ||
| 441 | 496 | readonly origin: string; |
| 442 | 497 | readonly audit_id: number; |
| 443 | 498 | readonly created_at: string; |
| 499 | /** The `/forge` request it answers; "" for chat. */ | |
| 500 | readonly ask_id: string; | |
| 444 | 501 | } |
| 445 | 502 | |
| 446 | 503 | /** Each box's worker, and the jobs whose crew turn this process is waiting on. */ |
| @@ -500,11 +557,11 @@ function nextJob(app: App, boxId: string): Job | null { | ||
| 500 | 557 | } |
| 501 | 558 | |
| 502 | 559 | /** The job's end: its outcome in the audit, its words in game, and the job gone, all or nothing. */ |
| 503 | function finish(app: App, box: GameBox, job: Job, outcome: string, lines: readonly string[], color = "gray"): void { | |
| 560 | function finish(app: App, box: GameBox, job: Job, outcome: string, lines: readonly string[], color = "gray", confirm?: Confirmed): void { | |
| 504 | 561 | app.db.transaction(() => { |
| 505 | 562 | if (app.db.query("DELETE FROM game_chat_job WHERE id = ?1").run(job.id).changes === 0) return; |
| 506 | 563 | if (outcome !== "") app.db.query("UPDATE game_chat SET outcome = ?2 WHERE id = ?1").run(job.audit_id, outcome.slice(0, 300)); |
| 507 | tell(app.db, box, job.service, job.player, lines, job.user_id, color); | |
| 564 | say(app.db, box, { service: job.service, player: job.player, ask: job.ask_id }, lines, job.user_id, color, confirm); | |
| 508 | 565 | })(); |
| 509 | 566 | } |
| 510 | 567 | |
| @@ -536,9 +593,11 @@ async function runJob(app: App, box: GameBox, job: Job): Promise<void> { | ||
| 536 | 593 | return db.transaction(() => { |
| 537 | 594 | // Five minutes from when the plan is shown, however long it took to make. |
| 538 | 595 | db.query( |
| 539 | "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)", | |
| 540 | ).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); | |
| 541 | 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."]); | |
| 596 | "INSERT OR REPLACE INTO game_chat_pending (box_id, player, service, user_id, words, created_at, sha, ask_id) VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7, ?8)", | |
| 597 | ).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, job.ask_id); | |
| 598 | const lines = planned.value.lines.slice(0, LINES_OUT - 1); | |
| 599 | if (job.ask_id !== "") finish(app, box, job, "planned", lines, "gray", { action: "yes", words: job.ask_id }); | |
| 600 | else finish(app, box, job, "planned", [...lines, "Type !forge yes within 5 minutes to build it, or !forge no."]); | |
| 542 | 601 | })(); |
| 543 | 602 | } |
| 544 | 603 | // A yes whose commit began before a restart: the server being there says it landed. |
| @@ -574,7 +633,7 @@ function ask(app: App, box: GameBox, job: Job, user: User): void { | ||
| 574 | 633 | const waiting: Job = { ...job, kind: "reply", conversation: conversation.value.id }; |
| 575 | 634 | db.query("UPDATE game_chat_job SET kind = 'reply', conversation = ?2 WHERE id = ?1").run(job.id, waiting.conversation); |
| 576 | 635 | db.query("UPDATE game_chat SET outcome = ?2 WHERE id = ?1").run(job.audit_id, sent.value.how); |
| 577 | tell(app.db, box, job.service, job.player, [`Asked the crew: the answer comes here and at ${job.origin}/talk/${waiting.conversation}`], user.id); | |
| 636 | say(app.db, box, { service: job.service, player: job.player, ask: job.ask_id }, [`Asked the crew: the answer comes here and at ${job.origin}/talk/${waiting.conversation}`], user.id); | |
| 578 | 637 | const { live } = workersOf(app); |
| 579 | 638 | if (sent.value.done === undefined) return; |
| 580 | 639 | live.add(job.id); |
src/games/door.ts added +121
| @@ -0,0 +1,121 @@ | ||
| 1 | /** | |
| 2 | * The proxy's door (#17610): `/forge …`, a command of the plugin on the proxy, carried to the forge | |
| 3 | * and back by the box's agent. The rules are `!forge`'s own (`chat.ts`); this keeps what only this | |
| 4 | * door has: the requests, what each may still confirm, and the answers on their way. | |
| 5 | * | |
| 6 | * A server can show text whose click runs `/forge …` as the player. So what changes something, or | |
| 7 | * starts crew work, is answered with `confirm`: the proxy shows the player a one-time code, and | |
| 8 | * only a later request that `confirms` this one acts, once, for the same player of the same box, in | |
| 9 | * time. | |
| 10 | */ | |
| 11 | ||
| 12 | import type { Database } from "bun:sqlite"; | |
| 13 | import { tell, type GameBox } from "./store.ts"; | |
| 14 | ||
| 15 | /** Where a player typed: the server they are on, and the request when it came from the proxy. */ | |
| 16 | export interface Where { | |
| 17 | readonly service: string; | |
| 18 | readonly player: string; | |
| 19 | /** The request's id; "" for a line of chat. */ | |
| 20 | readonly ask: string; | |
| 21 | } | |
| 22 | ||
| 23 | /** | |
| 24 | * What a player confirmed: words again, a link by its code's hash, or the plan made for a request. | |
| 25 | */ | |
| 26 | export interface Confirmed { | |
| 27 | readonly action: "words" | "link" | "yes"; | |
| 28 | readonly words: string; | |
| 29 | } | |
| 30 | ||
| 31 | /** The plugin's code lives two minutes from when it is shown; a minute more carries it here. */ | |
| 32 | export const CONFIRM_MS = 3 * 60_000; | |
| 33 | const ASK_KEPT_MS = 24 * 3_600_000; | |
| 34 | /** The plugin remembers a request for an hour: a later answer would be shown to nobody. */ | |
| 35 | const TOLD_KEPT_MS = 3_600_000; | |
| 36 | const TOLD_A_SYNC = 20; | |
| 37 | const ID = /^[0-9a-f]{8}(?:-[0-9a-f]{4}){3}-[0-9a-f]{12}$/; | |
| 38 | const PLAYER = /^[.]?[A-Za-z0-9_]{1,16}$/; | |
| 39 | ||
| 40 | export interface Ask { | |
| 41 | readonly id: string; | |
| 42 | readonly uuid: string; | |
| 43 | readonly player: string; | |
| 44 | readonly server: string; | |
| 45 | readonly words: string; | |
| 46 | readonly confirms: string; | |
| 47 | } | |
| 48 | ||
| 49 | /** | |
| 50 | * The requests in a sync that have the plugin's shape, from its first 20; `nobody` are the ids of | |
| 51 | * those that name no player, so no answer can reach one. | |
| 52 | */ | |
| 53 | export function asksIn(sent: unknown): { asks: Ask[]; nobody: string[] } { | |
| 54 | const nobody: string[] = []; | |
| 55 | const asks = (Array.isArray(sent) ? sent.slice(0, 20) : []).flatMap((raw: unknown) => { | |
| 56 | const r = (typeof raw === "object" && raw !== null ? raw : {}) as Record<string, unknown>; | |
| 57 | const s = (key: string): string => (typeof r[key] === "string" ? r[key] : ""); | |
| 58 | if (!ID.test(s("id"))) return []; | |
| 59 | if (!ID.test(s("uuid")) || !PLAYER.test(s("name"))) { | |
| 60 | nobody.push(s("id")); | |
| 61 | return []; | |
| 62 | } | |
| 63 | return [{ id: s("id"), uuid: s("uuid"), player: s("name"), server: s("server"), words: s("words").replace(/[\p{Cc}§]+/gu, " ").trim().slice(0, 300), confirms: s("confirms") }]; | |
| 64 | }); | |
| 65 | return { asks, nobody }; | |
| 66 | } | |
| 67 | ||
| 68 | /** Keeps a request; false for one this box sent before. */ | |
| 69 | export function keepAsk(db: Database, box: GameBox, ask: Ask, service: string, now: number): boolean { | |
| 70 | db.query("DELETE FROM game_ask WHERE created_at < ?1").run(new Date(now - ASK_KEPT_MS).toISOString()); | |
| 71 | return ( | |
| 72 | db | |
| 73 | .query("INSERT OR IGNORE INTO game_ask (box_id, id, uuid, player, service, created_at) VALUES (?1, ?2, ?3, ?4, ?5, ?6)") | |
| 74 | .run(box.id, ask.id, ask.uuid, ask.player, service, new Date(now).toISOString()).changes > 0 | |
| 75 | ); | |
| 76 | } | |
| 77 | ||
| 78 | /** | |
| 79 | * What `ask` confirms, taken so that nothing confirms it again; undefined when there is nothing. | |
| 80 | */ | |
| 81 | export function takeConfirmed(db: Database, box: GameBox, ask: Ask, now: number): (Confirmed & { service: string }) | undefined { | |
| 82 | const found = db | |
| 83 | .query<Confirmed & { service: string }, [string, string, string, string]>( | |
| 84 | "SELECT action, words, service FROM game_ask WHERE box_id = ?1 AND id = ?2 AND uuid = ?3 AND action != '' AND shown_at > ?4", | |
| 85 | ) | |
| 86 | .get(box.id, ask.confirms, ask.uuid, new Date(now - CONFIRM_MS).toISOString()); | |
| 87 | // The row stays: the request sent again is still one seen before. | |
| 88 | if (found !== null) db.query("UPDATE game_ask SET action = '', words = '' WHERE box_id = ?1 AND id = ?2").run(box.id, ask.confirms); | |
| 89 | return found ?? undefined; | |
| 90 | } | |
| 91 | ||
| 92 | /** | |
| 93 | * Words to a player where they asked: `tellraw` for chat, the proxy's answer for `/forge`. With | |
| 94 | * `confirm` (a `/forge` request only) the player is asked first, and this is what they confirm. | |
| 95 | */ | |
| 96 | export function say(db: Database, box: Pick<GameBox, "id">, at: Where, lines: readonly string[], by: string, color = "gray", confirm?: Confirmed): void { | |
| 97 | if (at.ask === "") return tell(db, box, at.service, at.player, lines, by, color); | |
| 98 | if (confirm !== undefined) db.query("UPDATE game_ask SET action = ?3, words = ?4 WHERE box_id = ?1 AND id = ?2").run(box.id, at.ask, confirm.action, confirm.words); | |
| 99 | db.query( | |
| 100 | `INSERT INTO game_told (box_id, ask_id, uuid, text, confirm, created_at) | |
| 101 | SELECT box_id, id, uuid, ?3, ?4, ?5 FROM game_ask WHERE box_id = ?1 AND id = ?2`, | |
| 102 | ).run(box.id, at.ask, lines.join("\n").replaceAll("!forge", "/forge").slice(0, 2_000), confirm === undefined ? 0 : 1, new Date().toISOString()); | |
| 103 | } | |
| 104 | ||
| 105 | /** The answers for a box's agent to carry, each handed out once; a code's time starts here. */ | |
| 106 | export function toldTo(db: Database, box: GameBox, now = Date.now()): { id: string; uuid: string; text: string; confirm: boolean }[] { | |
| 107 | return db.transaction(() => { | |
| 108 | db.query("DELETE FROM game_told WHERE created_at < ?1").run(new Date(now - TOLD_KEPT_MS).toISOString()); | |
| 109 | const rows = db | |
| 110 | .query< | |
| 111 | { n: number; id: string; uuid: string; text: string; confirm: number }, | |
| 112 | [string, number] | |
| 113 | >("SELECT id AS n, ask_id AS id, uuid, text, confirm FROM game_told WHERE box_id = ?1 ORDER BY game_told.id LIMIT ?2") | |
| 114 | .all(box.id, TOLD_A_SYNC); | |
| 115 | for (const r of rows) { | |
| 116 | db.query("DELETE FROM game_told WHERE id = ?1").run(r.n); | |
| 117 | if (r.confirm === 1) db.query("UPDATE game_ask SET shown_at = ?3 WHERE box_id = ?1 AND id = ?2").run(box.id, r.id, new Date(now).toISOString()); | |
| 118 | } | |
| 119 | return rows.map(({ id, uuid, text, confirm }) => ({ id, uuid, text, confirm: confirm === 1 })); | |
| 120 | })(); | |
| 121 | } |
src/games/store.ts +4
| @@ -489,6 +489,8 @@ export interface SyncBody { | ||
| 489 | 489 | * `docs/features/games.md`). |
| 490 | 490 | */ |
| 491 | 491 | readonly light?: boolean; |
| 492 | /** In a light sync: the agent reads `told` in its answer. */ | |
| 493 | readonly told?: unknown; | |
| 492 | 494 | /** |
| 493 | 495 | * The agent's last full sync did not get an answer: its log lines may be ones the forge already |
| 494 | 496 | * kept. |
| @@ -498,6 +500,8 @@ export interface SyncBody { | ||
| 498 | 500 | readonly chat?: unknown; |
| 499 | 501 | /** The batch those lines are: sent again, under the same id, until a sync is answered. */ |
| 500 | 502 | readonly chatId?: unknown; |
| 503 | /** The `/forge` requests the proxy's plugin wrote (`door.ts`); one sent again is kept once. */ | |
| 504 | readonly ask?: unknown; | |
| 501 | 505 | } |
| 502 | 506 | |
| 503 | 507 | const str = (v: unknown, max = 200): string => (typeof v === "string" ? v.slice(0, max) : ""); |
src/http/games_routes.ts +11 −2
| @@ -9,7 +9,8 @@ import { synced } from "../games/notify.ts"; | ||
| 9 | 9 | import { auditShellResults } from "../games/shell.ts"; |
| 10 | 10 | import { recordMetrics } from "../games/metrics.ts"; |
| 11 | 11 | import { recordPeople } from "../games/people.ts"; |
| 12 | import { gameChat, runChat } from "../games/chat.ts"; | |
| 12 | import { gameAsk, gameChat, runChat } from "../games/chat.ts"; | |
| 13 | import { toldTo } from "../games/door.ts"; | |
| 13 | 14 | import { packChecks } from "../games/pack_check.ts"; |
| 14 | 15 | import { lendAnswer } from "../games/lend.ts"; |
| 15 | 16 | import { recordProxyEvents, tellRefused } from "../games/player_events.ts"; |
| @@ -47,7 +48,9 @@ export async function gameAgentSync(ctx: Ctx): Promise<Response> { | ||
| 47 | 48 | if (body.light === true) { |
| 48 | 49 | auditShellResults(ctx.app, box, (body.results ?? []).map((r) => r.id)); |
| 49 | 50 | synced(ctx.app, box.id); |
| 50 | return json({ commands }); | |
| 51 | // Each answer is handed out once: only to an agent that says it reads them here. | |
| 52 | const told = body.told === true ? toldTo(ctx.app.db, box) : []; | |
| 53 | return json(told.length > 0 ? { commands, told } : { commands }); | |
| 51 | 54 | } |
| 52 | 55 | // Every shell command the box answered, its output with it, into the audit. |
| 53 | 56 | auditShellResults(ctx.app, box, (body.results ?? []).map((r) => r.id)); |
| @@ -65,6 +68,8 @@ export async function gameAgentSync(ctx: Ctx): Promise<Response> { | ||
| 65 | 68 | // `!forge` said in game chat: checked and kept here; a plan, a commit or the crew is never waited |
| 66 | 69 | // for (`games/chat.ts`). |
| 67 | 70 | gameChat(ctx.app, box, body.chat, compose?.text, ctx.url.origin, Date.now(), body.chatId); |
| 71 | // The same through the proxy's `/forge` (`games/door.ts`). | |
| 72 | const asked = gameAsk(ctx.app, box, body.ask, compose?.text, ctx.url.origin); | |
| 68 | 73 | void runChat(ctx.app, box.id); |
| 69 | 74 | synced(ctx.app, box.id); |
| 70 | 75 | const reply: Record<string, unknown> = { |
| @@ -73,6 +78,10 @@ export async function gameAgentSync(ctx: Ctx): Promise<Response> { | ||
| 73 | 78 | commands, |
| 74 | 79 | }; |
| 75 | 80 | if (compose !== undefined && compose.sha !== (typeof body.composeSha === "string" ? body.composeSha : "")) reply["compose"] = signJarUrls(ctx.app, box, compose.text, ctx.url.origin); |
| 81 | // Which requests it took, whenever the box sent any: it deletes those and no other. | |
| 82 | if (Array.isArray(body.ask)) reply["asked"] = asked; | |
| 83 | const told = toldTo(ctx.app.db, box); | |
| 84 | if (told.length > 0) reply["told"] = told; | |
| 76 | 85 | // The agent this forge runs: a box whose own differs fetches it (`gameAgentScript`) and restarts. |
| 77 | 86 | reply["agentSha"] = AGENT_SHA; |
| 78 | 87 | // The runner token of "Run checks while servers sleep", once; or the word to drop it. |
test/game-chat.test.ts +2 −4
| @@ -22,6 +22,7 @@ import { accountLinks, chatCommand, chatLog, exposedBackend, gameChat, linksOf, | ||
| 22 | 22 | import { readCompose, serviceEnv } from "../src/games/compose.ts"; |
| 23 | 23 | import { boxNamed, commandHistory, createGameBox, grant, recentCommands, recordSync, type GameBox } from "../src/games/store.ts"; |
| 24 | 24 | import { forgeHttp, type ForgeHttp } from "../src/http/server.ts"; |
| 25 | import { chatAged } from "./helpers/game-chat-clock.ts"; | |
| 25 | 26 | import { quietLogs } from "./helpers/globals.ts"; |
| 26 | 27 | import { pollUntil } from "./helpers/poll.ts"; |
| 27 | 28 | |
| @@ -293,10 +294,7 @@ describe("on a forge", () => { | ||
| 293 | 294 | }); |
| 294 | 295 | }; |
| 295 | 296 | /** A minute on, for the refusals: each is answered once a minute a name. */ |
| 296 | const aMinuteOn = () => { | |
| 297 | for (const r of app.db.query<{ id: number; at: string }, []>("SELECT id, at FROM game_chat WHERE kind = 'refused'").all()) | |
| 298 | app.db.query("UPDATE game_chat SET at = ?2 WHERE id = ?1").run(r.id, new Date(Date.parse(r.at) - 61_000).toISOString()); | |
| 299 | }; | |
| 297 | const aMinuteOn = () => chatAged(app.db, 61_000, "refused"); | |
| 300 | 298 | const link = async (user: User, player: string, service = "hub") => { |
| 301 | 299 | const code = newLinkCode(app, user); |
| 302 | 300 | await sync({ [service]: [paper(player, `!forge link ${code.toLowerCase()}`)] }); |
test/game-door.test.ts added +247
| @@ -0,0 +1,247 @@ | ||
| 1 | /** | |
| 2 | * `/forge` through the proxy's plugin (#17610): the same rules as `!forge` in chat, answered to the | |
| 3 | * request; what changes something or starts crew work acts only on the same player's confirmation | |
| 4 | * of that request, once, in time; and the two doors never answer each other's plans. | |
| 5 | */ | |
| 6 | import { afterAll, beforeAll, beforeEach, expect, test } from "bun:test"; | |
| 7 | import { mkdtemp, rm } from "node:fs/promises"; | |
| 8 | import { tmpdir } from "node:os"; | |
| 9 | import { join } from "node:path"; | |
| 10 | import { commitToBranch, createRepo } from "../src/actions/repos.ts"; | |
| 11 | import { createApp, type App } from "../src/app.ts"; | |
| 12 | import { createUser, type User } from "../src/core/users.ts"; | |
| 13 | import { chatLog, gameAsk, gameChat, linksOf, newLinkCode, runChat } from "../src/games/chat.ts"; | |
| 14 | import { readCompose } from "../src/games/compose.ts"; | |
| 15 | import { CONFIRM_MS, toldTo } from "../src/games/door.ts"; | |
| 16 | import { boxNamed, createGameBox, type GameBox } from "../src/games/store.ts"; | |
| 17 | import { forgeHttp } from "../src/http/server.ts"; | |
| 18 | import { chatAged } from "./helpers/game-chat-clock.ts"; | |
| 19 | import { quietLogs } from "./helpers/globals.ts"; | |
| 20 | ||
| 21 | quietLogs(); | |
| 22 | ||
| 23 | const COMPOSE = `configs: | |
| 24 | velocity_toml: | |
| 25 | content: | | |
| 26 | [servers] | |
| 27 | hub = "hub:25565" | |
| 28 | try = ["hub"] | |
| 29 | ||
| 30 | [forced-hosts] | |
| 31 | "play.example.test" = ["hub"] | |
| 32 | ||
| 33 | services: | |
| 34 | velocity: | |
| 35 | image: itzg/mc-proxy:latest | |
| 36 | ports: ["25565:25565"] | |
| 37 | configs: | |
| 38 | - source: velocity_toml | |
| 39 | target: /config/velocity.toml | |
| 40 | environment: | |
| 41 | TYPE: VELOCITY | |
| 42 | MEMORY: 768M | |
| 43 | hub: | |
| 44 | image: itzg/minecraft-server:latest | |
| 45 | environment: | |
| 46 | TYPE: PAPER | |
| 47 | VERSION: "1.21.6" | |
| 48 | MEMORY: 1G | |
| 49 | `; | |
| 50 | const ADA = "00000000-0000-4000-8000-00000000000a"; | |
| 51 | const EVE = "00000000-0000-4000-8000-00000000000e"; | |
| 52 | ||
| 53 | let dir = ""; | |
| 54 | let app: App; | |
| 55 | let ada: User; | |
| 56 | let box: GameBox; | |
| 57 | let other: GameBox; | |
| 58 | let token = ""; | |
| 59 | let now = Date.now(); | |
| 60 | ||
| 61 | const request = (words: string, more: Record<string, unknown> = {}) => ({ id: crypto.randomUUID() as string, at: now, uuid: ADA, name: "ada", server: "hub", words, ...more }); | |
| 62 | const send = async (asks: unknown, on = box) => { | |
| 63 | gameAsk(app, on, asks, (await readCompose(app, box))!.text, "http://forge.test", now); | |
| 64 | await runChat(app, on.id); | |
| 65 | return toldTo(app.db, on, now); | |
| 66 | }; | |
| 67 | const jobs = (): number => app.db.query<{ n: number }, []>("SELECT COUNT(*) AS n FROM game_chat_job").get()!.n; | |
| 68 | const anHourOn = () => chatAged(app.db, 3_600_001); | |
| 69 | const kinds = (n: number): string[] => chatLog(app, box.id, n).map((r) => r.kind); | |
| 70 | ||
| 71 | beforeAll(async () => { | |
| 72 | dir = await mkdtemp(join(tmpdir(), "forge-game-door-")); | |
| 73 | app = createApp({ dataDir: dir, port: 0, host: "forge.test", modrinthFetch: (async () => Response.json([])) as unknown as typeof fetch }); | |
| 74 | const u = await createUser(app.db, { username: "ada", email: "[email protected]", password: "a-good-passphrase", origin: "seed", isAdmin: true, trusted: true }); | |
| 75 | if (!u.ok) throw new Error(u.error); | |
| 76 | ada = u.value; | |
| 77 | const repo = await createRepo(app, ada, { name: "net", visibility: "private" }); | |
| 78 | if (!repo.ok) throw new Error(JSON.stringify(repo)); | |
| 79 | const put = await commitToBranch(app, ada, repo.value, { message: "net", files: [{ path: "docker-compose.yml", content: COMPOSE }] }); | |
| 80 | if (!put.ok) throw new Error(JSON.stringify(put.error)); | |
| 81 | token = createGameBox(app.db, { name: "mc", repo: "ada/net" }).token; | |
| 82 | createGameBox(app.db, { name: "mc2", repo: "ada/net" }); | |
| 83 | box = boxNamed(app.db, "mc")!; | |
| 84 | other = boxNamed(app.db, "mc2")!; | |
| 85 | app.db | |
| 86 | .query("INSERT OR REPLACE INTO game_service (box_id, name, state, health, started_at, cpu_pct, mem_mib, seen_at, asleep, online_json) VALUES (?1, 'hub', 'running', '', '', 0, 0, '', 0, ?2)") | |
| 87 | .run(box.id, JSON.stringify([{ name: "ada", uuid: ADA }])); | |
| 88 | }, 30_000); | |
| 89 | beforeEach(() => { | |
| 90 | now = Date.now(); | |
| 91 | // Past what the test before spent of the account's hour. | |
| 92 | anHourOn(); | |
| 93 | }); | |
| 94 | afterAll(async () => { | |
| 95 | app.close(); | |
| 96 | await rm(dir, { recursive: true, force: true }); | |
| 97 | }); | |
| 98 | ||
| 99 | test("a link waits for the player's confirmation, then binds the proxy's UUID", async () => { | |
| 100 | const first = request(`link ${newLinkCode(app, ada)}`); | |
| 101 | expect(await send([first])).toEqual([{ id: first.id, uuid: ADA, text: "Link ada to the forge account ada?", confirm: true }]); | |
| 102 | expect(linksOf(app, box.id)).toEqual([]); | |
| 103 | const yes = request("yes", { confirms: first.id }); | |
| 104 | const [done] = await send([yes]); | |
| 105 | expect(done).toMatchObject({ id: yes.id, confirm: false }); | |
| 106 | expect(done!.text).toStartWith("Linked to ada. Type /forge help"); | |
| 107 | expect(app.db.query("SELECT uuid FROM game_link WHERE box_id = ?1 AND player = 'ada'").get(box.id)).toEqual({ uuid: ADA }); | |
| 108 | }); | |
| 109 | ||
| 110 | test("a question is answered at once, to its request, and a request sent again is kept once", async () => { | |
| 111 | const ask = request("what is the address"); | |
| 112 | const answers = await send([ask]); | |
| 113 | expect(answers).toHaveLength(1); | |
| 114 | expect(answers[0]).toMatchObject({ id: ask.id, uuid: ADA, confirm: false }); | |
| 115 | expect(answers[0]!.text).toContain("play.example.test"); | |
| 116 | expect(await send([ask])).toEqual([]); | |
| 117 | }); | |
| 118 | ||
| 119 | test("every request in a sync is answered, a repeated refusal too", async () => { | |
| 120 | const asks = Array.from({ length: 4 }, () => request("help", { uuid: EVE, name: "eve" })); | |
| 121 | expect((await send(asks)).map((a) => a.id)).toEqual(asks.map((a) => a.id)); | |
| 122 | // Refused rows stay one a minute. | |
| 123 | expect(chatLog(app, box.id, 50).filter((r) => r.player === "eve")).toHaveLength(1); | |
| 124 | }); | |
| 125 | ||
| 126 | test("crew work starts only on the same player's confirmation, on the same box, once, in time", async () => { | |
| 127 | const before = request("when does the hub restart?"); | |
| 128 | expect(await send([before])).toEqual([{ id: before.id, uuid: ADA, text: 'Ask the crew: "when does the hub restart?"?', confirm: true }]); | |
| 129 | const refused = "That is no longer waiting for your yes: ask again."; | |
| 130 | const confirm = (more: Record<string, unknown> = {}) => request("yes", { confirms: before.id, ...more }); | |
| 131 | expect((await send([confirm({ uuid: EVE, name: "eve" })]))[0]!.text).toBe(refused); | |
| 132 | expect((await send([confirm()], other))[0]!.text).toBe(refused); | |
| 133 | expect((await send([confirm({ confirms: crypto.randomUUID() })]))[0]!.text).toBe(refused); | |
| 134 | expect(kinds(1)).toEqual(["asked"]); | |
| 135 | // In time: queued without running the crew. | |
| 136 | gameAsk(app, box, [confirm()], COMPOSE, "http://forge.test", now); | |
| 137 | expect(jobs()).toBe(1); | |
| 138 | expect(kinds(1)).toEqual(["talk"]); | |
| 139 | app.db.query("DELETE FROM game_chat_job").run(); | |
| 140 | expect((await send([confirm()]))[0]!.text).toBe(refused); | |
| 141 | // The confirmed request sent again by the box starts nothing over. | |
| 142 | expect(await send([before])).toEqual([]); | |
| 143 | expect((await send([confirm()]))[0]!.text).toBe(refused); | |
| 144 | ||
| 145 | anHourOn(); | |
| 146 | const late = request("when does the hub restart?"); | |
| 147 | await send([late]); | |
| 148 | app.db.query("UPDATE game_ask SET shown_at = ?2 WHERE id = ?1").run(late.id, new Date(now - CONFIRM_MS - 1).toISOString()); | |
| 149 | expect((await send([request("yes", { confirms: late.id })]))[0]!.text).toBe(refused); | |
| 150 | expect(jobs()).toBe(0); | |
| 151 | }); | |
| 152 | ||
| 153 | test("a typed yes builds nothing; the plan's own confirmation does, and chat's yes is not it", async () => { | |
| 154 | const plan = request("give me a flat world called build"); | |
| 155 | const [shown] = await send([plan]); | |
| 156 | expect(shown).toMatchObject({ id: plan.id, confirm: true }); | |
| 157 | expect(shown!.text).toStartWith("Adds build: "); | |
| 158 | expect(shown!.text).not.toContain("within 5 minutes"); | |
| 159 | expect((await send([request("yes")]))[0]!.text).toStartWith("Nothing here is waiting"); | |
| 160 | gameChat(app, box, { hub: ["[12:00:01] [Async Chat Thread - #3/INFO]: <ada> !forge yes"] }, COMPOSE, "http://forge.test", now); | |
| 161 | expect(jobs()).toBe(0); | |
| 162 | expect(chatLog(app, box.id, 1)[0]).toMatchObject({ kind: "yes", outcome: "nothing waiting" }); | |
| 163 | const [built] = await send([request("yes", { confirms: plan.id })]); | |
| 164 | expect(built!.text).toContain("The box brings it up on its next sync."); | |
| 165 | expect((await readCompose(app, box))!.text).toContain("\n build:\n"); | |
| 166 | }, 30_000); | |
| 167 | ||
| 168 | test("a plan through the proxy takes the place of chat's, and chat's yes does not build it", async () => { | |
| 169 | const say = async (words: string) => { | |
| 170 | gameChat(app, box, { hub: [`[12:00:01] [Async Chat Thread - #3/INFO]: <ada> !forge ${words}`] }, COMPOSE, "http://forge.test", now); | |
| 171 | await runChat(app, box.id); | |
| 172 | }; | |
| 173 | await say("give me a flat world called mine"); | |
| 174 | await send([request("give me a flat world called theirs")]); | |
| 175 | await say("yes"); | |
| 176 | expect(chatLog(app, box.id, 1)[0]).toMatchObject({ kind: "yes", outcome: "nothing waiting" }); | |
| 177 | expect((await readCompose(app, box))!.text).not.toContain("theirs"); | |
| 178 | }, 30_000); | |
| 179 | ||
| 180 | test("what does not have the plugin's shape is dropped; a server that is not the network's is told", async () => { | |
| 181 | expect(await send("x")).toEqual([]); | |
| 182 | expect(await send([null, 1, {}, request("help", { id: "../a" }), request("help", { uuid: "u" }), request("help", { name: "a b" })])).toEqual([]); | |
| 183 | expect((await send([request("help", { server: "velocity" })]))[0]!.text).toStartWith("Join a server"); | |
| 184 | }); | |
| 185 | ||
| 186 | test("another player with the linked name is refused and the link goes", async () => { | |
| 187 | expect((await send([request("help", { uuid: EVE })]))[0]!.text).toContain("linked as another player"); | |
| 188 | expect(linksOf(app, box.id)).toEqual([]); | |
| 189 | }); | |
| 190 | ||
| 191 | test("the forge says which requests it took, so the box deletes no other", async () => { | |
| 192 | const take = (asks: unknown, compose: string | null = COMPOSE) => gameAsk(app, box, asks, compose ?? undefined, "http://forge.test", now); | |
| 193 | const asks = Array.from({ length: 21 }, () => request("help", { uuid: EVE, name: "eve" })); | |
| 194 | // The 21st is past what one sync reads: not taken, and taken when it comes again. | |
| 195 | expect(take(asks)).toEqual(asks.slice(0, 20).map((a) => a.id)); | |
| 196 | expect(take([asks[20]])).toEqual([asks[20]!.id]); | |
| 197 | // One sent again was taken before. | |
| 198 | expect(take([asks[0]])).toEqual([asks[0]!.id]); | |
| 199 | for (let n = 0; n < 3; n++) toldTo(app.db, box, now); | |
| 200 | // No compose file could be read: nothing is taken, and the same request is answered later. | |
| 201 | const waits = request("help"); | |
| 202 | expect(take([waits], null)).toEqual([]); | |
| 203 | expect((await send([waits])).map((a) => a.id)).toEqual([waits.id]); | |
| 204 | // Nobody to answer: taken all the same, so it does not hold the ones behind it. No id, not named. | |
| 205 | const nobody = request("help", { uuid: "u" }); | |
| 206 | expect(take([nobody, request("help", { id: "../a" }), null])).toEqual([nobody.id]); | |
| 207 | expect(toldTo(app.db, box, now)).toEqual([]); | |
| 208 | }); | |
| 209 | ||
| 210 | test("a request over the account's limit is taken and its player is told", async () => { | |
| 211 | await send([request(`link ${newLinkCode(app, ada)}`)]).then(([a]) => send([request("yes", { confirms: a!.id })])); | |
| 212 | const asks = Array.from({ length: 7 }, () => request("what is the address")); | |
| 213 | const taken = gameAsk(app, box, asks, COMPOSE, "http://forge.test", now); | |
| 214 | expect(taken).toEqual(asks.map((a) => a.id)); | |
| 215 | await runChat(app, box.id); | |
| 216 | const told = toldTo(app.db, box, now); | |
| 217 | expect(told.map((a) => a.id).sort()).toEqual([...taken].sort()); | |
| 218 | expect(told.some((a) => a.text.includes("play.example.test"))).toBe(true); | |
| 219 | expect(told.some((a) => /commands a minute|try again/i.test(a.text))).toBe(true); | |
| 220 | }); | |
| 221 | ||
| 222 | test("the sync carries a request in and its answer out, once", async () => { | |
| 223 | const ask = request("help"); | |
| 224 | const sync = async (more: object) => { | |
| 225 | const res = await forgeHttp(app).handle( | |
| 226 | new Request("http://forge.test/api/v1/games/agent/sync", { | |
| 227 | method: "POST", | |
| 228 | headers: { authorization: `Bearer ${token}`, "content-type": "application/json" }, | |
| 229 | body: JSON.stringify({ agent: 1, ...more }), | |
| 230 | }), | |
| 231 | ); | |
| 232 | expect(res.status).toBe(200); | |
| 233 | const { told, asked } = (await res.json()) as { told?: { id: string }[]; asked?: string[] }; | |
| 234 | return { told: told?.map((a) => a.id), asked }; | |
| 235 | }; | |
| 236 | expect(await sync({ ask: [ask] })).toEqual({ told: [ask.id], asked: [ask.id] }); | |
| 237 | expect(await sync({ ask: [ask] })).toEqual({ told: undefined, asked: [ask.id] }); | |
| 238 | expect(await sync({ ask: [null] })).toEqual({ told: undefined, asked: [] }); | |
| 239 | expect(await sync({})).toEqual({ told: undefined, asked: undefined }); | |
| 240 | ||
| 241 | // The quick poll hands answers only to an agent that says it reads them there. | |
| 242 | const next = request("help"); | |
| 243 | gameAsk(app, box, [next], COMPOSE, "http://forge.test", now); | |
| 244 | expect((await sync({ light: true })).told).toBeUndefined(); | |
| 245 | expect((await sync({ light: true, told: true })).told).toEqual([next.id]); | |
| 246 | expect((await sync({ light: true, told: true })).told).toBeUndefined(); | |
| 247 | }); |
test/helpers/game-chat-clock.ts added +7
| @@ -0,0 +1,7 @@ | ||
| 1 | /** A box's chat audit made older, as if `ms` had passed: for limits counted from its rows. */ | |
| 2 | import type { Database } from "bun:sqlite"; | |
| 3 | ||
| 4 | export function chatAged(db: Database, ms: number, kind = ""): void { | |
| 5 | for (const r of db.query<{ id: number; at: string }, [string]>("SELECT id, at FROM game_chat WHERE ?1 = '' OR kind = ?1").all(kind)) | |
| 6 | db.query("UPDATE game_chat SET at = ?2 WHERE id = ?1").run(r.id, new Date(Date.parse(r.at) - ms).toISOString()); | |
| 7 | } |
new above
offline
Duplicate of
aMinuteOnin test/game-chat.test.ts. Share one helper from test/helpers/.