Skip to content
Open
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
3 changes: 3 additions & 0 deletions react-app/src/shared/utils/externalHref.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,13 +6,16 @@ describe('externalHref', () => {
it('returns http(s) URLs unchanged (Angular binds item.url as-is)', () => {
expect(externalHref('https://example.com/a?b=1')).toBe('https://example.com/a?b=1');
expect(externalHref('http://example.com')).toBe('http://example.com');
expect(externalHref('httpS://example.com/a')).toBe('httpS://example.com/a');
});

it.each([
['HN-relative Ask/Show URL', 'item?id=123'],
['javascript: URL', 'javascript:alert(1)'],
['data: URL', 'data:text/html,hi'],
['"http" prefix that is not a URL', 'httpfoo'],
['scheme-only https URL', 'https:example.com'],
['scheme-only http URL with one slash', 'http:/example.com'],
['empty string', ''],
['undefined', undefined],
])('returns null for %s', (_, url) => {
Expand Down
10 changes: 7 additions & 3 deletions react-app/src/shared/utils/externalHref.ts
Original file line number Diff line number Diff line change
@@ -1,11 +1,15 @@
import { isSafeHref } from './sanitizeHtml';

/**
* Angular `hasUrl` (`url.indexOf('http') === 0`), tightened: only a parseable, safe http(s) URL renders as an
* external link. Everything else (HN-relative `item?id=N` for Ask/Show/text posts) links to `/item/:id`.
* Angular `hasUrl` (`url.indexOf('http') === 0`), tightened: only a parseable, safe, absolute `http(s)://` URL renders
* as an external link. Everything else (HN-relative `item?id=N` for Ask/Show/text posts) links to `/item/:id`.
* Scheme-only forms like `https:example.com` are rejected: `new URL` accepts them, but as an href the browser resolves
* them relative to the page.
*/
const ABSOLUTE_HTTP = /^http[sS]?:\/\//;

export function externalHref(url: string | null | undefined): string | null {
if (typeof url !== 'string' || url.indexOf('http') !== 0 || !isSafeHref(url)) return null;
if (typeof url !== 'string' || !ABSOLUTE_HTTP.test(url) || !isSafeHref(url)) return null;
try {
const parsed = new URL(url);
return parsed.protocol === 'http:' || parsed.protocol === 'https:' ? url : null;
Expand Down
Loading