Skip to content

Instantly share code, notes, and snippets.

@AlexanderC
Last active November 12, 2020 09:55
Show Gist options
  • Save AlexanderC/201e5b16eeb1e7a58b329a2da3210acd to your computer and use it in GitHub Desktop.
Save AlexanderC/201e5b16eeb1e7a58b329a2da3210acd to your computer and use it in GitHub Desktop.
Stupid JSONRPC proxy
/* 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));
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment