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

The Apple app can read the game door, lock it and open a write window, through one JSON route #18341

opened this

Merged 51m ago, live in production

scout/forge:scout/18337-the-apple-app-can-read-the-game-door-loc → main 0 commits fork

  • Merged. scout/18337-the-apple-app-can-read-the-game-door-loc was merged into main as 37d7870.

Review

Sign in to review this change.
10 files changed +244 −0
docs/features/game-box.md +4
@@ -51,3 +51,7 @@ Code: `src/games/store.ts` (the `game_box` row and its token, the games store's)
5151 ## Key exchange (#18032)
5252
5353 Every hour the agent reads the TLS group its HTTPS to the forge negotiates (`openssl s_client`), logs it (`TLS key exchange with the forge: X25519MLKEM768`) and sends it as `diag.tlsGroup`. The box's owner reads it under "Key exchange with the forge" on `/games/<box>` and in the terminal's box screen (`b` in Games): a hybrid with ML-KEM reads "(post-quantum hybrid)", any other group "(classical)". Nothing is refused for a classical group, and an older or unreadable box shows no line. New boxes only: the live `mc` box stays on 24.04 until it is moved on purpose.
54
55 ## The game door from the Apple app (#18337)
56
57 `/api/v1/games/<box>/door` (`src/http/api/game_door.ts`) is the door's third way beside `/games/<box>` and the terminal's box screen (`w`): the same code (`src/games/write_window.ts`, `src/actions/passkey_proof.ts`), the box's owner only (forge admins own every box); anyone else gets 404. `GET` (a read token) answers the door as `{ state, minutes, …, words }`. `POST` (a write token; a cookie's post must be same-origin) takes `{ "op": "lock" }`; `{ "op": "challenge" }` for a passkey challenge, `allow` (the keys that may answer) and `rpId`; and `{ "op": "open", challenge, id, clientDataJSON, authenticatorData, signature }`, which opens a window of the box's length only when one of the owner's passkeys signed the challenge just now, else 403 in words and the door as it was. Setting the window's length and lock-on-leave stay on the page and in the terminal. Neither door writes an audit row for these: the page's own lock and open write none.
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: "A game box's door: locked or open, and the words the page says of it",
7 detail: "For the box's owner only; anyone else is told the box is not there. Answers the door's state and `words`.",
8 auth: true,
9 role: "member",
10 refusals: { unauthorized: "401: no signed-in account", not_found: "404: no such box, or not yours" },
11 errorStatus: { 401: "`unauthorized`: no signed-in account", 404: "`not_found`: no such box, or not yours" },
12 };
src/contract/openapi/routes/index.ts +2
@@ -136,6 +136,7 @@ export { route as getApiV1ForgesTemplates } from "./getApiV1ForgesTemplates.ts";
136136 export { route as getApiV1ForksFlows } from "./getApiV1ForksFlows.ts";
137137 export { route as getApiV1Front } from "./getApiV1Front.ts";
138138 export { route as getApiV1GamesAgentScript } from "./getApiV1GamesAgentScript.ts";
139 export { route as getApiV1GamesBoxDoor } from "./getApiV1GamesBoxDoor.ts";
139140 export { route as getApiV1Health } from "./getApiV1Health.ts";
140141 export { route as getApiV1Here } from "./getApiV1Here.ts";
141142 export { route as getApiV1HomeLanes } from "./getApiV1HomeLanes.ts";
@@ -418,6 +419,7 @@ export { route as postApiV1Forges } from "./postApiV1Forges.ts";
418419 export { route as postApiV1ForgesNameClaimLink } from "./postApiV1ForgesNameClaimLink.ts";
419420 export { route as postApiV1ForgesNameSandbox } from "./postApiV1ForgesNameSandbox.ts";
420421 export { route as postApiV1GamesAgentSync } from "./postApiV1GamesAgentSync.ts";
422 export { route as postApiV1GamesBoxDoor } from "./postApiV1GamesBoxDoor.ts";
421423 export { route as postApiV1Heartbeat } from "./postApiV1Heartbeat.ts";
422424 export { route as postApiV1MailAws } from "./postApiV1MailAws.ts";
423425 export { route as postApiV1MaintenanceDutiesName } from "./postApiV1MaintenanceDutiesName.ts";
src/contract/openapi/routes/postApiV1GamesBoxDoor.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",
6 summary: "Lock a game box's door, ask for a passkey challenge, or open a write window",
7 detail: "For the box's owner only. Send `{ op: \"lock\" }` to lock; `{ op: \"challenge\" }` for a passkey challenge and rpId; `{ op: \"open\", ...signed answer }` to open a window, which needs a passkey signed just now. Answers the door's state and `words`.",
8 auth: true,
9 role: "member",
10 refusals: { unauthorized: "401: no signed-in account", not_found: "404: no such box, or not yours" },
11 errorStatus: { 401: "`unauthorized`: no signed-in account", 403: "`passkey_required`: opening needs a fresh passkey", 404: "`not_found`: no such box, or not yours", 422: "`invalid_body`: op is lock, challenge or open" },
12 };
src/http/api.ts +2
@@ -364,6 +364,7 @@ import { takeOrder } from "../crew/take_order.ts";
364364 import { forgeCarries } from "../origins/words.ts";
365365 import { forgeOriginRoutes } from "./api/forge_origin.ts";
366366 import { appleTelemetryRoutes } from "./api/telemetry_apple.ts";
367 import { gameDoorApiRoutes } from "./api/game_door.ts";
367368 import { crashReportRoutes } from "./api/crash_reports.ts";
368369 import { pushDeviceRoutes } from "./api/push_devices.ts";
369370 import { userRoutes } from "./api/user.ts";
@@ -1291,6 +1292,7 @@ export function apiRoutes(router: Router<Handler>, isPage: (path: string) => boo
12911292 mayRoutes(router);
12921293 pushDeviceRoutes(router);
12931294 appleTelemetryRoutes(router);
1295 gameDoorApiRoutes(router);
12941296 crashReportRoutes(router);
12951297 forgeOriginRoutes(router);
12961298 adminRoutes(router);
src/http/api/game_door.ts added +62
@@ -0,0 +1,62 @@
1 /**
2 * `/api/v1/games/:box/door`: the game door for the Apple app (#18337), what /games/<box> does for
3 * the box's owner, from the same code (`games/write_window.ts`, `actions/passkey_proof.ts`). GET
4 * reads the door; POST `op` is `lock`, `challenge` (a passkey challenge and the keys that may
5 * answer it) or `open` (a window, only with the signed answer in the body's `PROOF_FIELDS`). Anyone
6 * who is not the box's owner is told the box is not there. Bearer tokens and the session cookie
7 * both work; a cookie's post must be same-origin (`requireScope`).
8 */
9
10 import { passkeyProves, proofChallenge, PROOF_FIELDS } from "../../actions/passkey_proof.ts";
11 import { getUserById } from "../../core/users.ts";
12 import { boxNamed, mayDo, roleOn } from "../../games/store.ts";
13 import { doorOf, doorWords, lockDoor, openWindow } from "../../games/write_window.ts";
14 import type { Ctx, Handler } from "../context.ts";
15 import { apiError, body, json, notFound, requireScope } from "../respond.ts";
16 import type { Router } from "../router.ts";
17
18 /** The box when the caller owns it. */
19 function ownedBox(ctx: Ctx) {
20 const user = ctx.auth.user;
21 const box = user === null || user === undefined ? undefined : boxNamed(ctx.app.db, ctx.params.box ?? "");
22 return user && box && mayDo(roleOn(ctx.app.db, user, box.id), "owner") ? box : undefined;
23 }
24
25 /** The door as the app reads it: the state and the words the page says of it. */
26 function doorView(ctx: Ctx, boxId: string): Response {
27 const d = doorOf(ctx.app.db, boxId);
28 return json({ ...d, words: doorWords(d, (id) => getUserById(ctx.app.db, id)?.username ?? "someone") });
29 }
30
31 export function gameDoorApiRoutes(router: Router<Handler>): void {
32 router.add("GET", "/api/v1/games/:box/door", (ctx) => {
33 const denied = requireScope(ctx, "ro");
34 if (denied) return denied;
35 const box = ownedBox(ctx);
36 return box ? doorView(ctx, box.id) : notFound();
37 });
38 router.add("POST", "/api/v1/games/:box/door", async (ctx) => {
39 const denied = requireScope(ctx, "rw");
40 if (denied) return denied;
41 const box = ownedBox(ctx);
42 if (!box) return notFound();
43 const user = ctx.auth.user!;
44 const input = await body(ctx.request);
45 const op = input.op;
46 if (op === "lock") {
47 lockDoor(ctx.app.db, box.id, user.id);
48 return doorView(ctx, box.id);
49 }
50 if (op === "challenge") return json({ ...proofChallenge(ctx.app, user.id), rpId: ctx.url.hostname });
51 if (op !== "open") return apiError("invalid_body", 422, "op is lock, challenge or open.");
52 const answer = {} as Record<(typeof PROOF_FIELDS)[number], string>;
53 for (const n of PROOF_FIELDS) {
54 const v = input[n];
55 answer[n] = typeof v === "string" && v.length <= 8192 ? v : "";
56 }
57 if (answer.challenge === "" || !(await passkeyProves(ctx.app, user.id, answer, { origin: ctx.url.origin, rpId: ctx.url.hostname })))
58 return apiError("passkey_required", 403, "Opening a write window needs a passkey of yours, signed just now. The game door stays as it was.");
59 openWindow(ctx.app.db, box.id, user.id);
60 return doorView(ctx, box.id);
61 });
62 }
src/http/lazy_lists.ts +2
@@ -1282,6 +1282,8 @@ export const API_ROUTES = [
12821282 ["POST", "/api/v1/user/devices"],
12831283 ["DELETE", "/api/v1/user/devices/:id"],
12841284 ["POST", "/api/v1/telemetry/apple"],
1285 ["GET", "/api/v1/games/:box/door"],
1286 ["POST", "/api/v1/games/:box/door"],
12851287 ["POST", "/api/v1/repos/:owner/:name/crash-reports"],
12861288 ["POST", "/api/v1/apps/:owner/:name/crash-reports"],
12871289 ["GET", "/api/v1/repos/:owner/:name/report-key"],
test/budgets/unfixtured/api-v1-games-box-door.json added +4
@@ -0,0 +1,4 @@
1 {
2 "pattern": "/api/v1/games/:box/door",
3 "why": "no fixture holds a game box this route needs"
4 }
test/game-door-api.test.ts added +143
@@ -0,0 +1,143 @@
1 /**
2 * The game door for the Apple app (#18337): GET reads it, POST locks it, and opens a window only
3 * with a passkey's signed answer; anyone but the box's owner is told the box is not there.
4 */
5 import { afterAll, beforeAll, beforeEach, expect, test } from "bun:test";
6 import { mkdtempSync } from "node:fs";
7 import { rm } from "node:fs/promises";
8 import { tmpdir } from "node:os";
9 import { join } from "node:path";
10 import { createApp, type App } from "../src/app.ts";
11 import { b64u } from "../src/auth/webauthn.ts";
12 import { addPasskey } from "../src/core/passkeys.ts";
13 import { createSession } from "../src/core/sessions.ts";
14 import { createToken } from "../src/core/tokens.ts";
15 import { createUser, type User } from "../src/core/users.ts";
16 import { boxNamed, createGameBox, grant } from "../src/games/store.ts";
17 import { doorOf, WINDOW_MINUTES } from "../src/games/write_window.ts";
18 import { forgeHttp } from "../src/http/server.ts";
19 import { quietLogs } from "./helpers/globals.ts";
20
21 quietLogs();
22
23 const ORIGIN = "http://forge.test";
24 const te = new TextEncoder();
25 const sha = async (d: Uint8Array<ArrayBuffer>) => new Uint8Array(await crypto.subtle.digest("SHA-256", d));
26
27 let dir = "";
28 let app: App;
29 let ada: User;
30 let boxId = "";
31 let adaToken = "";
32 let bobToken = "";
33 let key: CryptoKeyPair;
34 let count = 0;
35
36 const call = (method: string, token: string, body?: unknown, headers: Record<string, string> = {}) =>
37 forgeHttp(app).handle(
38 new Request(`${ORIGIN}/api/v1/games/mc/door`, {
39 method,
40 headers: { authorization: `Bearer ${token}`, "content-type": "application/json", ...headers },
41 body: body === undefined ? undefined : JSON.stringify(body),
42 }),
43 );
44
45 /** A signed answer to `challenge`, as the app's passkey would give it. */
46 async function sign(challenge: string, id: string): Promise<Record<string, string>> {
47 const clientData = te.encode(JSON.stringify({ type: "webauthn.get", challenge, origin: ORIGIN }));
48 const authData = new Uint8Array(37);
49 authData.set(await sha(te.encode("forge.test")));
50 authData[32] = 0x05;
51 authData[36] = ++count;
52 const signed = new Uint8Array([...authData, ...(await sha(clientData))]);
53 const raw = new Uint8Array(await crypto.subtle.sign({ name: "ECDSA", hash: "SHA-256" }, key.privateKey, signed));
54 const int = (b: Uint8Array) => {
55 let i = 0;
56 while (i < b.length - 1 && b[i] === 0) i++;
57 b = b.subarray(i);
58 if (b[0]! & 0x80) b = new Uint8Array([0, ...b]);
59 return [2, b.length, ...b];
60 };
61 const parts = [...int(raw.subarray(0, 32)), ...int(raw.subarray(32))];
62 return { challenge, id, clientDataJSON: b64u(clientData), authenticatorData: b64u(authData), signature: b64u(new Uint8Array([0x30, parts.length, ...parts])) };
63 }
64
65 beforeAll(async () => {
66 dir = mkdtempSync(join(tmpdir(), "forge-door-api-"));
67 app = createApp({ dataDir: dir, port: 0, host: "forge.test" });
68 const mk = async (username: string, isAdmin: boolean) => {
69 const u = await createUser(app.db, { username, email: `${username}@f.test`, password: "a-good-passphrase", origin: "seed", isAdmin, trusted: true });
70 if (!u.ok) throw new Error(u.error);
71 return u.value;
72 };
73 ada = await mk("ada", true);
74 const bob = await mk("bob", false);
75 createGameBox(app.db, { name: "mc" });
76 boxId = boxNamed(app.db, "mc")!.id;
77 grant(app.db, boxId, ada.id, "owner");
78 grant(app.db, boxId, bob.id, "operator");
79 adaToken = createToken(app.db, ada.id, "phone", "rw").token;
80 bobToken = createToken(app.db, bob.id, "phone", "rw").token;
81 key = (await crypto.subtle.generateKey({ name: "ECDSA", namedCurve: "P-256" }, true, ["sign"])) as CryptoKeyPair;
82 const jwk = await crypto.subtle.exportKey("jwk", key.publicKey);
83 const added = addPasskey(app.db, ada.id, "phone", { id: "cred-1", alg: "ES256", key: { kty: "EC", crv: "P-256", x: jwk.x!, y: jwk.y! }, signCount: 0 });
84 if (!added.ok) throw new Error(added.error);
85 });
86 beforeEach(() => {
87 app.db.query("DELETE FROM game_door").run();
88 });
89 afterAll(async () => {
90 app.close();
91 await rm(dir, { recursive: true, force: true });
92 });
93
94 test("GET: the owner reads the door; another gets 404", async () => {
95 const res = await call("GET", adaToken);
96 expect(res.status).toBe(200);
97 expect(await res.json()).toMatchObject({ state: "closed", minutes: WINDOW_MINUTES });
98 expect((await call("GET", bobToken)).status).toBe(404);
99 });
100
101 test("POST lock: the owner locks it; a non-owner gets 404 and the door is unchanged", async () => {
102 expect((await call("POST", bobToken, { op: "lock" })).status).toBe(404);
103 expect(doorOf(app.db, boxId).state).toBe("closed");
104 const res = await call("POST", adaToken, { op: "lock" });
105 expect(res.status).toBe(200);
106 expect(((await res.json()) as { state: string }).state).toBe("locked");
107 expect(doorOf(app.db, boxId)).toMatchObject({ state: "locked", by: ada.id });
108 });
109
110 test("POST: a bad op is 422, a cross-origin cookie post is refused", async () => {
111 expect((await call("POST", adaToken, { op: "dance" })).status).toBe(422);
112 const cookie = `forge_session=${createSession(app.db, ada.id).token}`;
113 const post = (origin: string) =>
114 forgeHttp(app).handle(new Request(`${ORIGIN}/api/v1/games/mc/door`, { method: "POST", headers: { cookie, origin, "content-type": "application/json" }, body: JSON.stringify({ op: "lock" }) }));
115 expect((await post("http://evil.test")).status).toBe(403);
116 expect(doorOf(app.db, boxId).state).toBe("closed");
117 });
118
119 test("POST open without proof is 403 in words; with a wrong answer too", async () => {
120 const none = await call("POST", adaToken, { op: "open" });
121 expect(none.status).toBe(403);
122 expect(JSON.stringify(await none.json())).toContain("passkey");
123 const { challenge } = (await (await call("POST", adaToken, { op: "challenge" })).json()) as { challenge: string };
124 const forged = { ...(await sign(challenge, "cred-1")), signature: "AAAA" };
125 expect((await call("POST", adaToken, { op: "open", ...forged })).status).toBe(403);
126 expect(doorOf(app.db, boxId).state).toBe("closed");
127 });
128
129 test("POST open with a passkey's proof opens the window for WINDOW_MINUTES, and lifts a lock", async () => {
130 await call("POST", adaToken, { op: "lock" });
131 const got = (await (await call("POST", adaToken, { op: "challenge" })).json()) as { challenge: string; allow: string[]; rpId: string };
132 expect(got.rpId).toBe("forge.test");
133 expect(got.allow).toEqual(["cred-1"]);
134 const before = Date.now();
135 const res = await call("POST", adaToken, { op: "open", ...(await sign(got.challenge, "cred-1")) });
136 expect(res.status).toBe(200);
137 const door = (await res.json()) as { state: string; until: string };
138 expect(door.state).toBe("open");
139 expect(Date.parse(door.until) - before).toBeGreaterThan((WINDOW_MINUTES - 1) * 60_000);
140 expect(Date.parse(door.until) - before).toBeLessThanOrEqual(WINDOW_MINUTES * 60_000 + 5_000);
141 // A challenge answers once.
142 expect((await call("POST", adaToken, { op: "open", ...(await sign(got.challenge, "cred-1")) })).status).toBe(403);
143 });
test/security-floor-routes.test.ts +1
@@ -135,6 +135,7 @@ const UNSEEDED: Record<string, string> = {
135135 "/api/v1/conversation/files/:id": "an attachment id exists only once its owner uploads a file; the seed holds none",
136136 "/api/v1/devices/:id/print/:job": "a printer job exists only once an app sends one to a device; the seed holds none",
137137 "/api/v1/fleet/ops/:id": FLEET,
138 "/api/v1/games/:box/door": "needs a game box owned by the signed-in person; the seed has no box",
138139 "/api/v1/migrate/:job": MIGRATE,
139140 "/api/v1/migrate/:job/stream": MIGRATE,
140141 "/api/v1/orgs/:org": ORG,

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

Keyboard shortcuts

Docs