Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
115 changes: 113 additions & 2 deletions pkgs/id/web/src/home.test.ts
Original file line number Diff line number Diff line change
@@ -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", () => {
Expand All @@ -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<typeof renderTagList>[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 = `
<section data-home-app>
<ol data-home-recent><li>last recent</li></ol>
<ol data-home-popular><li>last popular</li></ol>
<ol data-home-recent-tags><li>last recent tag</li></ol>
<ol data-home-popular-tags><li>last popular tag</li></ol>
<p data-home-updated>Previously updated.</p>
</section>`;
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");
}
});
});
75 changes: 73 additions & 2 deletions pkgs/id/web/src/home.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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<string, unknown> {
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");
Expand Down Expand Up @@ -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");
Expand Down Expand Up @@ -102,16 +166,23 @@ 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);
renderTagList(popularTags, feed.popular_tags);
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;
Expand Down