Skip to content

Commit 2b59260

Browse files
committed
fix: parse port in x-forwarded-for (#827)
1 parent 77a4cfb commit 2b59260

File tree

2 files changed

+29
-2
lines changed

2 files changed

+29
-2
lines changed

Diff for: lib/request.js

+11-2
Original file line numberDiff line numberDiff line change
@@ -5,7 +5,7 @@
55
* Module dependencies.
66
*/
77

8-
const URL = require('url').URL;
8+
const url = require('url');
99
const net = require('net');
1010
const contentType = require('content-type');
1111
const stringify = require('url').format;
@@ -283,7 +283,7 @@ module.exports = {
283283
const host = this.host;
284284
const originalUrl = this.originalUrl || ''; // avoid undefined in template string
285285
try {
286-
this.memoizedURL = new URL(`${protocol}://${host}${originalUrl}`);
286+
this.memoizedURL = new url.URL(`${protocol}://${host}${originalUrl}`);
287287
} catch (err) {
288288
this.memoizedURL = Object.create(null);
289289
}
@@ -433,6 +433,15 @@ module.exports = {
433433
const val = this.get('X-Forwarded-For');
434434
return proxy && val
435435
? val.split(/\s*,\s*/)
436+
.map(host => {
437+
let normalizedHost = host;
438+
if (net.isIPv6(host)) {
439+
normalizedHost = `[${host}]`;
440+
}
441+
442+
return url.parse(`http://${normalizedHost}`).hostname;
443+
})
444+
.filter(ip => !!ip)
436445
: [];
437446
},
438447

Diff for: test/request/ips.js

+18
Original file line numberDiff line numberDiff line change
@@ -23,5 +23,23 @@ describe('req.ips', () => {
2323
assert.deepEqual(req.ips, ['127.0.0.1', '127.0.0.2']);
2424
});
2525
});
26+
27+
describe('and contains IPv4', () => {
28+
it('should not return port', () => {
29+
const req = request();
30+
req.app.proxy = true;
31+
req.header['x-forwarded-for'] = '127.0.0.1:80,127.0.0.2';
32+
assert.deepEqual(req.ips, ['127.0.0.1', '127.0.0.2']);
33+
});
34+
});
35+
36+
describe('and contains IPv6', () => {
37+
it('should parse correctly', () => {
38+
const req = request();
39+
req.app.proxy = true;
40+
req.header['x-forwarded-for'] = '::1';
41+
assert.deepEqual(req.ips, ['::1']);
42+
});
43+
});
2644
});
2745
});

0 commit comments

Comments
 (0)