This repository has been archived by the owner on Dec 2, 2019. It is now read-only.
-
-
Notifications
You must be signed in to change notification settings - Fork 5
/
index.js
123 lines (118 loc) · 2.87 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
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
require('dotenv').config()
const WSS = require('ws').Server
const secret = process.env.BEZERK_SECRET
const Server = new WSS({
clientTracking: true,
port: process.env.BEZERK_PORT
})
Server.on('connection', socket => {
socket.on('message', msg => handle(socket, msg))
socket.on('close', () => {})
socket.on('error', console.error)
send(socket, {
op: '1001'
})
})
function handle (socket, msg) {
if (socket.readyState !== 1) return
try {
msg = JSON.parse(msg)
validate(socket, msg)
} catch (e) {
return socket.close(4001) // JSON_DECRYPT_ERROR
}
switch (msg.op) {
case '1050': { // COUNT
send(socket, {
op: '1051',
c: {
shards: Array.from(Server.clients).filter(x => x.type === 'shard').length,
listeners: Array.from(Server.clients).filter(x => x.type === 'listener').length
}
})
break
}
case '1003': { // IDENTIFY_SUPPLY
if (socket.type) return socket.close(4002) // ALREADY_AUTHENTICATED
if (msg.c.secret === secret) {
send(socket, {
op: '1002',
c: {
success: true
}
})
if (msg.c.shard) {
socket.type = 'shard'
socket.shardid = msg.c.shard
} else {
socket.type = 'listener'
}
} else {
send(socket, {
op: '1002',
c: {
success: false
}
})
}
break
}
case '2002': { // REQUEST_REPLY
if (socket.type === 'shard') {
Server.clients.forEach(x => {
if (x.type === 'listener') {
send(x, {
op: '2002',
c: msg.c
})
}
})
}
break
}
case '2005': { // REQUEST_APPLY
if (socket.type === 'listener') {
if (msg.d !== undefined) {
Server.clients.forEach(x => {
if (x.type === 'shard' && x.shardid) {
return send(x, {
op: '2001', // REQUEST
c: msg.c
})
}
})
send(socket, {
op: '5000' // CANNOT_COMPLY
})
} else {
Server.clients.forEach(x => {
if (x.type === 'shard') {
send(x, {
op: '2001', // REQUEST
c: msg.c
})
}
})
}
}
break
}
case '5000': { // CANNOT_COMPLY
Server.clients.forEach(x => {
if (x.type !== socket.type) send(x, msg)
})
break
}
}
}
function send (socket, payload) {
if (socket.readyState !== 1) return
if (typeof payload === 'object') payload = JSON.stringify(payload)
socket.send(payload)
}
function validate (socket, msg) {
if (socket.readyState !== 1) return
if (msg.op === undefined) throw new Error()
if (msg.c === undefined) throw new Error()
return true
}