Skip to content

Instantly share code, notes, and snippets.

@num8er
Last active January 25, 2022 23:20
Show Gist options
  • Save num8er/8d0ae2b1011dc5c50785a0c7cdf2e4b6 to your computer and use it in GitHub Desktop.
Save num8er/8d0ae2b1011dc5c50785a0c7cdf2e4b6 to your computer and use it in GitHub Desktop.
const net = require("net");
const server = net.createServer();
server.on("connection", (clientToProxySocket) => {
//console.log("Client connected to proxy");
clientToProxySocket.once("data", (data) => {
let isTLSConnection = data.toString().indexOf("CONNECT") !== -1;
let serverPort = 8008;
let serverAddress = '127.0.0.1';
// Creating a connection from proxy to destination server
const proxyToServerSocket = net.createConnection(
{
host: serverAddress,
port: serverPort,
},
() => {
// console.log("Proxy to server set up");
}
);
if (isTLSConnection) {
clientToProxySocket.write("HTTP/1.1 200 OK\r\n\r\n");
} else {
proxyToServerSocket.write(data);
}
clientToProxySocket.pipe(proxyToServerSocket);
proxyToServerSocket.pipe(clientToProxySocket);
proxyToServerSocket.on('close', () => {
//console.log('server closed connection');
});
clientToProxySocket.on('close', () => {
try {
proxyToServerSocket.destroy();
}
catch {}
//console.log('client closed connection');
});
proxyToServerSocket.on("error", (err) => {
if (err.code.toString().trim() === 'ECONNRESET') return;
if (err.code.toString().trim() === 'ECONNREFUSED') return;
console.log("Proxy to server error");
console.log(err);
});
clientToProxySocket.on("error", (err) => {
if (err.code.toString().trim() === 'ECONNRESET') return;
if (err.code.toString().trim() === 'ECONNREFUSED') return;
console.log("Client to proxy error");
console.log(err)
});
});
});
server.on("error", (err) => {
console.log("Some internal server error occurred");
console.log(err.message);
});
server.on("close", () => {
//console.log("Client disconnected");
});
server.listen(
{
host: "0.0.0.0",
port: 80,
},
() => {
console.log("Server listening on 0.0.0.0:80");
}
);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment