Repository navigation
Expand file tree
/
Copy pathbackground.js
More file actions
734 lines (663 loc) · 27.2 KB
/
Copy pathbackground.js
File metadata and controls
734 lines (663 loc) · 27.2 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
// NULLBREACH — Background Service Worker
// Handles: message routing, findings storage, request header capture, CVE lookups
const STORAGE_KEY = 'nb_findings';
const SESSION_KEY = 'nb_sessions';
const MAX_SESSIONS = 50;
// ── CVE DATABASE (embedded, offline) ──────────────────────────────────────
const CVE_DB = {
'jquery': [
{ version_lt: '3.5.0', cve: 'CVE-2020-11022', cvss: 6.1, desc: 'XSS via passing HTML containing option elements' },
{ version_lt: '3.5.0', cve: 'CVE-2020-11023', cvss: 6.1, desc: 'XSS via HTML manipulation methods' },
{ version_lt: '3.0.0', cve: 'CVE-2015-9251', cvss: 6.1, desc: 'XSS via jQuery.ajax() cross-domain requests' },
{ version_lt: '1.12.0', cve: 'CVE-2012-6708', cvss: 6.1, desc: 'Selector interpreted as HTML — XSS vector' },
],
'angular': [
{ version_lt: '1.6.0', cve: 'CVE-2019-14863', cvss: 6.1, desc: 'XSS via Angular expression in template interpolation' },
{ version_lt: '1.8.0', cve: 'CVE-2020-7676', cvss: 6.1, desc: 'XSS due to improper sanitization of SVG' },
],
'bootstrap': [
{ version_lt: '3.4.1', cve: 'CVE-2019-8331', cvss: 6.1, desc: 'XSS in tooltip/popover data-template attribute' },
{ version_lt: '4.3.1', cve: 'CVE-2019-8331', cvss: 6.1, desc: 'XSS in tooltip/popover data-template attribute' },
],
'lodash': [
{ version_lt: '4.17.21', cve: 'CVE-2021-23337', cvss: 7.2, desc: 'Command injection via template() function' },
{ version_lt: '4.17.19', cve: 'CVE-2020-8203', cvss: 7.4, desc: 'Prototype pollution via Object.merge' },
{ version_lt: '4.17.11', cve: 'CVE-2018-16487', cvss: 9.8, desc: 'Prototype pollution via defaultsDeep, merge, mergeWith' },
],
'moment': [
{ version_lt: '2.29.4', cve: 'CVE-2022-31129', cvss: 7.5, desc: 'ReDoS in rfc2822 and iso8601 parsing functions' },
{ version_lt: '2.29.2', cve: 'CVE-2022-24785', cvss: 7.5, desc: 'Path traversal in locale loading' },
],
'handlebars': [
{ version_lt: '4.7.7', cve: 'CVE-2021-23369', cvss: 9.8, desc: 'RCE via crafted template with "lookup" helper' },
{ version_lt: '4.7.6', cve: 'CVE-2021-23383', cvss: 9.8, desc: 'Prototype pollution via "lookup" helper' },
],
'underscore': [
{ version_lt: '1.13.0', cve: 'CVE-2021-23358', cvss: 7.2, desc: 'Arbitrary code execution via template() with sourceURL' },
],
'axios': [
{ version_lt: '0.21.2', cve: 'CVE-2021-3749', cvss: 7.5, desc: 'ReDoS via crafted CSRF token' },
],
'serialize-javascript': [
{ version_lt: '3.1.0', cve: 'CVE-2020-7660', cvss: 8.1, desc: 'XSS via object with malicious unicode string values' },
],
'highlight.js': [
{ version_lt: '10.1.2', cve: 'CVE-2020-26237', cvss: 5.4, desc: 'ReDoS in multiple language parsers' },
],
'marked': [
{ version_lt: '2.0.0', cve: 'CVE-2021-21306', cvss: 7.5, desc: 'ReDoS via crafted markdown input' },
],
};
// ── KNOWN DANGEROUS HEADER PATTERNS ──────────────────────────────────────
const SECURITY_HEADERS = {
required: [
'content-security-policy',
'x-frame-options',
'x-content-type-options',
'strict-transport-security',
'referrer-policy',
'permissions-policy',
],
optional: [
'expect-ct',
'cross-origin-opener-policy',
'cross-origin-embedder-policy',
'cross-origin-resource-policy',
]
};
// ── SECRET SCANNING ────────────────────────────────────────────────────────
// Secret scanning is intentionally not automated here.
// For exposed credentials: manually inspect via DevTools > Sources > Search (Ctrl+Shift+F)
// Look for patterns like: apiKey, secret, token, password in JS files
// Tools like truffleHog and gitleaks are the appropriate specialized tools for this
const SECRET_PATTERNS = []; // Intentionally empty — use DevTools manually
// ── RESPONSE HEADER CAPTURE ───────────────────────────────────────────────
const tabHeaders = {};
chrome.webRequest.onHeadersReceived.addListener(
(details) => {
if (details.type === 'main_frame') {
tabHeaders[details.tabId] = {
url: details.url,
statusCode: details.statusCode,
headers: details.responseHeaders || [],
timestamp: Date.now(),
};
}
},
{ urls: ['<all_urls>'] },
['responseHeaders', 'extraHeaders']
);
chrome.webRequest.onCompleted.addListener(
(details) => {
if (details.type === 'xmlhttprequest' || details.type === 'fetch') {
const entry = tabHeaders[details.tabId];
if (entry) {
if (!entry.apiEndpoints) entry.apiEndpoints = [];
entry.apiEndpoints.push({
url: details.url,
method: details.method,
statusCode: details.statusCode,
headers: details.responseHeaders || [],
});
}
}
},
{ urls: ['<all_urls>'] },
['responseHeaders']
);
// ── MESSAGE ROUTER ────────────────────────────────────────────────────────
chrome.runtime.onMessage.addListener((message, sender, sendResponse) => {
const tabId = sender.tab?.id;
switch (message.type) {
case 'SCAN_COMPLETE':
handleScanComplete(tabId, message.data, sendResponse);
return true;
case 'GET_HEADERS':
sendResponse({ headers: tabHeaders[message.tabId] || null });
return false;
case 'GET_FINDINGS':
getFindings(message.tabId || tabId, sendResponse);
return true;
case 'GET_ALL_SESSIONS':
getAllSessions(sendResponse);
return true;
case 'CLEAR_FINDINGS':
clearFindings(message.tabId, sendResponse);
return true;
case 'ANALYSE_SECRETS':
analyseSecrets(message.code, message.source, sendResponse);
return true;
case 'CHECK_CVE':
checkCVE(message.library, message.version, sendResponse);
return true;
case 'GET_TAB_URL':
chrome.tabs.get(message.tabId, (tab) => {
sendResponse({ url: tab?.url || '' });
});
return true;
case 'GET_COOKIES_FOR_URL':
handleGetCookies(message.url, sendResponse);
return true;
case 'DEEP_FINDINGS':
mergeDeepFindings(tabId, message.findings, sendResponse);
return true;
case 'SCAN_RESULT_READY':
// Broadcast to all extension views (popup)
chrome.runtime.sendMessage({ type: 'SCAN_RESULT_READY' }).catch(() => {});
sendResponse({ ok: true });
return false;
}
});
// ── SCAN COMPLETE HANDLER ─────────────────────────────────────────────────
async function handleScanComplete(tabId, scanData, sendResponse) {
try {
const headerData = tabHeaders[tabId] || {};
const findings = [];
// Merge header analysis into findings
const headerFindings = analyseHeaders(headerData.headers || [], scanData.url);
findings.push(...headerFindings);
// Cookie analysis
const cookieFindings = analyseCookies(scanData.cookies || [], scanData.url);
findings.push(...cookieFindings);
// CORS analysis from API endpoints
const corsFindings = analyseCORS(headerData, scanData.corsData || []);
findings.push(...corsFindings);
// Mixed content
if (scanData.mixedContent && scanData.mixedContent.length > 0) {
findings.push({
id: genId(),
type: 'MIXED_CONTENT',
title: `Mixed Content (${scanData.mixedContent.length} resources)`,
severity: 'medium',
description: `Page loads ${scanData.mixedContent.length} insecure HTTP resource(s) over HTTPS`,
detail: scanData.mixedContent.slice(0, 10).join('\n'),
cwe: 'CWE-311',
cvss: 5.3,
path: scanData.url,
timestamp: Date.now(),
});
}
// XSS surface findings
if (scanData.xssSurfaces && scanData.xssSurfaces.length > 0) {
for (const surface of scanData.xssSurfaces) {
findings.push({
id: genId(),
type: 'XSS_SURFACE',
title: `XSS Surface — ${surface.type}`,
severity: surface.severity || 'high',
description: surface.description,
detail: surface.detail || '',
cwe: 'CWE-79',
cvss: 6.1,
path: surface.location || scanData.url,
timestamp: Date.now(),
});
}
}
// Open redirect surfaces
if (scanData.openRedirects && scanData.openRedirects.length > 0) {
for (const r of scanData.openRedirects) {
findings.push({
id: genId(),
type: 'OPEN_REDIRECT',
title: 'Potential Open Redirect',
severity: 'medium',
description: `URL parameter "${r.param}" may accept arbitrary redirect destinations`,
detail: r.url,
cwe: 'CWE-601',
cvss: 6.1,
path: r.url,
timestamp: Date.now(),
});
}
}
// Library CVE findings (already analysed by content script, just include)
if (scanData.cveFindings && scanData.cveFindings.length > 0) {
findings.push(...scanData.cveFindings.map(f => ({ ...f, id: genId(), timestamp: Date.now() })));
}
// Secret findings
if (scanData.secretFindings && scanData.secretFindings.length > 0) {
findings.push(...scanData.secretFindings.map(f => ({ ...f, id: genId(), timestamp: Date.now() })));
}
// Info disclosures
if (scanData.infoDisclosures && scanData.infoDisclosures.length > 0) {
findings.push(...scanData.infoDisclosures.map(f => ({ ...f, id: genId(), timestamp: Date.now() })));
}
// Endpoint map
const endpointMap = [
...(scanData.endpoints || []),
...(headerData.apiEndpoints || []).map(e => e.url),
];
// Compute threat score
const score = computeThreatScore(findings);
// Build session
const session = {
tabId,
url: scanData.url,
domain: extractDomain(scanData.url),
timestamp: Date.now(),
scanDuration: scanData.scanDuration || 0,
findings,
endpointMap,
score,
techStack: scanData.techStack || [],
headers: headerData.headers || [],
statusCode: headerData.statusCode || 0,
};
// Save to storage
await saveSession(tabId, session);
sendResponse({ success: true, session });
} catch (err) {
console.error('[NULLBREACH] handleScanComplete error:', err);
sendResponse({ success: false, error: err.message });
}
}
// ── HEADER ANALYSIS ───────────────────────────────────────────────────────
function analyseHeaders(headers, url) {
const findings = [];
const headerMap = {};
for (const h of headers) {
headerMap[h.name.toLowerCase()] = h.value;
}
// Missing required security headers
const missingHeaders = SECURITY_HEADERS.required.filter(h => !headerMap[h]);
for (const missing of missingHeaders) {
const meta = headerMeta(missing);
findings.push({
id: genId(),
type: 'MISSING_HEADER',
title: `Missing ${meta.display}`,
severity: meta.severity,
description: meta.description,
detail: `Header "${missing}" not present in response`,
cwe: meta.cwe,
cvss: meta.cvss,
path: url,
timestamp: Date.now(),
});
}
// Server version disclosure
const server = headerMap['server'];
if (server && /[\d.]+/.test(server)) {
findings.push({
id: genId(),
type: 'INFO_DISCLOSURE',
title: 'Server Version Disclosed',
severity: 'low',
description: `Server header reveals software version: "${server}"`,
detail: `Server: ${server}`,
cwe: 'CWE-200',
cvss: 3.7,
path: url,
timestamp: Date.now(),
});
}
// X-Powered-By disclosure
const poweredBy = headerMap['x-powered-by'];
if (poweredBy) {
findings.push({
id: genId(),
type: 'INFO_DISCLOSURE',
title: 'Technology Stack Disclosed',
severity: 'low',
description: `X-Powered-By header reveals backend technology: "${poweredBy}"`,
detail: `X-Powered-By: ${poweredBy}`,
cwe: 'CWE-200',
cvss: 3.7,
path: url,
timestamp: Date.now(),
});
}
// Weak CSP check
const csp = headerMap['content-security-policy'];
if (csp) {
if (csp.includes("'unsafe-inline'")) {
findings.push({
id: genId(),
type: 'WEAK_CSP',
title: "CSP allows 'unsafe-inline'",
severity: 'high',
description: "Content-Security-Policy contains 'unsafe-inline', allowing inline script execution and negating XSS protection",
detail: `CSP: ${csp.substring(0, 200)}`,
cwe: 'CWE-693',
cvss: 6.1,
path: url,
timestamp: Date.now(),
});
}
if (csp.includes("'unsafe-eval'")) {
findings.push({
id: genId(),
type: 'WEAK_CSP',
title: "CSP allows 'unsafe-eval'",
severity: 'medium',
description: "Content-Security-Policy contains 'unsafe-eval', allowing dynamic code evaluation",
detail: `CSP: ${csp.substring(0, 200)}`,
cwe: 'CWE-693',
cvss: 5.4,
path: url,
timestamp: Date.now(),
});
}
if (csp.includes('*') && !csp.includes("'none'")) {
findings.push({
id: genId(),
type: 'WEAK_CSP',
title: 'CSP Wildcard Source Detected',
severity: 'medium',
description: "Content-Security-Policy uses wildcard (*) source — attacker-controlled domains can serve scripts",
detail: `CSP: ${csp.substring(0, 200)}`,
cwe: 'CWE-693',
cvss: 5.4,
path: url,
timestamp: Date.now(),
});
}
}
// HSTS check
const hsts = headerMap['strict-transport-security'];
if (hsts) {
const maxAgeMatch = hsts.match(/max-age=(\d+)/);
if (maxAgeMatch) {
const maxAge = parseInt(maxAgeMatch[1]);
if (maxAge < 31536000) {
findings.push({
id: genId(),
type: 'WEAK_HSTS',
title: 'HSTS Max-Age Too Short',
severity: 'low',
description: `HSTS max-age is ${maxAge}s (${Math.floor(maxAge/86400)} days). Recommended minimum is 31536000s (1 year)`,
detail: `Strict-Transport-Security: ${hsts}`,
cwe: 'CWE-523',
cvss: 3.1,
path: url,
timestamp: Date.now(),
});
}
}
if (!hsts.includes('includeSubDomains')) {
findings.push({
id: genId(),
type: 'WEAK_HSTS',
title: 'HSTS Missing includeSubDomains',
severity: 'info',
description: 'Strict-Transport-Security does not include "includeSubDomains" directive — subdomains remain vulnerable to downgrade attacks',
detail: `Strict-Transport-Security: ${hsts}`,
cwe: 'CWE-523',
cvss: 2.6,
path: url,
timestamp: Date.now(),
});
}
}
return findings;
}
// ── COOKIE ANALYSIS ───────────────────────────────────────────────────────
function analyseCookies(cookies, url) {
const findings = [];
const isHTTPS = url.startsWith('https://');
for (const cookie of cookies) {
if (!cookie.httpOnly) {
findings.push({
id: genId(),
type: 'INSECURE_COOKIE',
title: `Cookie Missing HttpOnly — "${cookie.name}"`,
severity: cookie.name.toLowerCase().includes('session') || cookie.name.toLowerCase().includes('auth') || cookie.name.toLowerCase().includes('token') ? 'high' : 'medium',
description: `Cookie "${cookie.name}" lacks HttpOnly flag — readable by JavaScript, vulnerable to XSS-based session theft`,
detail: `Cookie: ${cookie.name}; Missing: HttpOnly`,
cwe: 'CWE-1004',
cvss: cookie.name.toLowerCase().includes('session') ? 7.4 : 5.3,
path: url,
timestamp: Date.now(),
});
}
if (isHTTPS && !cookie.secure) {
findings.push({
id: genId(),
type: 'INSECURE_COOKIE',
title: `Cookie Missing Secure Flag — "${cookie.name}"`,
severity: 'medium',
description: `Cookie "${cookie.name}" lacks Secure flag — can be transmitted over HTTP, vulnerable to interception`,
detail: `Cookie: ${cookie.name}; Missing: Secure`,
cwe: 'CWE-614',
cvss: 5.3,
path: url,
timestamp: Date.now(),
});
}
if (!cookie.sameSite || cookie.sameSite === 'no_restriction') {
findings.push({
id: genId(),
type: 'INSECURE_COOKIE',
title: `Cookie Missing SameSite — "${cookie.name}"`,
severity: 'medium',
description: `Cookie "${cookie.name}" has SameSite=None or missing — vulnerable to CSRF attacks`,
detail: `Cookie: ${cookie.name}; SameSite: ${cookie.sameSite || 'not set'}`,
cwe: 'CWE-352',
cvss: 5.4,
path: url,
timestamp: Date.now(),
});
}
}
return findings;
}
// ── CORS ANALYSIS ─────────────────────────────────────────────────────────
function analyseCORS(headerData, corsData) {
const findings = [];
const headers = headerData.headers || [];
const headerMap = {};
for (const h of headers) headerMap[h.name.toLowerCase()] = h.value;
const acao = headerMap['access-control-allow-origin'];
const acac = headerMap['access-control-allow-credentials'];
if (acao === '*' && acac === 'true') {
findings.push({
id: genId(),
type: 'CORS_MISCONFIGURATION',
title: 'CORS Wildcard with Credentials',
severity: 'critical',
description: 'Access-Control-Allow-Origin: * combined with Access-Control-Allow-Credentials: true — browsers will reject this, but the misconfiguration indicates flawed CORS logic that may be exploitable with a reflected-origin attack',
detail: `ACAO: ${acao}\nACAC: ${acac}`,
cwe: 'CWE-942',
cvss: 9.1,
path: headerData.url || '',
timestamp: Date.now(),
});
} else if (acao === '*') {
findings.push({
id: genId(),
type: 'CORS_MISCONFIGURATION',
title: 'CORS Allows All Origins',
severity: 'medium',
description: 'Access-Control-Allow-Origin: * — any domain can read non-credentialed responses. Review if this endpoint returns sensitive data',
detail: `ACAO: ${acao}`,
cwe: 'CWE-942',
cvss: 5.3,
path: headerData.url || '',
timestamp: Date.now(),
});
}
// Check reflected-origin CORS (detected by content script)
for (const c of corsData) {
if (c.reflectedOrigin) {
findings.push({
id: genId(),
type: 'CORS_MISCONFIGURATION',
title: 'Reflected Origin CORS',
severity: 'critical',
description: `Endpoint appears to reflect the Origin header as Access-Control-Allow-Origin — any attacker-controlled domain can read credentialed responses`,
detail: `Endpoint: ${c.url}`,
cwe: 'CWE-942',
cvss: 9.1,
path: c.url,
timestamp: Date.now(),
});
}
}
return findings;
}
// ── SECRET ANALYSIS ───────────────────────────────────────────────────────
// Flags the PRESENCE of secret patterns only — does not extract or store values
function analyseSecrets(code, source, sendResponse) {
const found = [];
for (const p of SECRET_PATTERNS) {
if (p.pattern.test(code)) {
found.push({
id: genId(),
type: 'EXPOSED_SECRET',
title: `Possible ${p.name} Pattern Detected`,
severity: p.severity,
description: `A pattern matching ${p.name} was detected in ${source}. Manually verify in DevTools > Sources and rotate the credential if confirmed`,
detail: `Source: ${source}\nPattern type: ${p.name}\nAction: Open DevTools > Sources to inspect and confirm`,
cwe: 'CWE-312',
cvss: p.severity === 'critical' ? 9.8 : p.severity === 'high' ? 7.5 : 5.3,
path: source,
timestamp: Date.now(),
});
}
}
sendResponse({ findings: found });
}
// ── CVE CHECK ─────────────────────────────────────────────────────────────
function checkCVE(library, version, sendResponse) {
const lib = library.toLowerCase().replace(/[^a-z0-9-]/g, '');
const cves = CVE_DB[lib];
if (!cves) { sendResponse({ findings: [] }); return; }
const found = [];
for (const cve of cves) {
if (versionLessThan(version, cve.version_lt)) {
found.push({
type: 'VULNERABLE_LIBRARY',
title: `${library} ${version} — ${cve.cve}`,
severity: cve.cvss >= 9.0 ? 'critical' : cve.cvss >= 7.0 ? 'high' : cve.cvss >= 4.0 ? 'medium' : 'low',
description: cve.desc,
detail: `Library: ${library} v${version}\nCVE: ${cve.cve}\nFixed in: v${cve.version_lt}+`,
cwe: 'CWE-1035',
cvss: cve.cvss,
path: '',
timestamp: Date.now(),
});
}
}
sendResponse({ findings: found });
}
// ── STORAGE HELPERS ───────────────────────────────────────────────────────
async function saveSession(tabId, session) {
const result = await chrome.storage.local.get(SESSION_KEY);
const sessions = result[SESSION_KEY] || {};
sessions[tabId] = session;
// Prune old sessions if over limit
const keys = Object.keys(sessions);
if (keys.length > MAX_SESSIONS) {
const sorted = keys.sort((a, b) => (sessions[a].timestamp || 0) - (sessions[b].timestamp || 0));
delete sessions[sorted[0]];
}
await chrome.storage.local.set({ [SESSION_KEY]: sessions });
}
function getFindings(tabId, sendResponse) {
chrome.storage.local.get(SESSION_KEY, (result) => {
const sessions = result[SESSION_KEY] || {};
sendResponse({ session: sessions[tabId] || null });
});
}
function getAllSessions(sendResponse) {
chrome.storage.local.get(SESSION_KEY, (result) => {
sendResponse({ sessions: result[SESSION_KEY] || {} });
});
}
function clearFindings(tabId, sendResponse) {
chrome.storage.local.get(SESSION_KEY, (result) => {
const sessions = result[SESSION_KEY] || {};
if (tabId) {
delete sessions[tabId];
} else {
Object.keys(sessions).forEach(k => delete sessions[k]);
}
chrome.storage.local.set({ [SESSION_KEY]: sessions }, () => {
sendResponse({ success: true });
});
});
}
// ── SCORING ───────────────────────────────────────────────────────────────
function computeThreatScore(findings) {
let score = 0;
const weights = { critical: 25, high: 15, medium: 8, low: 3, info: 1 };
for (const f of findings) {
score += weights[f.severity] || 0;
}
return Math.min(100, score);
}
// ── HEADER META ───────────────────────────────────────────────────────────
function headerMeta(header) {
const map = {
'content-security-policy': { display: 'Content-Security-Policy', severity: 'high', cwe: 'CWE-693', cvss: 6.1, description: 'No Content-Security-Policy header — no XSS mitigation in place' },
'x-frame-options': { display: 'X-Frame-Options', severity: 'medium', cwe: 'CWE-1021', cvss: 5.4, description: 'No X-Frame-Options — page may be embeddable in iframes for clickjacking' },
'x-content-type-options': { display: 'X-Content-Type-Options', severity: 'low', cwe: 'CWE-693', cvss: 3.7, description: 'No X-Content-Type-Options — browser may MIME-sniff responses, enabling content injection' },
'strict-transport-security': { display: 'Strict-Transport-Security', severity: 'medium', cwe: 'CWE-523', cvss: 5.9, description: 'No HSTS header — site may be vulnerable to SSL stripping / downgrade attacks' },
'referrer-policy': { display: 'Referrer-Policy', severity: 'low', cwe: 'CWE-200', cvss: 3.1, description: 'No Referrer-Policy — sensitive URL fragments may leak to third-party origins via Referer header' },
'permissions-policy': { display: 'Permissions-Policy', severity: 'info', cwe: 'CWE-693', cvss: 2.1, description: 'No Permissions-Policy — browser features (camera, mic, geolocation) not explicitly restricted' },
};
return map[header] || { display: header, severity: 'info', cwe: 'CWE-693', cvss: 2.0, description: `Security header "${header}" not present` };
}
// ── COOKIE HANDLER ────────────────────────────────────────────────────────
function handleGetCookies(url, sendResponse) {
try {
chrome.cookies.getAll({ url }, (cookies) => {
const mapped = (cookies || []).map(c => ({
name: c.name,
httpOnly: c.httpOnly,
secure: c.secure,
sameSite: c.sameSite,
session: c.session,
domain: c.domain,
path: c.path,
}));
sendResponse({ cookies: mapped });
});
} catch {
sendResponse({ cookies: [] });
}
}
// ── DEEP FINDINGS MERGE ───────────────────────────────────────────────────
async function mergeDeepFindings(tabId, newFindings, sendResponse) {
try {
const result = await chrome.storage.local.get(SESSION_KEY);
const sessions = result[SESSION_KEY] || {};
const session = sessions[tabId];
if (!session) { sendResponse({ ok: false }); return; }
// Tag and deduplicate
const existingTitles = new Set((session.findings || []).map(f => f.title));
const toAdd = (newFindings || []).filter(f => !existingTitles.has(f.title)).map(f => ({
...f,
id: genId(),
timestamp: Date.now(),
}));
session.findings = [...(session.findings || []), ...toAdd];
session.score = computeThreatScore(session.findings);
sessions[tabId] = session;
await chrome.storage.local.set({ [SESSION_KEY]: sessions });
sendResponse({ ok: true, added: toAdd.length });
} catch (err) {
sendResponse({ ok: false, error: err.message });
}
}
// ── UTILITIES ─────────────────────────────────────────────────────────────
function genId() {
return 'nb_' + Math.random().toString(36).substr(2, 9) + '_' + Date.now().toString(36);
}
function extractDomain(url) {
try { return new URL(url).hostname; } catch { return url; }
}
function versionLessThan(v1, v2) {
if (!v1 || !v2) return false;
const a = v1.replace(/[^0-9.]/g, '').split('.').map(Number);
const b = v2.replace(/[^0-9.]/g, '').split('.').map(Number);
for (let i = 0; i < Math.max(a.length, b.length); i++) {
const ai = a[i] || 0;
const bi = b[i] || 0;
if (ai < bi) return true;
if (ai > bi) return false;
}
return false;
}
console.log('[NULLBREACH] Background service worker initialized');