Skip to content

Commit

Permalink
Use req.socket over deprecated req.connection
Browse files Browse the repository at this point in the history
fixes #8
closes #9
  • Loading branch information
dougwilson committed May 31, 2021
1 parent d56b75b commit 63a16a6
Show file tree
Hide file tree
Showing 3 changed files with 47 additions and 3 deletions.
5 changes: 5 additions & 0 deletions HISTORY.md
Original file line number Diff line number Diff line change
@@ -1,3 +1,8 @@
unreleased
==========

* Use `req.socket` over deprecated `req.connection`

0.1.2 / 2017-09-14
==================

Expand Down
16 changes: 15 additions & 1 deletion index.js
Original file line number Diff line number Diff line change
Expand Up @@ -28,13 +28,27 @@ function forwarded (req) {

// simple header parsing
var proxyAddrs = parse(req.headers['x-forwarded-for'] || '')
var socketAddr = req.connection.remoteAddress
var socketAddr = getSocketAddr(req)
var addrs = [socketAddr].concat(proxyAddrs)

// return all addresses
return addrs
}

/**
* Get the socket address for a request.
*
* @param {object} req
* @return {string}
* @private
*/

function getSocketAddr (req) {
return req.socket
? req.socket.remoteAddress
: req.connection.remoteAddress
}

/**
* Parse the X-Forwarded-For header.
*
Expand Down
29 changes: 27 additions & 2 deletions test/test.js
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@ describe('forwarded(req)', function () {
assert.throws(forwarded.bind(null), /argument req.*required/)
})

it('should work without X-Forwarded-For header', function () {
it('should work with X-Forwarded-For header', function () {
var req = createReq('127.0.0.1')
assert.ok(deepEqual(forwarded(req), ['127.0.0.1']))
})
Expand All @@ -34,11 +34,36 @@ describe('forwarded(req)', function () {
})
assert.ok(deepEqual(forwarded(req), ['127.0.0.1', '10.0.0.1', '10.0.0.2']))
})

describe('socket address', function () {
it('should begin with socket address', function () {
var req = createReq('127.0.0.1')
assert.strictEqual(forwarded(req)[0], '127.0.0.1')
})

it('should use address from req.socket', function () {
var req = createReq('127.0.0.1')
assert.strictEqual(forwarded(req)[0], req.socket.remoteAddress)
})

it('should prefer req.socket', function () {
var req = createReq('127.0.0.1')
req.connection = { remoteAddress: '10.0.0.1' }
assert.strictEqual(forwarded(req)[0], '127.0.0.1')
})

it('should use fall back to req.connection', function () {
var req = createReq('127.0.0.1')
req.connection = { remoteAddress: '10.0.0.1' }
req.socket = undefined
assert.strictEqual(forwarded(req)[0], '10.0.0.1')
})
})
})

function createReq (socketAddr, headers) {
return {
connection: {
socket: {
remoteAddress: socketAddr
},
headers: headers || {}
Expand Down

0 comments on commit 63a16a6

Please sign in to comment.