-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathserver.js
More file actions
executable file
·2260 lines (1931 loc) · 73.7 KB
/
server.js
File metadata and controls
executable file
·2260 lines (1931 loc) · 73.7 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import express from 'express';
import path from 'path';
import { fileURLToPath } from 'url';
import { dirname } from 'path';
import { GoogleGenerativeAI } from '@google/generative-ai';
import compression from 'compression';
import rateLimit from 'express-rate-limit';
import cors from 'cors';
import cookieParser from 'cookie-parser';
import crypto from 'crypto';
import xxhash from 'xxhash-wasm';
import { SECURITY_CONFIG } from './serverConfig.js';
import fs from 'fs';
import { execFile } from 'child_process';
import { promisify } from 'util';
import os from 'os';
import multer from 'multer';
import JSZip from 'jszip';
const execFileAsync = promisify(execFile);
import {
initCache,
hashContent,
getCachedAIReport,
setCachedAIReport,
getCachedWinDBGAnalysis,
setCachedWinDBGAnalysis,
getCachedAnalysis,
setCachedAnalysis,
isAnalysisCached,
getCacheStats
} from './services/cache.js';
const __filename = fileURLToPath(import.meta.url);
const __dirname = dirname(__filename);
const app = express();
const PORT = process.env.PORT || 8080;
// Trust proxy headers (required for Cloud Run)
// Set to 2 to trust both Cloudflare and Cloud Run load balancer
// This ensures req.ip extracts the real client IP from X-Forwarded-For
app.set('trust proxy', 2);
// Helper to get client IP - prefer Cloudflare's header for accuracy
function getClientIp(req) {
// Cloudflare provides the real client IP in CF-Connecting-IP header
// This is more reliable than parsing X-Forwarded-For
return req.headers['cf-connecting-ip'] || req.ip || req.connection.remoteAddress;
}
// Initialize xxhash (awaited before server starts listening)
let hasher;
// Initialize Upstash Redis cache
initCache();
// Secret for session validation
const SESSION_SECRET = process.env.SESSION_SECRET;
if (!SESSION_SECRET) {
if (process.env.NODE_ENV === 'production') {
console.error('WARNING: SESSION_SECRET not set - using temporary secret. Sessions will be invalid on restart.');
// Use a temporary secret to allow the service to start
const TEMP_SECRET = crypto.randomBytes(32).toString('hex');
process.env.SESSION_SECRET = TEMP_SECRET;
}
}
// Use the secret (either from env or temporary)
const ACTUAL_SESSION_SECRET = process.env.SESSION_SECRET || crypto.randomBytes(32).toString('hex');
// Store valid sessions
const validSessions = new Map(); // sessionId -> { hash, timestamp, ip }
const SESSION_EXPIRY = 60 * 60 * 1000; // 1 hour
// Track API requests per session (prevent rapid abuse)
const sessionRequestTracking = new Map(); // sessionId -> { count, resetTime, totalTokens }
const REQUEST_LIMIT_PER_SESSION = 50; // Max 50 requests per hour per session
const TOKEN_LIMIT_PER_SESSION = 500000; // Max ~500K tokens per hour per session (increased for full WinDBG output)
// ============================================================
// External API Key Authentication
// ============================================================
const BSOD_API_KEY = process.env.BSOD_API_KEY;
if (!BSOD_API_KEY) {
console.warn('WARNING: BSOD_API_KEY not configured - external API access disabled');
}
// Multer configuration for file uploads (memory storage for API endpoint)
const upload = multer({
storage: multer.memoryStorage(),
limits: {
fileSize: 500 * 1024 * 1024, // 500MB max
files: 1 // Single file only
},
fileFilter: (req, file, cb) => {
// Accept dump files and archives
const allowedExtensions = ['.dmp', '.mdmp', '.hdmp', '.kdmp', '.zip', '.7z', '.rar'];
const ext = file.originalname.toLowerCase().substring(file.originalname.lastIndexOf('.'));
if (allowedExtensions.includes(ext)) {
cb(null, true);
} else {
cb(new Error(`Invalid file type. Allowed: ${allowedExtensions.join(', ')}`));
}
}
});
// Clean up expired sessions periodically
setInterval(() => {
const now = Date.now();
for (const [sessionId, data] of validSessions.entries()) {
if (now - data.timestamp > SESSION_EXPIRY) {
validSessions.delete(sessionId);
}
}
}, 10 * 60 * 1000); // Clean every 10 minutes
// Read model name from config file
let DEFAULT_MODEL_NAME = 'gemini-3.1-flash-lite-preview';
try {
const modelConfig = fs.readFileSync(path.join(__dirname, 'model.cfg'), 'utf8').trim();
if (modelConfig) {
DEFAULT_MODEL_NAME = modelConfig;
}
} catch (error) {
console.log('model.cfg not found or error reading, using default model:', DEFAULT_MODEL_NAME);
}
// Load SRI mapping if available
let sriMapping = {};
try {
const sriPath = path.join(__dirname, 'dist', 'sri-mapping.json');
if (fs.existsSync(sriPath)) {
sriMapping = JSON.parse(fs.readFileSync(sriPath, 'utf8'));
console.log('SRI mapping loaded:', Object.keys(sriMapping).length, 'files');
}
} catch (error) {
console.log('No SRI mapping found, continuing without integrity checks');
}
// Configure CORS with Cloud Run best practices
const corsOptions = {
origin: function (origin, callback) {
// Important: Allow requests with no origin (same-origin, server-side, curl, etc.)
// This is safe and necessary for Cloud Run
if (!origin) {
return callback(null, true);
}
// Allow file:// protocol origins
if (origin.startsWith('file://')) {
return callback(null, true);
}
// Build allowed origins based on environment
const allowedOrigins = [];
if (process.env.NODE_ENV !== 'production') {
// Development origins
allowedOrigins.push(
'http://localhost:5173', // Vite dev server
'http://localhost:8080', // Local server
'http://localhost:3000' // Common React dev port
);
}
// Production origins from environment
if (process.env.PRODUCTION_URL) {
allowedOrigins.push(process.env.PRODUCTION_URL);
}
if (process.env.ALLOWED_ORIGINS) {
// Support comma-separated list
allowedOrigins.push(...process.env.ALLOWED_ORIGINS.split(',').map(o => o.trim()));
}
// Default production origins
allowedOrigins.push(
'https://bsod.windowsforum.com',
'https://bsod-analyzer-ctlmwtcf5q-ue.a.run.app', // Cloud Run URL
'https://bsod-analyzer-399450330005.us-east1.run.app' // New Cloud Run URL
);
// Allow any *.windowsforum.com subdomain (including www.)
const isWindowsForumDomain = origin && /^https:\/\/(www\.)?([a-z0-9-]+\.)?windowsforum\.com$/i.test(origin);
// Allow any Cloud Run URL (*.run.app) - we control the deployment
const isCloudRunApp = origin && /^https:\/\/[a-z0-9-]+(\.[a-z0-9-]+)*\.run\.app$/i.test(origin);
if (allowedOrigins.includes(origin) || isWindowsForumDomain || isCloudRunApp) {
callback(null, true);
} else {
console.warn(`CORS blocked origin: ${origin}`);
callback(new Error('Not allowed by CORS'));
}
},
credentials: true,
methods: ['GET', 'POST', 'PUT', 'DELETE', 'OPTIONS'],
allowedHeaders: ['Content-Type', 'Authorization', 'X-Requested-With'],
exposedHeaders: ['Content-Length', 'Content-Type'],
maxAge: 86400, // Cache preflight for 24 hours
preflightContinue: false,
optionsSuccessStatus: 204
};
// Middleware
// Apply CORS globally (Cloud Run best practice)
app.use(cors(corsOptions));
// Cookie parser middleware
app.use(cookieParser());
// Rate limiting middleware
const apiLimiter = rateLimit({
windowMs: SECURITY_CONFIG.api.rateLimiting.windowMs,
max: SECURITY_CONFIG.api.rateLimiting.maxRequests,
message: SECURITY_CONFIG.api.rateLimiting.message,
standardHeaders: true,
legacyHeaders: false,
// Skip successful requests to prevent false positives
skipSuccessfulRequests: false,
// Explicitly handle the trust proxy configuration
skip: (req) => {
// Skip rate limiting for health check endpoint
return req.path === '/health';
}
});
app.use(compression({
level: 6, // Compression level 1-9 (6 is good balance)
threshold: 1024, // Only compress responses above 1KB
filter: (req, res) => {
// Don't compress if client doesn't support it
if (req.headers['x-no-compression']) {
return false;
}
// Use compression filter
return compression.filter(req, res);
}
}));
// Higher limit parser for file upload endpoints (base64-encoded files can be up to 133MB for 100MB files)
const largeJsonParser = express.json({ limit: '150mb' });
// Default JSON body limit for most API endpoints
// Skip for routes that need larger payloads (they use largeJsonParser directly)
app.use((req, res, next) => {
if (req.path === '/api/windbg/upload') {
return next(); // Skip default parser, route will use largeJsonParser
}
express.json({ limit: '10mb' })(req, res, next);
});
// Precompute CSP header string once at startup (avoids rebuilding on every request)
const CSP_HEADER = [
"default-src 'self'",
"script-src 'self' 'unsafe-inline' 'wasm-unsafe-eval' https://*.cloudflare.com https://static.cloudflareinsights.com https://*.google https://*.google.com https://*.googletagmanager.com https://*.googlesyndication.com https://adnxs.com https://www.paypalobjects.com",
"style-src 'self' 'unsafe-inline' https://fonts.googleapis.com https://*.googleapis.com",
"font-src 'self' data: https://fonts.gstatic.com",
"img-src 'self' data: https: blob:",
"connect-src 'self' https://challenges.cloudflare.com https://*.google https://*.google.com https://*.gstatic.com https://*.googletagmanager.com https://*.googlesyndication.com https://*.doubleclick.net https://api.claude.ai https://generativelanguage.googleapis.com https://www.paypal.com",
"frame-src 'self' https://challenges.cloudflare.com https://*.google https://*.google.com https://*.googletagmanager.com https://*.googlesyndication.com https://*.doubleclick.net https://www.paypal.com",
"object-src 'none'",
"base-uri 'self'",
"form-action 'self' https://www.paypal.com",
"frame-ancestors 'self'",
"upgrade-insecure-requests"
].join('; ');
// Global security headers middleware
app.use((req, res, next) => {
res.setHeader('X-Content-Type-Options', 'nosniff');
res.setHeader('X-Frame-Options', 'SAMEORIGIN');
res.setHeader('X-XSS-Protection', '1; mode=block');
res.setHeader('Referrer-Policy', 'strict-origin-when-cross-origin');
res.setHeader('Permissions-Policy', 'geolocation=(), microphone=(), camera=()');
res.setHeader('Content-Security-Policy', CSP_HEADER);
res.setHeader('Cross-Origin-Resource-Policy', 'cross-origin');
res.setHeader('Cross-Origin-Opener-Policy', 'same-origin');
next();
});
// MIME type lookup for static assets
const MIME_TYPES = {
'.js': 'application/javascript', '.mjs': 'application/javascript',
'.css': 'text/css', '.html': 'text/html', '.json': 'application/json',
'.woff2': 'font/woff2', '.woff': 'font/woff', '.ttf': 'font/ttf',
'.otf': 'font/otf', '.eot': 'application/vnd.ms-fontobject',
'.png': 'image/png', '.jpg': 'image/jpeg', '.jpeg': 'image/jpeg',
'.webp': 'image/webp', '.svg': 'image/svg+xml', '.ico': 'image/x-icon',
};
// Set MIME types for assets BEFORE any other middleware
// Ensures Cloud Run serves files with correct Content-Type
app.use((req, res, next) => {
if (req.path.startsWith('/assets/')) {
const ext = path.extname(req.path).toLowerCase();
const mime = MIME_TYPES[ext];
if (mime) res.type(mime);
}
next();
});
// Security middleware - block access to sensitive paths
app.use((req, res, next) => {
const blockedPaths = [
'/public',
'/src',
'/components',
'/pages',
'/services',
'/hooks',
'/types',
'/node_modules',
'/.git',
'/.env'
];
const blockedExtensions = [
'.ts',
'.tsx',
'.js.map',
'.css.map',
'.log',
'package.json',
'package-lock.json',
'tsconfig.json',
'vite.config.ts',
'.env'
];
// Block access to sensitive directories
if (blockedPaths.some(path => req.path.startsWith(path))) {
return res.status(403).send('Access Denied');
}
// Block access to sensitive file types
if (blockedExtensions.some(ext => req.path.endsWith(ext))) {
return res.status(403).send('Access Denied');
}
next();
});
// Static file serving with MIME types and caching via shared lookup
const TEXT_EXTS = new Set(['.js', '.mjs', '.css', '.html', '.json']);
const NOSNIFF_EXTS = new Set(['.js', '.mjs', '.css', '.html']);
const FONT_EXTS = new Set(['.woff2', '.woff', '.ttf', '.otf', '.eot']);
app.use(express.static(path.join(__dirname, 'dist'), {
maxAge: '1y',
etag: true,
lastModified: true,
setHeaders: (res, filePath) => {
const ext = path.extname(filePath).toLowerCase();
const mime = MIME_TYPES[ext];
if (mime) {
res.setHeader('Content-Type', TEXT_EXTS.has(ext) ? `${mime}; charset=utf-8` : mime);
}
if (NOSNIFF_EXTS.has(ext)) {
res.setHeader('X-Content-Type-Options', 'nosniff');
}
// Cache strategy
if (filePath.endsWith('sw.js')) {
res.setHeader('Cache-Control', 'public, max-age=0, s-maxage=0');
} else if (ext === '.html') {
res.setHeader('Cache-Control', 'public, max-age=300, s-maxage=86400');
} else if (ext === '.json') {
res.setHeader('Cache-Control', 'public, max-age=86400');
if (filePath.includes('/symbols/')) {
res.setHeader('Access-Control-Allow-Origin', '*');
}
} else if (mime) {
res.setHeader('Cache-Control', 'public, max-age=31536000, immutable');
}
// CORS for fonts
if (FONT_EXTS.has(ext)) {
res.setHeader('Access-Control-Allow-Origin', '*');
}
}
}));
// Validate Gemini API key at startup
if (!process.env.GEMINI_API_KEY) {
console.error('WARNING: GEMINI_API_KEY not configured - AI analysis will not work');
// Don't exit in production - allow service to start but AI features will be disabled
}
// Initialize Gemini AI with server-side API key
const genAI = process.env.GEMINI_API_KEY ? new GoogleGenerativeAI(process.env.GEMINI_API_KEY) : null;
// Turnstile secret key from environment/Secret Manager
const TURNSTILE_SECRET_KEY = process.env.TURNSTILE_SECRET_KEY;
// Store used tokens to prevent replay attacks
const usedTurnstileTokens = new Map(); // token -> timestamp
// Clean up old tokens periodically (older than 5 minutes)
setInterval(() => {
const fiveMinutesAgo = Date.now() - (5 * 60 * 1000);
for (const [token, timestamp] of usedTurnstileTokens.entries()) {
if (timestamp < fiveMinutesAgo) {
usedTurnstileTokens.delete(token);
}
}
}, 60 * 1000); // Clean every minute
// Verify Turnstile token with proper Siteverify implementation
async function verifyTurnstileToken(token, ip, idempotencyKey = null) {
if (!TURNSTILE_SECRET_KEY) {
console.error('TURNSTILE_SECRET_KEY not configured');
return {
success: false,
'error-codes': ['missing-input-secret'],
error: 'Turnstile not configured'
};
}
if (!token) {
return {
success: false,
'error-codes': ['missing-input-response'],
error: 'No token provided'
};
}
// Check if token was already used (prevent replay attacks)
if (usedTurnstileTokens.has(token) && !idempotencyKey) {
console.warn('Turnstile token already used:', token.substring(0, 20) + '...');
return {
success: false,
'error-codes': ['timeout-or-duplicate'],
error: 'Token already used'
};
}
try {
// Build form data as required by Siteverify API
const formData = new URLSearchParams();
formData.append('secret', TURNSTILE_SECRET_KEY);
formData.append('response', token); // Must be called 'response', not 'token'
if (ip) {
formData.append('remoteip', ip);
}
// Add idempotency key for retry support
if (idempotencyKey) {
formData.append('idempotency_key', idempotencyKey);
}
const response = await fetch('https://challenges.cloudflare.com/turnstile/v0/siteverify', {
method: 'POST',
headers: {
'Content-Type': 'application/x-www-form-urlencoded'
},
body: formData
});
if (!response.ok) {
console.error('Siteverify HTTP error:', response.status);
return {
success: false,
'error-codes': ['internal-error'],
error: 'Siteverify request failed'
};
}
const result = await response.json();
if (result.success) {
// Mark token as used to prevent replay attacks
usedTurnstileTokens.set(token, Date.now());
// Log successful verification
console.log('Turnstile verification successful:', {
hostname: result.hostname,
challenge_ts: result.challenge_ts,
action: result.action
});
} else {
console.error('Turnstile verification failed:', result['error-codes']);
}
return result;
} catch (error) {
console.error('Turnstile Siteverify error:', error);
return {
success: false,
'error-codes': ['internal-error'],
error: 'Verification request failed'
};
}
}
// Generate session cookie
function generateSessionCookie(ip) {
if (!hasher) {
console.error('XXHash not initialized when trying to generate session');
throw new Error('XXHash not initialized');
}
const sessionId = crypto.randomBytes(32).toString('hex');
const timestamp = Date.now();
const dataToHash = `${sessionId}:${timestamp}:${ip}:${ACTUAL_SESSION_SECRET}`;
const sessionHash = hasher.h64ToString(dataToHash);
// Store session
validSessions.set(sessionId, {
hash: sessionHash,
timestamp,
ip
});
return {
sessionId,
sessionHash
};
}
// Set session cookies on a response
function setSessionCookies(res, sessionId, sessionHash) {
const cookieOptions = {
httpOnly: true,
secure: process.env.NODE_ENV === 'production',
sameSite: 'lax',
maxAge: SESSION_EXPIRY,
path: '/',
};
res.cookie('bsod_session_id', sessionId, cookieOptions);
res.cookie('bsod_session_hash', sessionHash, cookieOptions);
return cookieOptions;
}
// Validate session cookie
function validateSession(sessionId, sessionHash, ip) {
const sessionData = validSessions.get(sessionId);
if (!sessionData) {
return { valid: false, reason: 'Session not found' };
}
// Check expiry
if (Date.now() - sessionData.timestamp > SESSION_EXPIRY) {
validSessions.delete(sessionId);
return { valid: false, reason: 'Session expired' };
}
// Verify IP matches
if (sessionData.ip !== ip) {
return { valid: false, reason: 'IP mismatch' };
}
// Verify hash
if (sessionData.hash !== sessionHash) {
return { valid: false, reason: 'Invalid session hash' };
}
return { valid: true };
}
// Middleware to validate session for analyzer API
const requireSession = (req, res, next) => {
const sessionId = req.cookies.bsod_session_id;
const sessionHash = req.cookies.bsod_session_hash;
const clientIp = getClientIp(req);
// In development mode, skip validation
if (process.env.NODE_ENV === 'development') {
return next();
}
if (!sessionId || !sessionHash) {
console.log('Session validation failed - missing cookies:', {
sessionId: !!sessionId,
sessionHash: !!sessionHash,
cookies: Object.keys(req.cookies || {})
});
return res.status(401).json({ error: 'Session required', code: 'NO_SESSION' });
}
const validation = validateSession(sessionId, sessionHash, clientIp);
if (!validation.valid) {
console.log('Session validation failed:', {
reason: validation.reason,
sessionId: sessionId.substring(0, 10) + '...',
clientIp
});
return res.status(401).json({ error: validation.reason, code: 'INVALID_SESSION' });
}
// Refresh session timestamp
const sessionData = validSessions.get(sessionId);
sessionData.timestamp = Date.now();
next();
};
// Middleware to validate API key for external service access
const requireApiKey = (req, res, next) => {
const apiKey = req.headers['x-api-key'];
if (!BSOD_API_KEY) {
console.log('[API Auth] External API access not configured');
return res.status(503).json({
success: false,
error: 'External API access not configured',
code: 'API_NOT_CONFIGURED'
});
}
if (!apiKey) {
console.log('[API Auth] Missing API key in request');
return res.status(401).json({
success: false,
error: 'API key required',
code: 'NO_API_KEY'
});
}
if (apiKey !== BSOD_API_KEY) {
console.log('[API Auth] Invalid API key provided');
return res.status(401).json({
success: false,
error: 'Invalid API key',
code: 'INVALID_API_KEY'
});
}
// Mark request as API-authenticated (for logging)
req.isApiAuthenticated = true;
console.log('[API Auth] External API request authenticated');
next();
};
// Health check endpoint for Cloud Run (not rate limited)
app.get('/health', async (req, res) => {
const cacheStats = await getCacheStats();
res.status(200).json({
status: 'ok',
timestamp: new Date().toISOString(),
services: {
gemini: !!genAI,
turnstile: !!TURNSTILE_SECRET_KEY,
session: !!ACTUAL_SESSION_SECRET,
cache: cacheStats
}
});
});
// Apply rate limiting to API endpoints
app.use('/api/', apiLimiter);
// Endpoint to verify Turnstile and create session
app.post('/api/auth/verify-turnstile', async (req, res) => {
try {
const { token, action, cdata } = req.body;
const clientIp = getClientIp(req);
// Generate idempotency key for this request
const idempotencyKey = crypto.randomUUID();
// Verify the Turnstile token with Siteverify
const verification = await verifyTurnstileToken(token, clientIp, idempotencyKey);
if (!verification.success) {
// Log detailed error for debugging
console.error('Turnstile Siteverify failed:', {
'error-codes': verification['error-codes'],
clientIp,
tokenPrefix: token ? token.substring(0, 20) + '...' : 'none'
});
// Return appropriate error based on error codes
const errorCode = verification['error-codes']?.[0] || 'unknown-error';
let userMessage = 'Security verification failed';
switch (errorCode) {
case 'missing-input-response':
userMessage = 'Security token missing';
break;
case 'invalid-input-response':
userMessage = 'Security token invalid or expired';
break;
case 'timeout-or-duplicate':
userMessage = 'Security token already used or expired';
break;
case 'invalid-input-secret':
userMessage = 'Server configuration error';
break;
}
return res.status(400).json({
success: false,
error: userMessage,
'error-codes': verification['error-codes']
});
}
// Validate expected action if provided
if (action && verification.action !== action) {
console.warn('Turnstile action mismatch:', {
expected: action,
received: verification.action
});
}
// Validate hostname matches expected domain
const expectedHostnames = [
'localhost',
'bsod.windowsforum.com',
process.env.ALLOWED_HOSTNAME
].filter(Boolean);
if (verification.hostname && !expectedHostnames.includes(verification.hostname)) {
console.warn('Unexpected hostname in Turnstile response:', verification.hostname);
}
// If verification successful, create session
const { sessionId, sessionHash } = generateSessionCookie(clientIp);
const cookieOptions = setSessionCookies(res, sessionId, sessionHash);
res.cookie('bsod_turnstile_verified', 'true', { ...cookieOptions, maxAge: 2 * 60 * 60 * 1000 }); // 2 hours
// Return success with verification details
res.json({
success: true,
challenge_ts: verification.challenge_ts,
hostname: verification.hostname
});
} catch (error) {
console.error('Turnstile endpoint error:', error);
res.status(500).json({
success: false,
error: 'Verification failed',
'error-codes': ['internal-error']
});
}
});
// Signing key endpoint removed - signature validation simplified
// Endpoint to get session cookie (called when user visits analyzer page)
app.get('/api/auth/session', async (req, res) => {
try {
// Ensure XXHash is initialized
if (!hasher) {
console.log('Waiting for XXHash to initialize...');
await new Promise(resolve => setTimeout(resolve, 100));
if (!hasher) {
return res.status(503).json({ error: 'Session service not ready' });
}
}
const clientIp = getClientIp(req);
const { sessionId, sessionHash } = generateSessionCookie(clientIp);
console.log('Creating session:', {
sessionIdPrefix: sessionId.substring(0, 10) + '...',
clientIp,
cookieDomain: req.get('host')
});
setSessionCookies(res, sessionId, sessionHash);
res.json({ success: true });
} catch (error) {
console.error('Session generation error:', error);
res.status(500).json({ error: 'Failed to create session' });
}
});
// Helper function to validate that prompts are BSOD-related (prevent API abuse)
// SIMPLIFIED: Focus on blocking obvious abuse, allow all BSOD-related content
function validateBSODPrompt(contents) {
// Handle both string and array formats
let promptText;
if (typeof contents === 'string') {
// Direct string format
promptText = contents.toLowerCase();
} else if (Array.isArray(contents) && contents.length > 0) {
// Gemini API format: array of content objects
promptText = contents
.flatMap(c => c.parts || [])
.map(p => p.text || '')
.join(' ')
.toLowerCase();
} else {
console.log('[Validation] FAILED: Invalid contents structure');
return { valid: false, reason: 'Invalid contents structure' };
}
console.log('[Validation] Prompt length:', promptText.length, 'First 100 chars:', promptText.substring(0, 100));
// Must be substantial prompt (not just "hi" or "test")
if (promptText.length < 50) {
console.log('[Validation] FAILED: Prompt too short');
return { valid: false, reason: 'Prompt too short for crash analysis' };
}
// Must contain BSOD/crash analysis keywords (at least ONE)
const requiredKeywords = [
'crash dump',
'windows crash',
'bug check',
'bsod',
'analyzing a windows',
'kernel debugger',
'dump file',
'minidump',
'memory dump',
'stop code',
'exception code',
'faulting module',
'windows',
'crash',
'dump',
'error',
'blue screen',
'black screen'
];
const hasKeyword = requiredKeywords.some(keyword =>
promptText.includes(keyword)
);
if (!hasKeyword) {
console.log('[Validation] FAILED: Missing crash analysis keywords');
return { valid: false, reason: 'Missing crash analysis keywords' };
}
console.log('[Validation] Has keyword: true');
// Reject obvious abuse patterns (simplified)
const abusePatterns = [
/write\s+(me\s+)?(a\s+)?(story|poem|essay|song|novel)/i,
/tell\s+me\s+(a\s+)?(joke|story)/i,
/translate\s+to\s+/i,
/ignore\s+(previous|above)\s+instructions/i,
/forget\s+your\s+instructions/i
];
const matchedPattern = abusePatterns.find(pattern => pattern.test(promptText));
if (matchedPattern) {
console.log('[Validation] FAILED: Abuse pattern detected:', matchedPattern);
return { valid: false, reason: `Abuse pattern detected` };
}
console.log('[Validation] PASSED all checks');
return { valid: true };
}
// Proxy endpoint for Gemini API calls - now requires session
app.post('/api/gemini/generateContent', requireSession, async (req, res) => {
try {
// Check if Gemini AI is configured
if (!genAI) {
return res.status(503).json({
error: 'AI service not configured. Please try again later.'
});
}
// Validate request size
const requestSize = JSON.stringify(req.body).length;
if (requestSize > SECURITY_CONFIG.api.maxRequestSize) {
return res.status(413).json({
error: `Request too large. Maximum size is ${SECURITY_CONFIG.api.maxRequestSize / 1024 / 1024}MB`
});
}
const { contents, generationConfig, safetySettings, config, fileHash } = req.body;
const sessionId = req.cookies.bsod_session_id;
// Security: Session validation is handled by requireSession middleware
// Additional security layers: rate limiting, prompt validation, system instruction
// SECURITY: Check per-session rate limiting (prevent abuse even with valid prompts)
const now = Date.now();
let sessionTracking = sessionRequestTracking.get(sessionId);
if (!sessionTracking || now > sessionTracking.resetTime) {
// Initialize or reset tracking
sessionTracking = {
count: 0,
resetTime: now + (60 * 60 * 1000), // Reset after 1 hour
totalTokens: 0
};
sessionRequestTracking.set(sessionId, sessionTracking);
}
// Check request limit
if (sessionTracking.count >= REQUEST_LIMIT_PER_SESSION) {
console.warn('[Security] Per-session rate limit exceeded:', {
sessionId: sessionId?.substring(0, 10) + '...',
ip: getClientIp(req),
requestCount: sessionTracking.count,
resetTime: new Date(sessionTracking.resetTime).toISOString()
});
return res.status(429).json({
error: `Rate limit exceeded. Maximum ${REQUEST_LIMIT_PER_SESSION} analysis requests per hour.`,
code: 'SESSION_RATE_LIMIT',
resetTime: sessionTracking.resetTime
});
}
// Estimate tokens in request (rough estimate: 1 token ≈ 4 characters)
const requestText = JSON.stringify(contents);
const estimatedInputTokens = Math.ceil(requestText.length / 4);
// Check token limit
if (sessionTracking.totalTokens + estimatedInputTokens > TOKEN_LIMIT_PER_SESSION) {
console.warn('[Security] Per-session token limit exceeded:', {
sessionId: sessionId?.substring(0, 10) + '...',
ip: getClientIp(req),
totalTokens: sessionTracking.totalTokens,
estimatedRequest: estimatedInputTokens
});
return res.status(429).json({
error: 'Token quota exceeded for this session. Please try again later.',
code: 'SESSION_TOKEN_LIMIT',
resetTime: sessionTracking.resetTime
});
}
// SECURITY: Validate that prompt is BSOD-related (prevent API abuse)
const validation = validateBSODPrompt(contents);
if (!validation.valid) {
console.warn('[Security] Non-BSOD prompt blocked:', {
sessionId: sessionId?.substring(0, 10) + '...',
ip: getClientIp(req),
reason: validation.reason,
promptPreview: JSON.stringify(contents).substring(0, 150) + '...'
});
return res.status(400).json({
error: 'Invalid request. This endpoint only analyzes Windows crash dumps and BSOD errors.',
code: 'INVALID_PROMPT'
});
}
// Check cache using fileHash if provided (consistent with WinDBG cache)
const cacheKey = fileHash || hashContent(requestText);
const cachedResponse = await getCachedAIReport(cacheKey);
if (cachedResponse) {
console.log('[Gemini API] Cache HIT for:', fileHash ? `fileHash ${fileHash}` : 'prompt hash');
return res.json({
...cachedResponse,
cached: true
});
}
// Increment request count and token usage
sessionTracking.count++;
sessionTracking.totalTokens += estimatedInputTokens;
// Debug logging
console.log('[Gemini API] Cache MISS, calling Gemini. Contents type:', typeof contents);
if (typeof contents === 'object') {
console.log('[Gemini API] Contents structure:', JSON.stringify(contents).substring(0, 200) + '...');
}
// Always use the model from config file - ignore any client-provided model
const modelName = DEFAULT_MODEL_NAME;
// Extract configuration - frontend sends 'config', SDK expects 'generationConfig'
const frontendConfig = config || generationConfig || {};
// Build proper generationConfig for the SDK
const sdkGenerationConfig = {};
// Handle response_mime_type (correct field name for the SDK)
if (frontendConfig.responseMimeType) {
sdkGenerationConfig.response_mime_type = frontendConfig.responseMimeType;
}
// Handle response_schema (correct field name for the SDK)
if (frontendConfig.responseSchema) {
sdkGenerationConfig.response_schema = frontendConfig.responseSchema;
}
// Handle temperature if provided
if (frontendConfig.temperature !== undefined) {
sdkGenerationConfig.temperature = frontendConfig.temperature;
}
// Handle maxOutputTokens if provided (use snake_case for SDK consistency)
if (frontendConfig.maxOutputTokens !== undefined) {
sdkGenerationConfig.max_output_tokens = frontendConfig.maxOutputTokens;
}
// Handle topK if provided (use snake_case for SDK consistency)
if (frontendConfig.topK !== undefined) {
sdkGenerationConfig.top_k = frontendConfig.topK;
}
// Handle topP if provided (use snake_case for SDK consistency)
if (frontendConfig.topP !== undefined) {
sdkGenerationConfig.top_p = frontendConfig.topP;
}
// Copy any other config properties that might be supported