forked from DeepRoost/infinite
-
Notifications
You must be signed in to change notification settings - Fork 0
/
users.js
1637 lines (1526 loc) · 49.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
*/
const THROTTLE_DELAY = 600;
const THROTTLE_BUFFER_LIMIT = 6;
const THROTTLE_MULTILINE_WARN = 4;
var fs = require('graceful-fs');
var dns = require('dns');
/* global Users: true */
var Users = module.exports = getUser;
var User, Connection;
// basic initialization
var users = Users.users = Object.create(null);
var prevUsers = Users.prevUsers = Object.create(null);
var numUsers = 0;
/**
* 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;
var userid = toId(name);
var i = 0;
while (!exactName && userid && !users[userid] && i < 1000) {
userid = prevUsers[userid];
i++;
}
return users[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.
*
* You can also pass a boolean as Users.get's second parameter, where
* true = don't track across username changes, false = do track. This
* is not recommended since it's less readable.
*/
var getExactUser = Users.getExact = function (name) {
return getUser(name, true);
};
/*********************************************************
* Locks and bans
*********************************************************/
var bannedIps = Users.bannedIps = Object.create(null);
var bannedUsers = Object.create(null);
var lockedIps = Users.lockedIps = Object.create(null);
var lockedUsers = Object.create(null);
var lockedRanges = Users.lockedRanges = Object.create(null);
var rangelockedUsers = Object.create(null);
/**
* Searches for IP in table.
*
* For instance, if IP is '1.2.3.4', will return the value corresponding
* to any of the keys in table match '1.2.3.4', '1.2.3.*', '1.2.*', or '1.*'
*/
function ipSearch(ip, table) {
if (table[ip]) return table[ip];
var dotIndex = ip.lastIndexOf('.');
for (var i = 0; i < 4 && dotIndex > 0; i++) {
ip = ip.substr(0, dotIndex);
if (table[ip + '.*']) return table[ip + '.*'];
dotIndex = ip.lastIndexOf('.');
}
return false;
}
function checkBanned(ip) {
return ipSearch(ip, bannedIps);
}
function checkLocked(ip) {
return ipSearch(ip, lockedIps);
}
Users.checkBanned = checkBanned;
Users.checkLocked = checkLocked;
// Defined in commands.js
Users.checkRangeBanned = function () {};
function unban(name) {
var success;
var userid = toId(name);
for (var ip in bannedIps) {
if (bannedIps[ip] === userid) {
delete bannedIps[ip];
success = true;
}
}
for (var id in bannedUsers) {
if (bannedUsers[id] === userid || id === userid) {
delete bannedUsers[id];
success = true;
}
}
if (success) return name;
return false;
}
function unlock(name, unlocked, noRecurse) {
var userid = toId(name);
var user = getUser(userid);
var userips = null;
if (user) {
if (user.userid === userid) name = user.name;
if (user.locked) {
user.locked = false;
user.updateIdentity();
unlocked = unlocked || {};
unlocked[name] = 1;
}
if (!noRecurse) userips = user.ips;
}
for (var ip in lockedIps) {
if (userips && (ip in user.ips) && Users.lockedIps[ip] !== userid) {
unlocked = unlock(Users.lockedIps[ip], unlocked, true); // avoid infinite recursion
}
if (Users.lockedIps[ip] === userid) {
delete Users.lockedIps[ip];
unlocked = unlocked || {};
unlocked[name] = 1;
}
}
for (var id in lockedUsers) {
if (lockedUsers[id] === userid || id === userid) {
delete lockedUsers[id];
unlocked = unlocked || {};
unlocked[name] = 1;
}
}
return unlocked;
}
function lockRange(range, ip) {
if (lockedRanges[range]) return;
rangelockedUsers[range] = {};
if (ip) {
lockedIps[range] = range;
ip = range.slice(0, -1);
}
for (var i in users) {
var curUser = users[i];
if (!curUser.named || curUser.locked || curUser.group !== Config.groupsranking[0]) continue;
if (ip) {
if (!curUser.latestIp.startsWith(ip)) continue;
} else {
if (range !== Users.shortenHost(curUser.latestHost)) continue;
}
rangelockedUsers[range][curUser.userid] = 1;
curUser.locked = '#range';
curUser.send("|popup|You are in a range that has been temporarily locked from talking in chats and PMing regular users.");
curUser.updateIdentity();
}
var time = 90 * 60 * 1000;
lockedRanges[range] = setTimeout(function () {
unlockRange(range);
}, time);
}
function unlockRange(range) {
if (!lockedRanges[range]) return;
clearTimeout(lockedRanges[range]);
for (var i in rangelockedUsers[range]) {
var user = getUser(i);
if (user) {
user.locked = false;
user.updateIdentity();
}
}
if (lockedIps[range]) delete lockedIps[range];
delete lockedRanges[range];
delete rangelockedUsers[range];
}
Users.unban = unban;
Users.unlock = unlock;
Users.lockRange = lockRange;
Users.unlockRange = unlockRange;
/*********************************************************
* Routing
*********************************************************/
var connections = Users.connections = Object.create(null);
Users.shortenHost = function (host) {
var dotIndex = host.lastIndexOf('.');
if (host.substr(-6, 4) === '.co.') dotIndex = host.length - 6;
if (dotIndex >= 1) dotIndex = host.lastIndexOf('.', dotIndex - 1);
var shortHost = (dotIndex >= 1 ? host.substr(dotIndex + 1) : host);
return shortHost;
};
Users.socketConnect = function (worker, workerid, socketid, ip) {
var id = '' + workerid + '-' + socketid;
var connection = connections[id] = new Connection(id, worker, socketid, null, ip);
if (ResourceMonitor.countConnection(ip)) {
connection.destroy();
bannedIps[ip] = '#cflood';
return;
}
var checkResult = Users.checkBanned(ip);
if (!checkResult && Users.checkRangeBanned(ip)) {
checkResult = '#ipban';
}
if (checkResult) {
console.log('CONNECT BLOCKED - IP BANNED: ' + ip + ' (' + checkResult + ')');
if (checkResult === '#ipban') {
connection.send("|popup|Your IP (" + ip + ") is not allowed to connect to PS, because it has been used to spam, hack, or otherwise attack our server.||Make sure you are not using any proxies to connect to PS.");
} else if (checkResult === '#cflood') {
connection.send("|popup|PS is under heavy load and cannot accommodate your connection right now.");
} else {
connection.send("|popup|Your IP (" + ip + ") used is banned under the username '" + checkResult + "'. Your ban will expire in a few days.||" + (Config.appealurl ? " Or you can appeal at:\n" + Config.appealurl : ""));
}
return connection.destroy();
}
// Emergency mode connections logging
if (Config.emergency) {
fs.appendFile('logs/cons.emergency.log', '[' + ip + ']\n', function (err) {
if (err) {
console.log('!! Error in emergency conns log !!');
throw err;
}
});
}
var user = new User(connection);
connection.user = user;
// Generate 1024-bit challenge string.
require('crypto').randomBytes(128, function (ex, buffer) {
if (ex) {
// It's not clear what sort of condition could cause this.
// For now, we'll basically assume it can't happen.
console.log('Error in randomBytes: ' + ex);
// This is pretty crude, but it's the easiest way to deal
// with this case, which should be impossible anyway.
user.disconnectAll();
} else if (connection.user) { // if user is still connected
connection.challenge = buffer.toString('hex');
// console.log('JOIN: ' + connection.user.name + ' [' + connection.challenge.substr(0, 15) + '] [' + socket.id + ']');
var keyid = Config.loginserverpublickeyid || 0;
connection.sendTo(null, '|challstr|' + keyid + '|' + connection.challenge);
}
});
dns.reverse(ip, function (err, hosts) {
if (hosts && hosts[0]) {
user.latestHost = hosts[0];
if (Config.hostfilter) Config.hostfilter(hosts[0], user);
if (user.named && !user.locked && user.group === Config.groupsranking[0]) {
var shortHost = Users.shortenHost(hosts[0]);
if (lockedRanges[shortHost]) {
user.send("|popup|You are in a range that has been temporarily locked from talking in chats and PMing regular users.");
rangelockedUsers[shortHost][user.userid] = 1;
user.locked = '#range';
user.updateIdentity();
}
}
}
});
user.joinRoom('global', connection);
Dnsbl.query(connection.ip, function (isBlocked) {
if (isBlocked) {
connection.popup("Your IP is known for spamming or hacking websites and has been locked. If you're using a proxy, don't.");
if (connection.user && !connection.user.locked) {
connection.user.locked = '#dnsbl';
connection.user.updateIdentity();
}
}
});
};
Users.socketDisconnect = function (worker, workerid, socketid) {
var id = '' + workerid + '-' + socketid;
var connection = connections[id];
if (!connection) return;
connection.onDisconnect();
};
Users.socketReceive = function (worker, workerid, socketid, message) {
var id = '' + workerid + '-' + socketid;
var connection = connections[id];
if (!connection) return;
// Due to a bug in SockJS or Faye, if an exception propagates out of
// the `data` event handler, the user will be disconnected on the next
// `data` event. To prevent this, we log exceptions and prevent them
// from propagating out of this function.
// drop legacy JSON messages
if (message.substr(0, 1) === '{') return;
// drop invalid messages without a pipe character
var pipeIndex = message.indexOf('|');
if (pipeIndex < 0) return;
var roomid = message.substr(0, pipeIndex);
var lines = message.substr(pipeIndex + 1);
var room = Rooms.get(roomid);
if (!room) room = Rooms.lobby || Rooms.global;
var user = connection.user;
if (!user) return;
if (lines.substr(0, 3) === '>> ' || lines.substr(0, 4) === '>>> ') {
user.chat(lines, room, connection);
return;
}
lines = lines.split('\n');
if (lines.length >= THROTTLE_MULTILINE_WARN) {
connection.popup("You're sending too many lines at once. Try using a paste service like [[Pastebin]].");
return;
}
// Emergency logging
if (Config.emergency) {
fs.appendFile('logs/emergency.log', '[' + user + ' (' + connection.ip + ')] ' + message + '\n', function (err) {
if (err) {
console.log('!! Error in emergency log !!');
throw err;
}
});
}
for (var i = 0; i < lines.length; i++) {
if (user.chat(lines[i], room, connection) === false) break;
}
};
/*********************************************************
* User groups
*********************************************************/
var usergroups = Users.usergroups = Object.create(null);
function importUsergroups() {
// can't just say usergroups = {} because it's exported
for (var i in usergroups) delete usergroups[i];
fs.readFile('config/usergroups.csv', function (err, data) {
if (err) return;
data = ('' + data).split("\n");
for (var i = 0; i < data.length; i++) {
if (!data[i]) continue;
var row = data[i].split(",");
usergroups[toId(row[0])] = (row[1] || Config.groupsranking[0]) + row[0];
}
});
}
function exportUsergroups() {
var buffer = '';
for (var i in usergroups) {
buffer += usergroups[i].substr(1).replace(/,/g, '') + ',' + usergroups[i].substr(0, 1) + "\n";
}
fs.writeFile('config/usergroups.csv', buffer);
}
importUsergroups();
Users.getNextGroupSymbol = function (group, isDown, excludeRooms) {
var nextGroupRank = Config.groupsranking[Config.groupsranking.indexOf(group) + (isDown ? -1 : 1)];
if (excludeRooms === true && Config.groups[nextGroupRank]) {
var iterations = 0;
while (Config.groups[nextGroupRank].roomonly && iterations < 10) {
nextGroupRank = Config.groupsranking[Config.groupsranking.indexOf(group) + (isDown ? -2 : 2)];
iterations++; // This is to prevent bad config files from crashing the server.
}
}
if (!nextGroupRank) {
if (isDown) {
return Config.groupsranking[0];
} else {
return Config.groupsranking[Config.groupsranking.length - 1];
}
}
return nextGroupRank;
};
Users.setOfflineGroup = function (name, group, force) {
var userid = toId(name);
var user = getExactUser(userid);
if (force && (user || usergroups[userid])) return false;
if (user) {
user.setGroup(group);
return true;
}
if (!group || group === Config.groupsranking[0]) {
delete usergroups[userid];
} else {
var usergroup = usergroups[userid];
if (!usergroup && !force) return false;
name = usergroup ? usergroup.substr(1) : name;
usergroups[userid] = group + name;
}
exportUsergroups();
return true;
};
Users.importUsergroups = importUsergroups;
/*********************************************************
* User and Connection classes
*********************************************************/
// User
User = (function () {
function User(connection) {
numUsers++;
this.mmrCache = {};
this.guestNum = numUsers;
this.name = 'Guest ' + numUsers;
this.named = false;
this.renamePending = false;
this.authenticated = false;
this.userid = toId(this.name);
this.group = Config.groupsranking[0];
var 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 = {};
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.mutedRooms = {};
this.muteDuration = {};
this.locked = Users.checkLocked(connection.ip);
this.prevNames = {};
this.battles = {};
this.roomCount = {};
// challenges
this.challengesFrom = {};
this.challengeTo = null;
this.lastChallenge = 0;
// initialize
users[this.userid] = this;
}
User.prototype.isSysop = false;
User.prototype.forceRenamed = false;
// for the anti-spamming mechanism
User.prototype.lastMessage = '';
User.prototype.lastMessageTime = 0;
User.prototype.lastReportTime = 0;
User.prototype.blockChallenges = false;
User.prototype.ignorePMs = false;
User.prototype.lastConnected = 0;
User.prototype.sendTo = function (roomid, data) {
if (roomid && roomid.id) roomid = roomid.id;
if (roomid && roomid !== 'global' && roomid !== 'lobby') data = '>' + roomid + '\n' + data;
for (var i = 0; i < this.connections.length; i++) {
if (roomid && !this.connections[i].rooms[roomid]) continue;
this.connections[i].send(data);
ResourceMonitor.countNetworkUse(data.length);
}
};
User.prototype.send = function (data) {
for (var i = 0; i < this.connections.length; i++) {
this.connections[i].send(data);
ResourceMonitor.countNetworkUse(data.length);
}
};
User.prototype.popup = function (message) {
this.send('|popup|' + message.replace(/\n/g, '||'));
};
User.prototype.getIdentity = function (roomid) {
if (this.locked) {
return '‽' + this.name;
}
if (roomid) {
if (this.mutedRooms[roomid]) {
return '!' + this.name;
}
var room = Rooms.rooms[roomid];
if (room && room.auth) {
if (room.auth[this.userid]) {
return room.auth[this.userid] + this.name;
}
if (room.isPrivate === true) return ' ' + this.name;
}
}
return this.group + this.name;
};
User.prototype.isStaff = false;
User.prototype.can = function (permission, target, room) {
if (this.hasSysopAccess()) return true;
var group = this.group;
var targetGroup = '';
if (target) targetGroup = target.group;
var groupData = Config.groups[group];
var checkedGroups = {};
// does not inherit
if (groupData && groupData['root']) {
return true;
}
if (room && room.auth) {
if (room.auth[this.userid]) {
group = room.auth[this.userid];
} else if (room.isPrivate === true) {
group = ' ';
}
groupData = Config.groups[group];
if (target) {
if (room.auth[target.userid]) {
targetGroup = room.auth[target.userid];
} else if (room.isPrivate === true) {
targetGroup = ' ';
}
}
}
if (typeof target === 'string') targetGroup = target;
while (groupData) {
// Cycle checker
if (checkedGroups[group]) return false;
checkedGroups[group] = true;
if (groupData[permission]) {
var 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.indexOf(targetGroup) >= 0) {
return true;
}
if (jurisdiction.indexOf('s') >= 0 && target === this) {
return true;
}
if (jurisdiction.indexOf('u') >= 0 && Config.groupsranking.indexOf(group) > Config.groupsranking.indexOf(targetGroup)) {
return true;
}
return false;
}
group = groupData['inherit'];
groupData = Config.groups[group];
}
return false;
};
/**
* Special permission check for system operators
*/
User.prototype.hasSysopAccess = function () {
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.
*/
User.prototype.hasConsoleAccess = function (connection) {
if (this.hasSysopAccess()) return true;
if (!this.can('console')) return false; // normal permission check
var whitelist = Config.consoleips || ['127.0.0.1'];
if (whitelist.indexOf(connection.ip) >= 0) {
return true; // on the IP whitelist
}
if (!this.forceRenamed && (whitelist.indexOf(this.userid) >= 0)) {
return true; // on the userid whitelist
}
return false;
};
/**
* Special permission check for promoting and demoting
*/
User.prototype.canPromote = function (sourceGroup, targetGroup) {
return this.can('promote', {group:sourceGroup}) && this.can('promote', {group:targetGroup});
};
User.prototype.forceRename = function (name, authenticated, forcible) {
// skip the login server
var userid = toId(name);
if (users[userid] && users[userid] !== this) {
return false;
}
if (this.named) this.prevNames[this.userid] = this.name;
if (authenticated === undefined && userid === this.userid) {
authenticated = this.authenticated;
}
if (userid !== this.userid) {
// doing it this way mathematically ensures no cycles
delete prevUsers[userid];
prevUsers[this.userid] = userid;
// also MMR is different for each userid
this.mmrCache = {};
}
if (authenticated && userid in bannedUsers) {
var bannedUnder = '';
if (bannedUsers[userid] !== userid) bannedUnder = ' under the username ' + bannedUsers[userid];
this.send("|popup|Your username (" + name + ") is banned" + bannedUnder + "'. Your ban will expire in a few days." + (Config.appealurl ? " Or you can appeal at:\n" + Config.appealurl : ""));
this.ban(true, userid);
return;
}
if (authenticated && userid in lockedUsers) {
var bannedUnder = '';
if (lockedUsers[userid] !== userid) bannedUnder = ' under the username ' + lockedUsers[userid];
this.send("|popup|Your username (" + name + ") is locked" + bannedUnder + "'. Your lock will expire in a few days." + (Config.appealurl ? " Or you can appeal at:\n" + Config.appealurl : ""));
this.lock(true, userid);
}
if (this.group === Config.groupsranking[0]) {
var range = this.locked || Users.shortenHost(this.latestHost);
if (lockedRanges[range]) {
this.send("|popup|You are in a range that has been temporarily locked from talking in chats and PMing regular users.");
rangelockedUsers[range][this.userid] = 1;
this.locked = '#range';
this.updateIdentity();
}
} else if (this.locked && (this.locked === '#range' || lockedRanges[this.locked])) {
this.locked = false;
this.updateIdentity();
}
this.name = name;
var oldid = this.userid;
delete users[oldid];
this.userid = userid;
users[userid] = this;
this.authenticated = !!authenticated;
this.forceRenamed = !!forcible;
for (var i = 0; i < this.connections.length; i++) {
//console.log('' + name + ' renaming: socket ' + i + ' of ' + this.connections.length);
var initdata = '|updateuser|' + this.name + '|' + (true ? '1' : '0') + '|' + this.avatar;
this.connections[i].send(initdata);
}
var joining = !this.named;
this.named = (this.userid.substr(0, 5) !== 'guest');
for (var i in this.roomCount) {
Rooms.get(i, 'lobby').onRename(this, oldid, joining);
}
return true;
};
User.prototype.resetName = function () {
var name = 'Guest ' + this.guestNum;
var userid = toId(name);
if (this.userid === userid) return;
var i = 0;
while (users[userid] && users[userid] !== this) {
this.guestNum++;
name = 'Guest ' + this.guestNum;
userid = toId(name);
if (i > 1000) return false;
}
if (this.named) this.prevNames[this.userid] = this.name;
delete prevUsers[userid];
prevUsers[this.userid] = userid;
this.name = name;
var oldid = this.userid;
delete users[oldid];
this.userid = userid;
users[this.userid] = this;
this.authenticated = false;
this.group = Config.groupsranking[0];
this.isStaff = false;
this.isSysop = false;
for (var i = 0; i < this.connections.length; i++) {
// console.log('' + name + ' renaming: connection ' + i + ' of ' + this.connections.length);
var initdata = '|updateuser|' + this.name + '|' + (false ? '1' : '0') + '|' + this.avatar;
this.connections[i].send(initdata);
}
this.named = false;
for (var i in this.roomCount) {
Rooms.get(i, 'lobby').onRename(this, oldid, false);
}
return true;
};
User.prototype.updateIdentity = function (roomid) {
if (roomid) {
return Rooms.get(roomid, 'lobby').onUpdateIdentity(this);
}
for (var i in this.roomCount) {
Rooms.get(i, 'lobby').onUpdateIdentity(this);
}
};
User.prototype.filterName = function (name) {
if (Config.namefilter) {
name = Config.namefilter(name);
}
name = toName(name);
name = name.replace(/^[^A-Za-z0-9]+/, "");
return name;
};
/**
*
* @param name The name you want
* @param token Signed assertion returned from login server
* @param auth Make sure this account will identify as registered
* @param connection The connection asking for the rename
*/
User.prototype.rename = function (name, token, auth, connection) {
for (var i in this.roomCount) {
var room = Rooms.get(i);
if (room && room.rated && (this.userid === room.rated.p1 || this.userid === room.rated.p2)) {
this.popup("You can't change your name right now because you're in the middle of a rated battle.");
return false;
}
}
var challenge = '';
if (connection) {
challenge = connection.challenge;
}
if (!name) name = '';
name = this.filterName(name);
var userid = toId(name);
if (this.authenticated) auth = false;
if (!userid) {
// 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|' + "|You did not specify a name or your name was invalid.");
return false;
} else {
if (userid === this.userid && !auth) {
return this.forceRename(name, this.authenticated, this.forceRenamed);
}
}
if (users[userid] && !users[userid].authenticated && users[userid].connected && !auth) {
this.send('|nametaken|' + name + "|Someone is already using the name \"" + users[userid].name + "\".");
return false;
}
if (token && token.substr(0, 1) !== ';') {
var tokenSemicolonPos = token.indexOf(';');
var tokenData = token.substr(0, tokenSemicolonPos);
var tokenSig = token.substr(tokenSemicolonPos + 1);
this.renamePending = name;
var self = this;
Verifier.verify(tokenData, tokenSig, function (success, tokenData) {
self.finishRename(success, tokenData, token, auth, challenge);
});
} else {
this.send('|nametaken|' + name + "|Your authentication token was invalid.");
}
return false;
};
User.prototype.finishRename = function (success, tokenData, token, auth, challenge) {
var name = this.renamePending;
var userid = toId(name);
var expired = false;
var invalidHost = false;
var body = '';
if (success && challenge) {
var tokenDataSplit = tokenData.split(',');
if (tokenDataSplit.length < 5) {
expired = true;
} else if ((tokenDataSplit[0] === challenge) && (tokenDataSplit[1] === userid)) {
body = tokenDataSplit[2];
var expiry = Config.tokenexpiry || 25 * 60 * 60;
if (Math.abs(parseInt(tokenDataSplit[3], 10) - Date.now() / 1000) > expiry) {
expired = true;
}
if (Config.tokenhosts) {
var host = tokenDataSplit[4];
if (Config.tokenhosts.length === 0) {
Config.tokenhosts.push(host);
console.log('Added ' + host + ' to valid tokenhosts');
require('dns').lookup(host, function (err, address) {
if (err || (address === host)) return;
Config.tokenhosts.push(address);
console.log('Added ' + address + ' to valid tokenhosts');
});
} else if (Config.tokenhosts.indexOf(host) === -1) {
invalidHost = true;
}
}
} else if (tokenDataSplit[1] !== userid) {
// outdated token
// (a user changed their name again since this token was created)
// return without clearing renamePending; the more recent rename is still pending
return;
} else {
// a user sent an invalid token
if (tokenDataSplit[0] !== challenge) {
console.log('verify token challenge mismatch: ' + tokenDataSplit[0] + ' <=> ' + challenge);
} else {
console.log('verify token mismatch: ' + tokenData);
}
}
} else {
if (!challenge) {
console.log('verification failed; no challenge');
} else {
console.log('verify failed: ' + token);
}
}
if (invalidHost) {
console.log('invalid hostname in token: ' + tokenData);
body = '';
this.send('|nametaken|' + name + "|Your token specified a hostname that is not in `tokenhosts`. If this is your server, please read the documentation in config/config.js for help. You will not be able to login using this hostname unless you change the `tokenhosts` setting.");
} else if (expired) {
console.log('verify failed: ' + tokenData);
body = '';
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.");
} else if (body) {
// console.log('BODY: "' + body + '"');
if (users[userid] && !users[userid].authenticated && users[userid].connected) {
if (auth) {
if (users[userid] !== this) users[userid].resetName();
} else {
this.send('|nametaken|' + name + "|Someone is already using the name \"" + users[userid].name + "\".");
return this;
}
}
// if (!this.named) {
// console.log('IDENTIFY: ' + name + ' [' + this.name + '] [' + challenge.substr(0, 15) + ']');
// }
var group = Config.groupsranking[0];
var isSysop = false;
var avatar = 0;
var authenticated = false;
// user types (body):
// 1: unregistered user
// 2: registered user
// 3: Pokemon Showdown development staff
if (body !== '1') {
authenticated = true;
if (Config.customavatars && Config.customavatars[userid]) {
avatar = Config.customavatars[userid];
}
if (usergroups[userid]) {
group = usergroups[userid].substr(0, 1);
}
if (body === '3') {
isSysop = true;
this.autoconfirmed = userid;
} else if (body === '4') {
this.autoconfirmed = userid;
} else if (body === '5') {
this.lock(false, userid);
} else if (body === '6') {
this.ban(false, userid);
}
}
if (users[userid] && users[userid] !== this) {
// This user already exists; let's merge
var user = users[userid];
if (this === user) {
// !!!
return false;
}
for (var i in this.roomCount) {
Rooms.get(i, 'lobby').onLeave(this);
}
if (!user.authenticated) {
if (Object.isEmpty(Object.select(this.ips, user.ips))) {
user.mutedRooms = Object.merge(user.mutedRooms, this.mutedRooms);
user.muteDuration = Object.merge(user.muteDuration, this.muteDuration);
if (user.locked === '#dnsbl' && !this.locked) user.locked = false;
if (!user.locked && this.locked === '#dnsbl') this.locked = false;
if (this.locked) user.locked = this.locked;
this.mutedRooms = {};
this.muteDuration = {};
this.locked = false;
}
}
for (var i = 0; i < this.connections.length; i++) {
//console.log('' + this.name + ' preparing to merge: connection ' + i + ' of ' + this.connections.length);
user.merge(this.connections[i]);
}
this.roomCount = {};
this.connections = [];
// merge IPs
for (var ip in this.ips) {
if (user.ips[ip]) user.ips[ip] += this.ips[ip];
else user.ips[ip] = this.ips[ip];
}
this.ips = {};
user.latestIp = this.latestIp;
this.markInactive();
if (!this.authenticated) {
this.group = Config.groupsranking[0];
this.isStaff = false;
}
this.isSysop = false;
user.group = group;
user.isStaff = (user.group in {'%':1, '@':1, '&':1, '~':1});
user.isSysop = isSysop;
user.forceRenamed = false;
if (avatar) user.avatar = avatar;
user.authenticated = authenticated;
if (userid !== this.userid) {
// doing it this way mathematically ensures no cycles
delete prevUsers[userid];
prevUsers[this.userid] = userid;
}
for (var i in this.prevNames) {
if (!user.prevNames[i]) {
user.prevNames[i] = this.prevNames[i];
}
}
if (this.named) user.prevNames[this.userid] = this.name;