Public: anyone can read this; the crew can change it.
Game door: a read-only switch and a one-hour write window the owner opens with a second factor #18304
Merged 4h 49m ago, live in production
mason/forge:mason/18296-game-door-a-read-only-switch-and-a-one-h → main 0 commits fork 2 threads · 2 unresolved
22 files
changed +656
−61
- docs/features/games.md
- src/actions/account_close.ts
- src/actions/passkey_proof.ts
- src/contract/openapi/routes/index.ts
- src/contract/openapi/routes/postGamesBoxDoorOptions.ts
- src/core/account_purge.ts
- src/core/migration-pins/20261204212305-game-door-window.pin
- src/core/migrations/20261204212305-game-door-window.ts
- src/games/chat.ts
- src/games/door_hold.ts
- src/games/write_window.ts
- src/http/games_routes.ts
- src/http/lazy_lists.ts
- src/tui/screens/games.ts
- src/web/pages/account.ts
- src/web/pages/games.ts
- src/web/pages/games_door.ts
- src/web/passkey-client.ts
- test/game-chat.test.ts
- test/game-door.test.ts
- test/game-write-window.test.ts
- test/openapi-drift.test.ts
docs/features/games.md +3
| @@ -93,6 +93,7 @@ A linked name that holds any role on the server it types on, viewer too, can ask | ||
| 93 | 93 | A linked name that holds operator on the server it types on can also say: |
| 94 | 94 | |
| 95 | 95 | - `!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; preview 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. |
| 96 | - `!forge lock`: the game door only reads from now on (see The write window below). It shuts the whole box, so it takes an operator of the box (a viewer, or an operator of one server only, is refused), and no code through the proxy: a line that makes a player type it only stops writes. | |
| 96 | 97 | - `!forge help`. |
| 97 | 98 | - `!forge <anything else>`: a 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. Through the proxy's `/forge` the words go to Talk at once, with no confirmation first. A linked player is that account (the proxy checks the Minecraft account, and the link binds its UUID). The conversation is limited to reads and the held `games` tool (#18218): whatever the words say, the crew cannot close, assign, edit, merge, write a file or tell from it; it says what it found and the change is made on the forge's own page. The limit stays on that conversation if the person later writes in it on the web, and covers conversations the game door opened before the limit existed. The proxy's own confirmation (the player's code) stays for what the door itself does: linking, dropping a plan, building a new server. The player's next words continue the same conversation on that box, and the answer's last line is the link ("Open in Talk"). `/forge clear` ends it: the next words start a new one. Any role on the server may clear: it removes only that account's own pointer on that box, never a conversation or another account's. If the kept conversation is gone (archived or deleted), the next words start a new one and say so. |
| 98 | 99 | |
| @@ -112,6 +113,8 @@ A player is known by the UUID the proxy authenticated. That holds where the prox | ||
| 112 | 113 | |
| 113 | 114 | 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. |
| 114 | 115 | |
| 116 | **The write window (#18296).** A game session changes things only while the box's owner has opened a write window. The door starts closed. On `/games/<box>`, the owner's Game door block says how it stands, and **Allow writes from the game for 60 minutes** opens a window: it asks for one of the owner's passkeys (a password does not open it; with no passkey the block links to Settings → Passkeys). The length is a setting beside it, 5 to 720 minutes, an hour unless set, with why: long enough to build, short enough that a forgotten window closes by itself. A window ends at its time with nothing to sweep it. Outside a window a build asked in game (`/forge yes`, `!forge yes`) is not run: it is held as a confirm of the `games` tool's `create_server` in the player's game conversation on that box, answered on the forge (the conversation's Do it, Settings → Confirms) by the player, within its 10 minutes; the yes runs the tool with all its own checks. **Lock now** on the page, `w` on the terminal's box screen (`src/tui/screens/games.ts`) and `/forge lock` in game lock the door at once: an open window ends, and a build is refused, not held, until the owner opens a window again. The window is asked for at the yes and again right before the commit, so a lock while a plan is being made stops it. Reads, questions, plans and Talk are never gated: Talk's turns from the game were already limited to reads and the held `games` tool. Every command kept in `game_chat` says its door and player, and a write also its window (`write_window`: when the window it used was opened, or `closed` or `locked`); the owner's list of commands on the page shows it. The state is `game_door` (`src/games/write_window.ts`); the hold is `src/games/door_hold.ts`; the block and its two posts are `src/web/pages/games_door.ts`, and the terminal's door is the box screen in `src/tui/screens/games.ts`. | |
| 117 | ||
| 115 | 118 | 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. |
| 116 | 119 | |
| 117 | 120 | 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/actions/account_close.ts −39
| @@ -11,8 +11,6 @@ | ||
| 11 | 11 | |
| 12 | 12 | import type { Database } from "bun:sqlite"; |
| 13 | 13 | import type { App } from "../app.ts"; |
| 14 | import { challenges, verifyAssertion } from "../auth/webauthn.ts"; | |
| 15 | import { findPasskey, notePasskeyUsed, passkeyIds } from "../core/passkeys.ts"; | |
| 16 | 14 | import { hasPassword, verifyPasswordThrottled, type User } from "../core/users.ts"; |
| 17 | 15 | import { signOutElsewhere, signOutEveryBrowser } from "./signins.ts"; |
| 18 | 16 | |
| @@ -164,22 +162,6 @@ export async function askToClose( | ||
| 164 | 162 | return { ok: true, at: closeRequestedAt(app.db, user.id)! }; |
| 165 | 163 | } |
| 166 | 164 | |
| 167 | /* | |
| 168 | * A passkey confirms a close as a password does: the page asks for a | |
| 169 | * challenge, the browser signs it, and the signed answer rides back in the | |
| 170 | * close form's hidden fields, so the close stays one plain post. A challenge | |
| 171 | * answers once, and the key must be one of this person's. | |
| 172 | */ | |
| 173 | const closeChallenges = new WeakMap<App, ReturnType<typeof challenges>>(); | |
| 174 | function closeStore(app: App): ReturnType<typeof challenges> { | |
| 175 | let s = closeChallenges.get(app); | |
| 176 | if (s === undefined) closeChallenges.set(app, (s = challenges())); | |
| 177 | return s; | |
| 178 | } | |
| 179 | ||
| 180 | /** The hidden fields the signed answer fills, by name. */ | |
| 181 | export const PROOF_FIELDS = ["challenge", "id", "clientDataJSON", "authenticatorData", "signature"] as const; | |
| 182 | ||
| 183 | 165 | /** |
| 184 | 166 | * What the close block needs to know, in one statement: the request, and which proofs this person |
| 185 | 167 | * has. |
| @@ -203,27 +185,6 @@ export function closeStanding(db: Database, userId: string): CloseStanding { | ||
| 203 | 185 | return { at: r?.at ?? null, held: r?.held === 1, password: r?.password === 1, passkey: r?.passkey === 1 }; |
| 204 | 186 | } |
| 205 | 187 | |
| 206 | /** A fresh challenge for this person, and the keys that may answer it. */ | |
| 207 | export function closeChallenge(app: App, userId: string): { challenge: string; allow: string[] } { | |
| 208 | return { challenge: closeStore(app).issue(userId), allow: passkeyIds(app.db, userId) }; | |
| 209 | } | |
| 210 | ||
| 211 | /** True when `answer` is a fresh challenge signed by one of `userId`'s passkeys. */ | |
| 212 | export async function passkeyProves( | |
| 213 | app: App, | |
| 214 | userId: string, | |
| 215 | answer: Readonly<Record<(typeof PROOF_FIELDS)[number], string>>, | |
| 216 | rp: { readonly origin: string; readonly rpId: string }, | |
| 217 | ): Promise<boolean> { | |
| 218 | if (!closeStore(app).consume(answer.challenge)) return false; | |
| 219 | const found = findPasskey(app.db, answer.id); | |
| 220 | if (found === undefined || found.userId !== userId) return false; | |
| 221 | const verified = await verifyAssertion(answer, { challenge: answer.challenge, ...rp }, found.credential); | |
| 222 | if (!verified.ok) return false; | |
| 223 | notePasskeyUsed(app.db, found.id, verified.signCount); | |
| 224 | return true; | |
| 225 | } | |
| 226 | ||
| 227 | 188 | /** The other admins who can still sign in and are not closing themselves. */ |
| 228 | 189 | function otherAdmins(db: Database, userId: string): number { |
| 229 | 190 | return ( |
src/actions/passkey_proof.ts added +41
| @@ -0,0 +1,41 @@ | ||
| 1 | /** | |
| 2 | * A passkey as a second factor for one action (closing an account, #15619; opening the game door's | |
| 3 | * write window, #18296): the page asks for a challenge, the browser signs it, and the signed answer | |
| 4 | * rides back in the form's hidden fields, so the action stays one plain post. A challenge answers | |
| 5 | * once, within five minutes, and the key must be one of this person's. | |
| 6 | */ | |
| 7 | ||
| 8 | import type { App } from "../app.ts"; | |
| 9 | import { challenges, verifyAssertion } from "../auth/webauthn.ts"; | |
| 10 | import { findPasskey, notePasskeyUsed, passkeyIds } from "../core/passkeys.ts"; | |
| 11 | ||
| 12 | const proofChallenges = new WeakMap<App, ReturnType<typeof challenges>>(); | |
| 13 | function proofStore(app: App): ReturnType<typeof challenges> { | |
| 14 | let s = proofChallenges.get(app); | |
| 15 | if (s === undefined) proofChallenges.set(app, (s = challenges())); | |
| 16 | return s; | |
| 17 | } | |
| 18 | ||
| 19 | /** The hidden fields the signed answer fills, by name. */ | |
| 20 | export const PROOF_FIELDS = ["challenge", "id", "clientDataJSON", "authenticatorData", "signature"] as const; | |
| 21 | ||
| 22 | /** A fresh challenge for this person, and the keys that may answer it. */ | |
| 23 | export function proofChallenge(app: App, userId: string): { challenge: string; allow: string[] } { | |
| 24 | return { challenge: proofStore(app).issue(userId), allow: passkeyIds(app.db, userId) }; | |
| 25 | } | |
| 26 | ||
| 27 | /** True when `answer` is a fresh challenge signed by one of `userId`'s passkeys. */ | |
| 28 | export async function passkeyProves( | |
| 29 | app: App, | |
| 30 | userId: string, | |
| 31 | answer: Readonly<Record<(typeof PROOF_FIELDS)[number], string>>, | |
| 32 | rp: { readonly origin: string; readonly rpId: string }, | |
| 33 | ): Promise<boolean> { | |
| 34 | if (!proofStore(app).consume(answer.challenge)) return false; | |
| 35 | const found = findPasskey(app.db, answer.id); | |
| 36 | if (found === undefined || found.userId !== userId) return false; | |
| 37 | const verified = await verifyAssertion(answer, { challenge: answer.challenge, ...rp }, found.credential); | |
| 38 | if (!verified.ok) return false; | |
| 39 | notePasskeyUsed(app.db, found.id, verified.signCount); | |
| 40 | return true; | |
| 41 | } |
src/contract/openapi/routes/index.ts +1
| @@ -543,6 +543,7 @@ export { route as postApiV1UserOriginsIdSync } from "./postApiV1UserOriginsIdSyn | ||
| 543 | 543 | export { route as postApiV1UserOriginsOauth } from "./postApiV1UserOriginsOauth.ts"; |
| 544 | 544 | export { route as postApiV1UserPassword } from "./postApiV1UserPassword.ts"; |
| 545 | 545 | export { route as postApiV1Users } from "./postApiV1Users.ts"; |
| 546 | export { route as postGamesBoxDoorOptions } from "./postGamesBoxDoorOptions.ts"; | |
| 546 | 547 | export { route as postMcp } from "./postMcp.ts"; |
| 547 | 548 | export { route as postSettingsAccountCloseOptions } from "./postSettingsAccountCloseOptions.ts"; |
| 548 | 549 | export { route as putApiV1AdminBillingLinks } from "./putApiV1AdminBillingLinks.ts"; |
src/contract/openapi/routes/postGamesBoxDoorOptions.ts added +13
| @@ -0,0 +1,13 @@ | ||
| 1 | import type { Route } from "../shared.ts"; | |
| 2 | ||
| 3 | export const route: Route = { | |
| 4 | method: "post", | |
| 5 | path: "/games/{box}/door/options", | |
| 6 | summary: "A passkey challenge to open a box's game door (browser session, same origin)", | |
| 7 | detail: | |
| 8 | "Issues a one-use challenge and the ids of the owner's passkeys; the signed answer goes into the open form at /games/{box} (#18296).", | |
| 9 | auth: false, | |
| 10 | role: "member", | |
| 11 | reply: { challenge: "string", allow: "array", rpId: "string" }, | |
| 12 | errorStatus: { 403: "Not the box's owner, or the request came from another origin" }, | |
| 13 | }; |
src/core/account_purge.ts +3
| @@ -64,6 +64,9 @@ export const COVERED: Readonly<Record<string, Coverage>> = { | ||
| 64 | 64 | "game_client_link.created_by": DELETE, |
| 65 | 65 | // The !forge audit keeps what was said and what came of it; who said it becomes a former member. |
| 66 | 66 | "game_chat.user_id": FORMER, |
| 67 | // Who opened or locked a box's game door (#18296): the box's state, kept, as the former account. | |
| 68 | "game_door.opened_by": FORMER, | |
| 69 | "game_door.locked_by": FORMER, | |
| 67 | 70 | "account_ceiling.set_by": FORMER, |
| 68 | 71 | // The cloud audit is shared history of what was called and by whom: it keeps the line, as the |
| 69 | 72 | // former account. |
src/core/migration-pins/20261204212305-game-door-window.pin added +1
| @@ -0,0 +1,1 @@ | ||
| 1 | bff84fc15879e293841702f58f67fef180c3e52f0c3a6c340bd1db48770b3bd3 |
src/core/migrations/20261204212305-game-door-window.ts added +17
| @@ -0,0 +1,17 @@ | ||
| 1 | // The game door's write window (#18296): one row per box whose owner set its length, opened a | |
| 2 | // window with a passkey, or locked the door. Absent means the default: no window open, writes held, | |
| 3 | // an hour when one is opened. Every game-door command now says which window it used | |
| 4 | // (`game_chat.write_window`: the window's opening instant, 'closed' or 'locked'; '' for one that | |
| 5 | // writes nothing). Additive. | |
| 6 | export default ` | |
| 7 | CREATE TABLE IF NOT EXISTS game_door ( | |
| 8 | box_id TEXT PRIMARY KEY, | |
| 9 | minutes INTEGER NOT NULL DEFAULT 60, | |
| 10 | opened_at TEXT NOT NULL DEFAULT '', | |
| 11 | open_until TEXT NOT NULL DEFAULT '', | |
| 12 | opened_by TEXT NOT NULL DEFAULT '', | |
| 13 | locked_at TEXT NOT NULL DEFAULT '', | |
| 14 | locked_by TEXT NOT NULL DEFAULT '' | |
| 15 | ) WITHOUT ROWID; | |
| 16 | ALTER TABLE game_chat ADD COLUMN write_window TEXT NOT NULL DEFAULT ''; | |
| 17 | `; |
src/games/chat.ts +49 −9
| @@ -37,6 +37,8 @@ import { sha256 } from "../kernel/hash.ts"; | ||
| 37 | 37 | import { answerTo, questionOf, serversSeen } from "./ask.ts"; |
| 38 | 38 | import { composeServices, readCompose, serviceEnv } from "./compose.ts"; |
| 39 | 39 | import { asksIn, keepAsk, say, takeConfirmed, type Confirmed, type Where } from "./door.ts"; |
| 40 | import { holdBuild, type Holding } from "./door_hold.ts"; | |
| 41 | import { doorOf, lockDoor, windowUsed } from "./write_window.ts"; | |
| 40 | 42 | import { readLines, readOf } from "./forge_read.ts"; |
| 41 | 43 | import { commitServer, planServer, wishOn } from "./presets.ts"; |
| 42 | 44 | import { peopleOf } from "./people.ts"; |
| @@ -197,12 +199,12 @@ export const chatLog = ( | ||
| 197 | 199 | app: App, |
| 198 | 200 | boxId: string, |
| 199 | 201 | limit = 20, |
| 200 | ): { service: string; player: string; kind: string; words: string; outcome: string; at: string; door: string }[] => | |
| 202 | ): { service: string; player: string; kind: string; words: string; outcome: string; at: string; door: string; window: string }[] => | |
| 201 | 203 | app.db |
| 202 | 204 | .query< |
| 203 | { service: string; player: string; kind: string; words: string; outcome: string; at: string; door: string }, | |
| 205 | { service: string; player: string; kind: string; words: string; outcome: string; at: string; door: string; window: string }, | |
| 204 | 206 | [string, number] |
| 205 | >("SELECT service, player, kind, words, outcome, at, door FROM game_chat WHERE box_id = ?1 ORDER BY id DESC LIMIT ?2") | |
| 207 | >("SELECT service, player, kind, words, outcome, at, door, write_window AS window FROM game_chat WHERE box_id = ?1 ORDER BY id DESC LIMIT ?2") | |
| 206 | 208 | .all(boxId, limit); |
| 207 | 209 | |
| 208 | 210 | const audit = ( |
| @@ -214,10 +216,11 @@ const audit = ( | ||
| 214 | 216 | words: string, |
| 215 | 217 | outcome: string, |
| 216 | 218 | now: number, |
| 219 | window = "", | |
| 217 | 220 | ): void => { |
| 218 | 221 | app.db |
| 219 | .query("INSERT INTO game_chat (box_id, service, player, user_id, kind, words, outcome, at, door) VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7, ?8, ?9)") | |
| 220 | .run(box.id, at.service, at.player, userId, kind, words.slice(0, 300), outcome.slice(0, 300), new Date(now).toISOString(), at.ask === "" ? "" : "proxy"); | |
| 222 | .query("INSERT INTO game_chat (box_id, service, player, user_id, kind, words, outcome, at, door, write_window) VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7, ?8, ?9, ?10)") | |
| 223 | .run(box.id, at.service, at.player, userId, kind, words.slice(0, 300), outcome.slice(0, 300), new Date(now).toISOString(), at.ask === "" ? "" : "proxy", window); | |
| 221 | 224 | }; |
| 222 | 225 | |
| 223 | 226 | /** What there is, for someone not linked: nothing of this box or its network. */ |
| @@ -229,6 +232,7 @@ const OPERATOR_HELP = [ | ||
| 229 | 232 | "!forge give me a new void world with FAWE and bedwars: plans it, then !forge yes builds it.", |
| 230 | 233 | "!forge <anything else>: asks the crew; the answer comes here. !forge clear: ends that conversation.", |
| 231 | 234 | "!forge no: drops a plan. !forge link <code>: links this name (a code from your forge settings).", |
| 235 | "!forge lock: the game door only reads until the box's owner opens a write window on the forge.", | |
| 232 | 236 | ]; |
| 233 | 237 | |
| 234 | 238 | /** What `help` says to someone with `role`; through the proxy it names the two reads too. */ |
| @@ -470,8 +474,8 @@ function one( | ||
| 470 | 474 | return refuse(user.id, "rate limited", `At most ${most} an hour: try again in ${again}.`); |
| 471 | 475 | } |
| 472 | 476 | // Kept with its audit row, whose outcome the job writes when it is done. |
| 473 | const later = (kind: "ask" | "read" | "plan" | "yes" | "talk", said: string, sha = ""): void => { | |
| 474 | audit(app, box, at, user.id, kind, said, "waiting", now); | |
| 477 | const later = (kind: "ask" | "read" | "plan" | "yes" | "talk", said: string, sha = "", window = ""): void => { | |
| 478 | audit(app, box, at, user.id, kind, said, "waiting", now, window); | |
| 475 | 479 | db.query( |
| 476 | 480 | "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)", |
| 477 | 481 | ).run(box.id, service, player, user.id, kind, said, sha, origin, new Date(now).toISOString(), at.ask); |
| @@ -493,6 +497,14 @@ function one( | ||
| 493 | 497 | audit(app, box, at, user.id, "clear", words, "cleared", now); |
| 494 | 498 | return say(db, box, at, ["Cleared: your next words start a new conversation."], user.id); |
| 495 | 499 | } |
| 500 | if (lower === "lock") { | |
| 501 | // Locking only stops writes, so it needs no code through the proxy: a line that makes a player | |
| 502 | // type it does no harm. It locks the whole box, so it takes an operator of the box. | |
| 503 | if (!changesNetwork(app, user, box)) return refuse(user.id, "not an operator of the box", notBox(user, box)); | |
| 504 | const locked = lockDoor(db, box.id, user.id, now); | |
| 505 | audit(app, box, at, user.id, "lock", words, "locked", now, windowUsed(locked)); | |
| 506 | return say(db, box, at, ["Locked: the game door only reads now. Its owner opens a write window on the forge, with a passkey."], user.id, "green"); | |
| 507 | } | |
| 496 | 508 | if (lower === "no") { |
| 497 | 509 | if (door !== undefined && confirmed === undefined) return askFirst(user.id, "Drop the plan that is waiting?", { action: "words", words }); |
| 498 | 510 | db.query("DELETE FROM game_chat_pending WHERE box_id = ?1 AND player = ?2").run(box.id, player); |
| @@ -518,8 +530,12 @@ function one( | ||
| 518 | 530 | return say(db, box, at, ["Nothing here is waiting for your yes: ask again with !forge <what you want>."], user.id); |
| 519 | 531 | } |
| 520 | 532 | if (!changesNetwork(app, user, box)) return refuse(user.id, "not an operator of the box", notBox(user, box)); |
| 533 | // A write runs only inside the owner's window (#18296): locked, it is refused; closed, held. | |
| 534 | const gate = doorOf(db, box.id, now); | |
| 535 | if (gate.state === "locked") return refuse(user.id, "door locked", LOCKED_LINE); | |
| 521 | 536 | db.query("DELETE FROM game_chat_pending WHERE box_id = ?1 AND player = ?2").run(box.id, player); |
| 522 | return later("yes", pending.words, pending.sha); | |
| 537 | if (gate.state === "closed") return held(app, box, at, user.id, pending.words, pending.sha, origin, now); | |
| 538 | return later("yes", pending.words, pending.sha, windowUsed(gate)); | |
| 523 | 539 | } |
| 524 | 540 | if (asksForServer(words)) { |
| 525 | 541 | if (!changesNetwork(app, user, box)) return refuse(user.id, "not an operator of the box", notBox(user, box)); |
| @@ -528,6 +544,22 @@ function one( | ||
| 528 | 544 | later("talk", words); |
| 529 | 545 | } |
| 530 | 546 | |
| 547 | /** Said when the door is locked and a write is asked. */ | |
| 548 | const LOCKED_LINE = "The game door is locked, so nothing was changed: do it on the forge, or its owner opens a write window there."; | |
| 549 | ||
| 550 | /** Where a held write is answered, in game. */ | |
| 551 | const heldSays = (h: Holding, origin: string): string[] => | |
| 552 | h.ok | |
| 553 | ? [`Held: ${h.does}`, `The game door is closed for writes. Say yes on the forge within 10 minutes: ${origin}/talk/${h.conversation}`] | |
| 554 | : [`Not held: ${h.error}. Do it on the forge.`]; | |
| 555 | ||
| 556 | /** A write asked outside the window: held for the player's yes on the forge, with its audit row. */ | |
| 557 | function held(app: App, box: GameBox, at: Where, userId: string, words: string, sha: string, origin: string, now: number): void { | |
| 558 | const holding = holdBuild(app.db, box, userId, words, sha, now); | |
| 559 | audit(app, box, at, userId, "yes", words, holding.ok ? "held for a yes on the forge" : holding.error, now, "closed"); | |
| 560 | say(app.db, box, at, heldSays(holding, publicOrigin(app.config.url, origin)), userId, holding.ok ? "gray" : "red"); | |
| 561 | } | |
| 562 | ||
| 531 | 563 | /** |
| 532 | 564 | * A new server changes the whole network (its compose file, the proxy, the box's memory), so it |
| 533 | 565 | * takes operator of the box, as the page's form and create_server do: never of one server alone. |
| @@ -675,9 +707,17 @@ async function runJob(app: App, box: GameBox, job: Job): Promise<void> { | ||
| 675 | 707 | const wish = await wishOn(app, box, job.words); |
| 676 | 708 | const planned = await planServer(app, box, wish); |
| 677 | 709 | if (!planned.ok) return finish(app, box, job, planned.error, [`Not built: ${planned.error}`], "red"); |
| 678 | // The plan took a while: the grant is asked for once more, right before the commit. | |
| 710 | // The plan took a while: the grant and the window are asked for once more, right before the | |
| 711 | // commit. | |
| 679 | 712 | const still = getUserById(db, user.id); |
| 680 | 713 | if (still === undefined || !isActive(still) || !changesNetwork(app, still, box)) return finish(app, box, job, "not an operator of the box", [notBox(user, box)], "red"); |
| 714 | const gate = doorOf(db, box.id); | |
| 715 | if (gate.state !== "open") { | |
| 716 | db.query("UPDATE game_chat SET write_window = ?2 WHERE id = ?1").run(job.audit_id, windowUsed(gate)); | |
| 717 | if (gate.state === "locked") return finish(app, box, job, "door locked", [LOCKED_LINE], "red"); | |
| 718 | const holding = holdBuild(db, box, user.id, job.words, job.sha); | |
| 719 | return finish(app, box, job, holding.ok ? "held for a yes on the forge" : holding.error, heldSays(holding, job.origin), holding.ok ? "gray" : "red"); | |
| 720 | } | |
| 681 | 721 | db.query("UPDATE game_chat_job SET name = ?2 WHERE id = ?1").run(job.id, wish.name); |
| 682 | 722 | const done = await commitServer(app, still, box, planned.value, job.sha); |
| 683 | 723 | if (!done.ok) return finish(app, box, job, done.error, [`Not built: ${done.error}`], "red"); |
src/games/door_hold.ts added +48
| @@ -0,0 +1,48 @@ | ||
| 1 | /** | |
| 2 | * A game-door write outside the write window (#18296), held as a Talk confirm: the same held-action | |
| 3 | * step the crew's own asked-first calls take (`core/fence.ts` `hold`), answered by the player's yes | |
| 4 | * on the forge (/settings/confirms, the conversation's Do it, the terminal's confirms), never in | |
| 5 | * game. What is held is the `games` tool call that does the same thing, so the yes runs it with | |
| 6 | * every check that tool makes, as that person, once, within the confirm's ten minutes. | |
| 7 | * | |
| 8 | * The confirm lives in the player's game conversation on the box (`game_talk`), made, limited to | |
| 9 | * the game door's tools (`core/conversation_door.ts`) and kept when there is none, so the thread | |
| 10 | * shows it with its buttons. | |
| 11 | */ | |
| 12 | ||
| 13 | import type { Database } from "bun:sqlite"; | |
| 14 | import { limitToGame } from "../core/conversation_door.ts"; | |
| 15 | import { appendTurn, createConversation, getConversation } from "../core/conversations.ts"; | |
| 16 | import { hold } from "../core/fence.ts"; | |
| 17 | import { confirmSentence } from "../crew/conversation_ask.ts"; | |
| 18 | import type { GameBox } from "./store.ts"; | |
| 19 | ||
| 20 | /** What was held, or why nothing could be. */ | |
| 21 | export type Holding = { ok: true; confirm: string; conversation: string; does: string } | { ok: false; error: string }; | |
| 22 | ||
| 23 | /** | |
| 24 | * The player's game conversation on `box`: the kept one while it is there, else a new limited one. | |
| 25 | */ | |
| 26 | function conversationFor(db: Database, box: GameBox, userId: string): string | undefined { | |
| 27 | const kept = db.query<{ conversation: string }, [string, string]>("SELECT conversation FROM game_talk WHERE box_id = ?1 AND user_id = ?2").get(box.id, userId)?.conversation; | |
| 28 | if (kept !== undefined && getConversation(db, userId, kept) !== undefined) return kept; | |
| 29 | const made = createConversation(db, userId); | |
| 30 | if (!made.ok) return undefined; | |
| 31 | limitToGame(db, made.value.id); | |
| 32 | db.query("INSERT OR REPLACE INTO game_talk (box_id, user_id, conversation, created_at) VALUES (?1, ?2, ?3, ?4)").run(box.id, userId, made.value.id, new Date().toISOString()); | |
| 33 | return made.value.id; | |
| 34 | } | |
| 35 | ||
| 36 | /** | |
| 37 | * Holds the build of a planned server (`words`, on the plan's commit `sha`) for `userId`'s yes. | |
| 38 | */ | |
| 39 | export function holdBuild(db: Database, box: GameBox, userId: string, words: string, sha: string, now = Date.now()): Holding { | |
| 40 | const conversation = conversationFor(db, box, userId); | |
| 41 | if (conversation === undefined) return { ok: false, error: "too many conversations" }; | |
| 42 | const args = { action: "create_server", box: box.name, words, dryRun: false, sha }; | |
| 43 | const confirm = hold(db, `conversation:${conversation}`, userId, "games", args, now); | |
| 44 | if (confirm === null) return { ok: false, error: "too many confirms waiting" }; | |
| 45 | const does = confirmSentence("games", args); | |
| 46 | appendTurn(db, userId, conversation, { role: "confirm", text: JSON.stringify({ confirm, tool: "games", does }) }); | |
| 47 | return { ok: true, confirm, conversation, does }; | |
| 48 | } |
src/games/write_window.ts added +106
| @@ -0,0 +1,106 @@ | ||
| 1 | /** | |
| 2 | * The game door's write window (#18296). Words typed in game reach the forge through a server that | |
| 3 | * can show anyone a line whose click types them, so a game session changes things only while the | |
| 4 | * box's owner has opened a window, with a passkey on the web, for `minutes` (an hour unless set). | |
| 5 | * Outside it a write from the game is held for the player's yes on the forge (`door_hold.ts`), and | |
| 6 | * nothing runs. Locked (`/forge lock`, the toggle on /games/<box>, `w` in the terminal), the door | |
| 7 | * is read-only at once: an open window ends and a write is refused, not held, until the owner opens | |
| 8 | * a window again. Reads and questions are never gated. | |
| 9 | * | |
| 10 | * Plain data in, plain data out: who may open, lock or set the length is decided at each door. | |
| 11 | */ | |
| 12 | ||
| 13 | import type { Database } from "bun:sqlite"; | |
| 14 | ||
| 15 | /** An hour unless the owner sets otherwise; within these bounds. */ | |
| 16 | export const WINDOW_MINUTES = 60; | |
| 17 | const LEAST = 5; | |
| 18 | const MOST = 12 * 60; | |
| 19 | ||
| 20 | /** Said beside the setting: why the window is as long as it is. */ | |
| 21 | export const WINDOW_WHY = | |
| 22 | "Long enough to build what you came to build, short enough that a window you forget closes by itself: words typed in game can come from a line any server shows."; | |
| 23 | ||
| 24 | /** The door as it stands now. */ | |
| 25 | export type DoorState = | |
| 26 | | { readonly state: "open"; readonly minutes: number; readonly window: string; readonly until: string; readonly by: string } | |
| 27 | | { readonly state: "closed"; readonly minutes: number } | |
| 28 | | { readonly state: "locked"; readonly minutes: number; readonly at: string; readonly by: string }; | |
| 29 | ||
| 30 | interface Row { | |
| 31 | minutes: number; | |
| 32 | opened_at: string; | |
| 33 | open_until: string; | |
| 34 | opened_by: string; | |
| 35 | locked_at: string; | |
| 36 | locked_by: string; | |
| 37 | } | |
| 38 | ||
| 39 | /** The door of `boxId` at `now`. A window past its end is closed; nothing has to sweep it. */ | |
| 40 | export function doorOf(db: Database, boxId: string, now = Date.now()): DoorState { | |
| 41 | const r = db.query<Row, [string]>("SELECT minutes, opened_at, open_until, opened_by, locked_at, locked_by FROM game_door WHERE box_id = ?1").get(boxId); | |
| 42 | const minutes = r?.minutes ?? WINDOW_MINUTES; | |
| 43 | if (r === null || r === undefined) return { state: "closed", minutes }; | |
| 44 | if (r.locked_at !== "") return { state: "locked", minutes, at: r.locked_at, by: r.locked_by }; | |
| 45 | if (r.opened_at !== "" && Date.parse(r.open_until) > now) return { state: "open", minutes, window: r.opened_at, until: r.open_until, by: r.opened_by }; | |
| 46 | return { state: "closed", minutes }; | |
| 47 | } | |
| 48 | ||
| 49 | /** | |
| 50 | * What a game-door command records as the window it used: the window's opening instant, or the | |
| 51 | * state that stood in its place. | |
| 52 | */ | |
| 53 | export const windowUsed = (d: DoorState): string => (d.state === "open" ? d.window : d.state); | |
| 54 | ||
| 55 | /** | |
| 56 | * Opens a window of the box's length from `now`, by `userId`, and lifts a lock. The caller has | |
| 57 | * checked the owner and their passkey. | |
| 58 | */ | |
| 59 | export function openWindow(db: Database, boxId: string, userId: string, now = Date.now()): DoorState { | |
| 60 | const minutes = doorOf(db, boxId, now).minutes; | |
| 61 | db.query( | |
| 62 | `INSERT INTO game_door (box_id, minutes, opened_at, open_until, opened_by, locked_at, locked_by) VALUES (?1, ?2, ?3, ?4, ?5, '', '') | |
| 63 | ON CONFLICT (box_id) DO UPDATE SET opened_at = ?3, open_until = ?4, opened_by = ?5, locked_at = '', locked_by = ''`, | |
| 64 | ).run(boxId, minutes, new Date(now).toISOString(), new Date(now + minutes * 60_000).toISOString(), userId); | |
| 65 | return doorOf(db, boxId, now); | |
| 66 | } | |
| 67 | ||
| 68 | /** | |
| 69 | * Locks the door at once: an open window ends, and writes are refused until one is opened again. | |
| 70 | */ | |
| 71 | export function lockDoor(db: Database, boxId: string, userId: string, now = Date.now()): DoorState { | |
| 72 | db.query( | |
| 73 | `INSERT INTO game_door (box_id, locked_at, locked_by) VALUES (?1, ?2, ?3) | |
| 74 | ON CONFLICT (box_id) DO UPDATE SET opened_at = '', open_until = '', opened_by = '', locked_at = ?2, locked_by = ?3`, | |
| 75 | ).run(boxId, new Date(now).toISOString(), userId); | |
| 76 | return doorOf(db, boxId, now); | |
| 77 | } | |
| 78 | ||
| 79 | /** | |
| 80 | * The length of the next window, from what a person typed: whole minutes, 5 to 720. Undefined when | |
| 81 | * it is not one. | |
| 82 | */ | |
| 83 | export function windowMinutes(typed: string): number | undefined { | |
| 84 | if (!/^\d{1,4}$/.test(typed.trim())) return undefined; | |
| 85 | const n = Number(typed.trim()); | |
| 86 | return n >= LEAST && n <= MOST ? n : undefined; | |
| 87 | } | |
| 88 | ||
| 89 | /** Sets the length of the next window; one open now keeps the end it was opened with. */ | |
| 90 | export function setWindowMinutes(db: Database, boxId: string, minutes: number): void { | |
| 91 | db.query("INSERT INTO game_door (box_id, minutes) VALUES (?1, ?2) ON CONFLICT (box_id) DO UPDATE SET minutes = ?2").run(boxId, minutes); | |
| 92 | } | |
| 93 | ||
| 94 | /** The door in one line, the same on the page, the terminal and in game. */ | |
| 95 | export function doorWords(d: DoorState, nameOf: (userId: string) => string, now = Date.now()): string { | |
| 96 | if (d.state === "locked") return `Locked by ${nameOf(d.by)}: the game door only reads. Its owner opens a write window on the forge, with a passkey.`; | |
| 97 | if (d.state === "open") { | |
| 98 | const left = Math.max(1, Math.ceil((Date.parse(d.until) - now) / 60_000)); | |
| 99 | return `Open for writes for ${String(left)} more minute${left === 1 ? "" : "s"}, opened by ${nameOf(d.by)}.`; | |
| 100 | } | |
| 101 | return `Closed: a change asked in game is held for a yes on the forge. A window lasts ${String(d.minutes)} minutes.`; | |
| 102 | } | |
| 103 | ||
| 104 | /** A kept command's window, as its audit line ends: "" for one that wrote nothing. */ | |
| 105 | export const windowNote = (window: string): string => | |
| 106 | window === "" ? "" : window === "closed" || window === "locked" ? ` · door ${window}` : ` · window opened ${window.slice(0, 16).replace("T", " ")} UTC`; |
src/http/games_routes.ts +3
| @@ -31,6 +31,7 @@ import { gameMap, gameMapSlash } from "./games_map.ts"; | ||
| 31 | 31 | import { gameSparkView } from "../web/pages/games_spark_view.ts"; |
| 32 | 32 | import { gameSparkLink, gameSparkOpen, gameSparkPost, gameSparkRead } from "../web/pages/games_spark.ts"; |
| 33 | 33 | import { gameConfigCommit, gameConfigPage, gameConfigPreview } from "../web/pages/games_config.ts"; |
| 34 | import { gameDoorOptions, gameDoorSubmit } from "../web/pages/games_door.ts"; | |
| 34 | 35 | import { publicOrigin } from "../core/public_origin.ts"; |
| 35 | 36 | import type { Ctx, Handler } from "./context.ts"; |
| 36 | 37 | import { InvalidJson } from "./json_body.ts"; |
| @@ -181,6 +182,8 @@ export function gamesRoutes(router: Router<Handler>): void { | ||
| 181 | 182 | router.add("GET", "/games/:box", gameBoxPage); |
| 182 | 183 | router.add("POST", "/games/:box/grant", gameGrantSubmit); |
| 183 | 184 | router.add("POST", "/games/:box/lend", gameLendSubmit); |
| 185 | router.add("POST", "/games/:box/door", gameDoorSubmit); | |
| 186 | router.add("POST", "/games/:box/door/options", gameDoorOptions); | |
| 184 | 187 | // Before the service routes: no compose service can be named "@shell". |
| 185 | 188 | router.add("POST", "/games/:box/@shell", gameShellSubmit); |
| 186 | 189 | router.add("GET", "/games/:box/@shell/stream", gameShellStream); |
src/http/lazy_lists.ts +2
| @@ -665,6 +665,8 @@ export const OPERATIONS_ROUTES = [ | ||
| 665 | 665 | ["GET", "/games/:box"], |
| 666 | 666 | ["POST", "/games/:box/grant"], |
| 667 | 667 | ["POST", "/games/:box/lend"], |
| 668 | ["POST", "/games/:box/door"], | |
| 669 | ["POST", "/games/:box/door/options"], | |
| 668 | 670 | ["POST", "/games/:box/@shell"], |
| 669 | 671 | ["GET", "/games/:box/@shell/stream"], |
| 670 | 672 | ["POST", "/games/:box/@spark"], |
src/tui/screens/games.ts +14 −5
| @@ -9,7 +9,8 @@ | ||
| 9 | 9 | * settings (server.properties and Paper's, as the page's Settings block: |
| 10 | 10 | * `enter` sets one, the preview shows on top, `y` commits it through `commitSettings`). `G` opens |
| 11 | 11 | * the box's grants, which an owner sets with `a` there, through `grant`; `b` the box itself, as |
| 12 | * /games/<box>'s Box block (its diagnosis, the volume's device and log among it). | |
| 12 | * /games/<box>'s Box block (its diagnosis, the volume's device and log among it, and the game door, | |
| 13 | * which its owner locks with `w` there, #18296). | |
| 13 | 14 | */ |
| 14 | 15 | |
| 15 | 16 | import { movedKey } from "./moved_key.ts"; |
| @@ -39,7 +40,8 @@ import { pluginLines } from "../../games/plugins_loaded.ts"; | ||
| 39 | 40 | import { heldLines, heldOn } from "../../games/hold.ts"; |
| 40 | 41 | import { askPower, refusesNow, type Power } from "../../games/power.ts"; |
| 41 | 42 | import { cloudLine, pinnedOfBox } from "../../actions/cloud_says.ts"; |
| 42 | import { getUserByName } from "../../core/users.ts"; | |
| 43 | import { getUserById, getUserByName } from "../../core/users.ts"; | |
| 44 | import { doorOf, doorWords, lockDoor, WINDOW_WHY } from "../../games/write_window.ts"; | |
| 43 | 45 | import { commitServiceEnv, readCompose, serviceEnv } from "../../games/compose.ts"; |
| 44 | 46 | import { commitSettings, planSettings, settingsOf, type SettingsPlan, type SettingValue } from "../../games/settings.ts"; |
| 45 | 47 | import { |
| @@ -637,6 +639,11 @@ export function gameBoxScreen(f: Session, ctx: Ctx, box: GameBox): Screen { | ||
| 637 | 639 | // The page's Spare rows, in the same words, first (kept a minute, so a redraw is free). |
| 638 | 640 | const lending = lentRunnerOf(f.app.db, b.id) !== undefined; |
| 639 | 641 | const lend = mayDo(roleOn(f.app.db, f.user, b.id), "owner") ? [lendWords(lending), ...(lending && b.lendWhy !== "" ? [lendCannot(b.lendWhy)] : []), ""] : []; |
| 642 | // The game door (#18296), as /games/<box>'s block: `w` locks it; a window opens on the web | |
| 643 | // alone, with a passkey. | |
| 644 | const door = mayDo(roleOn(f.app.db, f.user, b.id), "owner") | |
| 645 | ? [`Game door: ${doorWords(doorOf(f.app.db, b.id), (id) => getUserById(f.app.db, id)?.username ?? "someone")}`, WINDOW_WHY, ""].flatMap((l) => (l === "" ? [""] : wrap(l, w))) | |
| 646 | : []; | |
| 640 | 647 | const spare = [spareRow(f.app.db, f.app.config.dataDir, b).map(([k, v]) => `${k}: ${v}.`).join(" "), ""]; |
| 641 | 648 | if (!mayDo(roleOn(f.app.db, f.user, b.id), "owner")) { |
| 642 | 649 | const shared = boxStatusShared(b.diag); |
| @@ -644,12 +651,12 @@ export function gameBoxScreen(f: Session, ctx: Ctx, box: GameBox): Screen { | ||
| 644 | 651 | } |
| 645 | 652 | const plain = [...boxStatus(b.diag), ...pluginLines(b.diag), ...healWords(f.app.db, b)]; |
| 646 | 653 | const tails = boxTails(b.diag); |
| 647 | if (plain.length + tails.length === 0) return [...held, ...lend, ...spare, "The box has sent no diagnosis yet: its agent sends one with every check-in."]; | |
| 648 | return [...held, ...lend, ...spare, ...plain, ...tails.flatMap(([k, v]) => ["", `== ${k}`, ...v.split("\n")])]; | |
| 654 | if (plain.length + tails.length === 0) return [...held, ...door, ...lend, ...spare, "The box has sent no diagnosis yet: its agent sends one with every check-in."]; | |
| 655 | return [...held, ...door, ...lend, ...spare, ...plain, ...tails.flatMap(([k, v]) => ["", `== ${k}`, ...v.split("\n")])]; | |
| 649 | 656 | }; |
| 650 | 657 | return { |
| 651 | 658 | title: `${box.name}: the box`, |
| 652 | keys: [binding(["j", "k"], "scroll"), binding(["l"], "run checks while servers sleep: switch"), binding(["p"], "spark profiles")], | |
| 659 | keys: [binding(["j", "k"], "scroll"), binding(["l"], "run checks while servers sleep: switch"), binding(["w"], "lock the game door"), binding(["p"], "spark profiles")], | |
| 653 | 660 | render(area, s) { |
| 654 | 661 | const c = ctx.theme.c; |
| 655 | 662 | const all = lines(Math.max(10, area.w)); |
| @@ -668,6 +675,8 @@ export function gameBoxScreen(f: Session, ctx: Ctx, box: GameBox): Screen { | ||
| 668 | 675 | } else if (e.key === "l" && mayDo(roleOn(f.app.db, f.user, box.id), "owner") && f.user !== undefined) { |
| 669 | 676 | const b = listBoxes(f.app.db).find((x) => x.id === box.id) ?? box; |
| 670 | 677 | setLend(f.app.db, b, lentRunnerOf(f.app.db, b.id) === undefined, f.user.id); |
| 678 | } else if (e.key === "w" && mayDo(roleOn(f.app.db, f.user, box.id), "owner") && f.user !== undefined) { | |
| 679 | lockDoor(f.app.db, box.id, f.user.id); | |
| 671 | 680 | } else return false; |
| 672 | 681 | ctx.invalidate(); |
| 673 | 682 | return true; |
src/web/pages/account.ts +2 −4
| @@ -76,14 +76,12 @@ import { | ||
| 76 | 76 | closingSays, |
| 77 | 77 | keepMyAccount, |
| 78 | 78 | keptSays, |
| 79 | closeChallenge, | |
| 80 | 79 | closeStanding, |
| 81 | 80 | type CloseStanding, |
| 82 | passkeyProves, | |
| 83 | PROOF_FIELDS, | |
| 84 | 81 | type CloseProof, |
| 85 | 82 | type CloseRefusal, |
| 86 | 83 | } from "../../actions/account_close.ts"; |
| 84 | import { passkeyProves, proofChallenge, PROOF_FIELDS } from "../../actions/passkey_proof.ts"; | |
| 87 | 85 | import { passkeyNote } from "../passkey-state.ts"; |
| 88 | 86 | import { PASSKEY_REJECTED } from "../passkey-words.ts"; |
| 89 | 87 | import { field, kept, readForm, refused, type Form, type Refused } from "../form.ts"; |
| @@ -1207,7 +1205,7 @@ export function closeOptions(ctx: Ctx): Response { | ||
| 1207 | 1205 | const user = ctx.auth.user; |
| 1208 | 1206 | if (user === undefined || !isAccountItself(ctx.app.db, ctx.auth)) |
| 1209 | 1207 | return json({ error: "refused", message: "Sign in to your account first." }, 401); |
| 1210 | return json({ ...closeChallenge(ctx.app, user.id), rpId: ctx.url.hostname }); | |
| 1208 | return json({ ...proofChallenge(ctx.app, user.id), rpId: ctx.url.hostname }); | |
| 1211 | 1209 | } |
| 1212 | 1210 | |
| 1213 | 1211 | /** While a close request stands, the day it closes and Keep my account; nothing otherwise. */ |
src/web/pages/games.ts +8 −2
| @@ -83,6 +83,9 @@ import { commitJar, heldWords, leftWords, ONLY_PINNED, pinOf, PINS, planJar } fr | ||
| 83 | 83 | import { canSleep, commitPolicy, EMPTY_SECONDS, isGameServer, policyOf, proxyOf, proxyPort, STILL_BILLED } from "../../games/sleep.ts"; |
| 84 | 84 | import { CLOUD_EVENT, cloudFacts, GAME_CLOUD_EVENT, pinnedOfBox } from "../../actions/cloud_says.ts"; |
| 85 | 85 | import { topologyBlock, TOPOLOGY_CSS } from "./games_topology.ts"; |
| 86 | import { doorBlock } from "./games_door.ts"; | |
| 87 | import { passkeyJs } from "../passkey-client.ts"; | |
| 88 | import { windowNote } from "../../games/write_window.ts"; | |
| 86 | 89 | import { defaultHeadResponse, headResponse } from "../../games/heads.ts"; |
| 87 | 90 | import { eventsOf, eventWords, isBedrock, knowsPlayer, peopleOf, peopleWords, queuePeople, UNDO, type PeopleOp } from "../../games/people.ts"; |
| 88 | 91 | import { queueWorld, undoOf } from "../../games/worlds.ts"; |
| @@ -313,12 +316,14 @@ export async function gameBoxPage(ctx: Ctx): Promise<Response> { | ||
| 313 | 316 | const leaving = operator ? (ctx.url.searchParams.get("remove") ?? "").slice(0, 64) : ""; |
| 314 | 317 | const removal = leaving === "" ? undefined : await planRemoveServer(ctx.app, box, leaving); |
| 315 | 318 | const removable = (n: string): boolean => operator && compose !== undefined && composeServices(compose.text).includes(n) && isGameServer(compose.text, n); |
| 319 | // The game door (#18296): the owner's, with the passkey ceremony when they have a key. | |
| 320 | const door = role === "owner" ? doorBlock(ctx, box) : undefined; | |
| 316 | 321 | return timePhase(ctx.request, "render", () => page({ |
| 317 | 322 | ctx, |
| 318 | 323 | title: `Games · ${box.name}`, |
| 319 | 324 | styleCss: TOPOLOGY_CSS, |
| 320 | 325 | // The owner's console streams its answers over the box's own sync. |
| 321 | ...(role === "owner" ? { scriptJs: terminalBlocksJs } : {}), | |
| 326 | ...(role === "owner" ? { scriptJs: door?.passkey === true ? terminalBlocksJs + passkeyJs : terminalBlocksJs } : {}), | |
| 322 | 327 | body: html`${pageHead(box.name, { |
| 323 | 328 | sub: `${box.repo}@${box.branch}:${box.path}${box.composeSha === "" ? "" : ` · running ${box.composeSha.slice(0, 10)}`}`, |
| 324 | 329 | })} |
| @@ -356,6 +361,7 @@ export async function gameBoxPage(ctx: Ctx): Promise<Response> { | ||
| 356 | 361 | ${topologyBlock(ctx, box, compose?.text, visible)} |
| 357 | 362 | ${operator ? newServerBlock(box, words, preview) : null} |
| 358 | 363 | ${chatBlock(ctx, box, role === "owner")} |
| 364 | ${door?.html ?? null} | |
| 359 | 365 | ${spareBlock(ctx, box)} |
| 360 | 366 | ${role === "owner" ? boxBlock(box, [...healWords(ctx.app.db, box), ...packCheckLines(ctx.app, box.id)]) : sharedBoxBlock(box, packCheckLines(ctx.app, box.id))} ${role === "owner" ? shellBlock(ctx, box) : null} |
| 361 | 367 | ${role === "owner" ? lendBlock(ctx, box) : null} |
| @@ -437,7 +443,7 @@ function chatBlock(ctx: Ctx, box: GameBox, owner: boolean): Html | null { | ||
| 437 | 443 | : rowList(players.map((p) => row({ title: p.player, meta: html`${p.username} · linked ${time(p.createdAt)}` })))} |
| 438 | 444 | ${said.length === 0 |
| 439 | 445 | ? null |
| 440 | : rowList(said.map((c) => row({ title: `${c.player} on ${c.service}: ${typedAs(c.door, c.words)}`, meta: html`${c.outcome} · ${time(c.at)}` })))} | |
| 446 | : rowList(said.map((c) => row({ title: `${c.player} on ${c.service}: ${typedAs(c.door, c.words)}`, meta: html`${c.outcome}${windowNote(c.window)} · ${time(c.at)}` })))} | |
| 441 | 447 | </section>`; |
| 442 | 448 | } |
| 443 | 449 |
src/web/pages/games_door.ts added +98
| @@ -0,0 +1,98 @@ | ||
| 1 | /** | |
| 2 | * The game door's block on /games/<box> (#18296), the owner's alone: whether a game session may | |
| 3 | * change things now (`games/write_window.ts`), Lock now, Open writes with a passkey, and the | |
| 4 | * window's length with why it is that long. The terminal's door is the box screen | |
| 5 | * (`tui/screens/games.ts`, `w` locks); `/forge lock` locks from the game. | |
| 6 | */ | |
| 7 | ||
| 8 | import { passkeyProves, proofChallenge, PROOF_FIELDS } from "../../actions/passkey_proof.ts"; | |
| 9 | import { passkeyIds } from "../../core/passkeys.ts"; | |
| 10 | import { getUserById } from "../../core/users.ts"; | |
| 11 | import { doorOf, doorWords, lockDoor, openWindow, setWindowMinutes, WINDOW_WHY, windowMinutes } from "../../games/write_window.ts"; | |
| 12 | import type { GameBox } from "../../games/store.ts"; | |
| 13 | import { crossOrigin, type Ctx } from "../../http/context.ts"; | |
| 14 | import { json } from "../../http/respond.ts"; | |
| 15 | import { field, readForm } from "../form.ts"; | |
| 16 | import { html, when, type Html } from "../html.ts"; | |
| 17 | import { flashTo } from "../layout.ts"; | |
| 18 | import { passkeyNote } from "../passkey-state.ts"; | |
| 19 | import { PASSKEY_REJECTED } from "../passkey-words.ts"; | |
| 20 | import { CAME_FROM_ELSEWHERE } from "../chrome.ts"; | |
| 21 | import { btn } from "../ui.ts"; | |
| 22 | import { boxOf } from "./games.ts"; | |
| 23 | ||
| 24 | const nameOf = | |
| 25 | (ctx: Ctx) => | |
| 26 | (id: string): string => | |
| 27 | getUserById(ctx.app.db, id)?.username ?? "someone"; | |
| 28 | ||
| 29 | /** The block; whether the page needs the passkey script is `passkey`. */ | |
| 30 | export function doorBlock(ctx: Ctx, box: GameBox): { readonly html: Html; readonly passkey: boolean } { | |
| 31 | const d = doorOf(ctx.app.db, box.id); | |
| 32 | const passkey = passkeyIds(ctx.app.db, ctx.auth.user!.id).length > 0; | |
| 33 | const action = `/games/${box.name}/door`; | |
| 34 | return { | |
| 35 | passkey, | |
| 36 | html: html`<section class="settings-block" id="door" data-door="${d.state}"> | |
| 37 | <h2>Game door</h2> | |
| 38 | <p class="small" data-door-says>${doorWords(d, nameOf(ctx))}</p> | |
| 39 | <div class="row-fields"> | |
| 40 | ${when(d.state !== "locked", () => html`<form method="post" action="${action}"><input type="hidden" name="op" value="lock" />${btn("Lock now", { type: "submit", variant: "secondary" })}</form>`)} | |
| 41 | ${passkey | |
| 42 | ? html`<form method="post" action="${action}"> | |
| 43 | <input type="hidden" name="op" value="open" /> | |
| 44 | ${PROOF_FIELDS.map((n) => html`<input type="hidden" name="${n}" value="" />`)} | |
| 45 | <span data-passkey="on" hidden>${btn(`Allow writes from the game for ${String(d.minutes)} minutes`, { type: "button", id: "passkey-window", variant: "secondary", data: { options: `${action}/options` } })}</span> | |
| 46 | ${passkeyNote("passkey-window-note")} | |
| 47 | </form>` | |
| 48 | : html`<p class="muted small">A write window opens only with a passkey: <a href="/settings/passkeys">add one</a> first.</p>`} | |
| 49 | </div> | |
| 50 | <form method="post" action="${action}" class="row-fields mt"> | |
| 51 | <input type="hidden" name="op" value="minutes" /> | |
| 52 | <label class="field">Window length, minutes | |
| 53 | <input type="number" name="minutes" min="5" max="720" step="1" value="${String(d.minutes)}" required /> | |
| 54 | </label> | |
| 55 | ${btn("Save", { type: "submit", variant: "ghost" })} | |
| 56 | </form> | |
| 57 | <p class="muted small" data-door-why>${WINDOW_WHY}</p> | |
| 58 | </section>`, | |
| 59 | }; | |
| 60 | } | |
| 61 | ||
| 62 | // POST /games/:box/door/options: a passkey challenge for the box's owner, and the keys that may | |
| 63 | // answer it. | |
| 64 | export function gameDoorOptions(ctx: Ctx): Response { | |
| 65 | if (crossOrigin(ctx.request, ctx.url, ctx.app.log)) return json({ error: "refused", message: CAME_FROM_ELSEWHERE }, 403); | |
| 66 | const got = boxOf(ctx, "owner"); | |
| 67 | if (got instanceof Response) return json({ error: "refused", message: "Only the box's owner opens its game door." }, 403); | |
| 68 | return json({ ...proofChallenge(ctx.app, ctx.auth.user!.id), rpId: ctx.url.hostname }); | |
| 69 | } | |
| 70 | ||
| 71 | // POST /games/:box/door: the owner locks the door, opens a window with a passkey, or sets its | |
| 72 | // length. | |
| 73 | export async function gameDoorSubmit(ctx: Ctx): Promise<Response> { | |
| 74 | const got = boxOf(ctx, "owner"); | |
| 75 | if (got instanceof Response) return got; | |
| 76 | const form = await readForm(ctx, "rw"); | |
| 77 | if (form instanceof Response) return form; | |
| 78 | const { box } = got; | |
| 79 | const user = ctx.auth.user!; | |
| 80 | const back = `/games/${box.name}#door`; | |
| 81 | const op = field(form, "op"); | |
| 82 | if (op === "lock") { | |
| 83 | lockDoor(ctx.app.db, box.id, user.id); | |
| 84 | return flashTo(ctx, back, { message: "Locked: the game door only reads now." }); | |
| 85 | } | |
| 86 | if (op === "minutes") { | |
| 87 | const minutes = windowMinutes(field(form, "minutes")); | |
| 88 | if (minutes === undefined) return flashTo(ctx, back, { tone: "danger", message: "A window is 5 to 720 whole minutes." }); | |
| 89 | setWindowMinutes(ctx.app.db, box.id, minutes); | |
| 90 | return flashTo(ctx, back, { message: `The next write window lasts ${String(minutes)} minutes.` }); | |
| 91 | } | |
| 92 | if (op !== "open") return flashTo(ctx, back, { tone: "danger", message: "Lock, open or set the length." }); | |
| 93 | const answer = Object.fromEntries(PROOF_FIELDS.map((n) => [n, field(form, n)])) as Record<(typeof PROOF_FIELDS)[number], string>; | |
| 94 | if (answer.challenge === "" || !(await passkeyProves(ctx.app, user.id, answer, { origin: ctx.url.origin, rpId: ctx.url.hostname }))) | |
| 95 | return flashTo(ctx, back, { tone: "danger", message: `${PASSKEY_REJECTED} The game door stays as it was.` }); | |
| 96 | const d = openWindow(ctx.app.db, box.id, user.id); | |
| 97 | return flashTo(ctx, back, { message: doorWords(d, nameOf(ctx)) }); | |
| 98 | } |
src/web/passkey-client.ts +6 −2
| @@ -173,7 +173,9 @@ export const passkeyJs = /* js */ ` | ||
| 173 | 173 | }); |
| 174 | 174 | // Close my account with a passkey (#15619): the signed answer goes into the |
| 175 | 175 | // close form's hidden fields and the form posts as it does with a password. |
| 176 | wire('passkey-close', function (el) { | |
| 176 | // A passkey as a second factor for one form's post (closing the account, opening the game door's | |
| 177 | // write window): the signed answer fills the form's hidden fields, then the form is sent. | |
| 178 | function prove(el) { | |
| 177 | 179 | var form = el.form; |
| 178 | 180 | var pw = form.elements.password; |
| 179 | 181 | if (pw) pw.required = false; |
| @@ -194,7 +196,9 @@ export const passkeyJs = /* js */ ` | ||
| 194 | 196 | form.submit(); |
| 195 | 197 | }); |
| 196 | 198 | }); |
| 197 | }); | |
| 199 | } | |
| 200 | wire('passkey-close', prove); | |
| 201 | wire('passkey-window', prove); | |
| 198 | 202 | wire('passkey-signin', function () { |
| 199 | 203 | return post('/signin/passkey/options').then(function (o) { |
| 200 | 204 | return navigator.credentials.get({ publicKey: { |
test/game-chat.test.ts +5
| @@ -20,6 +20,7 @@ import { mintViaToken } from "../src/core/via_token.ts"; | ||
| 20 | 20 | import { configureConversation } from "../src/crew/conversation.ts"; |
| 21 | 21 | import { accountLinks, chatCommand, chatLog, exposedBackend, gameChat, linksOf, newLinkCode, PER_MINUTE, playersOn, runChat, unlink } from "../src/games/chat.ts"; |
| 22 | 22 | import { readCompose, serviceEnv } from "../src/games/compose.ts"; |
| 23 | import { openWindow, setWindowMinutes } from "../src/games/write_window.ts"; | |
| 23 | 24 | import { boxNamed, commandHistory, createGameBox, grant, recentCommands, recordSync, type GameBox } from "../src/games/store.ts"; |
| 24 | 25 | import { forgeHttp, type ForgeHttp } from "../src/http/server.ts"; |
| 25 | 26 | import { chatAged } from "./helpers/game-chat-clock.ts"; |
| @@ -338,6 +339,10 @@ describe("on a forge", () => { | ||
| 338 | 339 | }); |
| 339 | 340 | if (!seeded.ok) throw new Error(JSON.stringify(seeded.error)); |
| 340 | 341 | token = createGameBox(app.db, { name: "mc", repo: "ada/mc-network" }).token; |
| 342 | // These builds run inside the owner's write window (#18296); outside it, | |
| 343 | // test/game-write-window.test.ts. | |
| 344 | setWindowMinutes(app.db, box().id, 720); | |
| 345 | openWindow(app.db, box().id, ada.id); | |
| 341 | 346 | // The crew answers every message with three lines. |
| 342 | 347 | const bin = join(dataDir, "claude"); |
| 343 | 348 | writeFileSync( |
test/game-door.test.ts +5
| @@ -19,6 +19,7 @@ import { chatLog, gameAsk, gameChat, linksOf, newLinkCode, runChat, typedAs } fr | ||
| 19 | 19 | import doorMigration from "../src/core/migrations/20261203042200-game-chat-door.ts"; |
| 20 | 20 | import { readCompose } from "../src/games/compose.ts"; |
| 21 | 21 | import { CONFIRM_MS, toldTo } from "../src/games/door.ts"; |
| 22 | import { openWindow, setWindowMinutes } from "../src/games/write_window.ts"; | |
| 22 | 23 | import { boxNamed, createGameBox, grant, type GameBox } from "../src/games/store.ts"; |
| 23 | 24 | import { forgeHttp, serve } from "../src/http/server.ts"; |
| 24 | 25 | import { chatAged } from "./helpers/game-chat-clock.ts"; |
| @@ -91,6 +92,10 @@ beforeAll(async () => { | ||
| 91 | 92 | createGameBox(app.db, { name: "mc2", repo: "ada/net" }); |
| 92 | 93 | box = boxNamed(app.db, "mc")!; |
| 93 | 94 | other = boxNamed(app.db, "mc2")!; |
| 95 | // These builds run inside the owner's write window (#18296); outside it, | |
| 96 | // test/game-write-window.test.ts. | |
| 97 | setWindowMinutes(app.db, box.id, 720); | |
| 98 | openWindow(app.db, box.id, ada.id); | |
| 94 | 99 | app.db |
| 95 | 100 | .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)") |
| 96 | 101 | .run(box.id, JSON.stringify([{ name: "ada", uuid: ADA }])); |
test/game-write-window.test.ts added +229
| @@ -0,0 +1,229 @@ | ||
| 1 | /** | |
| 2 | * The game door's write window (#18296): a build asked in game outside the owner's window is held | |
| 3 | * as a confirm, not run; inside it, it runs and its audit row names the window; `/forge lock` and | |
| 4 | * the page's Lock now stop writes at once; a window ends by itself; and only a passkey opens one. | |
| 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 { sayYes } from "../src/actions/conversation_confirms.ts"; | |
| 11 | import { commitToBranch, createRepo } from "../src/actions/repos.ts"; | |
| 12 | import type { Ctx } from "../src/http/context.ts"; | |
| 13 | import { createApp, type App } from "../src/app.ts"; | |
| 14 | import { waitingFor } from "../src/core/fence.ts"; | |
| 15 | import { createSession } from "../src/core/sessions.ts"; | |
| 16 | import { createUser, type User } from "../src/core/users.ts"; | |
| 17 | import { gameAsk, runChat } from "../src/games/chat.ts"; | |
| 18 | import { readCompose } from "../src/games/compose.ts"; | |
| 19 | import { toldTo } from "../src/games/door.ts"; | |
| 20 | import { boxNamed, createGameBox, grant, type GameBox } from "../src/games/store.ts"; | |
| 21 | import { doorOf, lockDoor, openWindow, setWindowMinutes, windowMinutes } from "../src/games/write_window.ts"; | |
| 22 | import { forgeHttp } from "../src/http/server.ts"; | |
| 23 | import { chatAged } from "./helpers/game-chat-clock.ts"; | |
| 24 | import { quietLogs } from "./helpers/globals.ts"; | |
| 25 | ||
| 26 | quietLogs(); | |
| 27 | ||
| 28 | const COMPOSE = `configs: | |
| 29 | velocity_toml: | |
| 30 | content: | | |
| 31 | [servers] | |
| 32 | hub = "hub:25565" | |
| 33 | try = ["hub"] | |
| 34 | ||
| 35 | [forced-hosts] | |
| 36 | "play.example.test" = ["hub"] | |
| 37 | ||
| 38 | services: | |
| 39 | velocity: | |
| 40 | image: itzg/mc-proxy:latest | |
| 41 | ports: ["25565:25565"] | |
| 42 | configs: | |
| 43 | - source: velocity_toml | |
| 44 | target: /config/velocity.toml | |
| 45 | environment: | |
| 46 | TYPE: VELOCITY | |
| 47 | MEMORY: 768M | |
| 48 | hub: | |
| 49 | image: itzg/minecraft-server:latest | |
| 50 | environment: | |
| 51 | TYPE: PAPER | |
| 52 | VERSION: "1.21.6" | |
| 53 | MEMORY: 1G | |
| 54 | `; | |
| 55 | const ADA = "00000000-0000-4000-8000-00000000000a"; | |
| 56 | ||
| 57 | let dir = ""; | |
| 58 | let app: App; | |
| 59 | let ada: User; | |
| 60 | let box: GameBox; | |
| 61 | ||
| 62 | const request = (words: string, more: Record<string, unknown> = {}) => ({ id: crypto.randomUUID() as string, at: Date.now(), uuid: ADA, name: "ada", server: "hub", words, ...more }); | |
| 63 | const compose = async (): Promise<string> => (await readCompose(app, box))!.text; | |
| 64 | const send = async (asks: unknown, run = true) => { | |
| 65 | gameAsk(app, box, asks, await compose(), "http://forge.test", Date.now()); | |
| 66 | if (run) await runChat(app, box.id); | |
| 67 | return toldTo(app.db, box, Date.now()); | |
| 68 | }; | |
| 69 | /** A plan through the proxy, and the request that confirms building it. */ | |
| 70 | const planned = async (name: string) => { | |
| 71 | const plan = request(`give me a flat world called ${name}`); | |
| 72 | const [shown] = await send([plan]); | |
| 73 | expect(shown).toMatchObject({ id: plan.id, confirm: true }); | |
| 74 | return request("yes", { confirms: plan.id }); | |
| 75 | }; | |
| 76 | const lastRow = () => | |
| 77 | app.db | |
| 78 | .query<{ kind: string; player: string; door: string; outcome: string; write_window: string }, [string]>( | |
| 79 | "SELECT kind, player, door, outcome, write_window FROM game_chat WHERE box_id = ?1 ORDER BY id DESC LIMIT 1", | |
| 80 | ) | |
| 81 | .get(box.id)!; | |
| 82 | ||
| 83 | beforeAll(async () => { | |
| 84 | dir = await mkdtemp(join(tmpdir(), "forge-game-window-")); | |
| 85 | app = createApp({ dataDir: dir, port: 0, host: "forge.test", modrinthFetch: (async () => Response.json([])) as unknown as typeof fetch }); | |
| 86 | const u = await createUser(app.db, { username: "ada", email: "[email protected]", password: "a-good-passphrase", origin: "seed", isAdmin: true, trusted: true }); | |
| 87 | if (!u.ok) throw new Error(u.error); | |
| 88 | ada = u.value; | |
| 89 | const repo = await createRepo(app, ada, { name: "net", visibility: "private" }); | |
| 90 | if (!repo.ok) throw new Error(JSON.stringify(repo)); | |
| 91 | const put = await commitToBranch(app, ada, repo.value, { message: "net", files: [{ path: "docker-compose.yml", content: COMPOSE }] }); | |
| 92 | if (!put.ok) throw new Error(JSON.stringify(put.error)); | |
| 93 | createGameBox(app.db, { name: "mc", repo: "ada/net" }); | |
| 94 | box = boxNamed(app.db, "mc")!; | |
| 95 | app.db | |
| 96 | .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)") | |
| 97 | .run(box.id, JSON.stringify([{ name: "ada", uuid: ADA }])); | |
| 98 | app.db.query("INSERT OR REPLACE INTO game_link (box_id, player, user_id, uuid, created_at) VALUES (?1, 'ada', ?2, ?3, ?4)").run(box.id, ada.id, ADA, new Date().toISOString()); | |
| 99 | }, 30_000); | |
| 100 | beforeEach(() => { | |
| 101 | app.db.query("DELETE FROM game_chat_job").run(); | |
| 102 | app.db.query("DELETE FROM game_door").run(); | |
| 103 | app.db.query("DELETE FROM conversation_held").run(); | |
| 104 | chatAged(app.db, 3_600_001); | |
| 105 | }); | |
| 106 | afterAll(async () => { | |
| 107 | app.close(); | |
| 108 | await rm(dir, { recursive: true, force: true }); | |
| 109 | }); | |
| 110 | ||
| 111 | test("a box's door starts closed, with an hour's window", () => { | |
| 112 | expect(doorOf(app.db, box.id)).toEqual({ state: "closed", minutes: 60 }); | |
| 113 | }); | |
| 114 | ||
| 115 | test("a build asked outside the window is held for a yes on the forge, not run, and its audit row says so", async () => { | |
| 116 | const yes = await planned("held"); | |
| 117 | const [told] = await send([yes]); | |
| 118 | expect(told!.text).toStartWith("Held: "); | |
| 119 | expect(told!.text).toContain("Say yes on the forge within 10 minutes: http://forge.test/talk/"); | |
| 120 | expect(await compose()).not.toContain("\n held:\n"); | |
| 121 | const waiting = waitingFor(app.db, ada.id); | |
| 122 | expect(waiting).toHaveLength(1); | |
| 123 | expect(waiting[0]).toMatchObject({ tool: "games", args: { action: "create_server", box: "mc", dryRun: false } }); | |
| 124 | expect(lastRow()).toEqual({ kind: "yes", player: "ada", door: "proxy", outcome: "held for a yes on the forge", write_window: "closed" }); | |
| 125 | // The player's yes on the forge, with their own session, builds it once. | |
| 126 | const ctx = { app, auth: { user: ada, scope: "rw" }, request: new Request("http://forge.test/"), url: new URL("http://forge.test/"), params: {} } as unknown as Ctx; | |
| 127 | const said = await sayYes(ctx, ada, waiting[0]!.id); | |
| 128 | expect(said).toMatchObject({ ok: true, done: true }); | |
| 129 | expect(await compose()).toContain("\n held:\n"); | |
| 130 | expect(await sayYes(ctx, ada, waiting[0]!.id)).toEqual({ ok: false, error: "answered" }); | |
| 131 | }, 30_000); | |
| 132 | ||
| 133 | test("inside the window a build runs, and its audit row names the window it used", async () => { | |
| 134 | const opened = openWindow(app.db, box.id, ada.id); | |
| 135 | if (opened.state !== "open") throw new Error("not open"); | |
| 136 | const yes = await planned("built"); | |
| 137 | const [told] = await send([yes]); | |
| 138 | expect(told!.text).toContain("The box brings it up on its next check-in."); | |
| 139 | expect(await compose()).toContain("\n built:\n"); | |
| 140 | expect(waitingFor(app.db, ada.id)).toEqual([]); | |
| 141 | expect(lastRow()).toMatchObject({ kind: "yes", player: "ada", door: "proxy", write_window: opened.window }); | |
| 142 | }, 30_000); | |
| 143 | ||
| 144 | test("/forge lock stops writes at once: the open window ends and a build is refused, not held", async () => { | |
| 145 | openWindow(app.db, box.id, ada.id); | |
| 146 | const [locked] = await send([request("lock")]); | |
| 147 | expect(locked!.text).toStartWith("Locked: the game door only reads now."); | |
| 148 | expect(doorOf(app.db, box.id).state).toBe("locked"); | |
| 149 | expect(lastRow()).toMatchObject({ kind: "lock", player: "ada", door: "proxy", write_window: "locked" }); | |
| 150 | const yes = await planned("locked"); | |
| 151 | const [refused] = await send([yes]); | |
| 152 | expect(refused!.text).toStartWith("The game door is locked, so nothing was changed"); | |
| 153 | expect(await compose()).not.toContain("\n locked:\n"); | |
| 154 | expect(waitingFor(app.db, ada.id)).toEqual([]); | |
| 155 | }, 30_000); | |
| 156 | ||
| 157 | test("/forge lock takes an operator of the box: a viewer's, or one server's operator's, is refused and the window stays open", async () => { | |
| 158 | const made = await createUser(app.db, { username: "vic", email: "[email protected]", password: "a-good-passphrase", origin: "seed", trusted: true }); | |
| 159 | if (!made.ok) throw new Error(made.error); | |
| 160 | const VIC = "00000000-0000-4000-8000-00000000000b"; | |
| 161 | grant(app.db, box.id, made.value.id, "viewer", "hub"); | |
| 162 | app.db.query("INSERT OR REPLACE INTO game_link (box_id, player, user_id, uuid, created_at) VALUES (?1, 'vic', ?2, ?3, ?4)").run(box.id, made.value.id, VIC, new Date().toISOString()); | |
| 163 | const opened = openWindow(app.db, box.id, ada.id); | |
| 164 | const [told] = await send([request("lock", { uuid: VIC, name: "vic" })]); | |
| 165 | expect(told!.text).not.toStartWith("Locked"); | |
| 166 | expect(doorOf(app.db, box.id)).toEqual(opened); | |
| 167 | expect(lastRow()).toMatchObject({ player: "vic", kind: "refused" }); | |
| 168 | // An operator of one server only is not an operator of the box, whose door the lock shuts. | |
| 169 | grant(app.db, box.id, made.value.id, "operator", "hub"); | |
| 170 | chatAged(app.db, 3_600_001); | |
| 171 | const [again] = await send([request("lock", { uuid: VIC, name: "vic" })]); | |
| 172 | expect(again!.text).not.toStartWith("Locked"); | |
| 173 | expect(doorOf(app.db, box.id)).toEqual(opened); | |
| 174 | expect(lastRow()).toMatchObject({ player: "vic", kind: "refused", outcome: "not an operator of the box" }); | |
| 175 | }, 30_000); | |
| 176 | ||
| 177 | test("a lock between the yes and the commit stops the commit", async () => { | |
| 178 | openWindow(app.db, box.id, ada.id); | |
| 179 | const yes = await planned("late"); | |
| 180 | await send([yes], false); | |
| 181 | lockDoor(app.db, box.id, ada.id); | |
| 182 | await runChat(app, box.id); | |
| 183 | expect(toldTo(app.db, box, Date.now()).at(-1)!.text).toStartWith("The game door is locked, so nothing was changed"); | |
| 184 | expect(await compose()).not.toContain("\n late:\n"); | |
| 185 | expect(lastRow()).toMatchObject({ kind: "yes", outcome: "door locked", write_window: "locked" }); | |
| 186 | }, 30_000); | |
| 187 | ||
| 188 | test("a window ends by itself after its length, and a build after it is held", async () => { | |
| 189 | setWindowMinutes(app.db, box.id, 30); | |
| 190 | const at = Date.now() - 31 * 60_000; | |
| 191 | expect(openWindow(app.db, box.id, ada.id, at)).toMatchObject({ state: "open", minutes: 30 }); | |
| 192 | expect(doorOf(app.db, box.id, at + 29 * 60_000).state).toBe("open"); | |
| 193 | expect(doorOf(app.db, box.id).state).toBe("closed"); | |
| 194 | const [told] = await send([await planned("expired")]); | |
| 195 | expect(told!.text).toStartWith("Held: "); | |
| 196 | expect(await compose()).not.toContain("\n expired:\n"); | |
| 197 | }, 30_000); | |
| 198 | ||
| 199 | test("a window's length is 5 to 720 whole minutes", () => { | |
| 200 | expect(["4", "5", "60", "720", "721", "1.5", "", "60m"].map(windowMinutes)).toEqual([undefined, 5, 60, 720, undefined, undefined, undefined, undefined]); | |
| 201 | }); | |
| 202 | ||
| 203 | test("the page: the owner sees the door, Lock now locks it, and no passkey answer opens it", async () => { | |
| 204 | const http = forgeHttp(app); | |
| 205 | const cookie = `forge_session=${createSession(app.db, ada.id).token}`; | |
| 206 | const post = (path: string, form: Record<string, string>, origin = "http://forge.test") => | |
| 207 | http.handle(new Request(`http://forge.test${path}`, { method: "POST", headers: { cookie, origin, "content-type": "application/x-www-form-urlencoded" }, body: new URLSearchParams(form) })); | |
| 208 | const page = await (await http.handle(new Request("http://forge.test/games/mc", { headers: { cookie } }))).text(); | |
| 209 | expect(page).toContain('data-door="closed"'); | |
| 210 | expect(page).toContain("Long enough to build what you came to build"); | |
| 211 | openWindow(app.db, box.id, ada.id); | |
| 212 | expect((await post("/games/mc/door", { op: "lock" }, "http://evil.test")).status).toBeGreaterThanOrEqual(400); | |
| 213 | expect(doorOf(app.db, box.id).state).toBe("open"); | |
| 214 | expect((await post("/games/mc/door", { op: "lock" })).status).toBe(303); | |
| 215 | expect(doorOf(app.db, box.id).state).toBe("locked"); | |
| 216 | // A forged or empty passkey answer opens nothing. | |
| 217 | expect((await post("/games/mc/door", { op: "open", challenge: "", id: "", clientDataJSON: "", authenticatorData: "", signature: "" })).status).toBe(303); | |
| 218 | expect((await post("/games/mc/door", { op: "open", challenge: "made-up", id: "x", clientDataJSON: "x", authenticatorData: "x", signature: "x" })).status).toBe(303); | |
| 219 | expect(doorOf(app.db, box.id).state).toBe("locked"); | |
| 220 | expect((await post("/games/mc/door", { op: "minutes", minutes: "2" })).status).toBe(303); | |
| 221 | expect(doorOf(app.db, box.id).minutes).toBe(60); | |
| 222 | expect((await post("/games/mc/door", { op: "minutes", minutes: "90" })).status).toBe(303); | |
| 223 | expect(doorOf(app.db, box.id).minutes).toBe(90); | |
| 224 | // The challenge is the owner's, from the same origin. | |
| 225 | expect((await post("/games/mc/door/options", {}, "http://evil.test")).status).toBe(403); | |
| 226 | const options = (await (await post("/games/mc/door/options", {})).json()) as { challenge: string; rpId: string }; | |
| 227 | expect(options.rpId).toBe("forge.test"); | |
| 228 | expect(options.challenge.length).toBeGreaterThan(10); | |
| 229 | }, 30_000); |
test/openapi-drift.test.ts +2
| @@ -15,6 +15,7 @@ const NOT_ROUTED: Readonly<Record<string, string>> = { | ||
| 15 | 15 | "GET /{}/{}/pulls/{}/check.txt": "routed outside /api/v1 (src/http/server.ts, check_text.ts); test/openapi-check-txt.test.ts pins it to server.ts", |
| 16 | 16 | "POST /mcp": "routed outside /api/v1 (src/http/mcp.ts); the MCP has its own card and tool list", |
| 17 | 17 | "POST /settings/account/close/options": "routed outside /api/v1 (src/http/settings_routes.ts): the close form's passkey challenge, a browser session's JSON (#15619)", |
| 18 | "POST /games/{}/door/options": "routed outside /api/v1 (src/http/games_routes.ts): the game door's passkey challenge, a browser session's JSON (#18296)", | |
| 18 | 19 | "GET /.well-known/mcp-server-card.json": "routed outside /api/v1 (src/http/server.ts, web/standards.ts): the MCP server card a harness finds at a well-known path", |
| 19 | 20 | "GET /oembed": "routed outside /api/v1 (src/http/server.ts, web/standards.ts): the oEmbed endpoint other tools discover from a page's head", |
| 20 | 21 | "GET /explore.json": "routed outside /api/v1 (src/http/server.ts, explore_json.ts): the explore page's own JSON form (#15744)", |
| @@ -103,6 +104,7 @@ const SESSION_ONLY: ReadonlySet<string> = new Set([ | ||
| 103 | 104 | "DELETE /api/v1/tokens/{}", |
| 104 | 105 | "POST /api/v1/conversation-tokens", |
| 105 | 106 | "POST /settings/account/close/options", |
| 107 | "POST /games/{}/door/options", | |
| 106 | 108 | ]); |
| 107 | 109 | |
| 108 | 110 | test("an anonymous route takes no token, a token route is never anonymous, and every /admin route is admin only", () => { |
new above
offline
High-ish (medium): no role check here. Docs say
!forge locktakes an operator of the server, but any linked player, a viewer too, can lock and end the owner's passkey-opened window. Gate on operator (aschangesNetwork/role does for yes) and test that a viewer is refused and the window stays open.