-
Notifications
You must be signed in to change notification settings - Fork 2
/
johnbox.js
509 lines (494 loc) · 21.5 KB
/
johnbox.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
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
/*
Johnbox - Jackbox Games Private Server Implementation
Copyright (C) 2022 InvoxiPlayGames
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as published
by the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
var fs = require("fs");
// var https = require("https");
var http = require("http");
var wslib = require("ws");
const util = require('util')
var URL = require("url");
// the host that the custom server is accessible with
var accessibleHost = "192.168.1.10";
// the TLS certificate / key used for the server
// must have valid SNI for accessibleHost
// var tlsCertificate = "certs/192.168.1.10.pem";
// var tlsKey = "certs/192.168.1.10-key.pem";
// the room code to automatically assign to rooms
var roomCode = "JOHN";
var appConfigResponse = {
"ok": true,
"body": {
"settings": {
"serverUrl": accessibleHost
}
}
}
var roomsResponse = {
"ok": true,
"body": {
"host": accessibleHost,
"code": roomCode,
"token": "000000000000000000000000"
}
}
var appTag = "";
var appID = "";
var roomLocked = false;
var maxPlayers = 0;
var joinRoomsResponse = {
"ok": true,
"body": {
"appId": "",
"appTag": "",
"audienceEnabled": false,
"code": roomCode,
"host": accessibleHost,
"audienceHost": accessibleHost,
"locked": false,
"full": false,
"moderationEnabled": false,
"passwordRequired": false,
"twitchLocked": false,
"locale": "en",
"keepalive": false
}
}
var genericResponse = {
"ok": true,
"body": {}
}
var oldRoomResponse = {"create":true,"server":accessibleHost}
function httpHandle(req, res) {
console.log('HTTP: ' + req.url);
// Ecast room create
if (req.method == 'POST' && req.url == '/api/v2/rooms') {
var data = "";
req.on('data', (chunk) => { data+=chunk; });
req.on('end', () => {
data = JSON.parse(data);
// console.log(data);
appID = data.appId;
appTag = data.appTag;
maxPlayers = data.maxPlayers;
res.writeHead(200, { 'Content-Type': 'application/json' });
res.end(JSON.stringify(roomsResponse));
});
// Ecast app configurations
} else if (req.url.startsWith('/api/v2/app-configs/')) {
res.writeHead(200, { 'Content-Type': 'application/json' });
res.end(JSON.stringify(appConfigResponse));
// Ecast room join
} else if (req.url.startsWith('/api/v2/rooms/')) {
if (appID == "") {
// if we don't have an app ID, return 404
res.writeHead(404, { 'Content-Type': 'application/json', 'Access-Control-Allow-Origin': '*' });
res.end();
return;
}
res.writeHead(200, { 'Content-Type': 'application/json', 'Access-Control-Allow-Origin': '*' });
joinRoomsResponse.body.appTag = appTag;
joinRoomsResponse.body.appId = appID;
joinRoomsResponse.body.locked = roomLocked;
joinRoomsResponse.body.full = playerCount >= maxPlayers;
res.end(JSON.stringify(joinRoomsResponse));
// Unknown
} else {
res.writeHead(200, { 'Content-Type': 'application/json' });
res.end(JSON.stringify(genericResponse));
}
}
const server = http.createServer({
// cert: fs.readFileSync(tlsCertificate),
// key: fs.readFileSync(tlsKey)
}, httpHandle);
const wss = new wslib.WebSocketServer({ server });
wss.on('connection', function connection(ws, request) {
console.log('WS: ' + request.url);
if (appID == "") {
ws.terminate();
return;
}
if (request.url.includes("role=host")) HostWSHandler(ws);
if (request.url.includes("role=player")) GuestWSHandler(ws, request.url);
});
server.listen(8080, "0.0.0.0");
var roomObjects = {};
var roomVersions = {};
var roomRestrictions = {};
var roomAcls = {};
var roomTypes = {};
var roomLocks = {};
var roomFroms = {};
var presenceMap = {};
var playerCount = 0;
var hostPC = 2;
var guestPC = [];
function HostWSHandler(ws) {
// reset state, start new game
playerCount = 0;
presenceMap = {};
roomObjects = {};
roomVersions = {};
roomRestrictions = {};
roomTypes = {};
roomLocks = {};
roomFroms = {};
guestPC = [];
roomLocked = false;
presenceMap[1] = { socket: ws, id: "1", roles: { host: {} } };
ws.on('message', function message(data) {
var parsed = JSON.parse(data);
// console.log(util.inspect(parsed, false, null, true));
var text = false;
var number = false;
var doodle = false;
switch (parsed.opcode) {
case "text/create":
case "text/update":
case "text/set":
text = true;
case "number/create":
case "number/update":
case "number/set":
number = true;
case "doodle/create":
doodle = true;
case "object/create":
case "object/update":
case "object/set": // setting / updating objects to be passed around to players
if (doodle && !text && !number) {
parsed.params["val"] = structuredClone(parsed.params);
delete parsed.params["val"]["acl"];
}
roomObjects[parsed.params.key] = parsed.params.val;
// if (roomLocks[parsed.params.key] === true) {
// return;
// }
roomLocks[parsed.params.key] = false;
if (roomVersions[parsed.params.key] !== undefined) {
roomVersions[parsed.params.key] += 1;
} else {
roomVersions[parsed.params.key] = 0;
}
if (parsed.params.acl) {
roomAcls[parsed.params.key] = parsed.params.acl[0].split(' ');
}
roomFroms[parsed.params.key] = 1;
console.log("Host modified object", parsed.params.key);
ws.send(JSON.stringify({ "pc": ++hostPC, "re": parsed.seq, "opcode": "ok", "result": {} }));
let opcode = "object";
if (text) {
opcode = "text";
} else if (number) {
opcode = "number";
roomRestrictions[parsed.params.key] = {};
if (parsed.params.min)
roomRestrictions[parsed.params.key]["min"] = parsed.params.min;
if (parsed.params.max)
roomRestrictions[parsed.params.key]["max"] = parsed.params.max;
if (parsed.params.type)
roomRestrictions[parsed.params.key]["type"] = parsed.params.type;
if (parsed.params.increment)
roomRestrictions[parsed.params.key]["increment"] = parsed.params.increment;
} else if (doodle) {
opcode = "doodle"
roomObjects[parsed.params.key]["lines"] = [];
}
roomTypes[parsed.params.key] = opcode;
for(var i = 2; i <= playerCount + 1; i++) {
// only deliver to clients if the acl allows it
// console.log("host", roomAcls[parsed.params.key]?.[1]);
let shouldnt_send = roomAcls[parsed.params.key] && (roomAcls[parsed.params.key][1] != `id:${i}` && roomAcls[parsed.params.key][1] != 'role:player' && roomAcls[parsed.params.key][1] != '*');
// console.log(shouldnt_send);
if (shouldnt_send) continue;
let result = parsed.params;
delete result["min"];
delete result["max"];
delete result["type"];
delete result["increment"];
delete result["accept"];
delete result["reject"];
if (number && !text) {
result["restrictions"] = roomRestrictions[parsed.params.key];
}
if (!doodle || text || number) {
result["version"] = roomVersions[parsed.params.key];
} else {
result["index"] = roomVersions[parsed.params.key];
}
result["from"] = 1;
result = { "pc": ++guestPC[i - 2], "opcode": opcode, "result": result };
// console.log(util.inspect(result, false, null, true));
presenceMap[i].socket.send(JSON.stringify(result));
}
break;
case "lock":
console.log("Host locked object", parsed.params.key);
// console.log(util.inspect(parsed, false, null, true));
roomLocks[parsed.params.key] = true;
let reply = { "pc": ++hostPC, "re": parsed.seq, "opcode": "ok", "result": {} }
// console.log(util.inspect(message, false, null, true));
ws.send(JSON.stringify(reply));
break;
case "drop": // delete the room object
delete roomObjects[parsed.params.key];
delete roomVersions[parsed.params.key];
delete roomRestrictions[parsed.params.key];
delete roomTypes[parsed.params.key];
delete roomLocks[parsed.params.key];
delete roomFroms[parsed.params.key];
delete roomAcls[parsed.params.key];
console.log("Host dropped object", parsed.params.key);
ws.send(JSON.stringify({ "pc": ++hostPC, "re": parsed.seq, "opcode": "ok", "result": {} }));
break;
case "room/get-audience": // we don't support audiences, but just return 0
ws.send(JSON.stringify({ "pc": ++hostPC, "re": parsed.seq, "opcode": "room/get-audience", "result": {"connections": 0} }));
break;
case "room/lock":
roomLocked = true;
console.log("Host locked room");
ws.send(JSON.stringify({ "pc": ++hostPC, "re": parsed.seq, "opcode": "ok", "result": {} }));
break;
case "room/exit": // kick all players
console.log("Host closed room");
appID = ""; // set app ID to nothing so rooms request fails
for(var i = 2; i <= playerCount + 1; i++) {
presenceMap[i].socket.terminate(); // disconnect all players
presenceMap[i] = {};
}
ws.send(JSON.stringify({ "pc": ++hostPC, "re": parsed.seq, "opcode": "ok", "result": {} }));
ws.terminate();
break;
case "text/filter": // Passes text to ecast to check for banned content, just looks for a default OK in response, TODO?
case "game/start": // Probably telemetry, expects a default OK in response, TODO?
case "room/start-audience": // start audience?, TODO
default:
// just ignore and return default OK
console.log("Unimplemented host opcode", parsed.opcode, "with data", util.inspect(parsed, false, null, true));
let message = { "pc": ++hostPC, "re": parsed.seq, "opcode": "ok", "result": {} };
// console.log(message)
ws.send(JSON.stringify(message));
break;
}
});
ws.on('close', function close() {
appID = ""; // set app ID to nothing so rooms request fails
for(var i = 2; i <= playerCount + 1; i++) {
presenceMap[i].socket.terminate(); // disconnect all players
presenceMap[i] = {};
}
});
// send welcome message
console.log("Sending host welcome.");
ws.send(JSON.stringify({
"pc": ++hostPC,
"opcode": "client/welcome",
"result": {
"id": 1,
"secret": "000000000000000000000000",
"reconnect": false,
"deviceId": "0000000000.0000000000000000000000",
"entities": {},
"here": {},
"profile": null
}
}));
}
function GuestWSHandler(ws, url) {
if (appID == "" || roomLocked || playerCount >= maxPlayers) {
console.log("Client tried to connect while no room, locked or full.");
ws.terminate();
return;
}
guestPC.push(2);
var playerID = playerCount;
var username = URL.parse(url, true).query["name"] ? URL.parse(url, true).query["name"] : `JOHN ${playerID + 1}`;
playerCount++;
presenceMap[1 + playerCount] = { socket: ws, id: `${1+playerCount}`, roles: { player: { name: username } } };
ws.on('message', function message(data) {
var parsed = JSON.parse(data);
var text = false;
var number = false;
var doodle = false;
switch (parsed.opcode) {
case "text/update":
case "text/set":
text = true;
case "number/update":
case "number/set":
number = true;
case "doodle/stroke":
doodle = true;
case "object/update":
case "object/set": // setting / updating objects to be passed around to players
// TODO: implement permissions checks
if (roomVersions[parsed.params.key] >= 0) { // only update object if it exists
if (roomLocks[parsed.params.key] === true) {
return;
}
roomLocks[parsed.params.key] = false;
// verify that the ACL allows the object to be edited
// if (roomAcls[parsed.params.key] && (roomAcls[parsed.params.key][1] != `id:${2 + playerID}` && roomAcls[parsed.params.key][1] != '*')) return;
if (!doodle || text || number) {
roomObjects[parsed.params.key] = parsed.params.val;
} else {
roomObjects[parsed.params.key]["lines"].push(...parsed.params.points);
}
console.log("Client", 2 + playerID, "modified object", parsed.params.key);
roomVersions[parsed.params.key] += 1;
roomFroms[parsed.params.key] = 2 + playerID;
let result = parsed.params;
if (!doodle || text || number) {
result["version"] = roomVersions[parsed.params.key];
} else {
result["index"] = roomVersions[parsed.params.key];
result["val"] = structuredClone(result);
delete result["val"]["key"];
}
result["from"] = 2 + playerID;
let opcode = "object";
if (text) {
opcode = "text";
} else if (number) {
opcode = "number";
} else if (doodle) {
opcode = "doodle/line";
}
let message = { "pc": ++hostPC, "opcode": opcode, "result": result };
presenceMap[1].socket.send(JSON.stringify(message));
}
ws.send(JSON.stringify({ "pc": ++guestPC[playerID], "re": parsed.seq, "opcode": "ok", "result": {} }));
break;
case "text/get":
text = true
case "number/get":
number = true
case "doodle/get":
doodle = true
case "object/get":
if (roomVersions[parsed.params.key] >= 0) { // only get object if exists
let result = parsed.params;
result["val"] = roomObjects[parsed.params.key];
if (!doodle || text || number) {
result["version"] = roomVersions[parsed.params.key];
} else {
result["index"] = roomVersions[parsed.params.key];
delete result["val"]["key"];
}
result["from"] = roomFroms[parsed.params.key];
let opcode = "object";
if (text) {
opcode = "text";
} else if (number) {
opcode = "number";
} else if (doodle) {
opcode = "doodle"
}
delete result["min"];
delete result["max"];
delete result["type"];
delete result["increment"];
delete result["accept"];
delete result["reject"];
delete result["acl"];
if (number && !text) {
result["restrictions"] = roomRestrictions[parsed.params.key];
}
let message = { "pc": ++guestPC[playerID], "re": parsed.seq, "opcode": opcode, "result": result };
console.log(util.inspect(message, false, null, true));
ws.send(JSON.stringify(message));
}
break;
case "lock":
console.log("Client", 2 + playerID, "locked object", parsed.params.key);
// console.log(util.inspect(parsed, false, null, true));
roomLocks[parsed.params.key] = true;
let message = { "pc": ++guestPC[playerID], "re": parsed.seq, "opcode": "ok", "result": {} }
// console.log(util.inspect(message, false, null, true));
ws.send(JSON.stringify(message));
message = { "pc": ++hostPC, "opcode": "lock", "result": { "key": parsed.params.key, "from": 2 + playerID } };
// console.log(util.inspect(message, false, null, true));
presenceMap[1].socket.send(JSON.stringify(message));
break;
case "client/send":
console.log("Client", parsed.params.from, "sent data to", parsed.params.to, ":", parsed.params.body);
// send it to host, TODO: check how this is supposed to behave
presenceMap[1].socket.send(JSON.stringify({ "pc": ++hostPC, "opcode": "client/send", "result": parsed.params }));
ws.send(JSON.stringify({ "pc": ++guestPC[playerID], "re": parsed.seq, "opcode": "ok", "result": {} }));
break;
default:
// just ignore and return default OK
console.log("Unimplemented client opcode", parsed.opcode, "with data", parsed);
ws.send(JSON.stringify({ "pc": ++guestPC[playerID], "re": parsed.seq, "opcode": "ok", "result": {} }));
break;
}
});
// send welcome message
console.log("Sending client welcome.");
var clientWelcome = {
"pc": ++guestPC[playerID],
"opcode": "client/welcome",
"result": {
"id": 1 + playerCount,
"name": username,
"secret": "00000000-0000-0000-0000-000000000000",
"reconnect": false,
"deviceId": "0000000000.0000000000000000000000",
"entities": {},
"here": {},
"profile":{
"id": 1 + playerCount,
"roles": {
"player": { "name": username }
}
}
}
};
for(var i = 1; i <= playerCount; i++) {
clientWelcome.result.here[`${i}`] = {};
Object.assign(clientWelcome.result.here[`${i}`], presenceMap[i]);
delete clientWelcome.result.here[`${i}`].socket;
}
var objectKeys = Object.keys(roomObjects);
for(var i = 0; i < objectKeys.length; i++) {
// only deliver to clients if the acl allows it
// console.log("guest", roomAcls[objectKeys[i]]?.[1])
let role = ((1 + playerCount) == 1) ? 'role:host' : 'role:player';
let shouldnt_send = roomAcls[objectKeys[i]] && (roomAcls[objectKeys[i]][1] != `id:${1 + playerCount}` && roomAcls[objectKeys[i]][1] != role && roomAcls[objectKeys[i]][1] != '*');
// console.log(shouldnt_send);
if (shouldnt_send) continue;
clientWelcome.result.entities[objectKeys[i]] = [ roomTypes[objectKeys[i]], { key: objectKeys[i], val: roomObjects[objectKeys[i]], version: roomVersions[objectKeys[i]], from: 1 }, { "locked": roomLocks[objectKeys[i]] } ];
}
// console.log(util.inspect(clientWelcome, false, null, true));
ws.send(JSON.stringify(clientWelcome));
// send client connected message
var clientConnected = {
"pc": ++hostPC,
"opcode": "client/connected",
"result": {
"id": 1 + playerCount,
"userId": `00000000-0000-0000-0000-00000000000${playerCount}`,
"name": username,
"role": "player",
"reconnect": false,
"profile": {
"id": 1 + playerCount,
"roles": {
"player": { "name": username }
}
}
}
};
presenceMap[1].socket.send(JSON.stringify(clientConnected));
}