diff --git a/pkgs/id/web/src/image-browser.test.ts b/pkgs/id/web/src/image-browser.test.ts index 6b5439eb6e..c7e1d227cc 100644 --- a/pkgs/id/web/src/image-browser.test.ts +++ b/pkgs/id/web/src/image-browser.test.ts @@ -27,6 +27,30 @@ function stubFetchImages(): void { ); } +/** Stub /api/images to return an arbitrary (possibly malformed) payload. */ +function stubFetchPayload(payload: unknown): void { + vi.stubGlobal( + "fetch", + vi.fn(async () => ({ + ok: true, + status: 200, + json: async () => payload, + })), + ); +} + +function gridText(): string { + return document.querySelector(".pm-image-browser-grid")?.textContent ?? ""; +} + +/** Open the browser and wait for the load-failure message in the grid. */ +async function openAndFail(view: EditorView): Promise { + openImageBrowser(view, richSchema); + await vi.waitFor(() => { + expect(gridText()).toContain("Failed to load images"); + }); +} + /** Create an EditorView with a one-paragraph doc in a container div. */ function createView(): { view: EditorView; container: HTMLElement } { const container = document.createElement("div"); @@ -309,3 +333,40 @@ describe("openImageBrowser", () => { expect(document.querySelector(".pm-image-browser-overlay")).toBeNull(); }); }); + +// ── Malformed /api/images payloads (#7812) ───────────────────────── +// +// The /api/images contract (routes.rs images_list_handler) is a bare +// array of { hash, name, url, size } entries. A wrong-shape 200 must +// fail closed: no cards, Insert stays disabled, and a clean failure +// message — never a raw TypeError, and never bogus cards built from +// unvalidated elements. Validation is all-or-nothing: one bad element +// rejects the whole payload instead of half-rendering the grid. + +describe("malformed /api/images payloads", () => { + const VALID = { hash: "abc123", name: "cat.png", url: "/api/images/abc123", size: 42 }; + + const cases: Array<[string, unknown]> = [ + ["null body", null], + ["non-array object body", { images: [VALID] }], + ["string body", "abc"], + ["null element", [null]], + ["wrong-typed field", [{ ...VALID, hash: 123 }]], + ["missing field", [{ hash: "abc123", name: "cat.png", url: "/api/images/abc123" }]], + ["one bad element among valid ones", [VALID, null]], + ]; + + for (const [name, payload] of cases) { + it(`fails closed on ${name}`, async () => { + stubFetchPayload(payload); + const { view } = trackedView(); + await openAndFail(view); + + expect(document.querySelectorAll(".pm-image-browser-card")).toHaveLength(0); + expect(gridText()).not.toContain("TypeError"); + expect(gridText()).not.toContain("undefined"); + const insertBtn = document.querySelector(".pm-image-browser-insert"); + expect(insertBtn?.disabled).toBe(true); + }); + } +}); diff --git a/pkgs/id/web/src/image-browser.ts b/pkgs/id/web/src/image-browser.ts index bee4e1081b..014ead2766 100644 --- a/pkgs/id/web/src/image-browser.ts +++ b/pkgs/id/web/src/image-browser.ts @@ -209,7 +209,9 @@ export function openImageBrowser(view: EditorView, schema: Schema): void { } }) .catch((err) => { - grid.textContent = `Failed to load images: ${err}`; + // Show the error's message only: a raw `err` interpolation leaks + // engine text ("TypeError: ...") into the dialog (#7812). + grid.textContent = `Failed to load images: ${err instanceof Error ? err.message : String(err)}`; }); function insertImage(img: ImageEntry): void { @@ -237,10 +239,39 @@ export function openImageBrowser(view: EditorView, schema: Schema): void { // API // ============================================================================ +/** + * Validate the /api/images payload against its contract before the + * caller touches the grid (#7812). The server contract + * (routes.rs `images_list_handler`) is a bare array of entries with + * string `hash`/`name`/`url` and numeric `size`. Validation is + * all-or-nothing — one malformed element rejects the whole payload — + * so a wrong-shape 200 fails closed with a clean error instead of + * rendering a raw TypeError or bogus cards from unvalidated fields. + * Oracle: the ImageEntry struct in pkgs/id/src/web/routes.rs. + */ +function parseImageEntries(data: unknown): ImageEntry[] { + if (!Array.isArray(data)) { + throw new Error("unexpected response from /api/images"); + } + for (const entry of data as Array | null>) { + if ( + entry === null || + typeof entry !== "object" || + typeof entry.hash !== "string" || + typeof entry.name !== "string" || + typeof entry.url !== "string" || + typeof entry.size !== "number" + ) { + throw new Error("unexpected response from /api/images"); + } + } + return data as ImageEntry[]; +} + async function fetchImages(): Promise { const response = await fetch("/api/images"); if (!response.ok) { throw new Error(`Failed to fetch images: ${response.status}`); } - return (await response.json()) as ImageEntry[]; + return parseImageEntries(await response.json()); }