/** * ThreatLens OSINT - Ethical Intelligence Platform * A legitimate OSINT analysis tool using transformers.js * * IMPORTANT: This platform only processes publicly available data * and operates within legal and ethical boundaries. */ import { pipeline, env } from 'https://cdn.jsdelivr.net/npm/@huggingface/transformers@3.8.0'; // Configure transformers.js env.allowLocalModels = false; env.useBrowserCache = true; // Application State const AppState = { models: { sentiment: null, ner: null, summarization: null, zeroShot: null }, isReady: false, complianceAccepted: false }; // Threat categories for classification const THREAT_CATEGORIES = [ 'malware', 'phishing', 'ransomware', 'data breach', 'denial of service', 'social engineering', 'insider threat', 'zero-day vulnerability', 'supply chain attack', 'credential theft' ]; // Sample threat intelligence data const SAMPLE_DATA = { threat: `CVE-2024-1234: Critical Remote Code Execution Vulnerability in Enterprise Software A critical security vulnerability has been discovered in the authentication module of Enterprise Software X, allowing remote attackers to execute arbitrary code. The vulnerability affects versions 2.0 through 3.5. Organizations running affected versions should immediately apply the security patch released by the vendor. Impact: Remote code execution with system privileges CVSS Score: 9.8 (Critical) Affected Components: Authentication module, session management Attack Vector: Network-based, requires no authentication Mitigation: Update to version 3.6 or apply vendor patch This vulnerability has been observed being actively exploited in the wild by threat actor group APT-29, targeting financial institutions in North America and Europe.`, entities: `Security researchers at Mandiant have identified a new threat actor group operating from Eastern Europe. The group, tracked as APT-45, has been targeting healthcare organizations in the United States, Germany, and France. The attacks originate from IP addresses in Russia and Ukraine. The group uses custom malware developed by a team based in Moscow. Victims include major hospitals in New York, Berlin, and Paris. The campaign has been active since January 2024.`, sentiment: `URGENT SECURITY ADVISORY: We have detected active exploitation of a critical vulnerability in our systems. Immediate action is required. All customers are advised to change their passwords immediately and enable multi-factor authentication. We take this incident extremely seriously and are working around the clock to address the situation.`, summary: `A sophisticated cyber espionage campaign has been discovered targeting government agencies and defense contractors across multiple countries. The campaign, attributed to a nation-state actor, employs advanced persistent threat tactics including custom malware, living-off-the-land techniques, and encrypted communication channels. The attackers gained initial access through spear-phishing emails containing malicious documents that exploited a previously unknown vulnerability in a popular document viewer. Once inside the network, the threat actors conducted reconnaissance, moved laterally using stolen credentials, and exfiltrated sensitive documents over a period of several months. The campaign was discovered when an organization's security team noticed unusual network traffic patterns to an unknown external server. Forensic analysis revealed the presence of a previously unknown backdoor that had been installed on multiple systems. The malware employed several anti-analysis techniques including code obfuscation, anti-debugging checks, and encrypted payloads. Communication with command and control servers was conducted using a custom protocol that mimicked legitimate HTTPS traffic. The threat actors demonstrated sophisticated operational security, rotating infrastructure frequently and using proxy servers to mask their true location. Attribution analysis suggests the campaign may be linked to a known threat group associated with a foreign intelligence service. Organizations are advised to review their security posture, implement network segmentation, and enhance monitoring for suspicious activity.`, classify: `An attacker is attempting to trick employees into revealing their login credentials by sending fraudulent emails that appear to come from the IT department, directing them to a fake login page.` }; // Initialize Application async function initApp() { // Check compliance const complianceAccepted = localStorage.getItem('complianceAccepted'); if (!complianceAccepted) { showComplianceModal(); } else { AppState.complianceAccepted = true; } // Setup navigation setupNavigation(); // Load models await loadModels(); } // Load AI Models async function loadModels() { updateModelStatus('loading', 'Loading AI models...'); try { // Load sentiment analysis model updateModelStatus('loading', 'Loading sentiment analysis model...'); AppState.models.sentiment = await pipeline('sentiment-analysis', 'Xenova/distilbert-base-uncased-finetuned-sst-2-english', { progress_callback: (progress) => updateProgress(progress) }); // Load NER model updateModelStatus('loading', 'Loading entity recognition model...'); AppState.models.ner = await pipeline('ner', 'Xenova/bert-base-NER', { progress_callback: (progress) => updateProgress(progress) }); // Load summarization model updateModelStatus('loading', 'Loading summarization model...'); AppState.models.summarization = await pipeline('summarization', 'Xenova/distilbart-cnn-6-6', { progress_callback: (progress) => updateProgress(progress) }); // Load zero-shot classification updateModelStatus('loading', 'Loading classification model...'); AppState.models.zeroShot = await pipeline('zero-shot-classification', 'Xenova/nli-deberta-v3-xsmall', { progress_callback: (progress) => updateProgress(progress) }); AppState.isReady = true; updateModelStatus('ready', 'AI models ready'); } catch (error) { console.error('Error loading models:', error); updateModelStatus('error', 'Error loading models'); showNotification('Failed to load AI models. Please refresh the page.', 'error'); } } // Update model status indicator function updateModelStatus(status, text) { const indicator = document.getElementById('modelStatus'); const statusText = document.getElementById('modelStatusText'); indicator.className = 'status-indicator ' + status; statusText.textContent = text; } // Update loading progress function updateProgress(progress) { if (progress.status === 'progress') { const fill = document.getElementById('progressFill'); if (fill) { fill.style.width = `${Math.round(progress.progress || 0)}%`; } } } // Setup Navigation function setupNavigation() { const navItems = document.querySelectorAll('.nav-item'); navItems.forEach(item => { item.addEventListener('click', () => { const tabId = item.dataset.tab; switchTab(tabId); }); }); } // Switch Tab function switchTab(tabId) { // Update nav items document.querySelectorAll('.nav-item').forEach(item => { item.classList.toggle('active', item.dataset.tab === tabId); }); // Update tab content document.querySelectorAll('.tab-content').forEach(tab => { tab.classList.toggle('active', tab.id === `${tabId}-tab`); }); } // Load Sample Data window.loadSampleData = function() { document.getElementById('threatInput').value = SAMPLE_DATA.threat; document.getElementById('entityInput').value = SAMPLE_DATA.entities; document.getElementById('sentimentInput').value = SAMPLE_DATA.sentiment; document.getElementById('summaryInput').value = SAMPLE_DATA.summary; document.getElementById('classifyInput').value = SAMPLE_DATA.classify; showNotification('Sample data loaded', 'success'); }; // Analyze Threat window.analyzeThreat = async function() { if (!AppState.isReady) { showNotification('Models are still loading. Please wait.', 'warning'); return; } const input = document.getElementById('threatInput').value.trim(); if (!input) { showNotification('Please enter text to analyze', 'warning'); return; } const btn = document.getElementById('analyzeBtn'); btn.disabled = true; showProgress('Analyzing threat intelligence...'); try { // Perform sentiment analysis const sentiment = await AppState.models.sentiment(input); // Perform classification const classification = await AppState.models.zeroShot(input, THREAT_CATEGORIES); // Generate analysis results const results = generateThreatAnalysis(input, sentiment, classification); displayAnalysisResults(results); } catch (error) { console.error('Analysis error:', error); showNotification('Error during analysis. Please try again.', 'error'); } finally { btn.disabled = false; hideProgress(); } }; // Generate Threat Analysis function generateThreatAnalysis(input, sentiment, classification) { // Determine threat level based on classification confidence const topCategory = classification.labels[0]; const topScore = classification.scores[0]; let threatLevel = 'low'; let threatColor = 'success'; let threatIcon = '✓'; if (topScore > 0.7 && ['ransomware', 'data breach', 'zero-day vulnerability'].includes(topCategory)) { threatLevel = 'critical'; threatColor = 'danger'; threatIcon = '⚠️'; } else if (topScore > 0.6 && ['malware', 'phishing', 'credential theft'].includes(topCategory)) { threatLevel = 'high'; threatColor = 'warning'; threatIcon = '⚡'; } else if (topScore > 0.4) { threatLevel = 'medium'; threatColor = 'info'; threatIcon = 'ℹ️'; } // Determine sentiment urgency const isUrgent = sentiment[0].label === 'NEGATIVE'; return { threatLevel, threatColor, threatIcon, category: topCategory, confidence: (topScore * 100).toFixed(1), sentiment: sentiment[0].label, sentimentScore: (sentiment[0].score * 100).toFixed(1), isUrgent, recommendations: generateRecommendations(topCategory, threatLevel) }; } // Generate Recommendations function generateRecommendations(category, level) { const recommendations = { 'malware': [ 'Isolate affected systems immediately', 'Run comprehensive malware scan', 'Check for lateral movement indicators' ], 'phishing': [ 'Alert users about the phishing campaign', 'Block malicious domains/URLs', 'Review email gateway logs' ], 'ransomware': [ 'Disconnect affected systems from network', 'Do not pay ransom - contact law enforcement', 'Restore from clean backups' ], 'data breach': [ 'Activate incident response plan', 'Notify affected parties per regulations', 'Preserve evidence for investigation' ], 'credential theft': [ 'Force password reset for affected accounts', 'Enable multi-factor authentication', 'Review access logs for unauthorized activity' ] }; return recommendations[category] || [ 'Review and assess the threat intelligence', 'Update security controls as needed', 'Monitor for indicators of compromise' ]; } // Display Analysis Results function displayAnalysisResults(results) { const output = document.getElementById('analysisOutput'); output.innerHTML = `