Skip to content

Commit

Permalink
fix: parse port in x-forwarded-for (#827)
Browse files Browse the repository at this point in the history
  • Loading branch information
jasonmacgowan committed Jul 19, 2020
1 parent 77a4cfb commit f860ab0
Show file tree
Hide file tree
Showing 2 changed files with 27 additions and 0 deletions.
9 changes: 9 additions & 0 deletions lib/request.js
Original file line number Diff line number Diff line change
Expand Up @@ -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)
: [];
},

Expand Down
18 changes: 18 additions & 0 deletions test/request/ips.js
Original file line number Diff line number Diff line change
Expand Up @@ -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']);
});
});
});
});

0 comments on commit f860ab0

Please sign in to comment.