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
|
const { WebSocketServer } = require('ws');
const fs = require('fs');
const uuid = require('uuid-v4');
const wss = new WebSocketServer({ port: 38050 });
const servers = {};
const clients = {};
wss.on('connection', function connection(ws, req) {
ws.linked = null;
ws.id = null;
ws.linkedServer = null;
console.log("New client: " + req.headers['x-forwarded-for'].split(',')[0].trim());
ws.on('message', (_data) => {
if (ws.linked) {
try {
let data = JSON.parse(_data.toString());
data["_id"] = ws.id;
servers[ws.linked].send(JSON.stringify(data));
} catch (e) {
console.error(e);
}
} else {
try {
let data = JSON.parse(_data.toString());
if (data.type === "client") {
if (Object.keys(servers).includes(data.id)) {
if (fs.existsSync(__dirname + "/../includes/tokens/" + data.token.replaceAll(".", "").replaceAll("/", ""))) {
ws.linked = data.id;
ws.id = uuid();
servers[data.id].send(JSON.stringify({
type: "client",
id: ws.id,
address: req.headers['x-forwarded-for'].split(',')[0].trim(),
name: data.name
}));
clients[ws.id] = ws;
} else {
console.log("close(c), reason: invalid token");
ws.close();
}
} else {
console.log("close(c), reason: no server");
ws.close();
}
} else if (data.type === "server") {
if (Object.keys(servers).includes(data.id)) {
console.log("close(s), reason: already online");
ws.close();
return;
}
ws.linkedServer = data.id;
servers[data.id] = ws;
} else if (data._id) {
try {
if (clients[data._id]) {
clients[data._id].send(_data);
}
} catch (e) {
console.error(e);
}
}
} catch (e) {
console.error(e);
}
}
})
ws.on('close', () => {
if (ws.linked) {
try {
servers[ws.linked].send(JSON.stringify({
type: "close",
id: ws.id
}))
} catch (e) {
console.error(e);
}
delete clients[ws.id];
} else if (ws.linkedServer) {
delete servers[ws.linkedServer];
}
})
});
|