-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathbackground.js
More file actions
1855 lines (1599 loc) · 62.8 KB
/
background.js
File metadata and controls
1855 lines (1599 loc) · 62.8 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
// This script runs in the background and handles extension tasks.
// Version from manifest.json - single source of truth
const APP_VERSION = browser.runtime.getManifest().version;
// Encryption utilities inlined to avoid module loading issues
async function getDerivedKey() {
// Use extension ID and browser info for key derivation (works in service workers)
const extensionId = browser.runtime.id;
const browserInfo = `${navigator.userAgent}-${navigator.language}-${extensionId}`;
const encoder = new TextEncoder();
const data = encoder.encode(browserInfo);
const hashBuffer = await crypto.subtle.digest('SHA-256', data);
return await crypto.subtle.importKey(
'raw',
hashBuffer,
{ name: 'AES-GCM', length: 256 },
false,
['encrypt', 'decrypt']
);
}
async function decryptApiKey(encrypted) {
if (!encrypted) return null;
try {
const key = await getDerivedKey();
const combined = Uint8Array.from(atob(encrypted), c => c.charCodeAt(0));
const iv = combined.slice(0, 12);
const data = combined.slice(12);
const decrypted = await crypto.subtle.decrypt(
{ name: 'AES-GCM', iv },
key,
data
);
const decoder = new TextDecoder();
return decoder.decode(decrypted);
} catch (error) {
// Handle decryption failures gracefully (e.g., different extension ID, corrupted data)
// Don't log as error since this is expected when switching between extension versions
console.debug('API key decryption failed (this is normal if switching extension versions):', error.message);
return null;
}
}
async function getDecryptedApiKey(keyName) {
const result = await browser.storage.local.get(keyName);
if (result[keyName]) {
return await decryptApiKey(result[keyName]);
}
return null;
}
// Concurrency limiter to prevent overwhelming network with DNS lookups
class ConcurrencyLimiter {
constructor(maxConcurrent = 10) {
this.maxConcurrent = maxConcurrent;
this.running = 0;
this.queue = [];
}
async run(fn) {
while (this.running >= this.maxConcurrent) {
await new Promise(resolve => this.queue.push(resolve));
}
this.running++;
try {
return await fn();
} finally {
this.running--;
const next = this.queue.shift();
if (next) next();
}
}
}
// Global concurrency limiter for all network requests
// With parallel link+safety checks, actual concurrent requests can be up to 20 (10 bookmarks × 2 checks each)
const networkLimiter = new ConcurrencyLimiter(10);
// URL validation utilities inlined to avoid module loading issues
const BLOCKED_SCHEMES = ['file', 'javascript', 'data', 'vbscript'];
const PRIVILEGED_SCHEMES = ['about', 'chrome', 'moz-extension', 'chrome-extension', 'view-source', 'jar', 'resource'];
const PRIVATE_IP_RANGES = [
/^127\./, /^10\./, /^172\.(1[6-9]|2\d|3[01])\./, /^192\.168\./,
/^169\.254\./, /^::1$/, /^fe80:/i, /^fc00:/i, /^fd00:/i, /^localhost$/i
];
function validateUrl(urlString) {
if (!urlString || typeof urlString !== 'string') {
return { valid: false, error: 'Invalid URL: empty or not a string' };
}
let url;
try {
url = new URL(urlString.trim());
} catch (error) {
return { valid: false, error: 'Invalid URL format' };
}
const scheme = url.protocol.replace(':', '').toLowerCase();
// Allow privileged schemes (browser internal pages, extensions, etc.)
if (PRIVILEGED_SCHEMES.includes(scheme)) {
return { valid: true, url: url.href, privileged: true };
}
// Block dangerous schemes
if (BLOCKED_SCHEMES.includes(scheme)) {
return { valid: false, error: `Blocked URL scheme: ${scheme}` };
}
// Only allow HTTP/HTTPS for regular URLs
if (scheme !== 'http' && scheme !== 'https') {
return { valid: false, error: `Only HTTP and HTTPS URLs are allowed` };
}
const hostname = url.hostname.toLowerCase();
for (const range of PRIVATE_IP_RANGES) {
if (range.test(hostname)) {
return { valid: false, error: 'Private/internal IP addresses are not allowed' };
}
}
if (url.username || url.password) {
return { valid: false, error: 'URLs with credentials are not allowed' };
}
return { valid: true, url: url.href };
}
function sanitizeUrl(urlString) {
const validation = validateUrl(urlString);
if (!validation.valid) {
console.warn(`URL validation failed: ${validation.error}`);
return null;
}
return validation.url;
}
const PARKING_DOMAINS = [
// Major registrars with parking
'hugedomains.com',
'godaddy.com',
'namecheap.com',
'namesilo.com',
'porkbun.com',
'dynadot.com',
'epik.com',
// Domain marketplaces
'sedo.com',
'dan.com',
'afternic.com',
'domainmarket.com',
'uniregistry.com',
'squadhelp.com',
'brandbucket.com',
'undeveloped.com',
'atom.com',
// Parking services
'bodis.com',
'parkingcrew.net',
'parkingcrew.com',
'above.com',
'sedoparking.com',
];
// Trusted domains that should never be flagged as unsafe by local blocklists
// These are well-known, trusted platforms that may have false positives in URLhaus/blocklists
// API-based scanners (Google, Yandex, VirusTotal) are NOT affected by this allow-list
const TRUSTED_DOMAINS = [
'archive.org',
'github.io',
'githubusercontent.com',
'github.com',
'gitlab.com',
'gitlab.io',
'docs.google.com',
'sites.google.com',
'drive.google.com',
];
// Domains that should never be flagged as "parked" (for link status checking)
// These are legitimate hosting platforms, not parking services
const PARKING_EXEMPTIONS = [
'github.io',
'github.com',
'githubusercontent.com',
'gitlab.io',
'gitlab.com',
'pages.dev', // Cloudflare Pages
'netlify.app',
'vercel.app',
'herokuapp.com',
];
// Helper function to check if a domain matches the trusted list (supports subdomains)
function isTrustedDomain(hostname) {
if (!hostname) return false;
const lowerHost = hostname.toLowerCase();
for (const trustedDomain of TRUSTED_DOMAINS) {
// Exact match
if (lowerHost === trustedDomain) {
return true;
}
// Subdomain match (e.g., "user.github.io" matches "github.io")
if (lowerHost.endsWith('.' + trustedDomain)) {
return true;
}
}
return false;
}
// Helper function to check if a domain should be exempt from parking detection
function isParkingExempt(hostname) {
if (!hostname) return false;
const lowerHost = hostname.toLowerCase();
for (const exemptDomain of PARKING_EXEMPTIONS) {
// Exact match
if (lowerHost === exemptDomain) {
return true;
}
// Subdomain match (e.g., "user.github.io" matches "github.io")
if (lowerHost.endsWith('.' + exemptDomain)) {
return true;
}
}
return false;
}
// Cache for link and safety checks (7 days TTL)
const CACHE_TTL = 7 * 24 * 60 * 60 * 1000; // 7 days in milliseconds
// Get cached result if valid
const getCachedResult = async (url, cacheKey) => {
try {
const cache = await browser.storage.local.get(cacheKey);
if (cache[cacheKey]) {
const cached = cache[cacheKey][url];
if (cached && (Date.now() - cached.timestamp < CACHE_TTL)) {
return cached.result;
}
}
} catch (e) {
console.warn('Cache read error:', e);
}
return null;
};
// Store result in cache (with mutex to prevent race conditions)
const cacheMutex = {};
const setCachedResult = async (url, result, cacheKey) => {
// Wait for any pending write to the same cache to complete
while (cacheMutex[cacheKey]) {
await new Promise(resolve => setTimeout(resolve, 10));
}
cacheMutex[cacheKey] = true;
try {
const cache = await browser.storage.local.get(cacheKey);
const cacheData = cache[cacheKey] || {};
cacheData[url] = {
result,
timestamp: Date.now()
};
await browser.storage.local.set({ [cacheKey]: cacheData });
} catch (e) {
console.warn('Cache write error:', e);
} finally {
cacheMutex[cacheKey] = false;
}
};
/**
* Check if a URL is a browser privileged/internal URL that should not be scanned
* @param {string} url The URL to check
* @returns {object|null} Object with type and label if privileged, null otherwise
*/
function isPrivilegedUrl(url) {
try {
const urlObj = new URL(url);
const scheme = urlObj.protocol.replace(':', '').toLowerCase();
// Browser internal pages
if (scheme === 'about') {
return { type: 'browser-internal', label: 'Browser internal page' };
}
if (scheme === 'chrome') {
return { type: 'browser-internal', label: 'Browser internal page' };
}
// Extension pages
if (scheme === 'moz-extension') {
return { type: 'extension', label: 'Extension page' };
}
if (scheme === 'chrome-extension') {
return { type: 'extension', label: 'Extension page' };
}
// Developer/debugging schemes
if (scheme === 'view-source') {
return { type: 'developer', label: 'View source page' };
}
if (scheme === 'jar') {
return { type: 'developer', label: 'JAR resource' };
}
if (scheme === 'resource') {
return { type: 'developer', label: 'Browser resource' };
}
return null;
} catch (e) {
return null;
}
}
/**
* Checks if a URL is reachable and resolves to the expected domain.
* This function runs in the background script, which has broader permissions
* than content scripts, allowing it to bypass CORS restrictions.
* @param {string} url The URL to check.
* @returns {Promise<'live' | 'dead' | 'parked'>} The status of the link.
*/
const checkLinkStatus = async (url, bypassCache = false) => {
// Check if this is a privileged URL that should not be scanned
const privilegedInfo = isPrivilegedUrl(url);
if (privilegedInfo) {
console.log(`[Link Check] Privileged URL detected: ${privilegedInfo.label}`);
// Cache the result so it persists after sidebar reload
await setCachedResult(url, 'live', 'linkStatusCache');
return 'live'; // Privileged URLs are always considered "live"
}
// Check cache first (unless bypassed for rescan)
if (!bypassCache) {
const cached = await getCachedResult(url, 'linkStatusCache');
if (cached) {
console.log(`[Link Check] Using cached result for ${url}: ${cached}`);
return cached;
}
} else {
console.log(`[Link Check] Bypassing cache for rescan of ${url}`);
}
let result;
// Check if the URL itself is on a parking domain
try {
const urlHost = new URL(url).hostname.toLowerCase();
// Skip parking check for exempt hosting platforms
if (!isParkingExempt(urlHost) && PARKING_DOMAINS.some(domain => urlHost.includes(domain))) {
result = 'parked';
await setCachedResult(url, result, 'linkStatusCache');
return result;
}
} catch (e) {
// Invalid URL, continue with fetch attempt
}
const controller = new AbortController();
const timeoutId = setTimeout(() => controller.abort(), 5000); // 5-second timeout
// Use a standard browser User-Agent to avoid being blocked
const headers = {
'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36'
};
try {
// Try HEAD request first (lighter weight)
// Note: Don't use mode: 'cors' - background scripts have broader permissions
const response = await fetch(url, {
method: 'HEAD',
signal: controller.signal,
credentials: 'omit',
redirect: 'follow',
headers: headers
});
clearTimeout(timeoutId);
// Check if redirected to parking domain
if (response.redirected || response.url !== url) {
const finalHost = new URL(response.url).hostname.toLowerCase();
// Skip parking check for exempt hosting platforms
if (!isParkingExempt(finalHost) && PARKING_DOMAINS.some(domain => finalHost.includes(domain))) {
result = 'parked';
await setCachedResult(url, result, 'linkStatusCache');
return result;
}
}
// Check for successful status codes
if (response.ok || (response.status >= 300 && response.status < 400)) {
// Skip content-based parking detection for exempt hosting platforms
const urlHost = new URL(url).hostname.toLowerCase();
if (isParkingExempt(urlHost)) {
result = 'live';
await setCachedResult(url, result, 'linkStatusCache');
return result;
}
// Try lightweight content check for parking indicators (with robust error handling)
try {
const contentController = new AbortController();
const contentTimeout = setTimeout(() => contentController.abort(), 3000); // Short 3s timeout
const contentResponse = await fetch(url, {
method: 'GET',
signal: contentController.signal,
credentials: 'omit',
redirect: 'follow',
headers: headers
});
clearTimeout(contentTimeout);
// Only check if we got a successful response
if (contentResponse.ok) {
const html = await contentResponse.text();
const htmlLower = html.toLowerCase();
// Real websites typically have substantial content
// Parked pages are usually very simple (<30KB)
const contentSize = html.length;
const isSubstantialContent = contentSize > 30000;
// Strong indicators - if any match, definitely parked
const strongParkingIndicators = [
'sedo domain parking',
'this domain is parked',
'domain is parked',
'parked by',
'parked domain',
'parkingcrew',
'bodis.com',
'hugedomains.com/domain',
'afternic.com/forsale',
'this domain name is for sale',
'the domain name is for sale',
'buy this domain name',
'domain has expired',
'this domain has been registered'
];
// If any strong indicator matches, it's parked
if (strongParkingIndicators.some(indicator => htmlLower.includes(indicator))) {
result = 'parked';
await setCachedResult(url, result, 'linkStatusCache');
return result;
}
// Skip weak indicator check for substantial content (real websites)
if (isSubstantialContent) {
result = 'live';
await setCachedResult(url, result, 'linkStatusCache');
return result;
}
// Weak indicators - need 3+ matches on small pages
const weakParkingIndicators = [
'domain for sale',
'buy this domain',
'domain is for sale',
'this domain may be for sale',
'make an offer',
'make offer',
'expired domain',
'register this domain',
'purchase this domain',
'acquire this domain',
'coming soon',
'under construction',
'inquire about this domain',
'interested in this domain',
'domain may be for sale'
];
const matchCount = weakParkingIndicators.filter(indicator =>
htmlLower.includes(indicator)
).length;
// Require 3+ weak indicators on small pages
if (matchCount >= 3) {
result = 'parked';
await setCachedResult(url, result, 'linkStatusCache');
return result;
}
}
} catch (contentError) {
// Log CORS and other errors for debugging parking detection issues
console.log(`[Parking Check] Content fetch failed for ${url}:`, contentError.message);
// Silently continue - don't break link checking
}
// If content check didn't find parking indicators (or failed), return live
result = 'live';
await setCachedResult(url, result, 'linkStatusCache');
return result;
}
// Check if it's a Cloudflare-protected site
const serverHeader = response.headers.get('server');
const cfRay = response.headers.get('cf-ray');
if (serverHeader?.toLowerCase().includes('cloudflare') || cfRay) {
// Cloudflare is fronting this domain - site is configured and live
// Even with 4xx/5xx errors, the domain is valid and accessible
// (403 often means the site blocks direct requests but works in browser)
console.log(`[Link Check] Cloudflare detected for ${url} (status ${response.status}), marking as live`);
result = 'live';
await setCachedResult(url, result, 'linkStatusCache');
return result;
}
// 4xx errors (except 404, 410, 451) often mean the site is blocking automated requests
// but the site itself is live and accessible in a browser
// 403 = Forbidden (often blocks bots), 401 = Unauthorized (needs login), 405 = Method Not Allowed
const liveButBlocking = [401, 403, 405, 406, 429];
if (liveButBlocking.includes(response.status)) {
console.log(`[Link Check] ${url} returned ${response.status}, likely blocking automated requests - marking as live`);
result = 'live';
await setCachedResult(url, result, 'linkStatusCache');
return result;
}
// 5xx errors could be temporary server issues - try GET fallback before marking dead
if (response.status >= 500) {
console.log(`[Link Check] ${url} returned ${response.status}, will try GET fallback`);
// Fall through to catch block logic by throwing
throw new Error(`Server error ${response.status}`);
}
// 404 from HEAD might be a site that doesn't support HEAD - try GET fallback
if (response.status === 404) {
console.log(`[Link Check] ${url} returned 404 on HEAD, trying GET fallback`);
throw new Error(`HEAD returned 404`);
}
// 410 (Gone), 451 (Legal) - these indicate the content is truly gone
console.log(`[Link Check] ${url} returned ${response.status}, marking as dead`);
result = 'dead';
await setCachedResult(url, result, 'linkStatusCache');
return result;
} catch (error) {
clearTimeout(timeoutId);
console.log(`[Link Check] HEAD failed for ${url}:`, error.name, error.message);
// If HEAD timed out or was aborted, mark as live (slow server, not dead)
if (error.name === 'AbortError' || error.message?.includes('abort')) {
console.log(`[Link Check] HEAD request timed out for ${url}, marking as live (slow server)`);
result = 'live';
await setCachedResult(url, result, 'linkStatusCache');
return result;
}
// If HEAD fails for other reasons, try GET as fallback
try {
const fallbackController = new AbortController();
const fallbackTimeout = setTimeout(() => fallbackController.abort(), 5000);
const fallbackResponse = await fetch(url, {
method: 'GET',
signal: fallbackController.signal,
credentials: 'omit',
redirect: 'follow',
headers: headers
});
clearTimeout(fallbackTimeout);
// Check for Cloudflare on fallback response too
const fbServerHeader = fallbackResponse.headers.get('server');
const fbCfRay = fallbackResponse.headers.get('cf-ray');
if (fbServerHeader?.toLowerCase().includes('cloudflare') || fbCfRay) {
console.log(`[Link Check] Cloudflare detected on fallback for ${url}, marking as live`);
result = 'live';
await setCachedResult(url, result, 'linkStatusCache');
return result;
}
// Only mark as live if GET returned a successful response
if (fallbackResponse.ok) {
console.log(`[Link Check] GET fallback succeeded for ${url}, marking as live`);
result = 'live';
await setCachedResult(url, result, 'linkStatusCache');
return result;
}
// GET also returned an error - site is dead
console.log(`[Link Check] GET fallback returned ${fallbackResponse.status} for ${url}, marking as dead`);
result = 'dead';
await setCachedResult(url, result, 'linkStatusCache');
return result;
} catch (fallbackError) {
// Check if it was a timeout (AbortError) - timeouts often mean slow server, not dead
if (fallbackError.name === 'AbortError') {
console.log(`[Link Check] Request timed out for ${url}, marking as live (slow server)`);
result = 'live';
await setCachedResult(url, result, 'linkStatusCache');
return result;
}
// NetworkError usually means CORS blocked the request - site exists but blocks cross-origin
// This is common for legitimate sites with strict security policies
if (fallbackError.message?.includes('NetworkError') || fallbackError.name === 'TypeError') {
console.log(`[Link Check] NetworkError for ${url}, likely CORS restriction - marking as live`);
result = 'live';
await setCachedResult(url, result, 'linkStatusCache');
return result;
}
// Other errors (DNS errors, truly unreachable) mean the link is dead
console.warn('Link check failed for:', url, fallbackError.message);
result = 'dead';
await setCachedResult(url, result, 'linkStatusCache');
return result;
}
}
};
// Malicious URL/domain database (aggregated from multiple sources)
let maliciousUrlsSet = new Set();
let domainSourceMap = new Map(); // Track which source(s) flagged each domain
let domainOnlyMap = new Map(); // Map of domain:port -> sources (for entries with paths like "1.2.3.4:80/malware")
let blocklistLastUpdate = 0;
let blocklistLoading = false; // Flag to prevent duplicate loads
// Helper to check if two timestamps are on the same calendar day.
function isSameDay(timestamp1, timestamp2) {
if (!timestamp1 || !timestamp2 || timestamp1 === 0 || timestamp2 === 0) return false;
const d1 = new Date(timestamp1);
const d2 = new Date(timestamp2);
return d1.getFullYear() === d2.getFullYear() &&
d1.getMonth() === d2.getMonth() &&
d1.getDate() === d2.getDate();
}
// Blocklist sources - all free, no API keys required
const BLOCKLIST_SOURCES = [
{
name: 'URLhaus (Active)',
// Official abuse.ch list - actively distributing malware URLs (updated every 5 minutes)
// Using cors-anywhere alternative proxy
url: 'https://api.codetabs.com/v1/proxy?quest=' + encodeURIComponent('https://urlhaus.abuse.ch/downloads/text/'),
format: 'urlhaus_text' // Full URLs with paths
},
{
name: 'URLhaus (Historical)',
// Using GitLab Pages CDN mirror with CORS support (updates every 12 hours from abuse.ch)
url: 'https://curbengh.github.io/malware-filter/urlhaus-filter.txt',
format: 'domains' // Domain list (one per line)
},
{
name: 'BlockList Project (Malware)',
url: 'https://blocklistproject.github.io/Lists/malware.txt',
format: 'hosts' // Hosts file format (0.0.0.0 domain.com)
},
{
name: 'BlockList Project (Phishing)',
url: 'https://blocklistproject.github.io/Lists/phishing.txt',
format: 'hosts'
},
{
name: 'BlockList Project (Scam)',
url: 'https://blocklistproject.github.io/Lists/scam.txt',
format: 'hosts'
},
{
name: 'HaGeZi TIF',
url: 'https://cdn.jsdelivr.net/gh/hagezi/dns-blocklists@latest/domains/tif.txt',
format: 'domains' // Plain domain list (one per line)
},
{
name: 'Phishing-Filter',
url: 'https://malware-filter.gitlab.io/malware-filter/phishing-filter-hosts.txt',
format: 'hosts'
},
{
name: 'OISD Big',
// Using GitHub mirror to avoid CORS issues with oisd.nl direct download
url: 'https://raw.githubusercontent.com/sjhgvr/oisd/refs/heads/main/domainswild2_big.txt',
format: 'domains' // Wildcard domains format
},
{
name: 'FMHY Filterlist',
// FMHY unsafe sites list - fake activators, malware distributors, unsafe piracy sites
url: 'https://raw.githubusercontent.com/fmhy/FMHYFilterlist/main/filterlist-basic-domains.txt',
format: 'domains' // Plain domain list (one per line)
},
{
name: 'Dandelion Sprout Anti-Malware',
// Curated anti-malware list - scams, phishing, malware domains
url: 'https://raw.githubusercontent.com/DandelionSprout/adfilt/master/Alternate%20versions%20Anti-Malware%20List/AntiMalwareHosts.txt',
format: 'hosts' // Hosts file format (127.0.0.1 domain.com)
}
];
// Check URL using Google Safe Browsing API (fallback/redundancy check)
// Get a free API key at: https://developers.google.com/safe-browsing/v4/get-started
// Free tier: 10,000 requests per day
// API key is stored in browser.storage.local.googleSafeBrowsingApiKey
const checkGoogleSafeBrowsing = async (url) => {
try {
// Get encrypted API key from storage and decrypt it
const apiKey = await getDecryptedApiKey('googleSafeBrowsingApiKey');
if (!apiKey || apiKey.trim() === '') {
console.log(`[Google SB] API key not configured, skipping`);
return 'unknown';
}
console.log(`[Google SB] Starting check for ${url}`);
const controller = new AbortController();
const timeout = setTimeout(() => controller.abort(), 5000); // 5s timeout
const response = await fetch(
`https://safebrowsing.googleapis.com/v4/threatMatches:find?key=${apiKey}`,
{
method: 'POST',
signal: controller.signal,
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify({
client: {
clientId: 'bookmark-manager-zero',
clientVersion: APP_VERSION
},
threatInfo: {
threatTypes: ['MALWARE', 'SOCIAL_ENGINEERING', 'UNWANTED_SOFTWARE', 'POTENTIALLY_HARMFUL_APPLICATION'],
platformTypes: ['ANY_PLATFORM'],
threatEntryTypes: ['URL'],
threatEntries: [{ url }]
}
})
}
);
clearTimeout(timeout);
if (!response.ok) {
if (response.status === 429) {
console.warn(`[Google SB] Rate limited (429). Check your quota.`);
} else {
console.error(`[Google SB] API error: ${response.status}`);
}
return 'unknown';
}
const data = await response.json();
// If matches found, URL is unsafe
if (data.matches && data.matches.length > 0) {
console.log(`[Google SB] ⚠️ Threat detected:`, data.matches[0].threatType);
return 'unsafe';
}
console.log(`[Google SB] Result: SAFE`);
return 'safe';
} catch (error) {
console.error(`[Google SB] Error:`, error.message);
return 'unknown';
}
};
// ============================================================================
// VIRUSTOTAL SCANNING (WITH RATE LIMITING)
// ============================================================================
// Session-based rate limiting flag for VirusTotal API
// Reset at the start of each scan session
let virusTotalRateLimited = false;
// Check VirusTotal by scraping public web page (no API key needed)
// This always runs on every bookmark scan
// WARNING: For personal use only. May violate VirusTotal ToS if distributed.
const checkURLVoidScraping = async (url) => {
try {
const urlObj = new URL(url);
const hostname = urlObj.hostname.toLowerCase();
console.log(`[URLVoid Scraping] Checking ${hostname}`);
const urlvoidUrl = `https://www.urlvoid.com/scan/${encodeURIComponent(hostname)}/`;
let html = null;
// Try direct fetch first (extensions have elevated privileges)
try {
const controller = new AbortController();
const timeout = setTimeout(() => controller.abort(), 10000);
const response = await fetch(urlvoidUrl, {
signal: controller.signal,
headers: {
'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:91.0) Gecko/20100101 Firefox/91.0'
}
});
clearTimeout(timeout);
if (response.ok) {
html = await response.text();
console.log(`[URLVoid Scraping] Direct fetch succeeded for ${hostname}`);
} else {
console.log(`[URLVoid Scraping] Direct fetch failed: ${response.status}`);
}
} catch (directError) {
console.log(`[URLVoid Scraping] Direct fetch error: ${directError.message}`);
}
// Fallback to CORS proxies if direct fetch failed
if (!html) {
console.log(`[URLVoid Scraping] Trying CORS proxy fallback for ${hostname}`);
const corsProxies = [
`https://corsproxy.io/?${encodeURIComponent(urlvoidUrl)}`,
`https://api.allorigins.win/raw?url=${encodeURIComponent(urlvoidUrl)}`,
`https://api.codetabs.com/v1/proxy?quest=${encodeURIComponent(urlvoidUrl)}`
];
// Race all proxies in parallel
const fetchPromises = corsProxies.map(async (proxiedUrl) => {
const controller = new AbortController();
const timeout = setTimeout(() => controller.abort(), 15000);
try {
const response = await fetch(proxiedUrl, { signal: controller.signal });
clearTimeout(timeout);
if (!response.ok) throw new Error(`HTTP ${response.status}`);
return await response.text();
} catch (error) {
clearTimeout(timeout);
throw error;
}
});
try {
html = await Promise.any(fetchPromises);
console.log(`[URLVoid Scraping] Proxy fallback succeeded for ${hostname}`);
} catch (aggregateError) {
console.log(`[URLVoid Scraping] All proxies failed for ${hostname}`);
return 'unknown';
}
}
const detectedPattern = /detected/gi;
const detectedMatches = html.match(detectedPattern) || [];
const detectedCount = detectedMatches.length;
console.log(`[URLVoid Scraping] ${hostname} - Detected: ${detectedCount}`);
if (detectedCount >= 2) {
return 'unsafe'; // 2 or more scanners detected malicious
} else if (detectedCount === 1) {
return 'warning'; // 1 scanner detected suspicious
} else {
return 'safe'; // No detections
}
} catch (error) {
console.log(`[URLVoid Scraping] Error:`, error.message);
return 'unknown';
}
};
// Check VirusTotal using API v3 (requires API key)
// Get a free API key at: https://www.virustotal.com/
// Free tier: 500 requests/day, 4 requests/minute
// API key is stored in browser.storage.local.virusTotalApiKey
const checkVirusTotal = async (url) => {
try {
// Get encrypted API key from storage and decrypt it
const apiKey = await getDecryptedApiKey('virusTotalApiKey');
if (!apiKey || apiKey.trim() === '') {
console.log(`[VirusTotal API] No API key configured, skipping`);
return 'unknown';
}
// Check if we've hit rate limit this session
if (virusTotalRateLimited) {
console.log(`[VirusTotal API] Rate limited, skipping check for ${url}`);
return 'unknown';
}
console.log(`[VirusTotal API] Starting check for ${url}`);
// Generate URL ID for VirusTotal API (base64url of the URL)
const urlId = btoa(url).replace(/\+/g, '-').replace(/\//g, '_').replace(/=/g, '');
// Try to get existing report first (uses GET endpoint, counts against rate limit)
const reportController = new AbortController();
const reportTimeout = setTimeout(() => reportController.abort(), 8000);
const reportResponse = await fetch(
`https://www.virustotal.com/api/v3/urls/${urlId}`,
{
method: 'GET',
signal: reportController.signal,
headers: {
'x-apikey': apiKey
}
}
);
clearTimeout(reportTimeout);
// Check for rate limiting
if (reportResponse.status === 429) {
console.log(`[VirusTotal API] Rate limit hit (429), will skip remaining checks this session`);
virusTotalRateLimited = true;
return 'unknown';
}
if (!reportResponse.ok) {
console.log(`[VirusTotal API] Failed to get report: ${reportResponse.status}`);
return 'unknown';
}
const reportData = await reportResponse.json();
// Extract analysis stats
const stats = reportData.data?.attributes?.last_analysis_stats;
if (!stats) {
console.log(`[VirusTotal API] No analysis stats available`);
return 'unknown';
}
const malicious = stats.malicious || 0;
const suspicious = stats.suspicious || 0;
console.log(`[VirusTotal API] Analysis stats - Malicious: ${malicious}, Suspicious: ${suspicious}`);
// Determine threat level
if (malicious >= 2) {
return 'unsafe';
}
if (malicious >= 1 || suspicious >= 2) {
return 'warning';
}
return 'safe';
} catch (error) {
if (error.name === 'AbortError') {
console.log(`[VirusTotal API] Request timed out`);
} else {
console.error(`[VirusTotal API] Error:`, error.message);
}
return 'unknown';
}
};
// Check URL using Yandex Safe Browsing API
// Register at: https://yandex.com/dev/
// Free tier: 100,000 requests per day
// API key is stored in browser.storage.local.yandexApiKey
const checkYandexSafeBrowsing = async (url) => {
try {
// Get encrypted API key from storage and decrypt it
const apiKey = await getDecryptedApiKey('yandexApiKey');
if (!apiKey || apiKey.trim() === '') {
console.log(`[Yandex SB] API key not configured, skipping`);
return 'unknown';
}
console.log(`[Yandex SB] Starting check for ${url}`);
const controller = new AbortController();
const timeout = setTimeout(() => controller.abort(), 5000); // 5s timeout
const response = await fetch(
`https://sba.yandex.net/v4/threatMatches:find?key=${apiKey}`,
{
method: 'POST',
signal: controller.signal,
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify({
threatInfo: {
threatTypes: ['MALWARE', 'SOCIAL_ENGINEERING', 'UNWANTED_SOFTWARE'],
platformTypes: ['ANY_PLATFORM'],
threatEntryTypes: ['URL'],
threatEntries: [{ url }]
}
})
}
);
clearTimeout(timeout);