diff --git a/README.md b/README.md index 321666a..b1b2948 100644 --- a/README.md +++ b/README.md @@ -28,9 +28,10 @@ const addresses = forwarded(req) ``` Parse the `X-Forwarded-For` header from the request. Returns an array -of the addresses, including the socket address for the `req`, in reverse -order (i.e. index `0` is the socket address and the last index is the -furthest address, typically the end-user). +of the addresses, including the socket address for the `req` if present, in reverse +order (i.e. index `0` is the socket address if present and the last index is the +furthest address, typically the end-user). May return an empty array if no socket +address (i.e. unix domain socket) and no `X-Forwarded-For` header. ## Testing diff --git a/index.js b/index.js index 1195216..d838c76 100644 --- a/index.js +++ b/index.js @@ -18,19 +18,23 @@ function forwarded (req) { const socketAddr = req.socket.remoteAddress if (!header || typeof header !== 'string') { - return [socketAddr] + return socketAddr ? [socketAddr] : [] } else if (header.indexOf(',') === -1) { const remote = header.trim() - return (remote.length) - ? [socketAddr, remote] - : [socketAddr] + if (socketAddr) { + return (remote.length) + ? [socketAddr, remote] + : [socketAddr] + } else { + return (remote.length) ? [remote] : [] + } } else { return parse(header, socketAddr) } } function parse (header, socketAddr) { - const result = [socketAddr] + const result = socketAddr ? [socketAddr] : [] let end = header.length let start = end diff --git a/test/test.js b/test/test.js index b7e3439..83f2a4b 100644 --- a/test/test.js +++ b/test/test.js @@ -138,6 +138,41 @@ test('should trim trailing OWS with tabs (HTAB)', function (t) { ]) }) +test('should handle unix domain sockets without X-Forwarded-For header', function (t) { + t.plan(1) + const req = createReq(undefined) + t.assert.deepStrictEqual(forwarded(req), []) +}) + +test('should handle unix domain sockets with X-Forwarded-For header containing no addresses', function (t) { + t.plan(1) + const req = createReq(undefined, { + 'x-forwarded-for': ' ' + }) + t.assert.deepStrictEqual(forwarded(req), []) +}) + +test('should handle unix domain sockets with X-Forwarded-For header containing one address', function (t) { + t.plan(1) + const req = createReq(undefined, { + 'x-forwarded-for': '10.0.0.1' + }) + t.assert.deepStrictEqual(forwarded(req), [ + '10.0.0.1' + ]) +}) + +test('should handle unix domain sockets with X-Forwarded-For header containing multiple addresses', function (t) { + t.plan(1) + const req = createReq(undefined, { + 'x-forwarded-for': '10.0.0.2, 10.0.0.1' + }) + t.assert.deepStrictEqual(forwarded(req), [ + '10.0.0.1', + '10.0.0.2' + ]) +}) + function createReq (socketAddr, headers) { return { socket: {