Skip to content

Commit f860ab0

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

File tree

2 files changed

+27
-0
lines changed

2 files changed

+27
-0
lines changed

lib/request.js

+9
Original file line numberDiff line numberDiff line change
@@ -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 parse(`http://${normalizedHost}`).hostname;
443+
})
444+
.filter(ip => !!ip)
436445
: [];
437446
},
438447

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)