forked from smogon/pokemon-showdown
-
Notifications
You must be signed in to change notification settings - Fork 0
/
users.ts
1731 lines (1585 loc) · 53.2 KB
/
users.ts
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.
*
* `Users.users` is the global table of all users, a `Map` of `ID:User`.
* Users should normally be accessed with `Users.get(userid)`
*
* `Users.connections` is the global table of all connections, a `Map` of
* `string:Connection` (the string is mostly meaningless but see
* `connection.id` for details). Connections are normally accessed through
* `user.connections`.
*
* @license MIT
*/
type StatusType = 'online' | 'busy' | 'idle';
const THROTTLE_DELAY = 600;
const THROTTLE_DELAY_TRUSTED = 100;
const THROTTLE_BUFFER_LIMIT = 6;
const THROTTLE_MULTILINE_WARN = 3;
const THROTTLE_MULTILINE_WARN_STAFF = 6;
const NAMECHANGE_THROTTLE = 2 * 60 * 1000; // 2 minutes
const NAMES_PER_THROTTLE = 3;
const PERMALOCK_CACHE_TIME = 30 * 24 * 60 * 60 * 1000; // 30 days
const DEFAULT_TRAINER_SPRITES = [1, 2, 101, 102, 169, 170, 265, 266];
import {FS, Utils, ProcessManager} from '../lib';
import {
Auth, GlobalAuth, SECTIONLEADER_SYMBOL, PLAYER_SYMBOL, HOST_SYMBOL, RoomPermission, GlobalPermission,
} from './user-groups';
const MINUTES = 60 * 1000;
const IDLE_TIMER = 60 * MINUTES;
const STAFF_IDLE_TIMER = 30 * MINUTES;
const CONNECTION_EXPIRY_TIME = 24 * 60 * MINUTES;
/*********************************************************
* Utility functions
*********************************************************/
// Low-level functions for manipulating Users.users and Users.prevUsers
// Keeping them all here makes it easy to ensure they stay consistent
function move(user: User, newUserid: ID) {
if (user.id === newUserid) return true;
if (!user) return false;
// doing it this way mathematically ensures no cycles
prevUsers.delete(newUserid);
prevUsers.set(user.id, newUserid);
users.delete(user.id);
user.id = newUserid;
users.set(newUserid, user);
return true;
}
function add(user: User) {
if (user.id) throw new Error(`Adding a user that already exists`);
numUsers++;
user.guestNum = numUsers;
user.name = `Guest ${numUsers}`;
user.id = toID(user.name);
if (users.has(user.id)) throw new Error(`userid taken: ${user.id}`);
users.set(user.id, user);
}
function deleteUser(user: User) {
prevUsers.delete('guest' + user.guestNum as ID);
users.delete(user.id);
}
function merge(toRemain: User, toDestroy: User) {
prevUsers.delete(toRemain.id);
prevUsers.set(toDestroy.id, toRemain.id);
}
/**
* 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.
*/
function getUser(name: string | User | null, exactName = false) {
if (!name || name === '!') return null;
if ((name as User).id) return name as User;
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) || 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.
*/
function getExactUser(name: string | User) {
return getUser(name, true);
}
/**
* Get a list of all users matching a list of userids and ips.
*
* Usage:
* Users.findUsers([userids], [ips])
*/
function findUsers(userids: ID[], ips: string[], options: {forPunishment?: boolean, includeTrusted?: boolean} = {}) {
const matches: User[] = [];
if (options.forPunishment) ips = ips.filter(ip => !Punishments.isSharedIp(ip));
const ipMatcher = IPTools.checker(ips);
for (const user of users.values()) {
if (!options.forPunishment && !user.named && !user.connected) continue;
if (!options.includeTrusted && user.trusted) continue;
if (userids.includes(user.id)) {
matches.push(user);
continue;
}
if (user.ips.some(ipMatcher)) {
matches.push(user);
}
}
return matches;
}
/*********************************************************
* User groups
*********************************************************/
const globalAuth = new GlobalAuth();
function isUsernameKnown(name: string) {
const userid = toID(name);
if (Users.get(userid)) return true;
if (globalAuth.has(userid)) return true;
for (const room of Rooms.global.chatRooms) {
if (room.auth.has(userid)) return true;
}
return false;
}
function isUsername(name: string) {
return /[A-Za-z0-9]/.test(name.charAt(0)) && /[A-Za-z]/.test(name) && !name.includes(',');
}
function isTrusted(userid: ID) {
if (globalAuth.has(userid)) return userid;
for (const room of Rooms.global.chatRooms) {
if (room.persist && room.settings.isPrivate !== true && room.auth.isStaff(userid)) {
return userid;
}
}
const staffRoom = Rooms.get('staff');
const staffAuth = staffRoom && !!(staffRoom.auth.has(userid) || staffRoom.users[userid]);
return staffAuth ? userid : false;
}
/*********************************************************
* User and Connection classes
*********************************************************/
const connections = new Map<string, Connection>();
export class Connection {
/**
* Connection IDs are mostly meaningless, beyond being known to be
* unique among connections. They set in `socketConnect` to
* `workerid-socketid`, so for instance `2-523` would be the 523th
* connection to the 2nd socket worker process.
*/
readonly id: string;
readonly socketid: string;
readonly worker: ProcessManager.StreamWorker;
readonly inRooms: Set<RoomID>;
readonly ip: string;
readonly protocol: string;
readonly connectedAt: number;
/**
* 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.
*/
user: User;
challenge: string;
autojoins: string;
/** The last bot html page this connection requested, formatted as `${bot.id}-${pageid}` */
lastRequestedPage: string | null;
lastActiveTime: number;
openPages: null | Set<string>;
constructor(
id: string,
worker: ProcessManager.StreamWorker,
socketid: string,
user: User | null,
ip: string | null,
protocol: string | null
) {
const now = Date.now();
this.id = id;
this.socketid = socketid;
this.worker = worker;
this.inRooms = new Set();
this.ip = ip || '';
this.protocol = protocol || '';
this.connectedAt = now;
this.user = user!;
this.challenge = '';
this.autojoins = '';
this.lastRequestedPage = null;
this.lastActiveTime = now;
this.openPages = null;
}
sendTo(roomid: RoomID | BasicRoom | null, data: string) {
if (roomid && typeof roomid !== 'string') roomid = roomid.roomid;
if (roomid && roomid !== 'lobby') data = `>${roomid}\n${data}`;
Sockets.socketSend(this.worker, this.socketid, data);
Monitor.countNetworkUse(data.length);
}
send(data: string) {
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: string) {
this.send(`|popup|` + message.replace(/\n/g, '||'));
}
joinRoom(room: Room) {
if (this.inRooms.has(room.roomid)) return;
this.inRooms.add(room.roomid);
Sockets.roomAdd(this.worker, room.roomid, this.socketid);
}
leaveRoom(room: Room) {
if (this.inRooms.has(room.roomid)) {
this.inRooms.delete(room.roomid);
Sockets.roomRemove(this.worker, room.roomid, this.socketid);
}
}
toString() {
let buf = this.user ? `${this.user.id}[${this.user.connections.indexOf(this)}]` : `[disconnected]`;
buf += `:${this.ip}`;
if (this.protocol !== 'websocket') buf += `:${this.protocol}`;
return buf;
}
}
type ChatQueueEntry = [string, RoomID, Connection];
export interface UserSettings {
blockChallenges: boolean | AuthLevel | 'friends';
blockPMs: boolean | AuthLevel | 'friends';
ignoreTickets: boolean;
hideBattlesFromTrainerCard: boolean;
blockInvites: AuthLevel | boolean;
doNotDisturb: boolean;
blockFriendRequests: boolean;
allowFriendNotifications: boolean;
displayBattlesToFriends: boolean;
hideLogins: boolean;
}
// User
export class User extends Chat.MessageContext {
/** In addition to needing it to implement MessageContext, this is also nice for compatibility with Connection. */
readonly user: User;
readonly inRooms: Set<RoomID>;
/**
* Set of room IDs
*/
readonly games: Set<RoomID>;
mmrCache: {[format: string]: number};
guestNum: number;
name: string;
named: boolean;
registered: boolean;
id: ID;
tempGroup: GroupSymbol;
avatar: string | number;
language: ID | null;
connected: boolean;
connections: Connection[];
latestHost: string;
latestHostType: string;
ips: string[];
latestIp: string;
locked: ID | PunishType | null;
semilocked: ID | PunishType | null;
namelocked: ID | PunishType | null;
permalocked: ID | PunishType | null;
punishmentTimer: NodeJS.Timer | null;
previousIDs: ID[];
lastChallenge: number;
lastPM: string;
lastMatch: ID;
settings: UserSettings;
battleSettings: {
team: string,
hidden: boolean,
inviteOnly: boolean,
special?: string,
};
isSysop: boolean;
isStaff: boolean;
lastDisconnected: number;
lastConnected: number;
foodfight?: {generatedTeam: string[], dish: string, ingredients: string[], timestamp: number};
friends?: Set<string>;
chatQueue: ChatQueueEntry[] | null;
chatQueueTimeout: NodeJS.Timeout | null;
lastChatMessage: number;
lastCommand: string;
notified: {
blockChallenges: boolean,
blockPMs: boolean,
blockInvites: boolean,
punishment: boolean,
lock: boolean,
};
lastMessage: string;
lastMessageTime: number;
lastReportTime: number;
lastNewNameTime = 0;
newNames = 0;
s1: string;
s2: string;
s3: string;
autoconfirmed: ID;
trusted: ID;
trackRename: string;
statusType: StatusType;
userMessage: string;
lastWarnedAt: number;
constructor(connection: Connection) {
super(connection.user);
this.user = this;
this.inRooms = new Set();
this.games = new Set();
this.mmrCache = Object.create(null);
this.guestNum = -1;
this.name = "";
this.named = false;
this.registered = false;
this.id = '';
this.tempGroup = Auth.defaultSymbol();
this.language = null;
this.avatar = DEFAULT_TRAINER_SPRITES[Math.floor(Math.random() * DEFAULT_TRAINER_SPRITES.length)];
this.connected = true;
Users.onlineCount++;
if (connection.user) connection.user = this;
this.connections = [connection];
this.latestHost = '';
this.latestHostType = '';
this.ips = [connection.ip];
// 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` array, not just the latest IP.
this.latestIp = connection.ip;
this.locked = null;
this.semilocked = null;
this.namelocked = null;
this.permalocked = null;
this.punishmentTimer = null;
this.previousIDs = [];
// misc state
this.lastChallenge = 0;
this.lastPM = '';
this.lastMatch = '';
// settings
this.settings = {
blockChallenges: false,
blockPMs: false,
ignoreTickets: false,
hideBattlesFromTrainerCard: false,
blockInvites: false,
doNotDisturb: false,
blockFriendRequests: false,
allowFriendNotifications: false,
displayBattlesToFriends: false,
hideLogins: false,
};
this.battleSettings = {
team: '',
hidden: false,
inviteOnly: false,
};
this.isSysop = false;
this.isStaff = false;
this.lastDisconnected = 0;
this.lastConnected = connection.connectedAt;
// chat queue
this.chatQueue = null;
this.chatQueueTimeout = null;
this.lastChatMessage = 0;
this.lastCommand = '';
// for the anti-spamming mechanism
this.lastMessage = ``;
this.lastMessageTime = 0;
this.lastReportTime = 0;
this.s1 = '';
this.s2 = '';
this.s3 = '';
this.notified = {
blockChallenges: false,
blockPMs: false,
blockInvites: false,
punishment: false,
lock: false,
};
this.autoconfirmed = '';
this.trusted = '';
// Used in punishments
this.trackRename = '';
this.statusType = 'online';
this.userMessage = '';
this.lastWarnedAt = 0;
// initialize
Users.add(this);
}
sendTo(roomid: RoomID | BasicRoom | null, data: string) {
if (roomid && typeof roomid !== 'string') roomid = roomid.roomid;
if (roomid && 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);
}
}
send(data: string) {
for (const connection of this.connections) {
connection.send(data);
Monitor.countNetworkUse(data.length);
}
}
popup(message: string) {
this.send(`|popup|` + message.replace(/\n/g, '||'));
}
getIdentity(room: BasicRoom | null = null) {
const punishgroups = Config.punishgroups || {locked: null, muted: null};
if (this.locked || this.namelocked) {
const lockedSymbol = (punishgroups.locked && punishgroups.locked.symbol || '\u203d');
return lockedSymbol + this.name;
}
if (room) {
if (room.isMuted(this)) {
const mutedSymbol = (punishgroups.muted && punishgroups.muted.symbol || '!');
return mutedSymbol + this.name;
}
return room.auth.get(this) + this.name;
}
if (this.semilocked) {
const mutedSymbol = (punishgroups.muted && punishgroups.muted.symbol || '!');
return mutedSymbol + this.name;
}
return this.tempGroup + this.name;
}
getIdentityWithStatus(room: BasicRoom | null = null) {
const identity = this.getIdentity(room);
const status = this.statusType === 'online' ? '' : '@!';
return `${identity}${status}`;
}
getStatus() {
const statusMessage = this.statusType === 'busy' ? '!(Busy) ' : this.statusType === 'idle' ? '!(Idle) ' : '';
const status = statusMessage + (this.userMessage || '');
return status;
}
can(permission: RoomPermission, target: User | null, room: BasicRoom, cmd?: string): boolean;
can(permission: GlobalPermission, target?: User | null): boolean;
can(permission: RoomPermission & GlobalPermission, target: User | null, room?: BasicRoom | null, cmd?: string): boolean;
can(permission: string, target: User | null = null, room: BasicRoom | null = null, cmd?: string): boolean {
return Auth.hasPermission(this, permission, target, room, cmd);
}
/**
* Special permission check for system operators
*/
hasSysopAccess() {
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.
*/
hasConsoleAccess(connection: Connection) {
if (this.hasSysopAccess()) return true;
if (!this.can('console')) return false; // normal permission check
const whitelist = Config.consoleips || ['127.0.0.1'];
// on the IP whitelist OR the userid whitelist
return whitelist.includes(connection.ip) || whitelist.includes(this.id);
}
resetName(isForceRenamed = false) {
return this.forceRename('Guest ' + this.guestNum, false, isForceRenamed);
}
updateIdentity(roomid: RoomID | null = null) {
if (roomid) {
return Rooms.get(roomid)!.onUpdateIdentity(this);
}
for (const inRoomID of this.inRooms) {
Rooms.get(inRoomID)!.onUpdateIdentity(this);
}
}
async validateToken(token: string, name: string, userid: ID, connection: Connection) {
if (!token && Config.noguestsecurity) {
if (Users.isTrusted(userid)) {
this.send(`|nametaken|${name}|You need an authentication token to log in as a trusted user.`);
return null;
}
return '1';
}
if (!token || token.startsWith(';')) {
this.send(`|nametaken|${name}|Your authentication token was invalid.`);
return null;
}
let challenge = '';
if (connection) {
challenge = connection.challenge;
}
if (!challenge) {
Monitor.warn(`verification failed; no challenge`);
return null;
}
const [tokenData, tokenSig] = Utils.splitFirst(token, ';');
const tokenDataSplit = tokenData.split(',');
const [signedChallenge, signedUserid, userType, signedDate, signedHostname] = tokenDataSplit;
if (signedHostname && Config.legalhosts && !Config.legalhosts.includes(signedHostname)) {
Monitor.warn(`forged assertion: ${tokenData}`);
this.send(`|nametaken|${name}|Your assertion is for the wrong server. This server is ${Config.legalhosts[0]}.`);
return null;
}
if (tokenDataSplit.length < 5) {
Monitor.warn(`outdated assertion format: ${tokenData}`);
this.send(`|nametaken|${name}|The assertion you sent us is corrupt or incorrect. Please send the exact assertion given by the login server's JSON response.`);
return null;
}
if (signedUserid !== userid) {
// userid mismatch
this.send(`|nametaken|${name}|Your verification signature doesn't match your new username.`);
return null;
}
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 null;
}
const 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 null;
}
const 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 null;
}
// future-proofing
this.s1 = tokenDataSplit[5];
this.s2 = tokenDataSplit[6];
this.s3 = tokenDataSplit[7];
return userType;
}
/**
* Do a rename, passing and validating a login token.
*
* @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
*/
async rename(name: string, token: string, newlyRegistered: boolean, connection: Connection) {
let userid = toID(name);
if (userid !== this.id) {
for (const roomid of this.games) {
const room = Rooms.get(roomid);
if (!room?.game || room.game.ended) {
this.games.delete(roomid);
console.log(`desynced roomgame ${roomid} renaming ${this.id} -> ${userid}`);
continue;
}
if (room.game.allowRenames || !this.named) continue;
this.popup(`You can't change your name right now because you're in ${room.game.title}, which doesn't allow renaming.`);
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.id && !newlyRegistered) {
return this.forceRename(name, this.registered);
}
}
const userType = await this.validateToken(token, name, userid, connection);
if (userType === null) return;
if (userType === '1') newlyRegistered = false;
if (!this.trusted && userType === '1') { // userType '1' means unregistered
const elapsed = Date.now() - this.lastNewNameTime;
if (elapsed < NAMECHANGE_THROTTLE && !Config.nothrottle) {
if (this.newNames >= NAMES_PER_THROTTLE) {
this.send(
`|nametaken|${name}|You must wait ${Chat.toDurationString(NAMECHANGE_THROTTLE - elapsed)} more
seconds before using another unregistered name.`
);
return false;
}
this.newNames++;
} else {
this.lastNewNameTime = Date.now();
this.newNames = 1;
}
}
this.handleRename(name, userid, newlyRegistered, userType);
}
handleRename(name: string, userid: ID, newlyRegistered: boolean, userType: string) {
const registered = (userType !== '1');
const conflictUser = users.get(userid);
if (conflictUser) {
// unregistered users can only merge in limited situations
let canMerge = registered && conflictUser.registered;
if (
!registered && !conflictUser.registered && conflictUser.latestIp === this.latestIp &&
!conflictUser.connected
) {
canMerge = true;
}
if (!canMerge) {
if (registered && !conflictUser.registered) {
// user has just registered; don't merge just to be safe
if (conflictUser !== this) conflictUser.resetName();
} else {
this.send(`|nametaken|${name}|Someone is already using the name "${conflictUser.name}".`);
return false;
}
}
}
// user types:
// 1: unregistered user
// 2: registered user
// 3: Pokemon Showdown system operator
// 4: autoconfirmed
// 5: permalocked
// 6: permabanned
if (registered) {
if (userType === '3') {
this.isSysop = true;
this.isStaff = true;
this.trusted = userid;
this.autoconfirmed = userid;
} else if (userType === '4') {
this.autoconfirmed = userid;
} else if (userType === '5') {
this.permalocked = userid;
void Punishments.lock(this, Date.now() + PERMALOCK_CACHE_TIME, userid, true, `Permalocked as ${name}`, true);
} else if (userType === '6') {
void Punishments.lock(this, Date.now() + PERMALOCK_CACHE_TIME, userid, true, `Permabanned as ${name}`, true);
this.disconnectAll();
}
}
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;
this.destroyPunishmentTimer();
}
let user = users.get(userid);
const possibleUser = Users.get(userid);
if (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 (const id of this.previousIDs) {
if (!user.previousIDs.includes(id)) user.previousIDs.push(id);
}
if (this.named && !user.previousIDs.includes(this.id)) user.previousIDs.push(this.id);
this.destroy();
Punishments.checkName(user, userid, registered);
Rooms.global.checkAutojoin(user);
Rooms.global.joinOldBattles(this);
Chat.loginfilter(user, this, userType);
return true;
}
Punishments.checkName(this, userid, registered);
if (this.namelocked) {
Chat.loginfilter(this, null, userType);
return false;
}
// rename success
if (!this.forceRename(name, registered)) {
return false;
}
Rooms.global.checkAutojoin(this);
Rooms.global.joinOldBattles(this);
Chat.loginfilter(this, null, userType);
return true;
}
forceRename(name: string, registered: boolean, isForceRenamed = false) {
// skip the login server
const userid = toID(name);
if (users.has(userid) && users.get(userid) !== this) {
return false;
}
const oldname = this.name;
const oldid = this.id;
if (userid !== this.id) {
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.previousIDs.includes(oldid)) this.previousIDs.push(oldid);
this.name = name;
const joining = !this.named;
this.named = !userid.startsWith('guest') || !!this.namelocked;
if (isForceRenamed) this.userMessage = '';
for (const connection of this.connections) {
// console.log('' + name + ' renaming: socket ' + i + ' of ' + this.connections.length);
connection.send(this.getUpdateuserText());
}
for (const roomid of this.games) {
const room = Rooms.get(roomid);
if (!room) {
Monitor.warn(`while renaming, room ${roomid} expired for user ${this.id} in rooms ${[...this.inRooms]} and games ${[...this.games]}`);
this.games.delete(roomid);
continue;
}
if (!room.game) {
Monitor.warn(`game desync for user ${this.id} in room ${room.roomid}`);
this.games.delete(roomid);
continue;
}
room.game.onRename(this, oldid, joining, isForceRenamed);
}
for (const roomid of this.inRooms) {
Rooms.get(roomid)!.onRename(this, oldid, joining);
}
if (isForceRenamed) this.trackRename = oldname;
return true;
}
getUpdateuserText() {
const named = this.named ? 1 : 0;
const settings = {
...this.settings,
// Battle privacy state needs to be propagated in addition to regular settings so that the
// 'Ban spectators' checkbox on the client can be kept in sync (and disable privacy correctly)
hiddenNextBattle: this.battleSettings.hidden,
inviteOnlyNextBattle: this.battleSettings.inviteOnly,
language: this.language,
};
return `|updateuser|${this.getIdentityWithStatus()}|${named}|${this.avatar}|${JSON.stringify(settings)}`;
}
update() {
this.send(this.getUpdateuserText());
}
/**
* If Alice logs into Bob's account, and Bob is currently logged into PS,
* their connections will be merged, so that both `Connection`s are attached
* to the Alice `User`.
*
* In this function, `this` is Bob, and `oldUser` is Alice.
*
* This is a pretty routine thing: If Alice opens PS, then opens PS again in
* a new tab, PS will first create a Guest `User`, then automatically log in
* and merge that Guest `User` into the Alice `User` from the first tab.
*/
merge(oldUser: User) {
oldUser.cancelReady();
for (const roomid of oldUser.inRooms) {
Rooms.get(roomid)!.onLeave(oldUser);
}
const oldLocked = this.locked;
const oldSemilocked = this.semilocked;
if (!oldUser.semilocked) this.semilocked = null;
// If either user is unlocked and neither is locked by name, remove the lock.
// Otherwise, keep any locks that were by name.
if (
(!oldUser.locked || !this.locked) &&
oldUser.locked !== oldUser.id &&
this.locked !== this.id &&
// Only unlock if no previous names are locked
!oldUser.previousIDs.some(id => !!Punishments.hasPunishType(id, 'LOCK'))
) {
this.locked = null;
this.destroyPunishmentTimer();
} else if (this.locked !== this.id) {
this.locked = oldUser.locked;
}
if (oldUser.autoconfirmed) this.autoconfirmed = oldUser.autoconfirmed;
this.updateGroup(this.registered, true);
if (oldLocked !== this.locked || oldSemilocked !== this.semilocked) this.updateIdentity();
// We only propagate the 'busy' statusType through merging - merging is
// active enough that the user should no longer be in the 'idle' state.
// Doing this before merging connections ensures the updateuser message
// shows the correct idle state.
const isBusy = this.statusType === 'busy' || oldUser.statusType === 'busy';
this.setStatusType(isBusy ? 'busy' : 'online');
for (const connection of oldUser.connections) {
this.mergeConnection(connection);
}
oldUser.inRooms.clear();
oldUser.connections = [];
if (oldUser.chatQueue) {
if (!this.chatQueue) this.chatQueue = [];
this.chatQueue.push(...oldUser.chatQueue);
oldUser.clearChatQueue();
if (!this.chatQueueTimeout) this.startChatQueue();
}
this.s1 = oldUser.s1;
this.s2 = oldUser.s2;
this.s3 = oldUser.s3;
// merge IPs
for (const ip of oldUser.ips) {
if (!this.ips.includes(ip)) this.ips.push(ip);
}
if (oldUser.isSysop) {
this.isSysop = true;
oldUser.isSysop = false;
}
oldUser.ips = [];
this.latestIp = oldUser.latestIp;