-
Notifications
You must be signed in to change notification settings - Fork 529
/
save.ts
533 lines (485 loc) · 20.2 KB
/
save.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
const modulename = 'WebServer:SettingsSave';
import fsp from 'node:fs/promises';
import path from 'node:path';
import slash from 'slash';
import { jsonrepair } from 'jsonrepair';
import { parseSchedule, anyUndefined } from '@core/extras/helpers';
import { resolveCFGFilePath } from '@core/extras/fxsConfigHelper';
import { generateStatusMessage } from '@core/components/DiscordBot/commands/status';
import consoleFactory from '@extras/console';
import { AuthedCtx } from '@core/components/WebServer/ctxTypes';
const console = consoleFactory(modulename);
//Helper functions
const isUndefined = (x: unknown) => (typeof x === 'undefined');
/**
* Handle all the server control actions
*/
export default async function SettingsSave(ctx: AuthedCtx) {
//Sanity check
if (isUndefined(ctx.params.scope)) {
return ctx.utils.error(400, 'Invalid Request');
}
let scope = ctx.params.scope;
//Check permissions
if (!ctx.admin.testPermission('settings.write', modulename)) {
return ctx.send({
type: 'danger',
message: 'You don\'t have permission to execute this action.',
});
}
//Delegate to the specific scope functions
if (scope == 'global') {
return await handleGlobal(ctx);
} else if (scope == 'fxserver') {
return await handleFXServer(ctx);
} else if (scope == 'playerDatabase') {
return await handlePlayerDatabase(ctx);
} else if (scope == 'monitor') {
return await handleMonitor(ctx);
} else if (scope == 'discord') {
return await handleDiscord(ctx);
} else if (scope == 'menu') {
return await handleMenu(ctx);
} else {
return ctx.send({
type: 'danger',
message: 'Unknown settings scope.',
});
}
};
//================================================================
/**
* Handle Global settings
*/
async function handleGlobal(ctx: AuthedCtx) {
//Sanity check
if (
isUndefined(ctx.request.body.serverName)
|| isUndefined(ctx.request.body.language)
) {
return ctx.utils.error(400, 'Invalid Request - missing parameters');
}
//Prepare body input
const cfg = {
serverName: ctx.request.body.serverName.trim(),
language: ctx.request.body.language.trim(),
};
//Trying to load language file
try {
ctx.txAdmin.translator.getLanguagePhrases(cfg.language);
} catch (error) {
return ctx.send({
type: 'danger',
markdown: true,
message: `**Language error:** ${(error as Error).message}`
});
}
//Preparing & saving config
const newConfig = ctx.txAdmin.configVault.getScopedStructure('global');
newConfig.serverName = cfg.serverName;
newConfig.language = cfg.language;
try {
ctx.txAdmin.configVault.saveProfile('global', newConfig);
} catch (error) {
console.warn(`[${ctx.admin.name}] Error changing global settings.`);
console.verbose.dir(error);
return ctx.send({
type: 'danger',
markdown: true,
message: `**Error saving the configuration file:** ${(error as Error).message}`
});
}
//Sending output
ctx.txAdmin.refreshConfig();
ctx.txAdmin.translator.refreshConfig();
ctx.admin.logAction('Changing global settings.');
return ctx.send({ type: 'success', markdown: true, message: '**Global configuration saved!**' });
}
//================================================================
/**
* Handle FXServer settings
*/
async function handleFXServer(ctx: AuthedCtx) {
//Sanity check
if (
isUndefined(ctx.request.body.serverDataPath)
|| isUndefined(ctx.request.body.cfgPath)
|| isUndefined(ctx.request.body.commandLine)
|| isUndefined(ctx.request.body.onesync)
|| isUndefined(ctx.request.body.autostart)
|| isUndefined(ctx.request.body.quiet)
) {
return ctx.utils.error(400, 'Invalid Request - missing parameters');
}
//Prepare body input
const cfg = {
serverDataPath: slash(path.normalize(ctx.request.body.serverDataPath + '/')),
cfgPath: slash(path.normalize(ctx.request.body.cfgPath)),
commandLine: ctx.request.body.commandLine.trim(),
onesync: ctx.request.body.onesync,
autostart: (ctx.request.body.autostart === 'true'),
quiet: (ctx.request.body.quiet === 'true'),
};
//Validating Base Path
try {
const resPath = path.join(cfg.serverDataPath, 'resources');
const resStat = await fsp.stat(resPath);
if (!resStat.isDirectory()) {
throw new Error("Couldn't locate or read a resources folder inside of the base path.");
}
} catch (error) {
const msg = cfg.serverDataPath.includes('resources')
? 'Looks like this path is the \'resources\' folder, but the server data path must be the folder that contains the resources folder instead of the resources folder itself.'
: (error as Error).message;
return ctx.send({ type: 'danger', message: `<strong>Server Data Folder error:</strong> ${msg}` });
}
//Validating CFG Path
try {
const cfgFilePath = resolveCFGFilePath(cfg.cfgPath, cfg.serverDataPath);
const cfgFileStat = await fsp.stat(cfgFilePath);
if (!cfgFileStat.isFile()) {
throw new Error('The path provided is not a file');
}
} catch (error) {
return ctx.send({ type: 'danger', message: `<strong>CFG Path error:</strong> ${(error as Error).message}` });
}
//Preparing & saving config
const newConfig = ctx.txAdmin.configVault.getScopedStructure('fxRunner');
newConfig.serverDataPath = cfg.serverDataPath;
newConfig.cfgPath = cfg.cfgPath;
newConfig.onesync = cfg.onesync;
newConfig.autostart = cfg.autostart;
newConfig.quiet = cfg.quiet;
newConfig.commandLine = cfg.commandLine;
try {
ctx.txAdmin.configVault.saveProfile('fxRunner', newConfig);
} catch (error) {
console.warn(`[${ctx.admin.name}] Error changing FXServer settings.`);
console.verbose.dir(error);
return ctx.send({
type: 'danger',
markdown: true,
message: `**Error saving the configuration file:** ${(error as Error).message}`
});
}
//Sending output
ctx.txAdmin.fxRunner.refreshConfig();
ctx.admin.logAction('Changing fxRunner settings.');
return ctx.send({
type: 'success',
markdown: true,
message: `**FXServer configuration saved!**
You need to restart the server for the changes to take effect.`
});
}
//================================================================
/**
* Handle Player Database settings
*/
async function handlePlayerDatabase(ctx: AuthedCtx) {
//Sanity check
if (anyUndefined(
ctx.request.body,
ctx.request.body.onJoinCheckBan,
ctx.request.body.whitelistMode,
ctx.request.body.whitelistedDiscordRoles,
ctx.request.body.whitelistRejectionMessage,
ctx.request.body.requiredBanHwidMatches,
ctx.request.body.banRejectionMessage,
)) {
return ctx.utils.error(400, 'Invalid Request - missing parameters');
}
//Prepare body input
const cfg = {
whitelistMode: ctx.request.body.whitelistMode.trim(),
whitelistRejectionMessage: ctx.request.body.whitelistRejectionMessage.trim(),
onJoinCheckBan: (ctx.request.body.onJoinCheckBan === 'true'),
requiredBanHwidMatches: parseInt(ctx.request.body.requiredBanHwidMatches),
banRejectionMessage: ctx.request.body.banRejectionMessage.trim(),
whitelistedDiscordRoles: ctx.request.body.whitelistedDiscordRoles
.split(',')
.map((x: string) => x.trim())
.filter((x: string) => x.length),
};
//Validating Discord whitelisted roles
if (cfg.whitelistMode === 'guildRoles' && !cfg.whitelistedDiscordRoles.length) {
return ctx.send({
type: 'danger',
message: 'The whitelisted roles field is required when the whitelist mode is set to Discord Guild Role'
});
}
const invalidRoleInputs = cfg.whitelistedDiscordRoles.filter((x: string) => !/^\d{17,20}$/.test(x));
if (invalidRoleInputs.length) {
return ctx.send({
type: 'danger',
message: `The whitelist role(s) "${invalidRoleInputs.join(', ')}" do not appear to be valid`
});
}
//Validating HWID bans
if (typeof cfg.requiredBanHwidMatches !== 'number' || isNaN(cfg.requiredBanHwidMatches)) {
return ctx.send({ type: 'danger', message: 'requiredBanHwidMatches must be a number.' });
}
if (cfg.requiredBanHwidMatches < 0 || cfg.requiredBanHwidMatches > 6) {
return ctx.send({ type: 'danger', message: 'The Required Ban HWID matches must be between 0 (disabled) and 6.' });
}
//Validating custom rejection messages
if (cfg.whitelistRejectionMessage.length > 512) {
return ctx.send({ type: 'danger', message: 'The whitelist rejection message must be less than 512 characters.' });
}
if (cfg.banRejectionMessage.length > 512) {
return ctx.send({ type: 'danger', message: 'The ban rejection message must be less than 512 characters.' });
}
//Preparing & saving config
const newConfig = ctx.txAdmin.configVault.getScopedStructure('playerDatabase');
newConfig.onJoinCheckBan = cfg.onJoinCheckBan;
newConfig.whitelistMode = cfg.whitelistMode;
newConfig.whitelistedDiscordRoles = cfg.whitelistedDiscordRoles;
newConfig.whitelistRejectionMessage = cfg.whitelistRejectionMessage;
newConfig.requiredBanHwidMatches = cfg.requiredBanHwidMatches;
newConfig.banRejectionMessage = cfg.banRejectionMessage;
try {
ctx.txAdmin.configVault.saveProfile('playerDatabase', newConfig);
} catch (error) {
console.warn(`[${ctx.admin.name}] Error changing Player Manager settings.`);
console.verbose.dir(error);
return ctx.send({
type: 'danger',
markdown: true,
message: `**Error saving the configuration file:** ${(error as Error).message}`
});
}
//Sending output
ctx.txAdmin.statisticsManager.whitelistCheckTime.clear();
ctx.txAdmin.playerDatabase.refreshConfig();
ctx.admin.logAction('Changing Player Manager settings.');
return ctx.send({
type: 'success',
markdown: true,
message: `**Player Manager configuration saved!**`
});
}
//================================================================
/**
* Handle Monitor settings
*/
async function handleMonitor(ctx: AuthedCtx) {
//Sanity check
if (
isUndefined(ctx.request.body.restarterSchedule),
isUndefined(ctx.request.body.resourceStartingTolerance)
) {
return ctx.utils.error(400, 'Invalid Request - missing parameters');
}
//Prepare body input
let cfg = {
restarterSchedule: ctx.request.body.restarterSchedule.split(',').map((x: string) => x.trim()),
resourceStartingTolerance: parseInt(ctx.request.body.resourceStartingTolerance),
};
//Checking if resourceStartingTolerance is valid integer
if (typeof cfg.resourceStartingTolerance !== 'number' || isNaN(cfg.resourceStartingTolerance)) {
return ctx.send({ type: 'danger', message: 'resourceStartingTolerance must be a number.' });
}
//Validating restart times
const { valid: validRestartTimes, invalid: invalidRestartTimes } = parseSchedule(cfg.restarterSchedule);
if (invalidRestartTimes.length) {
let message = '<strong>The following entries were not recognized as valid 24h times:</strong><br>';
message += invalidRestartTimes.join('<br>\n');
return ctx.send({ type: 'danger', message: message });
}
//Preparing & saving config
const newConfig = ctx.txAdmin.configVault.getScopedStructure('monitor');
newConfig.restarterSchedule = validRestartTimes.map(t => t.string);
newConfig.resourceStartingTolerance = cfg.resourceStartingTolerance;
try {
ctx.txAdmin.configVault.saveProfile('monitor', newConfig);
} catch (error) {
console.warn(`[${ctx.admin.name}] Error changing Restarter settings.`);
console.verbose.dir(error);
return ctx.send({
type: 'danger',
markdown: true,
message: `**Error saving the configuration file:** ${(error as Error).message}`
});
}
//Sending output
ctx.txAdmin.healthMonitor.refreshConfig();
ctx.txAdmin.scheduler.refreshConfig();
ctx.admin.logAction('Changing monitor settings.');
return ctx.send({
type: 'success',
markdown: true,
message: `**Restarter configuration saved!**`
});
}
//================================================================
/**
* Handle Discord settings
*/
async function handleDiscord(ctx: AuthedCtx) {
//Sanity check
if (
isUndefined(ctx.request.body.enabled)
|| isUndefined(ctx.request.body.token)
|| isUndefined(ctx.request.body.guild)
|| isUndefined(ctx.request.body.announceChannel)
|| isUndefined(ctx.request.body.embedJson)
|| isUndefined(ctx.request.body.embedConfigJson)
) {
return ctx.utils.error(400, 'Invalid Request - missing parameters');
}
//Handle validate/repair JSONS
let embedJson, embedConfigJson, whichJson;
try {
whichJson = 'Embed JSON';
embedJson = jsonrepair(ctx.request.body.embedJson.trim());
whichJson = 'Embed Config JSON';
embedConfigJson = jsonrepair(ctx.request.body.embedConfigJson.trim());
} catch (error) {
return ctx.send({
type: 'danger',
markdown: true,
message: `**Invalid ${whichJson}:**\n${(error as Error).message}`,
});
}
//Validating embed JSONs
try {
generateStatusMessage(ctx.txAdmin, embedJson, embedConfigJson);
} catch (error) {
return ctx.send({
type: 'danger',
markdown: true,
message: `**Embed validation failed:**\n${(error as Error).message}`,
});
}
//Prepare body input
const cfg = {
enabled: (ctx.request.body.enabled === 'true'),
token: ctx.request.body.token.trim(),
guild: ctx.request.body.guild.trim(),
announceChannel: ctx.request.body.announceChannel.trim(),
embedJson,
embedConfigJson,
};
//Preparing & saving config
const newConfig = ctx.txAdmin.configVault.getScopedStructure('discordBot');
newConfig.enabled = cfg.enabled;
newConfig.token = cfg.token;
newConfig.guild = (cfg.guild.length) ? cfg.guild : false;
newConfig.announceChannel = (cfg.announceChannel.length) ? cfg.announceChannel : false;
newConfig.embedJson = cfg.embedJson;
newConfig.embedConfigJson = cfg.embedConfigJson;
try {
ctx.txAdmin.configVault.saveProfile('discordBot', newConfig);
} catch (error) {
console.warn(`[${ctx.admin.name}] Error changing Discord settings.`);
console.verbose.dir(error);
return ctx.send({
type: 'danger',
markdown: true,
message: `**Error saving the configuration file:** ${(error as Error).message}`
});
}
//Restarting discord bot
ctx.admin.logAction('Changing discordBot settings.');
try {
await ctx.txAdmin.discordBot.refreshConfig();
} catch (error) {
const errorCode = (error as any).code;
let extraContext = '';
if (errorCode === 'DisallowedIntents' || errorCode === 4014) {
extraContext = `**The bot requires the \`GUILD_MEMBERS\` intent.**
- Go to the Discord Dev Portal (https://discord.com/developers/applications)
- Navigate to \`Bot > Privileged Gateway Intents\`.
- Enable the \`GUILD_MEMBERS\` intent.
- Save on the dev portal.
- Go to the \`txAdmin > Settings > Discord Bot\` and press save.`;
} else if (errorCode === 'CustomNoGuild') {
const inviteUrl = ('clientId' in (error as any))
? `https://discord.com/oauth2/authorize?client_id=${(error as any).clientId}&scope=bot&permissions=0`
: `https://discordapi.com/permissions.html#0`
extraContext = `**This usually mean one of the issues below:**
- **Wrong guild/server ID:** read the description of the guild/server ID setting for more information.
- **Bot is not in the guild/server:** you need to [INVITE THE BOT](${inviteUrl}) to join the server.
- **Wrong bot:** you may be using the token of another discord bot.`;
} else if (errorCode === 'DangerousPermission') {
extraContext = `You need to remove the permissions listed above to be able to enable this bot.
This should be done in the Discord Server role configuration page and not in the Dev Portal.
Check every single role that the bot has in the server.
Please keep in mind that:
- These permissions are dangerous because if the bot token leaks, an attacker can cause permanent damage to your server.
- No bot should have more permissions than strictly needed, especially \`Administrator\`.
- You should never have multiple bots using the same token, create a new one for each bot.`;
}
return ctx.send({
type: 'danger',
markdown: true,
message: `**Error starting the bot:** ${(error as Error).message}\n${extraContext}`.trim()
});
}
//Sending output
return ctx.send({
type: 'success',
markdown: true,
message: `**Discord configuration saved!**
If _(and only if)_ the status embed is not being updated, check the System Logs page and make sure there are no embed errors.`
});
}
//================================================================
/**
* Handle Menu settings
* NOTE: scoped inside global settings
*/
async function handleMenu(ctx: AuthedCtx) {
//Sanity check
if (
isUndefined(ctx.request.body.menuEnabled)
|| isUndefined(ctx.request.body.menuAlignRight)
|| isUndefined(ctx.request.body.menuPageKey)
|| isUndefined(ctx.request.body.hideDefaultAnnouncement)
|| isUndefined(ctx.request.body.hideDefaultDirectMessage)
|| isUndefined(ctx.request.body.hideDefaultWarning)
|| isUndefined(ctx.request.body.hideDefaultScheduledRestartWarning)
) {
return ctx.utils.error(400, 'Invalid Request - missing parameters');
}
//Prepare body input
const cfg = {
menuEnabled: (ctx.request.body.menuEnabled === 'true'),
menuAlignRight: (ctx.request.body.menuAlignRight === 'true'),
menuPageKey: ctx.request.body.menuPageKey.trim(),
hideDefaultAnnouncement: (ctx.request.body.hideDefaultAnnouncement === 'true'),
hideDefaultDirectMessage: (ctx.request.body.hideDefaultDirectMessage === 'true'),
hideDefaultWarning: (ctx.request.body.hideDefaultWarning === 'true'),
hideDefaultScheduledRestartWarning: (ctx.request.body.hideDefaultScheduledRestartWarning === 'true'),
};
//Preparing & saving config
const newConfig = ctx.txAdmin.configVault.getScopedStructure('global');
newConfig.menuEnabled = cfg.menuEnabled;
newConfig.menuAlignRight = cfg.menuAlignRight;
newConfig.menuPageKey = cfg.menuPageKey;
newConfig.hideDefaultAnnouncement = cfg.hideDefaultAnnouncement;
newConfig.hideDefaultDirectMessage = cfg.hideDefaultDirectMessage;
newConfig.hideDefaultWarning = cfg.hideDefaultWarning;
newConfig.hideDefaultScheduledRestartWarning = cfg.hideDefaultScheduledRestartWarning;
try {
ctx.txAdmin.configVault.saveProfile('global', newConfig);
} catch (error) {
console.warn(`[${ctx.admin.name}] Error changing Global settings.`);
console.verbose.dir(error);
return ctx.send({
type: 'danger',
markdown: true,
message: `**Error saving the configuration file:** ${(error as Error).message}`
});
}
//Sending output
ctx.txAdmin.refreshConfig();
ctx.txAdmin.fxRunner.resetConvars();
ctx.admin.logAction('Changing menu settings.');
return ctx.send({
type: 'success',
markdown: true,
message: `**Game configuration saved!**
You need to restart the server for the changes to take effect.`
});
}