|
/* file:./proxy.json |
|
{ |
|
"servers": [ |
|
{ |
|
"token": "abc", |
|
"port": "8007", |
|
"target": "http://localhost:8008" |
|
}, |
|
{ |
|
"token": "def", |
|
"port": "8006", |
|
"target": "http://localhost:8005" |
|
} |
|
|
|
] |
|
} |
|
*/ |
|
|
|
const url = require('url'); |
|
const httpProxy = require('http-proxy'); |
|
const exitHook = require('exit-hook'); |
|
const config = require('./proxy.json'); |
|
|
|
process.env.NODE_TLS_REJECT_UNAUTHORIZED = '0'; |
|
|
|
function proxy(target, port, token) { |
|
const proxy = httpProxy.createProxyServer({ |
|
target, |
|
preserveHeaderKeyCase: true, |
|
followRedirects: true, |
|
ignorePath: true, |
|
}); |
|
|
|
proxy.on('error', e => { |
|
console.error(e); |
|
}); |
|
|
|
proxy.on('proxyReq', function(proxyReq, req, res, options) { |
|
const request = url.parse(req.url, true); |
|
|
|
if (request.query.token !== token) { |
|
console.warn( |
|
`Unauthorized on *:${port}: token="${request.query.token || |
|
'N/A'}" ip="${req.connection.remoteAddress || 'N/A'}"`, |
|
); |
|
res.writeHead(401, { 'Content-Type': 'application/json' }); |
|
res.end('{"jsonrpc": "2.0", "error": {"code": -32000, "message": "Missing or Invalid Access Token"}, "id": "0"}'); |
|
req.destroy('Unauthorized Client'); |
|
} |
|
}); |
|
|
|
console.info(`Proxying *:${ port } > ${ target }`); |
|
proxy.listen(port); |
|
|
|
return () => { |
|
console.info(`Stop proxying *:${ port } > ${target}`); |
|
proxy.close(); |
|
} |
|
} |
|
|
|
const proxies = []; |
|
|
|
exitHook(() => { |
|
for (const stopProxy of proxies) { |
|
stopProxy(); |
|
} |
|
}); |
|
|
|
for (const server of config.servers) { |
|
const { port, target, token } = server; |
|
proxies.push(proxy(target, port, token)); |
|
} |