Skip to content

Commit

Permalink
Allow loopback address urls as exception to loading from secure contexts
Browse files Browse the repository at this point in the history
Fixes #486
  • Loading branch information
brycekahle committed Aug 2, 2020
1 parent a098d4e commit a57c910
Show file tree
Hide file tree
Showing 3 changed files with 21 additions and 1 deletion.
5 changes: 4 additions & 1 deletion lib/main.js
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
4 changes: 4 additions & 0 deletions lib/utils/url.js
Original file line number Diff line number Diff line change
Expand Up @@ -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);
}
};
13 changes: 13 additions & 0 deletions tests/lib/main-node.js
Original file line number Diff line number Diff line change
Expand Up @@ -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');
Expand Down

0 comments on commit a57c910

Please sign in to comment.