-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcontent-script.js.backup
More file actions
1571 lines (1337 loc) · 54.9 KB
/
content-script.js.backup
File metadata and controls
1571 lines (1337 loc) · 54.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
// Hera Content Script - Form Protection & Real-time Warnings
// Prevents users from submitting data to insecure backends
// CRITICAL FIX P0-1: Chrome MV3 does NOT support static ES6 imports in content scripts
// Using dynamic imports instead (supported in content scripts)
// Note: Static imports work in background.js but NOT here due to injection mechanism
// CODE QUALITY FIX P3-1: Conditional debug logging
const DEBUG = false; // Set to true for development
function debug(...args) {
if (DEBUG) console.log('[Hera Debug]', ...args);
}
// PERFORMANCE FIX P2-2: Shadow DOM support for detectors
function querySelectorAllDeep(selector, root = document) {
const elements = [];
// Query regular DOM
elements.push(...root.querySelectorAll(selector));
// Query shadow roots recursively
const allElements = root.querySelectorAll('*');
for (const element of allElements) {
if (element.shadowRoot) {
elements.push(...querySelectorAllDeep(selector, element.shadowRoot));
}
}
return elements;
}
// Expose helper for detectors to use
window.__heraQuerySelectorAllDeep = querySelectorAllDeep;
let detectorsLoaded = false;
let detectors = null;
let loadingPromise = null; // CRITICAL FIX NEW-P0-2: Mutex for concurrent loading
// CRITICAL FIX P0-5 & NEW-P1-1: Fallback stub detectors with clear error indication
function createStubDetectors() {
console.error('Hera: CRITICAL - Using stub detectors, full analysis unavailable');
console.error('Hera: This page may be blocking the extension with CSP or module loading failed');
// Create a critical error finding that will be shown to the user
const errorFinding = {
type: 'analysis_error',
category: 'extension_blocked',
severity: 'critical',
title: '⚠️ Security Analysis Unavailable',
description: 'This page is blocking Hera\'s security analysis, possibly through Content Security Policy (CSP) restrictions. The extension cannot verify if this site is safe.',
recommendation: 'Exercise extreme caution. Do not enter sensitive information unless you trust this site from other sources.',
evidence: {
reason: 'Detector modules failed to load - CSP blocking or module error',
extensionId: chrome.runtime.id
},
timestamp: new Date().toISOString()
};
return {
darkPatternDetector: {
detectPatterns: async () => {
console.warn('Hera: Dark pattern detector unavailable (stub)');
return [errorFinding];
}
},
phishingDetector: {
detectPhishing: async () => {
console.warn('Hera: Phishing detector unavailable (stub)');
return [];
}
},
privacyViolationDetector: {
detectViolations: async () => {
console.warn('Hera: Privacy detector unavailable (stub)');
return [];
}
},
riskScoringEngine: {
calculateRiskScore: (findings) => {
console.warn('Hera: Risk scoring unavailable (stub)');
// Return FAILING grade to alert user
return {
overallScore: 0,
grade: 'F',
riskLevel: 'CRITICAL',
criticalIssues: findings.filter(f => f.severity === 'critical').length || 1,
warnings: 0,
info: 0,
breakdown: { security: 0, privacy: 0, ux: 0 },
message: '⚠️ ANALYSIS BLOCKED - Cannot verify site safety due to restrictions. Proceed with extreme caution.',
analysisMode: 'stub',
analysisBlocked: true
};
}
}
};
}
// CRITICAL FIX NEW-P2-2: Create stub for individual detector
function createStubDetector(name, method) {
return {
[method]: async () => {
console.warn(`Hera: ${name} unavailable (stub)`);
return [];
}
};
}
async function loadDetectors() {
// CRITICAL FIX P0-1: Detectors loaded via manifest content_scripts (no dynamic imports)
// This fixes CSP issues on GitHub, Gmail, banking sites, etc.
if (detectorsLoaded && detectors) {
return detectors;
}
// Wait for detectors to be available (they load before content-script.js in manifest)
const maxWait = 50; // 50 * 100ms = 5 seconds max
let attempts = 0;
while (attempts < maxWait) {
if (window.HeraSubdomainImpersonationDetector &&
window.subdomainImpersonationDetector &&
window.darkPatternDetector &&
window.phishingDetector &&
window.privacyViolationDetector &&
window.riskScoringEngine) {
// All detectors loaded successfully!
detectors = {
subdomainImpersonationDetector: window.subdomainImpersonationDetector,
darkPatternDetector: window.darkPatternDetector,
phishingDetector: window.phishingDetector,
privacyViolationDetector: window.privacyViolationDetector,
riskScoringEngine: window.riskScoringEngine
};
detectorsLoaded = true;
console.log('Hera: All 5 detectors loaded from manifest (CSP-safe, no dynamic imports)');
return detectors;
}
// Wait a bit for scripts to load
await new Promise(resolve => setTimeout(resolve, 100));
attempts++;
}
// Fallback to stubs if detectors didn't load within timeout
console.error('Hera: Detectors failed to load from manifest within 5s, using stubs');
const stubDetectors = createStubDetectors();
detectors = stubDetectors;
detectorsLoaded = true;
return stubDetectors;
}
// SECURITY FIX P1-1: Request isolated world injection from background script
// This prevents malicious pages from intercepting or poisoning the response data
(function requestInterceptorInjection() {
// Generate unique nonce for this page
const injectionNonce = crypto.randomUUID ? crypto.randomUUID() : Math.random().toString(36).substring(2);
window.__HERA_INJECTION_NONCE__ = injectionNonce;
// Request background script to inject interceptor in isolated world
// P1-SIXTEENTH-1 FIX: CSP failures are expected on many sites - don't log errors
chrome.runtime.sendMessage({
type: 'INJECT_RESPONSE_INTERCEPTOR',
nonce: injectionNonce,
tabId: null // Background will use sender.tab.id
}).then(response => {
if (response?.success) {
if (DEBUG) console.log('Hera: Response interceptor injected in isolated world');
} else {
// P1-SIXTEENTH-1 FIX: Downgrade to debug log - CSP blocking is normal and expected
if (DEBUG && response?.error) {
console.log('Hera: Response interceptor not injected:', response.error);
}
}
}).catch(error => {
// P1-SIXTEENTH-1 FIX: Only log if DEBUG enabled - CSP errors are expected
if (DEBUG) console.log('Hera: Error requesting interceptor injection:', error.message);
});
})();
// SECURITY FIX P1-1: Nonce tracking no longer needed
// Response interceptor runs in isolated world and sends directly to background
// No need for replay attack prevention since messages don't go through postMessage
// SECURITY FIX P1-1: Removed window.addEventListener for postMessage
// Response interceptor now runs in ISOLATED world and sends directly to background
// via chrome.runtime.sendMessage, so we no longer need to:
// 1. Listen for window.postMessage events
// 2. Validate nonces (isolated world is inherently secure)
// 3. Check for replay attacks (no cross-context messaging)
// 4. Forward messages to background (interceptor sends directly)
console.log('Hera: Response interception uses isolated world injection (no postMessage relay needed)');
class HeraFormProtector {
constructor() {
this.domain = window.location.hostname;
this.backendScanResults = null;
this.blockedSubmissions = 0;
this.currentAlert = null;
this.alertQueue = [];
this.init();
this.injectBrandedAlertStyles();
}
// Sanitize HTML to prevent XSS from backend scan results
sanitizeHTML(str) {
if (typeof str !== 'string') return '';
const div = document.createElement('div');
div.textContent = str; // This escapes HTML entities
return div.innerHTML;
}
async init() {
// Get backend scan results from background script
this.backendScanResults = await this.getBackendScanResults();
// Set up form monitoring
this.setupFormMonitoring();
// Show immediate warnings if critical issues found
if (this.backendScanResults?.shouldBlockDataEntry) {
this.showPageWarning();
}
}
async getBackendScanResults() {
return new Promise((resolve) => {
chrome.runtime.sendMessage({
action: 'getBackendScan',
domain: this.domain
}, (response) => {
resolve(response);
});
});
}
setupFormMonitoring() {
// Monitor all form submissions
document.addEventListener('submit', (e) => {
this.handleFormSubmission(e);
}, true);
// Monitor password fields for real-time warnings
document.addEventListener('input', (e) => {
if (e.target.type === 'password' || e.target.name?.toLowerCase().includes('password')) {
this.handlePasswordInput(e.target);
}
});
// Monitor for dynamically added forms
const observer = new MutationObserver((mutations) => {
mutations.forEach((mutation) => {
mutation.addedNodes.forEach((node) => {
if (node.nodeType === Node.ELEMENT_NODE) {
const forms = node.querySelectorAll ? node.querySelectorAll('form') : [];
forms.forEach(form => this.monitorForm(form));
}
});
});
});
observer.observe(document.body, { childList: true, subtree: true });
// Monitor existing forms
document.querySelectorAll('form').forEach(form => this.monitorForm(form));
}
handleFormSubmission(e) {
const form = e.target;
// Check if this form contains sensitive data
const hasSensitiveData = this.containsSensitiveData(form);
if (hasSensitiveData && this.backendScanResults?.shouldBlockDataEntry) {
e.preventDefault();
e.stopPropagation();
this.showCriticalFormWarning(form);
this.blockedSubmissions++;
// Report blocked submission
chrome.runtime.sendMessage({
action: 'reportBlockedSubmission',
domain: this.domain,
exposures: this.backendScanResults.exposed
});
return false;
}
// Show warning for high-risk but not critical
if (hasSensitiveData && this.backendScanResults?.riskScore > 50) {
const userChoice = this.showRiskWarning(form);
if (!userChoice) {
e.preventDefault();
return false;
}
}
}
containsSensitiveData(form) {
const sensitiveFields = [
'input[type="password"]',
'input[type="email"]',
'input[name*="password"]',
'input[name*="email"]',
'input[name*="phone"]',
'input[name*="credit"]',
'input[name*="card"]',
'input[name*="ssn"]',
'input[name*="social"]',
'input[name*="address"]',
'textarea[name*="message"]',
'textarea[name*="comment"]'
];
return sensitiveFields.some(selector => form.querySelector(selector));
}
showCriticalFormWarning(form) {
// Remove any existing warnings
const existingWarning = form.querySelector('.hera-form-warning');
if (existingWarning) existingWarning.remove();
// Create warning element
const warning = document.createElement('div');
warning.className = 'hera-form-warning critical';
warning.style.cssText = `
position: relative;
background: linear-gradient(135deg, #ff4444, #cc0000);
color: white;
padding: 20px;
border-radius: 8px;
margin: 15px 0;
font-family: -apple-system, BlinkMacSystemFont, sans-serif;
font-size: 14px;
box-shadow: 0 4px 12px rgba(255, 0, 0, 0.3);
border: 2px solid #ff0000;
z-index: 10000;
`;
const criticalExposures = this.backendScanResults.exposed.filter(e => e.severity === 'critical');
// Build DOM safely without innerHTML
const container = document.createElement('div');
container.style.cssText = 'display: flex; align-items: center; gap: 15px;';
const iconDiv = document.createElement('div');
iconDiv.style.fontSize = '48px';
iconDiv.textContent = '';
const contentDiv = document.createElement('div');
contentDiv.style.flex = '1';
const heading = document.createElement('h3');
heading.style.cssText = 'margin: 0 0 10px 0; font-size: 18px;';
heading.textContent = 'FORM SUBMISSION BLOCKED';
const description = document.createElement('div');
description.style.marginBottom = '15px';
// SECURITY FIX: Use textContent to prevent XSS
const descText = document.createTextNode('This website has ');
const strongCount = document.createElement('strong');
strongCount.textContent = `${criticalExposures.length} critical security vulnerabilities`;
const descText2 = document.createTextNode(' that could expose your data:');
description.appendChild(descText);
description.appendChild(strongCount);
description.appendChild(descText2);
const exposuresDiv = document.createElement('div');
exposuresDiv.style.cssText = 'background: rgba(255,255,255,0.1); padding: 12px; border-radius: 4px; margin: 10px 0;';
criticalExposures.forEach(exp => {
const expDiv = document.createElement('div');
expDiv.style.marginBottom = '8px';
// SECURITY FIX: Use DOM methods instead of innerHTML
expDiv.textContent = `• `;
const strong = document.createElement('strong');
strong.textContent = exp.type.toUpperCase() + ':';
expDiv.appendChild(strong);
const details = document.createTextNode(' ' + exp.details);
expDiv.appendChild(details);
exposuresDiv.appendChild(expDiv);
});
const warningText = document.createElement('div');
warningText.style.cssText = 'font-weight: bold; font-size: 16px;';
warningText.textContent = '⛔ Your data would be stored insecurely and could be stolen!';
contentDiv.appendChild(heading);
contentDiv.appendChild(description);
contentDiv.appendChild(exposuresDiv);
contentDiv.appendChild(warningText);
container.appendChild(iconDiv);
container.appendChild(contentDiv);
const buttonsDiv = document.createElement('div');
buttonsDiv.style.cssText = 'margin-top: 20px; display: flex; gap: 10px; justify-content: center;';
const understoodBtn = document.createElement('button');
understoodBtn.style.cssText = 'background: white; color: #cc0000; border: none; padding: 10px 20px; border-radius: 4px; font-weight: bold; cursor: pointer;';
understoodBtn.textContent = 'Understood';
understoodBtn.onclick = () => warning.remove();
const detailsBtn = document.createElement('button');
detailsBtn.style.cssText = 'background: transparent; color: white; border: 2px solid white; padding: 10px 20px; border-radius: 4px; cursor: pointer;';
detailsBtn.textContent = 'Technical Details';
detailsBtn.onclick = () => window.hera.showTechnicalDetails();
buttonsDiv.appendChild(understoodBtn);
buttonsDiv.appendChild(detailsBtn);
warning.appendChild(container);
warning.appendChild(buttonsDiv);
// Insert warning above the form
form.parentNode.insertBefore(warning, form);
// Disable form inputs
const inputs = form.querySelectorAll('input, textarea, select, button');
inputs.forEach(input => {
input.style.opacity = '0.5';
input.style.pointerEvents = 'none';
input.disabled = true;
});
}
// SECURITY FIX P0: Use DOM elements instead of HTML strings
showPageWarning() {
// Use SADS analysis if available
if (this.backendScanResults.sadsAnalysis) {
const sads = this.backendScanResults.sadsAnalysis;
const detailsDOM = this.formatSADSAlertDOM(sads);
// Add authentication analysis if available
if (this.backendScanResults.authAnalysis && this.backendScanResults.authAnalysis.riskScore > 30) {
detailsDOM.appendChild(document.createElement('br'));
const hr = document.createElement('hr');
hr.style.cssText = 'border-top: 1px solid #444; margin: 15px 0;';
detailsDOM.appendChild(hr);
detailsDOM.appendChild(document.createElement('br'));
detailsDOM.appendChild(this.formatAuthAnalysisDOM(this.backendScanResults.authAnalysis));
}
const alertData = {
title: `${sads.recommendation.icon} ${sads.sScore.category} Risk Detected`,
detailsDOM: detailsDOM, // Pass DOM element
severity: sads.sScore.category.toLowerCase(),
verification: sads.anomalies[0]?.verification || null
};
this.showBrandedAlert(alertData);
} else {
// Fallback to rule-based alerts
const criticalExposures = this.backendScanResults.exposed.filter(e => e.severity === 'critical');
const detailsDOM = document.createElement('div');
detailsDOM.appendChild(document.createTextNode(`Hera detected ${criticalExposures.length} critical security vulnerabilities on this website that could expose your data:`));
detailsDOM.appendChild(document.createElement('br'));
detailsDOM.appendChild(document.createElement('br'));
criticalExposures.forEach(exp => {
detailsDOM.appendChild(document.createTextNode('• '));
const typeStrong = document.createElement('strong');
typeStrong.textContent = exp.type.toUpperCase() + ':';
detailsDOM.appendChild(typeStrong);
detailsDOM.appendChild(document.createTextNode(' ' + exp.details));
detailsDOM.appendChild(document.createElement('br'));
});
detailsDOM.appendChild(document.createElement('br'));
const warning = document.createElement('strong');
warning.textContent = '⛔ Avoid entering personal information on this site!';
detailsDOM.appendChild(warning);
// Add authentication analysis if available
if (this.backendScanResults.authAnalysis && this.backendScanResults.authAnalysis.riskScore > 30) {
detailsDOM.appendChild(document.createElement('br'));
const hr = document.createElement('hr');
hr.style.cssText = 'border-top: 1px solid #444; margin: 15px 0;';
detailsDOM.appendChild(hr);
detailsDOM.appendChild(document.createElement('br'));
detailsDOM.appendChild(this.formatAuthAnalysisDOM(this.backendScanResults.authAnalysis));
}
const alertData = {
title: 'Critical Security Warning',
detailsDOM: detailsDOM, // Pass DOM element
severity: 'critical',
verification: criticalExposures[0]?.verification || null
};
this.showBrandedAlert(alertData);
}
}
// SECURITY FIX P0: Build DOM elements instead of HTML strings to prevent XSS
formatSADSAlertDOM(sadsAnalysis) {
const container = document.createElement('div');
// S-Score
const scoreStrong = document.createElement('strong');
scoreStrong.textContent = `S-Score: ${sadsAnalysis.sScore.normalized}/100`;
container.appendChild(scoreStrong);
container.appendChild(document.createElement('br'));
// Site Type
const siteType = document.createTextNode(`Site Type: ${sadsAnalysis.websiteType}`);
container.appendChild(siteType);
container.appendChild(document.createElement('br'));
container.appendChild(document.createElement('br'));
// Recommendation
const recStrong = document.createElement('strong');
recStrong.textContent = sadsAnalysis.recommendation.message;
container.appendChild(recStrong);
container.appendChild(document.createElement('br'));
container.appendChild(document.createElement('br'));
// Top surprise factors
const topSurprises = Object.entries(sadsAnalysis.surpriseScores)
.sort((a, b) => b[1] - a[1])
.slice(0, 3);
if (topSurprises.length > 0) {
const surpriseHeading = document.createElement('strong');
surpriseHeading.textContent = 'Unusual characteristics:';
container.appendChild(surpriseHeading);
container.appendChild(document.createElement('br'));
topSurprises.forEach(([factor, score]) => {
const item = document.createTextNode(`• ${this.humanizeFactor(factor)}: ${score.toFixed(1)}x unexpected`);
container.appendChild(item);
container.appendChild(document.createElement('br'));
});
container.appendChild(document.createElement('br'));
}
// Anomaly patterns
if (sadsAnalysis.anomalies.length > 0) {
const anomalyHeading = document.createElement('strong');
anomalyHeading.textContent = 'Patterns detected:';
container.appendChild(anomalyHeading);
container.appendChild(document.createElement('br'));
sadsAnalysis.anomalies.forEach(anomaly => {
const item = document.createTextNode(`• ${anomaly.description} (${Math.round(anomaly.confidence * 100)}% confidence)`);
container.appendChild(item);
container.appendChild(document.createElement('br'));
});
container.appendChild(document.createElement('br'));
}
// Assessment
if (sadsAnalysis.assessment.primaryConcerns.length > 0) {
const concernHeading = document.createElement('strong');
concernHeading.textContent = 'Primary concerns:';
container.appendChild(concernHeading);
container.appendChild(document.createElement('br'));
sadsAnalysis.assessment.primaryConcerns.forEach(concern => {
const item = document.createTextNode(`• ${concern}`);
container.appendChild(item);
container.appendChild(document.createElement('br'));
});
}
return container;
}
// SECURITY FIX P0: Build DOM elements instead of HTML strings to prevent XSS
formatAuthAnalysisDOM(authAnalysis) {
const container = document.createElement('div');
// Heading
const heading = document.createElement('strong');
heading.textContent = 'Authentication Analysis';
container.appendChild(heading);
container.appendChild(document.createElement('br'));
// Protocol
container.appendChild(document.createTextNode('Protocol: '));
const protocolStrong = document.createElement('strong');
protocolStrong.textContent = authAnalysis.protocol;
container.appendChild(protocolStrong);
container.appendChild(document.createElement('br'));
// Risk Score
container.appendChild(document.createTextNode('Risk Score: '));
const scoreStrong = document.createElement('strong');
scoreStrong.textContent = `${Math.round(authAnalysis.riskScore)}/100`;
container.appendChild(scoreStrong);
container.appendChild(document.createElement('br'));
// Recommendation
container.appendChild(document.createTextNode('Recommendation: '));
const recStrong = document.createElement('strong');
recStrong.textContent = authAnalysis.recommendation;
container.appendChild(recStrong);
container.appendChild(document.createElement('br'));
container.appendChild(document.createElement('br'));
if (authAnalysis.issues && authAnalysis.issues.length > 0) {
// Group issues by severity
const criticalIssues = authAnalysis.issues.filter(i => i.severity === 'CRITICAL');
const highIssues = authAnalysis.issues.filter(i => i.severity === 'HIGH');
const mediumIssues = authAnalysis.issues.filter(i => i.severity === 'MEDIUM');
if (criticalIssues.length > 0) {
const critHeading = document.createElement('strong');
critHeading.textContent = `🔴 Critical Issues (${criticalIssues.length}):`;
container.appendChild(critHeading);
container.appendChild(document.createElement('br'));
criticalIssues.forEach(issue => {
container.appendChild(document.createTextNode(`• ${issue.message}`));
container.appendChild(document.createElement('br'));
if (issue.exploitation) {
const em = document.createElement('em');
em.style.color = '#cc0000';
em.textContent = ` ${issue.exploitation}`;
container.appendChild(em);
container.appendChild(document.createElement('br'));
}
});
container.appendChild(document.createElement('br'));
}
if (highIssues.length > 0) {
const highHeading = document.createElement('strong');
highHeading.textContent = `🟠 High Risk Issues (${highIssues.length}):`;
container.appendChild(highHeading);
container.appendChild(document.createElement('br'));
highIssues.forEach(issue => {
container.appendChild(document.createTextNode(`• ${issue.message}`));
container.appendChild(document.createElement('br'));
});
container.appendChild(document.createElement('br'));
}
if (mediumIssues.length > 0) {
const medHeading = document.createElement('strong');
medHeading.textContent = `🟡 Medium Risk Issues (${mediumIssues.length}):`;
container.appendChild(medHeading);
container.appendChild(document.createElement('br'));
mediumIssues.forEach(issue => {
container.appendChild(document.createTextNode(`• ${issue.message}`));
container.appendChild(document.createElement('br'));
});
container.appendChild(document.createElement('br'));
}
// Security recommendations
if (authAnalysis.riskScore >= 80) {
const recHeading = document.createElement('strong');
recHeading.style.color = '#cc0000';
recHeading.textContent = '⛔ Recommended Action:';
container.appendChild(recHeading);
container.appendChild(document.createElement('br'));
container.appendChild(document.createTextNode('• Avoid entering sensitive credentials on this site'));
container.appendChild(document.createElement('br'));
container.appendChild(document.createTextNode('• Use alternative authentication methods if available'));
container.appendChild(document.createElement('br'));
container.appendChild(document.createTextNode('• Contact the site administrator about security issues'));
container.appendChild(document.createElement('br'));
} else if (authAnalysis.riskScore >= 60) {
const recHeading = document.createElement('strong');
recHeading.style.color = '#ff8800';
recHeading.textContent = 'Recommended Action:';
container.appendChild(recHeading);
container.appendChild(document.createElement('br'));
container.appendChild(document.createTextNode('• Exercise caution when authenticating'));
container.appendChild(document.createElement('br'));
container.appendChild(document.createTextNode('• Consider using multi-factor authentication'));
container.appendChild(document.createElement('br'));
container.appendChild(document.createTextNode('• Monitor for suspicious activity'));
container.appendChild(document.createElement('br'));
}
} else {
container.appendChild(document.createTextNode('No significant authentication issues detected.'));
container.appendChild(document.createElement('br'));
}
return container;
}
humanizeFactor(factor) {
const humanNames = {
gitExposure: 'Git repository exposure',
envExposure: 'Environment file exposure',
unexpectedCertIssuer: 'Unusual certificate issuer',
domainAgeMismatch: 'Domain age inconsistency',
techStackMismatch: 'Technology stack anomaly',
weakSecurity: 'Security header deficiency',
weakTLS: 'Outdated TLS configuration'
};
return humanNames[factor] || factor.replace(/([A-Z])/g, ' $1').toLowerCase();
}
monitorForm(form) {
// Add visual indicator for monitored forms
if (this.backendScanResults?.riskScore > 30) {
const indicator = document.createElement('div');
indicator.className = 'hera-form-indicator';
indicator.style.cssText = `
position: absolute;
top: -5px;
right: -5px;
background: ${this.backendScanResults.shouldBlockDataEntry ? '#ff4444' : '#ff8800'};
color: white;
padding: 2px 6px;
border-radius: 3px;
font-size: 10px;
font-weight: bold;
z-index: 1000;
`;
indicator.textContent = this.backendScanResults.shouldBlockDataEntry ? 'BLOCKED' : 'RISKY';
form.style.position = 'relative';
form.appendChild(indicator);
}
}
handlePasswordInput(passwordField) {
// Show real-time warning for password fields on risky sites
if (this.backendScanResults?.riskScore > 50) {
this.showPasswordWarning(passwordField);
}
}
showPasswordWarning(passwordField) {
// Remove existing warning
const existingWarning = passwordField.parentNode.querySelector('.hera-password-warning');
if (existingWarning) return; // Don't spam warnings
const warning = document.createElement('div');
warning.className = 'hera-password-warning';
warning.style.cssText = `
background: rgba(255, 68, 68, 0.1);
border: 1px solid #ff4444;
color: #cc0000;
padding: 8px 12px;
border-radius: 4px;
margin-top: 5px;
font-size: 12px;
font-family: -apple-system, BlinkMacSystemFont, sans-serif;
`;
// SECURITY FIX: Use DOM methods instead of innerHTML
const strong = document.createElement('strong');
strong.textContent = 'Security Risk:';
warning.appendChild(strong);
warning.appendChild(document.createTextNode(' This site has backend vulnerabilities. Consider using a temporary password.'));
passwordField.parentNode.insertBefore(warning, passwordField.nextSibling);
// Remove warning after 10 seconds
setTimeout(() => warning.remove(), 10000);
}
// ===== NEW BRANDED ALERT SYSTEM =====
injectBrandedAlertStyles() {
// Check if styles are already injected
if (document.getElementById('hera-branded-alert-styles')) return;
const styleSheet = document.createElement('style');
styleSheet.id = 'hera-branded-alert-styles';
styleSheet.textContent = `
.hera-security-alert {
position: fixed !important;
top: 45px !important;
right: 8px !important;
background: #e45549 !important;
color: white !important;
padding: 20px !important;
border-radius: 16px !important;
border: 3px solid #0ca678 !important;
min-width: 320px !important;
max-width: 400px !important;
z-index: 999999 !important;
animation: heraAlertSlideIn 0.5s ease-out !important;
font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif !important;
font-size: 14px !important;
line-height: 1.4 !important;
box-shadow: 0 12px 40px rgba(0,0,0,0.4), 0 0 0 1px rgba(12, 166, 120, 0.3) !important;
}
/* Speech bubble tail pointing to extension icon */
.hera-security-alert::before {
content: '' !important;
position: absolute !important;
top: -15px !important;
right: 24px !important;
width: 0 !important;
height: 0 !important;
border-left: 15px solid transparent !important;
border-right: 15px solid transparent !important;
border-bottom: 15px solid #0ca678 !important;
z-index: 2 !important;
filter: drop-shadow(0 -2px 3px rgba(0,0,0,0.2)) !important;
}
/* Inner triangle for speech bubble effect */
.hera-security-alert::after {
content: '' !important;
position: absolute !important;
top: -11px !important;
right: 27px !important;
width: 0 !important;
height: 0 !important;
border-left: 12px solid transparent !important;
border-right: 12px solid transparent !important;
border-bottom: 12px solid #e45549 !important;
z-index: 3 !important;
}
.hera-alert-header {
display: flex !important;
align-items: center !important;
gap: 12px !important;
margin-bottom: 16px !important;
padding-bottom: 12px !important;
border-bottom: 2px solid rgba(255,255,255,0.2) !important;
}
.hera-logo {
width: 24px !important;
height: 24px !important;
background: #0ca678 !important;
border-radius: 6px !important;
display: flex !important;
align-items: center !important;
justify-content: center !important;
font-weight: bold !important;
font-size: 14px !important;
color: white !important;
}
.hera-brand-text {
font-weight: 600 !important;
font-size: 16px !important;
color: white !important;
margin: 0 !important;
}
.hera-extension-label {
background: rgba(255,255,255,0.2) !important;
padding: 2px 8px !important;
border-radius: 4px !important;
font-size: 11px !important;
font-weight: 500 !important;
margin-left: auto !important;
}
.hera-alert-content {
display: flex !important;
align-items: flex-start !important;
gap: 12px !important;
}
.hera-alert-icon {
font-size: 20px !important;
margin-top: 2px !important;
flex-shrink: 0 !important;
}
.hera-alert-message {
flex: 1 !important;
font-weight: 500 !important;
line-height: 1.4 !important;
margin: 0 !important;
}
.hera-alert-details {
font-size: 13px !important;
margin-top: 12px !important;
opacity: 0.9 !important;
padding: 12px !important;
background: rgba(255,255,255,0.1) !important;
border-radius: 8px !important;
border-left: 4px solid #0ca678 !important;
}
.hera-alert-actions {
margin-top: 16px !important;
display: flex !important;
gap: 10px !important;
justify-content: flex-end !important;
}
.hera-alert-close, .hera-alert-verify {
background: rgba(255,255,255,0.2) !important;
border: 1px solid rgba(255,255,255,0.3) !important;
color: white !important;
font-size: 13px !important;
cursor: pointer !important;
padding: 8px 16px !important;
border-radius: 8px !important;
font-weight: 500 !important;
transition: all 0.2s ease !important;
font-family: inherit !important;
}
.hera-alert-verify {
background: #0ca678 !important;
border-color: #0ca678 !important;
}
.hera-alert-verify:hover {
background: #51a14f !important;
border-color: #51a14f !important;
}
@keyframes heraAlertSlideIn {
0% {
opacity: 0;
transform: translate(20px, -20px) scale(0.3);
transform-origin: top right;
}
50% {
opacity: 0.8;
transform: translate(5px, -5px) scale(1.05);
transform-origin: top right;
}
100% {
opacity: 1;
transform: translate(0, 0) scale(1);
transform-origin: top right;
}
}
@keyframes heraAlertSlideOut {
0% {
opacity: 1;
transform: translate(0, 0) scale(1);
transform-origin: top right;
}
100% {
opacity: 0;
transform: translate(20px, -20px) scale(0.3);
transform-origin: top right;
}
}
.hera-security-alert.critical {
animation: heraAlertSlideIn 0.5s ease-out, heraCriticalPulse 2s infinite 0.5s !important;
}
@keyframes heraCriticalPulse {
0%, 100% {
border-color: #0ca678;
}
50% {
border-color: #FFD700;
}
}
`;
document.head.appendChild(styleSheet);
}
showBrandedAlert(alertData) {
// Don't show duplicate alerts
if (this.currentAlert) {
this.alertQueue.push(alertData);
return;
}
this.currentAlert = this.createBrandedAlertElement(alertData);
document.body.appendChild(this.currentAlert);
// Auto-dismiss after 15 seconds unless it's critical
if (alertData.severity !== 'critical') {
setTimeout(() => {
this.dismissCurrentAlert();
}, 15000);
}
}
createBrandedAlertElement(alertData) {
const alertDiv = document.createElement('div');
alertDiv.className = `hera-security-alert ${alertData.severity || ''}`;
// Header
const header = document.createElement('div');
header.className = 'hera-alert-header';
const logo = document.createElement('div');
logo.className = 'hera-logo';
logo.textContent = 'H';
const brandText = document.createElement('div');
brandText.className = 'hera-brand-text';