bh / proxy.js
bahi-bh's picture
Create proxy.js
0a77b57 verified
Raw History Blame Contribute Delete
1.36 kB
const http = require('http');
const net = require('net');
const T_HOST = '127.0.0.1';
const T_PORT = 3080;
// إعادة كتابة الترويسات لتبدو الطلبات قادمة من localhost
function fix(h) {
const o = { ...h, host: `${T_HOST}:${T_PORT}` };
if (o.origin) o.origin = `http://${T_HOST}:${T_PORT}`;
for (const k of Object.keys(o)) {
if (k.startsWith('x-forwarded-')) delete o[k];
}
return o;
}
const server = http.createServer((req, res) => {
const p = http.request(
{
host: T_HOST,
port: T_PORT,
method: req.method,
path: req.url,
headers: fix(req.headers),
},
(pr) => {
res.writeHead(pr.statusCode, pr.headers);
pr.pipe(res);
}
);
p.on('error', () => {
res.writeHead(502);
res.end('upstream not ready');
});
req.pipe(p);
});
// دعم WebSocket
server.on('upgrade', (req, socket, head) => {
const up = net.connect(T_PORT, T_HOST, () => {
let raw = `${req.method} ${req.url} HTTP/1.1\r\n`;
for (const [k, v] of Object.entries(fix(req.headers))) {
raw += `${k}: ${v}\r\n`;
}
up.write(raw + '\r\n');
if (head && head.length) up.write(head);
socket.pipe(up);
up.pipe(socket);
});
up.on('error', () => socket.destroy());
socket.on('error', () => up.destroy());
});
server.listen(7860, '0.0.0.0');