-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathserver.js
More file actions
2975 lines (2810 loc) · 98.3 KB
/
server.js
File metadata and controls
2975 lines (2810 loc) · 98.3 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
#!/usr/bin/env node
const http = require('http');
const https = require('https');
const fs = require('fs');
const path = require('path');
const os = require('os');
const crypto = require('crypto');
const { execFile } = require('child_process');
const { URL, pathToFileURL } = require('url');
const logger = require('./server/utils/logger');
const { withFileLock } = require('./server/utils/fileLock');
const createRouter = require('./server/routes');
const loadEnvFile = filePath => {
try {
const content = fs.readFileSync(filePath, 'utf-8');
content.split(/\r?\n/).forEach(line => {
const trimmed = line.trim();
if (!trimmed || trimmed.startsWith('#')) {
return;
}
const index = trimmed.indexOf('=');
if (index === -1) {
return;
}
const key = trimmed.slice(0, index).trim();
const value = trimmed.slice(index + 1).trim();
if (!(key in process.env)) {
process.env[key] = value;
}
});
} catch (error) {
// ignore missing .env
}
};
loadEnvFile(path.join(__dirname, '.env'));
const PORT = process.env.PORT || 4173;
const HOST = process.env.HOST || '127.0.0.1';
const ROOT = path.resolve(__dirname);
const ASSETS_PATH = path.join(ROOT, 'assets');
const LOCATIONS_FILE = path.join(ASSETS_PATH, 'locations.json');
const TYPES_FILE = path.join(ASSETS_PATH, 'types.json');
const IMAGES_DIR = path.join(ASSETS_PATH, 'images');
const AUDIO_DIR = path.join(ASSETS_PATH, 'audio');
const AUDIT_DIR = path.join(ASSETS_PATH, 'logs');
const AUDIT_FILE = path.join(AUDIT_DIR, 'locations-audit.jsonl');
const SESSION_STORE_FILE = path.join(AUDIT_DIR, 'sessions.json');
const USERS_FILE = path.join(ASSETS_PATH, 'users.json');
const GROUPS_FILE = path.join(ASSETS_PATH, 'groups.json');
const ANNOTATIONS_FILE = path.join(ASSETS_PATH, 'annotations.json');
const TIMELINE_FILE = path.join(ASSETS_PATH, 'timeline.json');
const SITE_CONFIG_FILE = path.join(ASSETS_PATH, 'site-config.json');
const REMOTE_SYNC_URL = (process.env.REMOTE_SYNC_URL || '').trim();
const REMOTE_SYNC_TOKEN = (process.env.REMOTE_SYNC_TOKEN || '').trim();
const rawRemoteSyncMethod = (process.env.REMOTE_SYNC_METHOD || 'POST').trim().toUpperCase();
const REMOTE_SYNC_METHOD = ['POST', 'PUT', 'PATCH'].includes(rawRemoteSyncMethod) ? rawRemoteSyncMethod : 'POST';
const REMOTE_SYNC_TIMEOUT = Math.max(0, Number(process.env.REMOTE_SYNC_TIMEOUT) || 7000);
const MAX_UPLOAD_SIZE = 25 * 1024 * 1024;
const MAX_BODY_SIZE = 40 * 1024 * 1024;
const AVAILABILITY_DAYS = ['mon', 'tue', 'wed', 'thu', 'fri', 'sat', 'sun'];
const AVAILABILITY_SLOTS = ['morning', 'afternoon', 'evening', 'night'];
const DEFAULT_SITE_CONFIG = {
home: {
kicker: 'Accueil - Hub narratif',
title: "Entrez dans l'univers avant d'ouvrir la carte",
lead: "Explorez les lieux, suivez les quetes en direct, retrouvez votre groupe JDR et centralisez vos personnages. Cette page sert de point d'entree rapide pour la carte et la communaute.",
atmosphere: "Accueil narratif - entree rapide vers l'univers, la carte et la communaute.",
tags: ['Carte narrative', 'Quetes live', 'Groupes JDR', 'Profils & personnages'],
metrics: [
{ label: 'Hub', value: 'Carte + Communaute' },
{ label: 'Acces', value: 'Lecture / Discord / Admin' },
{ label: 'Etat', value: 'Version actuelle en production' }
],
visuals: {
backgroundImage: '/assets/home/backgrounds/hero-main.png',
mapPreviewImage: '/assets/home/mockups/map-preview-main.png',
characterImage: '/assets/home/characters/Chevalier.png',
floatingTitle: "Les terres d'Hesta",
floatingCopy: "Un apercu clair du monde, des routes, des villes et des quetes qui structurent vos campagnes."
}
},
community: {
youtubeUrl: 'https://www.youtube.com/',
discordUrl: 'https://discord.com/',
redditUrl: 'https://www.reddit.com/',
discord: {
badge: 'Discord',
title: 'Serveur principal',
copy: "Organisation des sessions, annonces JDR et coordination des groupes."
},
proof: {
mode: 'manual',
guildId: '',
manualCount: 200,
label: 'membres sur Discord',
note: 'Sessions, annonces et coordination des groupes JDR.'
},
youtube: {
badge: 'YouTube',
title: 'Lore & recaps',
copy: "Recaps, videos d univers et ambiances pour prolonger les campagnes."
},
reddit: {
badge: 'Reddit',
title: 'Discussions',
copy: "Partage d idees, feedback et archives communautaires."
}
},
support: {
issuesUrl: 'https://github.com/Daneisra/Carte-Interactive/issues',
contactEmail: 'contact@cartehesta.local'
},
legal: {
creditsUrl: '/docs/credits-assets.md',
footerNote: "Projet narratif / JDR - fan project / page d'accueil officielle."
},
changelog: [
{
date: '2026-02-28',
title: 'Nouvel accueil en ligne',
summary: "Nouvelle page d'accueil avec session, communaute, flux live, lieux mis en avant et patch notes."
}
]
};
const DEFAULT_TIMELINE = {
title: "Chronologie d'Hesta",
subtitle: "Une lecture lineaire des bascules politiques, spirituelles et militaires qui structurent les campagnes.",
entries: []
};
const MIME_TYPES = {
'.html': 'text/html; charset=utf-8',
'.css': 'text/css; charset=utf-8',
'.js': 'application/javascript; charset=utf-8',
'.mjs': 'application/javascript; charset=utf-8',
'.json': 'application/json; charset=utf-8',
'.png': 'image/png',
'.jpg': 'image/jpeg',
'.jpeg': 'image/jpeg',
'.svg': 'image/svg+xml',
'.ico': 'image/x-icon',
'.txt': 'text/plain; charset=utf-8'
};
const SECURITY_HEADERS = {
'Content-Security-Policy': [
"default-src 'self' data: blob:",
"script-src 'self' 'unsafe-eval' https://unpkg.com https://cdn.jsdelivr.net",
"style-src 'self' 'unsafe-inline' https://unpkg.com https://cdn.jsdelivr.net",
"img-src 'self' data: blob: https://unpkg.com https://cdn.jsdelivr.net",
"font-src 'self' data: https://unpkg.com https://cdn.jsdelivr.net",
"media-src 'self' data: blob:",
"connect-src 'self'",
"frame-src 'self' https://discord.com https://*.discord.com",
"frame-ancestors 'self'"
].join('; '),
'X-Content-Type-Options': 'nosniff'
};
const SSE_HEARTBEAT_MS = 30_000;
const sseClients = new Set();
const serverStartedAt = Date.now();
const sseMetrics = {
broadcastCount: 0,
lastEventAt: null,
lastEventName: null
};
const broadcastSse = (eventName, payload) => {
if (!sseClients.size) {
return;
}
sseMetrics.broadcastCount += 1;
sseMetrics.lastEventAt = Date.now();
sseMetrics.lastEventName = eventName || null;
const serialized = typeof payload === 'string' ? payload : JSON.stringify(payload);
sseClients.forEach(client => {
if (!client.res || client.res.writableEnded) {
return;
}
try {
client.res.write(`event: ${eventName}\ndata: ${serialized}\n\n`);
} catch (error) {
logger.warn('[sse] write failed', { error: error.message });
}
});
};
const registerSseClient = (req, res) => {
res.writeHead(200, {
...SECURITY_HEADERS,
'Content-Type': 'text/event-stream',
'Cache-Control': 'no-cache, no-transform',
Connection: 'keep-alive'
});
res.write(`event: connected\ndata: ${JSON.stringify({ timestamp: new Date().toISOString() })}\n\n`);
const client = { res, heartbeat: null };
client.heartbeat = setInterval(() => {
if (res.writableEnded) {
clearInterval(client.heartbeat);
return;
}
try {
res.write(`event: heartbeat\ndata: ${Date.now()}\n\n`);
} catch (error) {
clearInterval(client.heartbeat);
}
}, SSE_HEARTBEAT_MS);
const cleanup = () => {
clearInterval(client.heartbeat);
sseClients.delete(client);
};
req.on('close', cleanup);
res.on('close', cleanup);
sseClients.add(client);
};
const readJsonFile = async (targetPath, fallback) => {
try {
const raw = await fs.promises.readFile(targetPath, 'utf-8');
return JSON.parse(raw);
} catch (error) {
return Array.isArray(fallback) || typeof fallback === 'object' ? JSON.parse(JSON.stringify(fallback)) : fallback;
}
};
const writeJsonFile = async (targetPath, data) => {
await withFileLock(targetPath, async () => {
const directory = path.dirname(targetPath);
await fs.promises.mkdir(directory, { recursive: true });
await fs.promises.writeFile(targetPath, JSON.stringify(data, null, 2) + '\n', 'utf-8');
});
};
const readAnnotationsFile = async () => readJsonFile(ANNOTATIONS_FILE, []);
const writeAnnotationsFile = async annotations => writeJsonFile(ANNOTATIONS_FILE, annotations);
const readTimelineFile = async () => sanitizeTimelineConfig(await readJsonFile(TIMELINE_FILE, DEFAULT_TIMELINE));
const writeTimelineFile = async timeline => writeJsonFile(TIMELINE_FILE, sanitizeTimelineConfig(timeline));
let searchFiltersModulePromise = null;
const loadSearchFiltersModule = () => {
if (!searchFiltersModulePromise) {
const modulePath = pathToFileURL(path.join(__dirname, 'js', 'shared', 'searchFilters.mjs')).href;
searchFiltersModulePromise = import(modulePath);
}
return searchFiltersModulePromise;
};
let locationValidationModulePromise = null;
const loadLocationValidationModule = () => {
if (!locationValidationModulePromise) {
const modulePath = pathToFileURL(path.join(__dirname, 'js', 'shared', 'locationValidation.mjs')).href;
locationValidationModulePromise = import(modulePath);
}
return locationValidationModulePromise;
};
const send = (res, status, body = '', headers = {}) => {
res.writeHead(status, { ...SECURITY_HEADERS, ...headers });
if (body === null) {
res.end();
} else {
res.end(body);
}
};
const json = (res, status, payload = null) => {
const headers = { 'Content-Type': 'application/json' };
if (payload === null) {
send(res, status, null, headers);
return;
}
send(res, status, JSON.stringify(payload), headers);
};
const serveStatic = (req, res, urlObj) => {
let pathname = decodeURIComponent(urlObj.pathname);
if (pathname.includes('..')) {
send(res, 403, 'Forbidden');
return;
}
if (pathname.endsWith('/')) {
pathname += 'index.html';
}
if (pathname === '/') {
pathname = '/index.html';
}
const filePath = path.join(ROOT, pathname);
if (!filePath.startsWith(ROOT)) {
send(res, 403, 'Forbidden');
return;
}
fs.stat(filePath, (err, stats) => {
if (err) {
send(res, 404, 'Not Found');
return;
}
if (stats.isDirectory()) {
const indexPath = path.join(filePath, 'index.html');
fs.stat(indexPath, (indexErr, indexStats) => {
if (indexErr || !indexStats.isFile()) {
send(res, 404, 'Not Found');
return;
}
streamFile(indexPath, req, res);
});
return;
}
streamFile(filePath, req, res);
});
};
const streamFile = (filePath, req, res) => {
const ext = path.extname(filePath).toLowerCase();
const mime = MIME_TYPES[ext] || 'application/octet-stream';
const headers = { ...SECURITY_HEADERS, 'Content-Type': mime };
if (ext === '.json') {
headers['Cache-Control'] = 'no-store';
}
res.writeHead(200, headers);
if (req.method === 'HEAD') {
res.end();
return;
}
const stream = fs.createReadStream(filePath);
stream.on('error', () => {
if (!res.headersSent) {
send(res, 500, 'Internal Server Error');
} else {
res.destroy();
}
});
stream.pipe(res);
};
const UPLOAD_RULES = {
image: {
directory: IMAGES_DIR,
extensions: ['.png', '.jpg', '.jpeg', '.webp', '.gif', '.svg']
},
audio: {
directory: AUDIO_DIR,
extensions: ['.mp3', '.ogg', '.wav', '.flac', '.aac', '.m4a']
}
};
const IMAGE_EXTENSIONS = new Set(UPLOAD_RULES.image.extensions);
const AUDIO_EXTENSIONS = new Set(UPLOAD_RULES.audio.extensions);
let cachedTypes = null;
const canSyncRemote = REMOTE_SYNC_URL.length > 0 && REMOTE_SYNC_METHOD.length;
const ADMIN_API_TOKEN = (process.env.ADMIN_API_TOKEN || '').trim();
const USER_API_TOKENS = (process.env.USER_API_TOKENS || '')
.split(',')
.map(token => token.trim())
.filter(Boolean);
const authEnabled = ADMIN_API_TOKEN.length > 0 || USER_API_TOKENS.length > 0;
const DISCORD_CLIENT_ID = (process.env.DISCORD_CLIENT_ID || '').trim();
const DISCORD_CLIENT_SECRET = (process.env.DISCORD_CLIENT_SECRET || '').trim();
const DISCORD_REDIRECT_URI = (process.env.DISCORD_REDIRECT_URI || '').trim();
const DISCORD_OAUTH_ENABLED = DISCORD_CLIENT_ID.length > 0 && DISCORD_CLIENT_SECRET.length > 0 && DISCORD_REDIRECT_URI.length > 0;
const DISCORD_ADMIN_IDS = (process.env.DISCORD_ADMIN_IDS || '')
.split(',')
.map(id => id.trim())
.filter(Boolean);
const DISCORD_API_VERSION = 'v10';
const DEFAULT_DISCORD_API_ORIGIN = 'https://discord.com';
const rawDiscordApiOrigin = (process.env.DISCORD_API_ORIGIN || DEFAULT_DISCORD_API_ORIGIN).trim();
const DISCORD_API_ORIGIN = rawDiscordApiOrigin ? rawDiscordApiOrigin.replace(/\/+$/, '') : DEFAULT_DISCORD_API_ORIGIN;
const DISCORD_AUTHORIZE_URL = `${DISCORD_API_ORIGIN}/oauth2/authorize`;
const DISCORD_TOKEN_URL = `${DISCORD_API_ORIGIN}/api/oauth2/token`;
const DISCORD_USER_URL = `${DISCORD_API_ORIGIN}/api/${DISCORD_API_VERSION}/users/@me`;
const authRequired = authEnabled || DISCORD_OAUTH_ENABLED;
logger.info('Discord OAuth configuration', {
enabled: DISCORD_OAUTH_ENABLED,
origin: DISCORD_API_ORIGIN
});
const sessionStore = new Map();
const SESSION_COOKIE_NAME = 'map_session';
const oauthStateStore = new Map();
const OAUTH_STATE_TTL_MS = 5 * 60 * 1000;
const SESSION_TTL_MS = Math.max(5 * 60 * 1000, Number(process.env.SESSION_TTL_MS) || (12 * 60 * 60 * 1000));
const SESSION_SECRET = (process.env.SESSION_SECRET || 'dev-secret').padEnd(32, '0');
const SESSION_PERSIST_DEBOUNCE_MS = 1_000;
let sessionPersistTimer = null;
const serializeSessionStore = () => {
const sessions = [];
sessionStore.forEach((value, key) => {
sessions.push({ id: key, ...value });
});
return sessions;
};
const persistSessionStore = async () => {
try {
const payload = serializeSessionStore();
await withFileLock(SESSION_STORE_FILE, async () => {
const directory = path.dirname(SESSION_STORE_FILE);
await fs.promises.mkdir(directory, { recursive: true });
await fs.promises.writeFile(SESSION_STORE_FILE, JSON.stringify(payload, null, 2) + '\n', 'utf-8');
});
} catch (error) {
logger.warn('[session] persist failed', { error: error.message });
}
};
const scheduleSessionPersist = () => {
if (sessionPersistTimer) {
return;
}
sessionPersistTimer = setTimeout(() => {
sessionPersistTimer = null;
persistSessionStore();
}, SESSION_PERSIST_DEBOUNCE_MS);
if (typeof sessionPersistTimer.unref === 'function') {
sessionPersistTimer.unref();
}
};
const hydrateSessionStoreFromDisk = async () => {
try {
const raw = await fs.promises.readFile(SESSION_STORE_FILE, 'utf-8');
const entries = JSON.parse(raw);
if (!Array.isArray(entries)) {
return;
}
const now = Date.now();
entries.forEach(entry => {
if (!entry || typeof entry !== 'object') {
return;
}
const id = typeof entry.id === 'string' ? entry.id : null;
if (!id) {
return;
}
const expiresAt = Number(entry.expiresAt) || 0;
if (expiresAt <= now) {
return;
}
const { id: _omit, ...data } = entry;
sessionStore.set(id, data);
});
if (sessionStore.size) {
logger.info('[session] hydrated persisted store', { count: sessionStore.size });
}
} catch (error) {
if (error.code !== 'ENOENT') {
logger.warn('[session] hydrate failed', { error: error.message });
}
}
};
hydrateSessionStoreFromDisk();
const parseCookies = header => {
if (!header) {
return {};
}
return header.split(';').map(chunk => chunk.trim()).reduce((acc, item) => {
if (!item) {
return acc;
}
const idx = item.indexOf('=');
if (idx === -1) {
return acc;
}
const key = item.slice(0, idx).trim();
const value = decodeURIComponent(item.slice(idx + 1));
acc[key] = value;
return acc;
}, {});
};
const signSessionId = sessionId => {
const hmac = crypto.createHmac('sha256', SESSION_SECRET);
hmac.update(sessionId);
return `${sessionId}.${hmac.digest('hex')}`;
};
const verifySessionId = signed => {
if (!signed || typeof signed !== 'string') {
return null;
}
const parts = signed.split('.');
if (parts.length !== 2) {
return null;
}
const [sessionId, signature] = parts;
const hmac = crypto.createHmac('sha256', SESSION_SECRET);
hmac.update(sessionId);
const expected = hmac.digest('hex');
if (!crypto.timingSafeEqual(Buffer.from(signature), Buffer.from(expected))) {
return null;
}
return sessionId;
};
const createSession = payload => {
const sessionId = crypto.randomUUID();
const expiresAt = Date.now() + SESSION_TTL_MS;
sessionStore.set(sessionId, { ...payload, expiresAt });
scheduleSessionPersist();
return signSessionId(sessionId);
};
const getSession = req => {
const cookies = parseCookies(req.headers?.cookie);
const signed = cookies[SESSION_COOKIE_NAME];
const sessionId = verifySessionId(signed);
if (!sessionId) {
return null;
}
const record = sessionStore.get(sessionId);
if (!record) {
return null;
}
if (record.expiresAt <= Date.now()) {
sessionStore.delete(sessionId);
scheduleSessionPersist();
return null;
}
record.expiresAt = Date.now() + SESSION_TTL_MS;
sessionStore.set(sessionId, record);
scheduleSessionPersist();
return { sessionId, data: record };
};
const destroySession = req => {
const cookies = parseCookies(req.headers?.cookie);
const signed = cookies[SESSION_COOKIE_NAME];
const sessionId = verifySessionId(signed);
if (sessionId && sessionStore.delete(sessionId)) {
scheduleSessionPersist();
}
};
const sendSessionCookie = (res, signedId) => {
const maxAge = Math.floor(SESSION_TTL_MS / 1000);
const secure = process.env.COOKIE_SECURE === 'true' ? '; Secure' : '';
const cookie = `${SESSION_COOKIE_NAME}=${encodeURIComponent(signedId)}; Path=/; Max-Age=${maxAge}; HttpOnly; SameSite=Lax${secure}`;
res.setHeader('Set-Cookie', cookie);
};
const clearSessionCookie = res => {
const secure = process.env.COOKIE_SECURE === 'true' ? '; Secure' : '';
res.setHeader('Set-Cookie', `${SESSION_COOKIE_NAME}=; Path=/; Max-Age=0; HttpOnly; SameSite=Lax${secure}`);
};
const fetchJson = (url, options = {}) => new Promise((resolve, reject) => {
const parsed = new URL(url);
const transport = parsed.protocol === 'https:' ? https : http;
const requestOptions = {
method: options.method || 'GET',
headers: options.headers ? { ...options.headers } : {},
};
if (options.body && !requestOptions.headers['Content-Length']) {
requestOptions.headers['Content-Length'] = Buffer.byteLength(options.body);
}
const request = transport.request(url, requestOptions, response => {
let body = '';
response.on('data', chunk => { body += chunk; });
response.on('end', () => {
if (response.statusCode >= 200 && response.statusCode < 300) {
try {
resolve(body ? JSON.parse(body) : {});
} catch (error) {
reject(error);
}
} else {
reject(new Error(`HTTP ${response.statusCode}: ${body}`));
}
});
});
request.on('error', reject);
if (options.body) {
request.write(options.body);
}
request.end();
});
const execFileText = (file, args, options = {}) => new Promise((resolve, reject) => {
execFile(file, args, { ...options, encoding: 'utf8', windowsHide: true, maxBuffer: 1024 * 1024 }, (error, stdout, stderr) => {
if (error) {
error.stderr = stderr;
reject(error);
return;
}
resolve(stdout || '');
});
});
const readGitChangelogEntries = async (limit = 6) => {
const count = Math.max(1, Math.min(12, Number(limit) || 6));
const output = await execFileText('git', [
'log',
`-n=${count}`,
'--date=short',
'--pretty=format:%ad%x1f%s%x1f%b%x1e'
], { cwd: ROOT });
return output
.split('\x1e')
.map(entry => entry.trim())
.filter(Boolean)
.map(entry => {
const [dateRaw = '', titleRaw = '', bodyRaw = ''] = entry.split('\x1f');
const title = normalizeString(titleRaw) || 'Mise a jour';
const bodyLine = normalizeString(bodyRaw)
.split(/\r?\n/)
.map(line => normalizeString(line))
.find(Boolean);
return {
date: normalizeString(dateRaw) || '',
title,
summary: bodyLine || title
};
})
.filter(entry => entry.title);
};
const AUTH_PRIORITY = { user: 1, admin: 2 };
const extractBearerToken = req => {
const header = req.headers?.authorization || req.headers?.Authorization;
if (!header || typeof header !== 'string') {
return null;
}
const parts = header.split(/\s+/);
if (parts.length === 2 && parts[0].toLowerCase() === 'bearer') {
return parts[1].trim();
}
return null;
};
const ensureAuthorized = async (req, res, minimumRole = 'user') => {
if (!authRequired) {
req.auth = { role: 'admin' };
return 'admin';
}
let role = null;
let userRecord = null;
const session = getSession(req);
if (session?.data?.userId) {
const persisted = await findUserById(session.data.userId);
if (persisted) {
role = sanitizeRole(persisted.role);
userRecord = persisted;
sessionStore.set(session.sessionId, { ...session.data, role, username: persisted.username, expiresAt: session.data.expiresAt });
} else {
destroySession(req);
}
} else if (session?.data?.role) {
role = sanitizeRole(session.data.role);
if (session?.data?.username) {
userRecord = { username: session.data.username, role };
}
}
if (!role) {
const tokenResult = await resolveTokenUser(extractBearerToken(req));
if (tokenResult) {
role = tokenResult.role;
userRecord = tokenResult.user || null;
}
}
if (!role) {
send(res, 401, JSON.stringify({ status: 'error', message: 'Authorization required.' }), { 'Content-Type': 'application/json' });
return null;
}
if ((AUTH_PRIORITY[role] || 0) < (AUTH_PRIORITY[minimumRole] || 0)) {
send(res, 403, JSON.stringify({ status: 'error', message: 'Insufficient privileges.' }), { 'Content-Type': 'application/json' });
return null;
}
req.auth = { role, user: userRecord, session: session?.data || null };
return role;
};
const loadTypeMap = async () => {
if (cachedTypes) {
return cachedTypes;
}
try {
const raw = await fs.promises.readFile(TYPES_FILE, 'utf-8');
const parsed = JSON.parse(raw);
cachedTypes = parsed && typeof parsed === 'object' ? parsed : {};
} catch (error) {
cachedTypes = {};
}
return cachedTypes;
};
const normalizeString = value => (value ?? '').toString().trim();
const parseListParam = (searchParams, key) => {
const rawValues = searchParams.getAll(key) || [];
const collected = [];
rawValues.forEach(entry => {
if (typeof entry !== 'string') {
return;
}
entry.split(/[,;]+/).forEach(chunk => {
const normalized = normalizeString(chunk);
if (normalized) {
collected.push(normalized);
}
});
});
return collected;
};
const isHttpUrl = value => {
if (!value || typeof value !== 'string') {
return false;
}
try {
const parsed = new URL(value);
return parsed.protocol === 'http:' || parsed.protocol === 'https:';
} catch (error) {
return false;
}
};
const cloneSiteConfigDefaults = () => JSON.parse(JSON.stringify(DEFAULT_SITE_CONFIG));
const sanitizeSiteConfigText = (value, maxLength = 1200) => {
const normalized = normalizeString(value);
if (!normalized) {
return '';
}
return normalized.slice(0, maxLength);
};
const sanitizeSiteConfigDate = value => {
const normalized = normalizeString(value);
if (!normalized) {
return '';
}
const parsed = Date.parse(normalized);
return Number.isFinite(parsed) ? new Date(parsed).toISOString().slice(0, 10) : normalized.slice(0, 32);
};
const sanitizeSiteConfigUrl = (value, { allowRelative = false } = {}) => {
const normalized = normalizeString(value);
if (!normalized) {
return '';
}
if (allowRelative && normalized.startsWith('/')) {
return normalized;
}
return isHttpUrl(normalized) ? normalized : '';
};
const sanitizeSiteConfigContact = value => {
const normalized = normalizeString(value);
if (!normalized) {
return '';
}
if (/^mailto:[^@\s]+@[^@\s]+\.[^@\s]+$/i.test(normalized)) {
return normalized;
}
return /^[^@\s]+@[^@\s]+\.[^@\s]+$/i.test(normalized) ? normalized : '';
};
const sanitizeSiteConfigMode = value => {
const normalized = normalizeString(value).toLowerCase();
return normalized === 'discord' ? 'discord' : 'manual';
};
const sanitizeSiteConfigMetric = value => {
if (!value || typeof value !== 'object') {
return null;
}
const label = sanitizeSiteConfigText(value.label, 60);
const metricValue = sanitizeSiteConfigText(value.value, 120);
if (!label || !metricValue) {
return null;
}
return { label, value: metricValue };
};
const sanitizeSiteConfigChangelogEntry = value => {
if (!value || typeof value !== 'object') {
return null;
}
const date = sanitizeSiteConfigDate(value.date);
const title = sanitizeSiteConfigText(value.title, 120);
const summary = sanitizeSiteConfigText(value.summary, 400);
if (!date && !title && !summary) {
return null;
}
return {
date: date || '',
title: title || 'Mise a jour',
summary: summary || ''
};
};
const sanitizeTimelineText = (value, maxLength = 1200) => sanitizeSiteConfigText(value, maxLength);
const sanitizeTimelineColor = value => {
const normalized = normalizeString(value);
if (!normalized) {
return '#7dd3fc';
}
return /^#([0-9a-f]{3}|[0-9a-f]{6})$/i.test(normalized) ? normalized : '#7dd3fc';
};
const sanitizeTimelineEventKind = value => {
const normalized = normalizeString(value).toLowerCase();
return normalized === 'player' ? 'player' : 'lore';
};
const sanitizeTimelineId = value => {
const normalized = normalizeString(value)
.toLowerCase()
.replace(/[^a-z0-9_-]+/g, '-')
.replace(/-+/g, '-')
.replace(/^-+|-+$/g, '');
return normalized.slice(0, 80);
};
const sanitizeTimelineList = (list, maxItems = 8, itemMaxLength = 60) => (
Array.isArray(list)
? list.map(entry => sanitizeTimelineText(entry, itemMaxLength)).filter(Boolean).slice(0, maxItems)
: []
);
const sanitizeTimelineEntry = (value, index = 0) => {
if (!value || typeof value !== 'object') {
return null;
}
const yearValue = Number(value.year);
const year = Number.isFinite(yearValue) ? Math.round(yearValue) : index;
const title = sanitizeTimelineText(value.title, 140);
const summary = sanitizeTimelineText(value.summary, 280);
const content = sanitizeTimelineText(value.content, 2400);
const era = sanitizeTimelineText(value.era, 80);
const period = sanitizeTimelineText(value.period, 80);
const id = sanitizeTimelineId(value.id) || sanitizeTimelineId(`${year}-${title || `event-${index + 1}`}`) || `timeline-${index + 1}`;
return {
id,
year,
yearLabel: sanitizeTimelineText(value.yearLabel, 40) || String(year),
title: title || `Evenement ${index + 1}`,
summary: summary || content || '',
content: content || summary || '',
eventKind: sanitizeTimelineEventKind(value.eventKind),
era: era || period || 'Periode inconnue',
eraSummary: sanitizeTimelineText(value.eraSummary, 240),
sceneLabel: sanitizeTimelineText(value.sceneLabel, 60),
period: period || 'Periode inconnue',
tags: sanitizeTimelineList(value.tags, 10, 40),
locationNames: sanitizeTimelineList(value.locationNames, 10, 80),
imageUrl: sanitizeSiteConfigUrl(value.imageUrl, { allowRelative: true }),
mediaAlt: sanitizeTimelineText(value.mediaAlt, 180),
accentColor: sanitizeTimelineColor(value.accentColor),
visible: value.visible !== false
};
};
const sanitizeTimelineConfig = value => {
const source = value && typeof value === 'object' ? value : {};
const entries = Array.isArray(source.entries)
? source.entries.map((entry, index) => sanitizeTimelineEntry(entry, index)).filter(Boolean).slice(0, 120)
: [];
return {
title: sanitizeTimelineText(source.title, 120) || DEFAULT_TIMELINE.title,
subtitle: sanitizeTimelineText(source.subtitle, 320) || DEFAULT_TIMELINE.subtitle,
entries
};
};
const extractDiscordInviteCode = value => {
const normalized = normalizeString(value);
if (!normalized) {
return '';
}
try {
const parsed = new URL(normalized);
const parts = parsed.pathname.split('/').map(part => part.trim()).filter(Boolean);
return parts.length ? parts[parts.length - 1] : '';
} catch (_error) {
return normalized.replace(/^https?:\/\/[^/]+\//i, '').trim();
}
};
const fetchDiscordInviteStats = async inviteUrl => {
const inviteCode = extractDiscordInviteCode(inviteUrl);
if (!inviteCode) {
return null;
}
const url = `${DISCORD_API_ORIGIN}/api/${DISCORD_API_VERSION}/invites/${encodeURIComponent(inviteCode)}?with_counts=true`;
const payload = await fetchJson(url);
return {
inviteCode,
memberCount: Math.max(0, Number(payload?.approximate_member_count) || 0),
presenceCount: Math.max(0, Number(payload?.approximate_presence_count) || 0),
guildId: normalizeString(payload?.guild?.id || ''),
guildName: normalizeString(payload?.guild?.name || ''),
source: 'discord'
};
};
const fetchDiscordWidgetStats = async guildId => {
const normalizedGuildId = normalizeString(guildId);
if (!normalizedGuildId) {
return null;
}
const widgetUrl = `${DISCORD_API_ORIGIN}/api/guilds/${encodeURIComponent(normalizedGuildId)}/widget.json`;
const payload = await fetchJson(widgetUrl);
const presenceCount = Math.max(0, Number(payload?.presence_count) || 0);
const memberCount = Array.isArray(payload?.members) ? payload.members.length : 0;
return {
guildId: normalizedGuildId,
presenceCount,
memberCount,
instantInvite: typeof payload?.instant_invite === 'string' ? payload.instant_invite : null,
source: 'discord'
};
};
const sanitizeSiteConfig = value => {
const defaults = cloneSiteConfigDefaults();
const source = value && typeof value === 'object' ? value : {};
const homeSource = source.home && typeof source.home === 'object' ? source.home : {};
const communitySource = source.community && typeof source.community === 'object' ? source.community : {};
const supportSource = source.support && typeof source.support === 'object' ? source.support : {};
const legalSource = source.legal && typeof source.legal === 'object' ? source.legal : {};
const tags = Array.isArray(homeSource.tags)
? homeSource.tags.map(entry => sanitizeSiteConfigText(entry, 60)).filter(Boolean).slice(0, 8)
: defaults.home.tags;
const metrics = Array.isArray(homeSource.metrics)
? homeSource.metrics.map(sanitizeSiteConfigMetric).filter(Boolean).slice(0, 6)
: defaults.home.metrics;
const visualsSource = homeSource.visuals && typeof homeSource.visuals === 'object' ? homeSource.visuals : {};
const proofSource = communitySource.proof && typeof communitySource.proof === 'object' ? communitySource.proof : {};
const sanitizeCommunityCard = (key, fallback) => {
const cardSource = communitySource[key] && typeof communitySource[key] === 'object' ? communitySource[key] : {};
return {
badge: sanitizeSiteConfigText(cardSource.badge, 30) || fallback.badge,
title: sanitizeSiteConfigText(cardSource.title, 80) || fallback.title,
copy: sanitizeSiteConfigText(cardSource.copy, 240) || fallback.copy
};
};
const proof = {
mode: normalizeString(proofSource.mode) === 'discord' ? 'discord' : 'manual',
guildId: normalizeString(proofSource.guildId || ''),
manualCount: Math.max(0, Number(proofSource.manualCount) || 0),
label: sanitizeSiteConfigText(proofSource.label, 60) || defaults.community.proof.label,
note: sanitizeSiteConfigText(proofSource.note, 200) || defaults.community.proof.note
};
const changelog = Array.isArray(source.changelog)
? source.changelog.map(sanitizeSiteConfigChangelogEntry).filter(Boolean).slice(0, 12)
: defaults.changelog;
return {
home: {
kicker: sanitizeSiteConfigText(homeSource.kicker, 80) || defaults.home.kicker,
title: sanitizeSiteConfigText(homeSource.title, 180) || defaults.home.title,
lead: sanitizeSiteConfigText(homeSource.lead, 600) || defaults.home.lead,
atmosphere: sanitizeSiteConfigText(homeSource.atmosphere, 180) || defaults.home.atmosphere,
tags: tags.length ? tags : defaults.home.tags,
metrics: metrics.length ? metrics : defaults.home.metrics,
visuals: {
backgroundImage: sanitizeSiteConfigUrl(visualsSource.backgroundImage, { allowRelative: true }) || defaults.home.visuals.backgroundImage,
mapPreviewImage: sanitizeSiteConfigUrl(visualsSource.mapPreviewImage, { allowRelative: true }) || defaults.home.visuals.mapPreviewImage,
characterImage: sanitizeSiteConfigUrl(visualsSource.characterImage, { allowRelative: true }) || defaults.home.visuals.characterImage,
floatingTitle: sanitizeSiteConfigText(visualsSource.floatingTitle, 120) || defaults.home.visuals.floatingTitle,
floatingCopy: sanitizeSiteConfigText(visualsSource.floatingCopy, 260) || defaults.home.visuals.floatingCopy
}
},
community: {
youtubeUrl: sanitizeSiteConfigUrl(communitySource.youtubeUrl) || defaults.community.youtubeUrl,
discordUrl: sanitizeSiteConfigUrl(communitySource.discordUrl) || defaults.community.discordUrl,
redditUrl: sanitizeSiteConfigUrl(communitySource.redditUrl) || defaults.community.redditUrl,
discord: sanitizeCommunityCard('discord', defaults.community.discord),
proof,
youtube: sanitizeCommunityCard('youtube', defaults.community.youtube),
reddit: sanitizeCommunityCard('reddit', defaults.community.reddit)
},
support: {
issuesUrl: sanitizeSiteConfigUrl(supportSource.issuesUrl) || defaults.support.issuesUrl,
contactEmail: sanitizeSiteConfigContact(supportSource.contactEmail) || defaults.support.contactEmail
},
legal: {
creditsUrl: sanitizeSiteConfigUrl(legalSource.creditsUrl, { allowRelative: true }) || defaults.legal.creditsUrl,
footerNote: sanitizeSiteConfigText(legalSource.footerNote, 240) || defaults.legal.footerNote
},
changelog: changelog.length ? changelog : defaults.changelog
};
};
const readSiteConfigFile = async () => sanitizeSiteConfig(await readJsonFile(SITE_CONFIG_FILE, DEFAULT_SITE_CONFIG));