-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcontent.js
More file actions
1023 lines (830 loc) · 30.6 KB
/
content.js
File metadata and controls
1023 lines (830 loc) · 30.6 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
const CONFIG = {
CACHE_DURATION_CLEAN: 7 * 24 * 60 * 60 * 1000,
CACHE_DURATION_SUSPICIOUS: 24 * 60 * 60 * 1000,
DEBOUNCE_DELAY: 500
};
function escapeHtml(text) {
if (text == null) return '';
const div = document.createElement('div');
div.textContent = text;
return div.innerHTML;
}
const DETECTION_PATTERNS = {
ipv4: /\b(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\b/g,
ipv6: /\b(?:[0-9a-fA-F]{1,4}:){7}[0-9a-fA-F]{1,4}\b|\b(?:[0-9a-fA-F]{1,4}:){1,7}:\b|\b(?:[0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}\b|\b::(?:ffff:)?(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\b/gi,
domain: /\b(?:[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?\.)+[a-zA-Z]{2,}\b/g,
md5: /\b[a-fA-F0-9]{32}\b/g,
sha1: /\b[a-fA-F0-9]{40}\b/g,
sha256: /\b[a-fA-F0-9]{64}\b/g
};
const apiCache = new Map();
let currentTooltip = null;
let currentSpan = null;
let hideTooltipTimer = null;
let debounceTimer = null;
const processedNodes = new WeakSet();
let detectedIPsOnPage = new Set();
let highlightingEnabled = true;
// Load highlighting state from storage
chrome.storage.local.get('highlightingEnabled', (result) => {
if (typeof result.highlightingEnabled === 'boolean') {
highlightingEnabled = result.highlightingEnabled;
// Apply state to any already-rendered indicators
const highlightedIndicators = document.querySelectorAll('.vt-indicator');
if (!highlightingEnabled) {
highlightedIndicators.forEach(span => {
span.classList.add('vt-hidden');
});
}
}
});
function shouldIgnoreElement(element) {
if (!element || !element.tagName) return true;
const ignoredTags = ['SCRIPT', 'STYLE', 'NOSCRIPT', 'IFRAME', 'OBJECT', 'EMBED'];
const ignoredClasses = ['vt-tooltip', 'vt-indicator'];
if (ignoredTags.includes(element.tagName)) return true;
let current = element;
while (current) {
if (current.classList && ignoredClasses.some(cls => current.classList.contains(cls))) {
return true;
}
current = current.parentElement;
}
return false;
}
function extractIndicators(text) {
const indicators = [];
// Extract IPv4
const ipv4Matches = text.match(DETECTION_PATTERNS.ipv4);
if (ipv4Matches) {
ipv4Matches.forEach(ip => {
if (!isPrivateIP(ip) && !isReservedIP(ip)) {
indicators.push({ value: ip, type: 'ip' });
}
});
}
// Extract IPv6
const ipv6Matches = text.match(DETECTION_PATTERNS.ipv6);
if (ipv6Matches) {
ipv6Matches.forEach(ip => {
indicators.push({ value: ip, type: 'ip' });
});
}
// Extract domains (filter out common false positives)
const domainMatches = text.match(DETECTION_PATTERNS.domain);
if (domainMatches) {
domainMatches.forEach(domain => {
// Skip if it's part of an email or common file extensions
if (!isCommonFileExtension(domain) && !text.includes(`@${domain}`)) {
indicators.push({ value: domain.toLowerCase(), type: 'domain' });
}
});
}
// Extract MD5 hashes
const md5Matches = text.match(DETECTION_PATTERNS.md5);
if (md5Matches) {
md5Matches.forEach(hash => {
indicators.push({ value: hash.toLowerCase(), type: 'hash' });
});
}
// Extract SHA1 hashes
const sha1Matches = text.match(DETECTION_PATTERNS.sha1);
if (sha1Matches) {
sha1Matches.forEach(hash => {
indicators.push({ value: hash.toLowerCase(), type: 'hash' });
});
}
// Extract SHA256 hashes
const sha256Matches = text.match(DETECTION_PATTERNS.sha256);
if (sha256Matches) {
sha256Matches.forEach(hash => {
indicators.push({ value: hash.toLowerCase(), type: 'hash' });
});
}
return indicators;
}
function isCommonFileExtension(domain) {
const commonExtensions = ['jpg', 'jpeg', 'png', 'gif', 'pdf', 'doc', 'docx', 'xls', 'xlsx', 'txt', 'zip', 'rar', 'exe', 'dll', 'css', 'js', 'json', 'xml', 'svg', 'mp3', 'mp4', 'avi', 'mov'];
const parts = domain.split('.');
return parts.length === 2 && commonExtensions.includes(parts[1].toLowerCase());
}
function isPrivateIP(ip) {
const parts = ip.split('.').map(Number);
// 10.0.0.0/8
if (parts[0] === 10) return true;
// 172.16.0.0/12
if (parts[0] === 172 && parts[1] >= 16 && parts[1] <= 31) return true;
// 192.168.0.0/16
if (parts[0] === 192 && parts[1] === 168) return true;
// 127.0.0.0/8 (localhost)
if (parts[0] === 127) return true;
return false;
}
function isReservedIP(ip) {
const parts = ip.split('.').map(Number);
// 0.0.0.0/8
if (parts[0] === 0) return true;
// 255.255.255.255
if (parts.every(p => p === 255)) return true;
// 224.0.0.0/4 (multicast)
if (parts[0] >= 224 && parts[0] <= 239) return true;
// 240.0.0.0/4 (reserved)
if (parts[0] >= 240) return true;
return false;
}
function highlightIndicatorsInTextNode(textNode) {
if (!textNode || textNode.nodeType !== Node.TEXT_NODE) return;
if (processedNodes.has(textNode)) return;
if (shouldIgnoreElement(textNode.parentElement)) return;
const text = textNode.textContent;
const allMatches = [];
// Find all IPv4 addresses
let match;
const ipv4Regex = new RegExp(DETECTION_PATTERNS.ipv4.source, 'g');
while ((match = ipv4Regex.exec(text)) !== null) {
const ip = match[0];
if (!isPrivateIP(ip) && !isReservedIP(ip)) {
allMatches.push({ value: ip, type: 'ip', index: match.index, length: ip.length });
}
}
// Find all IPv6 addresses
const ipv6Regex = new RegExp(DETECTION_PATTERNS.ipv6.source, 'gi');
while ((match = ipv6Regex.exec(text)) !== null) {
allMatches.push({ value: match[0], type: 'ip', index: match.index, length: match[0].length });
}
// Find all domains
const domainRegex = new RegExp(DETECTION_PATTERNS.domain.source, 'g');
while ((match = domainRegex.exec(text)) !== null) {
const domain = match[0];
if (!isCommonFileExtension(domain) && !text.substring(Math.max(0, match.index - 1), match.index).includes('@')) {
allMatches.push({ value: domain.toLowerCase(), type: 'domain', index: match.index, length: domain.length });
}
}
// Find all MD5 hashes
const md5Regex = new RegExp(DETECTION_PATTERNS.md5.source, 'g');
while ((match = md5Regex.exec(text)) !== null) {
allMatches.push({ value: match[0].toLowerCase(), type: 'hash', index: match.index, length: match[0].length });
}
// Find all SHA1 hashes
const sha1Regex = new RegExp(DETECTION_PATTERNS.sha1.source, 'g');
while ((match = sha1Regex.exec(text)) !== null) {
allMatches.push({ value: match[0].toLowerCase(), type: 'hash', index: match.index, length: match[0].length });
}
// Find all SHA256 hashes
const sha256Regex = new RegExp(DETECTION_PATTERNS.sha256.source, 'g');
while ((match = sha256Regex.exec(text)) !== null) {
allMatches.push({ value: match[0].toLowerCase(), type: 'hash', index: match.index, length: match[0].length });
}
if (allMatches.length === 0) {
processedNodes.add(textNode);
return;
}
// Sort by index and remove overlapping matches
allMatches.sort((a, b) => a.index - b.index);
const filteredMatches = [];
let lastEnd = 0;
for (const match of allMatches) {
if (match.index >= lastEnd) {
filteredMatches.push(match);
lastEnd = match.index + match.length;
}
}
const fragment = document.createDocumentFragment();
let lastIndex = 0;
filteredMatches.forEach(({ value, type, index, length }) => {
if (index > lastIndex) {
fragment.appendChild(document.createTextNode(text.substring(lastIndex, index)));
}
detectedIPsOnPage.add(value);
const span = document.createElement('span');
span.className = 'vt-indicator';
span.textContent = text.substring(index, index + length);
span.dataset.value = value;
span.dataset.type = type;
// Apply highlighting state
if (!highlightingEnabled) {
span.classList.add('vt-hidden');
}
span.addEventListener('mouseenter', handleIndicatorHover);
span.addEventListener('mouseleave', handleIndicatorLeave);
span.addEventListener('click', handleIndicatorClick);
fragment.appendChild(span);
// Apply cached styling if available
applyCachedStyling(span, value, type);
lastIndex = index + length;
});
if (lastIndex < text.length) {
fragment.appendChild(document.createTextNode(text.substring(lastIndex)));
}
textNode.parentNode.replaceChild(fragment, textNode);
processedNodes.add(textNode);
updateBadgeCount();
}
async function applyCachedStyling(span, value, type) {
// Check if we have cached data
const cacheKey = `${type}_${value}`;
const memCached = apiCache.get(cacheKey);
if (memCached && !isCacheExpired(memCached)) {
updateSpanClass(span, memCached.data);
return;
}
// Check persistent storage cache
try {
const storageKey = `${type}data_${value}`;
const result = await chrome.storage.local.get(storageKey);
const storageCached = result[storageKey];
if (storageCached && !isCacheExpired(storageCached)) {
// Restore to memory cache
apiCache.set(cacheKey, storageCached);
updateSpanClass(span, storageCached.data);
}
} catch (error) {
// Silently fail - styling will be applied on hover
}
}
function isCacheExpired(cacheEntry) {
return Date.now() > cacheEntry.expiresAt;
}
function scanElement(element) {
if (shouldIgnoreElement(element)) return;
const walker = document.createTreeWalker(
element,
NodeFilter.SHOW_TEXT,
{
acceptNode: (node) => {
if (shouldIgnoreElement(node.parentElement)) {
return NodeFilter.FILTER_REJECT;
}
return NodeFilter.FILTER_ACCEPT;
}
}
);
const textNodes = [];
let node;
while (node = walker.nextNode()) {
textNodes.push(node);
}
textNodes.forEach(highlightIndicatorsInTextNode);
}
function updateBadgeCount() {
const count = detectedIPsOnPage.size;
chrome.runtime.sendMessage({
action: 'updateBadge',
count: count
});
}
function handleIndicatorClick(event) {
if (event.altKey) {
event.preventDefault();
const value = event.target.dataset.value;
if (value) {
// Copy to clipboard
navigator.clipboard.writeText(value).then(() => {
showCopyFeedback(event.target);
}).catch(err => {
console.error('Failed to copy:', err);
});
}
}
}
function showCopyFeedback(element) {
// Store original content
const originalText = element.textContent;
// Show "Copied!" message
element.textContent = '✓ Copied!';
element.style.fontWeight = 'bold';
// Restore after delay
setTimeout(() => {
element.textContent = originalText;
element.style.fontWeight = '';
}, 1000);
}
async function handleIndicatorHover(event) {
const span = event.target;
const value = span.dataset.value;
const type = span.dataset.type;
if (!value || !type) return;
// Cancel any pending hide
if (hideTooltipTimer) {
clearTimeout(hideTooltipTimer);
hideTooltipTimer = null;
}
// If we're already showing a tooltip for this indicator, don't recreate it
if (currentSpan === span && currentTooltip && currentTooltip.parentNode) {
return;
}
if (currentTooltip) {
// Immediate cleanup without animation
if (currentTooltip.parentNode) {
currentTooltip.removeEventListener('mouseenter', handleTooltipMouseEnter);
currentTooltip.removeEventListener('mouseleave', handleTooltipMouseLeave);
currentTooltip.parentNode.removeChild(currentTooltip);
}
currentTooltip = null;
}
// Store current span reference
currentSpan = span;
// Add loading class
span.classList.add('loading');
// Create and show tooltip
showTooltip(span, value, type);
// Fetch data
try {
const data = await fetchIndicatorData(value, type);
// Only update if this is still the current span
if (currentSpan === span) {
updateTooltipWithData(value, type, data);
updateSpanClass(span, data);
}
} catch (error) {
console.error('Error fetching indicator data:', error);
// Only update if this is still the current span
if (currentSpan === span) {
updateTooltipWithError(value, type, error.message);
}
} finally {
span.classList.remove('loading');
}
}
function handleIndicatorLeave(event) {
// Delay hiding to allow moving to tooltip
hideTooltipTimer = setTimeout(() => {
if (!isMouseOverTooltip()) {
hideTooltip();
}
}, 200);
}
function isMouseOverTooltip() {
if (!currentTooltip) return false;
return currentTooltip.matches(':hover');
}
function handleTooltipMouseEnter() {
if (hideTooltipTimer) {
clearTimeout(hideTooltipTimer);
hideTooltipTimer = null;
}
}
function handleTooltipMouseLeave() {
hideTooltipTimer = setTimeout(() => {
hideTooltip();
}, 100);
}
async function fetchIndicatorData(value, type) {
const cacheKey = `${type}_${value}`;
// Check in-memory cache first
const memCached = apiCache.get(cacheKey);
if (memCached && !isCacheExpired(memCached)) {
return memCached.data;
}
// Check persistent storage cache
try {
const storageKey = `${type}data_${value}`;
const result = await chrome.storage.local.get(storageKey);
const storageCached = result[storageKey];
if (storageCached && !isCacheExpired(storageCached)) {
// Restore to memory cache
apiCache.set(cacheKey, storageCached);
return storageCached.data;
}
} catch (error) {
console.warn('VirusTotal Add-on: Storage cache check failed:', error);
}
// Fetch from API via background service worker (to avoid CORS)
return new Promise((resolve, reject) => {
chrome.runtime.sendMessage(
{ action: 'fetchIndicatorData', value: value, type: type },
(response) => {
if (chrome.runtime.lastError) {
reject(new Error(chrome.runtime.lastError.message));
return;
}
if (response.success) {
// Determine cache duration based on reputation
const maliciousCount = response.data.data?.attributes?.last_analysis_stats?.malicious || 0;
const suspiciousCount = response.data.data?.attributes?.last_analysis_stats?.suspicious || 0;
const isClean = maliciousCount === 0 && suspiciousCount === 0;
const cacheDuration = isClean ? CONFIG.CACHE_DURATION_CLEAN : CONFIG.CACHE_DURATION_SUSPICIOUS;
const cacheEntry = {
data: response.data,
timestamp: Date.now(),
expiresAt: Date.now() + cacheDuration,
isClean: isClean
};
// Cache in memory
apiCache.set(cacheKey, cacheEntry);
// Cache in persistent storage
try {
const storageKey = `${type}data_${value}`;
chrome.storage.local.set({ [storageKey]: cacheEntry });
} catch (error) {
console.warn('VirusTotal Add-on: Storage cache save failed:', error);
}
resolve(response.data);
} else {
reject(new Error(response.error));
}
}
);
});
}
function showTooltip(element, value, type) {
// Create tooltip
const tooltip = document.createElement('div');
tooltip.className = 'vt-tooltip';
const typeLabel = type === 'ip' ? 'IP Address' : type === 'domain' ? 'Domain' : 'File Hash';
tooltip.innerHTML = `
<div class="vt-tooltip-header">
<span class="vt-tooltip-ip">${escapeHtml(value)}</span>
</div>
<div class="vt-tooltip-body">
<p class="vt-loading-text">Loading security data...</p>
<p style="font-size: 11px; color: #999; margin-top: 4px;">${typeLabel}</p>
</div>
`;
// Add mouse events to keep tooltip visible
tooltip.addEventListener('mouseenter', handleTooltipMouseEnter);
tooltip.addEventListener('mouseleave', handleTooltipMouseLeave);
document.body.appendChild(tooltip);
currentTooltip = tooltip;
// Position tooltip (use setTimeout to ensure browser has calculated dimensions)
setTimeout(() => {
positionTooltip(element, tooltip);
// Make visible with animation
tooltip.classList.add('visible');
}, 10);
}
function positionTooltip(element, tooltip) {
const rect = element.getBoundingClientRect();
// Force a reflow to ensure tooltip dimensions are calculated
tooltip.offsetHeight;
const tooltipRect = tooltip.getBoundingClientRect();
const scrollX = window.scrollX || window.pageXOffset;
const scrollY = window.scrollY || window.pageYOffset;
const viewportWidth = window.innerWidth;
const viewportHeight = window.innerHeight;
const spacing = 8; // Space between element and tooltip
const edgePadding = 10; // Padding from viewport edges
// Calculate available space in all 4 directions
const spaceAbove = rect.top;
const spaceBelow = viewportHeight - rect.bottom;
const spaceLeft = rect.left;
const spaceRight = viewportWidth - rect.right;
let top, left;
let position = 'bottom'; // default
// Determine best position based on available space
// Priority: bottom > top > right > left (but choose based on space)
if (spaceBelow >= tooltipRect.height + spacing + edgePadding) {
// Position below (default)
position = 'bottom';
top = rect.bottom + scrollY + spacing;
left = rect.left + scrollX;
} else if (spaceAbove >= tooltipRect.height + spacing + edgePadding) {
// Position above
position = 'top';
top = rect.top + scrollY - tooltipRect.height - spacing;
left = rect.left + scrollX;
} else if (spaceRight >= tooltipRect.width + spacing + edgePadding) {
// Position to the right
position = 'right';
top = rect.top + scrollY;
left = rect.right + scrollX + spacing;
} else if (spaceLeft >= tooltipRect.width + spacing + edgePadding) {
// Position to the left
position = 'left';
top = rect.top + scrollY;
left = rect.left + scrollX - tooltipRect.width - spacing;
} else {
// Not enough space anywhere, use the side with most space
const maxSpace = Math.max(spaceAbove, spaceBelow, spaceLeft, spaceRight);
if (maxSpace === spaceBelow) {
position = 'bottom';
top = rect.bottom + scrollY + spacing;
left = rect.left + scrollX;
} else if (maxSpace === spaceAbove) {
position = 'top';
top = rect.top + scrollY - tooltipRect.height - spacing;
left = rect.left + scrollX;
} else if (maxSpace === spaceRight) {
position = 'right';
top = rect.top + scrollY;
left = rect.right + scrollX + spacing;
} else {
position = 'left';
top = rect.top + scrollY;
left = rect.left + scrollX - tooltipRect.width - spacing;
}
}
// Adjust horizontal position to keep tooltip in viewport
if (position === 'top' || position === 'bottom') {
// Center tooltip on element if possible
left = rect.left + scrollX + (rect.width / 2) - (tooltipRect.width / 2);
// Keep within viewport bounds
if (left < scrollX + edgePadding) {
left = scrollX + edgePadding;
} else if (left + tooltipRect.width > scrollX + viewportWidth - edgePadding) {
left = scrollX + viewportWidth - tooltipRect.width - edgePadding;
}
}
// Adjust vertical position to keep tooltip in viewport
if (position === 'left' || position === 'right') {
// Center tooltip vertically on element if possible
top = rect.top + scrollY + (rect.height / 2) - (tooltipRect.height / 2);
// Keep within viewport bounds
if (top < scrollY + edgePadding) {
top = scrollY + edgePadding;
} else if (top + tooltipRect.height > scrollY + viewportHeight - edgePadding) {
top = scrollY + viewportHeight - tooltipRect.height - edgePadding;
}
}
tooltip.style.top = `${top}px`;
tooltip.style.left = `${left}px`;
}
function updateTooltipWithData(value, type, apiData) {
if (!currentTooltip || !currentSpan) return;
const data = apiData.data.attributes;
const stats = data.last_analysis_stats || {};
const malicious = stats.malicious || 0;
const suspicious = stats.suspicious || 0;
const harmless = stats.harmless || 0;
const undetected = stats.undetected || 0;
const total = malicious + suspicious + harmless + undetected;
let reputation = 'clean';
let reputationText = 'Clean';
if (malicious > 0) {
reputation = 'malicious';
reputationText = 'Malicious';
} else if (suspicious > 0) {
reputation = 'suspicious';
reputationText = 'Suspicious';
}
let additionalInfo = '';
let vtUrl = '';
if (type === 'ip') {
const country = escapeHtml(data.country || 'Unknown');
const asOwner = escapeHtml(data.as_owner || 'Unknown');
const asn = escapeHtml(data.asn ? String(data.asn) : 'N/A');
additionalInfo = `
<div class="vt-info-row">
<span class="vt-info-label">Country:</span>
<span class="vt-info-value">${country}</span>
</div>
<div class="vt-info-row">
<span class="vt-info-label">Owner:</span>
<span class="vt-info-value">${asOwner}</span>
</div>
<div class="vt-info-row">
<span class="vt-info-label">ASN:</span>
<span class="vt-info-value">${asn}</span>
</div>
`;
vtUrl = `https://www.virustotal.com/gui/ip-address/${encodeURIComponent(value)}`;
} else if (type === 'domain') {
const categories = data.categories ? Object.values(data.categories).join(', ') : 'Unknown';
const lastUpdate = data.last_modification_date ? new Date(data.last_modification_date * 1000).toLocaleDateString() : 'Unknown';
additionalInfo = `
<div class="vt-info-row">
<span class="vt-info-label">Category:</span>
<span class="vt-info-value">${escapeHtml(categories)}</span>
</div>
<div class="vt-info-row">
<span class="vt-info-label">Last Updated:</span>
<span class="vt-info-value">${lastUpdate}</span>
</div>
`;
vtUrl = `https://www.virustotal.com/gui/domain/${encodeURIComponent(value)}`;
} else if (type === 'hash') {
const fileName = escapeHtml(data.meaningful_name || data.names?.[0] || 'Unknown');
const fileType = escapeHtml(data.type_description || 'Unknown');
additionalInfo = `
<div class="vt-info-row">
<span class="vt-info-label">File Name:</span>
<span class="vt-info-value">${fileName}</span>
</div>
<div class="vt-info-row">
<span class="vt-info-label">File Type:</span>
<span class="vt-info-value">${fileType}</span>
</div>
`;
vtUrl = `https://www.virustotal.com/gui/file/${encodeURIComponent(value)}`;
}
currentTooltip.innerHTML = `
<div class="vt-tooltip-header">
<span class="vt-tooltip-ip">${escapeHtml(value)}</span>
<span class="vt-reputation-badge ${reputation}">${reputationText}</span>
</div>
<div class="vt-tooltip-body">
<div class="vt-info-row">
<span class="vt-info-label">Detection:</span>
<span class="vt-info-value">${malicious}/${total} vendors flagged</span>
</div>
${additionalInfo}
</div>
<div class="vt-tooltip-footer">
<a href="${vtUrl}" target="_blank" class="vt-tooltip-link">
View full report on VirusTotal →
</a>
<div style="margin-top: 8px; font-size: 11px; color: #999;">
<span>💡 Alt+Click to copy</span>
</div>
</div>
`;
currentTooltip.addEventListener('mouseenter', handleTooltipMouseEnter);
currentTooltip.addEventListener('mouseleave', handleTooltipMouseLeave);
positionTooltip(currentSpan, currentTooltip);
}
function updateTooltipWithError(value, type, errorMessage) {
if (!currentTooltip || !currentSpan) return;
const typeLabel = type === 'ip' ? 'IP' : type === 'domain' ? 'domain' : 'hash';
currentTooltip.innerHTML = `
<div class="vt-tooltip-header">
<span class="vt-tooltip-ip">${escapeHtml(value)}</span>
</div>
<div class="vt-tooltip-body">
<p class="vt-error-text">Error: ${escapeHtml(errorMessage)}</p>
<p style="font-size: 11px; color: #666; margin-top: 8px;">
The ${typeLabel} data could not be retrieved. Please try again later.
</p>
</div>
`;
currentTooltip.addEventListener('mouseenter', handleTooltipMouseEnter);
currentTooltip.addEventListener('mouseleave', handleTooltipMouseLeave);
positionTooltip(currentSpan, currentTooltip);
}
function updateSpanClass(span, apiData) {
const stats = apiData.data.attributes.last_analysis_stats || {};
const malicious = stats.malicious || 0;
const suspicious = stats.suspicious || 0;
if (malicious > 0) {
span.classList.add('malicious');
} else if (suspicious > 0) {
span.classList.add('suspicious');
} else {
span.classList.add('clean');
}
}
function hideTooltip() {
if (hideTooltipTimer) {
clearTimeout(hideTooltipTimer);
hideTooltipTimer = null;
}
if (currentTooltip) {
// Remove event listeners to prevent memory leaks
currentTooltip.removeEventListener('mouseenter', handleTooltipMouseEnter);
currentTooltip.removeEventListener('mouseleave', handleTooltipMouseLeave);
currentTooltip.classList.remove('visible');
// Use a local reference to avoid race conditions
const tooltipToRemove = currentTooltip;
currentTooltip = null;
setTimeout(() => {
if (tooltipToRemove && tooltipToRemove.parentNode) {
tooltipToRemove.parentNode.removeChild(tooltipToRemove);
}
}, 200);
}
currentSpan = null;
}
function handleMutations(mutations) {
// Clear existing timer
if (debounceTimer) {
clearTimeout(debounceTimer);
}
// Debounce the processing
debounceTimer = setTimeout(() => {
const nodesToProcess = new Set();
mutations.forEach(mutation => {
// Handle added nodes
mutation.addedNodes.forEach(node => {
nodesToProcess.add(node);
});
// Handle character data changes (text content updates)
if (mutation.type === 'characterData' && mutation.target.nodeType === Node.TEXT_NODE) {
// Clear the processed flag so it gets rescanned
processedNodes.delete(mutation.target);
nodesToProcess.add(mutation.target);
}
// Handle attribute changes that might indicate content updates
if (mutation.type === 'attributes' && mutation.target.nodeType === Node.ELEMENT_NODE) {
// Re-scan the element in case its content changed
nodesToProcess.add(mutation.target);
}
});
// Process all collected nodes
nodesToProcess.forEach(node => {
if (node.nodeType === Node.ELEMENT_NODE) {
scanElement(node);
} else if (node.nodeType === Node.TEXT_NODE) {
highlightIndicatorsInTextNode(node);
}
});
}, CONFIG.DEBOUNCE_DELAY);
}
function init() {
cleanupExpiredCache();
// Scan the initial page
scanElement(document.body);
// Set up MutationObserver for dynamic content with comprehensive options
const observer = new MutationObserver(handleMutations);
observer.observe(document.body, {
childList: true, // Watch for added/removed nodes
subtree: true, // Watch all descendants
characterData: true, // Watch for text content changes
characterDataOldValue: false,
attributes: true, // Watch for attribute changes
attributeFilter: ['class', 'style', 'data-value'], // Only watch specific attributes to reduce noise
attributeOldValue: false
});
// Additional safeguard: periodic re-scan for SPAs with heavy virtual scrolling
// This catches cases where mutations might be missed
let lastScrollY = window.scrollY;
let scrollCheckTimer = null;
window.addEventListener('scroll', () => {
// Only re-scan if scroll position changed significantly (more than viewport height)
const scrollDelta = Math.abs(window.scrollY - lastScrollY);
if (scrollDelta > window.innerHeight * 0.5) {
lastScrollY = window.scrollY;
// Clear existing timer
if (scrollCheckTimer) {
clearTimeout(scrollCheckTimer);
}
// Debounce the re-scan
scrollCheckTimer = setTimeout(() => {
// Get visible viewport area
const viewportTop = window.scrollY;
const viewportBottom = viewportTop + window.innerHeight;
// Find all elements in viewport that might have been updated
const elementsInViewport = document.elementsFromPoint(
window.innerWidth / 2,
window.innerHeight / 2
);
elementsInViewport.forEach(element => {
if (!shouldIgnoreElement(element)) {
// Scan for any new text nodes that weren't processed
const walker = document.createTreeWalker(
element,
NodeFilter.SHOW_TEXT,
{
acceptNode: (node) => {
if (shouldIgnoreElement(node.parentElement) || processedNodes.has(node)) {
return NodeFilter.FILTER_REJECT;
}
return NodeFilter.FILTER_ACCEPT;
}
}
);
const textNodes = [];
let node;
while (node = walker.nextNode()) {
textNodes.push(node);
}
textNodes.forEach(highlightIndicatorsInTextNode);
}
});
}, 300);
}
}, { passive: true });
}
// Listen for messages from popup
chrome.runtime.onMessage.addListener((request, sender, sendResponse) => {
if (request.action === 'toggleHighlighting') {
highlightingEnabled = request.enabled;
// Save state to storage
chrome.storage.local.set({ highlightingEnabled: highlightingEnabled });
const highlightedIndicators = document.querySelectorAll('.vt-indicator');
if (highlightingEnabled) {
highlightedIndicators.forEach(span => {
span.classList.remove('vt-hidden');
});
} else {
highlightedIndicators.forEach(span => {
span.classList.add('vt-hidden');
});
}
sendResponse({ success: true });
} else if (request.action === 'getHighlightingState') {
sendResponse({ enabled: highlightingEnabled });
}
return true;
});
async function cleanupExpiredCache() {
try {
const allData = await chrome.storage.local.get(null);