-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathevidence-collector.js
More file actions
1787 lines (1556 loc) · 60.9 KB
/
evidence-collector.js
File metadata and controls
1787 lines (1556 loc) · 60.9 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
/**
* Evidence Collection System for Hera
*
* This module implements comprehensive evidence collection for vulnerability verification.
* It captures complete request/response data, correlates authentication flows, and
* provides the foundation for evidence-based security testing.
*
* PHASE 1 OIDC ENHANCEMENT:
* - POST body capture with automatic redaction
* - Token request evidence collection
* - PKCE verification support
*
* P1-3 ENHANCEMENT:
* - Batch logging to reduce console spam
*
* P1-2 ENHANCEMENT:
* - Evidence quality indicators with request coverage tracking
* - Finding confidence metrics integration
* - Actionable suggestions for evidence improvement
*/
import { RequestBodyCapturer } from './modules/auth/request-body-capturer.js';
import { BatchLogger } from './modules/utils/batch-logger.js';
import { ConfidenceScorer } from './modules/auth/confidence-scorer.js';
class EvidenceCollector {
constructor() {
// CRITICAL FIX P0: Persistent storage for service worker restarts
this._responseCache = new Map();
this._flowCorrelation = new Map();
this._proofOfConcepts = [];
this._activeFlows = new Map();
this._timeline = [];
this.initialized = false;
this.initPromise = this.initialize();
this.MAX_CACHE_SIZE = 25; // Reduced from 50 - debug mode adds much more data per request
this.MAX_TIMELINE = 100; // Reduced from 500 - timeline events can be very large with debug data
// FIX #1: Per-request size limits to prevent evidence bloat
this.MAX_REQUEST_SIZE = 512000; // 500 KB per request
this.MAX_BODY_SIZE = 100000; // 100 KB for request/response bodies
// SECURITY FIX P2-NEW: Storage schema versioning
this.SCHEMA_VERSION = 1;
// PHASE 1: Initialize request body capturer
this.bodyCapturer = new RequestBodyCapturer();
// P0 FIX: IndexedDB for large evidence persistence
this.db = null;
this.lastSyncTime = null;
this.SYNC_INTERVAL_MS = 60000; // Auto-save every 60 seconds
this.autoSaveTimer = null;
// P1-3: Initialize batch logger to reduce console spam
this.logger = new BatchLogger({
interval: 10000, // Flush logs every 10 seconds
immediate: ['error', 'warn'] // Log errors/warnings immediately
});
}
async initialize() {
if (this.initialized) {return;}
try {
// P0 FIX: Initialize IndexedDB for persistent evidence storage
await this._initIndexedDB();
// Try to restore from IndexedDB first (larger storage)
const evidence = await this._loadFromIndexedDB();
if (evidence) {
if (evidence.responseCache) {
this._responseCache = new Map(Object.entries(evidence.responseCache));
}
if (evidence.flowCorrelation) {
this._flowCorrelation = new Map(Object.entries(evidence.flowCorrelation));
}
this._proofOfConcepts = evidence.proofOfConcepts || [];
this._timeline = evidence.timeline || [];
if (evidence.activeFlows) {
this._activeFlows = new Map(Object.entries(evidence.activeFlows));
}
this.logger.info('init', `Restored ${this._responseCache.size} responses, ${this._timeline.length} events from IndexedDB`);
} else {
// Fallback: Try chrome.storage.local (legacy)
const data = await chrome.storage.local.get(['heraEvidence', 'heraEvidenceSchemaVersion']);
if (data.heraEvidence) {
const legacyEvidence = data.heraEvidence;
if (legacyEvidence.responseCache) {
this._responseCache = new Map(Object.entries(legacyEvidence.responseCache));
}
if (legacyEvidence.flowCorrelation) {
this._flowCorrelation = new Map(Object.entries(legacyEvidence.flowCorrelation));
}
this._proofOfConcepts = legacyEvidence.proofOfConcepts || [];
this._timeline = legacyEvidence.timeline || [];
this.logger.info('init', `Migrated ${this._responseCache.size} responses from chrome.storage.local`);
// Migrate to IndexedDB and clean up old storage
await this._saveToIndexedDB();
await chrome.storage.local.remove(['heraEvidence']);
}
}
// P0 FIX: Start auto-save timer
this._startAutoSave();
this.initialized = true;
} catch (error) {
console.error('Hera: Failed to initialize evidence collector:', error);
this.initialized = true;
}
}
/**
* P0 FIX: Initialize IndexedDB for evidence persistence
*/
async _initIndexedDB() {
// Check if IndexedDB is available (not available in service worker in some contexts)
if (typeof indexedDB === 'undefined') {
console.warn('[Evidence] IndexedDB not available in this context - using fallback storage');
return;
}
return new Promise((resolve, reject) => {
try {
const request = indexedDB.open('HeraEvidence', 1);
request.onerror = () => {
console.warn('[Evidence] IndexedDB initialization failed:', request.error);
resolve(); // Don't reject - fall back to memory-only
};
request.onsuccess = () => {
this.db = request.result;
this.logger.debug('init', 'IndexedDB initialized successfully');
resolve();
};
request.onupgradeneeded = (event) => {
const db = event.target.result;
// Create object store for evidence
if (!db.objectStoreNames.contains('evidence')) {
db.createObjectStore('evidence', { keyPath: 'id' });
}
};
} catch (error) {
console.warn('[Evidence] IndexedDB not available:', error.message);
resolve(); // Don't fail initialization
}
});
}
/**
* P0 FIX: Load evidence from IndexedDB
*/
async _loadFromIndexedDB() {
if (!this.db) {return null;}
try {
return new Promise((resolve, reject) => {
const transaction = this.db.transaction(['evidence'], 'readonly');
const store = transaction.objectStore('evidence');
const request = store.get('current');
request.onsuccess = () => {
resolve(request.result?.data || null);
};
request.onerror = () => {
console.warn('[Evidence] Load from IndexedDB failed:', request.error);
resolve(null); // Don't fail - just return null
};
});
} catch (error) {
console.warn('[Evidence] IndexedDB load error:', error.message);
return null;
}
}
/**
* P0 FIX: Serialize data for IndexedDB (remove non-cloneable objects)
*/
_serializeForStorage(data) {
try {
// Deep clone using JSON (this will fail on non-serializable data)
// but will help us identify the issue
return JSON.parse(JSON.stringify(data, (key, value) => {
// Filter out non-serializable types
if (value instanceof Promise) {
console.warn(`[Evidence] Removed Promise from key: ${key}`);
return undefined;
}
if (typeof value === 'function') {
console.warn(`[Evidence] Removed function from key: ${key}`);
return undefined;
}
if (value instanceof Error) {
// Serialize errors as objects
return {
__error: true,
message: value.message,
name: value.name,
stack: value.stack
};
}
return value;
}));
} catch (error) {
console.error('[Evidence] Serialization failed:', error);
return null;
}
}
/**
* P0 FIX: Save evidence to IndexedDB
*/
async _saveToIndexedDB() {
if (!this.db) {
// No IndexedDB available - skip save (fallback to memory-only)
this.lastSyncTime = Date.now();
return;
}
try {
// Serialize Maps to plain objects
const rawEvidence = {
responseCache: Object.fromEntries(this._responseCache.entries()),
flowCorrelation: Object.fromEntries(this._flowCorrelation.entries()),
proofOfConcepts: this._proofOfConcepts,
timeline: this._timeline,
activeFlows: Object.fromEntries(this._activeFlows.entries())
};
// Clean up non-serializable data
const evidence = this._serializeForStorage(rawEvidence);
if (!evidence) {
console.error('[Evidence] Failed to serialize evidence - skipping save');
this.lastSyncTime = Date.now();
return;
}
return new Promise((resolve, reject) => {
const transaction = this.db.transaction(['evidence'], 'readwrite');
const store = transaction.objectStore('evidence');
const request = store.put({
id: 'current',
data: evidence,
timestamp: Date.now()
});
request.onsuccess = () => {
this.lastSyncTime = Date.now();
this.logger.debug('save', 'Saved to IndexedDB successfully');
resolve();
};
request.onerror = () => {
const errorMsg = request.error?.message || String(request.error);
console.warn('[Evidence] IndexedDB save failed:', errorMsg);
// Log detailed error for debugging
if (errorMsg.includes('DataCloneError')) {
console.error('[Evidence] DataCloneError - evidence contains non-cloneable data');
console.error('[Evidence] Evidence keys:', Object.keys(rawEvidence));
console.error('[Evidence] ResponseCache size:', this._responseCache.size);
console.error('[Evidence] FlowCorrelation size:', this._flowCorrelation.size);
}
this.lastSyncTime = Date.now();
resolve(); // Don't fail - just mark as synced
};
});
} catch (error) {
console.warn('[Evidence] IndexedDB save error:', error.message);
console.error('[Evidence] Full error:', error);
this.lastSyncTime = Date.now();
// Continue without failing
}
}
/**
* P0 FIX: Start auto-save timer
*/
_startAutoSave() {
// Clear existing timer
if (this.autoSaveTimer) {
clearInterval(this.autoSaveTimer);
}
// Auto-save every 60 seconds
this.autoSaveTimer = setInterval(async () => {
try {
await this._saveToIndexedDB();
if (this.db) {
const secondsAgo = Math.floor((Date.now() - this.lastSyncTime) / 1000);
this.logger.debug('auto-save', `Auto-saved (last sync: ${secondsAgo}s ago)`);
}
} catch (error) {
console.warn('[Evidence] Auto-save error:', error.message);
}
}, this.SYNC_INTERVAL_MS);
// Note: visibility change not available in service worker context
// Extension will save on interval and when explicitly called
}
async _syncToStorage() {
try {
await this.initPromise;
// P0-SIXTEENTH-2 FIX: Check quota before writing
const bytesInUse = await chrome.storage.local.getBytesInUse();
const quota = chrome.storage.local.QUOTA_BYTES || 10485760;
const usagePercent = (bytesInUse / quota * 100).toFixed(1);
if (bytesInUse / quota > 0.90) {
console.warn(`Hera: Evidence sync - quota at ${usagePercent}%, cleaning up in-memory cache first`);
// Clean up in-memory data WITHOUT recursive sync call
this._performCleanup();
// Check again after cleanup
const bytesAfter = await chrome.storage.local.getBytesInUse();
const afterPercent = (bytesAfter / quota * 100).toFixed(1);
if (bytesAfter / quota > 0.95) {
console.error(`Hera: Evidence sync aborted - quota still at ${afterPercent}% after cleanup`);
console.error('Hera: Run emergency cleanup in memory-manager or clear storage manually');
return;
}
console.log(`Hera: Evidence cleanup complete, quota now at ${afterPercent}%`);
}
// Build evidence object with already-cleaned in-memory data
// CRITICAL: Strip large fields from responses to prevent storage bloat
const strippedResponseCache = {};
for (const [key, response] of this._responseCache.entries()) {
strippedResponseCache[key] = {
url: response.url,
method: response.method,
statusCode: response.statusCode,
timestamp: response.timestamp,
requestId: response.requestId,
tabId: response.tabId,
// Strip large fields
headers: response.headers ? Object.keys(response.headers).slice(0, 20).reduce((obj, k) => {
obj[k] = response.headers[k];
return obj;
}, {}) : {},
// Keep only first 1000 chars of responseBody
responseBody: response.responseBody ? response.responseBody.substring(0, 1000) + '...' : null,
// Strip HTML snapshots entirely
timing: response.timing,
findings: response.findings || []
};
}
const evidence = {
responseCache: strippedResponseCache,
flowCorrelation: Object.fromEntries(this._flowCorrelation.entries()),
proofOfConcepts: this._proofOfConcepts.slice(-50), // Keep only last 50
timeline: this._timeline.slice(-this.MAX_TIMELINE),
activeFlows: Object.fromEntries(this._activeFlows.entries())
};
// Calculate size before storing
const evidenceSize = JSON.stringify(evidence).length;
const evidenceMB = (evidenceSize / 1024 / 1024).toFixed(2);
// Final check: if evidence itself is >8 MB, it's too big to store
if (evidenceSize > 8388608) { // 8 MB
console.error(`Hera: Evidence object is ${evidenceMB} MB - too large to store!`);
console.error('Hera: Performing aggressive cleanup...');
// Aggressively reduce cache size
this.MAX_CACHE_SIZE = Math.min(10, this.MAX_CACHE_SIZE);
this.MAX_TIMELINE = Math.min(50, this.MAX_TIMELINE);
this._performCleanup();
console.log(`Hera: Reduced MAX_CACHE_SIZE to ${this.MAX_CACHE_SIZE}, MAX_TIMELINE to ${this.MAX_TIMELINE}`);
return; // Don't write this sync, wait for next sync with smaller data
}
// P0 FIX: Now using IndexedDB for persistent storage (no quota limits)
// Don't sync to chrome.storage.local - IndexedDB handles it
const secondsSinceLastSync = this.lastSyncTime
? Math.floor((Date.now() - this.lastSyncTime) / 1000)
: 0;
const syncStatus = this.lastSyncTime
? `✓ Saved ${secondsSinceLastSync}s ago`
: '⏳ Syncing...';
this.logger.info('status', `${this._responseCache.size} responses, ${this._timeline.length} events (${evidenceMB} MB) - ${syncStatus}`);
} catch (error) {
if (error.message?.includes('QUOTA')) {
console.error('Hera: Evidence sync failed - QUOTA_BYTES exceeded');
console.error('Hera: Performing aggressive cleanup...');
// Reduce limits and clean up
this.MAX_CACHE_SIZE = Math.min(5, this.MAX_CACHE_SIZE); // Reduce to 5
this.MAX_TIMELINE = Math.min(25, this.MAX_TIMELINE); // Reduce to 25
this._performCleanup();
console.log(`Hera: Reduced MAX_CACHE_SIZE to ${this.MAX_CACHE_SIZE}, MAX_TIMELINE to ${this.MAX_TIMELINE}`);
// Don't recurse - wait for next sync
} else {
console.error('Hera: Failed to sync evidence:', error);
}
}
}
_performCleanup() {
// IMPORTANT: This is now synchronous and does NOT call _syncToStorage()
// to prevent infinite recursion
let cleaned = false;
if (this._responseCache.size > this.MAX_CACHE_SIZE) {
const beforeSize = this._responseCache.size;
const sorted = Array.from(this._responseCache.entries())
.sort((a, b) => (b[1].timestamp || 0) - (a[1].timestamp || 0));
this._responseCache = new Map(sorted.slice(0, this.MAX_CACHE_SIZE));
console.log(`Hera: Cleaned response cache: ${beforeSize} → ${this._responseCache.size}`);
cleaned = true;
}
if (this._timeline.length > this.MAX_TIMELINE) {
const beforeSize = this._timeline.length;
this._timeline = this._timeline.slice(-this.MAX_TIMELINE);
console.log(`Hera: Cleaned timeline: ${beforeSize} → ${this._timeline.length} events`);
cleaned = true;
}
// Clean up Maps that can grow unbounded
const MAX_FLOW_CORRELATION = 50; // Reduced from 100 - flow objects can be large
if (this._flowCorrelation.size > MAX_FLOW_CORRELATION) {
const beforeSize = this._flowCorrelation.size;
const entries = Array.from(this._flowCorrelation.entries()).slice(-MAX_FLOW_CORRELATION);
this._flowCorrelation = new Map(entries);
console.log(`Hera: Cleaned flow correlation: ${beforeSize} → ${this._flowCorrelation.size}`);
cleaned = true;
}
const MAX_ACTIVE_FLOWS = 25; // Reduced from 50 - active flows include full request data
// P1 FIX #6: Time-based cleanup - remove flows older than 30 minutes
const FLOW_TIMEOUT = 30 * 60 * 1000; // 30 minutes
const now = Date.now();
let expiredFlows = 0;
for (const [key, flow] of this._activeFlows.entries()) {
if (flow.startTime && (now - flow.startTime > FLOW_TIMEOUT)) {
this._activeFlows.delete(key);
expiredFlows++;
}
}
if (expiredFlows > 0) {
console.log(`Hera: Cleaned ${expiredFlows} expired flows (>30min old)`);
cleaned = true;
}
// Size-based cleanup (keep only most recent)
if (this._activeFlows.size > MAX_ACTIVE_FLOWS) {
const beforeSize = this._activeFlows.size;
const entries = Array.from(this._activeFlows.entries()).slice(-MAX_ACTIVE_FLOWS);
this._activeFlows = new Map(entries);
console.log(`Hera: Cleaned active flows: ${beforeSize} → ${this._activeFlows.size}`);
cleaned = true;
}
if (this._proofOfConcepts.length > 25) { // Reduced from 50 - POCs can be large
const beforeSize = this._proofOfConcepts.length;
this._proofOfConcepts = this._proofOfConcepts.slice(-25);
console.log(`Hera: Cleaned POCs: ${beforeSize} → ${this._proofOfConcepts.length}`);
cleaned = true;
}
if (!cleaned) {
console.log('Hera: Evidence cleanup - no action needed (within limits)');
}
// DO NOT call _syncToStorage() here - that creates infinite recursion!
}
_debouncedSync() {
// P0 FIX: Save to IndexedDB (persistent, no quota limits)
// Debounced to avoid excessive writes on high-traffic sites
if (this._syncTimeout) {clearTimeout(this._syncTimeout);}
this._syncTimeout = setTimeout(async () => {
try {
await this._saveToIndexedDB();
// Also update the console log
await this._syncToStorage();
} catch (err) {
console.error('[Evidence] Sync failed:', err.message);
// Additional debug info for common errors
if (err.name === 'DataCloneError') {
console.error('[Evidence] DataCloneError - evidence contains non-serializable data (Promise, Function, etc.)');
console.error('[Evidence] Check what is being stored in responseCache or flowCorrelation');
}
}
}, 1000); // 1 second debounce
}
// Getters for backward compatibility
get responseCache() { return this._responseCache; }
get flowCorrelation() { return this._flowCorrelation; }
get proofOfConcepts() { return this._proofOfConcepts; }
get activeFlows() { return this._activeFlows; }
get timeline() { return this._timeline; }
/**
* Capture complete response data with evidence analysis
* @param {string} requestId - Unique identifier for the request
* @param {Array} responseHeaders - Response headers array
* @param {string} responseBody - Response body content
* @param {number} statusCode - HTTP status code
* @param {Object} requestData - Original request data for correlation
* @returns {Object} Evidence package
*/
/**
* FIX #1: Truncate large request/response data to prevent evidence bloat
*
* Strategy:
* 1. Check total size before adding to cache
* 2. If > 500 KB, truncate bodies to 100 KB
* 3. If still > 500 KB, strip bodies entirely and keep metadata
*/
_truncateEvidence(evidence) {
const evidenceSize = JSON.stringify(evidence).length;
// If under limit, return as-is
if (evidenceSize <= this.MAX_REQUEST_SIZE) {
return evidence;
}
console.warn(`[Evidence] Request ${evidence.requestId} exceeds ${(this.MAX_REQUEST_SIZE/1024).toFixed(0)} KB (${(evidenceSize/1024).toFixed(0)} KB), truncating...`);
const truncated = JSON.parse(JSON.stringify(evidence)); // Deep clone
// Step 1: Truncate response body
if (truncated.body && typeof truncated.body === 'string' && truncated.body.length > this.MAX_BODY_SIZE) {
const originalSize = truncated.body.length;
truncated.body = truncated.body.substring(0, this.MAX_BODY_SIZE) +
`\n\n[TRUNCATED - original size: ${originalSize} bytes]`;
this.logger.debug('truncate', `Response body truncated: ${originalSize} → ${this.MAX_BODY_SIZE} bytes`);
}
// Step 2: Truncate request body if present
if (truncated.requestData?.requestBody && truncated.requestData.requestBody.length > this.MAX_BODY_SIZE) {
const originalSize = truncated.requestData.requestBody.length;
truncated.requestData.requestBody = truncated.requestData.requestBody.substring(0, this.MAX_BODY_SIZE) +
`\n\n[TRUNCATED - original size: ${originalSize} bytes]`;
this.logger.debug('truncate', `Request body truncated: ${originalSize} → ${this.MAX_BODY_SIZE} bytes`);
}
// Step 3: Check size again after truncation
const newSize = JSON.stringify(truncated).length;
if (newSize > this.MAX_REQUEST_SIZE) {
console.warn(`[Evidence] Request still too large after truncation: ${(newSize/1024).toFixed(0)} KB, stripping bodies entirely`);
// Last resort: Keep metadata only
delete truncated.body;
if (truncated.requestData) {
delete truncated.requestData.requestBody;
delete truncated.requestData.responseBody;
}
truncated.truncated = true;
truncated.truncationReason = 'Exceeded 500 KB limit after body truncation';
}
return truncated;
}
captureResponse(requestId, responseHeaders, responseBody, statusCode, requestData = null) {
const timestamp = Date.now();
const requestUrl = requestData?.url || null;
// P0 FIX: Truncate response body BEFORE creating evidence object
// This prevents memory bloat from analyzing large bodies
let truncatedBody = responseBody;
if (responseBody && typeof responseBody === 'string' && responseBody.length > this.MAX_BODY_SIZE) {
const originalSize = responseBody.length;
truncatedBody = responseBody.substring(0, this.MAX_BODY_SIZE) +
`\n\n[TRUNCATED - original size: ${originalSize} bytes]`;
this.logger.debug('truncate', `Pre-truncated response body: ${originalSize} → ${this.MAX_BODY_SIZE} bytes`);
}
// Truncate request body if present
let truncatedRequestData = requestData;
if (requestData?.requestBody && requestData.requestBody.length > this.MAX_BODY_SIZE) {
const originalSize = requestData.requestBody.length;
truncatedRequestData = {
...requestData,
requestBody: requestData.requestBody.substring(0, this.MAX_BODY_SIZE) +
`\n\n[TRUNCATED - original size: ${originalSize} bytes]`
};
this.logger.debug('truncate', `Pre-truncated request body: ${originalSize} → ${this.MAX_BODY_SIZE} bytes`);
}
let evidence = {
requestId,
timestamp,
headers: responseHeaders || [],
body: truncatedBody, // Use pre-truncated body
statusCode,
requestData: truncatedRequestData, // Use pre-truncated request data
evidence: {
hstsPresent: this.checkHSTSHeader(responseHeaders, requestUrl),
securityHeaders: this.analyzeSecurityHeaders(responseHeaders),
cookieFlags: this.analyzeCookies(responseHeaders),
contentType: this.extractContentType(responseHeaders),
cacheControl: this.extractCacheControl(responseHeaders)
},
analysis: {
vulnerabilities: this.analyzeForVulnerabilities(responseHeaders, truncatedBody, statusCode), // Use truncated body
flowContext: this.correlateWithFlow(requestId, requestData)
}
};
// FIX #1: Final size check - truncate entire evidence if still too large
evidence = this._truncateEvidence(evidence);
// Store in cache for correlation
this.responseCache.set(requestId, evidence);
// Add to timeline
this.timeline.push({
timestamp,
requestId,
type: 'response_captured',
url: requestData?.url,
method: requestData?.method
});
// CRITICAL FIX: Persist to storage.session
this._debouncedSync();
return evidence;
}
/**
* P0-A: Process response body captured by ResponseBodyCapturer
*
* PURPOSE:
* - Analyze response bodies for security findings
* - Detect DPoP token type
* - Detect WebAuthn/FIDO2 challenges
* - Detect TOTP/OTP codes
* - Detect session tokens
*
* CRITICAL FIX: Now accepts authRequests Map to avoid responseCache mismatch
*
* @param {string} requestId - Request ID to correlate with
* @param {Object|string} responseBody - Response body (may be redacted)
* @param {string} url - Request URL for context
* @param {Map} authRequests - Reference to authRequests Map (passed from ResponseBodyCapturer)
*/
processResponseBody(requestId, responseBody, url, authRequests = null) {
// CRITICAL FIX: Use authRequests if provided, otherwise fall back to responseCache
const requestsMap = authRequests || this.responseCache;
// Get existing evidence for this request
const existingEvidence = requestsMap.get(requestId);
if (!existingEvidence) {
console.warn(`[Evidence] No existing evidence for request ${requestId}`);
return;
}
// Parse response body if it's a string
let parsedBody = responseBody;
if (typeof responseBody === 'string') {
try {
parsedBody = JSON.parse(responseBody);
} catch (error) {
// Not JSON, skip analysis
return;
}
}
// Analyze response body for security findings
const findings = [];
// P1-5: DPoP Detection
if (parsedBody.token_type) {
const tokenType = parsedBody.token_type.toLowerCase();
if (tokenType === 'dpop') {
findings.push({
type: 'DPOP_DETECTED',
severity: 'INFO',
confidence: 'HIGH',
message: 'DPoP token type detected - tokens are sender-constrained',
evidence: {
token_type: parsedBody.token_type,
url,
note: 'RFC 9449: DPoP provides proof-of-possession for OAuth 2.0 tokens'
},
references: ['RFC 9449: OAuth 2.0 Demonstrating Proof-of-Possession']
});
} else if (tokenType === 'bearer') {
// Only report if this is a public client (higher risk)
findings.push({
type: 'BEARER_TOKEN_USED',
severity: 'INFO',
confidence: 'HIGH',
message: 'Bearer token type detected - tokens are not sender-constrained',
evidence: {
token_type: parsedBody.token_type,
url,
note: 'Consider upgrading to DPoP for enhanced security (RFC 9449)'
},
references: ['RFC 9449: OAuth 2.0 Demonstrating Proof-of-Possession']
});
}
}
// P2-7: WebAuthn Challenge Detection
if (parsedBody.publicKey && parsedBody.publicKey.challenge) {
findings.push({
type: 'WEBAUTHN_CHALLENGE_DETECTED',
severity: 'INFO',
confidence: 'HIGH',
message: 'WebAuthn authentication challenge detected',
evidence: {
rpId: parsedBody.publicKey.rpId,
timeout: parsedBody.publicKey.timeout,
userVerification: parsedBody.publicKey.userVerification,
url,
note: 'WebAuthn/FIDO2 provides phishing-resistant MFA'
},
references: ['W3C WebAuthn Level 2', 'FIDO2: Web Authentication']
});
}
// P2-7: Session Token Detection
if (parsedBody.session_token || parsedBody.sessionToken) {
findings.push({
type: 'SESSION_TOKEN_IN_RESPONSE',
severity: 'INFO',
confidence: 'MEDIUM',
message: 'Session token detected in response body',
evidence: {
url,
note: 'Verify session token is also set as HttpOnly cookie for CSRF protection'
}
});
}
// Add findings to evidence
if (findings.length > 0) {
if (!existingEvidence.metadata) {
existingEvidence.metadata = {};
}
if (!existingEvidence.metadata.responseBodyFindings) {
existingEvidence.metadata.responseBodyFindings = [];
}
existingEvidence.metadata.responseBodyFindings.push(...findings);
// CRITICAL FIX: Update the correct Map
requestsMap.set(requestId, existingEvidence);
this.logger.debug('findings', `Found ${findings.length} security findings in response body`, { url, count: findings.length });
}
}
/**
* Capture complete request data for flow correlation
* @param {string} requestId - Unique identifier for the request
* @param {Object} requestDetails - Complete request details
* @returns {Object} Request evidence package
*/
captureRequest(requestId, requestDetails) {
const timestamp = Date.now();
const evidence = {
requestId,
timestamp,
url: requestDetails.url,
method: requestDetails.method,
headers: requestDetails.requestHeaders || [],
body: requestDetails.requestBody,
type: requestDetails.type,
analysis: {
authFlow: this.analyzeAuthFlow(requestDetails),
oauth2Flow: this.analyzeOAuth2Flow(requestDetails),
credentials: this.analyzeCredentials(requestDetails),
crossOrigin: this.analyzeCrossOrigin(requestDetails)
}
};
// PHASE 1: Capture POST body for OAuth2/OIDC token requests with redaction
if (requestDetails.method === 'POST' && requestDetails.requestBody) {
try {
const bodyEvidence = this.bodyCapturer.captureRequestBody(requestDetails);
evidence.bodyEvidence = bodyEvidence;
// Add any vulnerabilities found during body analysis
if (bodyEvidence.security?.vulnerabilities?.length > 0) {
evidence.vulnerabilities = bodyEvidence.security.vulnerabilities;
}
} catch (error) {
console.warn('Hera: Failed to capture request body:', error);
}
}
// Correlate with active flows
this.correlateFlow(requestId, evidence);
// Add to timeline
this.timeline.push({
timestamp,
requestId,
type: 'request_captured',
url: requestDetails.url,
method: requestDetails.method
});
// CRITICAL FIX: Persist to storage.session
this._debouncedSync();
return evidence;
}
/**
* Check for HSTS header presence and configuration
* PHASE 6 ENHANCEMENT: Now includes preload list checking with fact-based reporting
* @param {Array} headers - Response headers
* @param {string} url - Request URL to verify HTTPS usage
* @returns {Object} HSTS analysis with preload check
*/
checkHSTSHeader(headers, url = null) {
if (!headers) {return { present: false, reason: 'no_headers' };}
// CRITICAL: HSTS is meaningless on HTTP connections
let isHTTPS = true;
let domain = null;
if (url) {
try {
const urlObj = new URL(url);
isHTTPS = urlObj.protocol === 'https:';
domain = urlObj.hostname;
} catch (e) {
// Invalid URL, assume HTTP for safety
isHTTPS = false;
}
}
const hstsHeader = headers.find(h =>
h.name.toLowerCase() === 'strict-transport-security'
);
// ADVERSARIAL DECISION: Do NOT check preload list
// Per CLAUDE.md ADVERSARIAL_PUSHBACK.md:
// - Preload list status varies by browser and version
// - Cannot verify what THIS USER'S BROWSER knows
// - Adds complexity without certainty
// - Report facts we can verify, not guesses
//
// What Hera does instead: Report header presence/absence with verification URL
if (!hstsHeader) {
return {
present: false,
reason: 'header_missing',
isHTTPS: isHTTPS,
warning: !isHTTPS ? 'Connection not using HTTPS - HSTS not applicable' : null,
evidence: headers.map(h => ({ name: h.name, value: h.value })),
// FACT-BASED recommendation (not speculation)
recommendation: domain ?
`Add HSTS header. Check preload status: https://hstspreload.org/?domain=${domain}` :
'Add HSTS header: Strict-Transport-Security: max-age=31536000; includeSubDomains; preload'
};
}
// HSTS header on HTTP connection is suspicious (should be stripped by browsers)
if (!isHTTPS) {
return {
present: true,
isHTTPS: false,
warning: 'CRITICAL: HSTS header sent over HTTP - potential security misconfiguration',
value: hstsHeader.value,
evidence: { name: hstsHeader.name, value: hstsHeader.value, protocol: 'HTTP' }
};
}
// Parse HSTS directive
const value = hstsHeader.value;
const maxAgeMatch = value.match(/max-age=(\d+)/i);
const includeSubDomains = /includeSubDomains/i.test(value);
const preload = /preload/i.test(value);
return {
present: true,
isHTTPS: true,
value: value,
maxAge: maxAgeMatch ? parseInt(maxAgeMatch[1]) : null,
includeSubDomains,
preload,
analysis: {
maxAgeAppropriate: maxAgeMatch && parseInt(maxAgeMatch[1]) >= 31536000, // 1 year
hasSubDomains: includeSubDomains,
preloadReady: preload
},
evidence: { name: hstsHeader.name, value: hstsHeader.value, protocol: 'HTTPS' },
// Manual preload check URL (not automated to avoid CSP issues)
manualPreloadCheckUrl: domain ? `https://hstspreload.org/?domain=${domain}` : null
};
}
/**
* Analyze security headers for evidence collection
* @param {Array} headers - Response headers
* @returns {Object} Security headers analysis
*/
analyzeSecurityHeaders(headers) {
if (!headers) {return { count: 0, headers: [], missing: [] };}
const securityHeaders = {
'strict-transport-security': null,
'content-security-policy': null,
'x-frame-options': null,
'x-content-type-options': null,
'referrer-policy': null,
'permissions-policy': null,
'x-xss-protection': null
};
const found = [];
const missing = [];
// Check for each security header
for (const headerName of Object.keys(securityHeaders)) {
const header = headers.find(h => h.name.toLowerCase() === headerName);
if (header) {
securityHeaders[headerName] = header.value;
found.push({ name: header.name, value: header.value });
} else {
missing.push(headerName);
}
}
return {
count: found.length,
headers: found,
missing,
analysis: {
score: this.calculateSecurityHeaderScore(found, missing),
recommendations: this.generateSecurityHeaderRecommendations(missing)
},
evidence: headers.map(h => ({ name: h.name, value: h.value }))
};
}
/**
* Analyze cookie security flags
* @param {Array} headers - Response headers
* @returns {Object} Cookie security analysis
*/
analyzeCookies(headers) {
if (!headers) {return { cookies: [], vulnerabilities: [] };}
const setCookieHeaders = headers.filter(h =>
h.name.toLowerCase() === 'set-cookie'
);
const analysis = {
cookies: [],
vulnerabilities: [],
evidence: setCookieHeaders
};
for (const cookieHeader of setCookieHeaders) {
const cookie = this.parseCookie(cookieHeader.value);
analysis.cookies.push(cookie);
// Check for security issues
if (!cookie.httpOnly) {
analysis.vulnerabilities.push({
type: 'missing_httponly',
cookie: cookie.name,
severity: 'MEDIUM',
evidence: cookieHeader.value
});
}
if (!cookie.secure) {
analysis.vulnerabilities.push({
type: 'missing_secure',
cookie: cookie.name,
severity: 'HIGH',
evidence: cookieHeader.value
});
}