diff --git a/lib/main.js b/lib/main.js index b25936ca..ce61eb29 100644 --- a/lib/main.js +++ b/lib/main.js @@ -77,7 +77,10 @@ function SockJS(url, protocols, options) { var secure = parsedUrl.protocol === 'https:'; // Step 2 - don't allow secure origin with an insecure protocol if (loc.protocol === 'https:' && !secure) { - throw new Error('SecurityError: An insecure SockJS connection may not be initiated from a page loaded over HTTPS'); + // exception is 127.0.0.0/8 and ::1 urls + if (!urlUtils.isLoopbackAddr(parsedUrl.host)) { + throw new Error('SecurityError: An insecure SockJS connection may not be initiated from a page loaded over HTTPS'); + } } // Step 3 - check port access - no need here diff --git a/lib/utils/url.js b/lib/utils/url.js index 2be2d413..980a5682 100644 --- a/lib/utils/url.js +++ b/lib/utils/url.js @@ -44,4 +44,8 @@ module.exports = { , addQuery: function (url, q) { return url + (url.indexOf('?') === -1 ? ('?' + q) : ('&' + q)); } + +, isLoopbackAddr: function (addr) { + return /^127\.([0-9]{1,3})\.([0-9]{1,3})\.([0-9]{1,3})$/i.test(addr) || /^::1$/.test(addr); + } }; diff --git a/tests/lib/main-node.js b/tests/lib/main-node.js index 87456be6..f4140654 100644 --- a/tests/lib/main-node.js +++ b/tests/lib/main-node.js @@ -22,6 +22,19 @@ describe('SockJS', function() { }); }); + // https://www.w3.org/TR/secure-contexts/#is-origin-trustworthy + it('should NOT throw SecurityError for 127.0.0.1/8 url from a secure page', function () { + expect(function () { + sjs('http://127.0.0.1'); + }).to.not.throwException(); + }); + + it('should NOT throw SecurityError for ::1 url from a secure page', function () { + expect(function () { + sjs('http://::1'); + }).to.not.throwException(); + }); + it('should throw SyntaxError for an invalid url', function () { expect(function () { sjs('//localhost');