-
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathserver.js
More file actions
6658 lines (6309 loc) · 323 KB
/
server.js
File metadata and controls
6658 lines (6309 loc) · 323 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
require('dotenv').config();
const http = require('http');
const https = require('https');
const fs = require('fs');
const zlib = require('zlib');
const { AsyncLocalStorage } = require('async_hooks');
const fsp = fs.promises;
const path = require('path');
const os = require('os');
const crypto = require('crypto');
const { spawn, spawnSync } = require('child_process');
// ── Auto-build dist/ if stale or missing ────────────────────────────────────
// The package.json `prestart` hook only runs under `npm start`. Deployments
// that invoke `node server.js` directly (the systemd unit in docs/install-ubuntu.md,
// docker, a fresh clone) would otherwise serve a stale or empty dist/ — users
// see old UI even after pulling new src/. Compare the newest src/ mtime
// against the dist/app.js marker and rebuild only when needed so warm
// restarts stay fast (one stat per source file, zero subprocess).
(function ensureBuildFresh() {
const distMarker = path.join(__dirname, 'dist', 'app.js');
const srcDir = path.join(__dirname, 'src');
if (!fs.existsSync(srcDir)) return; // not a source tree (e.g. extracted dist-only build)
let distMtime = 0;
try { distMtime = fs.statSync(distMarker).mtimeMs; } catch { /* missing */ }
let srcMtime = 0;
(function walk(dir) {
for (const entry of fs.readdirSync(dir, { withFileTypes: true })) {
const p = path.join(dir, entry.name);
if (entry.isDirectory()) walk(p);
else { const m = fs.statSync(p).mtimeMs; if (m > srcMtime) srcMtime = m; }
}
})(srcDir);
if (distMtime > 0 && distMtime >= srcMtime) return; // already fresh
console.log(distMtime === 0
? ' [build] dist/ missing — running build.js…'
: ' [build] dist/ older than src/ — running build.js…');
const r = spawnSync(process.execPath, [path.join(__dirname, 'build.js')], { stdio: 'inherit' });
if (r.status !== 0) console.warn(` [build] build.js exited with status ${r.status}; serving existing dist/ as-is`);
})();
// ── Mod extraction libraries (loaded lazily to avoid startup errors if missing) ─
// Each format has an optional dependency. We log a clear banner at startup if a
// library is missing so ops can see "RAR support disabled" before users hit a 500.
let StreamZip, Unrar, sevenZ, sevenBin;
const _missingExtractors = [];
try { StreamZip = require('node-stream-zip'); } catch { _missingExtractors.push('zip (node-stream-zip)'); }
try { Unrar = require('node-unrar-js'); } catch { _missingExtractors.push('rar (node-unrar-js)'); }
try { sevenZ = require('node-7z'); } catch { _missingExtractors.push('7z (node-7z)'); }
try { sevenBin = require('7zip-bin'); } catch { _missingExtractors.push('7z binary (7zip-bin)'); }
// Some npm installs (--ignore-scripts, tarball restores, or node_modules
// copied across machines) drop the +x bit on the bundled 7za binary, so
// spawn() later throws EACCES and chunked mod uploads fail with HTTP 500.
// chmod is a no-op on Windows and idempotent everywhere else.
if (sevenBin && sevenBin.path7za && process.platform !== 'win32') {
try { fs.chmodSync(sevenBin.path7za, 0o755); } catch { /* read-only fs etc. — surfaced later at spawn time */ }
}
if (_missingExtractors.length) {
console.warn(` Mod extraction limited — missing: ${_missingExtractors.join(', ')}. Run "npm install" to enable.`);
}
// ── Logging ──────────────────────────────────────────────────────────────────
// Each HTTP request runs inside an AsyncLocalStorage scope holding a short
// request id, surfaced as the `X-Request-Id` response header. log.info / .warn /
// .error pick up that id automatically — no extra parameter to thread through.
// Outside a request scope (startup, sweepers, AC spawn callbacks…) the id is
// omitted and the line still gets a timestamp + level.
const _reqContext = new AsyncLocalStorage();
// Re-entrant guard. log.* feeds appendLog, which iterates SSE clients and may
// trigger a write failure that someone in the future could decide to log via
// log.warn — instant infinite loop. The flag short-circuits the inner call
// to a console-only emit, breaking the cycle without losing the message.
let _logEmitDepth = 0;
function _logEmit(level, args) {
const ctx = _reqContext.getStore();
const ts = new Date().toISOString();
const prefix = ctx?.reqId ? `${ts} ${level} [${ctx.reqId}]` : `${ts} ${level}`;
const stream = (level === 'ERROR' || level === 'WARN') ? console.error : console.log;
stream(prefix, ...args);
if (_logEmitDepth > 0) return; // mid-broadcast — don't loop back through appendLog
// Mirror into logBuffer so the Dashboard activity card sees [UDP] events
// and other panel-internal log lines, not just stdout from a spawned
// BeamMP-Server child (which is empty whenever the panel adopts an existing PID).
_logEmitDepth++;
try {
if (typeof appendLog === 'function') {
const body = args.map(a => typeof a === 'string' ? a : (a && a.stack) || String(a)).join(' ');
appendLog(`${prefix} ${body}`);
}
} catch {} finally { _logEmitDepth--; }
}
const log = {
info: (...args) => _logEmit('INFO', args),
warn: (...args) => _logEmit('WARN', args),
error: (...args) => _logEmit('ERROR', args),
};
function newRequestId() {
// 8 hex chars is plenty for in-process correlation — collisions are not security-relevant
return require('crypto').randomBytes(4).toString('hex');
}
// ── Config ────────────────────────────────────────────────────────────────────
// Two BEAMMP_* env vars are the only ones a fresh install must supply:
// BEAMMP_SERVER_DIR (the directory holding BeamMP-Server + ServerConfig.toml +
// Resources/) and BEAMMP_BIN (the BeamMP-Server binary path). Everything else
// — log file, mods directory, ServerConfig.toml path — is derived from those.
function _firstExistingPath(candidates) {
for (const p of candidates) {
if (!p) continue;
try { fs.accessSync(p); return p; } catch {}
}
return null;
}
const _DEFAULT_SERVER_ROOTS = [
process.env.HOME && path.join(process.env.HOME, 'beammp'),
'/srv/beammp',
'/opt/beammp',
].filter(Boolean);
const _detectedServerRoot = _firstExistingPath(_DEFAULT_SERVER_ROOTS);
// When neither the env var nor any auto-detect candidate exists, the panel
// still needs *some* string for the BEAMMP_* constants so error messages
// mention a real-looking path. Default to ~/beammp so the user sees a path
// they recognise from .env.example, not a system path they never chose.
const _FALLBACK_SERVER_ROOT = process.env.HOME ? path.join(process.env.HOME, 'beammp') : '/opt/beammp';
const HOST = process.env.HOST || '127.0.0.1';
const PORT = parseInt(process.env.PORT || '3000', 10);
// BEAMMP_SERVER_DIR is the anchor. Other paths fall back to subdirs of it.
const BEAMMP_SERVER_DIR = process.env.BEAMMP_SERVER_DIR
|| _detectedServerRoot
|| _FALLBACK_SERVER_ROOT;
const BEAMMP_BIN = process.env.BEAMMP_BIN
|| path.join(BEAMMP_SERVER_DIR, 'BeamMP-Server');
const BEAMMP_CFG_FILE = process.env.BEAMMP_CFG
|| path.join(BEAMMP_SERVER_DIR, 'ServerConfig.toml');
const BEAMMP_LOG_FILE = process.env.BEAMMP_LOG
|| path.join(__dirname, 'logs', 'beammp.log');
// BeamMP serves mods out of two parallel directories: Client/ is what the
// game's auto-download pump streams to connecting players, Server/ holds Lua
// plugins that run on the server side only.
const BEAMMP_RESOURCES_DIR = path.join(BEAMMP_SERVER_DIR, 'Resources');
const BEAMMP_CLIENT_RESOURCES_DIR = path.join(BEAMMP_RESOURCES_DIR, 'Client');
const BEAMMP_SERVER_RESOURCES_DIR = path.join(BEAMMP_RESOURCES_DIR, 'Server');
// PanelBridge Lua plugin drop-box (tools/beammp-plugin/PanelBridge in this
// repo, installed into Resources/Server/PanelBridge on the BeamMP host).
// The plugin writes player state into state.json and reads moderation
// commands from commands.json. See docs/live-state.md.
const BEAMMP_PLUGIN_BRIDGE_DIR = path.join(BEAMMP_SERVER_RESOURCES_DIR, 'PanelBridge');
const BEAMMP_PLUGIN_STATE_FILE = path.join(BEAMMP_PLUGIN_BRIDGE_DIR, 'state.json');
const BEAMMP_PLUGIN_CHAT_FILE = path.join(BEAMMP_PLUGIN_BRIDGE_DIR, 'chat.json');
const BEAMMP_PLUGIN_COMMANDS_FILE = path.join(BEAMMP_PLUGIN_BRIDGE_DIR, 'commands.json');
// Ban list published to the plugin so onPlayerAuth in main.lua can refuse
// re-connections without the panel having to babysit every join — kicks for
// players already online still go through commands.json as before. Schema is
// a JSON object keyed by ban id (matches bans.id PRIMARY KEY, which is the
// player identifier from MP.GetPlayerIdentifiers). Value carries the reason
// so the plugin can echo it back to the client as the kick message.
const BEAMMP_PLUGIN_BANS_FILE = path.join(BEAMMP_PLUGIN_BRIDGE_DIR, 'bans.json');
// Voting bridge (PanelBridge v4). vote_config goes panel → plugin, the
// other two go plugin → panel. vote_result is one-shot — the panel deletes
// it after applying the result so the plugin doesn't try to re-trigger.
const BEAMMP_PLUGIN_VOTE_CONFIG_FILE = path.join(BEAMMP_PLUGIN_BRIDGE_DIR, 'vote_config.json');
const BEAMMP_PLUGIN_VOTE_STATE_FILE = path.join(BEAMMP_PLUGIN_BRIDGE_DIR, 'vote_state.json');
const BEAMMP_PLUGIN_VOTE_RESULT_FILE = path.join(BEAMMP_PLUGIN_BRIDGE_DIR, 'vote_result.json');
// Vanilla maps that ship with BeamNG.drive. The internal `level` matches the
// path BeamMP-Server expects in ServerConfig.toml#Map (e.g. /levels/<x>/info.json
// — the client resolves it against its own install). Metadata here drives the
// visual catalogue on the Maps page: `theme` selects the SVG thumbnail variant
// (city/offroad/racetrack/test/derby/training), `size` is a coarse S/M/L
// indicator, and `description` gives the operator a one-line summary so they
// don't have to remember which internal name maps to which place. Source:
// official BeamMP server-maintenance docs + BeamNG documentation site.
const VANILLA_MAPS_META = [
{ id: 'gridmap_v2', level: '/levels/gridmap_v2/info.json', name: 'Gridmap v2', nameEs: 'Mapa de prueba v2', theme: 'test', size: 'M', description: 'Flat grid test environment with ramps, jumps and material patches.' },
{ id: 'west_coast_usa', level: '/levels/west_coast_usa/info.json', name: 'West Coast, USA', nameEs: 'Costa Oeste, EE. UU.', theme: 'city', size: 'L', description: 'Coastal California sandbox: highway, harbour, downtown and off-road backroads.' },
{ id: 'east_coast_usa', level: '/levels/east_coast_usa/info.json', name: 'East Coast, USA', nameEs: 'Costa Este, EE. UU.', theme: 'offroad', size: 'L', description: 'Rural New England with twisty backroads, small towns and a forested mountain pass.' },
{ id: 'italy', level: '/levels/italy/info.json', name: 'Italy', nameEs: 'Italia', theme: 'offroad', size: 'L', description: 'Huge open Tuscan map with hill roads, vineyards, a coastal village and a circuit.' },
{ id: 'utah', level: '/levels/utah/info.json', name: 'Utah', nameEs: 'Utah, EE. UU.', theme: 'offroad', size: 'L', description: 'High-desert canyon roads, salt flats and a small interstate stretch.' },
{ id: 'johnson_valley', level: '/levels/johnson_valley/info.json', name: 'Johnson Valley', nameEs: 'Johnson Valley', theme: 'offroad', size: 'L', description: 'Dry-lake-bed playground and rocky off-road trails.' },
{ id: 'jungle_rock_island', level: '/levels/jungle_rock_island/info.json', name: 'Jungle Rock Island', nameEs: 'Isla Jungle Rock', theme: 'offroad', size: 'M', description: 'Tropical island with jungle trails, beaches and a small airstrip.' },
{ id: 'hirochi_raceway', level: '/levels/hirochi_raceway/info.json', name: 'Hirochi Raceway', nameEs: 'Pista de carreras Hirochi', theme: 'racetrack', size: 'M', description: 'Japanese-style closed circuit with multiple layout configurations.' },
{ id: 'automation_test_track', level: '/levels/automation_test_track/info.json', name: 'Automation Test Track', nameEs: 'Automation Test Track', theme: 'racetrack', size: 'M', description: 'Manufacturer-style proving ground: oval, handling course and acceleration straight.' },
{ id: 'industrial', level: '/levels/industrial/info.json', name: 'Industrial Site', nameEs: 'Polígono industrial', theme: 'city', size: 'M', description: 'Dense warehouse + factory district with narrow service roads and loading bays.' },
{ id: 'driver_training', level: '/levels/driver_training/info.json', name: 'Driver Training', nameEs: 'Centro ETK de formación de pilotos', theme: 'training', size: 'S', description: 'Closed asphalt pad with cones, slaloms and exercises — perfect for learning car physics.' },
{ id: 'derby', level: '/levels/derby/info.json', name: 'Derby Arenas', nameEs: 'Circuitos de demolición', theme: 'derby', size: 'S', description: 'Three demolition-derby arenas (figure-8, mud, stadium).' },
{ id: 'small_island', level: '/levels/small_island/info.json', name: 'Small Island', nameEs: 'Isla pequeña, EE. UU.', theme: 'offroad', size: 'S', description: 'Compact island with a single lap road and an off-road interior.' },
{ id: 'smallgrid', level: '/levels/smallgrid/info.json', name: 'Small Grid', nameEs: 'Cuadrícula, pequeño, sencillo', theme: 'test', size: 'S', description: 'Minimal flat plane for low-overhead testing and prop spawning.' },
{ id: 'cliff', level: '/levels/cliff/info.json', name: 'Cliff', nameEs: 'Acantilado', theme: 'offroad', size: 'S', description: 'Small cliffside map with a beach below and a coastal road, popular for stunts and photo runs.' },
];
const DB_PATH = process.env.DB_PATH || path.join(__dirname, 'panel.db');
const ADMIN_TOKEN = process.env.ADMIN_TOKEN || '';
const ROOT = __dirname;
// Boot-time path summary. Logged once on startup so operators can verify the
// auto-detection picked sane defaults without grepping the source. Failures
// here are non-fatal — the panel boots and shows a setup banner inside the UI.
function _logBootConfig() {
const exists = p => { try { fs.accessSync(p); return true; } catch { return false; } };
const status = (label, p) => ` ${label.padEnd(22)} ${p || '(unset)'} ${p ? (exists(p) ? '✓' : '✗ MISSING') : ''}`;
console.log(' BeamMP paths:');
console.log(status('BEAMMP_SERVER_DIR', BEAMMP_SERVER_DIR));
console.log(status('BEAMMP_BIN', BEAMMP_BIN));
console.log(status('BEAMMP_CFG', BEAMMP_CFG_FILE));
if (!process.env.BEAMMP_SERVER_DIR && _detectedServerRoot) {
console.log(` (auto-detected root: ${_detectedServerRoot})`);
}
if (!exists(BEAMMP_CFG_FILE)) {
console.warn(` ⚠️ ServerConfig.toml not found at ${BEAMMP_CFG_FILE}. The Config page will`);
console.warn(` show an error until you point BEAMMP_SERVER_DIR at the directory that holds it.`);
}
}
// BeamMP-Server child process handle, when the panel itself spawned it. NULL
// when the panel restarted while the server was already running — in that
// case the server is "adopted" via findBeamMPPid() / pgrep on every health
// check, and kill paths SIGTERM the adopted PID directly.
let beammpChild = null;
// ── Log buffer + SSE ──────────────────────────────────────────────────────────
const LOG_MAX = 500;
let logBuffer = [];
let logSeq = 0;
const sseClients = new Set();
function appendLog(raw) {
if (!raw || !raw.trim()) return;
const entry = parseLine(raw.trim(), logSeq++);
logBuffer.push(entry);
if (logBuffer.length > LOG_MAX) logBuffer.shift();
const data = JSON.stringify(entry);
// Iterate a snapshot so deleting on write-failure doesn't skip the next client
for (const res of [...sseClients]) {
try { res.write(`data: ${data}\n\n`); } catch { sseClients.delete(res); }
}
}
function loadLogFileIntoBuffer() {
try {
fs.mkdirSync(path.dirname(BEAMMP_LOG_FILE), { recursive: true });
const content = fs.readFileSync(BEAMMP_LOG_FILE, 'utf8');
const lines = content.trim().split('\n').filter(Boolean).slice(-LOG_MAX);
logBuffer = lines.map((l, i) => parseLine(l, i));
logSeq = logBuffer.length;
} catch {}
}
// Tail BEAMMP_LOG_FILE for new lines and push them to appendLog. BeamMP-Server
// writes its stdout/stderr directly to the file via a passed-in FD (so it
// survives a panel restart without dying of SIGPIPE on broken pipes); the
// panel reads them back via inotify + delta-read. Polling fallback covers
// edge cases where fs.watch misses events (e.g. log file truncated by the
// "Clear logs" admin action, or replaced under us by a rotator).
let _logTailPos = 0;
let _logTailWatcher = null;
let _logTailBuffer = '';
function startLogTail() {
if (_logTailWatcher) return;
try { _logTailPos = fs.statSync(BEAMMP_LOG_FILE).size; } catch { _logTailPos = 0; }
const LINE_BUF_MAX = 8 * 1024;
const flush = () => {
let size;
try { size = fs.statSync(BEAMMP_LOG_FILE).size; } catch { return; }
if (size < _logTailPos) _logTailPos = 0; // truncated or rotated
if (size === _logTailPos) return;
const len = size - _logTailPos;
let fd;
try { fd = fs.openSync(BEAMMP_LOG_FILE, 'r'); } catch { return; }
const buf = Buffer.alloc(len);
try { fs.readSync(fd, buf, 0, len, _logTailPos); }
finally { try { fs.closeSync(fd); } catch {} }
_logTailPos = size;
_logTailBuffer += buf.toString('utf8');
const parts = _logTailBuffer.split('\n');
_logTailBuffer = parts.pop();
for (const line of parts) appendLog(line);
if (_logTailBuffer.length > LINE_BUF_MAX) {
appendLog(_logTailBuffer.slice(0, LINE_BUF_MAX) + ' …(truncated)');
_logTailBuffer = '';
}
};
try { _logTailWatcher = fs.watch(BEAMMP_LOG_FILE, { persistent: false }, flush); }
catch (e) { log.warn('[LOG] fs.watch failed, falling back to poll-only:', e.message); }
// Safety-net poll @ 2s for environments where fs.watch under-reports
// (some networked filesystems, log rotators that replace the inode, etc.).
setInterval(flush, 2000).unref();
}
// Called when the admin truncates BEAMMP_LOG_FILE via /api/logs/clear so the
// tail watcher doesn't mistake the new (smaller) file for a missed write.
function resetLogTailPosition() { _logTailPos = 0; _logTailBuffer = ''; }
// ── Session store (SQLite-backed, survives server restarts) ───────────────────
const SESSION_TTL = 7 * 24 * 60 * 60 * 1000; // 7 days
const _sessionsMemory = new Map(); // fallback when DB not ready
function createSession(username, role) {
const token = crypto.randomBytes(32).toString('hex');
const expiresAt = Date.now() + SESSION_TTL;
if (db) {
try {
db.prepare('DELETE FROM sessions WHERE expires_at < ?').run(Date.now());
db.prepare('INSERT OR REPLACE INTO sessions (token, username, role, expires_at) VALUES (?, ?, ?, ?)').run(token, username, role, expiresAt);
} catch { _sessionsMemory.set(token, { username, role, expiresAt }); }
} else {
_sessionsMemory.set(token, { username, role, expiresAt });
}
return token;
}
// Parse a cookie name out of the request header by exact name match (split on `=`),
// not by `startsWith('name=')` — that would also match `name_alt=…`, `name-other=…`,
// or any future cookie whose name happens to share a prefix.
function readCookie(req, name) {
const raw = req.headers.cookie || '';
for (const part of raw.split(';')) {
const eq = part.indexOf('=');
if (eq < 0) continue;
if (part.slice(0, eq).trim() === name) return part.slice(eq + 1).trim();
}
return null;
}
function getSession(req) {
const token = readCookie(req, 'sid');
if (!token) return null;
if (db) {
try {
return db.prepare('SELECT username, role FROM sessions WHERE token = ? AND expires_at > ?').get(token, Date.now()) || null;
} catch {}
}
const s = _sessionsMemory.get(token);
if (!s) return null;
if (Date.now() > s.expiresAt) { _sessionsMemory.delete(token); return null; }
return s;
}
function deleteSession(token) {
if (db) { try { db.prepare('DELETE FROM sessions WHERE token = ?').run(token); } catch {} }
_sessionsMemory.delete(token);
}
// True when the request arrived over TLS, either directly or via a trusted proxy
// that set X-Forwarded-Proto. Browsers refuse Secure cookies on plain HTTP, so
// we only attach the flag when the connection is actually encrypted — otherwise
// dev/local installations would silently lose the cookie.
function requestIsHttps(req) {
if (req?.connection?.encrypted) return true;
const proto = (req?.headers?.['x-forwarded-proto'] || '').split(',')[0].trim().toLowerCase();
return proto === 'https';
}
function sessionCookieHeader(token, isHttps) {
return `sid=${token}; HttpOnly; SameSite=Strict; Path=/; Max-Age=${SESSION_TTL / 1000}`
+ (isHttps ? '; Secure' : '');
}
function checkAdminAuth(req) {
const sess = getSession(req);
if (sess?.role === 'admin' && !userMustChangePassword(sess.username)) return true;
if (!ADMIN_TOKEN) return false;
const h = req.headers['x-admin-token'] || req.headers['authorization']?.replace(/^Bearer\s+/i, '') || '';
// Constant-time compare so the header is not a timing oracle for ADMIN_TOKEN.
// Length must match for timingSafeEqual; mismatched length is a non-secret
// upper bound on the token, so the early return is fine.
if (!h || h.length !== ADMIN_TOKEN.length) return false;
try {
return crypto.timingSafeEqual(Buffer.from(h), Buffer.from(ADMIN_TOKEN));
} catch { return false; }
}
function checkAnyAuth(req) {
return getSession(req);
}
function userMustChangePassword(username) {
if (!db || !username) return false;
try {
const row = db.prepare('SELECT must_change_password FROM panel_users WHERE username = ?').get(username);
return row?.must_change_password === 1;
} catch { return false; }
}
// Canonical list of granular permissions exposed via the Usuarios card. Any
// permission referenced in route guards must appear here so the UI surfaces
// it and the defaults block above seeds a value for it.
const ROLE_PERMISSIONS = [
'serverControl', 'serverConfig', 'mapActivate', 'whitelistManage',
'playerModeration', 'modUpload', 'discordWebhook', 'auditView', 'dbBackup',
];
// Logical implications between permissions — declared once so the same set
// of derived grants applies everywhere the User role's permission map is
// computed (login response, admin update endpoint, route guards). Each key
// is "the permission that implies", value is the list of permissions that
// are implicitly granted too. Spares the operator from having to tick
// "Change active map" separately for a user who already has full server-
// config rights.
const PERMISSION_IMPLICATIONS = {
serverConfig: ['mapActivate'],
};
function _applyImplications(perms) {
for (const src of Object.keys(PERMISSION_IMPLICATIONS)) {
if (perms[src]) for (const dst of PERMISSION_IMPLICATIONS[src]) perms[dst] = true;
}
return perms;
}
function getUserRolePermissions() {
const fallback = Object.fromEntries(ROLE_PERMISSIONS.map(p => [p, false]));
if (!db) return fallback;
try {
const row = db.prepare(`SELECT value FROM panel_settings WHERE key = 'role_permissions_user'`).get();
if (!row?.value) return fallback;
const parsed = JSON.parse(row.value);
// Re-key against the canonical list so a stale row (older deploy that knew
// fewer permissions) cannot accidentally grant something we just added.
const out = {};
for (const p of ROLE_PERMISSIONS) out[p] = !!parsed[p];
return _applyImplications(out);
} catch { return fallback; }
}
// Per-request permission check. Admin always passes (subject to the must-
// change-password gate, same as checkAdminAuth). Users consult the stored
// JSON for this role. Callers should follow the pattern:
// if (!checkPermission(req, 'X')) return json(res, 403, { error: ... });
function checkPermission(req, perm) {
const sess = getSession(req);
if (!sess) return false;
if (userMustChangePassword(sess.username)) return false;
if (sess.role === 'admin') return true;
const perms = getUserRolePermissions();
return !!perms[perm];
}
// ── MIME ──────────────────────────────────────────────────────────────────────
const MIME = {
'.html': 'text/html; charset=utf-8',
'.css': 'text/css; charset=utf-8',
'.js': 'application/javascript; charset=utf-8',
'.jsx': 'application/javascript; charset=utf-8',
'.json': 'application/json; charset=utf-8',
'.webmanifest': 'application/manifest+json; charset=utf-8',
'.svg': 'image/svg+xml',
'.webp': 'image/webp',
'.png': 'image/png',
'.jpg': 'image/jpeg',
'.ico': 'image/x-icon',
'.woff2': 'font/woff2',
'.woff': 'font/woff',
};
// ── Database ──────────────────────────────────────────────────────────────────
let db = null;
try {
const Database = require('better-sqlite3');
db = new Database(DB_PATH);
db.pragma('journal_mode = WAL');
db.exec(`
CREATE TABLE IF NOT EXISTS panel_users (
username TEXT PRIMARY KEY,
password_hash TEXT NOT NULL,
salt TEXT NOT NULL,
role TEXT DEFAULT 'user',
created_at TEXT DEFAULT (datetime('now'))
);
CREATE TABLE IF NOT EXISTS panel_settings (
key TEXT PRIMARY KEY,
value TEXT NOT NULL
);
CREATE TABLE IF NOT EXISTS sessions (
token TEXT PRIMARY KEY,
username TEXT NOT NULL,
role TEXT NOT NULL,
expires_at INTEGER NOT NULL
);
CREATE TABLE IF NOT EXISTS mod_history (
id INTEGER PRIMARY KEY AUTOINCREMENT,
ok INTEGER NOT NULL,
filename TEXT,
mod_type TEXT,
mod_id TEXT,
destination TEXT,
files_extracted INTEGER,
error TEXT,
uploaded_by TEXT,
uploaded_at TEXT NOT NULL DEFAULT (datetime('now'))
);
CREATE TABLE IF NOT EXISTS audit_log (
id INTEGER PRIMARY KEY AUTOINCREMENT,
actor TEXT NOT NULL,
action TEXT NOT NULL,
target TEXT DEFAULT '',
detail TEXT DEFAULT '',
logged_at TEXT NOT NULL DEFAULT (datetime('now'))
);
CREATE INDEX IF NOT EXISTS idx_audit_logged_at ON audit_log(logged_at);
CREATE TABLE IF NOT EXISTS login_attempts (
ip TEXT PRIMARY KEY,
count INTEGER NOT NULL,
reset_at INTEGER NOT NULL
);
`);
// ── Schema migrations ─────────────────────────────────────────────────────
// Numbered, idempotent, recorded in schema_migrations so we know which ones
// have run on a given DB. Each migration is a {id, sql} pair; run order is
// ascending by id. Adding a new one means appending to the array — never
// rewriting an older entry, otherwise existing DBs would skip your change.
//
// The migrations table itself uses INSERT OR IGNORE so re-running a freshly
// initialised DB is a no-op. Failing migrations log loudly and skip the
// record-insert so the next boot retries; an environment-specific failure
// (CREATE UNIQUE INDEX against duplicate rows, for instance) doesn't poison
// the chain — fix the data, restart, the migration runs again.
db.exec(`CREATE TABLE IF NOT EXISTS schema_migrations (
id INTEGER PRIMARY KEY,
name TEXT NOT NULL,
applied_at TEXT NOT NULL DEFAULT (datetime('now'))
)`);
const MIGRATIONS = [
{ id: 1, name: 'add_must_change_password',
sql: `ALTER TABLE panel_users ADD COLUMN must_change_password INTEGER NOT NULL DEFAULT 0` },
{ id: 2, name: 'audit_chain_prev_hash',
sql: `ALTER TABLE audit_log ADD COLUMN prev_hash TEXT NOT NULL DEFAULT ''` },
{ id: 3, name: 'audit_chain_row_hash',
sql: `ALTER TABLE audit_log ADD COLUMN row_hash TEXT NOT NULL DEFAULT ''` },
{ id: 4, name: 'audit_chain_version',
sql: `ALTER TABLE audit_log ADD COLUMN chain_version INTEGER NOT NULL DEFAULT 0` },
{ id: 5, name: 'audit_compound_indices',
sql: `CREATE INDEX IF NOT EXISTS idx_audit_actor ON audit_log(actor);
CREATE INDEX IF NOT EXISTS idx_audit_action ON audit_log(action);` },
{ id: 6, name: 'panel_users_totp_secret',
sql: `ALTER TABLE panel_users ADD COLUMN totp_secret TEXT NOT NULL DEFAULT ''` },
{ id: 7, name: 'panel_users_totp_enabled',
sql: `ALTER TABLE panel_users ADD COLUMN totp_enabled INTEGER NOT NULL DEFAULT 0` },
{ id: 8, name: 'panel_users_totp_pending',
sql: `ALTER TABLE panel_users ADD COLUMN totp_pending TEXT NOT NULL DEFAULT ''` },
{ id: 9, name: 'bans_table',
sql: `CREATE TABLE IF NOT EXISTS bans (
id TEXT PRIMARY KEY,
name TEXT NOT NULL DEFAULT '',
reason TEXT NOT NULL DEFAULT '',
banned_by TEXT NOT NULL DEFAULT '',
banned_at TEXT NOT NULL DEFAULT (datetime('now')),
expires_at TEXT DEFAULT NULL
);
CREATE INDEX IF NOT EXISTS idx_bans_expires_at ON bans(expires_at);` },
{ id: 10, name: 'player_events',
// History of join/leave events derived from PanelBridge state.json
// diffs. One row per transition. action ∈ ('join', 'leave'). The
// identifiers blob carries the JSON-encoded MP.GetPlayerIdentifiers
// table from the Lua plugin so we can show "this player connected
// from IP X" without re-querying the running server.
sql: `CREATE TABLE IF NOT EXISTS player_events (
id INTEGER PRIMARY KEY AUTOINCREMENT,
player_id TEXT NOT NULL,
player_name TEXT NOT NULL,
action TEXT NOT NULL,
identifiers TEXT NOT NULL DEFAULT '',
event_at TEXT NOT NULL DEFAULT (datetime('now'))
);
CREATE INDEX IF NOT EXISTS idx_player_events_at ON player_events(event_at);
CREATE INDEX IF NOT EXISTS idx_player_events_pid ON player_events(player_id);` },
{ id: 11, name: 'player_nicknames',
// SUPERSEDED by migration 12 (players table). Kept in the chain so the
// numbering stays monotonic on existing DBs that already applied it.
sql: `CREATE TABLE IF NOT EXISTS player_nicknames (
player_id TEXT PRIMARY KEY,
nickname TEXT NOT NULL,
set_by TEXT NOT NULL DEFAULT '',
updated_at TEXT NOT NULL DEFAULT (datetime('now'))
);` },
{ id: 12, name: 'players',
// Canonical one-row-per-player table, mirroring the AC fork's `players`
// table. Populated on join by the PanelBridge event loop (UPSERT with
// first_seen on insert, last_seen on update). The Players page and the
// history endpoint join on this so the operator-set nickname renders
// alongside the in-game name on both live + past lists. Backfills from
// player_events on first apply so DBs with pre-existing history get a
// fully populated players list immediately, without waiting for every
// historical id to reconnect once.
sql: `CREATE TABLE IF NOT EXISTS players (
id TEXT PRIMARY KEY,
name TEXT NOT NULL DEFAULT '',
nickname TEXT NOT NULL DEFAULT '',
first_seen TEXT NOT NULL DEFAULT (datetime('now')),
last_seen TEXT NOT NULL DEFAULT (datetime('now'))
);
CREATE INDEX IF NOT EXISTS idx_players_last_seen ON players(last_seen);
INSERT OR IGNORE INTO players (id, name, first_seen, last_seen)
SELECT player_id, MAX(player_name), MIN(event_at), MAX(event_at)
FROM player_events
GROUP BY player_id;` },
{ id: 13, name: 'players_stable_id_purge',
// Up to this migration the PanelBridge consumer was using BeamMP's
// per-session SLOT NUMBER (0, 1, 2…) as the canonical player_id,
// collapsing every guest that ever held slot 0 into a single row.
// Stable IDs (now prefixed bmp:/ip:/slot:) land starting with this
// commit, so the cleanest path is to drop the pre-fix history — it
// can't be reattributed and keeping it just confuses the history
// view. Stable rows survive because their player_id is no longer
// purely numeric.
sql: `DELETE FROM player_events WHERE player_id GLOB '[0-9]*' AND player_id NOT GLOB '*:*';
DELETE FROM players WHERE id GLOB '[0-9]*' AND id NOT GLOB '*:*';
DELETE FROM bans WHERE id GLOB '[0-9]*' AND id NOT GLOB '*:*';` },
];
const _appliedRows = db.prepare('SELECT id FROM schema_migrations').all();
const _applied = new Set(_appliedRows.map(r => r.id));
const _recordMigration = db.prepare('INSERT OR IGNORE INTO schema_migrations (id, name) VALUES (?, ?)');
for (const m of MIGRATIONS) {
if (_applied.has(m.id)) continue;
try {
db.exec(m.sql);
_recordMigration.run(m.id, m.name);
console.log(` migration ${String(m.id).padStart(3, '0')}: ${m.name} ✓`);
} catch (e) {
// ALTER TABLE on an existing column throws "duplicate column" — that's
// exactly the upgrade-in-place case where the column was added by the
// pre-migrations-runner ALTER+catch code. Record the migration as
// applied so we don't retry next boot, but log it for visibility.
const msg = String(e && e.message || e);
if (/duplicate column|already exists/i.test(msg)) {
_recordMigration.run(m.id, m.name);
console.log(` migration ${String(m.id).padStart(3, '0')}: ${m.name} (already present, recorded)`);
} else {
console.error(` migration ${String(m.id).padStart(3, '0')} ${m.name} FAILED:`, msg);
}
}
}
// Seed default settings
db.prepare(`INSERT OR IGNORE INTO panel_settings (key, value) VALUES ('upload_max_mb', '500')`).run();
db.prepare(`INSERT OR IGNORE INTO panel_settings (key, value) VALUES ('lang', 'en')`).run();
db.prepare(`INSERT OR IGNORE INTO panel_settings (key, value) VALUES ('chunked_upload', '0')`).run();
db.prepare(`INSERT OR IGNORE INTO panel_settings (key, value) VALUES ('discord_webhook', '')`).run();
// Public per-player profile pages reachable at /p/<guid> with a matching
// JSON view at /api/public/players/<guid>. On by default so the feature is
// discoverable; admins can flip it off if the server isn't meant to be
// visible at all (e.g. development boxes behind Cloudflare Access).
db.prepare(`INSERT OR IGNORE INTO panel_settings (key, value) VALUES ('public_profiles_enabled', '1')`).run();
// Default permission set for the `user` role. Server control and mod upload
// were already open to users before granular permissions shipped, so an
// upgrade in place doesn't yank capabilities away from existing accounts.
db.prepare(`INSERT OR IGNORE INTO panel_settings (key, value) VALUES ('role_permissions_user', ?)`)
.run(JSON.stringify({
serverControl: true,
modUpload: true,
serverConfig: false,
whitelistManage: false,
playerModeration: false,
discordWebhook: false,
auditView: false,
dbBackup: false,
}));
console.log(' Database ready:', DB_PATH);
} catch (e) {
console.error(' Database init failed:', e.message);
}
// ── Auth helpers ─────────────────────────────────────────────────────────────
// Stored hash format: "scrypt$<hex>" (current) or bare hex (legacy pbkdf2).
// Legacy hashes are upgraded in-place on the next successful login.
//
// Both hash and verify must use IDENTICAL scrypt parameters; relying on Node's
// defaults to "happen to match" is brittle (if a future Node release bumps the
// defaults, every existing password silently fails to verify). Pin the cost
// explicitly in one constant and pass it to both code paths.
const SCRYPT_PARAMS = { N: 16384, r: 8, p: 1 };
const SCRYPT_KEYLEN = 64;
function hashPasswordScrypt(password, salt) {
return 'scrypt$' + crypto.scryptSync(password, salt, SCRYPT_KEYLEN, SCRYPT_PARAMS).toString('hex');
}
function hashPasswordPbkdf2(password, salt) {
return crypto.pbkdf2Sync(password, salt, 100000, 64, 'sha512').toString('hex');
}
function hashPassword(password, salt) {
return hashPasswordScrypt(password, salt);
}
// Pre-computed dummy hash used by apiAuthLogin when the username is unknown.
// Without this the login path returns ~immediately for non-existent users but
// spends ~50ms in scryptSync for real users — a measurable timing oracle that
// lets an attacker enumerate valid usernames. By running verifyPassword against
// this dummy in the not-found branch, both paths perform exactly one scrypt.
// Computed once at module load with a fixed salt — never used to authenticate.
const _DUMMY_LOGIN_SALT = 'a'.repeat(64);
const _DUMMY_LOGIN_HASH = hashPasswordScrypt('not-a-real-password-do-not-use', _DUMMY_LOGIN_SALT);
function verifyPassword(password, salt, stored) {
if (typeof stored !== 'string' || !stored) return false;
try {
if (stored.startsWith('scrypt$')) {
const expected = stored.slice(7);
const candidate = crypto.scryptSync(password, salt, SCRYPT_KEYLEN, SCRYPT_PARAMS).toString('hex');
return safeHexEqual(candidate, expected);
}
// Legacy pbkdf2 (bare hex)
const candidate = hashPasswordPbkdf2(password, salt);
return safeHexEqual(candidate, stored);
} catch { return false; }
}
// Server-side password policy. Returns null when accepted, otherwise a human
// readable error message. Mirror this in the UI for nicer feedback, but the
// check here is the authoritative gate.
function passwordPolicyError(pw) {
if (typeof pw !== 'string') return 'Password must be a string';
if (pw.length < 12) {
// Allow ≥8 chars only when the password mixes at least three character classes
if (pw.length < 8) return 'Password must be at least 8 characters';
const classes = [/[a-z]/, /[A-Z]/, /[0-9]/, /[^a-zA-Z0-9]/].filter(rx => rx.test(pw)).length;
if (classes < 3) return 'Short passwords (8–11 chars) need a mix of lowercase, UPPERCASE, digits and a symbol';
}
if (pw.length > 128) return 'Password must be at most 128 characters';
// Reject the most obvious sentinels
const banned = new Set(['password', 'qwerty12', 'admin1234', 'admin1234!', '12345678', 'changeme', 'letmein!']);
if (banned.has(pw.toLowerCase())) return 'This password is too common — choose something different';
return null;
}
function safeHexEqual(a, b) {
if (typeof a !== 'string' || typeof b !== 'string' || a.length !== b.length) return false;
try {
return crypto.timingSafeEqual(Buffer.from(a, 'hex'), Buffer.from(b, 'hex'));
} catch { return false; }
}
// ── TOTP (RFC 6238) ──────────────────────────────────────────────────────────
// Time-based one-time password generator + verifier, implemented inline so we
// don't pull in another npm dep. Standard parameters (SHA-1, 30-second step,
// 6 digits) — every off-the-shelf authenticator app (Aegis, Authy, Bitwarden,
// 2FAS, Google Authenticator, etc.) reads them out of the otpauth:// URI.
//
// The secret is stored as base32 in panel_users.totp_secret. Setup writes the
// candidate into totp_pending; only after the user confirms by entering a
// valid code from their app does it move into totp_secret + totp_enabled=1.
// This prevents a half-setup state where 2FA is "on" but the user never
// scanned the QR.
const _BASE32_ALPHABET = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ234567';
function _base32Encode(buf) {
let bits = '';
for (const b of buf) bits += b.toString(2).padStart(8, '0');
let out = '';
for (let i = 0; i < bits.length; i += 5) {
out += _BASE32_ALPHABET[parseInt(bits.slice(i, i + 5).padEnd(5, '0'), 2)];
}
return out;
}
function _base32Decode(str) {
const clean = String(str || '').toUpperCase().replace(/[^A-Z2-7]/g, '');
let bits = '';
for (const c of clean) bits += _BASE32_ALPHABET.indexOf(c).toString(2).padStart(5, '0');
const bytes = [];
for (let i = 0; i + 8 <= bits.length; i += 8) bytes.push(parseInt(bits.slice(i, i + 8), 2));
return Buffer.from(bytes);
}
function _totpCode(secretBuf, time = Math.floor(Date.now() / 1000), step = 30, digits = 6) {
const counter = Math.floor(time / step);
const buf = Buffer.alloc(8);
buf.writeBigUInt64BE(BigInt(counter), 0);
const hmac = crypto.createHmac('sha1', secretBuf).update(buf).digest();
const off = hmac[hmac.length - 1] & 0x0f;
const bin = ((hmac[off] & 0x7f) << 24) |
((hmac[off + 1] & 0xff) << 16) |
((hmac[off + 2] & 0xff) << 8) |
( hmac[off + 3] & 0xff);
return String(bin % (10 ** digits)).padStart(digits, '0');
}
// Constant-time string compare so the verifier doesn't leak which digit
// failed via timing. Both sides must be the same length already.
function _ctEqual(a, b) {
if (typeof a !== 'string' || typeof b !== 'string' || a.length !== b.length) return false;
try { return crypto.timingSafeEqual(Buffer.from(a), Buffer.from(b)); } catch { return false; }
}
function totpVerify(secretB32, code, drift = 1) {
if (!secretB32 || !code || !/^\d{6}$/.test(String(code))) return false;
const key = _base32Decode(secretB32);
if (!key.length) return false;
const now = Math.floor(Date.now() / 1000);
for (let i = -drift; i <= drift; i++) {
if (_ctEqual(_totpCode(key, now + i * 30), String(code))) return true;
}
return false;
}
function totpProvisioningUri({ secret, account, issuer }) {
// otpauth://totp/<issuer>:<account>?secret=...&issuer=...&algorithm=SHA1&digits=6&period=30
const label = encodeURIComponent(`${issuer}:${account}`);
const params = new URLSearchParams({ secret, issuer, algorithm: 'SHA1', digits: '6', period: '30' });
return `otpauth://totp/${label}?${params}`;
}
function seedDefaultUsers() {
if (!db) return;
try {
const DEFAULT_PASS = 'Admin1234!';
for (const [username, role] of [['Admin', 'admin']]) {
const existing = db.prepare('SELECT 1 FROM panel_users WHERE username = ?').get(username);
if (!existing) {
const salt = crypto.randomBytes(32).toString('hex');
db.prepare('INSERT INTO panel_users (username, password_hash, salt, role, must_change_password) VALUES (?, ?, ?, ?, 1)')
.run(username, hashPassword(DEFAULT_PASS, salt), salt, role);
}
}
} catch (e) {
console.error(' User seed failed:', e.message);
}
}
// ── Helpers ───────────────────────────────────────────────────────────────────
function getNetworkIP() {
for (const ifaces of Object.values(os.networkInterfaces())) {
for (const iface of ifaces) {
if (iface.family === 'IPv4' && !iface.internal) return iface.address;
}
}
return '127.0.0.1';
}
function setSecurityHeaders(req, res) {
// Stash the request on the response so downstream helpers (respond, json)
// can negotiate Content-Encoding without every call site threading req
// through manually. Set once per request inside the handler.
res._acReq = req;
res.setHeader('X-Frame-Options', 'DENY');
res.setHeader('X-Content-Type-Options', 'nosniff');
res.setHeader('Referrer-Policy', 'strict-origin-when-cross-origin');
// The panel is an admin tool, not a public website — keep it out of search
// engines so the login URL never surfaces in Google/Bing results when an
// operator forgets to gate the panel behind a private network. The meta tag
// in index.html covers HTML navigation; this header is what crawlers see on
// every other response (assets, JSON, JS bundles) and on the index.html
// fetch itself when only the headers are read.
res.setHeader('X-Robots-Tag', 'noindex, nofollow, noarchive, nosnippet, noimageindex');
// Lock down browser features the panel never uses
res.setHeader('Permissions-Policy',
'accelerometer=(), camera=(), geolocation=(), gyroscope=(), magnetometer=(), microphone=(), payment=(), usb=()');
// Content Security Policy. JSX is now pre-transpiled by build.js (esbuild) and
// served from /dist/ as plain JS, so 'unsafe-eval' / 'unsafe-inline' are no
// longer required. 'unsafe-inline' for style stays — many components use inline
// style props which compile to inline `style="..."` attributes.
res.setHeader('Content-Security-Policy', [
"default-src 'self'",
"script-src 'self' https://unpkg.com",
"style-src 'self' 'unsafe-inline' https://fonts.googleapis.com",
"font-src 'self' https://fonts.gstatic.com data:",
"img-src 'self' data: https:",
"connect-src 'self'",
"frame-ancestors 'none'",
"base-uri 'self'",
"form-action 'self'",
"object-src 'none'",
].join('; '));
// HSTS only when the connection actually arrived over HTTPS (or via a TLS-terminating proxy).
if (requestIsHttps(req)) {
res.setHeader('Strict-Transport-Security', 'max-age=31536000; includeSubDomains');
}
}
// Content types worth compressing. Already-compressed formats (webp, png,
// jpeg, woff2, …) come from MIME elsewhere and skip this path; for JSON, HTML,
// CSS, JS the saving over the wire is typically 4–8x and the CPU cost of
// gzip/brotli at default levels is negligible compared to the bytes saved.
const _COMPRESSIBLE_MIME = /^(?:application\/(?:json|javascript|manifest\+json)|text\/(?:plain|html|css|csv|event-stream))(?:\b|;)/i;
const _COMPRESS_MIN_BYTES = 1024; // skip compression for tiny payloads where the headers cost more than they save
function _negotiateEncoding(req, mime, bodyLen) {
if (!_COMPRESSIBLE_MIME.test(mime)) return null;
if (bodyLen < _COMPRESS_MIN_BYTES) return null;
const ae = (req?.headers?.['accept-encoding'] || '').toLowerCase();
if (!ae) return null;
// Prefer brotli (smaller) when offered, otherwise gzip. Identity ('') is
// always acceptable as a fallback.
if (ae.includes('br')) return 'br';
if (ae.includes('gzip')) return 'gzip';
return null;
}
function _compress(body, encoding) {
const buf = Buffer.isBuffer(body) ? body : Buffer.from(body);
if (encoding === 'br') return zlib.brotliCompressSync(buf, { params: { [zlib.constants.BROTLI_PARAM_QUALITY]: 5 } });
if (encoding === 'gzip') return zlib.gzipSync(buf, { level: 6 });
return buf;
}
// `req` for Accept-Encoding negotiation is pulled from res._acReq (stashed by
// setSecurityHeaders) so existing call sites don't have to thread it through.
// Older callers (or paths that bypass setSecurityHeaders) still work — they
// just don't benefit from compression.
function respond(res, status, mime, body, extraHeaders) {
const headers = {
'Content-Type': mime,
'Cache-Control': 'no-cache, no-store, must-revalidate',
'Vary': 'Accept-Encoding',
...extraHeaders,
};
let payload = body;
const req = res._acReq;
if (req && body && !headers['Content-Encoding']) {
const bodyLen = Buffer.isBuffer(body) ? body.length : Buffer.byteLength(body);
const enc = _negotiateEncoding(req, mime, bodyLen);
if (enc) {
payload = _compress(body, enc);
headers['Content-Encoding'] = enc;
}
}
res.writeHead(status, headers);
res.end(payload);
}
function respondImage(res, data, mime = 'image/png') {
res.writeHead(200, {
'Content-Type': mime,
'Cache-Control': 'public, max-age=3600',
});
res.end(data);
}
function serveAssetFallback(res, candidates) {
const tryNext = (index) => {
if (index >= candidates.length) return json(res, 404, { error: 'Asset not found' });
const { path: p, mime } = candidates[index];
fs.readFile(p, (err, data) => {
if (err) tryNext(index + 1);
else respondImage(res, data, mime);
});
};
tryNext(0);
}
function json(res, status, data) {
respond(res, status, 'application/json; charset=utf-8', JSON.stringify(data));
}
function readBody(req) {
const ct = req.headers['content-type'] || '';
if (!ct.includes('application/json')) return Promise.reject(new Error('Content-Type must be application/json'));
return new Promise((resolve, reject) => {
let raw = '';
let settled = false;
const settle = (fn, arg) => { if (settled) return; settled = true; clearTimeout(timer); fn(arg); };
// Hard timeout: a slow-loris client could otherwise stream a few bytes
// every minute and tie up a file descriptor + this promise forever. 30s
// is far longer than any real JSON body needs (the largest legitimate
// payload is ~10 MB chunked upload, which streams in seconds).
const timer = setTimeout(() => {
try { req.destroy(); } catch {}
settle(reject, new Error('Request body timeout'));
}, 30000);
req.on('data', chunk => {
raw += chunk;
if (raw.length > 512_000) {
try { req.destroy(); } catch {}
settle(reject, new Error('Body too large'));
}
});
req.on('end', () => { try { settle(resolve, JSON.parse(raw)); } catch { settle(reject, new Error('Invalid JSON')); } });
req.on('error', e => settle(reject, e));
});
}
// Best-effort prettifier for raw mod ids: turn `some_long_mod_id` into a more
// human-readable `Some Long Mod Id`. Used when no proper display name is
// available from the mod metadata.
function formatName(id) {
return id
.replace(/_/g, ' ')
.replace(/\b([a-z])/g, (_, c) => c.toUpperCase())
.trim();
}
function getPanelLang() {
try {
const row = db?.prepare(`SELECT value FROM panel_settings WHERE key = 'lang'`).get();
const v = row?.value;
return DISCORD_RECORD_TEMPLATES[v] ? v : 'en';
} catch { return 'en'; }
}
function getDiscordWebhook() {
try {
const row = db?.prepare(`SELECT value FROM panel_settings WHERE key = 'discord_webhook'`).get();
return row?.value || '';
} catch { return ''; }
}
// Discord webhook hosts — the only acceptable destinations for postDiscordMessage
// and apiDiscordWebhookTest. Defense in depth on top of isValidDiscordWebhook's
// regex: the regex validates the string shape, but `new URL(...)` could in
// principle yield a hostname that differs (IDN normalisation, unicode tricks,