-
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathserver.js
More file actions
8774 lines (8258 loc) · 417 KB
/
Copy pathserver.js
File metadata and controls
8774 lines (8258 loc) · 417 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 (systemd unit, docker, fresh clone)
// would otherwise serve a stale or empty dist/ — users see old UI even after
// pulling new src/. Compare newest src/ mtime against the dist/app.js marker
// and rebuild only when needed so warm restarts stay fast.
(function ensureBuildFresh() {
if (process.env.SKIP_BUILD) return; // trust the pre-built dist/ (e.g. the runtime image where esbuild was pruned)
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
// acServer child (which is empty whenever acServer was adopted via pidof).
_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 ────────────────────────────────────────────────────────────────────
// The four AC_* env vars below are the only ones a fresh install must supply.
// Everything else (results dir, log file, blacklist/whitelist paths) is
// derived so an operator can ship a 4-line .env and have it work.
//
// Auto-detect when an env var is missing: walk a small list of conventional
// paths and pick the first one that exists. Order matches what the README
// recommends — user-home install first, then the system-wide /srv layout.
function _firstExistingPath(candidates) {
for (const p of candidates) {
if (!p) continue;
try { fs.accessSync(p); return p; } catch {}
}
return null;
}
const _DEFAULT_AC_ROOTS = [
process.env.HOME && path.join(process.env.HOME, 'ac_server'),
'/srv/assetto',
'/opt/ac_server',
'/srv/acserver',
].filter(Boolean);
const _detectedAcRoot = _firstExistingPath(_DEFAULT_AC_ROOTS);
// When neither the env var nor any auto-detect candidate exists, the panel
// still needs *some* string for the AC_* constants so error messages mention
// a real-looking path. Default to ~/ac_server (the documented convention) so
// the user sees a path they recognise from .env.example, not a system path
// they never chose.
const _FALLBACK_AC_ROOT = process.env.HOME ? path.join(process.env.HOME, 'ac_server') : '/opt/ac_server';
function _ac(envName, ...relParts) {
if (process.env[envName]) return process.env[envName];
if (!_detectedAcRoot) return null;
return path.join(_detectedAcRoot, ...relParts);
}
const HOST = process.env.HOST || '127.0.0.1';
const PORT = parseInt(process.env.PORT || '3000', 10);
const AC_HTTP_PORT = parseInt(process.env.AC_HTTP_PORT || '8081', 10);
// AC_SERVER_DIR is the anchor: if the env var is missing, prefer an explicit
// AC_SERVER_BIN's parent, then the auto-detected root. The other AC_* paths
// fall back to subdirs of this anchor.
const AC_BIN_RAW = process.env.AC_SERVER_BIN || _ac('AC_SERVER_BIN', 'acServer');
const AC_BIN_DIR_RAW = process.env.AC_SERVER_DIR
|| (AC_BIN_RAW ? path.dirname(AC_BIN_RAW) : null)
|| _detectedAcRoot
|| _FALLBACK_AC_ROOT;
const AC_BIN = AC_BIN_RAW || path.join(AC_BIN_DIR_RAW, 'acServer');
const AC_BIN_DIR = AC_BIN_DIR_RAW;
const AC_LOG_FILE = process.env.AC_SERVER_LOG || path.join(__dirname, 'logs', 'ac_server.log');
const AC_RESULTS = process.env.AC_SERVER_RESULTS || path.join(AC_BIN_DIR, 'results');
const _AC_CFG_DIR_RESOLVED = process.env.AC_CFG_DIR
|| path.join(_detectedAcRoot || _FALLBACK_AC_ROOT, 'cfg');
const AC_CFG_FILE = path.join(_AC_CFG_DIR_RESOLVED, 'server_cfg.ini');
const _AC_CONTENT_DIR_RESOLVED = process.env.AC_CONTENT_DIR
|| path.join(_detectedAcRoot || _FALLBACK_AC_ROOT, 'content');
const AC_CARS_DIR = path.join(_AC_CONTENT_DIR_RESOLVED, 'cars');
const AC_TRACKS_DIR= path.join(_AC_CONTENT_DIR_RESOLVED, 'tracks');
const DB_PATH = process.env.DB_PATH || path.join(__dirname, 'assetto.db');
const AC_BLACKLIST = path.resolve(process.env.AC_BLACKLIST_FILE || path.join(AC_BIN_DIR, 'blacklist.txt'));
const ADMIN_TOKEN = process.env.ADMIN_TOKEN || '';
const ROOT = __dirname;
const KUNOS_ASSETS_DIR = path.join(__dirname, 'src/assets/kunos');
// 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(20)} ${p || '(unset)'} ${p ? (exists(p) ? '✓' : '✗ MISSING') : ''}`;
console.log(' AC paths:');
console.log(status('AC_CFG_DIR', _AC_CFG_DIR_RESOLVED));
console.log(status('AC_CONTENT_DIR', _AC_CONTENT_DIR_RESOLVED));
console.log(status('AC_SERVER_BIN', AC_BIN));
console.log(status('AC_SERVER_DIR', AC_BIN_DIR));
if (!process.env.AC_CFG_DIR && !process.env.AC_CONTENT_DIR && _detectedAcRoot) {
console.log(` (auto-detected root: ${_detectedAcRoot})`);
}
if (!exists(AC_CFG_FILE)) {
console.warn(` ⚠️ server_cfg.ini not found at ${AC_CFG_FILE}. The Config / Session pages will`);
console.warn(` show an error until you point AC_CFG_DIR at the directory that holds it.`);
}
}
let acChild = null; // tracked child process for the AC server
// ── 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(AC_LOG_FILE), { recursive: true });
const content = fs.readFileSync(AC_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 AC_LOG_FILE for new lines and push them to appendLog. acServer now
// 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(AC_LOG_FILE).size; } catch { _logTailPos = 0; }
const LINE_BUF_MAX = 8 * 1024;
const flush = () => {
let size;
try { size = fs.statSync(AC_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(AC_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(AC_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 AC_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 = ''; }
// Authoritative Kunos content ID sets, populated at startup from bundled assets
const KUNOS_CAR_IDS = new Set();
const KUNOS_TRACK_IDS = new Set();
async function loadKunosIds() {
try { for (const id of await fsp.readdir(path.join(KUNOS_ASSETS_DIR, 'cars'))) KUNOS_CAR_IDS.add(id); } catch {}
try { for (const id of await fsp.readdir(path.join(KUNOS_ASSETS_DIR, 'tracks'))) KUNOS_TRACK_IDS.add(id); } catch {}
}
// ── 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', 'sessionEdit', 'serverConfig', 'presetManage', 'whitelistManage',
'playerModeration', 'modUpload', 'discordWebhook', 'auditView', 'dbBackup',
];
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 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 processed_files (
filename TEXT PRIMARY KEY,
processed_at TEXT NOT NULL
);
CREATE TABLE IF NOT EXISTS players (
guid TEXT PRIMARY KEY,
name TEXT NOT NULL,
nation TEXT DEFAULT '',
first_seen TEXT DEFAULT '',
last_seen TEXT DEFAULT '',
total_laps INTEGER DEFAULT 0,
last_car TEXT DEFAULT '',
last_track TEXT DEFAULT ''
);
CREATE TABLE IF NOT EXISTS laps (
id INTEGER PRIMARY KEY AUTOINCREMENT,
driver_name TEXT NOT NULL,
driver_guid TEXT NOT NULL,
car TEXT NOT NULL,
track TEXT NOT NULL,
track_config TEXT DEFAULT '',
ms INTEGER NOT NULL,
lap_timestamp INTEGER DEFAULT 0,
s1 INTEGER DEFAULT 0,
s2 INTEGER DEFAULT 0,
s3 INTEGER DEFAULT 0,
cuts INTEGER DEFAULT 0,
valid INTEGER DEFAULT 1,
session_date TEXT DEFAULT '',
source_file TEXT DEFAULT '',
UNIQUE(driver_guid, car, track, track_config, lap_timestamp, source_file)
);
CREATE INDEX IF NOT EXISTS idx_laps_track ON laps(track);
CREATE INDEX IF NOT EXISTS idx_laps_driver ON laps(driver_guid);
CREATE INDEX IF NOT EXISTS idx_laps_valid ON laps(valid);
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: 'players_nickname',
sql: `ALTER TABLE players ADD COLUMN nickname TEXT NOT NULL DEFAULT ''` },
{ id: 6, name: 'laps_dedup_runtime_index',
sql: `CREATE UNIQUE INDEX IF NOT EXISTS laps_dedup_runtime
ON laps(driver_guid, ms, car, track, track_config)` },
{ id: 7, 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: 8, name: 'panel_users_totp_secret',
sql: `ALTER TABLE panel_users ADD COLUMN totp_secret TEXT NOT NULL DEFAULT ''` },
{ id: 9, name: 'panel_users_totp_enabled',
sql: `ALTER TABLE panel_users ADD COLUMN totp_enabled INTEGER NOT NULL DEFAULT 0` },
{ id: 10, name: 'panel_users_totp_pending',
sql: `ALTER TABLE panel_users ADD COLUMN totp_pending TEXT NOT NULL DEFAULT ''` },
{ id: 11, name: 'bans_table',
sql: `CREATE TABLE IF NOT EXISTS bans (
guid TEXT PRIMARY KEY,
name_snapshot 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: 12, name: 'session_presets_table',
// Saved bundles of (trackId, layout, slots[], session toggles, weather, time,
// penalties…) that an operator can browse and "Load into Session" with one
// click. The `config` column is a JSON blob keeping the exact same shape
// `sessionCfg` has on the client + the same shape /api/session/apply
// consumes — so adding a field to Session in the future doesn't need a
// schema change here, just a default-fill on load. `name` is UNIQUE
// (case-insensitive) so re-saving a preset with the same name reads as an
// overwrite, not a silent duplicate.
sql: `CREATE TABLE IF NOT EXISTS session_presets (
id INTEGER PRIMARY KEY AUTOINCREMENT,
name TEXT NOT NULL,
description TEXT NOT NULL DEFAULT '',
config TEXT NOT NULL,
created_by TEXT NOT NULL DEFAULT '',
created_at TEXT NOT NULL DEFAULT (datetime('now')),
updated_at TEXT NOT NULL DEFAULT (datetime('now'))
);
CREATE UNIQUE INDEX IF NOT EXISTS idx_session_presets_name_nocase ON session_presets(name COLLATE NOCASE);` },
{ id: 13, name: 'laps_combo_ms_index',
// Covering index for per-(track, layout, car) record lookups. Serves the
// WHERE track/track_config/car/valid + MIN(ms) in maybeNotifyRecord (runs on
// every inserted lap) and the `WHERE valid=1 GROUP BY track, track_config,
// car` MIN(ms) subquery + correlated (track, track_config, car, ms) lookups
// behind public player records. Only idx_laps_track(track) existed, so those
// fell back to a scan + temp b-tree; this turns them into a covering range.
sql: `CREATE INDEX IF NOT EXISTS idx_laps_combo_ms
ON laps(track, track_config, car, valid, ms)` },
{ id: 14, name: 'panel_users_role_index',
sql: `CREATE INDEX IF NOT EXISTS idx_panel_users_role ON panel_users(role)` },
];
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);
}
}
}
// Refresh SQLite's query-planner stats after migrations (cheap; pairs with the
// periodic optimize in sweepDbMaintenance).
try { db.pragma('optimize'); } catch {}
// 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. Mirrors the live state right
// before this granular-permissions feature shipped (server control, session
// edit and mod upload were already open to users), so an upgrade in place
// doesn't yank capabilities away from existing accounts.
const DEFAULT_USER_PERMS = {
serverControl: true,
sessionEdit: true,
modUpload: true,
presetManage: true,
serverConfig: false,
whitelistManage: false,
playerModeration: false,
discordWebhook: false,
auditView: false,
dbBackup: false,
};
db.prepare(`INSERT OR IGNORE INTO panel_settings (key, value) VALUES ('role_permissions_user', ?)`)
.run(JSON.stringify(DEFAULT_USER_PERMS));
// Backfill: for installs predating a release that introduced a new
// permission key, the stored row won't have an entry for it and
// getUserRolePermissions() will report it as false. Re-insert any missing
// key with its intended default so "granted by default" actually applies
// to existing user accounts, not just fresh installs. Only ADDS missing
// keys — never overwrites a value the admin has already set.
try {
const row = db.prepare(`SELECT value FROM panel_settings WHERE key = 'role_permissions_user'`).get();
if (row?.value) {
const parsed = JSON.parse(row.value);
let changed = false;
for (const [k, v] of Object.entries(DEFAULT_USER_PERMS)) {
if (!(k in parsed)) { parsed[k] = v; changed = true; }
}
if (changed) {
db.prepare(`UPDATE panel_settings SET value = ? WHERE key = 'role_permissions_user'`)
.run(JSON.stringify(parsed));
}
}
} catch {}
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);
}
}
// ── Results importer ──────────────────────────────────────────────────────────
function parseDateFromFilename(name) {
const m = name.match(/^(\d{4})_(\d{1,2})_(\d{1,2})/);
return m ? `${m[1]}-${String(m[2]).padStart(2,'0')}-${String(m[3]).padStart(2,'0')}` : '';
}
async function importResultFile(filename) {
if (!db) return false;
const filepath = path.join(AC_RESULTS, filename);
try {
const raw = await fsp.readFile(filepath, 'utf8');
const data = JSON.parse(raw);
const date = parseDateFromFilename(filename);
const track = data.TrackName || '';
const trackConfig = data.TrackConfig || '';
// Build player metadata from Cars array (has nation info)
const playerMeta = {};
for (const c of (data.Cars || [])) {
if (c.Driver?.Guid && c.Driver.Name) {
playerMeta[c.Driver.Guid] = {
name: c.Driver.Name,
nation: c.Driver.Nation || '',
car: c.Model || '',
};
}
}
const stmtLap = db.prepare(`
INSERT OR IGNORE INTO laps
(driver_name, driver_guid, car, track, track_config, ms, lap_timestamp, s1, s2, s3, cuts, valid, session_date, source_file)
VALUES
(@driver_name, @driver_guid, @car, @track, @track_config, @ms, @lap_timestamp, @s1, @s2, @s3, @cuts, @valid, @session_date, @source_file)
`);
// When the UDP plugin already recorded a lap live, the row exists with
// a placeholder s1 = lap_time and s2=s3=0. The JSON has authoritative
// sector data (or the same lap_time-in-s1 layout if the track doesn't
// emit per-sector splits), so we replace the row's sectors + canonical
// lap_timestamp + source_file. Guard by `source_file='udp:live'` so we
// only touch rows the UDP listener was the sole writer of — never
// clobber a previous JSON import.
const stmtFillSectors = db.prepare(`
UPDATE laps
SET s1 = @s1, s2 = @s2, s3 = @s3,
lap_timestamp = @lap_timestamp,
source_file = @source_file
WHERE driver_guid = @driver_guid
AND ms = @ms
AND car = @car
AND track = @track
AND track_config = @track_config
AND source_file = 'udp:live'
`);
const stmtPlayer = db.prepare(`
INSERT INTO players (guid, name, nation, first_seen, last_seen, total_laps, last_car, last_track)
VALUES (@guid, @name, @nation, @date, @date, @cnt, @car, @track)
ON CONFLICT(guid) DO UPDATE SET
name = excluded.name,
nation = CASE WHEN excluded.nation != '' THEN excluded.nation ELSE players.nation END,
last_seen = MAX(players.last_seen, excluded.last_seen),
first_seen = CASE WHEN players.first_seen = '' OR (excluded.first_seen != '' AND excluded.first_seen < players.first_seen)
THEN excluded.first_seen ELSE players.first_seen END,
total_laps = players.total_laps + excluded.total_laps,
last_car = excluded.last_car,
last_track = excluded.last_track
`);
const doImport = db.transaction(() => {
const lapsByPlayer = {};
for (const l of (data.Laps || [])) {
if (!l.DriverGuid || !l.DriverName) continue;
if (!l.LapTime || l.LapTime >= 999_000_000) continue;
const sectors = l.Sectors || [];
const s1 = (sectors[0] > 0 && sectors[0] < 2_000_000) ? sectors[0] : 0;
const s2 = (sectors[1] > 0 && sectors[1] < 2_000_000) ? sectors[1] : 0;
const s3 = (sectors[2] > 0 && sectors[2] < 2_000_000) ? sectors[2] : 0;
const payload = {
driver_name: l.DriverName,
driver_guid: l.DriverGuid,
car: l.CarModel || '',
track,
track_config: trackConfig,
ms: l.LapTime,
lap_timestamp: l.Timestamp || 0,
s1, s2, s3,
cuts: l.Cuts || 0,
valid: (l.Cuts || 0) === 0 ? 1 : 0,
session_date: date,
source_file: filename,
};
const r = stmtLap.run(payload);
if (r.changes > 0) {
if (!lapsByPlayer[l.DriverGuid]) lapsByPlayer[l.DriverGuid] = { cnt: 0, name: l.DriverName, car: l.CarModel || '' };
lapsByPlayer[l.DriverGuid].cnt++;
} else {
// Row already exists (UDP plugin captured it live). Fill in sectors
// and the canonical lap_timestamp + source_file from the JSON if
// the existing row only had the live snapshot.
stmtFillSectors.run(payload);
}
}
for (const [guid, info] of Object.entries(lapsByPlayer)) {
const meta = playerMeta[guid] || {};
stmtPlayer.run({
guid,
name: meta.name || info.name,
nation: meta.nation || '',
date: date || '',
cnt: info.cnt,
car: info.car,
track,
});
}
// Ensure players who connected but had no valid laps still appear
for (const [guid, meta] of Object.entries(playerMeta)) {
db.prepare(`
INSERT OR IGNORE INTO players (guid, name, nation, first_seen, last_seen, total_laps, last_car, last_track)
VALUES (?, ?, ?, ?, ?, 0, ?, ?)
`).run(guid, meta.name, meta.nation, date || '', date || '', meta.car, track);
}
});
doImport();
db.prepare(`INSERT OR REPLACE INTO processed_files (filename, processed_at) VALUES (?, datetime('now'))`).run(filename);
return true;
} catch (e) {
console.error(` Import failed [${filename}]:`, e.message);
return false;
}
}
async function importAllResults() {
if (!db) return;
try {
const files = (await fsp.readdir(AC_RESULTS)).filter(f => f.endsWith('.json')).sort();
let imported = 0;
for (const file of files) {
const already = db.prepare('SELECT 1 FROM processed_files WHERE filename = ?').get(file);
if (!already && await importResultFile(file)) imported++;
}
if (imported > 0) console.log(` Imported ${imported} result file(s) into database`);
} catch (e) {
if (e.code !== 'ENOENT') console.error(' Cannot scan results dir:', e.message);
}
}
const _pendingImports = new Set();
// Defensive shape check on watcher-supplied filenames. Linux's fs.watch
// normally hands us a leaf basename, but exotic filesystems (FUSE, NFS,
// SMB mounts) can return arbitrary strings — including ones containing
// `..` or path separators. importResultFile does path.join(AC_RESULTS,
// filename), and a `..` would escape the directory. This check refuses
// anything that isn't a plain basename ending in `.json`.
function _isSafeResultFilename(name) {
if (typeof name !== 'string' || !name) return false;
if (name.length > 128) return false;
if (name.includes('/') || name.includes('\\') || name.includes('\0')) return false;
if (name === '.' || name === '..' || name.includes('..')) return false;
return /^[A-Za-z0-9_\-.]+\.json$/.test(name);
}
function startResultsWatcher() {
if (!db) return;
try {
fs.watch(AC_RESULTS, (eventType, filename) => {
if (!_isSafeResultFilename(filename)) return;
if (_pendingImports.has(filename)) return;
_pendingImports.add(filename);
setTimeout(async () => {
_pendingImports.delete(filename);
const already = db.prepare('SELECT 1 FROM processed_files WHERE filename = ?').get(filename);
if (!already) await importResultFile(filename);
}, 2500);
});