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
15 changes: 14 additions & 1 deletion src/shared/domain.ts
Original file line number Diff line number Diff line change
Expand Up @@ -35,8 +35,19 @@ const MULTI_PART_SUFFIXES = new Set([

const IPV4_RE = /^(?:\d{1,3}\.){3}\d{1,3}$/;

/** An IPv6 literal in the bracketed form URL.hostname uses, e.g. "[2001:db8::1]". */
function isIpv6Literal(value: string): boolean {
if (!/^\[[0-9a-f:.]+\]$/i.test(value)) return false;
try {
return new URL(`http://${value}/`).hostname.length > 2;
} catch {
return false;
}
}

export function isValidHostname(value: string): boolean {
if (IPV4_RE.test(value)) return value.split('.').every((n) => Number(n) <= 255);
if (value.startsWith('[')) return isIpv6Literal(value);
return HOSTNAME_RE.test(value);
}

Expand Down Expand Up @@ -89,7 +100,9 @@ export function hostMatchesDomain(host: string, domain: string): boolean {

export function originPatternsFor(hostname: string): string[] {
const host = normalizeHostname(hostname);
if (/^\d{1,3}(?:\.\d{1,3}){3}$/.test(host)) return [`*://${host}/*`];
// An IP address has no subdomains, and "*.[2001:db8::1]" is not a valid
// match pattern, so addresses get the exact-host pattern only.
if (IPV4_RE.test(host) || host.startsWith('[')) return [`*://${host}/*`];
return [`*://${host}/*`, `*://*.${host}/*`];
}

Expand Down
17 changes: 17 additions & 0 deletions tests/unit/domain.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,16 @@ describe('hostnames', () => {
expect(isValidHostname('-bad.com')).toBe(false);
});

it('validates IPv6 literals as URL.hostname reports them', () => {
// new URL('http://[2001:db8::1]/').hostname is "[2001:db8::1]".
expect(isValidHostname('[::1]')).toBe(true);
expect(isValidHostname('[2001:db8::1]')).toBe(true);
expect(isValidHostname('[::ffff:192.0.2.1]')).toBe(true);
expect(isValidHostname('[2001:db8::1')).toBe(false);
expect(isValidHostname('[zz::1]')).toBe(false);
expect(isValidHostname('[]')).toBe(false);
});

it('matches subdomains but not lookalikes', () => {
expect(hostMatchesDomain('example.com', 'example.com')).toBe(true);
expect(hostMatchesDomain('www.news.example.com', 'example.com')).toBe(true);
Expand All @@ -39,6 +49,13 @@ describe('hostnames', () => {
'*://*.example.com/*',
]);
expect(originPatternsFor('127.0.0.1')).toEqual(['*://127.0.0.1/*']);
// An address has no subdomains: "*://*.[2001:db8::1]/*" is not a valid pattern.
expect(originPatternsFor('[2001:db8::1]')).toEqual(['*://[2001:db8::1]/*']);
});

it('round-trips an IPv6 host through its permission pattern', () => {
const [pattern] = originPatternsFor('[2001:db8::1]');
expect(hostFromPattern(pattern!)).toBe('[2001:db8::1]');
});

it('parses hosts back from patterns', () => {
Expand Down