diff --git a/pkgs/id/web/src/world-http.test.ts b/pkgs/id/web/src/world-http.test.ts new file mode 100644 index 0000000000..41805ea9f0 --- /dev/null +++ b/pkgs/id/web/src/world-http.test.ts @@ -0,0 +1,96 @@ +import { describe, expect, it } from "vitest"; +import { parseWorldHostViewPage, parseWorldInviteResponse } from "./world-http"; + +// Oracle: the server contracts in pkgs/id/src/web/world_ws.rs — +// HostViewResponse (all fields always present; snapshot/view/surface/ +// next_after nullable) and the invite handler's { capability, +// display_name } with a non-empty string capability. The malformed cases +// are the ones issue #7833 probed live against the unguarded page. + +const validSnapshot = { + world_id: "arena", + current_sequence: 7, + active_module_hash: null, + participants: [{ id: 1, display_name: "ann" }], +}; + +const validPage = { + snapshot: validSnapshot, + view: "hello", + surface: null, + records_sequence: 42, + records: { greeting: "hi" }, + next_after: null, +}; + +describe("parseWorldHostViewPage", () => { + it("accepts a well-formed page (control)", () => { + expect(parseWorldHostViewPage(validPage)).toEqual(validPage); + }); + + it("accepts a later page with null snapshot/view/surface and a string next_after", () => { + const page = { ...validPage, snapshot: null, view: null, next_after: "greeting" }; + expect(parseWorldHostViewPage(page)).toEqual(page); + }); + + it.each([null, {}, [], "abc", 42])("rejects a non-object or empty body: %j", (payload) => { + expect(() => parseWorldHostViewPage(payload)).toThrow(/^Host view unavailable/); + }); + + it("rejects records that are not a plain object (the per-character render case)", () => { + expect(() => parseWorldHostViewPage({ ...validPage, records: "abc" })).toThrow(/^Host view unavailable/); + expect(() => parseWorldHostViewPage({ ...validPage, records: null })).toThrow(/^Host view unavailable/); + expect(() => parseWorldHostViewPage({ ...validPage, records: [] })).toThrow(/^Host view unavailable/); + }); + + it("rejects a non-number records_sequence", () => { + expect(() => parseWorldHostViewPage({ ...validPage, records_sequence: "42" })).toThrow(/^Host view unavailable/); + expect(() => parseWorldHostViewPage({ ...validPage, records_sequence: Number.NaN })).toThrow( + /^Host view unavailable/, + ); + }); + + it("rejects a wrong-typed next_after", () => { + expect(() => parseWorldHostViewPage({ ...validPage, next_after: 3 })).toThrow(/^Host view unavailable/); + }); + + it("rejects a snapshot that fails the snapshot guard", () => { + expect(() => parseWorldHostViewPage({ ...validPage, snapshot: { world_id: "arena" } })).toThrow( + /^Host view unavailable/, + ); + expect( + () => parseWorldHostViewPage({ ...validPage, snapshot: { ...validSnapshot, participants: [{ id: "1" }] } }), + ).toThrow(/^Host view unavailable/); + }); +}); + +describe("parseWorldInviteResponse", () => { + it("accepts a well-formed invite (control)", () => { + expect(parseWorldInviteResponse({ capability: "cap-abc-123", display_name: "guest" })).toEqual({ + capability: "cap-abc-123", + display_name: "guest", + }); + }); + + it.each([null, {}, [], "abc", 42])("rejects a non-object or empty body: %j", (payload) => { + expect(() => parseWorldInviteResponse(payload)).toThrow(/^Invite failed/); + }); + + it("rejects a missing, empty, or non-string capability (the persisted-'undefined' case)", () => { + expect(() => parseWorldInviteResponse({ display_name: "guest" })).toThrow(/^Invite failed/); + expect(() => parseWorldInviteResponse({ capability: "" })).toThrow(/^Invite failed/); + expect(() => parseWorldInviteResponse({ capability: 123 })).toThrow(/^Invite failed/); + expect(() => parseWorldInviteResponse({ capability: null })).toThrow(/^Invite failed/); + }); + + it("falls back to a null display_name when it is absent or wrong-typed", () => { + expect(parseWorldInviteResponse({ capability: "cap-abc-123" })).toEqual({ + capability: "cap-abc-123", + display_name: null, + }); + expect(parseWorldInviteResponse({ capability: "cap-abc-123", display_name: 7 })).toEqual({ + capability: "cap-abc-123", + display_name: null, + }); + }); +}); diff --git a/pkgs/id/web/src/world-http.ts b/pkgs/id/web/src/world-http.ts new file mode 100644 index 0000000000..853d32a410 --- /dev/null +++ b/pkgs/id/web/src/world-http.ts @@ -0,0 +1,112 @@ +/** + * Fetch-boundary validation for the world page's HTTP responses (#7833). + * + * The server contracts are `HostViewResponse` in + * `pkgs/id/src/web/world_ws.rs` (snapshot/view/surface nullable, + * records_sequence a number, records a string-keyed map, next_after a + * string or null) and the invite handler's `{ capability, display_name }` + * (capability a non-empty string, per the server test asserting exactly + * that). A wrong-shape 200 (deploy skew, an error envelope returned with + * 200, a future contract change) must fail closed through the caller's + * existing error path — the same discipline the WebSocket paths in + * world.ts already apply to every frame, and the sibling pages adopted + * for /api/upload in #7823 (`parseUploadResponse`). + */ + +import type { ScreenSurface } from "./world-surface"; + +export type WorldSnapshotShape = { + world_id: string; + current_sequence: number; + active_module_hash?: string | null; + participants: Array<{ id: number; display_name: string }>; +}; + +export type WorldHostViewPage = { + snapshot: WorldSnapshotShape | null; + view: string | null; + surface: ScreenSurface | null; + records_sequence: number; + records: Record; + next_after: string | null; +}; + +export type WorldInviteResponse = { + capability: string; + display_name: string | null; +}; + +const isRecord = (value: unknown): value is Record => + typeof value === "object" && value !== null && !Array.isArray(value); +const isFiniteNumber = (value: unknown): value is number => + typeof value === "number" && Number.isFinite(value); + +const isWorldSnapshotShape = (value: unknown): value is WorldSnapshotShape => + isRecord(value) && + typeof value.world_id === "string" && + isFiniteNumber(value.current_sequence) && + Array.isArray(value.participants) && + value.participants.every( + (participant) => + isRecord(participant) && isFiniteNumber(participant.id) && typeof participant.display_name === "string", + ); + +/** + * Validate one `/api/world/host-view` page before any state is touched. + * Throws with the page's designed "Host view unavailable" vocabulary so + * the caller's catch renders that — never a raw engine TypeError, and + * never partially-rendered bogus records. + */ +export function parseWorldHostViewPage(payload: unknown): WorldHostViewPage { + if (!isRecord(payload)) { + throw new Error("Host view unavailable: malformed host-view response (expected an object)"); + } + const { snapshot, view, surface, records_sequence, records, next_after } = payload; + if (!isRecord(records)) { + throw new Error("Host view unavailable: malformed host-view response (records must be an object)"); + } + if (!isFiniteNumber(records_sequence)) { + throw new Error("Host view unavailable: malformed host-view response (records_sequence must be a number)"); + } + if (next_after !== undefined && next_after !== null && typeof next_after !== "string") { + throw new Error("Host view unavailable: malformed host-view response (next_after must be a string or null)"); + } + if (snapshot !== undefined && snapshot !== null && !isWorldSnapshotShape(snapshot)) { + throw new Error("Host view unavailable: malformed host-view response (snapshot failed validation)"); + } + if (view !== undefined && view !== null && typeof view !== "string") { + throw new Error("Host view unavailable: malformed host-view response (view must be a string or null)"); + } + if (surface !== undefined && surface !== null && !isRecord(surface)) { + throw new Error("Host view unavailable: malformed host-view response (surface must be an object or null)"); + } + return { + snapshot: (snapshot ?? null) as WorldSnapshotShape | null, + view: (view ?? null) as string | null, + surface: (surface ?? null) as ScreenSurface | null, + records_sequence, + records, + next_after: (next_after ?? null) as string | null, + }; +} + +/** + * Validate an `/api/world/invite` response at the fetch boundary. The + * capability is a credential: a missing, non-string, or empty one must + * never reach `showCapability` (which persists it to sessionStorage). + * `display_name` is cosmetic and falls back gracefully (null) when + * absent or wrong-typed. + */ +export function parseWorldInviteResponse(payload: unknown): WorldInviteResponse { + if (!isRecord(payload)) { + throw new Error("Invite failed: malformed /api/world/invite response (expected an object)"); + } + const { capability, display_name } = payload; + if (typeof capability !== "string" || capability.length === 0) { + throw new Error("Invite failed: malformed /api/world/invite response (capability must be a non-empty string)"); + } + return { + capability, + display_name: typeof display_name === "string" ? display_name : null, + }; +} diff --git a/pkgs/id/web/src/world.ts b/pkgs/id/web/src/world.ts index 175a41ca41..9c01ea7c8d 100644 --- a/pkgs/id/web/src/world.ts +++ b/pkgs/id/web/src/world.ts @@ -1,6 +1,7 @@ /** Browser presentation for the server-authoritative world session. */ import { terminalBytesForKey } from "./world-keyboard"; +import { parseWorldHostViewPage, parseWorldInviteResponse } from "./world-http"; import { parseWorldSeed } from "./world-seed"; import { applyScreenPatch, renderWorldSurface, type ScreenPatch, type ScreenSurface } from "./world-surface"; @@ -430,14 +431,11 @@ function initWorld(): void { throw new Error(response.status === 401 ? "Host authorization denied" : "Host view unavailable"); } if (generation !== hostViewGeneration || !hostMode) return; - const result = (await response.json()) as { - snapshot?: NonNullable; - view?: string | null; - surface?: ScreenSurface | null; - records_sequence: number; - records: Record; - next_after: string | null; - }; + // Validate the page at the fetch boundary before any state is + // touched (#7833): a wrong-shape 200 must fail closed with the + // designed "Host view unavailable" error, never a raw TypeError + // or bogus per-character records. + const result = parseWorldHostViewPage(await response.json()); if (recordsSequence !== null && recordsSequence !== result.records_sequence) { throw new Error("World records changed while paging; refresh the host view"); } @@ -563,11 +561,14 @@ function initWorld(): void { if (!response.ok) { throw new Error(response.status === 401 ? "Admin token refused" : `Invite failed (${response.status})`); } - const result = (await response.json()) as { capability: string; display_name: string }; + // Validate at the fetch boundary (#7833): a malformed 200 must + // never reach showCapability, which persists the capability to + // sessionStorage. + const result = parseWorldInviteResponse(await response.json()); showCapability(result.capability); admin.value = ""; setStatus("Invite created. Copy it or join this browser.", "good"); - appendLine(log, `Invite created for ${result.display_name}`); + appendLine(log, `Invite created for ${result.display_name ?? (name.value || "guest")}`); } catch (error) { setStatus(error instanceof Error ? error.message : "Invite failed", "error"); } finally {