diff --git a/lib/web/fetch/util.js b/lib/web/fetch/util.js index ad7f8ba5fb2..b7086c4799e 100644 --- a/lib/web/fetch/util.js +++ b/lib/web/fetch/util.js @@ -554,17 +554,11 @@ function stripURLForReferrer (url, originOnly = false) { return url } -const potentialleTrustworthyIPv4RegExp = new RegExp('^(?:' + - '(?:127\\.)' + - '(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\\.){2}' + - '(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[1-9])' + -')$') - -const potentialleTrustworthyIPv6RegExp = new RegExp('^(?:' + - '(?:(?:0{1,4}):){7}(?:(?:0{0,3}1))|' + - '(?:(?:0{1,4}):){1,6}(?::(?:0{0,3}1))|' + - '(?:::(?:0{0,3}1))|' + -')$') +const isPotentialleTrustworthyIPv4 = RegExp.prototype.test + .bind(/^127\.(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]\d|\d)\.){2}(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]\d|\d)$/) + +const isPotentiallyTrustworthyIPv6 = RegExp.prototype.test + .bind(/^(?:(?:0{1,4}:){7}|(?:0{1,4}:){1,6}:|::)0{0,3}1$/) /** * Check if host matches one of the CIDR notations 127.0.0.0/8 or ::1/128. @@ -579,11 +573,11 @@ function isOriginIPPotentiallyTrustworthy (origin) { if (origin[0] === '[' && origin[origin.length - 1] === ']') { origin = origin.slice(1, -1) } - return potentialleTrustworthyIPv6RegExp.test(origin) + return isPotentiallyTrustworthyIPv6(origin) } // IPv4 - return potentialleTrustworthyIPv4RegExp.test(origin) + return isPotentialleTrustworthyIPv4(origin) } /** diff --git a/test/fetch/util.js b/test/fetch/util.js index c0f8aefaa74..a23194242e5 100644 --- a/test/fetch/util.js +++ b/test/fetch/util.js @@ -282,6 +282,7 @@ describe('isValidHeaderValue', () => { describe('isOriginIPPotentiallyTrustworthy()', () => { [ + ['', false], ['0000:0000:0000:0000:0000:0000:0000:0001', true], ['0001:0000:0000:0000:0000:0000:0000:0001', false], ['0000:0000:0000:0000:0000:0000::0001', true], @@ -292,16 +293,20 @@ describe('isOriginIPPotentiallyTrustworthy()', () => { ['0000:0000:0000::0001', true], ['0000:0000::0001', true], ['0000::0001', true], + ['::1001', false], ['::0001', true], + ['::0011', false], ['::1', true], ['[::1]', true], + ['[::1', false], + ['::1]', false], ['::2', false], ['::', false], + ['126.0.0.0', false], + ['127.0.0.0', true], ['127.0.0.1', true], ['127.255.255.255', true], - ['128.255.255.255', false], - ['127.0.0.1', true], - ['127.0.0.0', false] + ['128.255.255.255', false] ].forEach(([ip, expected]) => { test(`${ip} is ${expected ? '' : 'not '}potentially trustworthy`, () => { assert.strictEqual(util.isOriginIPPotentiallyTrustworthy(ip), expected)