83 lines
2.5 KiB
JavaScript
83 lines
2.5 KiB
JavaScript
import {mkdirSync, rmSync} from "node:fs";
|
|
import http from "node:http";
|
|
import net from "node:net";
|
|
|
|
const mode = process.env.BRIDGE_MODE || "network";
|
|
const socketPath = process.env.BRIDGE_SOCKET || "/run/provider-proxy/upstream.sock";
|
|
const listenPort = Number.parseInt(process.env.LISTEN_PORT || "17897", 10);
|
|
const upstreamHost = process.env.UPSTREAM_HOST || "127.0.0.1";
|
|
const upstreamPort = Number.parseInt(process.env.UPSTREAM_PORT || "7897", 10);
|
|
const upstreamHttpHost = process.env.UPSTREAM_HTTP_HOST || "";
|
|
|
|
if (mode === "host") {
|
|
mkdirSync("/run/provider-proxy", {recursive: true});
|
|
rmSync(socketPath, {force: true});
|
|
}
|
|
|
|
function createTcpServer() {
|
|
return net.createServer((client) => {
|
|
client.pause();
|
|
const upstream = mode === "host"
|
|
? net.connect({host: upstreamHost, port: upstreamPort})
|
|
: net.connect(socketPath);
|
|
upstream.once("connect", () => {
|
|
client.pipe(upstream);
|
|
upstream.pipe(client);
|
|
client.resume();
|
|
});
|
|
const close = () => {
|
|
client.destroy();
|
|
upstream.destroy();
|
|
};
|
|
client.on("error", close);
|
|
upstream.on("error", close);
|
|
});
|
|
}
|
|
|
|
function createHttpServer() {
|
|
return http.createServer((request, response) => {
|
|
const upstream = http.request({
|
|
socketPath,
|
|
method: request.method,
|
|
path: request.url,
|
|
headers: {...request.headers, host: upstreamHttpHost}
|
|
}, (upstreamResponse) => {
|
|
response.writeHead(
|
|
upstreamResponse.statusCode || 502,
|
|
upstreamResponse.statusMessage,
|
|
upstreamResponse.headers
|
|
);
|
|
upstreamResponse.pipe(response);
|
|
});
|
|
|
|
upstream.on("error", () => {
|
|
if (!response.headersSent) response.writeHead(502);
|
|
response.end();
|
|
});
|
|
request.on("aborted", () => upstream.destroy());
|
|
request.pipe(upstream);
|
|
});
|
|
}
|
|
|
|
const server = mode === "network" && upstreamHttpHost
|
|
? createHttpServer()
|
|
: createTcpServer();
|
|
|
|
const listenTarget = mode === "host" ? socketPath : {host: "0.0.0.0", port: listenPort};
|
|
server.listen(listenTarget, () => {
|
|
const target = mode === "host" ? socketPath : `0.0.0.0:${listenPort}`;
|
|
const upstream = mode === "host" ? `${upstreamHost}:${upstreamPort}` : socketPath;
|
|
const protocol = upstreamHttpHost ? `http host=${upstreamHttpHost}` : "tcp";
|
|
console.log(`provider proxy ${mode} bridge ${target} -> ${upstream} (${protocol})`);
|
|
});
|
|
|
|
function shutdown() {
|
|
server.close(() => {
|
|
if (mode === "host") rmSync(socketPath, {force: true});
|
|
process.exit(0);
|
|
});
|
|
}
|
|
|
|
process.on("SIGTERM", shutdown);
|
|
process.on("SIGINT", shutdown);
|