Last active
May 22, 2020 17:11
-
-
Save kevinswiber/9a9a683002bc4af6dd27c7ef54953425 to your computer and use it in GitHub Desktop.
Reverse Proxy that passes through Postman's proxy to capture incoming HTTP traffic.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// A reverse proxy that captures incoming HTTP traffic and sends it | |
// through Postman's forward proxy, which forwards traffic to the | |
// specified target in process.env.TARGET. | |
// request | |
// client -> this-proxy -> postman-proxy --| | |
// | | |
// target | |
// response | | |
// client <- this-proxy <- postman-proxy --| | |
const http = require('http'); | |
const target = process.env.TARGET; | |
const proxy = new URL( | |
process.env.http_proxy || process.env.HTTP_PROXY || 'http://localhost:5555'); | |
const server = http.createServer((req, res) => { | |
try { | |
let forwardedFor = req.headers['x-forwarded-for'] || ''; | |
const ff = forwardedFor.split(','); | |
ff.push(req.connection.remoteAddress); | |
forwardedFor = ff.map(h => h.trim()).join(', '); | |
const options = { | |
headers: Object.assign({}, req.headers, | |
{ | |
'host': target, | |
'x-forwarded-proto': 'http', | |
'x-forwarded-host': req.headers.host, | |
'x-forwarded-for': forwardedFor | |
}), | |
host: proxy.hostname, | |
port: proxy.port, | |
method: req.method, | |
path: `http://${target}${req.url}` // convert to forward proxy style | |
}; | |
const client = http.request(options, (reply) => { | |
res.statusCode = reply.statusCode; | |
res.headers = reply.headers; | |
reply.pipe(res); | |
}); | |
log(`Forwarding request to ${options.path}`); | |
req.pipe(client); | |
} catch (ex) { | |
console.error(ex); | |
} | |
}); | |
server.on('connect', (_req, clientSocket, _head) => { | |
// HTTP tunneling not supported. | |
log('Client attempted to use an HTTP tunnel, sending 502 Bad Gateway.') | |
clientSocket.end('HTTP/1.1 502 Bad Gateway\r\n\rn'); | |
}); | |
server.on('listening', () => { | |
log(`Proxy listening on ${JSON.stringify(server.address())}`); | |
}); | |
server.listen(process.env.PORT || 3100); | |
const log = (msg) => { | |
console.log(new Date(), `=> ${msg}`); | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment