-
Notifications
You must be signed in to change notification settings - Fork 3
/
server.js
2024 lines (1738 loc) · 69.1 KB
/
server.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
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// Node.js OWOP Server created by dimden and mathias377
//
// Discord: https://discord.gg/k4u7ddk
// Website: https://dimden.dev/
// Mathias377 Discord: https://discord.gg/PpZq7HB
const WebSocket = require('ws');
const fetch = require("node-fetch");
const EventEmitter = require("events");
const IpsManager = require("./IpsManager.js");
const Manager = require("./manager.js");
const os = require('os');
const moment = require('moment');
const proxy_check = require('proxycheck-node.js');
const http = require("http");
const express = require("express");
const fs = require("fs");
const sqlite3 = require("sqlite3").verbose();
const serverVersion = require("./package.json").version;
function btoa(btoa) {
return Buffer.from(btoa).toString("base64");
}
function atob(atob) {
return Buffer.from(atob, 'base64').toString();
}
class Bucket {
constructor(rate, time, infinite = true) {
this.lastCheck = Date.now();
this.allowance = 0;
this.rate = rate;
this.time = time;
this.infinite = infinite;
}
update() {
this.allowance += (Date.now() - this.lastCheck) / 1000 * (this.rate / this.time);
this.lastCheck = Date.now();
if (this.allowance > this.rate) {
this.allowance = this.rate;
}
}
canSpend(count) {
if (this.infinite) {
return true;
}
this.update();
if (this.allowance < count) {
return false;
}
this.allowance -= count;
return true;
}
}
class Server extends EventEmitter {
/*
OPTIONS:
[class]server - http/https server. (optional)
[number]port - port of WS server. (optional, default - 3000)
[array]defaultPQuota - default PQuota. Array template - [rate, time]. (optional, default - [64, 4])
[string]adminlogin - admin password. (required)
[string]modlogin - moderator password. (required)
[string]captchaKey - grecaptcha private key. (required if "captcha" is true, otherwise optional)
[string]captchapass - captcha passworld. (required if "captcha" is true, otherwise optional)
[number]captchaSecurity - captcha security level. 0 = no captcha, 1 = captcha only once, 2 = captcha everytime (optional, default - 0)
[number]updateInterval - update interval in ms. (optional, default - 1000/60)
[number]saveInterval - database save interval in ms. (optional, default - 5000)
[string]database - database file location. (optional, default - database.db )
[number]chunksUpdateRate - worlds/chunks saving rate. (optional, default - Math.floor(1000 / 30))
*/
/*
EVENTS:
name - description [arguments].
user did:
join - emits when user connected and got verificated. [user]
open - emits when user connected to server. [user]
close - emits when user got disconnected. [user]
rawMessage - emits when user sends message to server. [user, message]
message - emits when user sends string. [user, message]
setPixel - set pixel. [user, x, y, [r, g, b]]
protectChunk - chunk (-un)protected. [user, x, y, newState]
requestChunk - user requested chunk from server [user, x, y]
paste - user has pasted something. [user, x, y, newData]
setChunk - user erased something. [user, x, y, [r, g, b]]
playerUpdate - emits when user updates self. [user]
rankVerification - emits when user sends rankVerification. [user, rankToVerifcate]
server:
savedWorlds - worlds saved. []
setRank - server has set rank for the user. [user]
sentData - server sent message to user. [user]
setPQuota - server set PQuota for user. [user]
teleport - server teleported user. [user]
setId - server set id for user. [user]
maxCount - server sends to mod or admin max count of clients on world. [user]
*/
constructor (options = {}) {
super();
const that = this;
this.utils = {
getKeyByValue(object, value) {
return Object.keys(object).find(key => object[key] === value);
},
tools: {
0: [1, "cursor"],
1: [0, "move"],
2: [0, "pippete"],
3: [2, "eraser"],
4: [0, "zoom"],
5: [1, "bucket"],
6: [2, "paste"],
7: [0, "export"],
8: [1, "line"],
9: [2, "protect"],
10: [2, "copy"]
},
rgbToHex(r, g, b) {
return "#" + ((1 << 24) + (r << 16) + (g << 8) + b).toString(16).slice(1);
},
hexToRgb(hex) {
// Expand shorthand form (e.g. "03F") to full form (e.g. "0033FF")
let shorthandRegex = /^#?([a-f\d])([a-f\d])([a-f\d])$/i;
hex = hex.replace(shorthandRegex, function(m, r, g, b) {
return r + r + g + g + b + b;
});
let result = /^#?([a-f\d]{2})([a-f\d]{2})([a-f\d]{2})$/i.exec(hex);
return result ? {
r: parseInt(result[1], 16),
g: parseInt(result[2], 16),
b: parseInt(result[3], 16)
} : null;
},
random(min, max) {
return Math.floor(Math.random() * (max - min + 1)) + min;
},
randomString(length) {
let result = '';
let characters = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';
for (let i = 0; i < length; i++) {
result += characters.charAt(that.utils.random(0, characters.length));
}
return result;
},
sendToAll(message, rank = 0, world) {
if(!message) return;
if(world) {
if(that.worlds[world]) for(let id in that.worlds[world].clients) if(that.worlds[world].clients[id].rank >= rank) that.worlds[world].clients[id].send(message);
} else for(let name in that.worlds) for(let id in that.worlds[name].clients) if(that.worlds[name].clients[id].rank >= rank) that.worlds[name].clients[id].send(message);
},
compress(data, tileX, tileY, protection) {
// copypasted, sorry ;-;
var result = new Uint8Array(16 * 16 * 3 + 10 + 4);
var s = 16 * 16 * 3;
var compressedPos = [];
var compBytes = 3;
var lastclr = data[2] << 16 | data[1] << 8 | data[0];
var t = 1;
for(var i = 3; i < data.length; i += 3) {
var clr = data[i + 2] << 16 | data[i + 1] << 8 | data[i];
compBytes += 3;
if(clr == lastclr) { ++t } else {
if(t >= 3) {
compBytes -= t * 3 + 3;
compressedPos.push({
pos: compBytes,
length: t
});
compBytes += 5 + 3;
}
lastclr = clr;
t = 1;
}
}
if(t >= 3) {
compBytes -= t * 3;
compressedPos.push({
pos: compBytes,
length: t
});
compBytes += 5;
}
var totalcareas = compressedPos.length;
var msg = new DataView(result.buffer);
msg.setUint8(0, that.protocol.server.chunkLoad);
msg.setInt32(1, tileX, true);
msg.setInt32(5, tileY, true);
msg.setUint8(9, protection);
var curr = 10; // as unsigned8
msg.setUint16(curr, s, true);
curr += 2; // size of unsigned 16 bit ints
msg.setUint16(curr, totalcareas, true);
curr += 2; // uint16 size
for(var i = 0; i < compressedPos.length; i++) {
var point = compressedPos[i];
msg.setUint16(curr, point.pos, true)
curr += 2; // uint16 size
}
var di = 0;
var ci = 0;
for(var i = 0; i < compressedPos.length; i++) {
var point = compressedPos[i];
while(ci < point.pos) {
msg.setUint8(curr + (ci++), data[di++]);
}
msg.setUint16(curr + ci, point.length, true);
ci += 2; // uint16 size
msg.setUint8(curr + (ci++), data[di++]);
msg.setUint8(curr + (ci++), data[di++]);
msg.setUint8(curr + (ci++), data[di++]);
di += point.length * 3 - 3;
}
while(di < s) {
msg.setUint8(curr + (ci++), data[di++]);
}
var size = compBytes + totalcareas * 2 + 10 + 2 + 2;
return result.slice(0, size);
},
world: class {
constructor(name) {
this.name = name;
this.latestId = 1;
this.updates = [];
this.clients = {};
this.pquota = that.defaultPQuota.toString();
this.doubleModQuota = true;
this.modlogin = that.modlogin;
this.motd = "";
this.pass = "";
this.bgcolor = "FFF";
this.restricted = false;
}
loadProps() {
this.restricted = that.manager.getProp(this.name, "restricted", "false") === "true";
this.pass = that.manager.getProp(this.name, "pass", "");
this.modlogin = that.manager.getProp(this.name, "modlogin", that.modlogin);
this.pquota = that.manager.getProp(this.name, "pquota", that.defaultPQuota.toString());
this.motd = that.manager.getProp(this.name, "motd", "");
this.bgcolor = that.manager.getProp(this.name, "bgcolor", "FFF");
this.doubleModQuota = that.manager.getProp(this.name, "doublemodquota", "true") !== "false";
}
},
UpdateClock: class { // this thing is kina diffrent than in normal owop :P
constructor() {
this.updates = {};
this.interval = setInterval(this.update.bind(this), this.updateInterval);
this.playerSizeInfo = 4 + // player id
4 + // x
4 + // y
1 + // r
1 + // g
1 + // b
1; // tool
this.pixelSizeInfo = 4 + // player id
4 + // pixel x
4 + // y
1 + // r
1 + // g
1; // b
this.leftSizeInfo = 4; // player id
}
update() {
for(var worldName in this.updates) {
let update = this.updates[worldName];
let updates = [];
while(update.playerUpdates.length || update.pixelUpdates.length || update.disconnectionsOfPlayers.length) {
let playerUpdates = update.playerUpdates.splice(0, 255); // Math.pow(2, 8)-1
let pixelUpdates = update.pixelUpdates.splice(0, 65535); // Math.pow(2, 16)-1
let disconnectionsOfPlayers = update.disconnectionsOfPlayers.splice(0, 255); // Math.pow(2, 8)-1
let updateSize = (1 + // that.protocol.server.worldUpdate
1 + // players update size
playerUpdates.length * this.playerSizeInfo + // player updates
2 + // pixels update size
pixelUpdates.length * this.pixelSizeInfo + // pixel updates
1 + // disconnections update size
this.leftSizeInfo * disconnectionsOfPlayers.length); // disconnections of players
let updateArray = new Uint8Array(updateSize);
let dv = new DataView(updateArray.buffer);
dv.setUint8(0, that.protocol.server.worldUpdate); // that.protocol.server.worldUpdate
dv.setUint8(1, playerUpdates.length); // players update size
let offset = 2;
for(let updateId = 0; updateId < playerUpdates.length; updateId++) { // player updates
var user = playerUpdates[updateId];
dv.setUint32(offset, user.id, true); // player id
dv.setInt32(offset + 4, user.x, true); // x
dv.setInt32(offset + 4 + 4, user.y, true); // y
dv.setUint8(offset + 4 + 4 + 4, user.r); // r
dv.setUint8(offset + 4 + 4 + 4 + 1, user.g); // g
dv.setUint8(offset + 4 + 4 + 4 + 1 + 1, user.b); // b
dv.setUint8(offset + 4 + 4 + 4 + 1 + 1 + 1, user.tool); // tool
offset += this.playerSizeInfo;
}
dv.setUint16(offset, pixelUpdates.length, true); // pixels update size
offset += 2;
for(let updateId = 0; updateId < pixelUpdates.length; updateId++) {
let pixel = pixelUpdates[updateId];
dv.setUint32(offset, pixel.id, true); // player id
dv.setInt32(offset + 4, pixel.x, true); // pixel x
dv.setInt32(offset + 4 + 4, pixel.y, true); // y
dv.setUint8(offset + 4 + 4 + 4, pixel.r); // r
dv.setUint8(offset + 4 + 4 + 4 + 1, pixel.g); // g
dv.setUint8(offset + 4 + 4 + 4 + 1 + 1, pixel.b); // b
offset += this.pixelSizeInfo;
}
dv.setUint8(offset, disconnectionsOfPlayers.length, true); // disconnections of players update size
offset += 1
for(let updateId = 0; updateId < disconnectionsOfPlayers.length; updateId++) { // disconnections of players
let leftId = disconnectionsOfPlayers[updateId];
dv.setUint32(offset, leftId, true);
offset += this.leftSizeInfo;
}
updates.push(updateArray);
}
let world = that.worlds[worldName];
if(!world) continue; // it can happen if everyone will leave and there still will be update
for(let i = 0; i < updates.length; i++) {
let updateArray = updates[i];
for(let id in world.clients) {
world.clients[id].send(updateArray); //sends update to clients
}
}
delete this.updates[worldName];
}
}
getUpdObj(world) {
world = world.toLowerCase();
if (!this.updates[world]) {
this.updates[world] = {
playerUpdates: [],
pixelUpdates: [],
disconnectionsOfPlayers: []
};
}
return this.updates[world]
}
doUpdatePlayer(world, client) {
let upd = this.getUpdObj(world).playerUpdates;
upd.push(client)
}
doUpdatePixel(world, pixelData) {
let upd = this.getUpdObj(world).pixelUpdates;
upd.push(pixelData)
}
doUpdatePlayerLeave(world, id) {
let upd = this.getUpdObj(world).disconnectionsOfPlayers;
upd.push(id)
}
},
captcha: class {
constructor(user) {
this.user = user;
if(!this.user) return;
if(!this.user.ip) return;
this.state = "waiting";
this.whitelisted = false;
}
show() {
if(this.whitelisted) return this.sendState("ok");
let security = that.captchaSecurity;
if (security < 0 || security > 3) security = 0;
switch (security) {
case 0:
this.sendState("ok");
break;
case 1:
if (Date.now() - that.captchaVerifiedIps[this.user.ip] < 1000 * 60 * 60 * 24) this.sendState("ok");
else this.sendState("waiting");
break;
case 2:
this.sendState("waiting");
break;
}
}
sendState(state) {
this.state = state;
this.user.send(new Uint8Array([that.protocol.server.captcha, that.captchaStates[state]]));
}
async onToken(message) {
let key = message;
let security = that.captchaSecurity;
if (security < 0 || security > 3) security = 0;
this.sendState("verifying");
switch (security) {
case 0:
this.sendState("ok");
break
case 1: { //save ips (shows only once per 24 hours)
let success = await this.verifyToken(key);
if (success == true) {
this.sendState("ok");
that.captchaVerifiedIps[this.user.ip] = Date.now();
} else {
this.sendState("invaild");
this.user.ws.close();
}
break;
}
case 2: { //don't save ip (always show)
let success = await this.verifyToken(key);
if (success === true) {
this.sendState("ok")
} else {
this.sendState("invaild");
this.user.ws.close();
}
break;
}
}
}
async verifyToken(key) {
if (key === "LETMEINPLZ" + that.captchaBypass || key === "LETMEINPLZ" + that.adminlogin) {
return true;
}
try {
let response = await fetch(`https://www.google.com/recaptcha/api/siteverify?secret=${that.captchaKey}&response=${key}`); // fetch is newer
response = await response.json();
return response.success;
} catch(e) {
console.error(e);
return false;
}
/*return new Promise(function(resolve, reject) {
request(`https://www.google.com/recaptcha/api/siteverify?secret=${that.captchaKey}&response=${key}`, function(error, response, body) {
if (error) {
resolve(false)
return;
};
body = body.replace(/\r/g, '');
let jsonresponse = JSON.parse(body);
resolve(jsonresponse.success);
}.bind(resolve))
})*/
}
},
getIp(req) {
return (req.headers['x-forwarded-for'] || req.connection.remoteAddress).split(",")[0].replace('::ffff:', '');
},
isPositive(x) {
return Math.sign(x) === 1 || x ===0;
},
outsideWorldBorder(x, y, raw = true) {
if(that.worldBorder === -1) return false;
if(!raw) {
x = Math.floor(x/16);
y = Math.floor(y/16);
}
if(that.utils.isPositive(x)) x++;
if(that.utils.isPositive(y)) y++;
return Math.abs(x) > that.worldBorder || Math.abs(y) > that.worldBorder;
},
outsideTpLimit(x, y) {
if(that.tpLimit === -1) return false;
if(that.utils.isPositive(x)) x++;
if(that.utils.isPositive(y)) y++;
return Math.abs(x) > that.tpLimit || Math.abs(y) > that.tpLimit;
},
player: class {
constructor(ws, req) {
this.muted = false;
this.id = null;
this.ip = that.utils.getIp(req);
this.rank = 0;
this.x = 0; this.y = 0;
this.pquota = new Bucket(0, 0);
this.cquota = new Bucket(0, 0);
this.r = 0; this.g = 0; this.b = 0;
this.stealth = false; // remove (A) or (M)
this.nick = "";
this.world = null;
this.ws = ws;
this.req = req;
this.captcha = new that.utils.captcha(this);
}
get realX() {
return this.x/16;
}
get realY() {
return this.y/16;
}
get before() {
let before = "";
let isAdmin = this.stealth ? false : this.rank === 3;
let isMod = this.stealth ? false : this.rank === 2;
let isUser = this.rank <= 1 || this.stealth;
let hasNick = !!this.nick.length;
if(isAdmin) before += "(A) ";
else if(isMod) before += "(M) ";
else if(isUser) {
if(hasNick) before += `[${this.id}] `;
else before += this.id;
}
if(hasNick) before += this.nick;
before = before.trim();
return before;
}
_setRank(rank) {
this.send(new Uint8Array([that.protocol.server.setRank, rank]))
}
setRank(rank) {
this.rank = rank;
this.cquota = rank === 0 || rank === 1 ? new Bucket(4, 6) :
rank === 2 ? new Bucket(10, 3) :
rank === 3 ? new Bucket(1000, 0) : new Bucket(0, 1000);
this._setRank(rank);
let pquota = this.world ? this.world.pquota.split(",") || that.defaultPQuota : that.defaultPQuota
let pq = this.rank === 1 ? pquota :
this.rank === 2 ? [pquota[0], this.world.doubleModPQuota ? Math.floor(pquota[1]/2) : pquota[1]] :
this.rank === 3 ? [1000, 0] : [0, 1000];
this.setPQuota(pq[0], pq[1]);
if(rank === 2) this.send("Server: You are now a moderator. Do /help for a list of commands.");
if(rank === 3) this.send("Server: You are now an administrator. Do /help for a list of commands.");
if(rank >= 2) this.setMaxCount(that.maxClientsOnWorld);
that.emit("setRank", this);
}
setMaxCount(maxCount) {
let array = new Uint8Array(3)
let dv = new DataView(array.buffer);
dv.setUint8(0, that.protocol.server.maxCount);
dv.setUint16(1, maxCount, true);
this.send(array);
that.emit("maxCount", this);
}
setPQuota(rate, per) {
this.pquota = new Bucket(rate, per);
let array = new Uint8Array(5)
let dv = new DataView(array.buffer);
dv.setUint8(0, that.protocol.server.setPQuota);
dv.setUint16(1, rate, true);
dv.setUint16(3, per, true);
this.send(dv);
that.emit("setPQuota", this);
}
setId(id) {
this.id = id;
let array = new Uint8Array(5);
let dv = new DataView(array.buffer);
dv.setUint8(0, that.protocol.server.setId);
dv.setUint32(1, id, true);
this.send(array);
that.emit("setId", this);
}
send(data) {
try {
if(this.ws.readyState === 1) this.ws.send(data);
} catch(e) {
console.error(e);
};
that.emit("sentData", this, data);
}
teleport(x, y) {
this.x = x
this.y = y
let array = new Uint8Array(9)
let dv = new DataView(array.buffer);
dv.setUint8(0, that.protocol.server.teleport);
dv.setUint32(1, x, true);
dv.setUint32(5, y, true);
this.send(array);
if(this.world) that.updateClock.doUpdatePlayer(this.world.name, {
id: this.id,
x: this.x,
y: this.y,
r: this.r,
g: this.g,
b: this.b,
tool: this.tool
})
that.emit("teleport", this);
}
},
Bucket,
distance: function(x,y,x2,y2) {
return Math.hypot(x2-x, y2-y)
},
getAllPlayers: function() {
let users = [];
for(let worldName in that.worlds) for(let userId in that.worlds[worldName].clients) users.push(that.worlds[worldName].clients[userId]);
return users;
},
getAllPlayersWithIp: function(ip) {
let users = [];
for(let worldName in that.worlds) for(let userId in that.worlds[worldName].clients) if(that.worlds[worldName].clients[userId].ip === ip) users.push(that.worlds[worldName].clients[userId]);
return users;
}
}
this.started = Date.now();
this.totalConnections = 0;
// api thing this looks fucking ugly
this.httpServer = http.createServer();
this.app = express();
let filesDirectory = "/dist/";
function checkHttps(req, res, next) { // thx https://support.glitch.com/t/solved-auto-redirect-http-https/2392
//return next();
if(req.headers.host.includes("local")) return next();
if(req.get('X-Forwarded-Proto').includes("https")){
return next()
} else {
res.redirect('https://' + req.hostname + req.url);
}
}
this.app.all('*', checkHttps);
this.funnySelfBanMessages = [
"DayDun? Is that you? (I'd make this message appear for swedish IPs only but I'm too lazy)",
"OWOT is actually pretty good!",
"You almost did it! Keep banning yourself! Only 239 messages to go.",
"Try playing Barony!",
"https://youtu.be/wGlBwW7f5HA",
"I don't think this was a good idea, dimden. I'll keep it so you can read these messages though.",
"Wow you did it, you banned yourself. Congratulations, are you happy now?",
"Did you know that the accounts are done? I have to finish the new OWOP client now.",
"You probably feel smart by reading these messages, don't you? Well, you're banned now. :^)",
// real^
"ur mom gay //dimden",
"you are really weird bro are you ok that you are banning yourself????? That's very illegal!",
"MATHIAS377 IS BEST!!!!!",
"dimden is admin since " + new Date(1586785345192),
"dimden became mod ~" + new Date(1571318652317),
"Infra drunk since -1923 0 0",
"DayDun left from OWOP ~" + new Date(1553180105000),
"dimden's retard list: 1. ludwig\n2. autoplayer\n3. Yui\ 4-Infinity: everyone else.",
btoa("No you aren't clever if you read it.")
];
this.api = express();
this.app.use("/api", this.api);
this.api.get("/disconnectme", function(req, res) {
let ip = that.utils.getIp(req);
let playersToKick = that.utils.getAllPlayersWithIp(ip);
for(let i = 0; i < playersToKick.length; i++) playersToKick[i].ws.close();
res.json({
hadEffect: !!playersToKick.length
});
});
this.api.get("/stats", function(req, res) {
res.json(that.pixelsPlaced);
})
this.api.get("/banme", function(req, res) {
res.send("Nope, you're gonna need something else to get yourself banned.");
});
this.api.put("/banme", async function(req, res) {
let ip = that.utils.getIp(req);
let ipInfo = await that.ipsManager.getIp(ip) || {};
if(ipInfo.banned > Date.now() || ipInfo.banned == -1) return res.send("Haha you thought I was going to keep giving you cool messages even when you're already banned? Think again, they are given to the most patient of self-banners.");
await that.ipsManager.setSelfBanned(ip, Date.now() + 1000 * 60 * that.utils.random(1, 6), ipInfo.selfBans++ || 1);
let playersToKick = that.utils.getAllPlayersWithIp(ip);
for(let i = 0; i < playersToKick.length; i++) playersToKick[i].ws.close();
res.send(that.funnySelfBanMessages[that.utils.random(0, that.funnySelfBanMessages.length-1)]);
})
this.api.get("/", async function(req, res) {
let ip = that.utils.getIp(req);
let ipInfo = await that.ipsManager.getIp(ip);
res.json({
banned: ipInfo ? ipInfo.banned : 0,
captchaEnabled: !!that.captchaSecurity,
maxConnectionsPerIp: that.maxClientsPerIp,
motd: that.motd,
numSelfBans: ipInfo ? ipInfo.selfBans : 0,
totalConnections: that.totalConnections,
uptime: Date.now() - that.started,
users: that.utils.getAllPlayers().length,
yourConns: that.utils.getAllPlayersWithIp(ip).length,
yourIp: ip
});
});
this.api.get("*", function(req, res) {
res.send(`"Unknown request"`);
});
this.app.get("*", function(req, res) {
let file = req.path;
if(file[0] === "/") file = file.slice(1);
if(file.endsWith("/")) file = file.slice(-1);
if(!file) file = "index.html";
fs.access(__dirname + filesDirectory + file, fs.constants.F_OK, function(err) {
if(err) file = "index.html"; // file not exists
res.sendFile(__dirname + filesDirectory + file);
});
});
this.wss = new WebSocket.Server({
server: this.httpServer
});
this.httpServer.on('request', this.app);
this.httpServer.listen(options.port ? options.port : process.env.PORT || 3000);
// server
this.worldBorder = Math.pow(2, 24) / 16
this.tpLimit = 1000000;
this.updateInterval = options.updateInterval || Math.floor(1000 / 30);
this.TERMINATION = false;
// database
this.databasePath = options.databasePath || "./database.db";
console.log(sqlite3.OPEN_READWRITE)
this.db = new sqlite3.Database(this.databasePath, sqlite3.OPEN_READWRITE | sqlite3.OPEN_CREATE);
this.db.serialize(() => {
this.db.run(`
CREATE table if not exists ips (
ip text primary key,
banned integer default 0,
whitelist boolean default false,
restrictImmune boolean default false,
muted boolean default false,
selfBans integer default 0
)
`)
});
this.ipsManager = new IpsManager(this.db);
this.chunksUpdateRate = options.chunksUpdateRate || 1000 * 60 * 5
this.chunkdataPath = options.chunkdataPath || "./chunkdata/";
this.manager = new Manager(this.chunksUpdateRate, this.chunkdataPath);
this.manager.on("savedWorlds", () => {that.emit("savedWorlds")});
// default config
this.adminlogin = options.adminlogin;
this.modlogin = options.modlogin;
this.defaultPQuota = options.defaultPQuota || [64, 4];
this.maxClientsPerIp = options.maxClientsPerIp || 3;
this.maxClientsOnWorld = options.maxClientsOnWorld || 50;
this.maxClientsOnServer = options.maxClientsOnServer || 500;
this.appealLink = options.appealLink || that.utils.random(0,1) === 1 ? "https://discord.gg/k4u7ddk" : "https://discord.gg/PpZq7HB"; //LOL
this.motd = options.motd || options.messageOfTheDay || "hi";
// captcha
this.captchaKey = options.captchaKey;
this.captchaPublicKey = options.captchaPublicKey; //it's not used anywhere
this.captchaBypass = options.captchaBypass ? that.captchaBypass : this.utils.randomString(60);
this.captchaSecurity = options.captchaSecurity || 0;
this.captchaEnabled = this.captchaKey && this.captchaSecurity > 0 && this.captchaSecurity < 3 && this.captchaBypass; //it's not used anywhere again
this.captchaVerifiedIps = {};
this.captchaStates = {
waiting: 0,
verifying: 1,
verified: 2,
ok: 3,
invaild: 4
}
this.originCheck = options.originCheck ? options.originCheck.map(origin => origin.endsWith("/") ? origin.substr(0, origin.length-1) : origin) : [];
// anti proxy
this.antiProxyApiKey = options.antiProxyApiKey;
this.antiProxyEnabled = options.antiProxyEnabled && !!this.antiProxyApiKey;
this.antiProxy = this.antiProxyEnabled ? new proxy_check({
api_key: this.antiProxyApiKey
}) : undefined;
if(typeof this.defaultPQuota !== "object" || this.defaultPQuota.length !== 2
|| isNaN(+this.defaultPQuota[0]) || isNaN(+this.defaultPQuota[1])) throw new Error("Bad PQuota.");
if(!options.adminlogin|| !options.modlogin) throw new Error("You should set 'adminlogin' and 'modlogin' options.");
// server things
this.pixelsPlaced = {
currentPixelsPlaced: 0,
lastPushOn: 0,
pixelsPlacedPerHour: []
};
setInterval(function() { // saves and resets upper thing
that.pixelsPlaced.pixelsPlacedPerHour.push(that.pixelsPlaced.currentPixelsPlaced);
that.pixelsPlaced.currentPixelsPlaced = 0;
}, 1000 * 60 * 60);
this.worlds = {};
this.protocol = {
server: {
setId: 0,
worldUpdate: 1,
chunkLoad: 2,
teleport: 3,
setRank: 4,
captcha: 5,
setPQuota: 6,
chunkProtected: 7,
maxCount: 8
},
client: {
rankVerification: 1, // rank
//captcha: 6,
requestChunk: 4 + // x
4, // y
protectChunk: 4 + // x
4 + // y
1 + // newstate
1, // blank place
setPixel: 4 + // x
4 + // y
1 + // r
1 + // g
1, // b
playerUpdate: 4 + // x
4 + // y
1 + // r
1 + // g
1 + // b
1, //tool
clearChunk: 4 + // x
4 + // y
1 + // r
1 + // g
1 + // b
2, // blank place
paste: 4 + // x
4 + // y
16 * 16 * 3 // 768 data
}
}
this.tokens = {
worldVerificationCode: 25565,
captchaCode: "CaptchA",
chatCode: "\n"
};
this.commands = {
help: {
action: (user, args) => {
let cmd = args[0];
if (cmd) {
let command = that.getCommand(cmd);
if (command) {
user.send(
`Command: ${cmd}\nDescription: ${
command.description
}\nAliases: ${
command.aliases.length ? command.aliases.join(" ") : "none"
}`
);
} else {
user.send("Server: Command not found.");
}
} else {
let string = "Server: ";
for (var commandName in this.commands) {
if (user.rank >= this.commands[commandName].requiredRank) {
string += commandName + " ";
}
}
user.send(string.slice(0, -1));
}
},
description: "Shows help",
aliases: ["h", "commands"],
requiredRank: 0
},
nick: {
action: (user, args) => {
let nick = args.join(" ").trim();
if (user.rank < 3) {
nick = nick
.replace(/\n/gm, "")
.slice(0, 16)
.trim();
}
if (nick) {
user.nick = nick;
user.send(`Nickname set to: "${nick}"`);
} else {
user.nick = "";
user.send("Nickname reset.");
}
},
description: "Sets new nick.",
aliases: ["nickname"],
requiredRank: 0
},
tell: {
action: (user, args) => {
let u = user.world.clients[args[0]];
let msg = args;
msg.shift();
msg = msg.join(" ");
if (!u || !msg) {
return user.send("Usage: /tell id message");
}
u.send(`-> ${user.id} tells you: ${msg}`);
user.send(`-> you tell ${u.id}: ${msg}`);
},
requiredRank: 0,
description: "PM other player.",
aliases: ["msg"]
},
pass: {
action: (user, args) => {
let world = user.world;
if (!world.pass || args[0] !== world.pass) return user.ws.close();
if(user.rank === 0) user.setRank(1);
},
requiredRank: 0,
description: "Unlock drawing with password.",
aliases: ["password"]
},
modlogin: {
action: (user, args) => {
let world = user.world;
let modlogin = args.join(" ");
if (modlogin !== world.modlogin) return user.ws.close();
user.setRank(2);
},
requiredRank: 0,
description: "Login to moderator.",