From f860ab067462a950c64d56acd7225843dd13c1f0 Mon Sep 17 00:00:00 2001 From: Jason Macgowan Date: Thu, 14 Jun 2018 14:09:26 -0400 Subject: [PATCH 1/2] fix: parse port in x-forwarded-for (#827) --- lib/request.js | 9 +++++++++ test/request/ips.js | 18 ++++++++++++++++++ 2 files changed, 27 insertions(+) diff --git a/lib/request.js b/lib/request.js index 7881d4c60..069d5b43a 100644 --- a/lib/request.js +++ b/lib/request.js @@ -433,6 +433,15 @@ module.exports = { const val = this.get('X-Forwarded-For'); return proxy && val ? val.split(/\s*,\s*/) + .map(host => { + let normalizedHost = host; + if (net.isIPv6(host)) { + normalizedHost = `[${host}]`; + } + + return parse(`http://${normalizedHost}`).hostname; + }) + .filter(ip => !!ip) : []; }, diff --git a/test/request/ips.js b/test/request/ips.js index 8e0a5f0c7..65478f09d 100644 --- a/test/request/ips.js +++ b/test/request/ips.js @@ -23,5 +23,23 @@ describe('req.ips', () => { assert.deepEqual(req.ips, ['127.0.0.1', '127.0.0.2']); }); }); + + describe('and contains IPv4', () => { + it('should not return port', () => { + const req = request(); + req.app.proxy = true; + req.header['x-forwarded-for'] = '127.0.0.1:80,127.0.0.2'; + assert.deepEqual(req.ips, ['127.0.0.1', '127.0.0.2']); + }); + }); + + describe('and contains IPv6', () => { + it('should parse correctly', () => { + const req = request(); + req.app.proxy = true; + req.header['x-forwarded-for'] = '::1'; + assert.deepEqual(req.ips, ['::1']); + }); + }); }); }); From d2a271489a5ab7d08393b3edfe539868b2af3771 Mon Sep 17 00:00:00 2001 From: Jason Macgowan <1389531+jasonmacgowan@users.noreply.github.com> Date: Sun, 19 Jul 2020 00:15:11 -0400 Subject: [PATCH 2/2] fix: use URL constuctor to parse IP --- lib/request.js | 31 +++++++++++++++++++------------ 1 file changed, 19 insertions(+), 12 deletions(-) diff --git a/lib/request.js b/lib/request.js index 9b1dae44e..4597680bf 100644 --- a/lib/request.js +++ b/lib/request.js @@ -433,21 +433,28 @@ module.exports = { get ips() { const proxy = this.app.proxy; const val = this.get(this.app.proxyIpHeader); - let ips = proxy && val - ? val.split(/\s*,\s*/) - .map(host => { - let normalizedHost = host; - if (net.isIPv6(host)) { - normalizedHost = `[${host}]`; - } - - return parse(`http://${normalizedHost}`).hostname; - }) - .filter(ip => !!ip) - : []; + let ips = []; + + if (proxy && val) { + ips = val.split(/\s*,\s*/) + .map(host => { + let normalizedHost = host; + + if (net.isIPv6(host)) { + normalizedHost = `[${host}]`; + } + + const hostname = new URL(`http://${normalizedHost}`).hostname; + + return hostname.replace(/(^\[|\]$)/g, ''); + }) + .filter(ip => !!ip); + } + if (this.app.maxIpsCount > 0) { ips = ips.slice(-this.app.maxIpsCount); } + return ips; },