Skip to content

Commit

Permalink
feat: follow proxies (#2)
Browse files Browse the repository at this point in the history
  • Loading branch information
astorm committed May 7, 2021
1 parent bb209fc commit 7406c37
Show file tree
Hide file tree
Showing 2 changed files with 54 additions and 1 deletion.
17 changes: 16 additions & 1 deletion index.js
Original file line number Diff line number Diff line change
@@ -1,7 +1,10 @@
const awaitEvent = require('await-event')
const socketLocation = require('socket-location')

module.exports = async function httpRequestToUrl (request) {
module.exports = async function httpRequestToUrl (request, opts = {}) {
// default to true
opts.followProxies = opts.followProxies !== false

if (!request.socket) {
await awaitEvent(request, 'socket')
}
Expand All @@ -10,5 +13,17 @@ module.exports = async function httpRequestToUrl (request) {
const proto = `http${socket.encrypted ? 's' : ''}:`
const location = await socketLocation(socket)

if (isProxiedRequest(request) && opts.followProxies) {
return request.path
}

if (isProxiedRequest(request) && !opts.followProxies) {
return `${proto}//${location}`
}

return `${proto}//${location}${request.path}`
}

function isProxiedRequest (request) {
return request.path.indexOf('https:') === 0 || request.path.indexOf('http:') === 0
}
38 changes: 38 additions & 0 deletions test.js
Original file line number Diff line number Diff line change
Expand Up @@ -29,6 +29,44 @@ tap.test('after connect', async t => {
t.end()
})

tap.test('proxy', async t => {
const { port } = await makeServer()

const opts = {
host: '127.0.0.1',
port,
method: 'GET',
path: 'http://example.com/foo'
}
const client = http.request(opts, res => res.resume())
client.end()

const location = await httpRequestToUrl(client)
t.equal(location, 'http://example.com/foo')

const location2 = await httpRequestToUrl(client, { followProxies: true })
t.equal(location2, 'http://example.com/foo')

t.end()
})

tap.test('proxy do not follow', async t => {
const { port } = await makeServer()

const opts = {
host: '127.0.0.1',
port,
method: 'GET',
path: 'http://example.com/foo'
}
const client = http.request(opts, res => res.resume())
client.end()

const location = await httpRequestToUrl(client, { followProxies: false })
t.equal(location, `http://127.0.0.1:${port}`)

t.end()
})
function makeServer () {
return new Promise(resolve => {
const server = http.createServer((req, res) => {
Expand Down

0 comments on commit 7406c37

Please sign in to comment.