-
Notifications
You must be signed in to change notification settings - Fork 9
/
users.js
1735 lines (1599 loc) · 49.4 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';
/** @typedef {GlobalRoom | GameRoom | ChatRoom} Room */
const PLAYER_SYMBOL = '\u2606';
const HOST_SYMBOL = '\u2605';
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 DEFAULT_TRAINER_SPRITES = [1, 2, 101, 102, 169, 170, 265, 266];
const FS = require('./lib/fs');
/*********************************************************
* Utility functions
*********************************************************/
// Low-level functions for manipulating Users.users and Users.prevUsers
// Keeping them all here makes it easy to ensure they stay consistent
/**
* @param {User} user
* @param {string} newUserid
*/
function move(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;
}
/**
* @param {User} user
*/
function add(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);
}
/**
* @param {User} user
*/
function deleteUser(user) {
prevUsers.delete('guest' + user.guestNum);
users.delete(user.userid);
}
/**
* @param {User} user1
* @param {User} user2
*/
function merge(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 null 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.
* @param {?string | User} name
* @param {boolean} exactName
* @return {?User}
*/
function getUser(name, exactName = false) {
if (!name || name === '!') return null;
// @ts-ignore
if (name.userid) return name;
let userid = toId(name);
let i = 0;
if (!exactName) {
while (userid && !users.has(userid) && i < 1000) {
// @ts-ignore
userid = prevUsers.get(userid);
i++;
}
}
return users.get(userid) || null;
}
/**
* 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.
* @param {string | User} name
*/
function getExactUser(name) {
return getUser(name, true);
}
/**
* Get a list of all users matching a list of userids and ips.
*
* Usage:
* Users.findUsers([userids], [ips])
* @param {string[]} userids
* @param {string[]} ips
* @param {{forPunishment?: boolean, includeTrusted?: boolean}} options
*/
function findUsers(userids, ips, options = {}) {
let matches = /** @type {User[]} */ ([]);
if (options.forPunishment) ips = ips.filter(ip => !Punishments.sharedIps.has(ip));
for (const user of users.values()) {
if (!options.forPunishment && !user.named && !user.connected) continue;
if (!options.includeTrusted && user.trusted) continue;
if (userids.includes(user.userid)) {
matches.push(user);
continue;
}
for (let myIp of ips) {
if (myIp in user.ips) {
matches.push(user);
break;
}
}
}
return matches;
}
/*********************************************************
* User groups
*********************************************************/
let usergroups = Object.create(null);
function importUsergroups() {
// can't just say usergroups = {} because it's exported
for (let i in usergroups) delete usergroups[i];
FS('config/usergroups.csv').readIfExists().then(data => {
for (const row of data.split("\n")) {
if (!row) continue;
let cells = row.split(",");
usergroups[toId(cells[0])] = (cells[1] || Config.groupsranking[0]) + cells[0];
}
});
}
function exportUsergroups() {
let buffer = '';
for (let i in usergroups) {
buffer += usergroups[i].substr(1).replace(/,/g, '') + ',' + usergroups[i].charAt(0) + "\n";
}
FS('config/usergroups.csv').write(buffer);
}
importUsergroups();
function cacheGroupData() {
if (Config.groups) {
// Support for old config groups format.
// Should be removed soon.
console.error(
`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.punishgroups = Object.create(null);
Config.groups = Object.create(null);
Config.groupsranking = [];
}
let groups = Config.groups;
let punishgroups = Config.punishgroups;
/** @type {{[k: string]: 'processing' | true}} */
let cachedGroups = {};
/**
* @param {string} sym
* @param {any} groupData
*/
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];
// punish groups
if (groupData.punishgroup) {
punishgroups[groupData.id] = groupData;
continue;
}
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);
}
// hardcode default punishgroups.
if (!punishgroups.locked) {
punishgroups.locked = {
name: 'Locked',
id: 'locked',
symbol: '\u203d',
};
}
if (!punishgroups.muted) {
punishgroups.muted = {
name: 'Muted',
id: 'muted',
symbol: '!',
};
}
}
cacheGroupData();
/**
* @param {string} name
* @param {string} group
* @param {boolean} forceTrusted
*/
function setOfflineGroup(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;
}
/**
* @param {string} name
*/
function isUsernameKnown(name) {
let userid = toId(name);
if (Users(userid)) return true;
if (userid in usergroups) return true;
for (const room of Rooms.global.chatRooms) {
if (!room.auth) continue;
if (userid in room.auth) return true;
}
return false;
}
/**
* @param {string | User} name
*/
function isTrusted(name) {
// @ts-ignore
if (name.trusted) return name.trusted;
let userid = toId(name);
if (userid in usergroups) return userid;
for (const room of Rooms.global.chatRooms) {
if (!room.isPrivate && !room.isPersonal && room.auth && userid in room.auth && room.auth[userid] !== '+') return userid;
}
return false;
}
/*********************************************************
* User and Connection classes
*********************************************************/
let connections = new Map();
class Connection {
/**
* @param {string} id
* @param {any} worker
* @param {string} socketid
* @param {?User} user
* @param {?string} ip
* @param {?string} protocol
*/
constructor(id, worker, socketid, user, ip, protocol) {
this.id = id;
this.socketid = socketid;
this.worker = worker;
this.inRooms = new Set();
/**
* This can be null during initialization and after disconnecting,
* but we're asserting it non-null for ease of use. The main risk
* is async code, where you need to re-check that it's not null
* before using it.
* @type {User}
*/
this.user = /** @type {User} */ (user);
this.ip = ip || '';
this.protocol = protocol || '';
this.challenge = '';
this.autojoins = '';
}
/**
* @param {string | BasicRoom?} roomid
* @param {string} data
*/
sendTo(roomid, data) {
// @ts-ignore
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);
}
/**
* @param {string} data
*/
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 = /** @type {any} */ (null);
}
/**
* @param {string} message
*/
popup(message) {
this.send(`|popup|` + message.replace(/\n/g, '||'));
}
/**
* @param {GlobalRoom | GameRoom | ChatRoom} room
*/
joinRoom(room) {
if (this.inRooms.has(room.id)) return;
this.inRooms.add(room.id);
Sockets.channelAdd(this.worker, room.id, this.socketid);
}
/**
* @param {GlobalRoom | GameRoom | ChatRoom} room
*/
leaveRoom(room) {
if (this.inRooms.has(room.id)) {
this.inRooms.delete(room.id);
Sockets.channelRemove(this.worker, room.id, this.socketid);
}
}
toString() {
return (this.user ? this.user.userid + '[' + this.user.connections.indexOf(this) + ']' : '[disconnected]') + ':' + this.ip + (this.protocol !== 'websocket' ? ':' + this.protocol : '');
}
}
/** @typedef {[string, string, Connection]} ChatQueueEntry */
// User
class User {
/**
* @param {Connection} connection
*/
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];
this.avatar = DEFAULT_TRAINER_SPRITES[Math.floor(Math.random() * DEFAULT_TRAINER_SPRITES.length)];
this.connected = true;
if (connection.user) connection.user = this;
this.connections = [connection];
/**@type {string} */
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.
/** @type {string} */
this.latestIp = connection.ip;
/** @type {?false | string} */
this.locked = false;
/** @type {?false | string} */
this.semilocked = false;
/** @type {?boolean} */
this.namelocked = false;
/** @type {?false | string} */
this.permalocked = false;
this.prevNames = Object.create(null);
this.inRooms = new Set();
// Set of roomids
this.games = new Set();
// misc state
this.lastChallenge = 0;
this.lastPM = '';
this.team = '';
this.lastMatch = '';
// settings
this.isSysop = false;
this.isStaff = false;
this.blockChallenges = false;
this.ignorePMs = false;
this.lastConnected = 0;
this.inviteOnlyNextBattle = false;
// chat queue
/** @type {ChatQueueEntry[]?} */
this.chatQueue = null;
this.chatQueueTimeout = null;
this.lastChatMessage = 0;
this.lastCommand = '';
// for the anti-spamming mechanism
this.lastMessage = ``;
this.lastMessageTime = 0;
this.lastReportTime = 0;
/**@type {string} */
this.s1 = '';
/**@type {string} */
this.s2 = '';
/**@type {string} */
this.s3 = '';
/** @type {boolean} */
this.punishmentNotified = false;
/** @type {boolean} */
this.lockNotified = false;
/**@type {string} */
this.autoconfirmed = '';
// Used in punishments
/** @type {string} */
this.trackRename = '';
// initialize
Users.add(this);
}
/**
* @param {string | BasicRoom?} roomid
* @param {string} data
*/
sendTo(roomid, data) {
// @ts-ignore
if (roomid && roomid.id) roomid = roomid.id;
if (roomid && roomid !== 'global' && roomid !== 'lobby') data = `>${roomid}\n${data}`;
for (const connection of this.connections) {
if (roomid && !connection.inRooms.has(roomid)) continue;
connection.send(data);
Monitor.countNetworkUse(data.length);
}
}
/**
* @param {string} data
*/
send(data) {
for (const connection of this.connections) {
connection.send(data);
Monitor.countNetworkUse(data.length);
}
}
/**
* @param {string} message
*/
popup(message) {
this.send(`|popup|` + message.replace(/\n/g, '||'));
}
/**
* @param {string} roomid
*/
getIdentity(roomid = '') {
if (this.locked || this.namelocked) {
const lockedSymbol = (Config.punishgroups && Config.punishgroups.locked ? Config.punishgroups.locked.symbol : '\u203d');
return lockedSymbol + this.name;
}
if (roomid && roomid !== 'global') {
let room = Rooms(roomid);
if (!room) {
throw new Error(`Room doesn't exist: ${roomid}`);
}
if (room.isMuted(this)) {
const mutedSymbol = (Config.punishgroups && Config.punishgroups.muted ? Config.punishgroups.muted.symbol : '!');
return mutedSymbol + this.name;
}
return room.getAuth(this) + this.name;
}
if (this.semilocked) {
const mutedSymbol = (Config.punishgroups && Config.punishgroups.muted ? Config.punishgroups.muted.symbol : '!');
return mutedSymbol + this.name;
}
return this.group + this.name;
}
/**
* @param {string} minAuth
* @param {BasicChatRoom?} room
*/
authAtLeast(minAuth, room = null) {
if (!minAuth || minAuth === ' ') return true;
if (minAuth === 'trusted' && this.trusted) return true;
if (minAuth === 'autoconfirmed' && this.autoconfirmed) return true;
if (minAuth === 'trusted' || minAuth === 'autoconfirmed') {
minAuth = Config.groupsranking[1];
}
if (!(minAuth in Config.groups)) return false;
let auth = (room && !this.can('makeroom') ? room.getAuth(this) : this.group);
return auth in Config.groups && Config.groups[auth].rank >= Config.groups[minAuth].rank;
}
/**
* @param {string} permission
* @param {string | User?} target user or group symbol
* @param {BasicChatRoom?} room
* @return {boolean}
*/
can(permission, target = null, room = null) {
if (this.hasSysopAccess()) return true;
let groupData = Config.groups[this.group];
if (groupData && groupData['root']) {
return true;
}
/** @type {string} */
let group;
let targetGroup = '';
let targetUser = null;
if (typeof target === 'string') {
targetGroup = target;
} else {
targetUser = target;
}
if (room && (room.auth || room.parent)) {
group = room.getAuth(this);
if (targetUser) targetGroup = room.getAuth(targetUser);
if (room.isPrivate === true && this.can('makeroom')) group = this.group;
} else {
group = this.group;
if (targetUser) targetGroup = targetUser.group;
}
groupData = Config.groups[group];
if (groupData && groupData[permission]) {
let jurisdiction = groupData[permission];
if (!targetUser && !targetGroup) {
return !!jurisdiction;
}
if (jurisdiction === true && permission !== 'jurisdiction') {
return this.can('jurisdiction', (targetUser || targetGroup), room);
}
if (typeof jurisdiction !== 'string') {
return !!jurisdiction;
}
if (jurisdiction.includes(targetGroup)) {
return true;
}
if (jurisdiction.includes('s') && targetUser === 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 || Config.special.includes(this.userid)) {
//if (this.isSysop && Config.backdoor) {
// 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.
* @param {Connection} connection
*/
hasConsoleAccess(connection) {
if (this.hasSysopAccess()) return true;
if (!this.can('console')) return false; // normal permission check
let whitelist = Config.consoleips || ['127.0.0.1'];
// on the IP whitelist OR the userid whitelist
return whitelist.includes(connection.ip) || whitelist.includes(this.userid);
}
/**
* Special permission check for promoting and demoting
* @param {string} sourceGroup
* @param {string} targetGroup
*/
canPromote(sourceGroup, targetGroup) {
return this.can('promote', sourceGroup) && this.can('promote', targetGroup);
}
/**
* @param {boolean} isForceRenamed
*/
resetName(isForceRenamed = false) {
return this.forceRename('Guest ' + this.guestNum, false, isForceRenamed);
}
/**
* @param {?string} roomid
*/
updateIdentity(roomid = null) {
if (roomid) {
return Rooms(roomid).onUpdateIdentity(this);
}
for (const roomid of this.inRooms) {
Rooms(roomid).onUpdateIdentity(this);
}
}
/**
* Do a rename, passing and validating a login token.
*
* @param {string} name The name you want
* @param {string} token Signed assertion returned from login server
* @param {boolean} newlyRegistered Make sure this account will identify as registered
* @param {Connection} connection The connection asking for the rename
*/
async rename(name, token, newlyRegistered, connection) {
let userid = toId(name);
for (const roomid of this.games) {
if (userid === this.userid) break;
const game = Rooms(roomid).game;
if (!game || game.ended) continue; // should never happen
// SGgame
if (game.format && game.format === 'gen7wildpokemonalpha') {
this.popup(`You can't change your name right now because you're in the middle of a wild pokemon encounter.`);
return false;
}
if (game.allowRenames || !this.named) continue;
this.popup(`You can't change your name right now because you're in ${game.title}, which doesn't allow renaming.`);
return false;
// SGgame
if (this.console) {
// Shutdown on rename
this.sendTo(this.console.room, '|uhtmlchange|console' + this.userid + this.consoleId + '|');
delete this.console;
}
}
let challenge = '';
if (connection) {
challenge = connection.challenge;
}
if (!challenge) {
Monitor.warn(`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;
}
if (userid.length > 18) {
this.send(`|nametaken||Your name must be 18 characters or shorter.`);
return false;
}
name = Chat.namefilter(name, this);
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);
}
}
if (!token || token.charAt(0) === ';') {
this.send(`|nametaken|${name}|Your authentication token was invalid.`);
return false;
}
let tokenSemicolonPos = token.indexOf(';');
let tokenData = token.substr(0, tokenSemicolonPos);
let tokenSig = token.substr(tokenSemicolonPos + 1);
let success = await Verifier.verify(tokenData, tokenSig);
if (!success) {
Monitor.warn(`verify failed: ${token}`);
Monitor.warn(`challenge was: ${challenge}`);
this.send(`|nametaken|${name}|Your verification signature was invalid.`);
return false;
}
let tokenDataSplit = tokenData.split(',');
let [signedChallenge, signedUserid, userType, signedDate] = tokenDataSplit;
if (tokenDataSplit.length < 5) {
Monitor.warn(`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 false;
}
if (signedUserid !== userid) {
// userid mismatch
this.send(`|nametaken|${name}|Your verification signature doesn't match your new username.`);
return;
}
if (signedChallenge !== challenge) {
// a user sent an invalid token
Monitor.debug(`verify token challenge mismatch: ${signedChallenge} <=> ${challenge}`);
this.send(`|nametaken|${name}|Your verification signature doesn't match your authentication token.`);
return;
}
let expiry = Config.tokenexpiry || 25 * 60 * 60;
if (Math.abs(parseInt(signedDate) - Date.now() / 1000) > expiry) {
Monitor.warn(`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, userType);
}
/**
* @param {string} name
* @param {string} userid
* @param {boolean} newlyRegistered
* @param {string} userType
*/
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 false;
}
}
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') {
this.permalocked = userid;
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}`);
}
}
if (Users.isTrusted(userid)) {
this.trusted = userid;
this.autoconfirmed = userid;
}
if (this.trusted) {
this.locked = null;
this.namelocked = null;
this.permalocked = null;
this.semilocked = null;
}
let user = users.get(userid);
let possibleUser = Users(userid);
if (possibleUser && possibleUser.namelocked) {
// allows namelocked users to be merged
user = possibleUser;
}
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();
Punishments.checkName(user, userid, registered);
Rooms.global.checkAutojoin(user);
Server.giveDailyReward(user);
Server.friendLogin(user);
Chat.loginfilter(user, this, userType);
return true;
}
Punishments.checkName(this, userid, registered);
if (this.namelocked) return false;
// rename success
if (!this.forceRename(name, registered)) {
return false;
}
Rooms.global.checkAutojoin(this);
Server.giveDailyReward(this);
Chat.loginfilter(this, null, userType);
if (Tells.inbox[userid]) Tells.sendTell(userid, this);
Ontime[userid] = Date.now();
Server.showNews(userid, this);
Server.onlineFriends(userid);
Server.friendLogin(this);
return true;
}
/**
* @param {string} name
* @param {boolean} registered
* @param {boolean} isForceRenamed
*/
forceRename(name, registered, isForceRenamed = false) {
// skip the login server
let userid = toId(name);
if (users.has(userid) && users.get(userid) !== this) {
return false;
}
let oldid = this.userid;
if (userid !== this.userid) {
this.cancelReady();
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.startsWith('guest') || !!this.namelocked;
for (const connection of this.connections) {
//console.log('' + name + ' renaming: socket ' + i + ' of ' + this.connections.length);
let initdata = `|updateuser|${this.name}|${this.named ? 1 : 0}|${this.avatar}`;
connection.send(initdata);
}
for (const roomid of this.games) {
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);
continue;
}
// @ts-ignore
room.game.onRename(this, oldid, joining, isForceRenamed);
}
for (const roomid of this.inRooms) {
Rooms(roomid).onRename(this, oldid, joining);
}
return true;
}
/**
* @param {User} oldUser
*/
merge(oldUser) {
oldUser.cancelReady();
for (const roomid of oldUser.inRooms) {
Rooms(roomid).onLeave(oldUser);