-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathadmin-sync.js
More file actions
587 lines (503 loc) · 17.8 KB
/
admin-sync.js
File metadata and controls
587 lines (503 loc) · 17.8 KB
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
import BasePlugin from "./base-plugin.js";
import axios from "axios";
import { promises as fsPromises } from "fs";
import path from "path";
export default class AdminSync extends BasePlugin {
static get description() {
return "Syncs the Admins.cfg file with admin data from a whitelist URL at regular intervals.";
}
static get defaultEnabled() {
return true;
}
static get optionsSpecification() {
return {
whitelistUrl: {
required: true,
description: "URL or array of URLs to fetch admin whitelist data from.",
example:
'https://example.com/whitelist.txt or ["https://example.com/whitelist1.txt", "https://example.com/whitelist2.txt"]',
},
adminsFilePath: {
required: true,
description: "Path to the Admins.cfg file.",
example: "/home/container/SquadGame/ServerConfig/Admins.cfg",
},
syncInterval: {
required: false,
description: "Interval in seconds between admin sync operations.",
default: 300,
example: 300,
},
updateOnStartup: {
required: false,
description: "Whether to update the admin list when the plugin starts.",
default: true,
},
chatCommands: {
required: false,
description: "Array of chat commands that will trigger an admin sync.",
default: ["!syncadmins", "!updateadmins"],
example: ["!syncadmins", "!updateadmins"],
},
backupBeforeSync: {
required: false,
description: "Whether to create a backup of Admins.cfg before syncing.",
default: true,
},
beautifyOutput: {
required: false,
description:
"Whether to beautify and organize the admin data with comments, statistics, and group sections.",
default: false,
},
maxBackupFiles: {
required: false,
description: "Maximum number of backup files to retain. Older backups are automatically deleted.",
default: 5,
example: 5,
},
};
}
constructor(server, options, connectors) {
super(server, options, connectors);
this.syncAdmins = this.syncAdmins.bind(this);
this.onChatMessage = this.onChatMessage.bind(this);
this.syncInterval = null;
this.isCurrentlySyncing = false;
}
async mount() {
this.verbose(1, "Admin Sync plugin mounted.");
// Register for CHAT_MESSAGE events
this.server.on("CHAT_MESSAGE", this.onChatMessage);
// Run an initial sync if configured
if (this.options.updateOnStartup) {
this.verbose(1, "Running initial admin sync on startup.");
await this.syncAdmins();
}
// Set up interval sync
if (this.options.syncInterval > 0) {
const intervalMs = this.options.syncInterval * 1000;
this.verbose(
1,
`Setting up admin sync interval: ${this.options.syncInterval}s (${intervalMs}ms)`
);
this.syncInterval = setInterval(async () => {
if (this.isCurrentlySyncing) {
this.verbose(
1,
"Skipping scheduled sync - another sync is already in progress."
);
return;
}
this.verbose(1, "Running scheduled admin sync...");
await this.syncAdmins();
}, intervalMs);
}
}
async unmount() {
// Clear interval
if (this.syncInterval) {
clearInterval(this.syncInterval);
this.syncInterval = null;
}
// Remove event listeners
this.server.removeEventListener("CHAT_MESSAGE", this.onChatMessage);
}
async onChatMessage(info) {
try {
// Only process commands from admin chat
if (info.chat !== "ChatAdmin") return;
// Check if the message is a command
const message = info.message.toLowerCase().trim();
const isCommand = this.options.chatCommands.some(
(cmd) => message === cmd.toLowerCase()
);
if (!isCommand) return;
if (this.isCurrentlySyncing) {
await this.server.rcon.warn(
info.player.eosID,
"Admin sync is already in progress. Please wait."
);
return;
}
this.verbose(
1,
`Admin ${info.player.name} (${info.player.eosID}) triggered admin sync via chat command.`
);
// Acknowledge the command
await this.server.rcon.warn(
info.player.eosID,
"Admin sync started. Check server logs for results."
);
// Sync the admins
const success = await this.syncAdmins();
// Notify the admin of completion
const resultMessage = success
? "Admin sync completed successfully."
: "Admin sync failed. Check server logs for details.";
await this.server.rcon.warn(info.player.eosID, resultMessage);
} catch (error) {
this.verbose(1, `Error processing chat command: ${error.message}`);
try {
await this.server.rcon.warn(
info.player.eosID,
"Admin sync failed due to an error."
);
} catch (rconError) {
this.verbose(
1,
`Failed to send error message to admin: ${rconError.message}`
);
}
}
}
async syncAdmins() {
if (this.isCurrentlySyncing) {
this.verbose(1, "Sync already in progress, skipping...");
return false;
}
this.isCurrentlySyncing = true;
try {
this.verbose(1, "Syncing admins...");
// Convert single URL to array for consistency
const urls = Array.isArray(this.options.whitelistUrl)
? this.options.whitelistUrl
: [this.options.whitelistUrl];
// Fetch data from all URLs concurrently
const combinedContent = await this.fetchAdminDataFromUrls(urls);
if (!combinedContent.trim()) {
this.verbose(1, "No valid admin data found from any whitelist URL.");
return false;
}
// Process content based on beautification setting
const finalContent = this.options.beautifyOutput
? this.beautifyAdminData(combinedContent)
: combinedContent;
// Update the Admins.cfg file
await this.updateAdminsFile(finalContent);
this.verbose(1, "Admin sync completed successfully.");
return true;
} catch (error) {
this.verbose(1, `Error syncing admins: ${error.message}`);
this.verbose(2, `Stack trace: ${error.stack}`);
return false;
} finally {
this.isCurrentlySyncing = false;
}
}
async updateAdminsFile(content) {
const filePath = this.options.adminsFilePath;
try {
// Create backup if requested
if (this.options.backupBeforeSync) {
await this.createBackup(filePath);
}
// Ensure the directory exists
const dir = path.dirname(filePath);
try {
await fsPromises.access(dir);
} catch {
await fsPromises.mkdir(dir, { recursive: true });
this.verbose(1, `Created directory: ${dir}`);
}
// Write the content to the file asynchronously
await fsPromises.writeFile(filePath, content, "utf8");
const mode = this.options.beautifyOutput ? "beautified" : "raw";
this.verbose(
1,
`Updated Admins.cfg with ${content.length} characters of ${mode} admin data.`
);
} catch (error) {
this.verbose(1, `Error updating admin file: ${error.message}`);
throw error;
}
}
beautifyAdminData(rawContent) {
const lines = rawContent.trim().split("\n");
const groups = new Map();
const admins = new Map();
// Parse groups and admins
for (const line of lines) {
const trimmedLine = line.trim();
if (!trimmedLine || trimmedLine.startsWith("//")) continue;
if (trimmedLine.startsWith("Group=")) {
const match = trimmedLine.match(/^Group=([^:]+):(.*)$/);
if (match) {
const [, groupName, permissions] = match;
groups.set(groupName, permissions);
}
} else if (trimmedLine.startsWith("Admin=")) {
const match = trimmedLine.match(/^Admin=([^:]+):([^\s]+)(.*)$/);
if (match) {
const [, id, groupName, comment] = match;
const isEOS = /^[0-9a-f]{32}$/.test(id);
const isSteam = id.startsWith("76561");
if (!admins.has(groupName)) {
admins.set(groupName, []);
}
admins.get(groupName).push({
id,
isEOS,
isSteam,
comment: comment.trim(),
original: trimmedLine,
});
}
}
}
// Calculate statistics
let totalAdmins = 0;
let totalEOS = 0;
let totalSteam = 0;
let totalGroups = groups.size;
for (const groupAdmins of admins.values()) {
totalAdmins += groupAdmins.length;
totalEOS += groupAdmins.filter((a) => a.isEOS).length;
totalSteam += groupAdmins.filter((a) => a.isSteam).length;
}
// Generate beautified output
let output = [];
// Header with statistics
output.push(
"//============================================================================="
);
output.push("// Squad Server Admin Configuration File");
output.push("// Auto-beautified and organized by AdminSync plugin");
output.push(
"//============================================================================="
);
output.push("//");
output.push(`// Total Statistics:`);
output.push(`// - Groups: ${totalGroups}`);
output.push(`// - Total Admins: ${totalAdmins}`);
output.push(`// - EOS IDs: ${totalEOS}`);
output.push(`// - Steam IDs: ${totalSteam}`);
output.push(`// - Last Sync: ${new Date().toISOString()}`);
output.push("//");
output.push(
"//============================================================================="
);
output.push("// GROUP DEFINITIONS");
output.push(
"//============================================================================="
);
output.push("");
// Sort groups by category
const adminGroups = [];
const clanGroups = [];
const specialGroups = [];
for (const [groupName, permissions] of groups) {
if (groupName.startsWith("Admin")) {
adminGroups.push([groupName, permissions]);
} else if (groupName.startsWith("Clan")) {
clanGroups.push([groupName, permissions]);
} else {
specialGroups.push([groupName, permissions]);
}
}
// Output admin groups
if (adminGroups.length > 0) {
output.push("// Administrative Groups");
for (const [groupName, permissions] of adminGroups.sort()) {
const count = admins.get(groupName)?.length || 0;
output.push(`Group=${groupName}:${permissions} // ${count} members`);
}
output.push("");
}
// Output special groups
if (specialGroups.length > 0) {
output.push("// Special Groups");
for (const [groupName, permissions] of specialGroups.sort()) {
const count = admins.get(groupName)?.length || 0;
output.push(`Group=${groupName}:${permissions} // ${count} members`);
}
output.push("");
}
// Output clan groups
if (clanGroups.length > 0) {
output.push("// Clan Groups");
for (const [groupName, permissions] of clanGroups.sort()) {
const count = admins.get(groupName)?.length || 0;
output.push(`Group=${groupName}:${permissions} // ${count} members`);
}
output.push("");
}
output.push(
"//============================================================================="
);
output.push("// ADMIN ASSIGNMENTS");
output.push(
"//============================================================================="
);
output.push("");
// Sort admin groups for output
const sortedAdminGroups = Array.from(admins.keys()).sort((a, b) => {
// Prioritize admin groups, then special, then clans
const aIsAdmin = a.startsWith("Admin");
const bIsAdmin = b.startsWith("Admin");
const aIsClan = a.startsWith("Clan");
const bIsClan = b.startsWith("Clan");
if (aIsAdmin && !bIsAdmin) return -1;
if (!aIsAdmin && bIsAdmin) return 1;
if (!aIsClan && bIsClan) return -1;
if (aIsClan && !bIsClan) return 1;
return a.localeCompare(b);
});
// Output admin assignments by group
for (const groupName of sortedAdminGroups) {
const groupAdmins = admins.get(groupName);
if (!groupAdmins || groupAdmins.length === 0) continue;
const eosCount = groupAdmins.filter((a) => a.isEOS).length;
const steamCount = groupAdmins.filter((a) => a.isSteam).length;
output.push(
`//-----------------------------------------------------------------------------`
);
output.push(
`// ${groupName} (${groupAdmins.length} members: ${eosCount} EOS, ${steamCount} Steam)`
);
output.push(
`//-----------------------------------------------------------------------------`
);
// Sort admins within group (EOS first, then Steam, then alphabetically)
const sortedAdmins = [...groupAdmins].sort((a, b) => {
if (a.isEOS && !b.isEOS) return -1;
if (!a.isEOS && b.isEOS) return 1;
return a.original.localeCompare(b.original);
});
for (const admin of sortedAdmins) {
output.push(admin.original);
}
output.push("");
}
output.push(
"//============================================================================="
);
output.push("// End of Configuration");
output.push(
"//============================================================================="
);
return output.join("\n");
}
async createBackup(filePath) {
try {
await fsPromises.access(filePath);
} catch {
this.verbose(1, "No existing Admins.cfg file to backup.");
return;
}
const timestamp = new Date().toISOString().replace(/[:.]/g, "-");
const backupPath = `${filePath}.backup.${timestamp}`;
try {
await fsPromises.copyFile(filePath, backupPath);
this.verbose(1, `Created backup: ${backupPath}`);
// Clean up old backups
await this.cleanupOldBackups(filePath);
} catch (error) {
this.verbose(1, `Failed to create backup: ${error.message}`);
throw error;
}
}
async cleanupOldBackups(filePath) {
try {
const dir = path.dirname(filePath);
const basename = path.basename(filePath);
const maxBackups = this.options.maxBackupFiles;
if (maxBackups <= 0) {
this.verbose(2, "Backup cleanup disabled (maxBackupFiles <= 0)");
return;
}
// Get all backup files for this admin file
const files = await fsPromises.readdir(dir);
const backupFiles = files.filter(file =>
file.startsWith(`${basename}.backup.`) && file !== basename
);
if (backupFiles.length <= maxBackups) {
this.verbose(2, `No cleanup needed. ${backupFiles.length} backups (max: ${maxBackups})`);
return;
}
// Sort backup files by creation time (oldest first)
const backupFilesWithStats = await Promise.all(
backupFiles.map(async (file) => {
const fullPath = path.join(dir, file);
const stats = await fsPromises.stat(fullPath);
return { file, fullPath, ctime: stats.ctime };
})
);
const sortedBackups = backupFilesWithStats.sort((a, b) =>
a.ctime.getTime() - b.ctime.getTime()
);
// Delete oldest backups to keep only maxBackupFiles
const filesToDelete = sortedBackups.slice(0, sortedBackups.length - maxBackups);
for (const { file, fullPath } of filesToDelete) {
try {
await fsPromises.unlink(fullPath);
this.verbose(1, `Deleted old backup: ${file}`);
} catch (deleteError) {
this.verbose(1, `Failed to delete backup ${file}: ${deleteError.message}`);
}
}
this.verbose(1, `Backup cleanup completed. Kept ${maxBackups} most recent backups.`);
} catch (error) {
this.verbose(1, `Error during backup cleanup: ${error.message}`);
// Don't throw error here as backup cleanup failure shouldn't stop the sync
}
}
async fetchAdminDataFromUrls(urls) {
const axiosConfig = {
timeout: 30000,
headers: {
"User-Agent": "SquadJS-AdminSync/1.0",
Accept: "text/plain, */*",
},
};
const fetchPromises = urls.map(async (url) => {
if (!url) return "";
try {
this.verbose(1, `Fetching admin data from: ${url}`);
// Add cache busting parameter
const separator = url.includes("?") ? "&" : "?";
const cacheBuster = `${separator}t=${Date.now()}`;
const response = await axios.get(`${url}${cacheBuster}`, axiosConfig);
if (!response.data) {
this.verbose(1, `No data received from whitelist URL: ${url}`);
return "";
}
this.verbose(
1,
`Fetched ${response.data.length} characters from: ${url}`
);
return response.data;
} catch (error) {
this.verbose(1, `Error fetching from ${url}: ${error.message}`);
if (error.code === "ECONNABORTED") {
this.verbose(1, `Request timeout for ${url}`);
} else if (error.response) {
this.verbose(1, `HTTP ${error.response.status} for ${url}`);
} else if (error.request) {
this.verbose(1, `Network error for ${url}`);
}
return "";
}
});
const results = await Promise.allSettled(fetchPromises);
let combinedContent = "";
let successCount = 0;
for (const result of results) {
if (result.status === "fulfilled" && result.value) {
if (combinedContent && !combinedContent.endsWith("\n")) {
combinedContent += "\n";
}
combinedContent += result.value;
successCount++;
}
}
this.verbose(
1,
`Successfully fetched data from ${successCount}/${urls.length} URLs`
);
if (successCount === 0) {
throw new Error("Failed to fetch data from any whitelist URL");
}
return combinedContent;
}
}