-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathpopup.js
More file actions
2080 lines (1745 loc) · 70.9 KB
/
popup.js
File metadata and controls
2080 lines (1745 loc) · 70.9 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
console.log("popup.js loaded");
// More aggressive approach to disable analytics - define before any imports
if (typeof window !== 'undefined') {
window.SCREENPIPE_CONFIG = {
disableAnalytics: true,
disableSSE: true,
disablePostHog: true,
disableReporting: true,
disableErrorLogging: true,
disable_external_dependency_loading: true
};
// Block analytics/PostHog requests at fetch level
const origFetch = window.fetch;
window.fetch = function(url, ...args) {
if (typeof url === 'string' && (
url.includes('posthog.com') ||
url.includes('analytics') ||
url.includes('telemetry')
)) {
console.log('Blocked analytics/PostHog request:', url);
return Promise.resolve(new Response('{}', {status: 200}));
}
return origFetch.apply(this, [url, ...args]);
};
}
// Import modules - after analytics blocking
const screenpipe = require('@screenpipe/browser');
// --- PATCH PostHog/Screenpipe analytics loader to prevent CSP errors ---
if (window && window.__PosthogExtensions__ && typeof window.__PosthogExtensions__.loadExternalDependency === 'function') {
window.__PosthogExtensions__.loadExternalDependency = function(instance, script, cb) {
// Prevent loading any external analytics scripts
if (typeof cb === 'function') cb("Blocked by extension CSP patch");
};
}
// --- PATCH Screenpipe SDK to block remote config and SSE ---
if (screenpipe && screenpipe.pipe) {
// Patch any method that tries to load remote config or analytics
if (screenpipe.pipe.initAnalyticsIfNeeded) {
screenpipe.pipe.initAnalyticsIfNeeded = async () => {
// No-op: always return analytics disabled
return { analyticsEnabled: false, userId: undefined, email: undefined };
};
}
if (screenpipe.pipe._loadRemoteConfigJs) {
screenpipe.pipe._loadRemoteConfigJs = () => {};
}
if (screenpipe.pipe._loadRemoteConfigJSON) {
screenpipe.pipe._loadRemoteConfigJSON = () => {};
}
if (screenpipe.pipe._loadSSESettings) {
screenpipe.pipe._loadSSESettings = () => {};
}
}
// Cache for screen data
let cachedScreenData = null;
// Global variables for real-time scanning
let autoScanEnabled = true;
let scanInterval = 10; // minutes
let notificationsEnabled = true;
let notifyThreshold = 'high';
let nextScanTimeoutId = null;
let historyRetention = 30; // days
// Cache for scan history
let scanHistory = [];
document.addEventListener('DOMContentLoaded', async function() {
// Initialize tabs
initTabs();
// Get site information for the current tab
await getSiteInfo();
// Setup event listeners
setupEventListeners();
// Load API key from storage
loadApiKey();
// Initialize security analysis
initSecurityAnalysis();
// Set default content type from settings (original functionality)
try {
const { defaultContentType } = await chrome.storage.sync.get(['defaultContentType']);
if (defaultContentType) {
document.getElementById("contentType").value = defaultContentType;
}
} catch (error) {
console.error('Failed to load default content type:', error);
}
// Check that background script is responsive (original functionality)
chrome.runtime.sendMessage({ action: "ping" }, response => {
console.log("Background status:", response?.status || "No response");
});
// Load scan settings
loadScanSettings();
// Initialize auto scanning if enabled
if (autoScanEnabled) {
scheduleNextScan();
}
// Load scan history
await loadScanHistory();
// Initialize Link Markers UI
initLinkMarkersUI();
// Add event listeners for Link Markers
addLinkMarkerEventListeners();
// Initialize toggle switches
initializeToggleSwitches();
// Add event listener for save button
const saveSettingsBtn = document.getElementById('saveSettings');
if (saveSettingsBtn) {
saveSettingsBtn.addEventListener('click', saveAllSettings);
}
});
// Tab functionality
function initTabs() {
const tabButtons = document.querySelectorAll('.tab-btn');
const tabPanes = document.querySelectorAll('.tab-pane');
tabButtons.forEach(button => {
button.addEventListener('click', () => {
// Remove active class from all buttons and panes
tabButtons.forEach(btn => btn.classList.remove('active'));
tabPanes.forEach(pane => pane.classList.remove('active'));
// Add active class to clicked button and corresponding pane
button.classList.add('active');
const tabId = button.dataset.tab;
document.getElementById(tabId).classList.add('active');
});
});
}
// Get current site information
async function getSiteInfo() {
try {
const tabs = await chrome.tabs.query({ active: true, currentWindow: true });
const currentTab = tabs[0];
// Update site name and URL
document.getElementById('site-name').textContent = currentTab.title || 'Unknown Site';
document.getElementById('site-url').textContent = currentTab.url || 'Unknown URL';
// Get and display favicon
const faviconUrl = currentTab.favIconUrl || 'icons/globe.png';
document.getElementById('site-icon').src = faviconUrl;
// Store current URL for later use
window.currentUrl = currentTab.url;
} catch (error) {
console.error('Error getting site info:', error);
}
}
// Setup event listeners
function setupEventListeners() {
// Save API key button
const saveApiKeyBtn = document.getElementById('save-api-key');
if (saveApiKeyBtn) {
saveApiKeyBtn.addEventListener('click', saveApiKey);
}
// Chat input and send button
const chatInput = document.getElementById('chat-input');
const sendBtn = document.getElementById('send-btn');
if (chatInput && sendBtn) {
sendBtn.addEventListener('click', () => handleChatInput(chatInput.value));
chatInput.addEventListener('keydown', (e) => {
if (e.key === 'Enter') {
handleChatInput(chatInput.value);
}
});
}
// Original functionality - Fetch data button handler
const fetchDataBtn = document.getElementById("fetchData");
if (fetchDataBtn) {
fetchDataBtn.addEventListener("click", fetchScreenData);
}
// Original functionality - Display captured content button
const displayContentBtn = document.getElementById("displayContent");
if (displayContentBtn) {
displayContentBtn.addEventListener("click", displayScreenContent);
}
// Original functionality - Filter content button handler
const filterContentBtn = document.getElementById("filterContent");
if (filterContentBtn) {
filterContentBtn.addEventListener("click", filterContent);
}
// Original functionality - Settings link handler
const openSettingsBtn = document.getElementById("openSettings");
if (openSettingsBtn) {
openSettingsBtn.addEventListener("click", () => {
// Show the settings tab
const tabButtons = document.querySelectorAll('.tab-btn');
const tabPanes = document.querySelectorAll('.tab-pane');
tabButtons.forEach(btn => btn.classList.remove('active'));
tabPanes.forEach(pane => pane.classList.remove('active'));
const settingsPane = document.getElementById('settings');
if (settingsPane) {
settingsPane.classList.add('active');
}
});
}
// Real-time tab event handlers
const analyzeDataBtn = document.getElementById('analyzeData');
if (analyzeDataBtn) {
analyzeDataBtn.addEventListener('click', analyzeScreenData);
}
// History tab event handlers
const refreshHistoryBtn = document.getElementById('refreshHistory');
if (refreshHistoryBtn) {
refreshHistoryBtn.addEventListener('click', refreshScanHistory);
}
const historyPeriodSelect = document.getElementById('historyPeriod');
if (historyPeriodSelect) {
historyPeriodSelect.addEventListener('change', filterScanHistory);
}
// Settings tab event handlers
const saveSettingsBtn = document.getElementById('saveSettings');
if (saveSettingsBtn) {
saveSettingsBtn.addEventListener('click', saveScanSettings);
}
const enableAutoScanToggle = document.getElementById('enableAutoScan');
if (enableAutoScanToggle) {
enableAutoScanToggle.addEventListener('change', function() {
const scanIntervalSelect = document.getElementById('scanInterval');
if (scanIntervalSelect) {
scanIntervalSelect.disabled = !this.checked;
}
});
}
const clearHistoryBtn = document.getElementById('clearHistory');
if (clearHistoryBtn) {
clearHistoryBtn.addEventListener('click', clearScanHistory);
}
const saveGroqApiKeyBtn = document.getElementById('saveGroqApiKey');
if (saveGroqApiKeyBtn) {
saveGroqApiKeyBtn.addEventListener('click', saveGroqApiKey);
}
}
// Handle chat input
async function handleChatInput(message) {
if (!message.trim()) return;
const chatInput = document.getElementById('chat-input');
const chatMessages = document.getElementById('chat-messages');
// Clear input
chatInput.value = '';
// Add user message to chat
addMessageToChat('user', message);
// Show loading indicator
const assistantMessage = addMessageToChat('assistant', '...');
try {
// Get API key from storage
const apiKey = await getApiKey();
if (!apiKey) {
updateAssistantMessage(assistantMessage, 'Please add your Groq API key in the settings below.');
return;
}
// Get current URL context
const currentUrlContext = `This question is about the website: ${window.currentUrl}`;
const securityContext = generateSecurityContext();
// Send to Groq API
const response = await queryGroqAPI(message, apiKey, currentUrlContext, securityContext);
// Update assistant message with response
updateAssistantMessage(assistantMessage, response);
} catch (error) {
console.error('Error processing message:', error);
updateAssistantMessage(assistantMessage, 'Sorry, there was an error processing your request.');
}
}
// Generate security context based on current analysis
function generateSecurityContext() {
const connectionStatusEl = document.querySelector('#connection-status .value');
const sslStatusEl = document.querySelector('#ssl-status .value');
const riskScoreEl = document.querySelector('#risk-score .value');
const securityHeadersEl = document.querySelector('#security-headers .value');
const vendorRatingsEl = document.querySelector('#vendor-ratings .value');
const securityScoreEl = document.getElementById('security-score-value');
const connectionStatus = connectionStatusEl ? connectionStatusEl.textContent : 'Unknown';
const sslStatus = sslStatusEl ? sslStatusEl.textContent : 'Unknown';
const riskScore = riskScoreEl ? riskScoreEl.textContent : 'Unknown';
const securityHeaders = securityHeadersEl ? securityHeadersEl.textContent : 'Unknown';
const vendorRatings = vendorRatingsEl ? vendorRatingsEl.textContent : 'Unknown';
const securityScore = securityScoreEl ? securityScoreEl.textContent : 'Unknown';
return `Security analysis of this website:
Connection: ${connectionStatus}
SSL/TLS: ${sslStatus}
Risk Score: ${riskScore}
Security Headers: ${securityHeaders}
Vendor Ratings: ${vendorRatings}
Overall Security Score: ${securityScore}/100`;
}
// Add message to chat
function addMessageToChat(sender, content) {
const chatMessages = document.getElementById('chat-messages');
if (!chatMessages) return;
const messageElement = document.createElement('div');
messageElement.classList.add('chat-message', `${sender}-message`);
messageElement.textContent = content;
chatMessages.appendChild(messageElement);
// Scroll to bottom
chatMessages.scrollTop = chatMessages.scrollHeight;
return messageElement;
}
// Update assistant message
function updateAssistantMessage(messageElement, content) {
if (!messageElement) return;
messageElement.textContent = content;
// Scroll to bottom
const chatMessages = document.getElementById('chat-messages');
if (chatMessages) {
chatMessages.scrollTop = chatMessages.scrollHeight;
}
}
// Query Groq API
async function queryGroqAPI(message, apiKey, urlContext, securityContext) {
try {
// Use background script as proxy to avoid CSP issues
const response = await chrome.runtime.sendMessage({
action: 'groqChatQuery',
apiKey: apiKey,
message: message,
urlContext: urlContext,
securityContext: securityContext,
model: 'llama3-70b-8192' // Using Llama3 70B model
});
if (response.error) {
throw new Error(response.error);
}
return response.result;
} catch (error) {
console.error('Error querying Groq API:', error);
return "I'm having trouble connecting to my AI service right now. Please check your API key in settings and ensure you have an internet connection.";
}
}
// API key functions
async function saveApiKey() {
const apiKeyInput = document.getElementById('api-key-input');
if (!apiKeyInput) return;
const apiKey = apiKeyInput.value.trim();
if (apiKey) {
try {
await chrome.storage.sync.set({ 'sentinelApiKey': apiKey });
apiKeyInput.value = '';
apiKeyInput.placeholder = 'API key saved!';
setTimeout(() => {
apiKeyInput.placeholder = 'Enter Groq API Key';
}, 3000);
} catch (error) {
console.error('Error saving API key:', error);
}
}
}
async function loadApiKey() {
try {
const data = await chrome.storage.sync.get('sentinelApiKey');
const apiKey = data.sentinelApiKey;
const apiKeyInput = document.getElementById('api-key-input');
if (apiKey && apiKeyInput) {
apiKeyInput.placeholder = 'API key is set';
}
} catch (error) {
console.error('Error loading API key:', error);
}
}
async function getApiKey() {
try {
const data = await chrome.storage.sync.get('sentinelApiKey');
return data.sentinelApiKey;
} catch (error) {
console.error('Error getting API key:', error);
return null;
}
}
// Save Groq API key from settings tab
async function saveGroqApiKey() {
const apiKeyInput = document.getElementById('groqApiKey');
if (!apiKeyInput) return;
const apiKey = apiKeyInput.value.trim();
if (apiKey) {
try {
await chrome.storage.sync.set({ 'sentinelApiKey': apiKey });
apiKeyInput.value = '';
apiKeyInput.placeholder = 'API key saved!';
setTimeout(() => {
apiKeyInput.placeholder = 'Enter Groq API Key';
}, 3000);
} catch (error) {
console.error('Error saving API key:', error);
}
}
}
// Security analysis functions
function initSecurityAnalysis() {
// Start security analysis for current site
analyzeSiteSecurity();
}
async function analyzeSiteSecurity() {
try {
const tabs = await chrome.tabs.query({ active: true, currentWindow: true });
const currentTab = tabs[0];
const url = new URL(currentTab.url);
// Show loading indicators for all data fields
updateSecurityItem('connection-status', 'Analyzing...', '');
updateSecurityItem('ssl-status', 'Analyzing...', '');
updateSecurityItem('risk-score', 'Analyzing...', '');
updateSecurityItem('security-headers', 'Analyzing...', '');
updateSecurityItem('domain-age', 'Analyzing...', '');
updateSecurityItem('vendor-ratings', 'Analyzing...', '');
const securityScoreEl = document.getElementById('security-score-value');
if (securityScoreEl) {
securityScoreEl.textContent = '...';
}
// Set up a timeout to ensure we always show something
const analysisTimeout = setTimeout(() => {
calculateAndDisplaySecurityScore();
}, 5000); // 5 second timeout
// Update connection status - Real check
const isHttps = url.protocol === 'https:';
updateSecurityItem('connection-status', isHttps ? 'Secure (HTTPS)' : 'Insecure (HTTP)', isHttps ? 'secure' : 'danger');
// Get VirusTotal data - Real API data
chrome.runtime.sendMessage({ action: 'getVirusTotalReport', url: currentTab.url }, (response) => {
clearTimeout(analysisTimeout);
if (response && response.report) {
const report = response.report;
// Update vendor ratings
if (report.vendorRatings) {
const { safe, warning, unsafe, total } = report.vendorRatings;
let statusClass = 'secure';
let statusText = 'Safe';
// Fix logic to properly identify safe sites
if (unsafe > 0 && unsafe > safe / 10) {
// Only mark as unsafe if there are significant unsafe votes
statusClass = 'danger';
statusText = 'Unsafe';
} else if (warning > safe && warning > 10) {
// Only mark as warning if warnings are significant
statusClass = 'warning';
statusText = 'Warning';
}
// Otherwise stays "Safe"
updateSecurityItem('vendor-ratings',
`${statusText} (${safe} Safe / ${warning} Warning / ${unsafe} Unsafe)`,
statusClass);
} else {
updateSecurityItem('vendor-ratings', 'No vendor data available', 'warning');
}
// Update domain age if available from VirusTotal
if (report.lastAnalysisDate) {
try {
// Try to estimate domain age from VirusTotal data
// Parse attributes.creation_date if available or use lastAnalysisDate as fallback
const creationDate = report.creationDate ? new Date(report.creationDate * 1000) : null;
if (creationDate) {
const now = new Date();
const ageInMilliseconds = now - creationDate;
const ageInYears = Math.floor(ageInMilliseconds / (1000 * 60 * 60 * 24 * 365.25));
const ageInMonths = Math.floor(ageInMilliseconds / (1000 * 60 * 60 * 24 * 30.44)) % 12;
let ageClass = 'secure';
if (ageInYears < 1) {
ageClass = 'danger'; // New domains are more suspicious
} else if (ageInYears < 2) {
ageClass = 'warning'; // Relatively new domains get warning
}
updateSecurityItem('domain-age',
`${ageInYears} year${ageInYears !== 1 ? 's' : ''} ${ageInMonths > 0 ? `, ${ageInMonths} month${ageInMonths !== 1 ? 's' : ''}` : ''}`,
ageClass);
} else {
// If we don't have creation date, estimate from categories or other data
const knownSafeDomains = [
'google.com', 'microsoft.com', 'github.com', 'apple.com',
'amazon.com', 'facebook.com', 'twitter.com', 'linkedin.com',
'wikipedia.org', 'mozilla.org', 'adobe.com', 'cloudflare.com',
'dropbox.com', 'instagram.com', 'netflix.com', 'spotify.com',
'paypal.com', 'stripe.com', 'slack.com', 'zoom.us'
];
const domain = url.hostname;
const isKnownSafeDomain = knownSafeDomains.some(d => domain.includes(d));
if (isKnownSafeDomain) {
updateSecurityItem('domain-age', 'Established (10+ years)', 'secure');
} else {
updateSecurityItem('domain-age', 'Unknown age', 'warning');
}
}
} catch (error) {
console.error('Error processing domain age:', error);
updateSecurityItem('domain-age', 'Unknown age', 'warning');
}
} else {
updateSecurityItem('domain-age', 'Unknown age', 'warning');
}
} else {
updateSecurityItem('vendor-ratings', 'No data available', 'warning');
updateSecurityItem('domain-age', 'Unknown age', 'warning');
}
calculateAndDisplaySecurityScore();
});
// Analyze SSL/TLS - Real certificate check
chrome.runtime.sendMessage({ action: 'checkCertificate', url: currentTab.url }, (response) => {
if (response && response.certificate) {
updateCertificateInfo(response.certificate);
// Update SSL status
const validSsl = response.certificate.valid;
updateSecurityItem('ssl-status', validSsl ? 'Valid' : 'Invalid or Missing', validSsl ? 'secure' : 'danger');
} else {
updateSecurityItem('ssl-status', 'Unknown', 'warning');
}
calculateAndDisplaySecurityScore();
});
// Get security headers from background
chrome.runtime.sendMessage({ action: 'getSecurityInfo', url: currentTab.url }, (response) => {
if (response && response.securityInfo && response.securityInfo.securityHeaders) {
const headers = response.securityInfo.securityHeaders;
const presentHeaders = Object.keys(headers).filter(key => headers[key] !== null).length;
const totalHeaders = Object.keys(headers).length;
// Update security headers status
const headerRatio = Math.round((presentHeaders / totalHeaders) * 100);
let headerStatus = 'Poor';
let headerClass = 'danger';
if (headerRatio >= 70) {
headerStatus = 'Good';
headerClass = 'secure';
} else if (headerRatio >= 40) {
headerStatus = 'Moderate';
headerClass = 'warning';
}
updateSecurityItem('security-headers', `${headerStatus} (${presentHeaders}/${totalHeaders})`, headerClass);
} else {
updateSecurityItem('security-headers', 'Unknown', 'warning');
}
calculateAndDisplaySecurityScore();
});
// Get risk score from background service
chrome.runtime.sendMessage({ action: 'getRiskScore', url: currentTab.url }, (response) => {
if (response && response.riskScore !== undefined) {
// Update risk score
const score = response.riskScore;
let riskClass = 'danger';
if (score < 30) riskClass = 'secure';
else if (score < 70) riskClass = 'warning';
updateSecurityItem('risk-score', `${score}/100`, riskClass);
} else {
updateSecurityItem('risk-score', 'Unknown', 'warning');
}
calculateAndDisplaySecurityScore();
});
} catch (error) {
console.error('Error analyzing site security:', error);
// Ensure we still show a score even on error
calculateAndDisplaySecurityScore();
}
}
function updateSecurityItem(id, value, className) {
const element = document.querySelector(`#${id} .value`);
if (element) {
element.textContent = value;
element.className = 'value ' + (className || '');
}
}
function updateCertificateInfo(certificate) {
const certificateDetails = document.querySelector('.certificate-details');
if (!certificateDetails) return;
if (certificate) {
let html = `
<h3>SSL/TLS Certificate</h3>
<div class="certificate-item">
<strong>Subject:</strong>
${certificate.subject || 'Unknown'}
</div>
<div class="certificate-item">
<strong>Issuer:</strong>
${certificate.issuer || 'Unknown'}
</div>
<div class="certificate-item">
<strong>Valid From:</strong>
${certificate.validFrom || 'Unknown'}
</div>
<div class="certificate-item">
<strong>Valid To:</strong>
${certificate.validTo || 'Unknown'}
</div>
<div class="certificate-item">
<strong>Status:</strong>
<span class="${certificate.valid ? 'secure' : 'danger'}">${certificate.valid ? 'Valid' : 'Invalid'}</span>
</div>`;
// Include additional details if available
if (certificate.details) {
if (certificate.details.serialNumber) {
html += `
<div class="certificate-item">
<strong>Serial Number:</strong>
${certificate.details.serialNumber}
</div>`;
}
if (certificate.details.fingerprint) {
html += `
<div class="certificate-item">
<strong>Fingerprint:</strong>
${certificate.details.fingerprint}
</div>`;
}
if (certificate.details.subjectAltNames && certificate.details.subjectAltNames.length > 0) {
html += `
<div class="certificate-item">
<strong>Subject Alternative Names:</strong>
<ul>`;
certificate.details.subjectAltNames.slice(0, 5).forEach(name => {
html += `<li>${name}</li>`;
});
if (certificate.details.subjectAltNames.length > 5) {
html += `<li>And ${certificate.details.subjectAltNames.length - 5} more...</li>`;
}
html += `</ul>
</div>`;
}
}
certificateDetails.innerHTML = html;
} else {
certificateDetails.innerHTML = '<p>No certificate information available</p>';
}
}
function calculateAndDisplaySecurityScore() {
const scoreCircle = document.querySelector('.score-circle');
const securityScoreElement = document.getElementById('security-score-value');
if (!scoreCircle || !securityScoreElement) return;
// Get all security factors
const connectionStatusEl = document.querySelector('#connection-status .value');
const sslStatusEl = document.querySelector('#ssl-status .value');
const riskScoreEl = document.querySelector('#risk-score .value');
const securityHeadersEl = document.querySelector('#security-headers .value');
const vendorRatingsEl = document.querySelector('#vendor-ratings .value');
const connectionStatus = connectionStatusEl ? connectionStatusEl.textContent : '';
const sslStatus = sslStatusEl ? sslStatusEl.textContent : '';
const riskScore = riskScoreEl ? riskScoreEl.textContent : '';
const securityHeaders = securityHeadersEl ? securityHeadersEl.textContent : '';
const vendorRatings = vendorRatingsEl ? vendorRatingsEl.textContent : '';
// Don't calculate if we're still loading data
if (connectionStatus === 'Analyzing...' ||
sslStatus === 'Analyzing...' ||
riskScore === 'Analyzing...' ||
securityHeaders === 'Analyzing...' ||
vendorRatings === 'Analyzing...') {
return;
}
let score = 50; // Start with neutral score
// Adjust score based on connection
if (connectionStatus.includes('Secure')) {
score += 20;
} else if (connectionStatus.includes('Insecure')) {
score -= 20;
}
// Adjust score based on SSL
if (sslStatus.includes('Valid')) {
score += 15;
} else if (sslStatus.includes('Invalid')) {
score -= 15;
}
// Adjust score based on risk
if (riskScore !== 'Unknown') {
const riskValue = parseInt(riskScore);
if (!isNaN(riskValue)) {
score += (100 - riskValue) / 10; // Higher is riskier, so invert
}
}
// Adjust score based on security headers
if (securityHeaders.includes('Good')) {
score += 15;
} else if (securityHeaders.includes('Moderate')) {
score += 7;
} else if (securityHeaders.includes('Poor')) {
score -= 7;
}
// Adjust score based on vendor ratings
if (vendorRatings.includes('Safe')) {
score += 20;
} else if (vendorRatings.includes('Warning')) {
score -= 10;
} else if (vendorRatings.includes('Unsafe')) {
score -= 30;
}
// Clamp score between 0 and 100
score = Math.max(0, Math.min(100, Math.round(score)));
// Update score display
securityScoreElement.textContent = score;
// Update score circle class
scoreCircle.classList.remove('score-high', 'score-medium', 'score-low');
if (score >= 70) {
scoreCircle.classList.add('score-high');
} else if (score >= 40) {
scoreCircle.classList.add('score-medium');
} else {
scoreCircle.classList.add('score-low');
}
}
// Original ScreenPipe functionality - Fetch screen data from Screenpipe
async function fetchScreenData() {
const dataDiv = document.getElementById("data");
const contentDisplayDiv = document.getElementById("contentDisplay");
if (!dataDiv || !contentDisplayDiv) return;
const contentType = document.getElementById("contentType")?.value || "ocr";
contentDisplayDiv.innerHTML = "<p>Fetching data...</p>";
dataDiv.textContent = "Fetching data...";
console.log("Fetch button clicked. Starting data fetch...");
try {
// Revert to simple time calculation to avoid issues with Screenpipe's video handling
const oneHourAgo = new Date(Date.now() - 60 * 60 * 1000).toISOString();
const now = new Date().toISOString();
console.log("Querying Screenpipe API...");
const results = await screenpipe.pipe.queryScreenpipe({
contentType: contentType.toLowerCase(),
startTime: oneHourAgo,
endTime: now,
limit: 20,
includeFrames: false // Set to false initially to prevent video processing errors
});
console.log("Data fetched successfully:", results);
if (results && results.data) {
cachedScreenData = results.data;
dataDiv.textContent = JSON.stringify(results.data, null, 2);
// Immediately display the content
displayScreenContent();
} else {
contentDisplayDiv.innerHTML = "<p>No data returned from Screenpipe.</p>";
dataDiv.textContent = "No data returned from Screenpipe.";
}
} catch (error) {
console.error("Failed to fetch data:", error);
contentDisplayDiv.innerHTML = `<p>Failed to fetch data: ${error.message}</p>`;
if (dataDiv) {
dataDiv.textContent = `Failed to fetch data: ${error.message}`;
}
}
// After fetching data, provide option to analyze
const analyzeBtn = document.getElementById('analyzeData');
if (analyzeBtn) {
analyzeBtn.classList.add('highlight');
setTimeout(() => {
analyzeBtn.classList.remove('highlight');
}, 2000);
}
}
// Original functionality - Display screen content in a user-friendly format
function displayScreenContent() {
const contentDiv = document.getElementById("contentDisplay");
if (!contentDiv) return;
if (!cachedScreenData || cachedScreenData.length === 0) {
contentDiv.innerHTML = "<p>No screen data available. Please fetch screen data first.</p>";
return;
}
let html = "";
cachedScreenData.forEach((item, index) => {
html += `<div class="content-item">`;
if (item.type && item.type.toLowerCase() === "ocr") {
html += `<h3>Captured Text #${index + 1}</h3>`;
// Add timestamp
if (item.content && item.content.timestamp) {
const timestamp = new Date(item.content.timestamp).toLocaleString();
html += `<p class="timestamp">Time: ${timestamp}</p>`;
}
// Add app name if available
if (item.content && item.content.app_name) {
html += `<p class="app-name">App: ${item.content.app_name}</p>`;
}
// Add browser URL if available
if (item.content && item.content.browserUrl) {
html += `<p class="browser-url">URL: ${item.content.browserUrl}</p>`;
}
// Add text content
html += `<div class="text-content">${item.content && item.content.text ? item.content.text : "No text content"}</div>`;
// Add image frame if available
if (item.content && item.content.frame) {
html += `<div class="image-container">
<img src="data:image/png;base64,${item.content.frame}" alt="Screen capture" />
</div>`;
}
} else if (item.type && item.type.toLowerCase() === "audio") {
html += `<h3>Audio Transcription #${index + 1}</h3>`;
html += `<div class="audio-content">${item.content && item.content.transcription ? item.content.transcription : "No transcription available"}</div>`;
} else {
html += `<h3>Data Item #${index + 1}</h3>`;
html += `<pre>${JSON.stringify(item, null, 2)}</pre>`;
}
html += `</div>`;
});
if (html === "") {
html = "<p>No displayable content found in the data.</p>";
}
contentDiv.innerHTML = html;
}
// Original functionality - Filter content based on search query
function filterContent() {
const filterQuery = document.getElementById("filterQuery")?.value.toLowerCase() || "";
const contentDiv = document.getElementById("contentDisplay");
if (!contentDiv) return;
if (!cachedScreenData || cachedScreenData.length === 0) {
contentDiv.innerHTML = "<p>Please fetch screen data first.</p>";
return;
}
if (!filterQuery) {
displayScreenContent();
return;
}
const filteredData = cachedScreenData.filter(item => {
if (item.type === "OCR") {
const text = item.content.text?.toLowerCase() || "";
const appName = item.content.app_name?.toLowerCase() || "";
const browserUrl = item.content.browserUrl?.toLowerCase() || "";
return text.includes(filterQuery) || appName.includes(filterQuery) || browserUrl.includes(filterQuery);
} else if (item.type === "Audio") {
const transcription = item.content.transcription?.toLowerCase() || "";
return transcription.includes(filterQuery);
}
return false;
});
let html = "";
if (filteredData.length === 0) {
html = `<p>No results found for "${filterQuery}"</p>`;
} else {
filteredData.forEach((item, index) => {
html += `<div class="content-item">`;
if (item.type === "OCR") {
html += `<h3>Captured Text #${index + 1}</h3>`;
if (item.content.timestamp) {
const timestamp = new Date(item.content.timestamp).toLocaleString();
html += `<p class="timestamp">Time: ${timestamp}</p>`;
}
if (item.content.app_name) {
html += `<p class="app-name">App: ${item.content.app_name}</p>`;
}
if (item.content.browserUrl) {
html += `<p class="browser-url">URL: ${item.content.browserUrl}</p>`;
}
const text = item.content.text || "No text content";
const highlightedText = text.replace(new RegExp(filterQuery, 'gi'), match => `<mark>${match}</mark>`);
html += `<div class="text-content">${highlightedText}</div>`;
if (item.content.frame) {
html += `<div class="image-container">
<img src="data:image/png;base64,${item.content.frame}" alt="Screen capture" />
</div>`;
}
} else if (item.type === "Audio") {
html += `<h3>Audio Transcription #${index + 1}</h3>`;
const transcription = item.content.transcription || "No transcription available";
const highlightedTranscription = transcription.replace(new RegExp(filterQuery, 'gi'), match => `<mark>${match}</mark>`);
html += `<div class="audio-content">${highlightedTranscription}</div>`;
}