-
Notifications
You must be signed in to change notification settings - Fork 531
/
index.js
624 lines (551 loc) · 21.9 KB
/
index.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
const modulename = 'AdminVault';
import fse from 'fs-extra';
import fs from 'node:fs';
import fsp from 'node:fs/promises';
import { cloneDeep } from 'lodash-es';
import { nanoid } from 'nanoid';
import { convars, txEnv } from '@core/globalData';
import CitizenFXProvider from './providers/CitizenFX.js';
import { createHash } from 'node:crypto';
import consoleFactory from '@extras/console';
import chalk from 'chalk';
const console = consoleFactory(modulename);
//Helpers
const migrateProviderIdentifiers = (providerName, providerData) => {
if (providerName === 'citizenfx') {
// data may be empty, or nameid may be invalid
try {
const res = /\/user\/(\d{1,8})/.exec(providerData.data.nameid);
providerData.identifier = `fivem:${res[1]}`;
} catch (error) {
providerData.identifier = 'fivem:00000000';
}
} else if (providerName === 'discord') {
providerData.identifier = `discord:${providerData.id}`;
}
};
export default class AdminVault {
constructor() {
this.adminsFile = `${txEnv.dataPath}/admins.json`;
this.adminsFileHash = null;
this.admins = null;
this.refreshRoutine = null;
//Not alphabetical order, but that's fine
this.registeredPermissions = {
'all_permissions': 'All Permissions',
'manage.admins': 'Manage Admins', //will enable the "set admin" button in the player modal
'settings.view': 'Settings: View (no tokens)',
'settings.write': 'Settings: Change',
'console.view': 'Console: View',
'console.write': 'Console: Write',
'control.server': 'Start/Stop Server + Scheduler',
'commands.resources': 'Start/Stop Resources',
'server.cfg.editor': 'Read/Write server.cfg',
'txadmin.log.view': 'View System Logs', //FIXME: rename to system.log.view
'menu.vehicle': 'Spawn / Fix Vehicles',
'menu.clear_area': 'Reset world area',
'menu.viewids': 'View Player IDs in-game', //be able to see the ID of the players
'players.message': 'Announcement / DM', //enable/disable the dm button on modal as well
'players.whitelist': 'Whitelist',
'players.warn': 'Warn',
'players.kick': 'Kick',
'players.ban': 'Ban',
'players.freeze': 'Freeze Players',
'players.heal': 'Heal', //self, everyone, and the "heal" button in player modal
'players.playermode': 'NoClip / God Mode', //self playermode, and also the player spectate option
'players.spectate': 'Spectate', //self playermode, and also the player spectate option
'players.teleport': 'Teleport', //self teleport, and the bring/go to on player modal
'players.troll': 'Troll Actions', //all the troll options in the player modal
};
this.hardConfigs = {
refreshInterval: 15e3,
};
//Load providers
try {
this.providers = {
discord: false,
citizenfx: new CitizenFXProvider(),
};
} catch (error) {
throw new Error(`Failed to load providers with error: ${error.message}`);
}
//Check if admins file exists
let adminFileExists;
try {
fs.statSync(this.adminsFile, fs.constants.F_OK);
adminFileExists = true;
} catch (error) {
if (error.code === 'ENOENT') {
adminFileExists = false;
} else {
throw new Error(`Failed to check presence of admin file with error: ${error.message}`);
}
}
//Printing PIN or starting loop
if (!adminFileExists) {
if (!convars.defaultMasterAccount) {
this.addMasterPin = (Math.random() * 10000).toFixed().padStart(4, '0');
this.admins = false;
} else {
console.log(`Setting up master account '${convars.defaultMasterAccount.name}'. The password is the same as in zap-hosting.com.`);
this.createAdminsFile(convars.defaultMasterAccount.name, false, false, convars.defaultMasterAccount.password_hash, false);
}
} else {
this.loadAdminsFile();
this.setupRefreshRoutine();
}
}
/**
* sets the admins file refresh routine
*/
setupRefreshRoutine() {
this.refreshRoutine = setInterval(() => {
this.checkAdminsFile();
}, this.hardConfigs.refreshInterval);
}
/**
* Creates a admins.json file based on the first account
* @param {string} username
* @param {string} identifier
* @param {object} provider_data
* @param {string} password backup password
* @param {boolean} isPlainText
* @param {string|undefined} discordId
* @returns {(boolean)} true or throws an error
*/
createAdminsFile(username, identifier, provider_data, password, isPlainText, discordId) {
//Sanity check
if (this.admins !== false && this.admins !== null) throw new Error('Admins file already exists.');
if (typeof username !== 'string' || username.length < 3) throw new Error('Invalid username parameter.');
if (typeof password !== 'string' || password.length < 6) throw new Error('Invalid password parameter.');
//Creating admin array
const providers = {};
if (identifier && provider_data) {
providers.citizenfx = {
id: username,
identifier,
data: provider_data,
};
}
if (discordId) {
providers.discord = {
id: discordId,
identifier: `discord:${discordId}`,
data: {},
};
}
const newAdmin = {
name: username,
master: true,
password_hash: (isPlainText) ? GetPasswordHash(password) : password,
providers,
permissions: [],
};
this.admins = [newAdmin];
this.addMasterPin = undefined;
//Saving admin file
try {
const jsonData = JSON.stringify(this.admins);
this.adminsFileHash = createHash('sha1').update(jsonData).digest('hex');
fse.writeFileSync(this.adminsFile, jsonData, { encoding: 'utf8', flag: 'wx' });
this.setupRefreshRoutine();
return newAdmin;
} catch (error) {
let message = `Failed to create '${this.adminsFile}' with error: ${error.message}`;
console.verbose.error(message);
throw new Error(message);
}
}
/**
* Returns a list of admins and permissions
*/
getAdminsList() {
if (this.admins == false) return [];
return this.admins.map((user) => {
return {
name: user.name,
master: user.master,
providers: Object.keys(user.providers),
permissions: user.permissions,
};
});
}
/**
* Returns the raw array of admins, except for the hash
*/
getRawAdminsList() {
if (this.admins === false) return [];
return cloneDeep(this.admins);
}
/**
* Returns all data from an admin by provider user id (ex discord id), or false
* @param {string} uid
*/
getAdminByProviderUID(uid) {
if (this.admins == false) return false;
let id = uid.trim().toLowerCase();
if (!id.length) return false;
let admin = this.admins.find((user) => {
return Object.keys(user.providers).find((provider) => {
return (id === user.providers[provider].id.toLowerCase());
});
});
return (admin) ? cloneDeep(admin) : false;
}
/**
* Returns all data from an admin by their name, or false
* @param {string} uname
*/
getAdminByName(uname) {
if (!this.admins) return false;
const username = uname.trim().toLowerCase();
if (!username.length) return false;
const admin = this.admins.find((user) => {
return (username === user.name.toLowerCase());
});
return (admin) ? cloneDeep(admin) : false;
}
/**
* Returns all data from an admin by game identifier, or false
* @param {string[]} identifiers
*/
getAdminByIdentifiers(identifiers) {
if (!this.admins) return false;
identifiers = identifiers
.map((i) => i.trim().toLowerCase())
.filter((i) => i.length);
if (!identifiers.length) return false;
const admin = this.admins.find((user) =>
identifiers.find((identifier) =>
Object.keys(user.providers).find((provider) =>
(identifier === user.providers[provider].identifier.toLowerCase()))));
return (admin) ? cloneDeep(admin) : false;
}
/**
* Returns a list with all registered permissions
*/
getPermissionsList() {
return cloneDeep(this.registeredPermissions);
}
/**
* Writes to storage the admins file
*/
async writeAdminsFile() {
const jsonData = JSON.stringify(this.admins, null, 2);
this.adminsFileHash = createHash('sha1').update(jsonData).digest('hex');
await fsp.writeFile(this.adminsFile, jsonData, 'utf8');
return true;
}
/**
* Writes to storage the admins file
*/
async checkAdminsFile() {
const restore = async () => {
try {
await this.writeAdminsFile();
console.ok('Restored admins.json file.');
} catch (error) {
console.error(`Failed to restore admins.json file: ${error.message}`);
console.verbose.dir(error);
}
};
try {
const jsonData = await fse.readFile(this.adminsFile, 'utf8');
const inboundHash = createHash('sha1').update(jsonData).digest('hex');
if (this.adminsFileHash !== inboundHash) {
console.warn('The admins.json file was modified or deleted by an external source, txAdmin will try to restore it.');
restore();
}
} catch (error) {
console.error(`Cannot check admins file integrity: ${error.message}`);
restore();
}
}
/**
* Add a new admin to the admins file
* NOTE: I'm fully aware this coud be optimized. Leaving this way to improve readability and error verbosity
* @param {string} name
* @param {object|undefined} citizenfxData or false
* @param {object|undefined} discordData or false
* @param {string} password
* @param {array} permissions
*/
async addAdmin(name, citizenfxData, discordData, password, permissions) {
if (this.admins == false) throw new Error('Admins not set');
//Check if username is already taken
if (this.getAdminByName(name)) throw new Error('Username already taken');
//Preparing admin
const admin = {
name: name,
master: false,
password_hash: GetPasswordHash(password),
password_temporary: true,
providers: {},
permissions: permissions,
};
//Check if provider uid already taken and inserting into admin object
if (citizenfxData) {
const existingCitizenFX = this.getAdminByProviderUID(citizenfxData.id);
if (existingCitizenFX) throw new Error('CitizenFX ID already taken');
admin.providers.citizenfx = {
id: citizenfxData.id,
identifier: citizenfxData.identifier,
data: {},
};
}
if (discordData) {
const existingDiscord = this.getAdminByProviderUID(discordData.id);
if (existingDiscord) throw new Error('Discord ID already taken');
admin.providers.discord = {
id: discordData.id,
identifier: discordData.identifier,
data: {},
};
}
//Saving admin file
this.admins.push(admin);
this.refreshOnlineAdmins().catch((e) => { });
try {
return await this.writeAdminsFile();
} catch (error) {
throw new Error(`Failed to save admins.json with error: ${error.message}`);
}
}
/**
* Edit admin and save to the admins file
* @param {string} name
* @param {string|null} password
* @param {object|undefined} citizenfxData or false
* @param {object|undefined} discordData or false
* @param {array|undefined} permissions
*/
async editAdmin(name, password, citizenfxData, discordData, permissions) {
if (this.admins == false) throw new Error('Admins not set');
//Find admin index
let username = name.toLowerCase();
let adminIndex = this.admins.findIndex((user) => {
return (username === user.name.toLowerCase());
});
if (adminIndex == -1) throw new Error('Admin not found');
//Editing admin
if (password !== null) {
this.admins[adminIndex].password_hash = GetPasswordHash(password);
delete this.admins[adminIndex].password_temporary;
}
if (typeof citizenfxData !== 'undefined') {
if (!citizenfxData) {
delete this.admins[adminIndex].providers.citizenfx;
} else {
this.admins[adminIndex].providers.citizenfx = {
id: citizenfxData.id,
identifier: citizenfxData.identifier,
data: {},
};
}
}
if (typeof discordData !== 'undefined') {
if (!discordData) {
delete this.admins[adminIndex].providers.discord;
} else {
this.admins[adminIndex].providers.discord = {
id: discordData.id,
identifier: discordData.identifier,
data: {},
};
}
}
if (typeof permissions !== 'undefined') this.admins[adminIndex].permissions = permissions;
//Prevent race condition, will allow the session to be updated before refreshing socket.io
//sessions which will cause reauth and closing of the temp password modal on first access
setTimeout(() => {
this.refreshOnlineAdmins().catch((e) => { });
}, 250);
//Saving admin file
try {
await this.writeAdminsFile();
return (password !== null) ? this.admins[adminIndex].password_hash : true;
} catch (error) {
throw new Error(`Failed to save admins.json with error: ${error.message}`);
}
}
/**
* Refreshes admin's social login data
* TODO: this should be stored on PersistentCache instead of admins.json
* otherwise it refreshes the admins connected
* @param {string} name
* @param {string} provider
* @param {string} identifier
* @param {object} providerData
*/
async refreshAdminSocialData(name, provider, identifier, providerData) {
if (this.admins == false) throw new Error('Admins not set');
//Find admin index
const username = name.toLowerCase();
const adminIndex = this.admins.findIndex((user) => {
return (username === user.name.toLowerCase());
});
if (adminIndex == -1) throw new Error('Admin not found');
//Refresh admin data
if (!this.admins[adminIndex].providers[provider]) throw new Error('Provider not available for this admin');
this.admins[adminIndex].providers[provider].identifier = identifier;
this.admins[adminIndex].providers[provider].data = providerData;
//Saving admin file
this.refreshOnlineAdmins().catch((e) => { });
try {
return await this.writeAdminsFile();
} catch (error) {
throw new Error(`Failed to save admins.json with error: ${error.message}`);
}
}
/**
* Delete admin and save to the admins file
* @param {string} name
*/
async deleteAdmin(name) {
if (this.admins == false) throw new Error('Admins not set');
//Delete admin
let username = name.toLowerCase();
let found = false;
this.admins = this.admins.filter((user) => {
if (username !== user.name.toLowerCase()) {
return true;
} else {
found = true;
return false;
}
});
if (!found) throw new Error('Admin not found');
//Saving admin file
this.refreshOnlineAdmins().catch((e) => { });
try {
return await this.writeAdminsFile();
} catch (error) {
throw new Error(`Failed to save admins.json with error: ${error.message}`);
}
}
/**
* Loads the admins.json file into the admins list
* NOTE: The verbosity here is driving me insane.
* But still seems not to be enough for people that don't read the README.
*/
async loadAdminsFile() {
let raw = null;
let jsonData = null;
let migrated = false;
const callError = (reason) => {
console.error(`Unable to load admins.json: ${reason}`);
if (reason === 'cannot read file') {
console.error('This means the file doesn\'t exist or txAdmin doesn\'t have permission to read it.');
} else {
console.error('This likely means the file got somehow corrupted.');
console.error('You can try restoring it or you can delete it and let txAdmin create a new one.');
}
console.error(`Admin File Path: ${this.adminsFile}`);
process.exit(5300);
};
try {
raw = await fsp.readFile(this.adminsFile, 'utf8');
this.adminsFileHash = createHash('sha1').update(raw).digest('hex');
} catch (error) {
return callError('cannot read file');
}
if (!raw.length) {
return callError('empty file');
}
try {
jsonData = JSON.parse(raw);
} catch (error) {
return callError('json parse error');
}
if (!Array.isArray(jsonData)) {
return callError('not an array');
}
if (!jsonData.length) {
return callError('no admins');
}
const structureIntegrityTest = jsonData.some((x) => {
if (typeof x.name !== 'string' || x.name.length < 3) return true;
if (typeof x.master !== 'boolean') return true;
if (typeof x.password_hash !== 'string' || !x.password_hash.startsWith('$2')) return true;
if (typeof x.providers !== 'object') return true;
const providersTest = Object.keys(x.providers).some((y) => {
if (!Object.keys(this.providers).includes(y)) return true;
if (typeof x.providers[y].id !== 'string' || x.providers[y].id.length < 3) return true;
if (typeof x.providers[y].data !== 'object') return true;
if (typeof x.providers[y].identifier === 'string') {
if (x.providers[y].identifier.length < 3) return true;
} else {
migrateProviderIdentifiers(y, x.providers[y]);
migrated = true;
}
});
if (providersTest) return true;
if (!Array.isArray(x.permissions)) return true;
return false;
});
if (structureIntegrityTest) {
return callError('invalid data in the admins file');
}
const masters = jsonData.filter((x) => { return x.master; });
if (masters.length !== 1) {
return callError('must have exactly 1 master account');
}
this.admins = jsonData;
//NOTE: since this runs only at the start, nobody is online yet
// this.refreshOnlineAdmins().catch((e) => { });
if (migrated) {
try {
await this.writeAdminsFile();
console.ok('The admins.json file was migrated to a new version.');
} catch (error) {
console.error(`Failed to migrate admins.json with error: ${error.message}`);
}
}
return true;
}
/**
* Notify game server about admin changes
*/
async refreshOnlineAdmins() {
//Refresh auth of all admins connected to socket.io
globals.webServer.webSocket.reCheckAdminAuths().catch((e) => { });
//Refresh in-game auth of all admins connected to the server
if (globals.playerlistManager === null) return;
try {
//Getting all admin identifiers
const adminIDs = this.admins.reduce((ids, adm) => {
const adminIDs = Object.keys(adm.providers).map((pName) => adm.providers[pName].identifier);
return ids.concat(adminIDs);
}, []);
//Finding online admins
const playerList = globals.playerlistManager.getPlayerList();
const onlineIDs = playerList.filter((p) => {
return p.ids.some((i) => adminIDs.includes(i));
}).map((p) => p.netid);
globals.fxRunner.sendEvent('adminsUpdated', onlineIDs);
} catch (error) {
console.verbose.error('Failed to refreshOnlineAdmins() with error:');
console.verbose.dir(error);
}
}
/**
* Returns a random token to be used as CSRF Token.
*/
genCsrfToken() {
return nanoid();
}
/**
* Checks if there are admins configured or not.
* Optionally, prints the master PIN on the console.
*/
hasAdmins(printPin = false) {
if (Array.isArray(this.admins) && this.admins.length) {
return true;
} else {
if (printPin) {
console.warn('Use this PIN to add a new master account: ' + chalk.inverse(` ${this.addMasterPin} `));
}
return false;
}
}
};