From bd11624a371ccc820cd3c8b60a4fa9cf21715555 Mon Sep 17 00:00:00 2001 From: repo-worker-code-k Date: Sun, 8 Nov 2026 17:37:56 -0600 Subject: [PATCH 1/2] fix(id/web): validate host-view and invite response shapes (#7831) --- pkgs/id/web/src/world-shape.test.ts | 183 ++++++++++++++++++++++++++++ pkgs/id/web/src/world.ts | 44 +++++-- 2 files changed, 218 insertions(+), 9 deletions(-) create mode 100644 pkgs/id/web/src/world-shape.test.ts diff --git a/pkgs/id/web/src/world-shape.test.ts b/pkgs/id/web/src/world-shape.test.ts new file mode 100644 index 0000000000..eb7004234e --- /dev/null +++ b/pkgs/id/web/src/world-shape.test.ts @@ -0,0 +1,183 @@ +import { readFileSync } from "node:fs"; +import { dirname, resolve } from "node:path"; +import { fileURLToPath } from "node:url"; +import { afterAll, beforeAll, describe, expect, it, vi } from "vitest"; + +/** + * #7831 regression tests: the world page's HTTP doors validate shape. + * + * /api/world/host-view and /api/world/invite used to be shape-trusted — + * a wrong-shape 200 surfaced a raw TypeError as the host-view status, + * and the invite path reported fake success while persisting a bogus + * capability ('undefined' / coerced) to sessionStorage. Both doors now + * fail closed through the existing error paths. The malformed cases + * below fail pre-fix. + */ + +const here = dirname(fileURLToPath(import.meta.url)); + +function worldPageMarkup(): string { + const source = readFileSync(resolve(here, "../../src/web/templates.rs"), "utf8"); + const start = source.indexOf("pub fn render_world_page"); + const open = source.indexOf('r#"', start); + const close = source.indexOf('"#;', open); + if (start < 0 || open < 0 || close < 0) throw new Error("world page template not found in templates.rs"); + return source.slice(open + 3, close); +} + +class FakeSocket extends EventTarget { + static readonly CONNECTING = 0; + static readonly OPEN = 1; + static readonly CLOSING = 2; + static readonly CLOSED = 3; + static readonly all: FakeSocket[] = []; + + readyState = FakeSocket.CONNECTING; + bufferedAmount = 0; + onclose: ((event: Event) => void) | null = null; + readonly sentFrames: Array> = []; + + constructor(readonly url: string) { + super(); + FakeSocket.all.push(this); + } + + send(data: string): void { + this.sentFrames.push(JSON.parse(data) as Record); + } + + close(): void { + if (this.readyState === FakeSocket.CLOSED) return; + this.readyState = FakeSocket.CLOSED; + setTimeout(() => this.dispatchEvent(new Event("close")), 0); + } + + open(): void { + this.readyState = FakeSocket.OPEN; + this.dispatchEvent(new Event("open")); + } + + deliver(frame: Record): void { + this.dispatchEvent(new MessageEvent("message", { data: JSON.stringify(frame) })); + } + + sent(type: string): Array> { + return this.sentFrames.filter((frame) => frame.type === type); + } +} + +class FakeResizeObserver { + constructor(readonly callback: ResizeObserverCallback) {} + observe(): void {} + unobserve(): void {} + disconnect(): void {} +} + +const flushAsync = () => new Promise((resolveFlush) => setTimeout(resolveFlush, 20)); + +describe("world page HTTP response shape validation (#7831)", () => { + const realWebSocket = globalThis.WebSocket; + const realResizeObserver = globalThis.ResizeObserver; + const realFetch = globalThis.fetch; + let root: HTMLElement; + const q = (selector: string): T => { + const found = root.querySelector(selector); + if (!found) throw new Error(`missing ${selector}`); + return found; + }; + const status = () => q("[data-world-status]").textContent; + const storageKey = () => `id-world-capability:${window.location.host}`; + let payload: unknown = null; + + beforeAll(async () => { + vi.stubGlobal("WebSocket", FakeSocket); + vi.stubGlobal("ResizeObserver", FakeResizeObserver); + vi.stubGlobal( + "fetch", + vi.fn( + async () => + new Response(JSON.stringify(payload), { status: 200, headers: { "content-type": "application/json" } }), + ), + ); + sessionStorage.clear(); + document.body.innerHTML = worldPageMarkup(); + await import("./world"); + root = document.querySelector("[data-world-app]") as HTMLElement; + expect(root.dataset.initialized).toBe("true"); + }); + + afterAll(() => { + vi.stubGlobal("WebSocket", realWebSocket); + vi.stubGlobal("ResizeObserver", realResizeObserver); + vi.stubGlobal("fetch", realFetch); + document.body.innerHTML = ""; + }); + + it.each([ + ["null", null], + ["empty object", {}], + ["string", "abc"], + ["array", []], + ["records null", { records_sequence: 0, records: null, next_after: null }], + ["records missing", { records_sequence: 0, next_after: null }], + ["records_sequence missing", { records: {}, next_after: null }], + ["next_after wrong type", { records_sequence: 0, records: {}, next_after: 7 }], + ])("host-view malformed payload (%s) fails closed with no partial render", async (_label, p) => { + payload = p; + const recordsBefore = q("[data-world-records]").textContent; + q("[data-world-admin]").value = "admin-secret"; + q("[data-world-host-view]").click(); + await flushAsync(); + expect(status()).toBe("Host view unavailable"); + expect(q("[data-world-records]").textContent).toBe(recordsBefore); + }); + + it("host-view well-formed payload still renders (control)", async () => { + payload = { + snapshot: { world_id: "lobby", current_sequence: 0, active_module_hash: null, participants: [] }, + view: null, + surface: null, + records_sequence: 0, + records: { k: 1 }, + next_after: null, + }; + q("[data-world-admin]").value = "admin-secret"; + q("[data-world-host-view]").click(); + await flushAsync(); + expect(status()).toBe("Read-only host view"); + expect(q("[data-world-records]").textContent).toContain('"k": 1'); + }); + + it.each([ + ["null", null], + ["empty object", {}], + ["string", "abc"], + ["array", []], + ["numeric capability", { capability: 123, display_name: "ada" }], + ["empty capability", { capability: "", display_name: "ada" }], + ["missing display_name", { capability: "cap-x" }], + ])("invite malformed payload (%s) fails with nothing stored or shown", async (_label, p) => { + payload = p; + sessionStorage.clear(); + q("[data-world-capability]").value = ""; + q("[data-world-admin]").value = "admin-secret"; + q("[data-world-invite]").click(); + await flushAsync(); + expect(status()).toBe("Invite failed"); + expect(q("[data-world-capability]").value).toBe(""); + expect(sessionStorage.getItem(storageKey())).toBeNull(); + expect(q("[data-world-invite-output]").hidden).toBe(true); + }); + + it("invite well-formed payload still shows the capability (control)", async () => { + payload = { capability: "cap-123", display_name: "ada" }; + sessionStorage.clear(); + q("[data-world-admin]").value = "admin-secret"; + q("[data-world-invite]").click(); + await flushAsync(); + expect(status()).toContain("Invite created"); + expect(q("[data-world-capability]").value).toBe("cap-123"); + expect(sessionStorage.getItem(storageKey())).toBe("cap-123"); + expect(q("[data-world-invite-output]").hidden).toBe(false); + }); +}); diff --git a/pkgs/id/web/src/world.ts b/pkgs/id/web/src/world.ts index 175a41ca41..9bb88752f0 100644 --- a/pkgs/id/web/src/world.ts +++ b/pkgs/id/web/src/world.ts @@ -173,6 +173,33 @@ function initWorld(): void { } return false; }; + // The HTTP doors validate like the WS doors do (#7831): a 200 with the + // wrong shape fails closed through the existing error paths instead of + // throwing a raw TypeError or trusting fields the server never promised. + // Field set mirrors HostViewResponse in pkgs/id/src/web/world_ws.rs. + const isHostViewResponse = ( + value: unknown, + ): value is { + snapshot: NonNullable | null; + view: string | null; + surface: ScreenSurface | null; + records_sequence: number; + records: Record; + next_after: string | null; + } => + isRecord(value) && + isFiniteNumber(value.records_sequence) && + isRecord(value.records) && + (value.next_after === null || typeof value.next_after === "string") && + (value.snapshot === null || value.snapshot === undefined || isWorldSnapshot(value.snapshot)) && + (value.view === null || value.view === undefined || typeof value.view === "string") && + (value.surface === null || value.surface === undefined || isRecord(value.surface)); + const isInviteResponse = (value: unknown): value is { capability: string; display_name: string } => + isRecord(value) && + typeof value.capability === "string" && + value.capability.length > 0 && + typeof value.display_name === "string"; + const rejectFrame = () => { setStatus("Received an invalid world frame", "error"); appendLine(log, "error: invalid world frame"); @@ -430,14 +457,10 @@ 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; - }; + const result: unknown = await response.json(); + if (!isHostViewResponse(result)) { + throw new Error("Host view unavailable"); + } if (recordsSequence !== null && recordsSequence !== result.records_sequence) { throw new Error("World records changed while paging; refresh the host view"); } @@ -563,7 +586,10 @@ 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 }; + const result: unknown = await response.json(); + if (!isInviteResponse(result)) { + throw new Error("Invite failed"); + } showCapability(result.capability); admin.value = ""; setStatus("Invite created. Copy it or join this browser.", "good"); From ca93cd31dfc64611d0a36620830f2cc267e563de Mon Sep 17 00:00:00 2001 From: repo-worker-code-k Date: Sun, 8 Nov 2026 20:23:48 -0600 Subject: [PATCH 2/2] fix(id/web): reject empty invite display_name and cover merged shape cases (#7831) Fold the surviving cases from the superseded PR #7840 into #7858: a numeric records_sequence and a non-record surface are rejected, and an empty or non-string display_name now fails the invite door along with a missing one. Adds the three corresponding regression cases. --- pkgs/id/web/src/world-shape.test.ts | 4 ++++ pkgs/id/web/src/world.ts | 3 ++- 2 files changed, 6 insertions(+), 1 deletion(-) diff --git a/pkgs/id/web/src/world-shape.test.ts b/pkgs/id/web/src/world-shape.test.ts index eb7004234e..20caea1274 100644 --- a/pkgs/id/web/src/world-shape.test.ts +++ b/pkgs/id/web/src/world-shape.test.ts @@ -121,7 +121,9 @@ describe("world page HTTP response shape validation (#7831)", () => { ["records null", { records_sequence: 0, records: null, next_after: null }], ["records missing", { records_sequence: 0, next_after: null }], ["records_sequence missing", { records: {}, next_after: null }], + ["records_sequence wrong type", { records_sequence: "7", records: {}, next_after: null }], ["next_after wrong type", { records_sequence: 0, records: {}, next_after: 7 }], + ["surface wrong type", { records_sequence: 0, records: {}, next_after: null, surface: "x" }], ])("host-view malformed payload (%s) fails closed with no partial render", async (_label, p) => { payload = p; const recordsBefore = q("[data-world-records]").textContent; @@ -156,6 +158,8 @@ describe("world page HTTP response shape validation (#7831)", () => { ["numeric capability", { capability: 123, display_name: "ada" }], ["empty capability", { capability: "", display_name: "ada" }], ["missing display_name", { capability: "cap-x" }], + ["empty display_name", { capability: "cap-x", display_name: "" }], + ["display_name wrong type", { capability: "cap-x", display_name: 7 }], ])("invite malformed payload (%s) fails with nothing stored or shown", async (_label, p) => { payload = p; sessionStorage.clear(); diff --git a/pkgs/id/web/src/world.ts b/pkgs/id/web/src/world.ts index 9bb88752f0..3b325c4ced 100644 --- a/pkgs/id/web/src/world.ts +++ b/pkgs/id/web/src/world.ts @@ -198,7 +198,8 @@ function initWorld(): void { isRecord(value) && typeof value.capability === "string" && value.capability.length > 0 && - typeof value.display_name === "string"; + typeof value.display_name === "string" && + value.display_name.length > 0; const rejectFrame = () => { setStatus("Received an invalid world frame", "error");