Skip to content

Commit

Permalink
fix: parse port in x-forwarded-for (koajs#827)
Browse files Browse the repository at this point in the history
  • Loading branch information
jasonmacgowan committed Jun 14, 2018
1 parent 77a4cfb commit 2b59260
Show file tree
Hide file tree
Showing 2 changed files with 29 additions and 2 deletions.
13 changes: 11 additions & 2 deletions lib/request.js
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@
* Module dependencies.
*/

const URL = require('url').URL;
const url = require('url');
const net = require('net');
const contentType = require('content-type');
const stringify = require('url').format;
Expand Down Expand Up @@ -283,7 +283,7 @@ module.exports = {
const host = this.host;
const originalUrl = this.originalUrl || ''; // avoid undefined in template string
try {
this.memoizedURL = new URL(`${protocol}://${host}${originalUrl}`);
this.memoizedURL = new url.URL(`${protocol}://${host}${originalUrl}`);
} catch (err) {
this.memoizedURL = Object.create(null);
}
Expand Down 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 url.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 2b59260

Please sign in to comment.