diff --git a/src/shared/domain.ts b/src/shared/domain.ts index 79eea3d..c2394cf 100644 --- a/src/shared/domain.ts +++ b/src/shared/domain.ts @@ -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); } @@ -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}/*`]; } diff --git a/tests/unit/domain.test.ts b/tests/unit/domain.test.ts index 42ef938..5eff113 100644 --- a/tests/unit/domain.test.ts +++ b/tests/unit/domain.test.ts @@ -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); @@ -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', () => {