Public: anyone can read this; the crew can change it.
iOS: use the same Talk and the game door's write window and lock (#18247) #18328
Parked 14h 25m ago
mason/forge:mason/18311-ios-use-the-same-talk-and-the-game-door → main 3 commits fork
17 files
changed +374
−24
- docs/features/games.md
- src/actions/game_door.ts
- src/contract/openapi/routes/getApiV1GamesBoxDoor.ts
- src/contract/openapi/routes/index.ts
- src/contract/openapi/routes/postApiV1GamesBoxDoorLock.ts
- src/contract/openapi/routes/postApiV1GamesBoxDoorMinutes.ts
- src/contract/openapi/routes/postApiV1GamesBoxDoorOpen.ts
- src/contract/openapi/routes/postApiV1GamesBoxDoorOptions.ts
- src/http/api/conversation_confirms.ts
- src/http/api/game_door.ts
- src/http/games_routes.ts
- src/http/lazy_lists.ts
- src/http/own_credential.ts
- src/web/pages/games_door.ts
- test/budgets/unfixtured/api-games-box-door.json
- test/game-door-api.test.ts
- test/security-floor-routes.test.ts
docs/features/games.md +2
| @@ -115,6 +115,8 @@ A server can show text whose click runs a command as the player, so a request th | ||
| 115 | 115 | |
| 116 | 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 | 117 | |
| 118 | **The door on iOS (#18311).** The iOS app drives the same door, and the same Talk, as the page: Talk and a held action's yes or no already ride `POST /api/v1/conversation/messages` and `POST /api/v1/conversation-confirms/:id`, so a build held in game is answered in the app and the answer shows on the web and in game. The door itself is five routes for the box's owner, on their own session or rw token (a conversation's via token, a run or an app token never): `GET /api/v1/games/<box>/door` (state, `says`, `why`, `passkey`), `POST …/door/lock`, `POST …/door/minutes` with `{ minutes }`, and a window with a passkey in two steps, `POST …/door/options` for a challenge (with `rpId` and the owner's key ids) and `POST …/door/open` with the signed answer (`challenge`, `id`, `clientDataJSON`, `authenticatorData`, `signature`). A password or a token alone never opens a window. The page and the routes call the same three acts in `src/actions/game_door.ts`; the routes are `src/http/api/game_door.ts`. The terminal shows the door and locks it (`w`); a window needs a passkey, so it opens on the web or in the app. | |
| 119 | ||
| 118 | 120 | 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. |
| 119 | 121 | |
| 120 | 122 | 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/game_door.ts added +68
| @@ -0,0 +1,68 @@ | ||
| 1 | /** | |
| 2 | * The game door's three acts, once for every door that asks (#18311): the web block on | |
| 3 | * /games/<box>, and the JSON routes the iOS app drives. Lock now, open a write window with a | |
| 4 | * passkey, and the window's length. Who may ask (the box's owner) and the same-origin check are | |
| 5 | * decided at each door; the state itself is `games/write_window.ts`. | |
| 6 | */ | |
| 7 | ||
| 8 | import type { App } from "../app.ts"; | |
| 9 | import { passkeyIds } from "../core/passkeys.ts"; | |
| 10 | import { getUserById, type User } from "../core/users.ts"; | |
| 11 | import type { GameBox } from "../games/store.ts"; | |
| 12 | import { doorOf, doorWords, lockDoor, openWindow, setWindowMinutes, WINDOW_WHY, windowMinutes, type DoorState } from "../games/write_window.ts"; | |
| 13 | import { passkeyProves, PROOF_FIELDS } from "./passkey_proof.ts"; | |
| 14 | ||
| 15 | /** | |
| 16 | * What a person reading the door is told: its state, its words, and whether they hold a passkey. | |
| 17 | */ | |
| 18 | export interface DoorView { | |
| 19 | readonly door: DoorState; | |
| 20 | readonly says: string; | |
| 21 | readonly why: string; | |
| 22 | readonly passkey: boolean; | |
| 23 | } | |
| 24 | ||
| 25 | /** The username of a user id, for the words ("someone" for one gone). */ | |
| 26 | const nameIn = | |
| 27 | (app: App) => | |
| 28 | (id: string): string => | |
| 29 | getUserById(app.db, id)?.username ?? "someone"; | |
| 30 | ||
| 31 | /** The door of `box` as `user` sees it. */ | |
| 32 | export function doorView(app: App, box: GameBox, user: User): DoorView { | |
| 33 | const door = doorOf(app.db, box.id); | |
| 34 | return { door, says: doorWords(door, nameIn(app)), why: WINDOW_WHY, passkey: passkeyIds(app.db, user.id).length > 0 }; | |
| 35 | } | |
| 36 | ||
| 37 | /** Locks the door at once. */ | |
| 38 | export function lockNow(app: App, box: GameBox, user: User): DoorState { | |
| 39 | return lockDoor(app.db, box.id, user.id); | |
| 40 | } | |
| 41 | ||
| 42 | /** | |
| 43 | * Sets the next window's length from typed text; undefined when it is not 5 to 720 whole minutes. | |
| 44 | */ | |
| 45 | export function setLength(app: App, box: GameBox, typed: string): number | undefined { | |
| 46 | const minutes = windowMinutes(typed); | |
| 47 | if (minutes !== undefined) setWindowMinutes(app.db, box.id, minutes); | |
| 48 | return minutes; | |
| 49 | } | |
| 50 | ||
| 51 | /** The fields a signed passkey answer carries, read from any bag of strings. */ | |
| 52 | export const proofOf = (get: (name: (typeof PROOF_FIELDS)[number]) => string): Record<(typeof PROOF_FIELDS)[number], string> => | |
| 53 | Object.fromEntries(PROOF_FIELDS.map((n) => [n, get(n)])) as Record<(typeof PROOF_FIELDS)[number], string>; | |
| 54 | ||
| 55 | /** | |
| 56 | * Opens a window when `answer` is a fresh challenge signed by one of `user`'s passkeys; the door | |
| 57 | * stays as it was otherwise (undefined). | |
| 58 | */ | |
| 59 | export async function openWithPasskey( | |
| 60 | app: App, | |
| 61 | box: GameBox, | |
| 62 | user: User, | |
| 63 | answer: Record<(typeof PROOF_FIELDS)[number], string>, | |
| 64 | rp: { readonly origin: string; readonly rpId: string }, | |
| 65 | ): Promise<DoorState | undefined> { | |
| 66 | if (answer.challenge === "" || !(await passkeyProves(app, user.id, answer, rp))) return undefined; | |
| 67 | return openWindow(app.db, box.id, user.id); | |
| 68 | } |
src/contract/openapi/routes/getApiV1GamesBoxDoor.ts added +12
| @@ -0,0 +1,12 @@ | ||
| 1 | import type { Route } from "../shared.ts"; | |
| 2 | ||
| 3 | export const route: Route = { | |
| 4 | method: "get", | |
| 5 | path: "/api/v1/games/{box}/door", | |
| 6 | summary: "How a game box's door stands: open, closed or locked, with its words", | |
| 7 | detail: "The game door of a box the caller owns (their own session or token; a box they see but do not own answers 403 `forbidden`): `state` is open, closed or locked, with `minutes` (the next window's length), `until` and `by` for an open window, `at` and `by` for a lock, `says` (the one line every door shows), `why` (why a window is as long as it is) and `passkey` (whether the owner holds a passkey, which a window needs). The iOS app reads it to draw the same block as /games/{box} (#18311)", | |
| 8 | auth: true, | |
| 9 | role: "member", | |
| 10 | reply: { state: "string", minutes: "number", says: "string", why: "string", passkey: "boolean" }, | |
| 11 | refuses: [401, 404], | |
| 12 | }; |
src/contract/openapi/routes/index.ts +5
| @@ -136,6 +136,7 @@ export { route as getApiV1ForgesTemplates } from "./getApiV1ForgesTemplates.ts"; | ||
| 136 | 136 | export { route as getApiV1ForksFlows } from "./getApiV1ForksFlows.ts"; |
| 137 | 137 | export { route as getApiV1Front } from "./getApiV1Front.ts"; |
| 138 | 138 | export { route as getApiV1GamesAgentScript } from "./getApiV1GamesAgentScript.ts"; |
| 139 | export { route as getApiV1GamesBoxDoor } from "./getApiV1GamesBoxDoor.ts"; | |
| 139 | 140 | export { route as getApiV1Health } from "./getApiV1Health.ts"; |
| 140 | 141 | export { route as getApiV1Here } from "./getApiV1Here.ts"; |
| 141 | 142 | export { route as getApiV1HomeLanes } from "./getApiV1HomeLanes.ts"; |
| @@ -418,6 +419,10 @@ export { route as postApiV1Forges } from "./postApiV1Forges.ts"; | ||
| 418 | 419 | export { route as postApiV1ForgesNameClaimLink } from "./postApiV1ForgesNameClaimLink.ts"; |
| 419 | 420 | export { route as postApiV1ForgesNameSandbox } from "./postApiV1ForgesNameSandbox.ts"; |
| 420 | 421 | export { route as postApiV1GamesAgentSync } from "./postApiV1GamesAgentSync.ts"; |
| 422 | export { route as postApiV1GamesBoxDoorLock } from "./postApiV1GamesBoxDoorLock.ts"; | |
| 423 | export { route as postApiV1GamesBoxDoorMinutes } from "./postApiV1GamesBoxDoorMinutes.ts"; | |
| 424 | export { route as postApiV1GamesBoxDoorOpen } from "./postApiV1GamesBoxDoorOpen.ts"; | |
| 425 | export { route as postApiV1GamesBoxDoorOptions } from "./postApiV1GamesBoxDoorOptions.ts"; | |
| 421 | 426 | export { route as postApiV1Heartbeat } from "./postApiV1Heartbeat.ts"; |
| 422 | 427 | export { route as postApiV1MailAws } from "./postApiV1MailAws.ts"; |
| 423 | 428 | export { route as postApiV1MaintenanceDutiesName } from "./postApiV1MaintenanceDutiesName.ts"; |
src/contract/openapi/routes/postApiV1GamesBoxDoorLock.ts added +12
| @@ -0,0 +1,12 @@ | ||
| 1 | import type { Route } from "../shared.ts"; | |
| 2 | ||
| 3 | export const route: Route = { | |
| 4 | method: "post", | |
| 5 | path: "/api/v1/games/{box}/door/lock", | |
| 6 | summary: "Lock a game box's door at once: an open window ends and writes are refused", | |
| 7 | detail: "Locks the door of a box the caller owns (rw scope, same origin for a browser): an open window ends, a write from the game is refused, not held, until the owner opens a window again with a passkey. Answers the door as it now stands (#18311)", | |
| 8 | auth: true, | |
| 9 | role: "member", | |
| 10 | reply: { state: "string", minutes: "number", says: "string" }, | |
| 11 | refuses: [401, 403, 404], | |
| 12 | }; |
src/contract/openapi/routes/postApiV1GamesBoxDoorMinutes.ts added +14
| @@ -0,0 +1,14 @@ | ||
| 1 | import type { Route } from "../shared.ts"; | |
| 2 | ||
| 3 | export const route: Route = { | |
| 4 | method: "post", | |
| 5 | path: "/api/v1/games/{box}/door/minutes", | |
| 6 | summary: "Set how long the next write window lasts", | |
| 7 | detail: "Sets the next window's length, 5 to 720 whole minutes; an open window keeps the end it was opened with. rw scope, same origin for a browser (#18311)", | |
| 8 | auth: true, | |
| 9 | role: "member", | |
| 10 | body: { minutes: "number" }, | |
| 11 | reply: { minutes: "number" }, | |
| 12 | refusals: { bad_minutes: "minutes is not 5 to 720 whole minutes (422)" }, | |
| 13 | refuses: [401, 403, 404], | |
| 14 | }; |
src/contract/openapi/routes/postApiV1GamesBoxDoorOpen.ts added +17
| @@ -0,0 +1,17 @@ | ||
| 1 | import type { Route } from "../shared.ts"; | |
| 2 | ||
| 3 | export const route: Route = { | |
| 4 | method: "post", | |
| 5 | path: "/api/v1/games/{box}/door/open", | |
| 6 | summary: "Open a box's write window with a signed passkey answer", | |
| 7 | detail: "Opens a write window of the box's length for the owner when the answer is a fresh challenge signed by one of their passkeys (a password never opens one); also lifts a lock. Answers the door as it now stands. rw scope, same origin for a browser (#18311)", | |
| 8 | auth: true, | |
| 9 | role: "member", | |
| 10 | body: { challenge: "string", id: "string", clientDataJSON: "string", authenticatorData: "string", signature: "string" }, | |
| 11 | reply: { state: "string", minutes: "number", until: "string", says: "string" }, | |
| 12 | refusals: { | |
| 13 | passkey_needed: "a field of the signed answer is missing (422)", | |
| 14 | passkey_refused: "the answer did not prove it is the owner's passkey; the door stays as it was (403)", | |
| 15 | }, | |
| 16 | refuses: [401, 403, 404], | |
| 17 | }; |
src/contract/openapi/routes/postApiV1GamesBoxDoorOptions.ts added +12
| @@ -0,0 +1,12 @@ | ||
| 1 | import type { Route } from "../shared.ts"; | |
| 2 | ||
| 3 | export const route: Route = { | |
| 4 | method: "post", | |
| 5 | path: "/api/v1/games/{box}/door/options", | |
| 6 | summary: "A passkey challenge to open a box's game door", | |
| 7 | detail: "Issues a one-use challenge, good for five minutes, and the ids of the owner's passkeys that may answer it; the signed answer goes to POST /api/v1/games/{box}/door/open (rw scope, same origin for a browser) (#18311)", | |
| 8 | auth: true, | |
| 9 | role: "member", | |
| 10 | reply: { challenge: "string", allow: "array", rpId: "string" }, | |
| 11 | refuses: [401, 403, 404], | |
| 12 | }; |
src/http/api/conversation_confirms.ts +3 −4
| @@ -10,16 +10,15 @@ import { scopeAllows } from "../../core/tokens.ts"; | ||
| 10 | 10 | import { REFUSED, sayNo, sayYes } from "../../actions/conversation_confirms.ts"; |
| 11 | 11 | import { crossOrigin, type Handler } from "../context.ts"; |
| 12 | 12 | import { apiError, boundedBody, forbidden, json, unauthorized } from "../respond.ts"; |
| 13 | import { ownCredential } from "../own_credential.ts"; | |
| 13 | 14 | import type { Router } from "../router.ts"; |
| 14 | 15 | |
| 15 | 16 | export function conversationConfirmRoutes(router: Router<Handler>): void { |
| 16 | 17 | router.add("POST", "/api/v1/conversation-confirms/:id", async (ctx) => { |
| 17 | 18 | const user = ctx.auth.user; |
| 18 | 19 | if (user === undefined) return unauthorized(); |
| 19 | // The person's own session, or their own rw token: never the forge's agent (a via token reaches | |
| 20 | // /mcp alone) nor a run, contribute or app token. | |
| 21 | const own = ctx.auth.via === "session" || (ctx.auth.via === "token" && ctx.auth.through === undefined && ctx.auth.run === undefined && ctx.auth.contribute === undefined && ctx.auth.appId === undefined); | |
| 22 | if (!own) return unauthorized(); | |
| 20 | // The person's own session, or their own rw token (`own_credential.ts`). | |
| 21 | if (!ownCredential(ctx)) return unauthorized(); | |
| 23 | 22 | if (crossOrigin(ctx.request, ctx.url, ctx.app.log)) return forbidden(); |
| 24 | 23 | if (ctx.auth.via === "token" && !scopeAllows(ctx.auth.scope ?? "ro", "rw")) return forbidden(); |
| 25 | 24 | // No body is a yes, as before; a body says `answer`: yes or no. |
src/http/api/game_door.ts added +86
| @@ -0,0 +1,86 @@ | ||
| 1 | /** | |
| 2 | * The game door over the API (#18311), for the iOS app: the same three acts as the block on | |
| 3 | * /games/<box> (`web/pages/games_door.ts`), through `actions/game_door.ts`. Only the box's owner, | |
| 4 | * on their own session or rw token (`own_credential.ts`); a window opens only with a passkey the | |
| 5 | * owner signs (`POST …/door/options` hands out the challenge, `POST …/door/open` takes the signed | |
| 6 | * answer), and the same-origin check holds for a browser's request. | |
| 7 | */ | |
| 8 | ||
| 9 | import { doorView, lockNow, openWithPasskey, proofOf, setLength } from "../../actions/game_door.ts"; | |
| 10 | import { proofChallenge, PROOF_FIELDS } from "../../actions/passkey_proof.ts"; | |
| 11 | import { scopeAllows } from "../../core/tokens.ts"; | |
| 12 | import { boxNamed, mayDo, roleOn, seesBox, type GameBox } from "../../games/store.ts"; | |
| 13 | import { doorWords } from "../../games/write_window.ts"; | |
| 14 | import { crossOrigin, type Ctx, type Handler } from "../context.ts"; | |
| 15 | import { ownCredential } from "../own_credential.ts"; | |
| 16 | import { apiError, boundedBody, forbidden, json, notFound, str, unauthorized } from "../respond.ts"; | |
| 17 | import type { Router } from "../router.ts"; | |
| 18 | ||
| 19 | const OWNER_ONLY = "Only the box's owner changes its game door."; | |
| 20 | ||
| 21 | /** The box the path names, when the caller sees it and owns it; else the answer to give. */ | |
| 22 | function ownedBox(ctx: Ctx, write: boolean): { box: GameBox } | Response { | |
| 23 | const user = ctx.auth.user; | |
| 24 | if (user === undefined) return unauthorized(); | |
| 25 | if (!ownCredential(ctx)) return unauthorized(); | |
| 26 | if (write) { | |
| 27 | if (crossOrigin(ctx.request, ctx.url, ctx.app.log)) return forbidden(); | |
| 28 | if (ctx.auth.via === "token" && !scopeAllows(ctx.auth.scope ?? "ro", "rw")) return forbidden(); | |
| 29 | } | |
| 30 | const box = boxNamed(ctx.app.db, ctx.params["box"] ?? ""); | |
| 31 | if (box === undefined || !seesBox(ctx.app.db, user, box.id)) return notFound(); | |
| 32 | if (!mayDo(roleOn(ctx.app.db, user, box.id), "owner")) return apiError("forbidden", 403, OWNER_ONLY); | |
| 33 | return { box }; | |
| 34 | } | |
| 35 | ||
| 36 | async function input(ctx: Ctx): Promise<Record<string, unknown> | Response> { | |
| 37 | const got = await boundedBody(ctx.request, 8_000); | |
| 38 | return got === "too_large" ? apiError("too_large", 413, "at most 8000 bytes") : got; | |
| 39 | } | |
| 40 | ||
| 41 | export function gameDoorRoutes(router: Router<Handler>): void { | |
| 42 | router.add("GET", "/api/v1/games/:box/door", (ctx) => { | |
| 43 | const got = ownedBox(ctx, false); | |
| 44 | if (got instanceof Response) return got; | |
| 45 | const { door, says, why, passkey } = doorView(ctx.app, got.box, ctx.auth.user!); | |
| 46 | return json({ ...door, says, why, passkey }); | |
| 47 | }); | |
| 48 | ||
| 49 | router.add("POST", "/api/v1/games/:box/door/lock", (ctx) => { | |
| 50 | const got = ownedBox(ctx, true); | |
| 51 | if (got instanceof Response) return got; | |
| 52 | const door = lockNow(ctx.app, got.box, ctx.auth.user!); | |
| 53 | return json({ ...door, says: doorWords(door, () => ctx.auth.user!.username) }); | |
| 54 | }); | |
| 55 | ||
| 56 | // A passkey challenge for the owner, and the keys that may answer it. | |
| 57 | router.add("POST", "/api/v1/games/:box/door/options", (ctx) => { | |
| 58 | const got = ownedBox(ctx, true); | |
| 59 | if (got instanceof Response) return got; | |
| 60 | return json({ ...proofChallenge(ctx.app, ctx.auth.user!.id), rpId: ctx.url.hostname }); | |
| 61 | }); | |
| 62 | ||
| 63 | router.add("POST", "/api/v1/games/:box/door/open", async (ctx) => { | |
| 64 | const got = ownedBox(ctx, true); | |
| 65 | if (got instanceof Response) return got; | |
| 66 | const body = await input(ctx); | |
| 67 | if (body instanceof Response) return body; | |
| 68 | const answer = proofOf((n) => str(body[n])); | |
| 69 | if (PROOF_FIELDS.some((n) => answer[n] === "")) return apiError("passkey_needed", 422, `A window opens with a passkey's signed answer: ${PROOF_FIELDS.join(", ")}.`); | |
| 70 | const user = ctx.auth.user!; | |
| 71 | const door = await openWithPasskey(ctx.app, got.box, user, answer, { origin: ctx.url.origin, rpId: ctx.url.hostname }); | |
| 72 | if (door === undefined) return apiError("passkey_refused", 403, "That passkey answer did not prove it is you. The game door stays as it was."); | |
| 73 | return json({ ...door, says: doorView(ctx.app, got.box, user).says }); | |
| 74 | }); | |
| 75 | ||
| 76 | router.add("POST", "/api/v1/games/:box/door/minutes", async (ctx) => { | |
| 77 | const got = ownedBox(ctx, true); | |
| 78 | if (got instanceof Response) return got; | |
| 79 | const body = await input(ctx); | |
| 80 | if (body instanceof Response) return body; | |
| 81 | const typed = typeof body["minutes"] === "number" ? String(body["minutes"]) : str(body["minutes"]); | |
| 82 | const minutes = setLength(ctx.app, got.box, typed); | |
| 83 | if (minutes === undefined) return apiError("bad_minutes", 422, "A window is 5 to 720 whole minutes."); | |
| 84 | return json({ minutes }); | |
| 85 | }); | |
| 86 | } |
src/http/games_routes.ts +2
| @@ -33,6 +33,7 @@ import { gameSparkView } from "../web/pages/games_spark_view.ts"; | ||
| 33 | 33 | import { gameSparkLink, gameSparkOpen, gameSparkPost, gameSparkRead } from "../web/pages/games_spark.ts"; |
| 34 | 34 | import { gameConfigCommit, gameConfigPage, gameConfigPreview } from "../web/pages/games_config.ts"; |
| 35 | 35 | import { gameDoorOptions, gameDoorSubmit } from "../web/pages/games_door.ts"; |
| 36 | import { gameDoorRoutes } from "./api/game_door.ts"; | |
| 36 | 37 | import { publicOrigin } from "../core/public_origin.ts"; |
| 37 | 38 | import type { Ctx, Handler } from "./context.ts"; |
| 38 | 39 | import { InvalidJson } from "./json_body.ts"; |
| @@ -170,6 +171,7 @@ export function gameAgentScript(ctx: Ctx): Response { | ||
| 170 | 171 | export function gamesApiRoutes(router: Router<Handler>): void { |
| 171 | 172 | router.add("POST", "/api/v1/games/agent/sync", gameAgentSync); |
| 172 | 173 | router.add("GET", "/api/v1/games/agent/script", gameAgentScript); |
| 174 | gameDoorRoutes(router); | |
| 173 | 175 | } |
| 174 | 176 | |
| 175 | 177 | export function gamesRoutes(router: Router<Handler>): void { |
src/http/lazy_lists.ts +5
| @@ -1363,6 +1363,11 @@ export const API_ROUTES = [ | ||
| 1363 | 1363 | ["GET", "/api/v1/arcade/games"], |
| 1364 | 1364 | ["POST", "/api/v1/games/agent/sync"], |
| 1365 | 1365 | ["GET", "/api/v1/games/agent/script"], |
| 1366 | ["GET", "/api/v1/games/:box/door"], | |
| 1367 | ["POST", "/api/v1/games/:box/door/lock"], | |
| 1368 | ["POST", "/api/v1/games/:box/door/options"], | |
| 1369 | ["POST", "/api/v1/games/:box/door/open"], | |
| 1370 | ["POST", "/api/v1/games/:box/door/minutes"], | |
| 1366 | 1371 | ["GET", "/api/v1/admin/maintenance"], |
| 1367 | 1372 | ["POST", "/api/v1/admin/maintenance/prepare"], |
| 1368 | 1373 | ["POST", "/api/v1/admin/maintenance/resume"], |
src/http/own_credential.ts added +10
| @@ -0,0 +1,10 @@ | ||
| 1 | /** | |
| 2 | * Whether a request is the person's own: their browser session, or their own token. Never the | |
| 3 | * forge's agent (a conversation's via token reaches `/mcp` alone) nor a run, contribute or app | |
| 4 | * token. A yes to a held action and a game door's window ask this (#7650, #18311). | |
| 5 | */ | |
| 6 | ||
| 7 | import type { Ctx } from "./context.ts"; | |
| 8 | ||
| 9 | export const ownCredential = (ctx: Ctx): boolean => | |
| 10 | ctx.auth.via === "session" || (ctx.auth.via === "token" && ctx.auth.through === undefined && ctx.auth.run === undefined && ctx.auth.contribute === undefined && ctx.auth.appId === undefined); |
src/web/pages/games_door.ts +10 −20
| @@ -5,10 +5,9 @@ | ||
| 5 | 5 | * (`tui/screens/games.ts`, `w` locks); `/forge lock` locks from the game. |
| 6 | 6 | */ |
| 7 | 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"; | |
| 8 | import { doorView, lockNow, openWithPasskey, proofOf, setLength } from "../../actions/game_door.ts"; | |
| 9 | import { proofChallenge, PROOF_FIELDS } from "../../actions/passkey_proof.ts"; | |
| 10 | import { WINDOW_WHY } from "../../games/write_window.ts"; | |
| 12 | 11 | import type { GameBox } from "../../games/store.ts"; |
| 13 | 12 | import { crossOrigin, type Ctx } from "../../http/context.ts"; |
| 14 | 13 | import { json } from "../../http/respond.ts"; |
| @@ -21,21 +20,15 @@ import { CAME_FROM_ELSEWHERE } from "../chrome.ts"; | ||
| 21 | 20 | import { btn } from "../ui.ts"; |
| 22 | 21 | import { boxOf } from "./games.ts"; |
| 23 | 22 | |
| 24 | const nameOf = | |
| 25 | (ctx: Ctx) => | |
| 26 | (id: string): string => | |
| 27 | getUserById(ctx.app.db, id)?.username ?? "someone"; | |
| 28 | ||
| 29 | 23 | /** The block; whether the page needs the passkey script is `passkey`. */ |
| 30 | 24 | 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; | |
| 25 | const { door: d, says, passkey } = doorView(ctx.app, box, ctx.auth.user!); | |
| 33 | 26 | const action = `/games/${box.name}/door`; |
| 34 | 27 | return { |
| 35 | 28 | passkey, |
| 36 | 29 | html: html`<section class="settings-block" id="door" data-door="${d.state}"> |
| 37 | 30 | <h2>Game door</h2> |
| 38 | <p class="small" data-door-says>${doorWords(d, nameOf(ctx))}</p> | |
| 31 | <p class="small" data-door-says>${says}</p> | |
| 39 | 32 | <div class="row-fields"> |
| 40 | 33 | ${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 | 34 | ${passkey |
| @@ -80,19 +73,16 @@ export async function gameDoorSubmit(ctx: Ctx): Promise<Response> { | ||
| 80 | 73 | const back = `/games/${box.name}#door`; |
| 81 | 74 | const op = field(form, "op"); |
| 82 | 75 | if (op === "lock") { |
| 83 | lockDoor(ctx.app.db, box.id, user.id); | |
| 76 | lockNow(ctx.app, box, user); | |
| 84 | 77 | return flashTo(ctx, back, { message: "Locked: the game door only reads now." }); |
| 85 | 78 | } |
| 86 | 79 | if (op === "minutes") { |
| 87 | const minutes = windowMinutes(field(form, "minutes")); | |
| 80 | const minutes = setLength(ctx.app, box, field(form, "minutes")); | |
| 88 | 81 | 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 | 82 | return flashTo(ctx, back, { message: `The next write window lasts ${String(minutes)} minutes.` }); |
| 91 | 83 | } |
| 92 | 84 | 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)) }); | |
| 85 | const d = await openWithPasskey(ctx.app, box, user, proofOf((n) => field(form, n)), { origin: ctx.url.origin, rpId: ctx.url.hostname }); | |
| 86 | if (d === undefined) return flashTo(ctx, back, { tone: "danger", message: `${PASSKEY_REJECTED} The game door stays as it was.` }); | |
| 87 | return flashTo(ctx, back, { message: doorView(ctx.app, box, user).says }); | |
| 98 | 88 | } |
test/budgets/unfixtured/api-games-box-door.json added +4
test/game-door-api.test.ts added +111
| @@ -0,0 +1,111 @@ | ||
| 1 | /** | |
| 2 | * The game door over the API (#18311): what the iOS app drives. The owner reads the door, locks it, | |
| 3 | * sets its length and asks a passkey challenge on their own session or rw token; nobody else does, | |
| 4 | * a read-only token and another origin change nothing, and a window opens only on a signed answer. | |
| 5 | */ | |
| 6 | import { afterAll, beforeAll, beforeEach, expect, test } from "bun:test"; | |
| 7 | import { rm } from "node:fs/promises"; | |
| 8 | import type { App } from "../src/app.ts"; | |
| 9 | import { createSession } from "../src/core/sessions.ts"; | |
| 10 | import { createToken } from "../src/core/tokens.ts"; | |
| 11 | import { createUser } from "../src/core/users.ts"; | |
| 12 | import { grant, type GameBox } from "../src/games/store.ts"; | |
| 13 | import { doorOf, openWindow } from "../src/games/write_window.ts"; | |
| 14 | import { forgeHttp } from "../src/http/server.ts"; | |
| 15 | import { openRig, type Rig } from "./helpers/game-door-rig.ts"; | |
| 16 | import { quietLogs } from "./helpers/globals.ts"; | |
| 17 | ||
| 18 | quietLogs(); | |
| 19 | ||
| 20 | let rig: Rig; | |
| 21 | let app: App; | |
| 22 | let box: GameBox; | |
| 23 | let rw = ""; | |
| 24 | let ro = ""; | |
| 25 | let bobToken = ""; | |
| 26 | let bobId = ""; | |
| 27 | ||
| 28 | const http = () => forgeHttp(app); | |
| 29 | const call = (method: string, path: string, auth: string, body?: unknown, headers: Record<string, string> = {}) => | |
| 30 | http().handle( | |
| 31 | new Request(`http://forge.test/api/v1/games/mc/door${path}`, { | |
| 32 | method, | |
| 33 | headers: { authorization: `Bearer ${auth}`, "content-type": "application/json", ...headers }, | |
| 34 | body: body === undefined ? undefined : JSON.stringify(body), | |
| 35 | }), | |
| 36 | ); | |
| 37 | ||
| 38 | beforeAll(async () => { | |
| 39 | rig = await openRig("forge-game-door-api-"); | |
| 40 | ({ app, box } = rig); | |
| 41 | rw = createToken(app.db, rig.ada.id, "ios", "rw").token; | |
| 42 | ro = createToken(app.db, rig.ada.id, "watch", "ro").token; | |
| 43 | const bob = await createUser(app.db, { username: "bob", email: "[email protected]", password: "a-good-passphrase", origin: "seed", trusted: true }); | |
| 44 | if (!bob.ok) throw new Error(bob.error); | |
| 45 | bobId = bob.value.id; | |
| 46 | bobToken = createToken(app.db, bobId, "ios", "rw").token; | |
| 47 | }, 30_000); | |
| 48 | beforeEach(() => { | |
| 49 | app.db.query("DELETE FROM game_door").run(); | |
| 50 | grant(app.db, box.id, bobId, "none"); | |
| 51 | }); | |
| 52 | afterAll(async () => { | |
| 53 | app.close(); | |
| 54 | await rm(rig.dir, { recursive: true, force: true }); | |
| 55 | }); | |
| 56 | ||
| 57 | test("the owner reads the door, the same words as the page", async () => { | |
| 58 | const r = await call("GET", "", rw); | |
| 59 | expect(r.status).toBe(200); | |
| 60 | expect(await r.json()).toMatchObject({ state: "closed", minutes: 60, passkey: false, says: expect.stringContaining("Closed") }); | |
| 61 | openWindow(app.db, box.id, rig.ada.id); | |
| 62 | expect(await (await call("GET", "", ro)).json()).toMatchObject({ state: "open", by: rig.ada.id }); | |
| 63 | }); | |
| 64 | ||
| 65 | test("lock ends an open window at once; a read-only token or another origin changes nothing", async () => { | |
| 66 | openWindow(app.db, box.id, rig.ada.id); | |
| 67 | expect((await call("POST", "/lock", ro)).status).toBe(403); | |
| 68 | const session = `forge_session=${createSession(app.db, rig.ada.id).token}`; | |
| 69 | const cross = await http().handle(new Request("http://forge.test/api/v1/games/mc/door/lock", { method: "POST", headers: { cookie: session, origin: "http://evil.test" } })); | |
| 70 | expect(cross.status).toBe(403); | |
| 71 | expect(doorOf(app.db, box.id).state).toBe("open"); | |
| 72 | const r = await call("POST", "/lock", rw); | |
| 73 | expect(r.status).toBe(200); | |
| 74 | expect(await r.json()).toMatchObject({ state: "locked" }); | |
| 75 | expect(doorOf(app.db, box.id).state).toBe("locked"); | |
| 76 | }); | |
| 77 | ||
| 78 | test("only the box's owner: a stranger sees no box, an operator is refused", async () => { | |
| 79 | expect((await call("GET", "", bobToken)).status).toBe(404); | |
| 80 | expect((await call("POST", "/lock", bobToken)).status).toBe(404); | |
| 81 | grant(app.db, box.id, bobId, "operator"); | |
| 82 | expect((await call("GET", "", bobToken)).status).toBe(403); | |
| 83 | expect((await call("POST", "/lock", bobToken)).status).toBe(403); | |
| 84 | expect((await call("POST", "/options", bobToken, {})).status).toBe(403); | |
| 85 | expect(doorOf(app.db, box.id).state).toBe("closed"); | |
| 86 | expect((await http().handle(new Request("http://forge.test/api/v1/games/mc/door"))).status).toBe(401); | |
| 87 | }); | |
| 88 | ||
| 89 | test("a window length is 5 to 720 whole minutes", async () => { | |
| 90 | expect((await call("POST", "/minutes", rw, { minutes: 2 })).status).toBe(422); | |
| 91 | expect((await call("POST", "/minutes", rw, { minutes: "1.5" })).status).toBe(422); | |
| 92 | expect((await call("POST", "/minutes", ro, { minutes: 90 })).status).toBe(403); | |
| 93 | expect(doorOf(app.db, box.id).minutes).toBe(60); | |
| 94 | const r = await call("POST", "/minutes", rw, { minutes: 90 }); | |
| 95 | expect(await r.json()).toEqual({ minutes: 90 }); | |
| 96 | expect(doorOf(app.db, box.id).minutes).toBe(90); | |
| 97 | }); | |
| 98 | ||
| 99 | test("a window opens only on a signed passkey answer", async () => { | |
| 100 | const options = (await (await call("POST", "/options", rw, {})).json()) as { challenge: string; rpId: string }; | |
| 101 | expect(options.rpId).toBe("forge.test"); | |
| 102 | expect(options.challenge.length).toBeGreaterThan(10); | |
| 103 | // Missing fields, a made-up answer and a password-less token alone open nothing. | |
| 104 | expect((await call("POST", "/open", rw, {})).status).toBe(422); | |
| 105 | const made = { challenge: options.challenge, id: "x", clientDataJSON: "x", authenticatorData: "x", signature: "x" }; | |
| 106 | expect((await call("POST", "/open", rw, made)).status).toBe(403); | |
| 107 | // The challenge answered once is spent. | |
| 108 | expect((await call("POST", "/open", rw, made)).status).toBe(403); | |
| 109 | expect((await call("POST", "/open", ro, made)).status).toBe(403); | |
| 110 | expect(doorOf(app.db, box.id).state).toBe("closed"); | |
| 111 | }); |
test/security-floor-routes.test.ts +1
| @@ -73,6 +73,7 @@ const UNSEEDED: Record<string, string> = { | ||
| 73 | 73 | "/tabforge-link/:id": "a shared tab-forge app named by a random id the seed does not hold (test/tab-share.test.ts covers it)", |
| 74 | 74 | "/tab/v/:hash/:file": "a vendored file of the browser-tab forge, named by its content hash, which the seed does not hold (test/tab.test.ts covers it)", |
| 75 | 75 | "/infra/end/:act/*path": "the plan of a stop or delete for a cloud resource, which the seed does not have (test/cloud-end.test.ts covers it)", |
| 76 | "/api/v1/games/:box/door": "a game box, which the seed does not make (test/game-door-api.test.ts covers it)", | |
| 76 | 77 | "/games/:box": "a game box, which the seed does not make (test/games.test.ts covers it)", |
| 77 | 78 | "/games/:box/:service": "a game box, which the seed does not make (test/games.test.ts covers it)", |
| 78 | 79 | "/games/:box/@shell/stream": "a game box's shell output for its owner, which the seed does not make (test/game-console.test.ts covers it)", |
new above
offline