-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathindex.js
More file actions
9041 lines (8472 loc) · 326 KB
/
Copy pathindex.js
File metadata and controls
9041 lines (8472 loc) · 326 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
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
import 'dotenv/config';
import express from 'express';
import cors from 'cors';
import http from 'http';
import { Server as IOServer } from 'socket.io';
import bcrypt from 'bcrypt';
import fs from 'fs/promises';
import path from 'path';
import { fileURLToPath } from 'url';
import jwt from 'jsonwebtoken';
import crypto from 'crypto';
import geoip from 'geoip-lite';
import multer from 'multer';
import { db, initDb } from './db/index.js';
import { authMiddleware, signToken, requireAdmin } from './auth.js';
// index.js
import {
connectRcon,
sendRconCommand,
closeRcon as terminateRcon,
subscribeToRcon,
startAutoMonitor,
rconEventBus,
fetchServerInfo,
fetchLevelUrl,
fetchWorldSettings
} from './rcon.js';
import {
fetchRustMapMetadata,
downloadRustMapImage,
configureRustMapsCache,
ensureRustMapsCacheDirs,
loadCachedRustMapMetadata,
saveCachedRustMapMetadata,
removeCachedRustMapMetadata,
findCachedRustMapImage,
resolveRustMapImageCachePath,
firstThursdayResetTime,
isRustMapMetadataStale,
purgeRustMapCacheIfDue
} from './rustmaps.js';
import { encodeDiscordBotConfig, normaliseDiscordBotConfig, parseDiscordBotConfig } from './discord-config.js';
import {
normaliseRolePermissions,
serialiseRolePermissions,
hasGlobalPermission,
canAccessServer,
filterServersByPermission,
filterStatusMapByPermission,
describeRoleTemplates
} from './permissions.js';
const __filename = fileURLToPath(import.meta.url);
const __dirname = path.dirname(__filename);
const DATA_DIR = process.env.DATA_DIR ? path.resolve(process.env.DATA_DIR) : path.resolve(process.cwd(), 'data');
const MAP_STORAGE_DIR = path.join(DATA_DIR, 'maps');
const MAX_MAP_IMAGE_BYTES = 40 * 1024 * 1024;
const TICKET_PREVIEW_PAGE = process.env.TICKET_PREVIEW_PAGE || '/ticket-preview.html';
const PANEL_PUBLIC_URL = normalizeBaseUrl(process.env.PANEL_PUBLIC_URL);
const APP_URL_FROM_ENV = normalizeBaseUrl(process.env.APP_URL);
const LEGACY_PUBLIC_APP_URL = normalizeBaseUrl(process.env.PUBLIC_APP_URL);
const TEAM_AUTH_APP_URL = APP_URL_FROM_ENV || PANEL_PUBLIC_URL || LEGACY_PUBLIC_APP_URL || '';
import {
extractInteger,
extractFloat,
isLikelyLevelUrl,
isCustomLevelUrl,
isFacepunchLevelUrl,
parseServerInfoMessage,
parseChatMessage,
stripAnsiSequences,
stripRconTimestampPrefix,
parseF7ReportLine
} from './rcon-parsers.js';
const mapImageUpload = multer({
storage: multer.memoryStorage(),
limits: { fileSize: MAX_MAP_IMAGE_BYTES }
});
const mapImageUploadMiddleware = (req, res, next) => {
mapImageUpload.single('image')(req, res, (err) => {
if (err) {
if (err instanceof multer.MulterError && err.code === 'LIMIT_FILE_SIZE') {
return res.status(413).json({ error: 'image_too_large' });
}
return res.status(400).json({ error: 'invalid_image' });
}
next();
});
};
const REGION_DISPLAY = typeof Intl !== 'undefined' && typeof Intl.DisplayNames === 'function'
? new Intl.DisplayNames(['en'], { type: 'region' })
: null;
const COUNTRY_NAME_FALLBACKS = {
UK: 'United Kingdom',
EU: 'European Union'
};
const WORLD_ENTITY_CACHE_TTL_MS = 15000;
const ENTITY_SEARCH_TIMEOUT_MS = 4500;
const DISCORD_API_BASE = 'https://discord.com/api/v10';
const MAX_DISCORD_MESSAGE_LENGTH = 2000;
const MAX_DISCORD_TICKET_MESSAGES = 50;
const TEAM_AUTH_COOKIE_NAME = process.env.TEAM_AUTH_COOKIE_NAME || 'team_auth_session';
const TEAM_AUTH_COOKIE_MAX_AGE_MS = (() => {
const daysRaw = Number(process.env.TEAM_AUTH_COOKIE_MAX_AGE_DAYS);
const days = Number.isFinite(daysRaw) && daysRaw > 0 ? daysRaw : 180;
return Math.max(1, Math.round(days)) * 24 * 60 * 60 * 1000;
})();
const TEAM_AUTH_LINK_TTL_MS = (() => {
const value = Number(process.env.TEAM_AUTH_LINK_TTL_MS);
if (Number.isFinite(value) && value >= 60 * 1000) return Math.floor(value);
return 15 * 60 * 1000;
})();
const AUTH_COOKIE_SECURE = (() => {
if (typeof process.env.COOKIE_SECURE === 'string') {
const flag = process.env.COOKIE_SECURE.trim().toLowerCase();
if (flag === 'true') return true;
if (flag === 'false') return false;
}
return (process.env.NODE_ENV || '').toLowerCase() === 'production';
})();
const TEAM_AUTH_DISCORD_COOKIE_NAME = `${TEAM_AUTH_COOKIE_NAME}_discord`;
const TEAM_AUTH_STEAM_COOKIE_NAME = `${TEAM_AUTH_COOKIE_NAME}_steam`;
const TEAM_AUTH_SESSION_TTL_MS = Math.max(TEAM_AUTH_LINK_TTL_MS, TEAM_AUTH_COOKIE_MAX_AGE_MS);
const TEAM_AUTH_STATE_SECRET = (() => {
if (typeof process.env.TEAM_AUTH_STATE_SECRET === 'string' && process.env.TEAM_AUTH_STATE_SECRET.trim()) {
return process.env.TEAM_AUTH_STATE_SECRET.trim();
}
if (typeof process.env.JWT_SECRET === 'string' && process.env.JWT_SECRET.trim()) {
return process.env.JWT_SECRET.trim();
}
const fallback = crypto.randomBytes(32).toString('hex');
console.warn('TEAM_AUTH_STATE_SECRET not configured; using ephemeral secret. Configure TEAM_AUTH_STATE_SECRET for stable OAuth sessions.');
return fallback;
})();
const DISCORD_OAUTH_CLIENT_ID = typeof process.env.DISCORD_OAUTH_CLIENT_ID === 'string'
? process.env.DISCORD_OAUTH_CLIENT_ID.trim()
: '';
const DISCORD_OAUTH_CLIENT_SECRET = typeof process.env.DISCORD_OAUTH_CLIENT_SECRET === 'string'
? process.env.DISCORD_OAUTH_CLIENT_SECRET.trim()
: '';
const DISCORD_OAUTH_REDIRECT_URI = typeof process.env.DISCORD_OAUTH_REDIRECT_URI === 'string'
? process.env.DISCORD_OAUTH_REDIRECT_URI.trim()
: '';
const STEAM_OPENID_REALM = typeof process.env.STEAM_OPENID_REALM === 'string'
? process.env.STEAM_OPENID_REALM.trim()
: '';
const STEAM_OPENID_RETURN_URL = typeof process.env.STEAM_OPENID_RETURN_URL === 'string'
? process.env.STEAM_OPENID_RETURN_URL.trim()
: '';
const ENTITY_SEARCH_DEFINITIONS = [
{
type: 'patrol_helicopter',
label: 'Patrol Helicopter',
icon: 'patrol-helicopter',
commands: [
'find "assets/prefabs/npc/patrolhelicopter/patrolhelicopter.prefab"',
'find "patrol helicopter"',
'find patrolhelicopter'
],
matchers: [/patrol/i, /heli/i]
},
{
type: 'cargo_ship',
label: 'Cargo Ship',
icon: 'cargo-ship',
commands: [
'find "assets/content/vehicles/boats/cargoship/cargoship.prefab"',
'find "cargo ship"',
'find cargoship'
],
matchers: [/cargo/i, /ship/i]
}
];
const worldEntityCache = new Map();
function lookupCountryCodeFromIp(ip) {
if (typeof ip !== 'string' || !ip) return null;
try {
const result = geoip.lookup(ip);
const code = typeof result?.country === 'string' ? result.country.trim() : '';
if (!code) return null;
return code.toUpperCase();
} catch {
return null;
}
}
function countryNameFromCode(code) {
if (!code) return null;
const upper = String(code).trim().toUpperCase();
if (!upper) return null;
if (COUNTRY_NAME_FALLBACKS[upper]) return COUNTRY_NAME_FALLBACKS[upper];
if (REGION_DISPLAY) {
try {
const label = REGION_DISPLAY.of(upper);
if (label && label !== upper) return label;
} catch {
// ignore lookup errors
}
}
return COUNTRY_NAME_FALLBACKS[upper] || upper;
}
function resolveIpCountry(ip) {
const code = lookupCountryCodeFromIp(ip);
if (!code) {
return { code: null, name: null };
}
return {
code,
name: countryNameFromCode(code)
};
}
const app = express();
const server = http.createServer(app);
const io = new IOServer(server, { cors: { origin: process.env.CORS_ORIGIN?.split(',') || '*' } });
io.use(async (socket, next) => {
const token = socket.handshake.auth?.token || socket.handshake.query?.token;
if (!token) return next(new Error('unauthorized'));
try {
const payload = jwt.verify(token, JWT_SECRET);
const context = await loadUserContext(payload.uid);
if (!context) return next(new Error('unauthorized'));
socket.data.user = context;
next();
} catch (err) {
next(new Error('unauthorized'));
}
});
const PORT = parseInt(process.env.PORT || '8787', 10);
const BIND = process.env.BIND || '0.0.0.0';
const JWT_SECRET = process.env.JWT_SECRET || 'dev';
const ALLOW_REGISTRATION = (process.env.ALLOW_REGISTRATION || '').toLowerCase() === 'true';
async function loadUserContext(userId) {
const numeric = Number(userId);
if (!Number.isFinite(numeric)) return null;
const row = await db.getUser(numeric);
if (!row) return null;
let teams = [];
if (typeof db.listUserTeams === 'function') {
try {
teams = await db.listUserTeams(numeric);
} catch (err) {
console.warn('Failed to load user teams', err);
}
}
let activeTeamId = null;
if (typeof db.getUserActiveTeam === 'function') {
try {
const storedTeam = await db.getUserActiveTeam(numeric);
if (storedTeam && teams.some((team) => team.id === storedTeam)) {
activeTeamId = storedTeam;
}
} catch (err) {
console.warn('Failed to load active team', err);
}
}
if (!activeTeamId && teams.length > 0) {
activeTeamId = teams[0].id;
if (typeof db.setUserActiveTeam === 'function') {
db.setUserActiveTeam(numeric, activeTeamId).catch((err) => {
console.warn('Failed to persist default active team', err);
});
}
}
if (!activeTeamId && typeof db.createTeam === 'function') {
try {
const name = row.username ? `${row.username}'s Team` : 'My Team';
const teamId = await db.createTeam({ name, owner_user_id: row.id });
await db.addTeamMember({ team_id: teamId, user_id: row.id, role: row.role || 'admin' });
if (typeof db.setUserActiveTeam === 'function') {
await db.setUserActiveTeam(row.id, teamId);
}
activeTeamId = teamId;
teams = await db.listUserTeams(numeric);
} catch (err) {
console.warn('Failed to create default team for user', err);
}
}
let effectiveRole = row.role;
let rolePermissions = row.role_permissions;
let activeTeamName = null;
let activeTeamRoleName = null;
let activeTeamHasDiscordToken = false;
let activeTeamDiscordGuildId = null;
let activeTeamDiscordTokenPreview = null;
const roleCache = new Map();
let teamServers = [];
if (activeTeamId && Array.isArray(teams)) {
const membership = teams.find((team) => team.id === activeTeamId) || null;
if (membership?.role) {
effectiveRole = membership.role;
if (typeof db.getRole === 'function') {
if (!roleCache.has(membership.role)) {
const roleRecord = await db.getRole(membership.role);
roleCache.set(membership.role, roleRecord);
}
const roleRecord = roleCache.get(membership.role);
if (roleRecord?.permissions) {
rolePermissions = roleRecord.permissions;
activeTeamRoleName = roleRecord.name || membership.role;
}
}
}
if (membership) {
activeTeamName = membership.name || null;
activeTeamHasDiscordToken = Boolean(membership.discord_token);
activeTeamDiscordGuildId = membership.discord_guild_id != null && membership.discord_guild_id !== ''
? String(membership.discord_guild_id)
: null;
if (membership.discord_token) {
activeTeamDiscordTokenPreview = previewDiscordToken(membership.discord_token);
}
}
if (typeof db.listTeamServerIds === 'function') {
try {
teamServers = await db.listTeamServerIds(activeTeamId);
} catch (err) {
console.warn('Failed to list team server ids', err);
}
}
}
const permissions = normaliseRolePermissions(rolePermissions, effectiveRole);
if (Array.isArray(permissions?.servers?.allowed)) {
const teamIds = teamServers.map((id) => Number(id)).filter((id) => Number.isFinite(id));
if (permissions.servers.allowed.includes('*')) {
permissions.servers.allowed = teamIds;
} else {
const allowedSet = new Set(
permissions.servers.allowed
.map((value) => {
const numericValue = Number(value);
return Number.isFinite(numericValue) ? numericValue : null;
})
.filter((value) => value != null)
);
permissions.servers.allowed = teamIds.filter((id) => allowedSet.has(id));
}
}
const projectedTeams = [];
if (Array.isArray(teams)) {
for (const team of teams) {
let roleName = null;
if (team?.role) {
if (!roleCache.has(team.role) && typeof db.getRole === 'function') {
const roleRecord = await db.getRole(team.role);
roleCache.set(team.role, roleRecord);
}
const cachedRole = roleCache.get(team.role);
roleName = cachedRole?.name || team.role;
}
projectedTeams.push({
id: team.id,
name: team.name,
ownerId: team.owner_user_id,
role: team.role,
roleName,
hasDiscordToken: Boolean(team.discord_token),
discordGuildId: team.discord_guild_id != null && team.discord_guild_id !== '' ? String(team.discord_guild_id) : null,
discordTokenPreview: team.discord_token ? previewDiscordToken(team.discord_token) : null
});
}
}
return {
id: row.id,
username: row.username,
role: effectiveRole,
roleName: activeTeamRoleName || row.role_name || effectiveRole,
permissions,
activeTeamId,
activeTeamName,
teams: projectedTeams,
created_at: row.created_at,
activeTeamHasDiscordToken,
activeTeamDiscordGuildId,
activeTeamDiscordTokenPreview,
teamDiscord: {
hasToken: activeTeamHasDiscordToken,
guildId: activeTeamDiscordGuildId,
tokenPreview: activeTeamDiscordTokenPreview
}
};
}
function requireGlobalPermissionMiddleware(permission) {
return (req, res, next) => {
if (!hasGlobalPermission(req.authUser, permission)) {
return res.status(403).json({ error: 'forbidden' });
}
next();
};
}
function ensureServerCapability(req, res, capability, param = 'id') {
const raw = req.params?.[param];
const id = toServerId(raw);
if (id == null) {
res.status(400).json({ error: 'invalid_id' });
return null;
}
if (!canAccessServer(req.authUser, id, capability)) {
res.status(403).json({ error: 'forbidden' });
return null;
}
return id;
}
function userHasTeamAccess(user, teamId) {
if (!user) return false;
const numericTeamId = Number(teamId);
if (!Number.isFinite(numericTeamId)) return false;
const activeTeamId = Number(user.activeTeamId);
if (Number.isFinite(activeTeamId) && activeTeamId === numericTeamId) return true;
if (Array.isArray(user.teams)) {
for (const team of user.teams) {
const id = Number(team?.id ?? team?.team_id);
if (Number.isFinite(id) && id === numericTeamId) return true;
}
}
return false;
}
async function ensureTeamAccess(req, res, param = 'teamId') {
const raw = req.params?.[param] ?? req.query?.[param];
const numericTeamId = Number(raw);
if (!Number.isFinite(numericTeamId)) {
res.status(400).json({ error: 'invalid_team' });
return null;
}
let hasAccess = userHasTeamAccess(req.authUser, numericTeamId);
if (!hasAccess && Number.isFinite(Number(req.authUser?.id)) && typeof db?.getTeamMember === 'function') {
try {
const membership = await db.getTeamMember(numericTeamId, req.authUser.id);
hasAccess = Boolean(membership);
} catch (err) {
console.warn('failed to verify team membership', err);
}
}
if (!hasAccess) {
res.status(403).json({ error: 'forbidden' });
return null;
}
return numericTeamId;
}
function projectRole(row) {
if (!row) return null;
return {
key: row.key,
name: row.name,
description: row.description,
permissions: normaliseRolePermissions(row.permissions, row.key),
created_at: row.created_at,
updated_at: row.updated_at
};
}
function projectF7Report(row, fallback = {}) {
const source = row || {};
const base = fallback || {};
const idCandidate = Number(source.id ?? base.id);
const serverIdCandidate = Number(source.server_id ?? source.serverId ?? base.serverId);
const createdAt = source.created_at || source.createdAt || base.createdAt || new Date().toISOString();
const updatedAt = source.updated_at || source.updatedAt || createdAt;
return {
id: Number.isFinite(idCandidate) ? idCandidate : null,
serverId: Number.isFinite(serverIdCandidate) ? serverIdCandidate : null,
reportId: source.report_id ?? source.reportId ?? base.reportId ?? null,
reporterSteamId: source.reporter_steamid ?? source.reporterSteamId ?? base.reporterSteamId ?? null,
reporterName: source.reporter_name ?? source.reporterName ?? base.reporterName ?? null,
targetSteamId: source.target_steamid ?? source.targetSteamId ?? base.targetSteamId ?? null,
targetName: source.target_name ?? source.targetName ?? base.targetName ?? null,
category: source.category ?? base.category ?? null,
message: source.message ?? base.message ?? null,
raw: source.raw ?? base.raw ?? null,
createdAt,
updatedAt
};
}
function normalizeBaseUrl(value) {
if (typeof value !== 'string') return '';
const trimmed = value.trim();
if (!trimmed) return '';
return trimmed.replace(/\/+$/, '');
}
function resolvePreviewHref(relative) {
if (!relative) return relative;
if (/^https?:\/\//i.test(relative)) return relative;
if (!PANEL_PUBLIC_URL) return relative;
if (relative.startsWith('/')) {
return `${PANEL_PUBLIC_URL}${relative}`;
}
return `${PANEL_PUBLIC_URL}/${relative}`;
}
function projectDiscordTicket(row) {
if (!row) return null;
const idCandidate = Number(row.id ?? row.ticketId);
const serverIdCandidate = Number(row.server_id ?? row.serverId);
const teamIdCandidate = Number(row.team_id ?? row.teamId);
const ticketNumberCandidate = Number(row.ticket_number ?? row.ticketNumber);
const createdAt = row.created_at ?? row.createdAt ?? null;
const updatedAt = row.updated_at ?? row.updatedAt ?? createdAt;
const closedAt = row.closed_at ?? row.closedAt ?? null;
const previewTokenCandidate = typeof row.preview_token === 'string'
? row.preview_token
: (typeof row.previewToken === 'string' ? row.previewToken : null);
const previewUrl = buildTicketPreviewUrl(
teamIdCandidate,
{ id: idCandidate, previewToken: previewTokenCandidate }
);
return {
id: Number.isFinite(idCandidate) ? idCandidate : null,
serverId: Number.isFinite(serverIdCandidate) ? serverIdCandidate : null,
teamId: Number.isFinite(teamIdCandidate) ? teamIdCandidate : null,
guildId: typeof row.guild_id === 'string' ? row.guild_id : (typeof row.guildId === 'string' ? row.guildId : null),
channelId: typeof row.channel_id === 'string' ? row.channel_id : (typeof row.channelId === 'string' ? row.channelId : null),
ticketNumber: Number.isFinite(ticketNumberCandidate) ? ticketNumberCandidate : null,
subject: typeof row.subject === 'string' ? row.subject : null,
details: typeof row.details === 'string' ? row.details : null,
createdBy: typeof row.created_by === 'string' ? row.created_by : (typeof row.createdBy === 'string' ? row.createdBy : null),
createdByTag: typeof row.created_by_tag === 'string'
? row.created_by_tag
: (typeof row.createdByTag === 'string' ? row.createdByTag : null),
status: typeof row.status === 'string' ? row.status : 'open',
createdAt,
updatedAt,
closedAt,
closedBy: typeof row.closed_by === 'string' ? row.closed_by : (typeof row.closedBy === 'string' ? row.closedBy : null),
closedByTag: typeof row.closed_by_tag === 'string'
? row.closed_by_tag
: (typeof row.closedByTag === 'string' ? row.closedByTag : null),
closeReason: typeof row.close_reason === 'string'
? row.close_reason
: (typeof row.closeReason === 'string' ? row.closeReason : null),
previewToken: typeof previewTokenCandidate === 'string' && previewTokenCandidate.trim()
? previewTokenCandidate.trim()
: null,
previewUrl
};
}
function buildTicketDialogEntries(row) {
const entries = [];
if (!row) return entries;
const ticketId = Number(row.id ?? row.ticket_number ?? Date.now());
const createdAt = row.created_at ?? null;
const details = typeof row.details === 'string' ? row.details.trim() : '';
if (details) {
entries.push({
id: `ticket-${ticketId}-request`,
role: 'requester',
authorId: typeof row.created_by === 'string' ? row.created_by : null,
authorTag: typeof row.created_by_tag === 'string' ? row.created_by_tag : null,
content: details,
postedAt: createdAt
});
}
const closeReason = typeof row.close_reason === 'string' ? row.close_reason.trim() : '';
if (closeReason) {
entries.push({
id: `ticket-${ticketId}-close`,
role: 'staff',
authorId: typeof row.closed_by === 'string' ? row.closed_by : null,
authorTag: typeof row.closed_by_tag === 'string' ? row.closed_by_tag : null,
content: closeReason,
postedAt: row.closed_at ?? row.updated_at ?? null
});
}
return entries;
}
function projectStoredTicketDialogEntry(row) {
if (!row) return null;
const id = typeof row.message_id === 'string'
? row.message_id.trim()
: (typeof row.messageId === 'string' ? row.messageId.trim() : '');
if (!id) return null;
const role = typeof row.role === 'string' && row.role.trim().toLowerCase() === 'requester'
? 'requester'
: 'staff';
const content = typeof row.content === 'string'
? row.content
: (typeof row.message === 'string' ? row.message : '');
if (!content) return null;
const authorId = typeof row.author_id === 'string'
? row.author_id
: (typeof row.authorId === 'string' ? row.authorId : null);
const authorTag = typeof row.author_tag === 'string'
? row.author_tag
: (typeof row.authorTag === 'string' ? row.authorTag : null);
const postedAt = row.posted_at ?? row.postedAt ?? null;
return { id, role, authorId, authorTag, content, postedAt };
}
function buildTicketPreviewUrl(teamId, ticket) {
const numericTeamId = Number(teamId);
if (!Number.isFinite(numericTeamId)) return null;
let previewToken = null;
if (typeof ticket === 'string') {
const trimmed = ticket.trim();
previewToken = trimmed || null;
} else if (typeof ticket === 'number') {
previewToken = Number.isFinite(ticket) ? String(Math.trunc(ticket)) : null;
} else if (ticket && typeof ticket === 'object') {
const direct = typeof ticket.previewToken === 'string' ? ticket.previewToken.trim() : '';
const legacy = typeof ticket.preview_token === 'string' ? ticket.preview_token.trim() : '';
const idValue = ticket.id ?? ticket.ticketId;
if (direct) {
previewToken = direct;
} else if (legacy) {
previewToken = legacy;
} else if (typeof idValue === 'string' && idValue.trim()) {
previewToken = idValue.trim();
} else if (Number.isFinite(idValue)) {
previewToken = String(Number(idValue));
}
} else if (ticket != null) {
const text = String(ticket).trim();
previewToken = text || null;
}
if (!previewToken) return null;
const base = TICKET_PREVIEW_PAGE || '/ticket-preview.html';
const [pathPart, searchPart = ''] = String(base).split('?');
const params = new URLSearchParams(searchPart);
params.set('teamId', String(numericTeamId));
params.set('ticketToken', previewToken);
const relative = `${pathPart}?${params.toString()}`;
return resolvePreviewHref(relative);
}
function slugifyTicketSubject(subject) {
if (typeof subject !== 'string') return '';
const trimmed = subject.trim().toLowerCase();
if (!trimmed) return '';
return trimmed
.normalize('NFKD')
.replace(/[^a-z0-9\s-]/g, '')
.trim()
.replace(/\s+/g, '-')
.replace(/-+/g, '-')
.replace(/^-+/, '')
.replace(/-+$/, '');
}
function buildTicketPreviewMessages(ticket, dialog, { teamName } = {}) {
const fallbackRequester = ticket?.createdByTag || ticket?.createdBy || 'Requester';
const staffLabel = teamName ? `${teamName} Staff` : 'Support Staff';
const fallbackCreatedAt = ticket?.createdAt || null;
const fallbackClosedAt = ticket?.closedAt || ticket?.updatedAt || fallbackCreatedAt;
const entries = Array.isArray(dialog) ? dialog : [];
const messages = [];
entries.forEach((entry, index) => {
if (!entry || typeof entry.content !== 'string' || !entry.content.trim()) return;
const role = entry.role === 'staff' ? 'staff' : 'requester';
const avatarIndex = role === 'staff' ? 1 : 0;
const fallbackId = `${role}-${ticket?.id ?? 'ticket'}-${index}`;
messages.push({
id: entry.id || fallbackId,
discord_id: entry.authorId || fallbackId,
nickname: entry.authorTag || entry.authorId || (role === 'staff' ? staffLabel : fallbackRequester),
avatar: `https://cdn.discordapp.com/embed/avatars/${avatarIndex}.png`,
timestamp: entry.postedAt || (role === 'staff' ? fallbackClosedAt : fallbackCreatedAt) || new Date().toISOString(),
message: entry.content,
reactions: []
});
});
if (messages.length === 0) {
messages.push({
id: `ticket-${ticket?.id ?? 'unknown'}-open`,
discord_id: ticket?.createdBy || `ticket-${ticket?.id ?? 'unknown'}`,
nickname: fallbackRequester,
avatar: 'https://cdn.discordapp.com/embed/avatars/0.png',
timestamp: fallbackCreatedAt || new Date().toISOString(),
message: ticket?.subject || 'Ticket opened',
reactions: []
});
}
return messages.sort((a, b) => new Date(a.timestamp).getTime() - new Date(b.timestamp).getTime());
}
function buildTicketPreviewPayload({ ticket, dialog, teamName }) {
const identifier = ticket?.ticketNumber != null
? `#${ticket.ticketNumber}`
: (ticket?.id != null ? `#${ticket.id}` : '#ticket');
const subjectSlug = slugifyTicketSubject(ticket?.subject || '');
const channelSuffix = subjectSlug ? `-${subjectSlug}` : '';
const channelTitle = `#ticket-${ticket?.ticketNumber ?? ticket?.id ?? 'thread'}${channelSuffix}`;
const messages = buildTicketPreviewMessages(ticket, dialog, { teamName });
return {
pageTitle: `${teamName || 'Support'} — Ticket ${identifier}`,
channelTitle,
team: ticket?.teamId != null ? { id: ticket.teamId, name: teamName || null } : null,
ticket: {
...ticket,
previewUrl: buildTicketPreviewUrl(ticket?.teamId, ticket)
},
messages
};
}
function safeTrimString(value) {
if (typeof value === 'string') return value.trim();
if (typeof value === 'number' && Number.isFinite(value)) return String(value).trim();
return '';
}
function sanitizeDiscordOutgoingContent(text) {
if (typeof text !== 'string') return '';
return text.replace(/\r\n?/g, '\n').replace(/@/g, '@\u200b').trim();
}
function buildPanelReplyMessage(username, message) {
const displayName = safeTrimString(username) || 'Panel User';
const prefix = `[Control Panel] ${displayName}: `;
const body = sanitizeDiscordOutgoingContent(message);
if (!body) {
const err = new Error('message_required');
err.code = 'message_required';
throw err;
}
const maxContentLength = MAX_DISCORD_MESSAGE_LENGTH - prefix.length;
if (maxContentLength <= 0) {
const err = new Error('message_too_long');
err.code = 'message_too_long';
throw err;
}
if (body.length > maxContentLength) {
const err = new Error('message_too_long');
err.code = 'message_too_long';
err.limit = maxContentLength;
throw err;
}
return prefix + body;
}
function toDiscordAuthorTag(author = {}) {
if (!author || typeof author !== 'object') return null;
const display = safeTrimString(author.global_name) || safeTrimString(author.username);
if (!display) return null;
const discriminator = safeTrimString(author.discriminator);
if (discriminator && discriminator !== '0') {
return `${display}#${discriminator}`;
}
return display;
}
function entryTimestamp(entry) {
if (!entry || !entry.postedAt) return 0;
const timestamp = new Date(entry.postedAt).getTime();
return Number.isFinite(timestamp) ? timestamp : 0;
}
function mapDiscordMessageToDialogEntry(message, { requesterId = null } = {}) {
if (!message || typeof message !== 'object') return null;
if (typeof message.type === 'number' && message.type !== 0 && message.type !== 19) return null;
const id = typeof message.id === 'string' && message.id ? message.id : null;
const content = safeTrimString(message.content);
const attachments = Array.isArray(message.attachments) ? message.attachments : [];
const attachmentLines = attachments
.map((attachment) => {
if (!attachment || typeof attachment !== 'object') return null;
if (typeof attachment.url !== 'string' || !attachment.url) return null;
const name = safeTrimString(attachment.filename);
return name ? `${name}: ${attachment.url}` : attachment.url;
})
.filter((line) => typeof line === 'string' && line.trim() !== '');
const lines = [];
if (content) lines.push(content);
lines.push(...attachmentLines);
if (lines.length === 0) return null;
const author = typeof message.author === 'object' && message.author != null ? message.author : {};
const authorId = typeof author.id === 'string' ? author.id : null;
const authorTag = toDiscordAuthorTag(author);
const requester = requesterId ? String(requesterId) : null;
const role = requester && authorId === requester ? 'requester' : 'staff';
const postedAt = typeof message.timestamp === 'string' ? message.timestamp : null;
return {
id: id || (authorId && postedAt ? `${authorId}:${postedAt}` : null),
role,
postedAt,
content: lines.join('\n'),
authorId,
authorTag
};
}
async function getDiscordTokenForTicket(row) {
if (!row || typeof db?.getTeam !== 'function') return null;
const teamIdCandidate = Number(row.team_id ?? row.teamId);
if (!Number.isFinite(teamIdCandidate)) return null;
try {
const team = await db.getTeam(teamIdCandidate);
if (!team) return null;
const token = safeTrimString(team.discord_token);
return token || null;
} catch (err) {
console.error(`failed to load team ${teamIdCandidate} for ticket`, err);
return null;
}
}
async function fetchDiscordTicketMessages(row) {
if (!row || typeof fetch !== 'function') return [];
const channelId = safeTrimString(row.channel_id ?? row.channelId);
if (!channelId) return [];
const token = await getDiscordTokenForTicket(row);
if (!token) return [];
const url = `${DISCORD_API_BASE}/channels/${channelId}/messages?limit=${MAX_DISCORD_TICKET_MESSAGES}`;
let response;
try {
response = await fetch(url, {
headers: {
Authorization: `Bot ${token}`
}
});
} catch (err) {
console.error(`failed to fetch discord messages for channel ${channelId}`, err);
return [];
}
if (!response.ok) {
if (response.status !== 403 && response.status !== 404) {
console.error(`discord api returned ${response.status} for channel ${channelId}`);
}
return [];
}
let data;
try {
data = await response.json();
} catch (err) {
console.error(`failed to parse discord messages for channel ${channelId}`, err);
return [];
}
if (!Array.isArray(data)) return [];
const requesterId = row.created_by ?? row.createdBy ?? null;
const entries = [];
data.reverse();
for (const message of data) {
const entry = mapDiscordMessageToDialogEntry(message, { requesterId });
if (entry) entries.push(entry);
}
return entries;
}
async function assembleTicketDialog(row) {
const baseEntries = buildTicketDialogEntries(row);
const entries = Array.isArray(baseEntries) ? [...baseEntries] : [];
const seen = new Set(entries.map((entry) => entry?.id).filter(Boolean));
const ticketId = Number(row?.id ?? row?.ticket_id ?? row?.ticketId);
if (Number.isFinite(ticketId) && typeof db.listDiscordTicketDialogEntries === 'function') {
try {
const storedRows = await db.listDiscordTicketDialogEntries(ticketId);
for (const stored of storedRows) {
const entry = projectStoredTicketDialogEntry(stored);
if (!entry) continue;
const key = entry.id;
if (key && seen.has(key)) continue;
entries.push(entry);
if (key) seen.add(key);
}
} catch (err) {
console.error('failed to load stored ticket dialog entries', err);
}
}
try {
const discordEntries = await fetchDiscordTicketMessages(row);
for (const entry of discordEntries) {
if (!entry) continue;
const key = entry.id;
if (key && seen.has(key)) continue;
entries.push(entry);
if (key) seen.add(key);
}
} catch (err) {
console.error('failed to assemble ticket dialog', err);
}
entries.sort((a, b) => entryTimestamp(a) - entryTimestamp(b));
return entries;
}
const ROLE_KEY_PATTERN = /^[a-z0-9_\-]{3,32}$/i;
const RESERVED_ROLE_KEYS = new Set(['admin', 'user']);
function normalizeRoleKey(value) {
if (typeof value !== 'string') return null;
const key = value.trim();
if (!ROLE_KEY_PATTERN.test(key)) return null;
return key.toLowerCase();
}
function normalizeUsername(value) {
return typeof value === 'string' ? value.trim() : '';
}
async function findUserCaseInsensitive(username) {
if (typeof db.getUserByUsernameInsensitive === 'function') {
return await db.getUserByUsernameInsensitive(username);
}
return await db.getUserByUsername(username);
}
function buildRolePermissionsPayload(body = {}, roleKey = 'default') {
const source = body && typeof body.permissions === 'object' ? body.permissions : {};
const payload = { ...source };
if (source.servers && typeof source.servers === 'object') {
payload.servers = { ...source.servers };
}
if (source.global && typeof source.global === 'object') {
payload.global = { ...source.global };
}
const allowed = body.allowedServers ?? body.allowed ?? body.servers;
if (typeof allowed !== 'undefined') {
payload.servers = { ...(payload.servers || {}), allowed };
}
if (typeof body.capabilities !== 'undefined') {
payload.servers = { ...(payload.servers || {}), capabilities: body.capabilities };
}
if (body.global && typeof body.global === 'object') {
payload.global = { ...(payload.global || {}), ...body.global };
}
return serialiseRolePermissions(payload, roleKey);
}
const toInt = (value, fallback) => {
const parsed = parseInt(value, 10);
return Number.isFinite(parsed) ? parsed : fallback;
};
const MONITOR_INTERVAL = Math.max(toInt(process.env.MONITOR_INTERVAL_MS || '60000', 60000), 15000);
const MONITOR_TIMEOUT = Math.max(toInt(process.env.MONITOR_TIMEOUT_MS || '8000', 8000), 2000);
const DEFAULT_RUSTMAPS_API_KEY = process.env.RUSTMAPS_API_KEY || '';
const SERVER_INFO_TTL = Math.max(toInt(process.env.SERVER_INFO_CACHE_MS, 60000), 10000);
const ALLOWED_USER_SETTINGS = new Set(['rustmaps_api_key']);
const MAP_PURGE_INTERVAL = Math.max(toInt(process.env.MAP_PURGE_INTERVAL_MS, 6 * 60 * 60 * 1000), 15 * 60 * 1000);
const STEAM_PROFILE_CACHE_TTL = Math.max(toInt(process.env.STEAM_PROFILE_CACHE_MS || '300000', 300000), 60000);
const STEAM_PROFILE_REFRESH_INTERVAL = Math.max(toInt(process.env.STEAM_PROFILE_REFRESH_MS || '1800000', 1800000), 300000);
const STEAM_PLAYTIME_REFRESH_INTERVAL = Math.max(toInt(process.env.STEAM_PLAYTIME_REFRESH_MS || '21600000', 21600000), 3600000);
const RUST_STEAM_APP_ID = 252490;
const MIN_PLAYER_HISTORY_RANGE_MS = 60 * 60 * 1000; // 1 hour
const MAX_PLAYER_HISTORY_RANGE_MS = 30 * 24 * 60 * 60 * 1000; // 30 days
const MIN_PLAYER_HISTORY_INTERVAL_MS = 5 * 60 * 1000; // 5 minutes
const MAX_PLAYER_HISTORY_INTERVAL_MS = 24 * 60 * 60 * 1000; // 24 hours
const PLAYER_HISTORY_MAX_BUCKETS = 2000;
const PLAYER_LIST_DEFAULT_LIMIT = 200;
const PLAYER_LIST_MAX_LIMIT = 1000;
const PLAYER_LIMIT_UNLIMITED_TOKENS = new Set(['unlimited', 'all', '*', 'infinite', 'infinity', 'none']);
const MAX_PLAYER_NOTE_LENGTH = 2000;
const DEFAULT_RANGE_INTERVALS = [
{ maxRange: 6 * 60 * 60 * 1000, interval: 15 * 60 * 1000 },
{ maxRange: 24 * 60 * 60 * 1000, interval: 60 * 60 * 1000 },
{ maxRange: 3 * 24 * 60 * 60 * 1000, interval: 3 * 60 * 60 * 1000 },
{ maxRange: 7 * 24 * 60 * 60 * 1000, interval: 6 * 60 * 60 * 1000 },
{ maxRange: MAX_PLAYER_HISTORY_RANGE_MS + 1, interval: 24 * 60 * 60 * 1000 }
];
function clamp(value, min, max) {
if (Number.isNaN(value) || !Number.isFinite(value)) return min;
if (value < min) return min;
if (value > max) return max;
return value;
}
function parsePlayerQueryLimit(value, { defaultLimit = PLAYER_LIST_DEFAULT_LIMIT, maxLimit = PLAYER_LIST_MAX_LIMIT } = {}) {
const rawValue = Array.isArray(value) ? value[0] : value;
if (rawValue == null) return defaultLimit;
const str = String(rawValue).trim();
if (!str) return defaultLimit;
const lower = str.toLowerCase();
if (PLAYER_LIMIT_UNLIMITED_TOKENS.has(lower)) return null;
const numeric = Number(str);
if (!Number.isFinite(numeric) || numeric <= 0) return defaultLimit;
const integer = Math.floor(numeric);
if (!Number.isFinite(maxLimit) || maxLimit <= 0) return integer;
return Math.min(integer, Math.floor(maxLimit));
}
function parsePlayerQueryOffset(value) {
const rawValue = Array.isArray(value) ? value[0] : value;
const parsed = parseInt(rawValue ?? '0', 10);
if (!Number.isFinite(parsed) || parsed <= 0) return 0;
return Math.floor(parsed);
}