diff --git a/pkgs/id/web/src/home.test.ts b/pkgs/id/web/src/home.test.ts index 241a7755be..8e1e9c7cdf 100644 --- a/pkgs/id/web/src/home.test.ts +++ b/pkgs/id/web/src/home.test.ts @@ -1,5 +1,57 @@ -import { describe, expect, it } from "vitest"; -import { renderTagList } from "./home"; +import { afterEach, describe, expect, it, vi } from "vitest"; +import { initHome, parseHomeFeed, renderTagList } from "./home"; + +const validFeed = { + scope: "public local", + popularity_metric: "tag count", + recent: [{ name: "notes.md", hash: "abc123", updated_at: 1_800_000_000, tag_count: 1, tags: ["topic:rust"] }], + popular: [], + recent_tags: [{ label: "topic:rust", subject: "notes.md", timestamp: 1_800_000_000_000_000, occurrences: 1 }], + popular_tags: [{ label: "topic:rust", timestamp: 1_800_000_000_000_000, occurrences: 4 }], +}; + +function malformedFeeds(): unknown[] { + const arrayFields = ["recent", "popular", "recent_tags", "popular_tags"] as const; + const malformed: unknown[] = [null, [], "abc", {}]; + + for (const field of arrayFields) { + const { [field]: _omitted, ...withoutArray } = validFeed; + malformed.push(withoutArray); + for (const invalid of [null, {}, "items"]) { + malformed.push({ ...validFeed, [field]: invalid }); + } + + const isDocumentList = field === "recent" || field === "popular"; + const validItem = isDocumentList ? validFeed.recent[0] : validFeed.popular_tags[0]; + const wrongTypedItem = isDocumentList + ? { ...validFeed.recent[0], name: null } + : { ...validFeed.popular_tags[0], label: null }; + malformed.push( + { ...validFeed, [field]: [null] }, + { ...validFeed, [field]: [wrongTypedItem] }, + { ...validFeed, [field]: [validItem, null] }, + ); + } + + malformed.push( + { ...validFeed, recent: [{ ...validFeed.recent[0], updated_at: "now" }] }, + { ...validFeed, recent: [{ ...validFeed.recent[0], tag_count: "1" }] }, + { ...validFeed, recent: [{ ...validFeed.recent[0], tags: [1] }] }, + { ...validFeed, recent_tags: [{ ...validFeed.recent_tags[0], subject: 1 }] }, + { ...validFeed, recent_tags: [{ ...validFeed.recent_tags[0], timestamp: "now" }] }, + { ...validFeed, popular_tags: [{ ...validFeed.popular_tags[0], occurrences: null }] }, + { ...validFeed, scope: null }, + { ...validFeed, popularity_metric: 1 }, + ); + + return malformed; +} + +afterEach(() => { + document.body.innerHTML = ""; + initHome(); + vi.unstubAllGlobals(); +}); describe("home tag feeds", () => { it("renders untrusted tag labels as text rather than HTML", () => { @@ -20,4 +72,63 @@ describe("home tag feeds", () => { expect(list.textContent).toContain("topic:rust"); expect(list.textContent).toContain("4 documents"); }); + + it("does not replace a tag list when an item has the wrong shape", () => { + const list = document.createElement("ol"); + renderTagList(list, [{ label: "keep", timestamp: 1_800_000_000_000_000, occurrences: 2 }]); + const previousMarkup = list.innerHTML; + const malformedInputs: unknown[] = [null, {}, "abc", [null], [{ label: "new" }, null]]; + + for (const input of malformedInputs) { + renderTagList(list, input as Parameters[1]); + expect(list.innerHTML).toBe(previousMarkup); + } + }); +}); + +describe("home feed validation (#7811)", () => { + it("accepts a well-formed feed with an omitted optional subject", () => { + expect(parseHomeFeed(validFeed)).toEqual(validFeed); + }); + + it("rejects malformed feed bodies, arrays, and item fields", () => { + for (const feed of malformedFeeds()) { + expect(parseHomeFeed(feed)).toBeNull(); + } + }); + + it("keeps the last rendered lists and shows a clean message for every malformed response", async () => { + const visibility = Object.getOwnPropertyDescriptor(document, "visibilityState"); + Object.defineProperty(document, "visibilityState", { configurable: true, value: "visible" }); + + try { + for (const malformedFeed of malformedFeeds()) { + document.body.innerHTML = ` +
+
  1. last recent
+
  1. last popular
+
  1. last recent tag
+
  1. last popular tag
+

Previously updated.

+
`; + const lists = Array.from(document.querySelectorAll("[data-home-app] ol")); + const previousMarkup = lists.map((list) => list.innerHTML); + vi.stubGlobal( + "fetch", + vi.fn().mockResolvedValue({ ok: true, json: async () => malformedFeed }), + ); + + initHome(); + await new Promise((resolve) => setTimeout(resolve, 0)); + + expect(lists.map((list) => list.innerHTML)).toEqual(previousMarkup); + expect(document.querySelector("[data-home-updated]")?.textContent).toBe( + "Feed is temporarily unavailable.", + ); + } + } finally { + if (visibility) Object.defineProperty(document, "visibilityState", visibility); + else Reflect.deleteProperty(document, "visibilityState"); + } + }); }); diff --git a/pkgs/id/web/src/home.ts b/pkgs/id/web/src/home.ts index 966016a851..e0413ac89a 100644 --- a/pkgs/id/web/src/home.ts +++ b/pkgs/id/web/src/home.ts @@ -22,9 +22,72 @@ type HomeFeed = { popular_tags: FeedTag[]; }; +const FEED_UNAVAILABLE = "Feed is temporarily unavailable."; + let homeRefreshTimer: number | undefined; +function isRecord(value: unknown): value is Record { + return typeof value === "object" && value !== null && !Array.isArray(value); +} + +function isFiniteNumber(value: unknown): value is number { + return typeof value === "number" && Number.isFinite(value); +} + +function isStringArray(value: unknown): value is string[] { + return Array.isArray(value) && value.every((item) => typeof item === "string"); +} + +function isFeedDocument(value: unknown): value is FeedDocument { + return ( + isRecord(value) && + typeof value.name === "string" && + typeof value.hash === "string" && + isFiniteNumber(value.updated_at) && + isFiniteNumber(value.tag_count) && + isStringArray(value.tags) + ); +} + +function isFeedTag(value: unknown): value is FeedTag { + return ( + isRecord(value) && + typeof value.label === "string" && + (value.subject === undefined || typeof value.subject === "string") && + isFiniteNumber(value.timestamp) && + isFiniteNumber(value.occurrences) + ); +} + +function isFeedDocumentArray(value: unknown): value is FeedDocument[] { + return Array.isArray(value) && value.every(isFeedDocument); +} + +function isFeedTagArray(value: unknown): value is FeedTag[] { + return Array.isArray(value) && value.every(isFeedTag); +} + +/** + * Validate an untrusted `/api/home/feed` body. Returns `null` for any payload that + * does not match the server contract, so callers never render a partial feed. + */ +export function parseHomeFeed(value: unknown): HomeFeed | null { + if (!isRecord(value)) return null; + if (typeof value.scope !== "string" || typeof value.popularity_metric !== "string") return null; + if (!isFeedDocumentArray(value.recent) || !isFeedDocumentArray(value.popular)) return null; + if (!isFeedTagArray(value.recent_tags) || !isFeedTagArray(value.popular_tags)) return null; + return { + scope: value.scope, + popularity_metric: value.popularity_metric, + recent: value.recent, + popular: value.popular, + recent_tags: value.recent_tags, + popular_tags: value.popular_tags, + }; +} + function renderList(list: HTMLOListElement, documents: FeedDocument[]): void { + if (!isFeedDocumentArray(documents)) return; list.replaceChildren(); if (documents.length === 0) { const empty = document.createElement("li"); @@ -52,6 +115,7 @@ function renderList(list: HTMLOListElement, documents: FeedDocument[]): void { /** Populate a tag list using text nodes; tag values are untrusted user metadata. */ export function renderTagList(list: HTMLOListElement, tags: FeedTag[]): void { + if (!isFeedTagArray(tags)) return; list.replaceChildren(); if (tags.length === 0) { const empty = document.createElement("li"); @@ -102,8 +166,12 @@ export function initHome(): void { try { const response = await fetch("/api/home/feed", { headers: { accept: "application/json" } }); if (!response.ok) throw new Error(`feed request failed (${response.status})`); - const feed = (await response.json()) as HomeFeed; + const feed = parseHomeFeed(await response.json()); if (!root.isConnected) return; + if (feed === null) { + updated.textContent = FEED_UNAVAILABLE; + return; + } renderList(recent, feed.recent); renderList(popular, feed.popular); renderTagList(recentTags, feed.recent_tags); @@ -111,7 +179,10 @@ export function initHome(): void { updated.textContent = `Updated live from ${feed.scope}. ${feed.popularity_metric}.`; } catch (error) { if (root.isConnected) { - updated.textContent = error instanceof Error ? error.message : "Feed is temporarily unavailable."; + updated.textContent = + error instanceof Error && error.message.startsWith("feed request failed (") + ? error.message + : FEED_UNAVAILABLE; } } finally { pending = false;