-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain.js
442 lines (368 loc) · 12.1 KB
/
main.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
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
const firebase = require('firebase-admin');
const config = require('./src/config');
global.firebase = firebase;
firebase.initializeApp({
credential: firebase.credential.cert(config.FIREBASE_CREDENTIALS),
});
const { log, debug } = require('./src/log');
const miakode = require('./src/miakode');
const sha256 = require('./src/sha256');
const ws = require('./src/wsServer').server;
const auth = firebase.auth();
const db = firebase.firestore();
const fcm = firebase.messaging();
function setState() {
db.collection('SERVERS').doc(config.SERVER_URL).set({
name: config.SERVER_NAME,
last: Date.now(),
});
}
if (config.SERVER_URL && config.SERVER_NAME) {
log(`Server URL: ${config.SERVER_URL}`);
setState();
setInterval(setState, 1800000); // 1800000ms = 30min = 48/day
} else log('Server has no URL');
/** @enum @const */
const P_TYPES = {
AUTH: {
/** From server (0x) */
OK: '\x00',
/** From user (02) */
USER: '\x02',
/** From coordinator (04) */
COORD: '\x04',
},
USER: {
/** From server (1x) */
PING: '\x10',
DATA: '\x11',
/** From user (2x) */
PONG: '\x20',
ACTION: '\x21',
},
COORD: {
/** From server (3x) */
PING: '\x30',
USERLIST: '\x31',
USER_CONNECT: '\x32',
USER_ACTION: '\x33',
/** From coordinator (4x) */
PONG: '\x40',
COMMIT: '\x41',
NOTIF: '\x42',
},
};
/**
* @param {import('websocket').connection} socket
* @param {string} type
* @param {string} data
*/
function sendPacket(socket, type, data = '') {
socket.sendBytes(Buffer.from(`${type}${data}`));
debug(type);
}
function parsePacket(packet) {
if (!packet.binaryData) return { type: 'unknown' };
const parsed = packet.binaryData.toString();
return {
type: parsed[0],
data: parsed.substring(1),
};
}
const genPayload = () => miakode.string.encode(Math.round(Math.random() * 10000).toString());
function Home(homeID) {
this.id = homeID;
this.variables = {};
this.listeners = {};
this.disconnectCoord = () => null;
/** @type {{ id: string, name: string, displayName: string }[]} */
this.fGroups = [];
/**
* @typedef {Object} fRelation
* @property {string} id ID of the relation (homeID@userID)
* @property {string} home Home ID of the relation
* @property {string} user User ID of the relation
* @property {string} displayName Display name of the user in this home
* @property {string[]} groups Group names of the user in this home
* @property {boolean} isAdmin True if the user is admin in this home
*/
/** @type {fRelation[]} */
this.fRelations = [];
/** @typedef {'onHomeUpdate' | 'onData' | 'onUserEvent' | 'onUserAction'} event */
/** @callback eventCallback @param {{}} data */
/**
* @param {number} socketID
* @param {event} eventName
* @param {eventCallback} callback
*/
this.subscribe = (socketID, eventName, callback) => {
if (!this.listeners[socketID]) this.listeners[socketID] = {};
this.listeners[socketID][eventName] = callback;
};
/** @param {number} socketID */
this.removeListeners = (socketID) => {
delete this.listeners[socketID];
};
/**
* @param {event} event
* @param {eventData} data
*/
this.emit = (event, ...data) => {
Object.values(this.listeners).filter((l) => l[event]).forEach((l) => l[event](...data));
};
const homeDoc = db.collection('homes').doc(homeID);
const groupsDoc = homeDoc.collection('groups');
const homeUsers = db.collection('relations').where('home', '==', homeID);
const unsubGroups = groupsDoc.onSnapshot((snapshot) => {
this.fGroups = snapshot.docs.map((a) => ({ id: a.id, ...a.data() }));
if (this.fRelations.length > 0) this.emit('onHomeUpdate');
debug('Groups changes');
});
const unsubUsers = homeUsers.onSnapshot((snapshot) => {
this.fRelations = snapshot.docs.map((a) => ({ id: a.id, ...a.data() }));
if (this.fGroups.length > 0) this.emit('onHomeUpdate');
debug('Users changes');
});
this.destroy = () => {
unsubGroups();
unsubUsers();
};
}
/** @type {Object<string, Home>} */
const HOMES = {};
let incrementer = 0;
log('Ready !');
ws.on('connect', (socket) => {
incrementer += 1;
const client = {
/** @type {'USER' | 'COORD' | null} */
type: null,
/** @type {string | null} */
homeID: null,
/** @type {number} Packet unique ID */
socketID: incrementer,
/** @type {number} User or coordinator ID */
clientID: null,
};
let pongPayload = null;
let pongTime = null;
socket.on('message', async (packet) => {
const msg = parsePacket(packet);
if (!msg.data) return;
// If not authenticated and packet is not an authentication packet
if (!client.type && ![P_TYPES.AUTH.COORD, P_TYPES.AUTH.USER].includes(msg.type)) return;
// USER AUTHENTICATION
if (msg.type === P_TYPES.AUTH.USER && !client.type) {
debug('Auth user');
const [homeID, userID, userToken] = miakode.array.decode(msg.data);
if (!homeID || !userID || !userToken) {
socket.close(4002, 'WRONG_REQUEST');
return;
}
auth.verifyIdToken(userToken).then(async (fUser) => {
if (fUser.uid !== userID) {
socket.close(4001, 'WRONG_ACCOUNT_CHECK');
return;
}
const relationDoc = await db.collection('relations').doc(`${homeID}@${userID}`).get();
if (!relationDoc.exists) {
socket.close(4001, 'WRONG_ACCOUNT_CHECK');
return;
}
if (!HOMES[homeID]) {
socket.close(4003, 'NO_COORDINATOR');
debug(HOMES);
return;
}
const uGroups = relationDoc.get('groups');
if (!uGroups || uGroups.length === 0) {
socket.close(4004, 'NO_GROUP');
return;
}
client.homeID = homeID;
client.type = 'USER';
client.clientID = userID;
function sendVariables() {
const userVariables = {};
const ugNames = uGroups.map((id) => (
HOMES[homeID].fGroups.find((g) => g.id === id)
|| { name: 'NONE' }
).name);
Object.keys(HOMES[homeID].variables).forEach((k) => {
const namespace = k.split('.')[0];
if (['global', ...ugNames].includes(namespace)) {
userVariables[k] = HOMES[homeID].variables[k];
}
});
sendPacket(socket, P_TYPES.USER.DATA, miakode.object.encode(userVariables));
debug('HomeVariables', HOMES[homeID].variables);
debug('UserVariables', userVariables);
}
HOMES[homeID].subscribe(client.socketID, 'onData', sendVariables);
sendVariables();
socket.on('close', () => {
HOMES[client.homeID].emit('onUserEvent', userID, client.socketID, '0');
});
HOMES[client.homeID].emit('onUserEvent', userID, client.socketID, '1');
debug('=>', client);
}).catch((e) => {
debug(e);
socket.close(4001, 'WRONG_CREDENTIALS');
});
return;
}
if (msg.type === P_TYPES.USER.ACTION && client.type === 'USER') {
const isInput = (msg.data[0] === '1');
const [id, name, value] = miakode.array.decode(msg.data.substring(1));
HOMES[client.homeID].emit(
'onUserAction',
[client.clientID, (isInput ? 1 : 0), id, name, value],
);
return;
}
// COORDINATOR AUTHENTICATION
if (msg.type === P_TYPES.AUTH.COORD && !client.type) {
debug('Auth coord');
const [homeID, coordID, coordSecret] = miakode.array.decode(msg.data);
if (!homeID || !coordID || !coordSecret) {
socket.close(4002, 'WRONG_REQUEST');
return;
}
const homeDoc = db.collection('homes').doc(homeID);
if ((await homeDoc.get()).exists) {
const coordDoc = homeDoc.collection('coordinators').doc(coordID);
const fCoord = await coordDoc.get();
if (fCoord.exists && fCoord.data().secret === sha256(coordSecret)) {
coordDoc.update({ lastDate: firebase.firestore.FieldValue.serverTimestamp() });
client.homeID = homeID;
client.clientID = coordID;
client.type = 'COORD';
debug('=>', client);
if (!HOMES[client.homeID]) {
HOMES[client.homeID] = new Home(client.homeID);
} else {
HOMES[client.homeID].disconnectCoord();
}
HOMES[client.homeID].disconnectCoord = () => {
socket.close(4005, 'NEW_CONNECTION');
};
const sendHomeUsers = () => {
const users = HOMES[client.homeID].fRelations.map((r) => {
const gNs = (!r.groups) ? [] : r.groups.map((id) => {
const group = HOMES[homeID].fGroups.find((g) => g.id === id);
return (group && group.name) ? group.name : null;
}).filter((g) => g);
return `${
r.isAdmin ? '1' : '0'
}${
r.notifications ? '1' : '0'
}${
r.user
}\x01${
r.displayName
}\x01${
gNs.join('\x02')
}`;
}).join('\x00');
sendPacket(socket, P_TYPES.COORD.USERLIST, users);
};
HOMES[client.homeID].subscribe(client.socketID, 'onHomeUpdate', sendHomeUsers);
sendHomeUsers();
HOMES[client.homeID].subscribe(
client.socketID,
'onUserEvent',
(userID, socketID, event) => {
debug('onUserEvent', userID, socketID, event);
sendPacket(
socket,
P_TYPES.COORD.USER_CONNECT,
miakode.string.encode(`${event}${socketID}@${userID}`),
);
},
);
HOMES[client.homeID].subscribe(client.socketID, 'onUserAction', (action) => {
debug('onUserAction', action);
sendPacket(socket, P_TYPES.COORD.USER_ACTION, miakode.array.encode(action));
});
sendPacket(socket, P_TYPES.AUTH.OK);
return;
}
}
socket.close(4001, 'WRONG_CREDENTIALS');
return;
}
if (msg.type === P_TYPES.COORD.COMMIT && client.type === 'COORD') {
HOMES[client.homeID].variables = miakode.object.decode(msg.data);
HOMES[client.homeID].emit('onData');
debug('COMMIT DATA', HOMES[client.homeID].variables);
return;
}
if (msg.type === P_TYPES.COORD.NOTIF && client.type === 'COORD') {
const [userID, title, body, tag, image] = miakode.array.decode(msg.data);
(
await (db
.collection('users')
.doc(userID)
.collection('pushTokens')
.get()
)
).forEach(({ id: token }) => {
debug(
'SEND NOTIF',
[userID, title, body, tag, image],
'to',
token,
);
fcm.send({
token,
data: {
title,
body,
tag,
image,
timestamp: Date.now().toString(),
},
}).catch(() => {
db.collection('users')
.doc(userID)
.collection('pushTokens')
.doc(token)
.delete();
});
});
return;
}
if (msg.type === P_TYPES[client.type].PONG) {
pongTime = Date.now();
pongPayload = msg.data;
return;
}
log('Unknown packet', msg);
});
let pingPayload = null;
let pingTime = null;
const pingInterval = setInterval(() => {
debug('ping');
if (!client.type || pingPayload !== pongPayload) {
socket.close(4000, 'TIMEOUT');
return;
}
if (pongTime) debug('Ping', pongTime - pingTime, 'ms');
pingPayload = genPayload();
pingTime = Date.now();
sendPacket(socket, P_TYPES[client.type].PING, pingPayload);
}, 5000);
socket.on('close', (code, desc) => {
debug('DISCONNECT', code, desc);
clearInterval(pingInterval);
if (client.homeID && HOMES[client.homeID]) {
debug(
'Remove listeners',
client.socketID,
HOMES[client.homeID].listeners[client.socketID],
);
HOMES[client.homeID].removeListeners(client.socketID);
debug(HOMES[client.homeID].listeners);
}
});
});