-
Notifications
You must be signed in to change notification settings - Fork 237
Expand file tree
/
Copy pathwsproxy.js
More file actions
93 lines (77 loc) · 2.1 KB
/
Copy pathwsproxy.js
File metadata and controls
93 lines (77 loc) · 2.1 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
import { WebSocketServer } from 'ws';
import net from 'net';
// Parse command line arguments
const args = {};
for (let i = 2; i < process.argv.length; i++) {
const arg = process.argv[i];
if (arg.startsWith('-')) {
const key = arg.replace(/^-+/, '');
const val = process.argv[i + 1];
if (val && !val.startsWith('-')) {
args[key] = val;
i++;
} else {
args[key] = true;
}
}
}
const port = parseInt(args.p || args.port || process.env.PORT || '5999', 10);
const redirectStr = args.r || args.redirect || '';
const redirects = {};
if (redirectStr) {
redirectStr.split(',').forEach(pair => {
const [src, dest] = pair.split('=');
if (src && dest) {
redirects[src.trim()] = dest.trim();
}
});
}
console.log(`[wsProxy] Listening on port ${port}`);
if (Object.keys(redirects).length > 0) {
console.log('[wsProxy] Configured redirects:', redirects);
}
const wss = new WebSocketServer({ port });
wss.on('connection', (ws, req) => {
const from = req.socket.remoteAddress;
let target = req.url.slice(1); // Remove leading slash
// Apply redirects
if (redirects[target]) {
console.log(`[wsProxy] Redirecting ${target} -> ${redirects[target]}`);
target = redirects[target];
}
console.log(`[wsProxy] Connection request from ${from} to ${target}`);
const parts = target.split(':');
if (parts.length !== 2) {
console.log(`[wsProxy] Invalid target format: ${target}`);
ws.close();
return;
}
const [host, portStr] = parts;
const targetPort = parseInt(portStr, 10);
const tcp = net.connect(targetPort, host, () => {
console.log(`[wsProxy] Connected to target ${host}:${targetPort}`);
});
tcp.setNoDelay(true);
ws.on('message', message => {
if (tcp.writable) {
tcp.write(message);
}
});
tcp.on('data', data => {
if (ws.readyState === ws.OPEN) {
ws.send(data);
}
});
const cleanup = () => {
tcp.end();
ws.close();
console.log(`[wsProxy] Connection closed for ${target}`);
};
ws.on('close', cleanup);
ws.on('error', cleanup);
tcp.on('close', cleanup);
tcp.on('error', err => {
console.error(`[wsProxy] TCP Error for ${target}:`, err.message);
cleanup();
});
});