diff --git a/lib/utils.js b/lib/utils.js index 11ff55a..cf6f2c9 100755 --- a/lib/utils.js +++ b/lib/utils.js @@ -1,6 +1,7 @@ 'use strict'; const Boom = require('@hapi/boom'); +const Url = require('url'); const internals = {}; @@ -17,12 +18,6 @@ exports.limits = { }; -// Extract host and port from request - -// $1 $2 -internals.hostHeaderRegex = /^(?:(?:\r\n)?\s)*((?:[^:]+)|(?:\[[^\]]+\]))(?::(\d+))?(?:(?:\r\n)?\s)*$/; // (IPv4, hostname)|(IPv6) - - exports.parseHost = function (req, hostHeaderName) { hostHeaderName = (hostHeaderName ? hostHeaderName.toLowerCase() : 'host'); @@ -35,14 +30,17 @@ exports.parseHost = function (req, hostHeaderName) { return null; } - const hostParts = hostHeader.match(internals.hostHeaderRegex); - if (!hostParts) { + let uri; + try { + uri = new Url.URL('http://' + hostHeader); + } + catch (err) { return null; } return { - name: hostParts[1], - port: (hostParts[2] ? hostParts[2] : (req.connection && req.connection.encrypted ? 443 : 80)) + name: uri.hostname, + port: (uri.port ? uri.port : (req.connection && req.connection.encrypted ? 443 : 80)) }; }; diff --git a/test/utils.js b/test/utils.js index 252b35b..c9b3138 100755 --- a/test/utils.js +++ b/test/utils.js @@ -55,7 +55,7 @@ describe('Utils', () => { method: 'POST', url: '/resource/4?filter=a', headers: { - host: '[123:123:123]', + host: '[123:123::123]', 'content-type': 'text/plain;x=y' }, connection: { @@ -72,7 +72,7 @@ describe('Utils', () => { method: 'POST', url: '/resource/4?filter=a', headers: { - host: '[123:123:123]:8000', + host: '[123:123::123]:8000', 'content-type': 'text/plain;x=y' }, connection: { @@ -82,7 +82,7 @@ describe('Utils', () => { const host = Hawk.utils.parseHost(req, 'Host'); expect(host.port).to.equal('8000'); - expect(host.name).to.equal('[123:123:123]'); + expect(host.name).to.equal('[123:123::123]'); }); it('errors on header too long', () => {