-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathserver.js
More file actions
3077 lines (2636 loc) · 120 KB
/
server.js
File metadata and controls
3077 lines (2636 loc) · 120 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
const express = require('express');
const cors = require('cors');
const fs = require('fs-extra');
const path = require('path');
const crypto = require('crypto');
const { v4: uuidv4 } = require('uuid');
const helmet = require('helmet');
const rateLimit = require('express-rate-limit');
const cookieParser = require('cookie-parser');
// ID format validation — accepts both standard UUIDs (with dashes) and UE-style GUIDs (32 hex chars)
// Prevents path traversal and injection via IDs
const VALID_ID_REGEX = /^[0-9a-f]{8}-?[0-9a-f]{4}-?[0-9a-f]{4}-?[0-9a-f]{4}-?[0-9a-f]{12}$/i;
function isValidUUID(id) {
return typeof id === 'string' && VALID_ID_REGEX.test(id);
}
// Try to load Sharp, fallback if not available
let sharp;
try {
sharp = require('sharp');
console.log('Sharp image compression enabled');
} catch (error) {
console.warn('Sharp not available, image compression disabled:', error.message);
}
// Try to load Anthropic SDK for AI crash analysis
let Anthropic;
try {
Anthropic = require('@anthropic-ai/sdk').default;
console.log('Anthropic SDK loaded for AI crash analysis');
} catch (error) {
console.warn('Anthropic SDK not available, AI crash analysis disabled:', error.message);
}
// Try to load AdmZip for crash report extraction
let AdmZip;
try {
AdmZip = require('adm-zip');
console.log('AdmZip loaded for crash report extraction');
} catch (error) {
console.warn('AdmZip not available, crash report extraction disabled:', error.message);
}
const app = express();
const PORT = process.env.PORT || 3000;
// Environment-based configuration
const isDevelopment = process.env.NODE_ENV !== 'production';
// CORS configuration — require ALLOWED_ORIGINS in production, never default to wildcard
const corsOptions = {
origin: isDevelopment
? ['http://localhost:3000', 'http://127.0.0.1:3000']
: process.env.ALLOWED_ORIGINS ? process.env.ALLOWED_ORIGINS.split(',') : false,
methods: ['GET', 'POST', 'DELETE'],
allowedHeaders: ['Content-Type', 'x-admin-key', 'x-api-key'],
};
// Security middleware
app.use(helmet({
contentSecurityPolicy: false, // Dashboard has its own CSP
crossOriginResourcePolicy: { policy: 'cross-origin' } // Allow thumbnail loading
}));
app.use(cors(corsOptions));
app.use(cookieParser());
app.use(express.json({ limit: '50mb' })); // Large limit for save data + thumbnails
app.use(express.urlencoded({ extended: true, limit: '50mb' }));
// Rate limiting — general API
const apiLimiter = rateLimit({
windowMs: 15 * 60 * 1000, // 15 minutes
max: 300,
standardHeaders: true,
legacyHeaders: false,
message: { error: 'Too many requests, please try again later' }
});
app.use('/api/', apiLimiter);
// Stricter rate limit for write endpoints only (POST/DELETE, not GET)
const writeLimiter = rateLimit({
windowMs: 15 * 60 * 1000,
max: 30,
standardHeaders: true,
legacyHeaders: false,
message: { error: 'Too many upload requests, please try again later' },
skip: (req) => req.method === 'GET'
});
app.use('/api/designs', writeLimiter);
app.use('/api/crashes', writeLimiter);
// Shared admin authentication middleware — uses timing-safe comparison to prevent side-channel attacks
function requireAdmin(req, res, next) {
const adminKey = req.headers['x-admin-key'];
const expectedKey = process.env.ADMIN_RESET_KEY;
if (!expectedKey) {
console.error('ADMIN_RESET_KEY not set — admin endpoints disabled');
return res.status(503).json({ error: 'Admin endpoints not configured' });
}
if (!adminKey || typeof adminKey !== 'string') {
return res.status(403).json({ error: 'Invalid admin key' });
}
// Constant-time comparison prevents timing attacks that could leak the key
const keyBuffer = Buffer.from(adminKey);
const expectedBuffer = Buffer.from(expectedKey);
if (keyBuffer.length !== expectedBuffer.length || !crypto.timingSafeEqual(keyBuffer, expectedBuffer)) {
return res.status(403).json({ error: 'Invalid admin key' });
}
next();
}
// Game client authentication middleware — shared secret between game and server
// This blocks casual abuse; a determined attacker can still extract the key from the game binary
function requireApiKey(req, res, next) {
const apiKey = req.headers['x-api-key'];
const expectedKey = process.env.GAME_API_KEY;
// If no key configured, skip check (backwards compatible / development)
if (!expectedKey) {
return next();
}
if (!apiKey || typeof apiKey !== 'string') {
return res.status(403).json({ error: 'API key required' });
}
const keyBuffer = Buffer.from(apiKey);
const expectedBuffer = Buffer.from(expectedKey);
if (keyBuffer.length !== expectedBuffer.length || !crypto.timingSafeEqual(keyBuffer, expectedBuffer)) {
return res.status(403).json({ error: 'Invalid API key' });
}
next();
}
// Serve analytics dashboard with login page
const DASHBOARD_DIR = path.join(__dirname, 'dashboard', 'dist');
if (fs.existsSync(DASHBOARD_DIR)) {
const LOGIN_PAGE = `<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Small Spaces Admin</title>
<style>
* { margin: 0; padding: 0; box-sizing: border-box; }
body {
font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, Oxygen, Ubuntu, sans-serif;
background: #0f1419;
color: #e7e9ea;
min-height: 100vh;
display: flex;
align-items: center;
justify-content: center;
}
.login-card {
background: #1a1f26;
border: 1px solid #2f3640;
border-radius: 12px;
padding: 40px;
width: 100%;
max-width: 380px;
}
.login-card h1 {
font-size: 20px;
font-weight: 600;
margin-bottom: 8px;
}
.login-card p {
font-size: 14px;
color: #8b98a5;
margin-bottom: 24px;
}
.login-card input {
width: 100%;
padding: 10px 14px;
background: #0f1419;
border: 1px solid #2f3640;
border-radius: 8px;
color: #e7e9ea;
font-size: 14px;
outline: none;
transition: border-color 0.15s;
}
.login-card input:focus { border-color: #5b9bd5; }
.login-card button {
width: 100%;
margin-top: 16px;
padding: 10px;
background: #5b9bd5;
color: #fff;
border: none;
border-radius: 8px;
font-size: 14px;
font-weight: 600;
cursor: pointer;
transition: background 0.15s;
}
.login-card button:hover { background: #4a8ac4; }
.error {
margin-top: 12px;
padding: 8px 12px;
background: rgba(220, 53, 69, 0.15);
border: 1px solid rgba(220, 53, 69, 0.3);
border-radius: 6px;
color: #f87171;
font-size: 13px;
display: none;
}
</style>
</head>
<body>
<form class="login-card" method="POST" action="/admin/login">
<h1>Small Spaces</h1>
<p>Enter admin key to continue</p>
<input type="password" name="key" placeholder="Admin key" required autofocus>
<button type="submit">Log in</button>
<div class="error" id="error">Invalid admin key.</div>
</form>
<script>
if (new URLSearchParams(location.search).get('error') === '1') {
document.getElementById('error').style.display = 'block';
}
</script>
</body>
</html>`;
// Validate admin session cookie
function isValidAdminSession(req) {
const expectedKey = process.env.ADMIN_RESET_KEY;
if (!expectedKey) return false;
const sessionKey = req.cookies?.admin_session;
if (!sessionKey || typeof sessionKey !== 'string') return false;
const keyBuffer = Buffer.from(sessionKey);
const expectedBuffer = Buffer.from(expectedKey);
return keyBuffer.length === expectedBuffer.length && crypto.timingSafeEqual(keyBuffer, expectedBuffer);
}
// POST /admin/login — validate key and set session cookie
app.post('/admin/login', (req, res) => {
const expectedKey = process.env.ADMIN_RESET_KEY;
if (!expectedKey) return res.status(503).send('Admin not configured');
const providedKey = req.body?.key;
if (!providedKey || typeof providedKey !== 'string') {
return res.redirect('/admin/login?error=1');
}
const keyBuffer = Buffer.from(providedKey);
const expectedBuffer = Buffer.from(expectedKey);
if (keyBuffer.length !== expectedBuffer.length || !crypto.timingSafeEqual(keyBuffer, expectedBuffer)) {
return res.redirect('/admin/login?error=1');
}
res.cookie('admin_session', providedKey, {
httpOnly: true,
secure: !isDevelopment,
sameSite: 'strict',
maxAge: 24 * 60 * 60 * 1000 // 24 hours
});
res.redirect('/admin');
});
// GET /admin/login — show login page
app.get('/admin/login', (req, res) => {
if (isValidAdminSession(req)) return res.redirect('/admin');
res.send(LOGIN_PAGE);
});
// GET /admin/logout — clear session
app.get('/admin/logout', (req, res) => {
res.clearCookie('admin_session');
res.redirect('/admin/login');
});
// Dashboard auth gate — redirect to login if no valid session
const dashboardAuth = (req, res, next) => {
// Allow static assets (JS/CSS/SVG) if they have a valid referer from /admin
const referer = req.headers.referer || '';
if (referer.includes('/admin') && (req.path.endsWith('.js') || req.path.endsWith('.css') || req.path.endsWith('.svg'))) {
return next();
}
if (!isValidAdminSession(req)) {
return res.redirect('/admin/login');
}
next();
};
app.use('/admin', dashboardAuth, express.static(DASHBOARD_DIR));
// Handle SPA routing - serve index.html for all /admin routes
app.get('/admin/*', dashboardAuth, (req, res) => {
res.sendFile(path.join(DASHBOARD_DIR, 'index.html'));
});
console.log('Analytics dashboard enabled at /admin (login-gated)');
}
// Storage directories - use persistent volume on Railway Pro
const STORAGE_DIR = process.env.RAILWAY_VOLUME_MOUNT_PATH || path.join(__dirname, 'storage');
const DESIGNS_DIR = path.join(STORAGE_DIR, 'designs');
const THUMBNAILS_DIR = path.join(STORAGE_DIR, 'thumbnails');
const METADATA_FILE = path.join(STORAGE_DIR, 'metadata.json');
// Analytics storage directories
const ANALYTICS_DIR = path.join(STORAGE_DIR, 'analytics');
const ANALYTICS_EVENTS_FILE = path.join(ANALYTICS_DIR, 'events.json');
const ANALYTICS_SESSIONS_FILE = path.join(ANALYTICS_DIR, 'sessions.json');
// Crash reports storage
const CRASHES_DIR = path.join(STORAGE_DIR, 'crashes');
const CRASHES_METADATA_FILE = path.join(STORAGE_DIR, 'crashes_metadata.json');
const CRASH_GROUPS_FILE = path.join(STORAGE_DIR, 'crash_groups.json');
const FEATURED_FILE = path.join(STORAGE_DIR, 'featured.json');
// Ensure storage directories exist
try {
fs.ensureDirSync(DESIGNS_DIR);
fs.ensureDirSync(THUMBNAILS_DIR);
fs.ensureDirSync(ANALYTICS_DIR);
fs.ensureDirSync(CRASHES_DIR);
console.log('Storage directories created/verified');
} catch (error) {
console.error('Failed to create storage directories:', error);
process.exit(1);
}
// Initialize metadata file if it doesn't exist
try {
if (!fs.existsSync(METADATA_FILE)) {
fs.writeJsonSync(METADATA_FILE, []);
console.log('Metadata file initialized');
}
} catch (error) {
console.error('Failed to initialize metadata file:', error);
process.exit(1);
}
// Initialize analytics files if they don't exist
try {
if (!fs.existsSync(ANALYTICS_EVENTS_FILE)) {
fs.writeJsonSync(ANALYTICS_EVENTS_FILE, []);
console.log('Analytics events file initialized');
}
if (!fs.existsSync(ANALYTICS_SESSIONS_FILE)) {
fs.writeJsonSync(ANALYTICS_SESSIONS_FILE, []);
console.log('Analytics sessions file initialized');
}
} catch (error) {
console.error('Failed to initialize analytics files:', error);
// Non-fatal - analytics is optional
}
// Initialize crashes metadata file if it doesn't exist
try {
if (!fs.existsSync(CRASHES_METADATA_FILE)) {
fs.writeJsonSync(CRASHES_METADATA_FILE, []);
console.log('Crashes metadata file initialized');
}
} catch (error) {
console.error('Failed to initialize crashes metadata file:', error);
// Non-fatal - crashes is optional
}
// Initialize crash groups file if it doesn't exist
try {
if (!fs.existsSync(CRASH_GROUPS_FILE)) {
fs.writeJsonSync(CRASH_GROUPS_FILE, []);
console.log('Crash groups file initialized');
}
} catch (error) {
console.error('Failed to initialize crash groups file:', error);
}
// Helper functions
function loadMetadata() {
try {
return fs.readJsonSync(METADATA_FILE);
} catch (error) {
console.error('Error loading metadata:', error);
return [];
}
}
function saveMetadata(metadata) {
try {
fs.writeJsonSync(METADATA_FILE, metadata, { spaces: 2 });
} catch (error) {
console.error('Error saving metadata:', error);
}
}
function saveBase64File(base64Data, filename) {
try {
const buffer = Buffer.from(base64Data, 'base64');
fs.writeFileSync(filename, buffer);
return true;
} catch (error) {
console.error('Error saving file:', error);
return false;
}
}
// Analytics helper functions
function loadAnalyticsEvents() {
try {
return fs.readJsonSync(ANALYTICS_EVENTS_FILE);
} catch (error) {
console.error('Error loading analytics events:', error);
return [];
}
}
function saveAnalyticsEvents(events) {
try {
fs.writeJsonSync(ANALYTICS_EVENTS_FILE, events, { spaces: 2 });
} catch (error) {
console.error('Error saving analytics events:', error);
}
}
function loadAnalyticsSessions() {
try {
return fs.readJsonSync(ANALYTICS_SESSIONS_FILE);
} catch (error) {
console.error('Error loading analytics sessions:', error);
return [];
}
}
function saveAnalyticsSessions(sessions) {
try {
fs.writeJsonSync(ANALYTICS_SESSIONS_FILE, sessions, { spaces: 2 });
} catch (error) {
console.error('Error saving analytics sessions:', error);
}
}
async function compressAndSaveThumbnail(base64Data, filename) {
// Fallback to original save if Sharp is not available
if (!sharp) {
console.log('Sharp not available, saving original thumbnail');
return saveBase64File(base64Data, filename) ? filename : null;
}
try {
const buffer = Buffer.from(base64Data, 'base64');
// Guard against decompression bombs: check image dimensions before processing
const metadata = await sharp(buffer).metadata();
if (metadata.width > 4096 || metadata.height > 4096) {
console.warn(`Thumbnail rejected: dimensions ${metadata.width}x${metadata.height} exceed 4096px limit`);
return saveBase64File(base64Data, filename) ? filename : null;
}
// Compress only (keep original resolution): 90% quality JPEG
const compressedBuffer = await sharp(buffer)
.jpeg({
quality: 90,
progressive: true
})
.toBuffer();
// Keep .png extension for game compatibility (JPEG data in PNG file)
fs.writeFileSync(filename, compressedBuffer);
const originalSize = buffer.length;
const compressedSize = compressedBuffer.length;
const savings = ((originalSize - compressedSize) / originalSize * 100).toFixed(1);
console.log(`Thumbnail compressed: ${(originalSize/1024/1024).toFixed(1)}MB → ${(compressedSize/1024).toFixed(0)}KB (${savings}% savings)`);
return filename;
} catch (error) {
console.error('Error compressing thumbnail:', error);
// Fallback to original save
return saveBase64File(base64Data, filename) ? filename : null;
}
}
// Crash report helper functions
function loadCrashesMetadata() {
try {
return fs.readJsonSync(CRASHES_METADATA_FILE);
} catch (error) {
console.error('Error loading crashes metadata:', error);
return [];
}
}
function saveCrashesMetadata(metadata) {
try {
fs.writeJsonSync(CRASHES_METADATA_FILE, metadata, { spaces: 2 });
} catch (error) {
console.error('Error saving crashes metadata:', error);
}
}
function loadCrashGroups() {
try {
return fs.readJsonSync(CRASH_GROUPS_FILE);
} catch (error) {
console.error('Error loading crash groups:', error);
return [];
}
}
function saveCrashGroups(groups) {
try {
fs.writeJsonSync(CRASH_GROUPS_FILE, groups, { spaces: 2 });
} catch (error) {
console.error('Error saving crash groups:', error);
}
}
// Extract crash context from UE5 crash report ZIP
// Includes ZIP bomb protection: limits individual entry sizes
const MAX_ZIP_ENTRY_SIZE = 10 * 1024 * 1024; // 10 MB max per extracted entry
function extractCrashContext(buffer) {
if (!AdmZip) return null;
try {
const zip = new AdmZip(buffer);
const entry = zip.getEntry('CrashContext.runtime-xml');
if (!entry) return null;
// ZIP bomb protection: check decompressed size before extracting
if (entry.header.size > MAX_ZIP_ENTRY_SIZE) {
console.warn(`ZIP entry CrashContext.runtime-xml too large: ${entry.header.size} bytes, skipping`);
return null;
}
const xml = entry.getData().toString('utf-8');
// Simple XML tag extractor (avoids needing an XML parser dependency)
const get = (tag) => {
const m = xml.match(new RegExp(`<${tag}>([\\s\\S]*?)</${tag}>`));
return m ? m[1].trim() : '';
};
// Extract actual crash timestamp from minidump header
let crash_time = null;
const dmpEntry = zip.getEntry('UEMinidump.dmp');
if (dmpEntry && dmpEntry.header.size <= MAX_ZIP_ENTRY_SIZE) {
const dmpData = dmpEntry.getData();
// MINIDUMP_HEADER: Signature(4) Version(4) NumberOfStreams(4) StreamDirectoryRva(4) CheckSum(4) TimeDateStamp(4)
if (dmpData.length >= 24 && dmpData.toString('ascii', 0, 4) === 'MDMP') {
const unixTimestamp = dmpData.readUInt32LE(20);
if (unixTimestamp > 0) {
crash_time = new Date(unixTimestamp * 1000).toISOString();
}
}
}
return {
error_message: get('ErrorMessage'),
crash_type: get('CrashType'),
is_assert: get('IsAssert') === 'true',
is_stall: get('IsStall') === 'true',
is_oom: get('MemoryStats.bIsOOM') === '1',
callstack_hash: get('PCallStackHash'),
callstack: get('PCallStack'),
cpu: get('Misc.CPUBrand'),
gpu: get('Misc.PrimaryGPUBrand'),
os: get('Misc.OSVersionMajor'),
ram_gb: parseInt(get('MemoryStats.TotalPhysicalGB')) || 0,
ram_available_bytes: parseInt(get('MemoryStats.AvailablePhysical')) || 0,
vram_used_bytes: parseInt(get('MemoryStats.UsedVirtual')) || 0,
engine_version: get('EngineVersion'),
build_config: get('BuildConfiguration'),
seconds_since_start: parseInt(get('SecondsSinceStart')) || 0,
game_name: get('GameName'),
locale: get('AppDefaultLocale'),
crash_time: crash_time
};
} catch (error) {
console.error('Failed to extract crash context:', error.message);
return null;
}
}
// Derive a meaningful category from the error message content, not just crash_type
function deriveCategory(ctx) {
const err = (ctx.error_message || '').toLowerCase();
const crashType = (ctx.crash_type || '').toLowerCase();
// Specific error patterns (checked first — most informative)
if (err.includes('shader compilation failures')) return 'Shader Compilation';
if (err.includes('out of video memory')) return 'Out of VRAM';
if (err.includes('ran out of memory') || err.includes('paging file')) return 'Out of RAM';
if (err.includes('gpu crash dump')) return 'GPU Crash';
if (err.includes('timed out waiting for renderthread')) return 'Render Hang';
if (err.includes('hang detected')) return 'Thread Hang';
if (err.includes('scalability.ini') || err.includes('ecvf_scalability')) return 'Config Error';
if (err.includes('exception_access_violation')) return 'Access Violation';
if (err.includes('uniformbuffer') || err.includes('shadertablehash')) return 'Shader Mismatch';
if (err.includes('material') && (err.includes('deleted') || err.includes('render proxy'))) return 'Material Error';
if (err.includes('isingamethread') || err.includes('isinrenderingthread')) return 'Threading Error';
if (err.includes('crashing the gamethread at your request')) return 'Intentional Crash';
// Fall back to crash_type for anything unmatched
if (crashType === 'outofmemory') return 'Out of Memory';
if (crashType === 'gpucrash') return 'GPU Crash';
if (crashType === 'hang') return 'Hang';
if (crashType === 'ensure') return 'Assertion';
if (crashType === 'assert') return 'Fatal Error';
if (crashType === 'crash') return 'Crash';
return 'Unknown';
}
// Derive severity from group crash count
function deriveSeverity(count) {
if (count >= 10) return 'critical';
if (count >= 5) return 'high';
if (count >= 2) return 'medium';
return 'low';
}
// Derive a group key from the error message — groups by error pattern, not exact callstack
function deriveGroupKey(ctx) {
const err = ctx.error_message || '';
// Extract [File:...\Filename.cpp] [Line: N] pattern
const fileLineMatch = err.match(/\[File:.*?([^\\\/:]+)\]\s*\[Line:\s*(\d+)\]/);
if (fileLineMatch) {
return `${fileLineMatch[1]}:${fileLineMatch[2]}`;
}
// For messages without file/line, normalize the first line
const firstLine = err.split('\n')[0].trim();
const normalized = firstLine
.replace(/0x[0-9a-fA-F]+/g, '0x_') // hex addresses
.replace(/after \d+\.\d+ seconds/g, 'after N seconds') // timeout values
.replace(/allocating \d+/g, 'allocating N') // allocation sizes
.slice(0, 120);
return normalized || ctx.crash_type || 'unknown';
}
// Parse JSON from AI response (handles markdown code blocks)
function parseAIJson(responseText) {
try {
return JSON.parse(responseText);
} catch (e) {
const jsonMatch = responseText.match(/```(?:json)?\s*([\s\S]*?)```/);
if (jsonMatch) {
return JSON.parse(jsonMatch[1].trim());
}
throw new Error('Failed to parse AI response as JSON');
}
}
// Get the actual crash date (prefer minidump timestamp over upload date)
function getCrashDateForReport(c) {
return new Date((c.crash_context && c.crash_context.crash_time) || c.upload_date);
}
// Filter crashes by date range
function filterCrashesByDate(crashes, from, to) {
let result = crashes;
if (from) {
const fromDate = new Date(from);
if (!isNaN(fromDate)) result = result.filter(c => getCrashDateForReport(c) >= fromDate);
}
if (to) {
const toDate = new Date(to);
if (!isNaN(toDate)) {
// Set to end of day
toDate.setHours(23, 59, 59, 999);
result = result.filter(c => getCrashDateForReport(c) <= toDate);
}
}
return result;
}
// Filter crashes by hardware properties
function filterCrashesByHardware(crashes, query) {
let result = crashes;
if (query.gpu) {
result = result.filter(c => ((c.crash_context && c.crash_context.gpu) || c.gpu || '') === query.gpu);
}
if (query.cpu) {
result = result.filter(c => (c.crash_context && c.crash_context.cpu || '') === query.cpu);
}
if (query.ram) {
const ramGb = parseInt(query.ram);
if (!isNaN(ramGb)) result = result.filter(c => c.crash_context && c.crash_context.ram_gb === ramGb);
}
if (query.os) {
result = result.filter(c => {
if (!c.crash_context || !c.crash_context.os) return false;
const os = c.crash_context.os;
if (query.os === 'Windows 11') return os.includes('Windows 11');
if (query.os === 'Windows 10') return os.includes('Windows 10');
return os.includes(query.os);
});
}
return result;
}
// Apply both date and hardware filters from a request's query params
function applyFilters(crashes, query) {
let result = filterCrashesByDate(crashes, query.from, query.to);
return filterCrashesByHardware(result, query);
}
// Categorize and group a crash (no AI, instant, deterministic)
function categorizeAndGroupCrash(crashId) {
const allCrashes = loadCrashesMetadata();
const crash = allCrashes.find(c => c.id === crashId);
if (!crash) return;
const groups = loadCrashGroups();
const ctx = crash.crash_context || {};
// Group by error pattern (file+line or normalized message)
const groupKey = deriveGroupKey(ctx);
// Derive meaningful category from error content
const category = deriveCategory(ctx);
// Store classification on crash
crash.category = category;
crash.crash_type = ctx.crash_type || 'Unknown';
// Find or create group
let group = groups.find(g => g.group_key === groupKey);
const gpuName = ctx.gpu || crash.gpu;
const versionName = crash.version;
const platformName = crash.platform;
const crashDate = ctx.crash_time || crash.upload_date;
if (group) {
if (!group.crash_ids.includes(crashId)) {
group.crash_ids.push(crashId);
group.count = group.crash_ids.length;
group.severity = deriveSeverity(group.count);
// Update first/last seen using actual crash time
if (crashDate < group.first_seen) group.first_seen = crashDate;
if (crashDate > group.last_seen) group.last_seen = crashDate;
if (gpuName && gpuName !== 'unknown' && !group.affected_gpus.includes(gpuName)) {
group.affected_gpus.push(gpuName);
}
if (versionName && versionName !== 'unknown' && !group.affected_versions.includes(versionName)) {
group.affected_versions.push(versionName);
}
if (platformName && platformName !== 'unknown' && !group.affected_platforms.includes(platformName)) {
group.affected_platforms.push(platformName);
}
}
} else {
const title = ctx.error_message
? ctx.error_message.split('\n')[0].slice(0, 120)
: `Crash group ${groupKey.slice(0, 8)}`;
group = {
id: uuidv4(),
group_key: groupKey,
title,
category,
crash_type: ctx.crash_type || 'Unknown',
severity: 'low',
error_message: ctx.error_message || crash.error_message || '',
crash_ids: [crashId],
count: 1,
first_seen: crashDate,
last_seen: crashDate,
affected_gpus: gpuName && gpuName !== 'unknown' ? [gpuName] : [],
affected_versions: versionName && versionName !== 'unknown' ? [versionName] : [],
affected_platforms: platformName && platformName !== 'unknown' ? [platformName] : [],
// AI fields - populated on demand
ai_root_cause: '',
ai_suggested_fix: ''
};
groups.push(group);
}
crash.group_id = group.id;
saveCrashesMetadata(allCrashes);
saveCrashGroups(groups);
console.log(`Crash ${crashId} -> ${category} -> group "${group.title}" (${group.count} crashes)`);
}
// API Routes
// Upload design
app.post('/api/designs', requireApiKey, async (req, res) => {
try {
const { designId, title, description, authorName, level, saveData, thumbnail, christmasEvent } = req.body;
// Validate required fields
if (!title || !saveData) {
return res.status(400).json({ error: 'Title and saveData are required' });
}
// Input length validation
if (typeof title !== 'string' || title.length > 200) {
return res.status(400).json({ error: 'Title must be a string under 200 characters' });
}
if (description && (typeof description !== 'string' || description.length > 2000)) {
return res.status(400).json({ error: 'Description must be under 2000 characters' });
}
if (authorName && (typeof authorName !== 'string' || authorName.length > 100)) {
return res.status(400).json({ error: 'Author name must be under 100 characters' });
}
// Use provided designId or generate new one — validate format to prevent path traversal
if (designId && !isValidUUID(designId)) {
return res.status(400).json({ error: 'Invalid designId format (must be UUID)' });
}
const finalDesignId = designId || uuidv4();
const designFilename = `${finalDesignId}.sav`;
const designPath = path.join(DESIGNS_DIR, designFilename);
// Save design file (always overwrite)
if (!saveBase64File(saveData, designPath)) {
return res.status(500).json({ error: 'Failed to save design file' });
}
// Save and compress thumbnail if provided (always overwrite)
let thumbnailUrl = null;
if (thumbnail) {
const thumbnailFilename = `${finalDesignId}.png`;
const thumbnailPath = path.join(THUMBNAILS_DIR, thumbnailFilename);
// Use compression for new thumbnails
const savedThumbnailPath = await compressAndSaveThumbnail(thumbnail, thumbnailPath);
if (savedThumbnailPath) {
const savedFilename = path.basename(savedThumbnailPath);
thumbnailUrl = `/api/thumbnails/${savedFilename}`;
}
}
// Check if design already exists (update vs create)
const allMetadata = loadMetadata();
const existingIndex = allMetadata.findIndex(d => d.id === finalDesignId);
if (existingIndex !== -1) {
// Update existing design (preserve download_count)
const existingDesign = allMetadata[existingIndex];
allMetadata[existingIndex] = {
id: finalDesignId,
title: title || 'Untitled Design',
description: description || '',
author_name: authorName || 'Anonymous',
level: level || '',
download_count: existingDesign.download_count, // Preserve download count
upload_date: new Date().toISOString(), // Update to current time
thumbnail_url: thumbnailUrl || existingDesign.thumbnail_url, // Use new thumbnail or keep existing
christmas_event: christmasEvent === true // Boolean flag for Christmas event designs
};
console.log(`Design updated: ${title} by ${authorName} (ID: ${finalDesignId})${christmasEvent ? ' [Christmas Event]' : ''}`);
} else {
// Create new design
const designMetadata = {
id: finalDesignId,
title: title || 'Untitled Design',
description: description || '',
author_name: authorName || 'Anonymous',
level: level || '',
download_count: 0,
upload_date: new Date().toISOString(),
thumbnail_url: thumbnailUrl,
christmas_event: christmasEvent === true // Boolean flag for Christmas event designs
};
allMetadata.push(designMetadata);
console.log(`Design created: ${title} by ${authorName} (ID: ${finalDesignId})${christmasEvent ? ' [Christmas Event]' : ''}`);
}
saveMetadata(allMetadata);
const isUpdate = existingIndex !== -1;
res.json({
success: true,
design_id: finalDesignId,
updated: isUpdate,
message: isUpdate ? 'Design updated successfully' : 'Design uploaded successfully'
});
} catch (error) {
console.error('Upload error:', error);
res.status(500).json({ error: 'Internal server error' });
}
});
// Browse designs
app.get('/api/designs', requireApiKey, (req, res) => {
try {
let allMetadata = loadMetadata();
// Get sort parameter (default to date sorting for backward compatibility)
const sortMode = req.query.sort || 'date';
// Get search query parameter
const searchQuery = req.query.search;
// Get level filter parameter (single string)
const levelFilter = req.query.level;
// Get level filters parameter (JSON array of strings for localized level names)
let levelFilters = null;
if (req.query.levelFilters) {
try {
levelFilters = JSON.parse(req.query.levelFilters);
if (!Array.isArray(levelFilters)) {
levelFilters = null;
}
} catch (e) {
// Invalid JSON, ignore
levelFilters = null;
}
}
// Get date filter parameter (fromDate)
const fromDate = req.query.fromDate;
// Get Christmas event filter (true = only Christmas designs, false = exclude them, omit = all)
const christmasEventFilter = req.query.christmasEvent;
// Log request summary (not user-supplied data)
if (isDevelopment) {
console.log(`Browse request: sort=${sortMode}, hasSearch=${!!searchQuery}, hasLevel=${!!levelFilter}`);
}
// Filter by search query if provided
if (searchQuery && searchQuery.trim() !== '') {
const searchLower = searchQuery.toLowerCase().trim();
allMetadata = allMetadata.filter(design => {
const titleMatch = design.title.toLowerCase().includes(searchLower);
const authorMatch = design.author_name.toLowerCase().includes(searchLower);
return titleMatch || authorMatch;
});
}
// Filter by level - supports both single level and array of localized level names
if (levelFilters && levelFilters.length > 0) {
// Use array of filters (for localized level names)
allMetadata = allMetadata.filter(design => {
if (!design.level) return false;
// Match if design.level contains ANY of the filter strings
return levelFilters.some(filter => design.level.includes(filter));
});
} else if (levelFilter && levelFilter.trim() !== '') {
// Fallback to single level filter (backward compatible)
allMetadata = allMetadata.filter(design => {
// Support both exact match and partial match (for flexibility)
return design.level && design.level.includes(levelFilter);
});
}
// Filter by date if provided (only show designs from this date onwards)
if (fromDate && fromDate.trim() !== '') {
const filterDate = new Date(fromDate);
if (!isNaN(filterDate.getTime())) {
allMetadata = allMetadata.filter(design => {
const designDate = new Date(design.upload_date);
return designDate >= filterDate;
});
}
}
// Filter by Christmas event flag if provided
if (christmasEventFilter !== undefined && christmasEventFilter !== '') {
const wantChristmas = christmasEventFilter === 'true' || christmasEventFilter === true;
allMetadata = allMetadata.filter(design => {
// Treat missing/undefined christmas_event as false (backward compatible)
const isChristmas = design.christmas_event === true;
return wantChristmas ? isChristmas : !isChristmas;
});
}
// Sort based on the specified mode
if (sortMode === 'downloads') {
// Sort by download count (highest first), then by upload date (newest first)
allMetadata.sort((a, b) => {
if (b.download_count !== a.download_count) {
return b.download_count - a.download_count;
}
return new Date(b.upload_date) - new Date(a.upload_date);
});
} else {
// Default: Sort by upload date (newest first)
allMetadata.sort((a, b) => new Date(b.upload_date) - new Date(a.upload_date));
}
// ALWAYS return ALL designs (filtered if search/level/date provided) - no pagination
let logMessage = `Browse request: returning ${allMetadata.length} designs`;
if (searchQuery) logMessage += `, search="${searchQuery}"`;
if (levelFilters) logMessage += `, levelFilters=[${levelFilters.join(', ')}]`;
else if (levelFilter) logMessage += `, level="${levelFilter}"`;
if (fromDate) logMessage += `, fromDate="${fromDate}"`;
if (christmasEventFilter !== undefined && christmasEventFilter !== '') logMessage += `, christmasEvent=${christmasEventFilter}`;
logMessage += `, sort=${sortMode}`;
console.log(logMessage);
res.json({
designs: allMetadata,
total: allMetadata.length
});