mirxa2 commited on
Commit
063d154
·
verified ·
1 Parent(s): d2ed9c8

Upload index.js with huggingface_hub

Browse files
Files changed (1) hide show
  1. index.js +314 -0
index.js ADDED
@@ -0,0 +1,314 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ /**
2
+ * ThreatLens OSINT - Ethical Intelligence Platform
3
+ * A legitimate OSINT analysis tool using transformers.js
4
+ *
5
+ * IMPORTANT: This platform only processes publicly available data
6
+ * and operates within legal and ethical boundaries.
7
+ */
8
+
9
+ import { pipeline, env } from 'https://cdn.jsdelivr.net/npm/@huggingface/transformers@3.8.0';
10
+
11
+ // Configure transformers.js
12
+ env.allowLocalModels = false;
13
+ env.useBrowserCache = true;
14
+
15
+ // Application State
16
+ const AppState = {
17
+ models: {
18
+ sentiment: null,
19
+ ner: null,
20
+ summarization: null,
21
+ zeroShot: null
22
+ },
23
+ isReady: false,
24
+ complianceAccepted: false
25
+ };
26
+
27
+ // Threat categories for classification
28
+ const THREAT_CATEGORIES = [
29
+ 'malware',
30
+ 'phishing',
31
+ 'ransomware',
32
+ 'data breach',
33
+ 'denial of service',
34
+ 'social engineering',
35
+ 'insider threat',
36
+ 'zero-day vulnerability',
37
+ 'supply chain attack',
38
+ 'credential theft'
39
+ ];
40
+
41
+ // Sample threat intelligence data
42
+ const SAMPLE_DATA = {
43
+ threat: `CVE-2024-1234: Critical Remote Code Execution Vulnerability in Enterprise Software
44
+
45
+ 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.
46
+
47
+ Impact: Remote code execution with system privileges
48
+ CVSS Score: 9.8 (Critical)
49
+ Affected Components: Authentication module, session management
50
+ Attack Vector: Network-based, requires no authentication
51
+ Mitigation: Update to version 3.6 or apply vendor patch
52
+
53
+ 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.`,
54
+
55
+ entities: `Security researchers at Mandiant have identified a new threat actor group operating from Eastern Europe.
56
+ The group, tracked as APT-45, has been targeting healthcare organizations in the United States, Germany, and France.
57
+ The attacks originate from IP addresses in Russia and Ukraine. The group uses custom malware developed by a team
58
+ based in Moscow. Victims include major hospitals in New York, Berlin, and Paris. The campaign has been active
59
+ since January 2024.`,
60
+
61
+ sentiment: `URGENT SECURITY ADVISORY: We have detected active exploitation of a critical vulnerability in our systems.
62
+ Immediate action is required. All customers are advised to change their passwords immediately and enable multi-factor
63
+ authentication. We take this incident extremely seriously and are working around the clock to address the situation.`,
64
+
65
+ summary: `A sophisticated cyber espionage campaign has been discovered targeting government agencies and defense
66
+ contractors across multiple countries. The campaign, attributed to a nation-state actor, employs advanced persistent
67
+ threat tactics including custom malware, living-off-the-land techniques, and encrypted communication channels.
68
+ The attackers gained initial access through spear-phishing emails containing malicious documents that exploited a
69
+ previously unknown vulnerability in a popular document viewer. Once inside the network, the threat actors conducted
70
+ reconnaissance, moved laterally using stolen credentials, and exfiltrated sensitive documents over a period of
71
+ several months. The campaign was discovered when an organization's security team noticed unusual network traffic
72
+ patterns to an unknown external server. Forensic analysis revealed the presence of a previously unknown backdoor
73
+ that had been installed on multiple systems. The malware employed several anti-analysis techniques including
74
+ code obfuscation, anti-debugging checks, and encrypted payloads. Communication with command and control servers
75
+ was conducted using a custom protocol that mimicked legitimate HTTPS traffic. The threat actors demonstrated
76
+ sophisticated operational security, rotating infrastructure frequently and using proxy servers to mask their
77
+ true location. Attribution analysis suggests the campaign may be linked to a known threat group associated with
78
+ a foreign intelligence service. Organizations are advised to review their security posture, implement network
79
+ segmentation, and enhance monitoring for suspicious activity.`,
80
+
81
+ classify: `An attacker is attempting to trick employees into revealing their login credentials by sending
82
+ fraudulent emails that appear to come from the IT department, directing them to a fake login page.`
83
+ };
84
+
85
+ // Initialize Application
86
+ async function initApp() {
87
+ // Check compliance
88
+ const complianceAccepted = localStorage.getItem('complianceAccepted');
89
+ if (!complianceAccepted) {
90
+ showComplianceModal();
91
+ } else {
92
+ AppState.complianceAccepted = true;
93
+ }
94
+
95
+ // Setup navigation
96
+ setupNavigation();
97
+
98
+ // Load models
99
+ await loadModels();
100
+ }
101
+
102
+ // Load AI Models
103
+ async function loadModels() {
104
+ updateModelStatus('loading', 'Loading AI models...');
105
+
106
+ try {
107
+ // Load sentiment analysis model
108
+ updateModelStatus('loading', 'Loading sentiment analysis model...');
109
+ AppState.models.sentiment = await pipeline('sentiment-analysis', 'Xenova/distilbert-base-uncased-finetuned-sst-2-english', {
110
+ progress_callback: (progress) => updateProgress(progress)
111
+ });
112
+
113
+ // Load NER model
114
+ updateModelStatus('loading', 'Loading entity recognition model...');
115
+ AppState.models.ner = await pipeline('ner', 'Xenova/bert-base-NER', {
116
+ progress_callback: (progress) => updateProgress(progress)
117
+ });
118
+
119
+ // Load summarization model
120
+ updateModelStatus('loading', 'Loading summarization model...');
121
+ AppState.models.summarization = await pipeline('summarization', 'Xenova/distilbart-cnn-6-6', {
122
+ progress_callback: (progress) => updateProgress(progress)
123
+ });
124
+
125
+ // Load zero-shot classification
126
+ updateModelStatus('loading', 'Loading classification model...');
127
+ AppState.models.zeroShot = await pipeline('zero-shot-classification', 'Xenova/nli-deberta-v3-xsmall', {
128
+ progress_callback: (progress) => updateProgress(progress)
129
+ });
130
+
131
+ AppState.isReady = true;
132
+ updateModelStatus('ready', 'AI models ready');
133
+
134
+ } catch (error) {
135
+ console.error('Error loading models:', error);
136
+ updateModelStatus('error', 'Error loading models');
137
+ showNotification('Failed to load AI models. Please refresh the page.', 'error');
138
+ }
139
+ }
140
+
141
+ // Update model status indicator
142
+ function updateModelStatus(status, text) {
143
+ const indicator = document.getElementById('modelStatus');
144
+ const statusText = document.getElementById('modelStatusText');
145
+
146
+ indicator.className = 'status-indicator ' + status;
147
+ statusText.textContent = text;
148
+ }
149
+
150
+ // Update loading progress
151
+ function updateProgress(progress) {
152
+ if (progress.status === 'progress') {
153
+ const fill = document.getElementById('progressFill');
154
+ if (fill) {
155
+ fill.style.width = `${Math.round(progress.progress || 0)}%`;
156
+ }
157
+ }
158
+ }
159
+
160
+ // Setup Navigation
161
+ function setupNavigation() {
162
+ const navItems = document.querySelectorAll('.nav-item');
163
+
164
+ navItems.forEach(item => {
165
+ item.addEventListener('click', () => {
166
+ const tabId = item.dataset.tab;
167
+ switchTab(tabId);
168
+ });
169
+ });
170
+ }
171
+
172
+ // Switch Tab
173
+ function switchTab(tabId) {
174
+ // Update nav items
175
+ document.querySelectorAll('.nav-item').forEach(item => {
176
+ item.classList.toggle('active', item.dataset.tab === tabId);
177
+ });
178
+
179
+ // Update tab content
180
+ document.querySelectorAll('.tab-content').forEach(tab => {
181
+ tab.classList.toggle('active', tab.id === `${tabId}-tab`);
182
+ });
183
+ }
184
+
185
+ // Load Sample Data
186
+ window.loadSampleData = function() {
187
+ document.getElementById('threatInput').value = SAMPLE_DATA.threat;
188
+ document.getElementById('entityInput').value = SAMPLE_DATA.entities;
189
+ document.getElementById('sentimentInput').value = SAMPLE_DATA.sentiment;
190
+ document.getElementById('summaryInput').value = SAMPLE_DATA.summary;
191
+ document.getElementById('classifyInput').value = SAMPLE_DATA.classify;
192
+ showNotification('Sample data loaded', 'success');
193
+ };
194
+
195
+ // Analyze Threat
196
+ window.analyzeThreat = async function() {
197
+ if (!AppState.isReady) {
198
+ showNotification('Models are still loading. Please wait.', 'warning');
199
+ return;
200
+ }
201
+
202
+ const input = document.getElementById('threatInput').value.trim();
203
+ if (!input) {
204
+ showNotification('Please enter text to analyze', 'warning');
205
+ return;
206
+ }
207
+
208
+ const btn = document.getElementById('analyzeBtn');
209
+ btn.disabled = true;
210
+ showProgress('Analyzing threat intelligence...');
211
+
212
+ try {
213
+ // Perform sentiment analysis
214
+ const sentiment = await AppState.models.sentiment(input);
215
+
216
+ // Perform classification
217
+ const classification = await AppState.models.zeroShot(input, THREAT_CATEGORIES);
218
+
219
+ // Generate analysis results
220
+ const results = generateThreatAnalysis(input, sentiment, classification);
221
+ displayAnalysisResults(results);
222
+
223
+ } catch (error) {
224
+ console.error('Analysis error:', error);
225
+ showNotification('Error during analysis. Please try again.', 'error');
226
+ } finally {
227
+ btn.disabled = false;
228
+ hideProgress();
229
+ }
230
+ };
231
+
232
+ // Generate Threat Analysis
233
+ function generateThreatAnalysis(input, sentiment, classification) {
234
+ // Determine threat level based on classification confidence
235
+ const topCategory = classification.labels[0];
236
+ const topScore = classification.scores[0];
237
+
238
+ let threatLevel = 'low';
239
+ let threatColor = 'success';
240
+ let threatIcon = '✓';
241
+
242
+ if (topScore > 0.7 && ['ransomware', 'data breach', 'zero-day vulnerability'].includes(topCategory)) {
243
+ threatLevel = 'critical';
244
+ threatColor = 'danger';
245
+ threatIcon = '⚠️';
246
+ } else if (topScore > 0.6 && ['malware', 'phishing', 'credential theft'].includes(topCategory)) {
247
+ threatLevel = 'high';
248
+ threatColor = 'warning';
249
+ threatIcon = '⚡';
250
+ } else if (topScore > 0.4) {
251
+ threatLevel = 'medium';
252
+ threatColor = 'info';
253
+ threatIcon = 'ℹ️';
254
+ }
255
+
256
+ // Determine sentiment urgency
257
+ const isUrgent = sentiment[0].label === 'NEGATIVE';
258
+
259
+ return {
260
+ threatLevel,
261
+ threatColor,
262
+ threatIcon,
263
+ category: topCategory,
264
+ confidence: (topScore * 100).toFixed(1),
265
+ sentiment: sentiment[0].label,
266
+ sentimentScore: (sentiment[0].score * 100).toFixed(1),
267
+ isUrgent,
268
+ recommendations: generateRecommendations(topCategory, threatLevel)
269
+ };
270
+ }
271
+
272
+ // Generate Recommendations
273
+ function generateRecommendations(category, level) {
274
+ const recommendations = {
275
+ 'malware': [
276
+ 'Isolate affected systems immediately',
277
+ 'Run comprehensive malware scan',
278
+ 'Check for lateral movement indicators'
279
+ ],
280
+ 'phishing': [
281
+ 'Alert users about the phishing campaign',
282
+ 'Block malicious domains/URLs',
283
+ 'Review email gateway logs'
284
+ ],
285
+ 'ransomware': [
286
+ 'Disconnect affected systems from network',
287
+ 'Do not pay ransom - contact law enforcement',
288
+ 'Restore from clean backups'
289
+ ],
290
+ 'data breach': [
291
+ 'Activate incident response plan',
292
+ 'Notify affected parties per regulations',
293
+ 'Preserve evidence for investigation'
294
+ ],
295
+ 'credential theft': [
296
+ 'Force password reset for affected accounts',
297
+ 'Enable multi-factor authentication',
298
+ 'Review access logs for unauthorized activity'
299
+ ]
300
+ };
301
+
302
+ return recommendations[category] || [
303
+ 'Review and assess the threat intelligence',
304
+ 'Update security controls as needed',
305
+ 'Monitor for indicators of compromise'
306
+ ];
307
+ }
308
+
309
+ // Display Analysis Results
310
+ function displayAnalysisResults(results) {
311
+ const output = document.getElementById('analysisOutput');
312
+
313
+ output.innerHTML = `
314
+ <div class="threat-level threat-${results.threatLevel}">