-
Notifications
You must be signed in to change notification settings - Fork 0
/
appsec.js
50 lines (43 loc) · 1.64 KB
/
appsec.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
const WebSocket = require('ws');
const uuid = require('uuid');
const HttpsServer = require('https').createServer;
const fs = require('fs');
const server = HttpsServer({
cert: fs.readFileSync(process.env.BWS_CERT),
key: fs.readFileSync(process.env.BWS_KEY)
});
const wss = new WebSocket.Server({ server });
wss.on('connection', (ws) => {
ws.eventReady = false;
ws.clientID = undefined;
ws.listens = [];
ws.on('message', (data) => {
try {
const packet = JSON.parse(data);
if (!ws.eventReady) {
const { clientID, listens } = packet;
ws.clientID = clientID || uuid.v4();
ws.listens = listens || [];
ws.eventReady = true;
return;
}
packet.$sender = ws.clientID;
if ('$target' in packet) {
wss.clients.forEach((client) => {
if (client.clientID == packet.$target && client !== ws && client.readyState === WebSocket.OPEN && client.eventReady && client.listens.includes(JSON.parse(data).event)) {
client.send(JSON.stringify(packet));
}
});
} else {
wss.clients.forEach((client) => {
if (client !== ws && client.readyState === WebSocket.OPEN && client.eventReady && client.listens.includes(JSON.parse(data).event)) {
client.send(JSON.stringify(packet));
}
});
}
} catch {
ws.send(JSON.stringify({ $error: "Incoming packet malformed" }));
}
});
});
server.listen(443);