-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathservice-worker.js
More file actions
702 lines (584 loc) · 19.2 KB
/
service-worker.js
File metadata and controls
702 lines (584 loc) · 19.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
/**
* Smart Security Guardian - Service Worker
* Handles background tasks, API calls, and message passing
*/
// Import modules
import apiClient from './lib/api-client.js';
import securityScorer from './lib/security-scorer.js';
import { scanUrlViaBackend, checkBackendHealth } from './lib/backend-api.js';
// Configuration: Use backend or direct API calls
const USE_BACKEND = true; // Set to true to use backend API
console.log('Service worker loaded');
// ===== STORAGE KEYS =====
const STORAGE_KEYS = {
CACHE: 'site_cache',
STATS: 'statistics',
SETTINGS: 'settings',
WHITELIST: 'whitelist'
};
// ===== DEFAULT SETTINGS =====
const DEFAULT_SETTINGS = {
protectionEnabled: true,
phishingProtection: true,
malwareScanning: true,
trackerBlocking: true,
showNotifications: true
};
// ===== INITIALIZATION =====
chrome.runtime.onInstalled.addListener(async (details) => {
console.log('Extension installed:', details.reason);
if (details.reason === 'install') {
// First time installation
await initializeExtension();
} else if (details.reason === 'update') {
// Extension updated
console.log('Extension updated to version:', chrome.runtime.getManifest().version);
}
});
/**
* Initialize extension on first install
*/
async function initializeExtension() {
console.log('Initializing extension...');
// Set default settings
await chrome.storage.local.set({
[STORAGE_KEYS.SETTINGS]: DEFAULT_SETTINGS,
[STORAGE_KEYS.STATS]: {
blockedToday: 0,
threatsTotal: 0,
lastResetDate: new Date().toDateString()
},
[STORAGE_KEYS.WHITELIST]: [],
[STORAGE_KEYS.CACHE]: {}
});
// Initialize API client
await apiClient.init();
// Set default badge
await chrome.action.setBadgeBackgroundColor({ color: '#10B981' });
console.log('Extension initialized successfully');
}
// ===== MESSAGE HANDLING =====
chrome.runtime.onMessage.addListener((message, sender, sendResponse) => {
console.log('Message received:', message);
// Handle async operations
handleMessage(message, sender).then(sendResponse);
// Return true to indicate async response
return true;
});
/**
* Handle messages from popup and content scripts
*/
async function handleMessage(message, sender) {
const { action } = message;
try {
switch (action) {
case 'getSiteData':
return await getSiteData(message.url, message.tabId);
case 'getStatistics':
return await getStatistics();
case 'toggleProtection':
return await toggleProtection(message.url);
case 'reportThreat':
return await reportThreat(message.url, message.threat);
case 'updateSettings':
return await updateSettings(message.settings);
case 'pageAnalysis':
return await handlePageAnalysis(message.data);
case 'reloadApiKeys':
return await reloadApiKeys();
case 'testApiKeys':
return await testApiKeys();
default:
return { success: false, error: 'Unknown action' };
}
} catch (error) {
console.error('Error handling message:', error);
return { success: false, error: error.message };
}
}
/**
* Get site security data
*/
async function getSiteData(url, tabId) {
console.log('Getting site data for:', url);
try {
// Check cache first
const cache = await getCache();
const cachedData = cache[url];
if (cachedData && isValidCache(cachedData)) {
console.log('Returning cached data for:', url);
return { success: true, data: cachedData };
}
// Perform security scan
const scanData = await performSecurityScan(url, tabId);
// Cache the results
await cacheData(url, scanData);
// Update badge
await updateBadge(tabId, scanData.score);
return { success: true, data: scanData };
} catch (error) {
console.error('Error getting site data:', error);
return { success: false, error: error.message };
}
}
/**
* Perform security scan on URL
*/
async function performSecurityScan(url, tabId) {
console.log('Performing comprehensive security scan for:', url);
// Parse URL
const urlObj = new URL(url);
const hostname = urlObj.hostname;
// Initialize scan data with basic info
const scanData = {
url: url,
hostname: hostname,
protocol: urlObj.protocol,
score: 0,
threats: [],
riskLevel: 'unknown',
lastScan: Date.now()
};
try {
// Check whitelist first
const whitelistData = await chrome.storage.local.get(STORAGE_KEYS.WHITELIST);
const whitelist = whitelistData[STORAGE_KEYS.WHITELIST] || [];
if (whitelist.includes(hostname)) {
// Whitelisted site - give high score
scanData.score = 95;
scanData.riskLevel = 'safe';
scanData.whitelisted = true;
scanData.ssl = { valid: urlObj.protocol === 'https:' };
scanData.malware = { clean: true };
scanData.phishing = { safe: true };
scanData.trackers = { count: 0 };
scanData.cookies = { count: 0 };
scanData.fingerprinting = { protected: true };
console.log('Whitelisted site, returning high score');
return scanData;
}
let apiResults;
// Use backend or direct API calls
if (USE_BACKEND) {
console.log('🔄 Using BACKEND API for scanning...');
const backendResponse = await scanUrlViaBackend(url);
if (backendResponse.success && backendResponse.results) {
// Convert backend response to expected format
apiResults = {
virustotal: backendResponse.results.virustotal || null,
urlhaus: backendResponse.results.urlhaus || null,
phishing: backendResponse.results.phishing || null,
safeBrowsing: backendResponse.results.safeBrowsing || null,
ipReputation: null
};
console.log('✅ Backend scan successful:', apiResults);
} else {
console.warn('⚠️ Backend scan failed, using fallback');
apiResults = await apiClient.comprehensiveScan(url);
}
} else {
console.log('🔄 Using DIRECT API calls...');
apiResults = await apiClient.comprehensiveScan(url);
}
// Calculate security score using all results
const scoringData = {
url: url,
ssl: {
valid: urlObj.protocol === 'https:',
protocol: urlObj.protocol
},
virustotal: apiResults.virustotal,
urlhaus: apiResults.urlhaus,
phishing: apiResults.phishing,
safeBrowsing: apiResults.safeBrowsing,
ipReputation: apiResults.ipReputation
};
// Calculate comprehensive score
const scoreResult = securityScorer.calculateScore(scoringData);
// Update scan data with results
scanData.score = scoreResult.score;
scanData.riskLevel = scoreResult.riskLevel;
scanData.threats = scoreResult.threats;
scanData.factors = scoreResult.factors;
scanData.recommendation = scoreResult.recommendation;
// Map results to UI format
scanData.ssl = {
valid: urlObj.protocol === 'https:',
grade: scoreResult.factors.ssl >= 90 ? 'A+' : scoreResult.factors.ssl >= 80 ? 'A' : 'B'
};
scanData.malware = {
clean: scoreResult.factors.malware >= 90,
virustotal: apiResults.virustotal,
urlhaus: apiResults.urlhaus
};
scanData.phishing = {
safe: scoreResult.factors.phishing >= 90,
result: apiResults.phishing
};
// Will be updated by content script
scanData.trackers = { count: 0 };
scanData.cookies = { count: 0 };
scanData.fingerprinting = { protected: true };
// Update statistics if threats found
if (scoreResult.threats.length > 0) {
await updateThreatStats(scoreResult.threats);
}
console.log('Comprehensive scan completed:', scanData);
return scanData;
} catch (error) {
console.error('Error during security scan:', error);
// Fallback to basic analysis
const basicAnalysis = analyzeUrl(url);
scanData.score = basicAnalysis.score;
scanData.threats = basicAnalysis.threats;
scanData.riskLevel = basicAnalysis.score >= 85 ? 'safe' : basicAnalysis.score >= 60 ? 'warning' : 'danger';
scanData.ssl = { valid: urlObj.protocol === 'https:' };
scanData.malware = { clean: true };
scanData.phishing = { safe: true };
scanData.trackers = { count: 0 };
scanData.cookies = { count: 0 };
scanData.fingerprinting = { protected: true };
return scanData;
}
}
/**
* Update threat statistics
*/
async function updateThreatStats(threats) {
const criticalThreats = threats.filter(t => t.severity === 'critical');
const highThreats = threats.filter(t => t.severity === 'high');
if (criticalThreats.length > 0 || highThreats.length > 0) {
const statsData = await chrome.storage.local.get(STORAGE_KEYS.STATS);
const stats = statsData[STORAGE_KEYS.STATS] || { threatsTotal: 0 };
stats.threatsTotal += criticalThreats.length + highThreats.length;
await chrome.storage.local.set({ [STORAGE_KEYS.STATS]: stats });
}
}
/**
* Analyze URL for suspicious patterns
*/
function analyzeUrl(url) {
const result = {
score: 50, // Base score
threats: []
};
const urlObj = new URL(url);
const hostname = urlObj.hostname;
// Check for IP address instead of domain
if (/^\d+\.\d+\.\d+\.\d+$/.test(hostname)) {
result.threats.push({
type: 'suspicious_url',
severity: 'high',
message: 'Using IP address instead of domain name'
});
result.score -= 20;
}
// Check for suspicious TLDs
const suspiciousTlds = ['.tk', '.ml', '.ga', '.cf', '.gq', '.zip', '.xyz'];
if (suspiciousTlds.some(tld => hostname.endsWith(tld))) {
result.threats.push({
type: 'suspicious_tld',
severity: 'medium',
message: 'Using suspicious top-level domain'
});
result.score -= 15;
}
// Check URL length
if (url.length > 100) {
result.threats.push({
type: 'long_url',
severity: 'low',
message: 'Unusually long URL'
});
result.score -= 5;
}
// Check for @ symbol (phishing technique)
if (url.includes('@')) {
result.threats.push({
type: 'phishing_pattern',
severity: 'high',
message: 'URL contains @ symbol (phishing technique)'
});
result.score -= 25;
}
// Check for excessive subdomains
const subdomains = hostname.split('.');
if (subdomains.length > 4) {
result.threats.push({
type: 'excessive_subdomains',
severity: 'medium',
message: 'Excessive subdomains detected'
});
result.score -= 10;
}
return result;
}
/**
* Get statistics
*/
async function getStatistics() {
const statsData = await chrome.storage.local.get(STORAGE_KEYS.STATS);
const stats = statsData[STORAGE_KEYS.STATS] || {
blockedToday: 0,
threatsTotal: 0
};
// Reset daily counter if needed
const today = new Date().toDateString();
if (stats.lastResetDate !== today) {
stats.blockedToday = 0;
stats.lastResetDate = today;
await chrome.storage.local.set({ [STORAGE_KEYS.STATS]: stats });
}
return { success: true, data: stats };
}
/**
* Toggle protection for a specific site
*/
async function toggleProtection(url) {
const hostname = new URL(url).hostname;
const whitelistData = await chrome.storage.local.get(STORAGE_KEYS.WHITELIST);
let whitelist = whitelistData[STORAGE_KEYS.WHITELIST] || [];
const isWhitelisted = whitelist.includes(hostname);
if (isWhitelisted) {
// Remove from whitelist
whitelist = whitelist.filter(site => site !== hostname);
} else {
// Add to whitelist
whitelist.push(hostname);
}
await chrome.storage.local.set({ [STORAGE_KEYS.WHITELIST]: whitelist });
// Clear cache for this URL
const cache = await getCache();
delete cache[url];
await chrome.storage.local.set({ [STORAGE_KEYS.CACHE]: cache });
return { success: true, enabled: !isWhitelisted };
}
/**
* Report a threat
*/
async function reportThreat(url, threat) {
console.log('Reporting threat:', url, threat);
// Update statistics
const statsData = await chrome.storage.local.get(STORAGE_KEYS.STATS);
const stats = statsData[STORAGE_KEYS.STATS] || { threatsTotal: 0 };
stats.threatsTotal++;
await chrome.storage.local.set({ [STORAGE_KEYS.STATS]: stats });
return { success: true };
}
/**
* Update settings
*/
async function updateSettings(newSettings) {
const currentData = await chrome.storage.local.get(STORAGE_KEYS.SETTINGS);
const settings = { ...DEFAULT_SETTINGS, ...currentData[STORAGE_KEYS.SETTINGS], ...newSettings };
await chrome.storage.local.set({ [STORAGE_KEYS.SETTINGS]: settings });
return { success: true, settings };
}
/**
* Handle page analysis from content script
*/
async function handlePageAnalysis(data) {
console.log('Page analysis received:', data);
// Update statistics based on trackers found
if (data.trackers && data.trackers.length > 0) {
const statsData = await chrome.storage.local.get(STORAGE_KEYS.STATS);
const stats = statsData[STORAGE_KEYS.STATS] || { blockedToday: 0, threatsTotal: 0 };
stats.blockedToday += data.trackers.length;
await chrome.storage.local.set({ [STORAGE_KEYS.STATS]: stats });
}
// Update cache with privacy data
const cache = await getCache();
if (cache[data.url]) {
cache[data.url].trackers = {
count: data.trackers?.length || 0,
detailed: data.trackers || []
};
cache[data.url].trackersDetailed = data.trackers || [];
cache[data.url].cookies = data.cookies || { count: 0 };
cache[data.url].scripts = data.scripts || {};
cache[data.url].forms = data.forms || {};
await chrome.storage.local.set({ [STORAGE_KEYS.CACHE]: cache });
} else {
// Create new cache entry if it doesn't exist
cache[data.url] = {
url: data.url,
hostname: data.hostname,
score: 70, // Default score
trackers: {
count: data.trackers?.length || 0,
detailed: data.trackers || []
},
trackersDetailed: data.trackers || [],
cookies: data.cookies || { count: 0 },
scripts: data.scripts || {},
forms: data.forms || {},
ssl: { valid: data.protocol === 'https:' },
malware: { clean: true },
phishing: { safe: true },
fingerprinting: { protected: true },
lastScan: Date.now()
};
await chrome.storage.local.set({ [STORAGE_KEYS.CACHE]: cache });
}
return { success: true };
}
/**
* Reload API keys
*/
async function reloadApiKeys() {
await apiClient.init();
return { success: true };
}
/**
* Test API keys
*/
async function testApiKeys() {
const testUrl = 'https://www.google.com';
const results = {};
// Test VirusTotal
if (apiClient.getApiKey('virustotal')) {
try {
const vtResult = await apiClient.scanUrlVirusTotal(testUrl);
results.virustotal = { success: vtResult.success || vtResult.scanning };
} catch (error) {
results.virustotal = { success: false, error: error.message };
}
}
// Test URLhaus (always available)
try {
const urlhausResult = await apiClient.checkUrlhaus(testUrl);
results.urlhaus = { success: urlhausResult.success };
} catch (error) {
results.urlhaus = { success: false, error: error.message };
}
// Test AbuseIPDB
if (apiClient.getApiKey('abuseipdb')) {
try {
const ipResult = await apiClient.checkIpReputation('8.8.8.8');
results.abuseipdb = { success: ipResult.success };
} catch (error) {
results.abuseipdb = { success: false, error: error.message };
}
}
return { success: true, results };
}
// ===== CACHE MANAGEMENT =====
/**
* Get cache data
*/
async function getCache() {
const cacheData = await chrome.storage.local.get(STORAGE_KEYS.CACHE);
return cacheData[STORAGE_KEYS.CACHE] || {};
}
/**
* Check if cached data is still valid
*/
function isValidCache(cachedData) {
const CACHE_DURATION = 60 * 60 * 1000; // 1 hour
const age = Date.now() - cachedData.lastScan;
return age < CACHE_DURATION;
}
/**
* Cache scan data
*/
async function cacheData(url, data) {
const cache = await getCache();
cache[url] = data;
// Limit cache size (keep last 100 entries)
const entries = Object.entries(cache);
if (entries.length > 100) {
// Sort by lastScan and keep only recent 100
const sorted = entries.sort((a, b) => b[1].lastScan - a[1].lastScan);
const limited = Object.fromEntries(sorted.slice(0, 100));
await chrome.storage.local.set({ [STORAGE_KEYS.CACHE]: limited });
} else {
await chrome.storage.local.set({ [STORAGE_KEYS.CACHE]: cache });
}
}
// ===== BADGE UPDATES =====
/**
* Update extension badge based on security score
*/
async function updateBadge(tabId, score) {
let color, text;
if (score >= 85) {
color = '#10B981'; // green
text = '✓';
} else if (score >= 60) {
color = '#F59E0B'; // yellow
text = '!';
} else {
color = '#EF4444'; // red
text = 'X';
}
await chrome.action.setBadgeBackgroundColor({ color, tabId });
await chrome.action.setBadgeText({ text, tabId });
}
// ===== TAB MONITORING =====
/**
* Monitor tab updates and scan new pages
*/
chrome.tabs.onUpdated.addListener(async (tabId, changeInfo, tab) => {
// Only scan when page is completely loaded
if (changeInfo.status === 'complete' && tab.url) {
console.log('Tab updated:', tab.url);
// Skip internal pages
const invalidProtocols = ['chrome:', 'chrome-extension:', 'about:', 'edge:', 'brave:'];
if (invalidProtocols.some(protocol => tab.url.startsWith(protocol))) {
await chrome.action.setBadgeText({ text: '', tabId });
return;
}
// Scan the page
const result = await getSiteData(tab.url, tabId);
if (result.success && result.data.score < 60) {
// Show notification for unsafe sites
const settings = await chrome.storage.local.get(STORAGE_KEYS.SETTINGS);
if (settings[STORAGE_KEYS.SETTINGS]?.showNotifications) {
chrome.notifications.create({
type: 'basic',
iconUrl: 'icons/icon128.png',
title: 'Security Warning',
message: `${new URL(tab.url).hostname} may be unsafe (Score: ${result.data.score})`,
priority: 2
});
}
}
}
});
/**
* Monitor tab activation (user switches tabs)
*/
chrome.tabs.onActivated.addListener(async (activeInfo) => {
const tab = await chrome.tabs.get(activeInfo.tabId);
if (tab.url) {
console.log('Tab activated:', tab.url);
// Check if we have cached data and update badge
const cache = await getCache();
const cachedData = cache[tab.url];
if (cachedData) {
await updateBadge(activeInfo.tabId, cachedData.score);
}
}
});
// ===== PERIODIC CLEANUP =====
/**
* Setup periodic cache cleanup
*/
chrome.alarms.create('cleanup', { periodInMinutes: 60 });
chrome.alarms.onAlarm.addListener(async (alarm) => {
if (alarm.name === 'cleanup') {
console.log('Running periodic cleanup...');
// Clean old cache entries
const cache = await getCache();
const now = Date.now();
const cleaned = {};
for (const [url, data] of Object.entries(cache)) {
if (isValidCache(data)) {
cleaned[url] = data;
}
}
await chrome.storage.local.set({ [STORAGE_KEYS.CACHE]: cleaned });
console.log('Cleanup completed');
}
});
console.log('Service worker setup complete');