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
20 changes: 20 additions & 0 deletions src/components/ItemArticle.test.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -51,6 +51,26 @@ describe('ItemArticle', () => {
// Text posts render as plain text, not as a clickable link
expect(screen.queryByRole('link', { name: 'A great story' })).not.toBeInTheDocument();
});

it.each(['javascript:alert(1)', 'data:text/html,<script>alert(1)</script>', 'vbscript:msgbox(1)'])(
'does not render an anchor for non-http(s) URL scheme %s',
(url) => {
render(<ItemArticle item={story({ url })} />);

// Hostile schemes must never reach the anchor href; the title degrades
// to plain text instead.
expect(screen.queryByRole('link', { name: 'A great story' })).not.toBeInTheDocument();
},
);

it('renders the external link for ordinary http(s) URLs', () => {
render(<ItemArticle item={story({ url: 'https://example.com/article' })} />);

expect(screen.getByRole('link', { name: 'A great story' })).toHaveAttribute(
'href',
'https://example.com/article',
);
});
});

describe('author byline link', () => {
Expand Down
10 changes: 8 additions & 2 deletions src/components/ItemArticle.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,12 @@ export function ItemArticle({ item, className = 'mb-4 pb-4 border-b border-borde
const viewed = useIsViewed(item.id);
const hostname = getHostname(item.url);

// Gate the outbound href to http(s) so javascript:/data: URLs can't reach the
// DOM; anything else degrades to plain text. Keep it ONE `startsWith` — a `||`
// reopens the CodeQL js/xss alert (a LogOrExpr drops the guard's true outcome).
const rawUrl = item.url ?? '';
const safeUrl = rawUrl.startsWith('http') ? rawUrl : undefined;

const itemText = item.text;
const sanitizedText = useMemo(
() => itemText ? sanitizeHtml(itemText) : '',
Expand All @@ -31,9 +37,9 @@ export function ItemArticle({ item, className = 'mb-4 pb-4 border-b border-borde
// point reads cleanly instead of cascading inside itself.
<article className={`${className} story-stage-leader`}>
<h1 className={`text-xl font-semibold mb-2 leading-snug break-words ${viewed ? 'text-viewed' : 'text-foreground'}`}>
{item.url ? (
{safeUrl ? (
<a
href={item.url}
href={safeUrl}
Comment thread
github-advanced-security[bot] marked this conversation as resolved.
Fixed
rel="noreferrer"
className="hover:text-accent transition-colors"
onClick={() => markViewedWithTime(item.id, 'title')}
Expand Down
14 changes: 14 additions & 0 deletions src/components/StoryCard.test.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -141,6 +141,20 @@ describe('StoryCard', () => {
expect(titleLink).toHaveAttribute('href', '/item/67890');
});

it.each(['javascript:alert(1)', 'data:text/html,<script>alert(1)</script>', 'vbscript:msgbox(1)'])(
'never points the title link at a non-http(s) URL scheme %s',
(url) => {
render(<StoryCard story={createStoryItem({ ...mockStory, url })} />);

// Hostile schemes must not become the outbound href; the title degrades
// to the in-app discussion link instead.
const titleLink = screen.getByRole('link', {
name: 'Rust Is the Future of JavaScript Infrastructure',
});
expect(titleLink).toHaveAttribute('href', '/item/12345');
},
);

it('renders comments link', () => {
render(<StoryCard story={mockStory} />);

Expand Down
8 changes: 6 additions & 2 deletions src/components/StoryCard.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -31,6 +31,10 @@ interface StoryCardProps {

export function StoryCard({ story, index = 0, listType = 'top', fromDomain, fromUser, onBeforeNavigate, stageIdx, appendIdx }: StoryCardProps) {
const hostname = getHostname(story.url);
// http(s)-only outbound href (keeps javascript:/data: out); else use the in-app
// link below. Keep it ONE `startsWith` — a `||` reopens the CodeQL js/xss alert (see ItemArticle).
const rawUrl = story.url ?? '';
const safeUrl = rawUrl.startsWith('http') ? rawUrl : undefined;
const { startPrefetch, stopPrefetch } = usePrefetchItem();
const isPrefetchingRef = useRef(false);
const wasInExitZoneRef = useRef(false);
Expand Down Expand Up @@ -154,9 +158,9 @@ export function StoryCard({ story, index = 0, listType = 'top', fromDomain, from
<article ref={setRefs} className={wrapperClass} style={wrapperStyle} data-testid="story-card" data-story-id={story.id} data-viewed={viewed}>
<div className="space-y-1.5">
<h2 className="text-lg md:text-xl leading-[1.35] md:leading-[1.3] font-semibold break-words">
{story.url ? (
{safeUrl ? (
<a
href={story.url}
href={safeUrl}
rel="noreferrer"
className={`hover:text-accent transition-colors ${
viewed
Expand Down
26 changes: 16 additions & 10 deletions src/utils/sanitize.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import DOMPurify, { type Config } from 'dompurify';
import createDOMPurify, { type Config } from 'dompurify';

type DOMPurifyFactory = (w: Window) => typeof DOMPurify;
type DOMPurifyFactory = (w: Window) => typeof createDOMPurify;

// Single source for the browser-environment guard used by the private
// DOMPurify instance, runtime self-host detection, and base URL resolution.
Expand All @@ -10,12 +10,12 @@ const browserLocation: Location | null =
// Private DOMPurify instance so the link-rewriting hook below is scoped to
// this module; importing `dompurify` elsewhere gets the unmodified default
// singleton. Module load requires a DOM (browser or jsdom): in pure Node,
// the imported `DOMPurify` is a bare factory with no `.addHook`, so the
// `: DOMPurify` fallback would throw at hook registration. HackerTok runs
// only in browsers and jsdom, where `browserLocation` is never null.
const purify = browserLocation
? (DOMPurify as unknown as DOMPurifyFactory)(window)
: DOMPurify;
// the imported `createDOMPurify` is a bare factory with no `.addHook`, so the
// `: createDOMPurify` fallback would throw at hook registration. HackerTok
// runs only in browsers and jsdom, where `browserLocation` is never null.
const DOMPurify = browserLocation
? (createDOMPurify as unknown as DOMPurifyFactory)(window)
: createDOMPurify;

const PURIFY_CONFIG: Config = {
ALLOWED_TAGS: [
Expand Down Expand Up @@ -238,7 +238,7 @@ function isAutoLinkifiedText(text: string, parsed: URL): boolean {
return text.startsWith(parsed.origin);
}

purify.addHook('afterSanitizeAttributes', (node) => {
DOMPurify.addHook('afterSanitizeAttributes', (node) => {
if (node.tagName === 'PRE') {
// Make scrollable pre blocks keyboard-accessible (WCAG 2.1.1)
node.setAttribute('tabindex', '0');
Expand Down Expand Up @@ -363,5 +363,11 @@ export function sanitizeHtml(html: string | null | undefined): string {
if (!html || typeof html !== 'string') {
return '';
}
return purify.sanitize(autoLinkUrls(html), PURIFY_CONFIG);
// Defense in depth: sanitize the raw input *before* it is ever parsed into a
// DOM by `autoLinkUrls`, so untrusted markup can never reach an `innerHTML`
// write unsanitized (and CodeQL sees the DOMPurify barrier before the sink).
// The second pass re-runs the afterSanitizeAttributes hook on the anchors
// that auto-linking just created.
const sanitized = DOMPurify.sanitize(html, PURIFY_CONFIG);
return DOMPurify.sanitize(autoLinkUrls(sanitized), PURIFY_CONFIG);
}