-
Notifications
You must be signed in to change notification settings - Fork 29
/
Copy pathactions.ts
567 lines (518 loc) · 18.6 KB
/
actions.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
/**
* This file handles all loginserver actions. Each of these can be requested by making a request to
* /api/actionname, or to action.php?act=actname
* By Mia
* @author mia-pi-git
*/
import {Config} from './config-loader';
import * as fs from 'fs/promises';
import {Ladder} from './ladder';
import {Replays} from './replays';
import {ActionError, QueryHandler} from './server';
import {toID, updateserver, bash, time} from './utils';
import * as tables from './tables';
import * as pathModule from 'path';
import IPTools from './ip-tools';
import nodemailer from 'nodemailer';
// eslint-disable-next-line
const EMAIL_REGEX = /(?:[a-z0-9!#$%&\'*+\/=?^_`{|}~-]+(?:\.[a-z0-9!#$%&\'*+\/=?^_`{|}~-]+)*|"(?:[\x01-\x08\x0b\x0c\x0e-\x1f\x21\x23-\x5b\x5d-\x7f]|\\[\x01-\x09\x0b\x0c\x0e-\x7f])*")@(?:(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?|\[(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?|[a-z0-9-]*[a-z0-9]:(?:[\x01-\x08\x0b\x0c\x0e-\x1f\x21-\x5a\x53-\x7f]|\\[\x01-\x09\x0b\x0c\x0e-\x7f])+)\])/i;
const mailer = nodemailer.createTransport(Config.passwordemails.transportOpts);
export const actions: {[k: string]: QueryHandler} = {
async register(params) {
this.verifyCrossDomainRequest();
const {username, password, cpassword, captcha} = params;
if (!username) {
throw new ActionError(`You must specify a username.`);
}
const userid = toID(username);
if (!/[a-z]/.test(userid)) {
throw new ActionError(`Your username must include at least one letter.`);
}
if (await tables.users.get(userid)) {
throw new ActionError("Your username is already taken.");
}
if (!password) {
throw new ActionError('You must specify a password.');
}
if (userid.startsWith('guest')) {
throw new ActionError(`Your username cannot start with 'guest'.`);
}
if (password.replace(/\s/ig, '').length < 5) {
throw new ActionError(`Your password must have at least 5 characters.`);
}
if (password !== cpassword) {
throw new ActionError(`Your passwords do not match.`);
}
if (toID(captcha) !== 'pikachu') {
throw new ActionError(`Answer the anti-spam question.`);
}
const regcount = await this.session.getRecentRegistrationCount(2 * 60 * 60);
if (regcount && regcount > 2) {
throw new ActionError(`You cannot register more than 2 names every 2 hours.`);
}
const user = await this.session.addUser(username, password);
if (user === null) {
throw new ActionError(`Your username is already taken.`);
}
const challengekeyid = parseInt(params.challengekeyid!) || -1;
const challenge = params.challstr || params.challenge || "";
if (!challenge) throw new ActionError(`Invalid challenge string argument.`);
const assertion = await this.session.getAssertion(userid, challengekeyid, user, challenge);
return {
assertion,
actionsuccess: !assertion.startsWith(';'),
curuser: {loggedin: true, username, userid},
};
},
async logout(params) {
if (
this.request.method !== "POST" || !params.userid ||
params.userid !== this.user.id || this.user.id === 'guest'
) {
return {actionsuccess: false};
}
await this.session.logout(true);
return {actionsuccess: true};
},
async login(params) {
this.setPrefix('');
const challengeprefix = this.verifyCrossDomainRequest();
if (this.request.method !== 'POST') {
throw new ActionError(`For security reasons, logins must happen with POST data.`);
}
if (!params.name || !params.pass) {
throw new ActionError(`incorrect login data, you need "name" and "pass" fields`);
}
const userid = toID(params.name);
if (!userid) {
throw new ActionError(`incorrect login data, userid must contain at least one letter or number`);
}
const challengekeyid = parseInt(params.challengekeyid!) || -1;
const actionsuccess = await this.session.login(params.name, params.pass);
if (!actionsuccess) return {actionsuccess, assertion: false};
const challenge = params.challstr || params.challenge || "";
const assertion = await this.session.getAssertion(
userid, challengekeyid, null, challenge, challengeprefix
);
await this.session.setSid();
return {
actionsuccess: true,
assertion,
curuser: {loggedin: true, username: params.name, userid},
};
},
async updateuserstats(params) {
const server = await this.requireServer();
const date = parseInt(params.date!);
const usercount = parseInt(params.users! || params.usercount!);
if (isNaN(date) || isNaN(usercount)) {
return {actionsuccess: false};
}
await tables.userstats.replace({
serverid: server.id, date, usercount,
});
if (server.id === Config.mainserver) {
await tables.userstatshistory.insert({date, usercount});
}
return {actionsuccess: true};
},
async upkeep(params) {
const challengeprefix = this.verifyCrossDomainRequest();
const res = {assertion: '', username: '', loggedin: false};
const curuser = this.user;
let userid = '';
if (curuser.id !== 'guest') {
res.username = curuser.name;
userid = curuser.id;
}
if (userid !== '') {
const challengekeyid = !params.challengekeyid ? -1 : parseInt(params.challengekeyid);
const challenge = params.challstr || params.challenge || "";
res.assertion = await this.session.getAssertion(
userid, challengekeyid, curuser, challenge, challengeprefix
);
}
res.loggedin = !!curuser.loggedIn;
return res;
},
json() {
throw new ActionError("Malformed request", 400);
},
async prepreplay(params) {
const server = await this.getServer(true);
if (!server) {
// legacy error
return {errorip: this.getIp()};
}
const extractedFormatId = /^([a-z0-9]+)-[0-9]+$/.exec(`${params.id}`)?.[1];
const formatId = /^([a-z0-9]+)$/.exec(`${params.format}`)?.[1];
if (
// the server must send all the required values
!params.id || !params.format || !params.loghash || !params.p1 || !params.p2 ||
// player usernames cannot be longer than 18 characters
params.p1.length > 18 || params.p2.length > 18 ||
// the battle ID must be valid
!extractedFormatId ||
// the format from the battle ID must match the format ID
formatId !== extractedFormatId
) {
return 0;
}
if (server.id !== Config.mainserver) {
params.id = server.id + '-' + params.id;
}
params.serverid = server.id;
const result = await Replays.prep(params);
this.setPrefix(''); // No need for prefix since only usable by server.
return result;
},
uploadreplay(params) {
this.setHeader('Content-Type', 'text/plain; charset=utf-8');
return Replays.upload(params, this);
},
async invalidatecss() {
const server = await this.requireServer();
// No need to sanitise server['id'] because it should be safe already.
const cssfile = pathModule.join(process.env.CSS_DIR || Config.cssdir, `/${server['id']}.css`);
try {
await fs.unlink(cssfile);
return {actionsuccess: true};
} catch (err) {
return {actionsuccess: false};
}
},
async changepassword(params) {
if (this.request.method !== 'POST') {
throw new ActionError(`'changepassword' requests can only be made with POST data.`);
}
if (!params.oldpassword) {
throw new ActionError(`Specify your current password.`);
}
if (!params.password) {
throw new ActionError(`Specify your new password.`);
}
if (!params.cpassword) {
throw new ActionError(`Repeat your new password.`);
}
if (!this.user.loggedIn) {
throw new ActionError('Your session has expired. Please log in again.');
}
if (params.password !== params.cpassword) {
throw new ActionError('Your new passwords do not match.');
}
if (!(await this.session.passwordVerify(this.user.id, params.oldpassword))) {
throw new ActionError('Your old password was incorrect.');
}
params.password = params.password.replace(/\s/ig, '');
if (params.password.length < 5) {
throw new ActionError('Your new password must be at least 5 characters long.');
}
const actionsuccess = await this.session.changePassword(this.user.id, params.password);
return {actionsuccess};
},
async changeusername(params) {
if (this.request.method !== 'POST') {
throw new ActionError('Invalid request (username changing must be done through POST requests).');
}
if (!params.username) {
throw new ActionError(`Specify a username.`);
}
if (!this.user.loggedIn) {
throw new ActionError('Your session has expired. Please log in again.');
}
if (toID(params.username) !== this.user.id) {
throw new ActionError('You\'re not logged in as that user.');
}
// safe to use userid directly because we've confirmed they've logged in.
const actionsuccess = await tables.users.update(this.user.id, {
username: params.username,
});
await this.session.setSid();
return {actionsuccess};
},
async getassertion(params) {
this.setPrefix('');
params.userid = toID(params.userid) || this.user.id;
// NaN is falsy so this validates
const challengekeyid = Number(params.challengekeyid) || -1;
const challenge = params.challenge || params.challstr || "";
return this.session.getAssertion(
params.userid,
challengekeyid,
this.user,
challenge,
this.verifyCrossDomainRequest()
);
},
async ladderupdate(params) {
const server = await this.getServer(true);
if (server?.id !== Config.mainserver) {
// legacy error
return {errorip: this.getIp()};
}
if (!toID(params.format)) throw new ActionError("Invalid format.");
if (!params.score) throw new ActionError("Score required.");
const ladder = new Ladder(params.format!);
if (!Ladder.isValidPlayer(params.p1)) return 0;
if (!Ladder.isValidPlayer(params.p2)) return 0;
const out: {[k: string]: any} = {};
const [p1rating, p2rating] = await ladder.addMatch(params.p1!, params.p2!, parseFloat(params.score));
out.actionsuccess = true;
out.p1rating = p1rating;
out.p2rating = p2rating;
delete out.p1rating.rpdata;
delete out.p2rating.rpdata;
this.setPrefix(''); // No need for prefix since only usable by server.
return out;
},
async ladderget(params) {
// used by the client; doesn't need a serverid check; Main can be assumed
const user = Ladder.isValidPlayer(params.user);
if (!user) throw new ActionError("Invalid username.");
return Ladder.getAllRatings(user);
},
async mmr(params) {
const server = await this.getServer(true);
if (server?.id !== Config.mainserver) {
// legacy error
return {errorip: "This ladder is not for your server. You should turn off Config.remoteladder."};
}
if (!toID(params.format)) throw new ActionError("Specify a format.");
const ladder = new Ladder(params.format!);
if (!Ladder.isValidPlayer(params.user)) return 1000;
const rating = await ladder.getRating(params.user!);
return rating?.elo || 1000;
},
async restart() {
await this.requireMainServer();
if (!Config.restartip) {
throw new ActionError(`This feature is disabled.`);
}
if (this.getIp() !== Config.restartip) {
throw new ActionError(`Access denied for ${this.getIp()}.`);
}
const update = await updateserver();
let stderr;
[, , stderr] = await bash('npx tsc');
if (stderr) throw new ActionError(`Compilation failed:\n${stderr}`);
[, , stderr] = await bash('npx pm2 reload loginserver');
if (stderr) throw new ActionError(stderr);
return {updated: update, success: true};
},
async updatenamecolor(params) {
await this.requireMainServer();
const userid = toID(params.userid);
if (!userid) {
throw new ActionError('No userid was specified.');
}
const source = toID(params.source);
if ('source' in params && !source) {
throw new ActionError('No color adjustment was specified.');
}
if (userid.length > 18 || source.length > 18) {
throw new ActionError('Usernames can only be 18 characters long');
}
const by = toID(params.by);
if (!by) {
throw new ActionError('Specify the action\'s actor.');
}
if (!Config.colorpath) {
throw new ActionError("Editing custom colors is disabled");
}
const colors = {} as Record<string, string>;
try {
const content = await fs.readFile(Config.colorpath, 'utf-8');
Object.assign(colors, JSON.parse(content));
} catch (e) {
throw new ActionError(`Could not read color file (${e})`);
}
let entry = '';
if (!('source' in params)) {
if (!colors[userid]) {
throw new ActionError(
'That user does not have a custom color set by the loginserver. ' +
'Ask an admin to remove it manually if they have one.'
);
} else {
delete colors[userid];
entry = 'Username color was removed';
}
} else {
colors[userid] = source;
entry = `Username color was set to "${source}"${params.reason ? ` (${params.reason})` : ``}`;
}
await fs.writeFile(Config.colorpath, JSON.stringify(colors));
await tables.usermodlog.insert({
userid, actorid: by, date: time(), ip: this.getIp(), entry,
});
return {success: true};
},
async setstanding(params) {
await this.requireMainServer();
const userid = toID(params.user);
if (!userid) {
throw new ActionError("Target username not specified.");
}
const actor = toID(params.actor);
if (!actor) {
throw new ActionError("The staff executing this action must be specified.");
}
if (!params.reason || !params.reason.length) {
throw new ActionError("A reason must be specified.");
}
const standing = Number(params.standing);
if (isNaN(standing) || !params.standing) {
throw new ActionError("No standing specified.");
}
if (!Config.standings[standing]) {
throw new ActionError("Invalid standing.");
}
const res = await tables.users.update(userid, {
banstate: standing,
});
if (!res.affectedRows) {
throw new ActionError("User not found.");
}
await tables.usermodlog.insert({
actorid: actor,
userid,
date: time(),
ip: this.getIp(),
entry: `Standing changed to ${standing} (${Config.standings[standing]}): ${params.reason}`,
});
return {success: true};
},
async ipstanding(params) {
await this.requireMainServer();
const ip = params.ip?.trim() || "";
if (!IPTools.ipRegex.test(ip)) {
throw new ActionError("Invalid IP provided.");
}
const actor = toID(params.actor);
if (!actor) {
throw new ActionError("The staff executing this action must be specified.");
}
if (!params.reason || !params.reason.length) {
throw new ActionError("A reason must be specified.");
}
const standing = Number(params.standing);
if (isNaN(standing) || !params.standing) {
throw new ActionError("No standing specified.");
}
if (!Config.standings[standing]) {
throw new ActionError("Invalid standing.");
}
const matches = await tables.users.selectAll(['userid'])`ip = ${ip}`;
for (const {userid} of matches) {
await tables.users.update(userid, {banstate: standing});
await tables.usermodlog.insert({
actorid: actor,
userid,
date: time(),
ip: this.getIp(),
entry: `Standing changed to ${standing} (${Config.standings[standing]}): ${params.reason}`,
});
}
return {success: matches.length};
},
async ipmatches(params) {
await this.requireMainServer();
const userid = toID(params.id);
if (!userid) {
throw new ActionError("User not specified.");
}
const res = await tables.users.get(userid);
if (!res) {
throw new ActionError(`User ${userid} not found.`);
}
return {
matches: await tables.users.selectAll(['userid', 'banstate'])`ip = ${res.ip}`,
};
},
async setemail(params) {
if (!this.user.loggedIn) {
throw new ActionError(`You must be logged in to set an email.`);
}
if (!params.email || typeof params.email !== 'string') {
throw new ActionError(`You must send an email address.`);
}
const email = EMAIL_REGEX.exec(params.email)?.[0];
if (!email) throw new ActionError(`Email is invalid or already taken.`);
const data = await tables.users.get(this.user.id);
if (!data) throw new ActionError(`You are not registered.`);
if (data.email?.endsWith('@')) {
throw new ActionError(`You have 2FA, and do not need to set an email for password resets.`);
}
const emailUsed = await tables.users.selectAll(['userid'])`WHERE email = ${email}`;
if (emailUsed.length) {
throw new ActionError(`Email is invalid or already taken.`);
}
const result = await tables.users.update(this.user.id, {email});
delete (data as any).passwordhash;
return {
success: !!result.changedRows,
curuser: {loggedin: true, userid: this.user.id, username: data.username, email},
};
},
async clearemail() {
if (!this.user.loggedIn) {
throw new ActionError(`You must be logged in to edit your email.`);
}
const data = await tables.users.get(this.user.id);
if (!data) throw new ActionError(`You are not registered.`);
if (data.email?.endsWith('@')) {
throw new ActionError(
`You have 2FA, and need an administrator to set/unset your email manually.`
);
}
const result = await tables.users.update(this.user.id, {email: null});
delete (data as any).passwordhash;
return {
actionsuccess: !!result.changedRows,
curuser: {loggedin: true, userid: this.user.id, username: data.username, email: null},
};
},
async resetpassword(params) {
if (typeof params.email !== 'string' || !params.email) {
throw new ActionError(`You must provide an email address.`);
}
const email = EMAIL_REGEX.exec(params.email)?.[0];
if (!email) {
throw new ActionError(`Invalid email sent.`);
}
const data = await tables.users.selectOne()`WHERE email = ${email}`;
if (!data) {
// no user associated with that email.
// ...pretend like it succeeded (we don't wanna leak that it's in use, after all)
return {success: true};
}
if (!data.email) {
// should literally never happen
throw new Error(`Account data found with no email, but had an email match`);
}
if (data.email.endsWith('@')) {
throw new ActionError(`You have 2FA, and so do not need a password reset.`);
}
const token = await this.session.createPasswordResetToken(data.username);
await mailer.sendMail({
from: Config.passwordemails.from,
to: data.email,
subject: "Pokemon Showdown account password reset",
text: (
`You requested a password reset for the Pokemon Showdown account ${data.userid}. Click this link https://${Config.routes.root}/resetpassword/${token} and follow the instructions to change your password.\n` +
`Not you? Please contact staff by typing /ht in any chatroom on Pokemon Showdown. \n` +
`If you are unable to do so, visit the Help chatroom.`
),
html: (
`You requested a password reset for the Pokemon Showdown account ${data.userid}. ` +
`Click <a href="https://${Config.routes.root}/resetpassword/${token}">this link</a> and follow the instructions to change your password.<br />` +
`Not you? Please contact staff by typing <code>/ht</code> in any chatroom on Pokemon Showdown. <br />` +
`If you are unable to do so, visit the <a href="${Config.routes.client}/help">Help</a> chatroom.`
),
});
return {success: true};
},
};
if (Config.actions) {
Object.assign(actions, Config.actions);
}