forked from favibeas/node-proxy
-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathindex.js
69 lines (60 loc) · 1.47 KB
/
index.js
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
const express = require('express');
const http = require('http');
const WebSocket = require('ws');
const net = require('net');
const PORT = process.env.PORT || 8000;
// MongoDB
const blackPool = [
"stratum-mining-pool.zapto.org"
];
// App
const app = express();
const server = http.createServer(app);
const wss = new WebSocket.Server({ server });
function proxySender(ws, conn) {
ws.on('close', () => {
conn.end();
});
ws.on('message', (cmd) => {
try {
const command = JSON.parse(cmd);
const method = command.method;;
conn.write(cmd);
} catch (error) {
console.log(`[Error][INTERNAL] ${error}`);
ws.close();
}
});
}
function proxyReceiver(conn, cmdq) {
conn.on('data', (data) => {
cmdq.send(data.toString());
});
conn.on('end', () => {
cmdq.close();
});
conn.on('error', (err) => {
conn.end();
});
}
function proxyConnect(host, port) {
const conn = net.createConnection(port, host);
return conn;
}
async function proxyMain(ws, req) {
ws.on('message', (message) => {
const command = JSON.parse(message);
if (command.method === 'proxy.connect' && command.params.length === 2) {
const [host, port] = command.params || [];
const conn = proxyConnect(host, port);
if (conn) {
proxySender(ws, conn);
proxyReceiver(conn, ws);
}
}
});
}
wss.on('connection', proxyMain);
server.listen(PORT, "0.0.0.0", () => {
console.log(`Server running on port ${PORT}`);
});