pompelmi 0.35.5 → 1.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (133) hide show
  1. package/.claude/settings.local.json +40 -0
  2. package/LICENSE +12 -18
  3. package/README.md +159 -183
  4. package/eslint.config.mjs +8 -0
  5. package/package.json +26 -251
  6. package/src/ClamAVDatabaseUpdater.js +48 -0
  7. package/src/ClamAVInstaller.js +49 -0
  8. package/src/ClamAVScanner.js +31 -0
  9. package/src/InstallerCommand.js +11 -0
  10. package/src/config.js +22 -0
  11. package/src/constants.js +3 -0
  12. package/src/favicon.ico +0 -0
  13. package/src/grapefruit.png +0 -0
  14. package/src/index.js +5 -0
  15. package/CHANGELOG.md +0 -71
  16. package/dist/pompelmi.audit.cjs +0 -128
  17. package/dist/pompelmi.audit.cjs.map +0 -1
  18. package/dist/pompelmi.audit.esm.js +0 -107
  19. package/dist/pompelmi.audit.esm.js.map +0 -1
  20. package/dist/pompelmi.browser.cjs +0 -1549
  21. package/dist/pompelmi.browser.cjs.map +0 -1
  22. package/dist/pompelmi.browser.esm.js +0 -1523
  23. package/dist/pompelmi.browser.esm.js.map +0 -1
  24. package/dist/pompelmi.cjs +0 -2591
  25. package/dist/pompelmi.cjs.map +0 -1
  26. package/dist/pompelmi.esm.js +0 -2525
  27. package/dist/pompelmi.esm.js.map +0 -1
  28. package/dist/pompelmi.hooks.cjs +0 -75
  29. package/dist/pompelmi.hooks.cjs.map +0 -1
  30. package/dist/pompelmi.hooks.esm.js +0 -72
  31. package/dist/pompelmi.hooks.esm.js.map +0 -1
  32. package/dist/pompelmi.policy-packs.cjs +0 -240
  33. package/dist/pompelmi.policy-packs.cjs.map +0 -1
  34. package/dist/pompelmi.policy-packs.esm.js +0 -232
  35. package/dist/pompelmi.policy-packs.esm.js.map +0 -1
  36. package/dist/pompelmi.quarantine.cjs +0 -317
  37. package/dist/pompelmi.quarantine.cjs.map +0 -1
  38. package/dist/pompelmi.quarantine.esm.js +0 -293
  39. package/dist/pompelmi.quarantine.esm.js.map +0 -1
  40. package/dist/pompelmi.react.cjs +0 -1580
  41. package/dist/pompelmi.react.cjs.map +0 -1
  42. package/dist/pompelmi.react.esm.js +0 -1553
  43. package/dist/pompelmi.react.esm.js.map +0 -1
  44. package/dist/types/audit.d.ts +0 -84
  45. package/dist/types/browser-index.d.ts +0 -29
  46. package/dist/types/config.d.ts +0 -143
  47. package/dist/types/engines/dynamic-taint.d.ts +0 -102
  48. package/dist/types/engines/hybrid-orchestrator.d.ts +0 -65
  49. package/dist/types/engines/hybrid-taint-integration.d.ts +0 -129
  50. package/dist/types/engines/taint-policies.d.ts +0 -84
  51. package/dist/types/hipaa-compliance.d.ts +0 -110
  52. package/dist/types/hooks.d.ts +0 -89
  53. package/dist/types/index.d.ts +0 -29
  54. package/dist/types/magic.d.ts +0 -7
  55. package/dist/types/node/scanDir.d.ts +0 -30
  56. package/dist/types/policy-packs.d.ts +0 -98
  57. package/dist/types/policy.d.ts +0 -12
  58. package/dist/types/presets.d.ts +0 -72
  59. package/dist/types/quarantine/index.d.ts +0 -18
  60. package/dist/types/quarantine/storage.d.ts +0 -77
  61. package/dist/types/quarantine/types.d.ts +0 -78
  62. package/dist/types/quarantine/workflow.d.ts +0 -97
  63. package/dist/types/react-index.d.ts +0 -13
  64. package/dist/types/risk.d.ts +0 -18
  65. package/dist/types/scan/remote.d.ts +0 -12
  66. package/dist/types/scan.d.ts +0 -17
  67. package/dist/types/scanners/common-heuristics.d.ts +0 -14
  68. package/dist/types/scanners/zip-bomb-guard.d.ts +0 -9
  69. package/dist/types/scanners/zipTraversalGuard.d.ts +0 -19
  70. package/dist/types/src/audit.d.ts +0 -84
  71. package/dist/types/src/browser-index.d.ts +0 -29
  72. package/dist/types/src/config.d.ts +0 -143
  73. package/dist/types/src/engines/dynamic-taint.d.ts +0 -102
  74. package/dist/types/src/engines/hybrid-orchestrator.d.ts +0 -65
  75. package/dist/types/src/engines/hybrid-taint-integration.d.ts +0 -129
  76. package/dist/types/src/engines/taint-policies.d.ts +0 -84
  77. package/dist/types/src/hipaa-compliance.d.ts +0 -110
  78. package/dist/types/src/hooks.d.ts +0 -89
  79. package/dist/types/src/index.d.ts +0 -29
  80. package/dist/types/src/magic.d.ts +0 -7
  81. package/dist/types/src/node/scanDir.d.ts +0 -30
  82. package/dist/types/src/policy-packs.d.ts +0 -98
  83. package/dist/types/src/policy.d.ts +0 -12
  84. package/dist/types/src/presets.d.ts +0 -72
  85. package/dist/types/src/quarantine/index.d.ts +0 -18
  86. package/dist/types/src/quarantine/storage.d.ts +0 -77
  87. package/dist/types/src/quarantine/types.d.ts +0 -78
  88. package/dist/types/src/quarantine/workflow.d.ts +0 -97
  89. package/dist/types/src/react-index.d.ts +0 -13
  90. package/dist/types/src/risk.d.ts +0 -18
  91. package/dist/types/src/scan/remote.d.ts +0 -12
  92. package/dist/types/src/scan.d.ts +0 -17
  93. package/dist/types/src/scanners/common-heuristics.d.ts +0 -14
  94. package/dist/types/src/scanners/zip-bomb-guard.d.ts +0 -11
  95. package/dist/types/src/scanners/zipTraversalGuard.d.ts +0 -19
  96. package/dist/types/src/stream.d.ts +0 -10
  97. package/dist/types/src/types/decompilation.d.ts +0 -96
  98. package/dist/types/src/types/taint-tracking.d.ts +0 -495
  99. package/dist/types/src/types.d.ts +0 -48
  100. package/dist/types/src/useFileScanner.d.ts +0 -15
  101. package/dist/types/src/utils/advanced-detection.d.ts +0 -21
  102. package/dist/types/src/utils/batch-scanner.d.ts +0 -62
  103. package/dist/types/src/utils/cache-manager.d.ts +0 -95
  104. package/dist/types/src/utils/export.d.ts +0 -51
  105. package/dist/types/src/utils/performance-metrics.d.ts +0 -68
  106. package/dist/types/src/utils/threat-intelligence.d.ts +0 -96
  107. package/dist/types/src/validate.d.ts +0 -7
  108. package/dist/types/src/verdict.d.ts +0 -2
  109. package/dist/types/src/yara/browser.d.ts +0 -7
  110. package/dist/types/src/yara/index.d.ts +0 -17
  111. package/dist/types/src/yara/node.d.ts +0 -2
  112. package/dist/types/src/yara/remote.d.ts +0 -10
  113. package/dist/types/src/yara-bridge.d.ts +0 -3
  114. package/dist/types/src/zip.d.ts +0 -13
  115. package/dist/types/stream.d.ts +0 -10
  116. package/dist/types/types/decompilation.d.ts +0 -96
  117. package/dist/types/types/taint-tracking.d.ts +0 -495
  118. package/dist/types/types.d.ts +0 -48
  119. package/dist/types/useFileScanner.d.ts +0 -15
  120. package/dist/types/utils/advanced-detection.d.ts +0 -21
  121. package/dist/types/utils/batch-scanner.d.ts +0 -62
  122. package/dist/types/utils/cache-manager.d.ts +0 -95
  123. package/dist/types/utils/export.d.ts +0 -51
  124. package/dist/types/utils/performance-metrics.d.ts +0 -68
  125. package/dist/types/utils/threat-intelligence.d.ts +0 -96
  126. package/dist/types/validate.d.ts +0 -7
  127. package/dist/types/verdict.d.ts +0 -2
  128. package/dist/types/yara/browser.d.ts +0 -7
  129. package/dist/types/yara/index.d.ts +0 -17
  130. package/dist/types/yara/node.d.ts +0 -2
  131. package/dist/types/yara/remote.d.ts +0 -10
  132. package/dist/types/yara-bridge.d.ts +0 -3
  133. package/dist/types/zip.d.ts +0 -13
@@ -1,2525 +0,0 @@
1
- import * as crypto from 'crypto';
2
- import { createHash } from 'crypto';
3
- import * as os from 'os';
4
- import * as path from 'path';
5
- import { createInflateRaw } from 'zlib';
6
-
7
- /**
8
- * Advanced configuration system for pompelmi
9
- * @module config
10
- */
11
- /**
12
- * Default configuration
13
- */
14
- const DEFAULT_CONFIG = {
15
- defaultPreset: "zip-basic",
16
- performance: {
17
- enableCache: false,
18
- enablePerformanceTracking: false,
19
- enableParallel: true,
20
- maxConcurrency: 5,
21
- cacheOptions: {
22
- maxSize: 1000,
23
- ttl: 3600000, // 1 hour
24
- enableLRU: true,
25
- enableStats: false,
26
- },
27
- },
28
- security: {
29
- maxFileSize: 100 * 1024 * 1024, // 100MB
30
- enableThreatIntel: false,
31
- scanTimeout: 30000, // 30 seconds
32
- strictMode: false,
33
- },
34
- advanced: {
35
- enablePolyglotDetection: true,
36
- enableObfuscationDetection: true,
37
- enableNestedArchiveAnalysis: true,
38
- maxArchiveDepth: 5,
39
- },
40
- logging: {
41
- verbose: false,
42
- level: "info",
43
- enableStats: false,
44
- },
45
- };
46
- /**
47
- * Configuration presets for common use cases
48
- */
49
- const CONFIG_PRESETS = {
50
- /** Fast scanning with minimal features */
51
- fast: {
52
- defaultPreset: "basic",
53
- performance: {
54
- enableCache: true,
55
- enablePerformanceTracking: false,
56
- maxConcurrency: 10,
57
- },
58
- advanced: {
59
- enablePolyglotDetection: false,
60
- enableObfuscationDetection: false,
61
- enableNestedArchiveAnalysis: false,
62
- },
63
- },
64
- /** Balanced scanning (recommended) */
65
- balanced: DEFAULT_CONFIG,
66
- /** Thorough scanning with all features */
67
- thorough: {
68
- defaultPreset: "advanced",
69
- performance: {
70
- enableCache: true,
71
- enablePerformanceTracking: true,
72
- maxConcurrency: 3,
73
- },
74
- security: {
75
- maxFileSize: 500 * 1024 * 1024, // 500MB
76
- enableThreatIntel: true,
77
- scanTimeout: 60000, // 60 seconds
78
- strictMode: true,
79
- },
80
- advanced: {
81
- enablePolyglotDetection: true,
82
- enableObfuscationDetection: true,
83
- enableNestedArchiveAnalysis: true,
84
- maxArchiveDepth: 10,
85
- },
86
- logging: {
87
- verbose: true,
88
- level: "debug",
89
- enableStats: true,
90
- },
91
- },
92
- /** Production-ready configuration */
93
- production: {
94
- defaultPreset: "advanced",
95
- performance: {
96
- enableCache: true,
97
- enablePerformanceTracking: true,
98
- maxConcurrency: 5,
99
- cacheOptions: {
100
- maxSize: 5000,
101
- ttl: 7200000, // 2 hours
102
- enableLRU: true,
103
- enableStats: true,
104
- },
105
- },
106
- security: {
107
- maxFileSize: 200 * 1024 * 1024, // 200MB
108
- enableThreatIntel: true,
109
- scanTimeout: 45000,
110
- strictMode: false,
111
- },
112
- advanced: {
113
- enablePolyglotDetection: true,
114
- enableObfuscationDetection: true,
115
- enableNestedArchiveAnalysis: true,
116
- maxArchiveDepth: 7,
117
- },
118
- logging: {
119
- verbose: false,
120
- level: "warn",
121
- enableStats: true,
122
- },
123
- },
124
- /** Development configuration */
125
- development: {
126
- defaultPreset: "basic",
127
- performance: {
128
- enableCache: false,
129
- enablePerformanceTracking: true,
130
- maxConcurrency: 3,
131
- },
132
- security: {
133
- maxFileSize: 50 * 1024 * 1024, // 50MB
134
- scanTimeout: 15000,
135
- strictMode: false,
136
- },
137
- logging: {
138
- verbose: true,
139
- level: "debug",
140
- enableStats: true,
141
- },
142
- },
143
- };
144
- /**
145
- * Configuration manager
146
- */
147
- class ConfigManager {
148
- constructor(initialConfig) {
149
- this.config = this.mergeConfig(DEFAULT_CONFIG, initialConfig || {});
150
- }
151
- /**
152
- * Get current configuration
153
- */
154
- getConfig() {
155
- return { ...this.config };
156
- }
157
- /**
158
- * Update configuration
159
- */
160
- updateConfig(updates) {
161
- this.config = this.mergeConfig(this.config, updates);
162
- }
163
- /**
164
- * Load a preset configuration
165
- */
166
- loadPreset(preset) {
167
- const presetConfig = CONFIG_PRESETS[preset];
168
- this.config = this.mergeConfig(DEFAULT_CONFIG, presetConfig);
169
- }
170
- /**
171
- * Reset to default configuration
172
- */
173
- reset() {
174
- this.config = { ...DEFAULT_CONFIG };
175
- }
176
- /**
177
- * Get a specific configuration value
178
- */
179
- get(key) {
180
- return this.config[key];
181
- }
182
- /**
183
- * Set a specific configuration value
184
- */
185
- set(key, value) {
186
- this.config[key] = value;
187
- }
188
- /**
189
- * Validate configuration
190
- */
191
- validate() {
192
- const errors = [];
193
- // Validate performance settings
194
- if (this.config.performance?.maxConcurrency !== undefined) {
195
- if (this.config.performance.maxConcurrency < 1) {
196
- errors.push("maxConcurrency must be at least 1");
197
- }
198
- if (this.config.performance.maxConcurrency > 50) {
199
- errors.push("maxConcurrency should not exceed 50");
200
- }
201
- }
202
- // Validate security settings
203
- if (this.config.security?.maxFileSize !== undefined) {
204
- if (this.config.security.maxFileSize < 1024) {
205
- errors.push("maxFileSize must be at least 1KB");
206
- }
207
- }
208
- if (this.config.security?.scanTimeout !== undefined) {
209
- if (this.config.security.scanTimeout < 1000) {
210
- errors.push("scanTimeout must be at least 1000ms");
211
- }
212
- }
213
- // Validate advanced settings
214
- if (this.config.advanced?.maxArchiveDepth !== undefined) {
215
- if (this.config.advanced.maxArchiveDepth < 1) {
216
- errors.push("maxArchiveDepth must be at least 1");
217
- }
218
- if (this.config.advanced.maxArchiveDepth > 20) {
219
- errors.push("maxArchiveDepth should not exceed 20");
220
- }
221
- }
222
- return {
223
- valid: errors.length === 0,
224
- errors,
225
- };
226
- }
227
- /**
228
- * Deep merge configuration objects
229
- */
230
- mergeConfig(base, updates) {
231
- return {
232
- ...base,
233
- ...updates,
234
- performance: {
235
- ...base.performance,
236
- ...updates.performance,
237
- cacheOptions: {
238
- ...base.performance?.cacheOptions,
239
- ...updates.performance?.cacheOptions,
240
- },
241
- },
242
- security: {
243
- ...base.security,
244
- ...updates.security,
245
- },
246
- advanced: {
247
- ...base.advanced,
248
- ...updates.advanced,
249
- },
250
- logging: {
251
- ...base.logging,
252
- ...updates.logging,
253
- },
254
- callbacks: {
255
- ...base.callbacks,
256
- ...updates.callbacks,
257
- },
258
- presetOptions: {
259
- ...base.presetOptions,
260
- ...updates.presetOptions,
261
- },
262
- };
263
- }
264
- /**
265
- * Export configuration as JSON
266
- */
267
- toJSON() {
268
- return JSON.stringify(this.config, null, 2);
269
- }
270
- /**
271
- * Load configuration from JSON
272
- */
273
- fromJSON(json) {
274
- try {
275
- const parsed = JSON.parse(json);
276
- this.config = this.mergeConfig(DEFAULT_CONFIG, parsed);
277
- }
278
- catch (error) {
279
- throw new Error(`Failed to parse configuration JSON: ${error}`);
280
- }
281
- }
282
- }
283
- /**
284
- * Create a new configuration manager
285
- */
286
- function createConfig(config) {
287
- return new ConfigManager(config);
288
- }
289
- /**
290
- * Get a preset configuration
291
- */
292
- function getPresetConfig(preset) {
293
- return { ...DEFAULT_CONFIG, ...CONFIG_PRESETS[preset] };
294
- }
295
-
296
- /**
297
- * HIPAA Compliance Module for Pompelmi
298
- *
299
- * This module provides comprehensive HIPAA compliance features for healthcare environments
300
- * where Pompelmi is used to analyze potentially compromised systems containing PHI.
301
- *
302
- * Key protections:
303
- * - Data sanitization and redaction
304
- * - Secure temporary file handling
305
- * - Audit logging
306
- * - Memory protection
307
- * - Error message sanitization
308
- */
309
- class HipaaComplianceManager {
310
- constructor(config) {
311
- this.auditEvents = [];
312
- this.config = {
313
- sanitizeErrors: true,
314
- sanitizeFilenames: true,
315
- encryptTempFiles: true,
316
- memoryProtection: true,
317
- requireSecureTransport: true,
318
- ...config,
319
- enabled: config.enabled !== undefined ? config.enabled : true,
320
- };
321
- this.sessionId = this.generateSessionId();
322
- }
323
- /**
324
- * Sanitize filename to prevent PHI leakage in logs
325
- */
326
- sanitizeFilename(filename) {
327
- if (!this.config.enabled || !this.config.sanitizeFilenames || !filename) {
328
- return filename || "unknown";
329
- }
330
- // Remove potentially sensitive path information
331
- const basename = path.basename(filename);
332
- // Hash the filename to create a consistent but non-revealing identifier
333
- const hash = crypto.createHash("sha256").update(basename).digest("hex").substring(0, 8);
334
- // Preserve file extension for analysis purposes
335
- const ext = path.extname(basename);
336
- return `file_${hash}${ext}`;
337
- }
338
- /**
339
- * Sanitize error messages to prevent PHI exposure
340
- */
341
- sanitizeError(error) {
342
- if (!this.config.enabled || !this.config.sanitizeErrors) {
343
- return typeof error === "string" ? error : error.message;
344
- }
345
- const message = typeof error === "string" ? error : error.message;
346
- // Remove common patterns that might contain PHI
347
- const sanitized = message
348
- // Remove file paths
349
- .replace(/[A-Za-z]:\\\\[^\\s]+/g, "[REDACTED_PATH]")
350
- .replace(/\/[^\\s]+/g, "[REDACTED_PATH]")
351
- // Remove potential patient identifiers (numbers that could be MRNs, SSNs)
352
- .replace(/\\b\\d{3}-?\\d{2}-?\\d{4}\\b/g, "[REDACTED_ID]")
353
- .replace(/\\b\\d{6,}\\b/g, "[REDACTED_ID]")
354
- // Remove email addresses
355
- .replace(/[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\\.[a-zA-Z]{2,}/g, "[REDACTED_EMAIL]")
356
- // Remove potential names (capitalize words in error messages)
357
- .replace(/\\b[A-Z][a-z]+\\s+[A-Z][a-z]+\\b/g, "[REDACTED_NAME]")
358
- // Remove IP addresses
359
- .replace(/\\b(?:\\d{1,3}\\.){3}\\d{1,3}\\b/g, "[REDACTED_IP]");
360
- return sanitized;
361
- }
362
- /**
363
- * Create secure temporary file path with encryption if enabled
364
- */
365
- createSecureTempPath(prefix = "pompelmi") {
366
- if (!this.config.enabled) {
367
- return path.join(os.tmpdir(), `${prefix}-${Date.now()}-${Math.random().toString(36).slice(2)}`);
368
- }
369
- // Use cryptographically secure random names
370
- const randomId = crypto.randomBytes(16).toString("hex");
371
- const timestamp = Date.now();
372
- // Create path in secure temp directory
373
- const secureTempDir = this.getSecureTempDir();
374
- const tempPath = path.join(secureTempDir, `${prefix}-${timestamp}-${randomId}`);
375
- this.auditLog("temp_file_created", {
376
- action: "create_temp_file",
377
- success: true,
378
- metadata: { path: this.sanitizeFilename(tempPath) },
379
- });
380
- return tempPath;
381
- }
382
- /**
383
- * Get or create secure temporary directory with restricted permissions
384
- */
385
- getSecureTempDir() {
386
- const secureTempPath = path.join(os.tmpdir(), "pompelmi-secure");
387
- try {
388
- const fs = require("fs");
389
- if (!fs.existsSync(secureTempPath)) {
390
- fs.mkdirSync(secureTempPath, { mode: 0o700 }); // Owner read/write/execute only
391
- }
392
- }
393
- catch (error) {
394
- // Fallback to system temp
395
- return os.tmpdir();
396
- }
397
- return secureTempPath;
398
- }
399
- /**
400
- * Secure file cleanup with multiple overwrite passes
401
- */
402
- async secureFileCleanup(filePath) {
403
- if (!this.config.enabled) {
404
- try {
405
- const fs = await import('fs/promises');
406
- await fs.unlink(filePath);
407
- }
408
- catch {
409
- // Ignore cleanup errors
410
- }
411
- return;
412
- }
413
- try {
414
- const fs = await import('fs/promises');
415
- const stats = await fs.stat(filePath);
416
- if (this.config.memoryProtection) {
417
- // Overwrite file with random data multiple times (DoD 5220.22-M standard)
418
- const fileSize = stats.size;
419
- const buffer = crypto.randomBytes(Math.min(fileSize, 64 * 1024)); // 64KB chunks
420
- for (let pass = 0; pass < 3; pass++) {
421
- const handle = await fs.open(filePath, "r+");
422
- try {
423
- for (let offset = 0; offset < fileSize; offset += buffer.length) {
424
- const chunk = offset + buffer.length > fileSize ? buffer.subarray(0, fileSize - offset) : buffer;
425
- await handle.write(chunk, 0, chunk.length, offset);
426
- }
427
- await handle.sync();
428
- }
429
- finally {
430
- await handle.close();
431
- }
432
- }
433
- }
434
- // Final deletion
435
- await fs.unlink(filePath);
436
- this.auditLog("temp_file_deleted", {
437
- action: "secure_delete",
438
- success: true,
439
- metadata: {
440
- path: this.sanitizeFilename(filePath),
441
- overwritePasses: this.config.memoryProtection ? 3 : 0,
442
- },
443
- });
444
- }
445
- catch (error) {
446
- this.auditLog("temp_file_deleted", {
447
- action: "secure_delete",
448
- success: false,
449
- sanitizedError: this.sanitizeError(error),
450
- metadata: { path: this.sanitizeFilename(filePath) },
451
- });
452
- }
453
- }
454
- /**
455
- * Calculate secure file hash for audit purposes
456
- */
457
- calculateFileHash(data) {
458
- return crypto.createHash("sha256").update(data).digest("hex");
459
- }
460
- /**
461
- * Log audit event
462
- */
463
- auditLog(eventType, details) {
464
- if (!this.config.enabled)
465
- return;
466
- const event = {
467
- timestamp: new Date().toISOString(),
468
- eventType,
469
- sessionId: this.sessionId,
470
- details: {
471
- action: details.action || "unknown",
472
- success: details.success ?? true,
473
- ...details,
474
- },
475
- };
476
- this.auditEvents.push(event);
477
- // Write to audit log file if configured
478
- if (this.config.auditLogPath) {
479
- this.writeAuditLog(event).catch(() => {
480
- // Silent failure to prevent error loops
481
- });
482
- }
483
- }
484
- /**
485
- * Write audit event to file
486
- */
487
- async writeAuditLog(event) {
488
- if (!this.config.auditLogPath)
489
- return;
490
- try {
491
- const fs = await import('fs/promises');
492
- const logLine = JSON.stringify(event) + "\\n";
493
- await fs.appendFile(this.config.auditLogPath, logLine, { flag: "a" });
494
- }
495
- catch {
496
- // Silent failure
497
- }
498
- }
499
- /**
500
- * Generate cryptographically secure session ID
501
- */
502
- generateSessionId() {
503
- return crypto.randomBytes(16).toString("hex");
504
- }
505
- /**
506
- * Get current audit events for this session
507
- */
508
- getAuditEvents() {
509
- return [...this.auditEvents];
510
- }
511
- /**
512
- * Clear sensitive data from memory
513
- */
514
- clearSensitiveData() {
515
- if (!this.config.enabled || !this.config.memoryProtection)
516
- return;
517
- // Clear audit events
518
- this.auditEvents.length = 0;
519
- // Force garbage collection if available
520
- if (global.gc) {
521
- global.gc();
522
- }
523
- }
524
- /**
525
- * Validate transport security
526
- */
527
- validateTransportSecurity(url) {
528
- if (!this.config.enabled || !this.config.requireSecureTransport) {
529
- return true;
530
- }
531
- if (!url)
532
- return true;
533
- try {
534
- const urlObj = new URL(url);
535
- const isSecure = urlObj.protocol === "https:" ||
536
- urlObj.hostname === "localhost" ||
537
- urlObj.hostname === "127.0.0.1";
538
- if (!isSecure) {
539
- this.auditLog("security_violation", {
540
- action: "insecure_transport",
541
- success: false,
542
- metadata: { protocol: urlObj.protocol, hostname: urlObj.hostname },
543
- });
544
- }
545
- return isSecure;
546
- }
547
- catch {
548
- return false;
549
- }
550
- }
551
- }
552
- // Global HIPAA compliance instance
553
- let hipaaManager = null;
554
- /**
555
- * Initialize HIPAA compliance
556
- */
557
- function initializeHipaaCompliance(config) {
558
- hipaaManager = new HipaaComplianceManager(config);
559
- return hipaaManager;
560
- }
561
- /**
562
- * Get current HIPAA compliance manager
563
- */
564
- function getHipaaManager() {
565
- return hipaaManager;
566
- }
567
- /**
568
- * HIPAA-compliant error wrapper
569
- */
570
- function createHipaaError(error, context) {
571
- const manager = getHipaaManager();
572
- if (!manager) {
573
- return typeof error === "string" ? new Error(error) : error;
574
- }
575
- const sanitizedMessage = manager.sanitizeError(error);
576
- const hipaaError = new Error(sanitizedMessage);
577
- manager.auditLog("error_occurred", {
578
- action: context || "error",
579
- success: false,
580
- sanitizedError: sanitizedMessage,
581
- });
582
- return hipaaError;
583
- }
584
- /**
585
- * HIPAA-compliant temporary file utilities
586
- */
587
- const HipaaTemp = {
588
- createPath: (prefix) => {
589
- const manager = getHipaaManager();
590
- return manager
591
- ? manager.createSecureTempPath(prefix)
592
- : path.join(os.tmpdir(), `${prefix || "pompelmi"}-${Date.now()}`);
593
- },
594
- cleanup: async (filePath) => {
595
- const manager = getHipaaManager();
596
- if (manager) {
597
- await manager.secureFileCleanup(filePath);
598
- }
599
- else {
600
- try {
601
- const fs = await import('fs/promises');
602
- await fs.unlink(filePath);
603
- }
604
- catch {
605
- // Ignore errors
606
- }
607
- }
608
- },
609
- };
610
-
611
- const MB$1 = 1024 * 1024;
612
- const DEFAULT_POLICY = {
613
- includeExtensions: ["zip", "png", "jpg", "jpeg", "pdf"],
614
- allowedMimeTypes: ["application/zip", "image/png", "image/jpeg", "application/pdf", "text/plain"],
615
- maxFileSizeBytes: 20 * MB$1,
616
- timeoutMs: 5000,
617
- concurrency: 4,
618
- failClosed: true,
619
- };
620
- function definePolicy(input = {}) {
621
- const p = { ...DEFAULT_POLICY, ...input };
622
- if (!Array.isArray(p.includeExtensions))
623
- throw new TypeError("includeExtensions must be string[]");
624
- if (!Array.isArray(p.allowedMimeTypes))
625
- throw new TypeError("allowedMimeTypes must be string[]");
626
- if (!(Number.isFinite(p.maxFileSizeBytes) && p.maxFileSizeBytes > 0))
627
- throw new TypeError("maxFileSizeBytes must be > 0");
628
- if (!(Number.isFinite(p.timeoutMs) && p.timeoutMs > 0))
629
- throw new TypeError("timeoutMs must be > 0");
630
- if (!(Number.isInteger(p.concurrency) && p.concurrency > 0))
631
- throw new TypeError("concurrency must be > 0");
632
- return p;
633
- }
634
-
635
- /**
636
- * Policy packs for Pompelmi.
637
- *
638
- * Pre-configured, named policies for common upload scenarios. Each pack
639
- * defines the file type allowlist, size limits, and timeout appropriate for
640
- * its use case.
641
- *
642
- * All packs are built on `definePolicy` and are fully overridable:
643
- *
644
- * ```ts
645
- * import { POLICY_PACKS } from 'pompelmi/policy-packs';
646
- *
647
- * // Use a pack as-is:
648
- * const policy = POLICY_PACKS['images-only'];
649
- *
650
- * // Or override individual fields:
651
- * import { definePolicy } from 'pompelmi';
652
- * const custom = definePolicy({ ...POLICY_PACKS['documents-only'], maxFileSizeBytes: 5 * 1024 * 1024 });
653
- * ```
654
- *
655
- * These packs are *deterministic* and *descriptor-based* — they do not
656
- * depend on any external threat intelligence feed.
657
- *
658
- * @module policy-packs
659
- */
660
- const KB = 1024;
661
- const MB = 1024 * KB;
662
- // ── Policy packs ──────────────────────────────────────────────────────────────
663
- /**
664
- * Documents-only policy.
665
- *
666
- * Appropriate for: document management APIs, PDF/Office file upload endpoints,
667
- * data import pipelines.
668
- *
669
- * Allowed: PDF, Word (.docx/.doc), Excel (.xlsx/.xls), PowerPoint (.pptx/.ppt),
670
- * CSV, plain text, JSON, YAML, ODT/ODS/ODP (OpenDocument).
671
- * Max size: 25 MB.
672
- */
673
- const DOCUMENTS_ONLY = definePolicy({
674
- includeExtensions: [
675
- "pdf",
676
- "doc",
677
- "docx",
678
- "xls",
679
- "xlsx",
680
- "ppt",
681
- "pptx",
682
- "odt",
683
- "ods",
684
- "odp",
685
- "csv",
686
- "txt",
687
- "json",
688
- "yaml",
689
- "yml",
690
- "md",
691
- ],
692
- allowedMimeTypes: [
693
- "application/pdf",
694
- "application/msword",
695
- "application/vnd.openxmlformats-officedocument.wordprocessingml.document",
696
- "application/vnd.ms-excel",
697
- "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
698
- "application/vnd.ms-powerpoint",
699
- "application/vnd.openxmlformats-officedocument.presentationml.presentation",
700
- "application/vnd.oasis.opendocument.text",
701
- "application/vnd.oasis.opendocument.spreadsheet",
702
- "application/vnd.oasis.opendocument.presentation",
703
- "text/csv",
704
- "text/plain",
705
- "application/json",
706
- "text/yaml",
707
- "text/markdown",
708
- ],
709
- maxFileSizeBytes: 25 * MB,
710
- timeoutMs: 10000,
711
- concurrency: 4,
712
- failClosed: true,
713
- });
714
- /**
715
- * Images-only policy.
716
- *
717
- * Appropriate for: avatar uploads, product image APIs, content platforms with
718
- * user-generated imagery.
719
- *
720
- * Allowed: JPEG, PNG, GIF, WebP, AVIF, TIFF, BMP, ICO.
721
- * Max size: 10 MB.
722
- * Note: SVG is intentionally excluded — inline SVGs can contain scripts.
723
- */
724
- const IMAGES_ONLY = definePolicy({
725
- includeExtensions: ["jpg", "jpeg", "png", "gif", "webp", "avif", "tiff", "tif", "bmp", "ico"],
726
- allowedMimeTypes: [
727
- "image/jpeg",
728
- "image/png",
729
- "image/gif",
730
- "image/webp",
731
- "image/avif",
732
- "image/tiff",
733
- "image/bmp",
734
- "image/x-icon",
735
- "image/vnd.microsoft.icon",
736
- ],
737
- maxFileSizeBytes: 10 * MB,
738
- timeoutMs: 5000,
739
- concurrency: 8,
740
- failClosed: true,
741
- });
742
- /**
743
- * Strict public-upload policy.
744
- *
745
- * Appropriate for: anonymous or low-trust upload endpoints, public APIs,
746
- * any surface exposed to untrusted users.
747
- *
748
- * Aggressive size limit (5 MB), short timeout, fail-closed, narrow MIME
749
- * allowlist. Only allows plain images and PDF.
750
- */
751
- const STRICT_PUBLIC_UPLOAD = definePolicy({
752
- includeExtensions: ["jpg", "jpeg", "png", "webp", "pdf"],
753
- allowedMimeTypes: ["image/jpeg", "image/png", "image/webp", "application/pdf"],
754
- maxFileSizeBytes: 5 * MB,
755
- timeoutMs: 4000,
756
- concurrency: 2,
757
- failClosed: true,
758
- });
759
- /**
760
- * Conservative default policy.
761
- *
762
- * A hardened version of the built-in `DEFAULT_POLICY` suitable for
763
- * production without further customisation. Stricter size limit and
764
- * shorter timeout than the permissive default.
765
- */
766
- const CONSERVATIVE_DEFAULT = definePolicy({
767
- includeExtensions: ["zip", "png", "jpg", "jpeg", "pdf", "txt", "csv", "docx", "xlsx"],
768
- allowedMimeTypes: [
769
- "application/zip",
770
- "image/png",
771
- "image/jpeg",
772
- "application/pdf",
773
- "text/plain",
774
- "text/csv",
775
- "application/vnd.openxmlformats-officedocument.wordprocessingml.document",
776
- "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
777
- ],
778
- maxFileSizeBytes: 10 * MB,
779
- timeoutMs: 8000,
780
- concurrency: 4,
781
- failClosed: true,
782
- });
783
- /**
784
- * Archives policy.
785
- *
786
- * Appropriate for: endpoints that accept ZIP, tar, or compressed archives.
787
- * Combines a generous size allowance with a longer timeout for deep inspection.
788
- *
789
- * NOTE: Pair this policy with `createZipBombGuard()` to defend against
790
- * decompression-bomb attacks:
791
- *
792
- * ```ts
793
- * import { composeScanners, createZipBombGuard, CommonHeuristicsScanner } from 'pompelmi';
794
- * const scanner = composeScanners(
795
- * [['zipGuard', createZipBombGuard()], ['heuristics', CommonHeuristicsScanner]]
796
- * );
797
- * ```
798
- */
799
- const ARCHIVES = definePolicy({
800
- includeExtensions: ["zip", "tar", "gz", "tgz", "bz2", "xz", "7z", "rar"],
801
- allowedMimeTypes: [
802
- "application/zip",
803
- "application/x-tar",
804
- "application/gzip",
805
- "application/x-bzip2",
806
- "application/x-xz",
807
- "application/x-7z-compressed",
808
- "application/x-rar-compressed",
809
- ],
810
- maxFileSizeBytes: 100 * MB,
811
- timeoutMs: 30000,
812
- concurrency: 2,
813
- failClosed: true,
814
- });
815
- /**
816
- * Named map of all built-in policy packs.
817
- *
818
- * ```ts
819
- * import { POLICY_PACKS } from 'pompelmi/policy-packs';
820
- * const policy = POLICY_PACKS['strict-public-upload'];
821
- * ```
822
- */
823
- const POLICY_PACKS = {
824
- "documents-only": DOCUMENTS_ONLY,
825
- "images-only": IMAGES_ONLY,
826
- "strict-public-upload": STRICT_PUBLIC_UPLOAD,
827
- "conservative-default": CONSERVATIVE_DEFAULT,
828
- archives: ARCHIVES,
829
- };
830
- /**
831
- * Look up a policy pack by name.
832
- * Throws if the name is not recognised.
833
- */
834
- function getPolicyPack(name) {
835
- const policy = POLICY_PACKS[name];
836
- if (!policy)
837
- throw new Error(`Unknown policy pack: '${name}'. Valid names: ${Object.keys(POLICY_PACKS).join(", ")}`);
838
- return policy;
839
- }
840
-
841
- function hasAsciiToken(buf, token) {
842
- // Use latin1 so we can safely search binary
843
- return buf.indexOf(token, 0, "latin1") !== -1;
844
- }
845
- function startsWith(buf, bytes) {
846
- if (buf.length < bytes.length)
847
- return false;
848
- for (let i = 0; i < bytes.length; i++)
849
- if (buf[i] !== bytes[i])
850
- return false;
851
- return true;
852
- }
853
- function isPDF(buf) {
854
- // %PDF-
855
- return startsWith(buf, [0x25, 0x50, 0x44, 0x46, 0x2d]);
856
- }
857
- function isOleCfb(buf) {
858
- // D0 CF 11 E0 A1 B1 1A E1
859
- const sig = [0xd0, 0xcf, 0x11, 0xe0, 0xa1, 0xb1, 0x1a, 0xe1];
860
- return startsWith(buf, sig);
861
- }
862
- function isZipLike$1(buf) {
863
- // PK\x03\x04
864
- return startsWith(buf, [0x50, 0x4b, 0x03, 0x04]);
865
- }
866
- function isPeExecutable(buf) {
867
- // "MZ"
868
- return startsWith(buf, [0x4d, 0x5a]);
869
- }
870
- /** OOXML macro hint via filename token in ZIP container */
871
- function hasOoxmlMacros(buf) {
872
- if (!isZipLike$1(buf))
873
- return false;
874
- return hasAsciiToken(buf, "vbaProject.bin");
875
- }
876
- /** PDF risky features (/JavaScript, /OpenAction, /AA, /Launch) */
877
- function pdfRiskTokens(buf) {
878
- const tokens = ["/JavaScript", "/OpenAction", "/AA", "/Launch"];
879
- return tokens.filter((t) => hasAsciiToken(buf, t));
880
- }
881
- const CommonHeuristicsScanner = {
882
- async scan(input) {
883
- const buf = Buffer.from(input);
884
- const matches = [];
885
- // Office macros (OLE / OOXML)
886
- if (isOleCfb(buf)) {
887
- matches.push({ rule: "office_ole_container", severity: "suspicious" });
888
- }
889
- if (hasOoxmlMacros(buf)) {
890
- matches.push({ rule: "office_ooxml_macros", severity: "suspicious" });
891
- }
892
- // PDF risky tokens
893
- if (isPDF(buf)) {
894
- const toks = pdfRiskTokens(buf);
895
- if (toks.length) {
896
- matches.push({
897
- rule: "pdf_risky_actions",
898
- severity: "suspicious",
899
- meta: { tokens: toks },
900
- });
901
- }
902
- }
903
- // Executable header
904
- if (isPeExecutable(buf)) {
905
- matches.push({ rule: "pe_executable_signature", severity: "suspicious" });
906
- }
907
- // EICAR test file
908
- const EICAR_NEEDLE = "X5O!P%@AP[4\\PZX54(P^)7CC)7}$EICAR-STANDARD-ANTIVIRUS-TEST-FILE!";
909
- if (hasAsciiToken(buf, EICAR_NEEDLE)) {
910
- matches.push({
911
- rule: "eicar_test_file",
912
- severity: "high",
913
- meta: { note: "EICAR standard antivirus test file detected" },
914
- });
915
- }
916
- return matches;
917
- },
918
- };
919
-
920
- function toScanFn(s) {
921
- return (typeof s === "function" ? s : s.scan);
922
- }
923
- /** Map a Match's severity field to a Verdict for stopOn comparison. */
924
- function matchToVerdict(m) {
925
- const s = m.severity;
926
- if (s === "critical" || s === "high" || s === "malicious")
927
- return "malicious";
928
- if (s === "medium" || s === "low" || s === "suspicious" || s === "info")
929
- return "suspicious";
930
- return "clean";
931
- }
932
- /** Highest verdict across all matches in the list. */
933
- function highestSeverity(matches) {
934
- if (matches.length === 0)
935
- return null;
936
- if (matches.some((m) => matchToVerdict(m) === "malicious"))
937
- return "malicious";
938
- if (matches.some((m) => matchToVerdict(m) === "suspicious"))
939
- return "suspicious";
940
- return "clean";
941
- }
942
- const SEVERITY_RANK = { malicious: 2, suspicious: 1, clean: 0 };
943
- function shouldStop(matches, stopOn) {
944
- if (!stopOn)
945
- return false;
946
- const highest = highestSeverity(matches);
947
- if (!highest)
948
- return false;
949
- return SEVERITY_RANK[highest] >= SEVERITY_RANK[stopOn];
950
- }
951
- async function runWithTimeout(fn, timeoutMs) {
952
- if (!timeoutMs)
953
- return fn();
954
- return new Promise((resolve, reject) => {
955
- const timer = setTimeout(() => reject(new Error("scanner timeout")), timeoutMs);
956
- fn().then((v) => {
957
- clearTimeout(timer);
958
- resolve(v);
959
- }, (e) => {
960
- clearTimeout(timer);
961
- reject(e);
962
- });
963
- });
964
- }
965
- // eslint-disable-next-line @typescript-eslint/no-explicit-any
966
- function composeScanners(...args) {
967
- const first = args[0];
968
- const rest = args.slice(1);
969
- // ── Named-scanner array form ──────────────────────────────────────────────
970
- if (Array.isArray(first) &&
971
- (first.length === 0 || (Array.isArray(first[0]) && typeof first[0][0] === "string"))) {
972
- const entries = first;
973
- const opts = rest.length > 0 &&
974
- !Array.isArray(rest[0]) &&
975
- typeof rest[0] !== "function" &&
976
- !(typeof rest[0] === "object" && rest[0] !== null && "scan" in rest[0])
977
- ? rest[0]
978
- : {};
979
- return async (input, ctx) => {
980
- const all = [];
981
- if (opts.parallel) {
982
- // Parallel execution — collect all results then return
983
- const results = await Promise.allSettled(entries.map(([_name, scanner]) => runWithTimeout(() => toScanFn(scanner)(input, ctx), opts.timeoutMsPerScanner)));
984
- for (let i = 0; i < results.length; i++) {
985
- const result = results[i];
986
- if (result.status === "fulfilled" && Array.isArray(result.value)) {
987
- const matches = opts.tagSourceName
988
- ? result.value.map((m) => ({
989
- ...m,
990
- meta: { ...m.meta, _sourceName: entries[i][0] },
991
- }))
992
- : result.value;
993
- all.push(...matches);
994
- }
995
- }
996
- }
997
- else {
998
- // Sequential execution with optional stopOn short-circuit
999
- for (const [name, scanner] of entries) {
1000
- try {
1001
- const out = await runWithTimeout(() => toScanFn(scanner)(input, ctx), opts.timeoutMsPerScanner);
1002
- if (Array.isArray(out)) {
1003
- const matches = opts.tagSourceName
1004
- ? out.map((m) => ({ ...m, meta: { ...m.meta, _sourceName: name } }))
1005
- : out;
1006
- all.push(...matches);
1007
- if (shouldStop(all, opts.stopOn))
1008
- break;
1009
- }
1010
- }
1011
- catch {
1012
- // individual scanner failure is non-fatal
1013
- }
1014
- }
1015
- }
1016
- return all;
1017
- };
1018
- }
1019
- // ── Variadic form (backward-compatible) ───────────────────────────────────
1020
- const scanners = [first, ...rest].filter(Boolean);
1021
- return async (input, ctx) => {
1022
- const all = [];
1023
- for (const s of scanners) {
1024
- try {
1025
- const out = await toScanFn(s)(input, ctx);
1026
- if (Array.isArray(out))
1027
- all.push(...out);
1028
- }
1029
- catch {
1030
- // ignore individual scanner failures
1031
- }
1032
- }
1033
- return all;
1034
- };
1035
- }
1036
- function createPresetScanner(preset, opts = {}) {
1037
- const baseScanners = [CommonHeuristicsScanner];
1038
- const dynamicScannerPromises = [];
1039
- // Add decompilation scanners based on preset
1040
- if (preset === "decompilation-basic" ||
1041
- preset === "decompilation-deep" ||
1042
- preset === "malware-analysis" ||
1043
- opts.enableDecompilation) {
1044
- const depth = preset === "decompilation-deep" || preset === "malware-analysis"
1045
- ? "deep"
1046
- : preset === "decompilation-basic"
1047
- ? "basic"
1048
- : opts.decompilationDepth || "basic";
1049
- let importModule;
1050
- try {
1051
- // Dynamic import to avoid bundling issues - using Function to bypass TypeScript type checking
1052
- importModule = new Function("specifier", "return import(specifier)");
1053
- }
1054
- catch {
1055
- importModule = undefined;
1056
- }
1057
- if (importModule &&
1058
- (!opts.decompilationEngine ||
1059
- opts.decompilationEngine === "binaryninja-hlil" ||
1060
- opts.decompilationEngine === "both")) {
1061
- dynamicScannerPromises.push(importModule("@pompelmi/engine-binaryninja")
1062
- .then((mod) => mod.createBinaryNinjaScanner({
1063
- timeout: opts.decompilationTimeout || opts.timeout || 30000,
1064
- depth,
1065
- pythonPath: opts.pythonPath,
1066
- binaryNinjaPath: opts.binaryNinjaPath,
1067
- }))
1068
- .catch(() => null));
1069
- }
1070
- if (importModule &&
1071
- (!opts.decompilationEngine ||
1072
- opts.decompilationEngine === "ghidra-pcode" ||
1073
- opts.decompilationEngine === "both")) {
1074
- dynamicScannerPromises.push(importModule("@pompelmi/engine-ghidra")
1075
- .then((mod) => mod.createGhidraScanner({
1076
- timeout: opts.decompilationTimeout || opts.timeout || 30000,
1077
- depth,
1078
- ghidraPath: opts.ghidraPath,
1079
- analyzeHeadless: opts.analyzeHeadless,
1080
- }))
1081
- .catch(() => null));
1082
- }
1083
- }
1084
- let composedScannerPromise;
1085
- const getComposedScanner = async () => {
1086
- composedScannerPromise ?? (composedScannerPromise = Promise.all(dynamicScannerPromises).then((dynamicScanners) => composeScanners(...baseScanners, ...dynamicScanners.filter((scanner) => scanner !== null))));
1087
- return composedScannerPromise;
1088
- };
1089
- return async (input, ctx) => {
1090
- const scanner = await getComposedScanner();
1091
- return scanner(input, ctx);
1092
- };
1093
- }
1094
-
1095
- /**
1096
- * Advanced threat detection utilities
1097
- * @module utils/advanced-detection
1098
- */
1099
- /**
1100
- * Enhanced polyglot file detection
1101
- * Detects files that can be interpreted as multiple formats
1102
- */
1103
- function detectPolyglot(bytes) {
1104
- const matches = [];
1105
- // Check for PDF/ZIP polyglot
1106
- if (isPDFZipPolyglot(bytes)) {
1107
- matches.push({
1108
- rule: "polyglot_pdf_zip",
1109
- severity: "high",
1110
- meta: { description: "File can be interpreted as both PDF and ZIP" },
1111
- });
1112
- }
1113
- // Check for image/script polyglot
1114
- if (isImageScriptPolyglot(bytes)) {
1115
- matches.push({
1116
- rule: "polyglot_image_script",
1117
- severity: "high",
1118
- meta: { description: "Image file contains executable script content" },
1119
- });
1120
- }
1121
- // Check for GIFAR (GIF/JAR polyglot)
1122
- if (isGIFAR(bytes)) {
1123
- matches.push({
1124
- rule: "polyglot_gifar",
1125
- severity: "critical",
1126
- meta: { description: "GIF file contains Java archive" },
1127
- });
1128
- }
1129
- return matches;
1130
- }
1131
- /**
1132
- * Detect obfuscated JavaScript/VBScript
1133
- */
1134
- function detectObfuscatedScripts(bytes) {
1135
- const matches = [];
1136
- const text = new TextDecoder("utf-8", { fatal: false }).decode(bytes.slice(0, Math.min(64 * 1024, bytes.length)));
1137
- // Check for common obfuscation patterns
1138
- const obfuscationPatterns = [
1139
- /eval\s*\(\s*unescape\s*\(/gi,
1140
- /eval\s*\(\s*atob\s*\(/gi,
1141
- /String\.fromCharCode\s*\(\s*\d+(?:\s*,\s*\d+){10,}/gi,
1142
- /[a-z0-9]{100,}/gi, // Long encoded strings
1143
- /\\x[0-9a-f]{2}/gi, // Hex escapes
1144
- ];
1145
- for (const pattern of obfuscationPatterns) {
1146
- if (pattern.test(text)) {
1147
- matches.push({
1148
- rule: "obfuscated_script",
1149
- severity: "medium",
1150
- meta: {
1151
- description: "Detected obfuscated script content",
1152
- pattern: pattern.source,
1153
- },
1154
- });
1155
- break;
1156
- }
1157
- }
1158
- return matches;
1159
- }
1160
- /**
1161
- * Enhanced nested archive detection with depth limits
1162
- */
1163
- function analyzeNestedArchives(bytes, maxDepth = 10) {
1164
- let depth = 0;
1165
- let currentBytes = bytes;
1166
- while (depth < maxDepth) {
1167
- if (isArchive(currentBytes)) {
1168
- depth++;
1169
- {
1170
- break;
1171
- }
1172
- }
1173
- else {
1174
- break;
1175
- }
1176
- }
1177
- return {
1178
- depth,
1179
- hasExcessiveNesting: depth >= 5,
1180
- };
1181
- }
1182
- // Helper functions
1183
- function isPDFZipPolyglot(bytes) {
1184
- if (bytes.length < 8)
1185
- return false;
1186
- // Check for PDF signature
1187
- const hasPDF = bytes[0] === 0x25 && bytes[1] === 0x50 && bytes[2] === 0x44 && bytes[3] === 0x46;
1188
- // Check for ZIP signature anywhere in the file
1189
- let hasZIP = false;
1190
- for (let i = 0; i < Math.min(bytes.length - 4, 1024); i++) {
1191
- if (bytes[i] === 0x50 &&
1192
- bytes[i + 1] === 0x4b &&
1193
- bytes[i + 2] === 0x03 &&
1194
- bytes[i + 3] === 0x04) {
1195
- hasZIP = true;
1196
- break;
1197
- }
1198
- }
1199
- return hasPDF && hasZIP;
1200
- }
1201
- function isImageScriptPolyglot(bytes) {
1202
- if (bytes.length < 100)
1203
- return false;
1204
- // Check for image signatures
1205
- const isImage = (bytes[0] === 0xff && bytes[1] === 0xd8) || // JPEG
1206
- (bytes[0] === 0x89 && bytes[1] === 0x50 && bytes[2] === 0x4e && bytes[3] === 0x47) || // PNG
1207
- (bytes[0] === 0x47 && bytes[1] === 0x49 && bytes[2] === 0x46); // GIF
1208
- if (!isImage)
1209
- return false;
1210
- // Check for script content
1211
- const text = new TextDecoder("utf-8", { fatal: false }).decode(bytes);
1212
- return /<script|javascript:|eval\(|function\s*\(/i.test(text);
1213
- }
1214
- function isGIFAR(bytes) {
1215
- if (bytes.length < 100)
1216
- return false;
1217
- // Check for GIF signature
1218
- const isGIF = bytes[0] === 0x47 && bytes[1] === 0x49 && bytes[2] === 0x46;
1219
- // Check for ZIP/JAR signature
1220
- let hasZIP = false;
1221
- for (let i = 0; i < Math.min(bytes.length - 4, 1024); i++) {
1222
- if (bytes[i] === 0x50 &&
1223
- bytes[i + 1] === 0x4b &&
1224
- bytes[i + 2] === 0x03 &&
1225
- bytes[i + 3] === 0x04) {
1226
- hasZIP = true;
1227
- break;
1228
- }
1229
- }
1230
- return isGIF && hasZIP;
1231
- }
1232
- function isArchive(bytes) {
1233
- if (bytes.length < 4)
1234
- return false;
1235
- return (
1236
- // ZIP
1237
- (bytes[0] === 0x50 && bytes[1] === 0x4b && bytes[2] === 0x03 && bytes[3] === 0x04) ||
1238
- // RAR
1239
- (bytes[0] === 0x52 && bytes[1] === 0x61 && bytes[2] === 0x72 && bytes[3] === 0x21) ||
1240
- // 7z
1241
- (bytes[0] === 0x37 && bytes[1] === 0x7a && bytes[2] === 0xbc && bytes[3] === 0xaf) ||
1242
- // tar.gz
1243
- (bytes[0] === 0x1f && bytes[1] === 0x8b));
1244
- }
1245
-
1246
- /**
1247
- * Cache management system for scan results
1248
- * @module utils/cache-manager
1249
- */
1250
- /**
1251
- * LRU cache for scan results with TTL support
1252
- */
1253
- class ScanCacheManager {
1254
- constructor(options = {}) {
1255
- this.cache = new Map();
1256
- // Statistics
1257
- this.stats = {
1258
- hits: 0,
1259
- misses: 0,
1260
- evictions: 0,
1261
- };
1262
- this.maxSize = options.maxSize ?? 1000;
1263
- this.ttl = options.ttl ?? 3600000; // 1 hour default
1264
- this.enableLRU = options.enableLRU ?? true;
1265
- this.enableStats = options.enableStats ?? false;
1266
- }
1267
- /**
1268
- * Generate cache key from file content
1269
- */
1270
- generateKey(content, preset) {
1271
- const hash = createHash("sha256")
1272
- .update(content)
1273
- .update(preset || "default")
1274
- .digest("hex");
1275
- return hash;
1276
- }
1277
- /**
1278
- * Check if cache entry is still valid
1279
- */
1280
- isValid(entry) {
1281
- return Date.now() - entry.timestamp < this.ttl;
1282
- }
1283
- /**
1284
- * Evict oldest or least-used entry when cache is full
1285
- */
1286
- evict() {
1287
- if (this.cache.size === 0)
1288
- return;
1289
- let targetKey = null;
1290
- let oldestTime = Infinity;
1291
- let lowestAccess = Infinity;
1292
- for (const [key, entry] of this.cache.entries()) {
1293
- if (this.enableLRU) {
1294
- // LRU: evict least recently used
1295
- if (entry.timestamp < oldestTime) {
1296
- oldestTime = entry.timestamp;
1297
- targetKey = key;
1298
- }
1299
- }
1300
- else {
1301
- // LFU: evict least frequently used
1302
- if (entry.accessCount < lowestAccess) {
1303
- lowestAccess = entry.accessCount;
1304
- targetKey = key;
1305
- }
1306
- }
1307
- }
1308
- if (targetKey) {
1309
- this.cache.delete(targetKey);
1310
- if (this.enableStats)
1311
- this.stats.evictions++;
1312
- }
1313
- }
1314
- /**
1315
- * Store scan result in cache
1316
- */
1317
- set(content, report, preset) {
1318
- const key = this.generateKey(content, preset);
1319
- // Evict if necessary
1320
- if (this.cache.size >= this.maxSize) {
1321
- this.evict();
1322
- }
1323
- this.cache.set(key, {
1324
- report,
1325
- timestamp: Date.now(),
1326
- accessCount: 0,
1327
- });
1328
- }
1329
- /**
1330
- * Retrieve scan result from cache
1331
- */
1332
- get(content, preset) {
1333
- const key = this.generateKey(content, preset);
1334
- const entry = this.cache.get(key);
1335
- if (!entry) {
1336
- if (this.enableStats)
1337
- this.stats.misses++;
1338
- return null;
1339
- }
1340
- if (!this.isValid(entry)) {
1341
- this.cache.delete(key);
1342
- if (this.enableStats)
1343
- this.stats.misses++;
1344
- return null;
1345
- }
1346
- // Update access tracking
1347
- entry.accessCount++;
1348
- entry.timestamp = Date.now(); // Update for LRU
1349
- if (this.enableStats)
1350
- this.stats.hits++;
1351
- return entry.report;
1352
- }
1353
- /**
1354
- * Check if result exists in cache
1355
- */
1356
- has(content, preset) {
1357
- const key = this.generateKey(content, preset);
1358
- const entry = this.cache.get(key);
1359
- return entry !== undefined && this.isValid(entry);
1360
- }
1361
- /**
1362
- * Clear entire cache
1363
- */
1364
- clear() {
1365
- this.cache.clear();
1366
- if (this.enableStats) {
1367
- this.stats.hits = 0;
1368
- this.stats.misses = 0;
1369
- this.stats.evictions = 0;
1370
- }
1371
- }
1372
- /**
1373
- * Remove expired entries
1374
- */
1375
- prune() {
1376
- let removed = 0;
1377
- for (const [key, entry] of this.cache.entries()) {
1378
- if (!this.isValid(entry)) {
1379
- this.cache.delete(key);
1380
- removed++;
1381
- }
1382
- }
1383
- return removed;
1384
- }
1385
- /**
1386
- * Get cache statistics
1387
- */
1388
- getStats() {
1389
- const total = this.stats.hits + this.stats.misses;
1390
- const hitRate = total > 0 ? (this.stats.hits / total) * 100 : 0;
1391
- return {
1392
- hits: this.stats.hits,
1393
- misses: this.stats.misses,
1394
- size: this.cache.size,
1395
- hitRate,
1396
- evictions: this.stats.evictions,
1397
- };
1398
- }
1399
- /**
1400
- * Get current cache size
1401
- */
1402
- get size() {
1403
- return this.cache.size;
1404
- }
1405
- }
1406
- // Export singleton instance for convenience
1407
- let defaultCache = null;
1408
- /**
1409
- * Get or create the default cache instance
1410
- */
1411
- function getDefaultCache(options) {
1412
- if (!defaultCache) {
1413
- defaultCache = new ScanCacheManager(options);
1414
- }
1415
- return defaultCache;
1416
- }
1417
- /**
1418
- * Reset the default cache instance
1419
- */
1420
- function resetDefaultCache() {
1421
- defaultCache = null;
1422
- }
1423
-
1424
- /**
1425
- * Performance monitoring utilities for pompelmi scans
1426
- * @module utils/performance-metrics
1427
- */
1428
- /**
1429
- * Track performance metrics for a scan operation
1430
- */
1431
- class PerformanceTracker {
1432
- constructor() {
1433
- this.checkpoints = new Map();
1434
- this.startTime = Date.now();
1435
- }
1436
- /**
1437
- * Mark a checkpoint in the scan process
1438
- */
1439
- checkpoint(name) {
1440
- this.checkpoints.set(name, Date.now());
1441
- }
1442
- /**
1443
- * Get duration since start or since a specific checkpoint
1444
- */
1445
- getDuration(since) {
1446
- const now = Date.now();
1447
- if (since && this.checkpoints.has(since)) {
1448
- return now - (this.checkpoints.get(since) ?? now);
1449
- }
1450
- return now - this.startTime;
1451
- }
1452
- /**
1453
- * Generate final metrics report
1454
- */
1455
- getMetrics(bytesScanned) {
1456
- const totalDuration = this.getDuration();
1457
- const throughput = totalDuration > 0 ? (bytesScanned / totalDuration) * 1000 : 0;
1458
- return {
1459
- totalDurationMs: totalDuration,
1460
- heuristicsDurationMs: this.checkpoints.has("heuristics_end")
1461
- ? (this.checkpoints.get("heuristics_end") ?? 0) -
1462
- (this.checkpoints.get("heuristics_start") ?? 0)
1463
- : undefined,
1464
- yaraDurationMs: this.checkpoints.has("yara_end")
1465
- ? (this.checkpoints.get("yara_end") ?? 0) - (this.checkpoints.get("yara_start") ?? 0)
1466
- : undefined,
1467
- prepDurationMs: this.checkpoints.has("prep_end")
1468
- ? (this.checkpoints.get("prep_end") ?? 0) - this.startTime
1469
- : undefined,
1470
- throughputBps: throughput,
1471
- bytesScanned,
1472
- startedAt: this.startTime,
1473
- completedAt: Date.now(),
1474
- };
1475
- }
1476
- }
1477
- /**
1478
- * Aggregate statistics from multiple scan reports
1479
- */
1480
- function aggregateScanStats(reports) {
1481
- let cleanCount = 0;
1482
- let suspiciousCount = 0;
1483
- let maliciousCount = 0;
1484
- let totalDuration = 0;
1485
- let totalBytes = 0;
1486
- let validDurationCount = 0;
1487
- for (const report of reports) {
1488
- if (report.verdict === "clean")
1489
- cleanCount++;
1490
- else if (report.verdict === "suspicious")
1491
- suspiciousCount++;
1492
- else if (report.verdict === "malicious")
1493
- maliciousCount++;
1494
- if (report.durationMs !== undefined) {
1495
- totalDuration += report.durationMs;
1496
- validDurationCount++;
1497
- }
1498
- if (report.file?.size !== undefined) {
1499
- totalBytes += report.file.size;
1500
- }
1501
- }
1502
- const avgDuration = validDurationCount > 0 ? totalDuration / validDurationCount : 0;
1503
- const avgThroughput = totalDuration > 0 ? (totalBytes / totalDuration) * 1000 : 0;
1504
- return {
1505
- totalScans: reports.length,
1506
- cleanCount,
1507
- suspiciousCount,
1508
- maliciousCount,
1509
- avgDurationMs: avgDuration,
1510
- avgThroughputBps: avgThroughput,
1511
- totalBytesScanned: totalBytes,
1512
- };
1513
- }
1514
-
1515
- /** Mappa veloce estensione -> mime (basic) */
1516
- function guessMimeByExt(name) {
1517
- if (!name)
1518
- return;
1519
- const ext = name.toLowerCase().split(".").pop();
1520
- switch (ext) {
1521
- case "zip":
1522
- return "application/zip";
1523
- case "png":
1524
- return "image/png";
1525
- case "jpg":
1526
- case "jpeg":
1527
- return "image/jpeg";
1528
- case "pdf":
1529
- return "application/pdf";
1530
- case "txt":
1531
- return "text/plain";
1532
- default:
1533
- return;
1534
- }
1535
- }
1536
- /** Heuristica semplice per verdetto */
1537
- function computeVerdict(matches) {
1538
- if (!matches.length)
1539
- return "clean";
1540
- // se la regola contiene 'zip_' lo marchiamo "suspicious"
1541
- const anyHigh = matches.some((m) => (m.tags ?? []).includes("critical") || (m.tags ?? []).includes("high"));
1542
- return anyHigh ? "malicious" : "suspicious";
1543
- }
1544
- /** Converte i Match (heuristics) in YaraMatch-like per uniformare l'output */
1545
- function toYaraMatches(ms) {
1546
- return ms.map((m) => ({
1547
- rule: m.rule,
1548
- namespace: "heuristics",
1549
- tags: ["heuristics"].concat(m.severity ? [m.severity] : []),
1550
- meta: m.meta,
1551
- }));
1552
- }
1553
- /** Scan di bytes (browser/node) usando preset (default: zip-basic) */
1554
- async function scanBytes(input, opts = {}) {
1555
- // Check cache first if enabled
1556
- if (opts.enableCache || opts.config?.performance?.enableCache) {
1557
- const cache = getDefaultCache(opts.config?.performance?.cacheOptions);
1558
- const cached = cache.get(input, opts.preset);
1559
- if (cached) {
1560
- return cached;
1561
- }
1562
- }
1563
- const perfTracker = opts.enablePerformanceTracking || opts.config?.performance?.enablePerformanceTracking
1564
- ? new PerformanceTracker()
1565
- : null;
1566
- perfTracker?.checkpoint("prep_start");
1567
- const preset = opts.preset ?? opts.config?.defaultPreset ?? "zip-basic";
1568
- const ctx = {
1569
- ...opts.ctx,
1570
- mimeType: opts.ctx?.mimeType ?? guessMimeByExt(opts.ctx?.filename),
1571
- size: opts.ctx?.size ?? input.byteLength,
1572
- };
1573
- perfTracker?.checkpoint("prep_end");
1574
- perfTracker?.checkpoint("heuristics_start");
1575
- const scanFn = createPresetScanner(preset);
1576
- const matchesH = await (typeof scanFn === "function"
1577
- ? scanFn
1578
- : scanFn.scan)(input, ctx);
1579
- const allMatches = [...matchesH];
1580
- perfTracker?.checkpoint("heuristics_end");
1581
- // Advanced detection (enabled by default, can be overridden by config)
1582
- const advancedEnabled = opts.enableAdvancedDetection ?? opts.config?.advanced?.enablePolyglotDetection ?? true;
1583
- if (advancedEnabled) {
1584
- perfTracker?.checkpoint("advanced_start");
1585
- // Detect polyglot files
1586
- if (opts.config?.advanced?.enablePolyglotDetection !== false) {
1587
- const polyglotMatches = detectPolyglot(input);
1588
- allMatches.push(...polyglotMatches);
1589
- }
1590
- // Detect obfuscated scripts
1591
- if (opts.config?.advanced?.enableObfuscationDetection !== false) {
1592
- const obfuscatedMatches = detectObfuscatedScripts(input);
1593
- allMatches.push(...obfuscatedMatches);
1594
- }
1595
- // Check for excessive nesting in archives
1596
- if (opts.config?.advanced?.enableNestedArchiveAnalysis !== false) {
1597
- const nestingAnalysis = analyzeNestedArchives(input);
1598
- const maxDepth = opts.config?.advanced?.maxArchiveDepth ?? 5;
1599
- if (nestingAnalysis.hasExcessiveNesting || nestingAnalysis.depth > maxDepth) {
1600
- allMatches.push({
1601
- rule: "excessive_archive_nesting",
1602
- severity: "high",
1603
- meta: {
1604
- description: "Excessive archive nesting detected",
1605
- depth: nestingAnalysis.depth,
1606
- maxAllowed: maxDepth,
1607
- },
1608
- });
1609
- }
1610
- }
1611
- perfTracker?.checkpoint("advanced_end");
1612
- }
1613
- const matches = toYaraMatches(allMatches);
1614
- const verdict = computeVerdict(matches);
1615
- perfTracker ? perfTracker.getDuration() : Date.now();
1616
- const durationMs = perfTracker ? perfTracker.getDuration() : 0;
1617
- const report = {
1618
- ok: verdict === "clean",
1619
- verdict,
1620
- matches,
1621
- reasons: matches.map((m) => m.rule),
1622
- file: { name: ctx.filename, mimeType: ctx.mimeType, size: ctx.size },
1623
- durationMs,
1624
- engine: "heuristics",
1625
- truncated: false,
1626
- timedOut: false,
1627
- };
1628
- // Add performance metrics if tracking enabled
1629
- if (perfTracker &&
1630
- (opts.enablePerformanceTracking || opts.config?.performance?.enablePerformanceTracking)) {
1631
- report.performanceMetrics = perfTracker.getMetrics(input.byteLength);
1632
- }
1633
- // Cache result if enabled
1634
- if (opts.enableCache || opts.config?.performance?.enableCache) {
1635
- const cache = getDefaultCache(opts.config?.performance?.cacheOptions);
1636
- cache.set(input, report, opts.preset);
1637
- }
1638
- // Invoke callbacks if configured
1639
- opts.config?.callbacks?.onScanComplete?.(report);
1640
- return report;
1641
- }
1642
- /** Scan di un file su disco (Node). Import dinamico per non vincolare il bundle browser. */
1643
- async function scanFile(filePath, opts = {}) {
1644
- const [{ readFile, stat }, path] = await Promise.all([import('fs/promises'), import('path')]);
1645
- const [buf, st] = await Promise.all([readFile(filePath), stat(filePath)]);
1646
- const ctx = {
1647
- filename: path.basename(filePath),
1648
- mimeType: guessMimeByExt(filePath),
1649
- size: st.size,
1650
- };
1651
- return scanBytes(new Uint8Array(buf.buffer, buf.byteOffset, buf.byteLength), { ...opts, ctx });
1652
- }
1653
- /** Scan multipli File (browser) usando scanBytes + preset di default */
1654
- async function scanFiles(files, opts = {}) {
1655
- const list = Array.from(files);
1656
- const out = [];
1657
- for (const f of list) {
1658
- const buf = new Uint8Array(await f.arrayBuffer());
1659
- const rep = await scanBytes(buf, {
1660
- ...opts,
1661
- ctx: { filename: f.name, mimeType: f.type || guessMimeByExt(f.name), size: f.size },
1662
- });
1663
- out.push(rep);
1664
- }
1665
- return out;
1666
- }
1667
-
1668
- async function createRemoteEngine(opts) {
1669
- const { endpoint, headers = {}, rulesField = "rules", fileField = "file", mode = "multipart", rulesAsBase64 = false, } = opts;
1670
- const engine = {
1671
- async compile(rulesSource) {
1672
- return {
1673
- async scan(data) {
1674
- const fetchFn = globalThis.fetch;
1675
- if (!fetchFn)
1676
- throw new Error("[remote-yara] fetch non disponibile in questo ambiente");
1677
- let res;
1678
- if (mode === "multipart") {
1679
- const FormDataCtor = globalThis.FormData;
1680
- const BlobCtor = globalThis.Blob;
1681
- if (!FormDataCtor || !BlobCtor) {
1682
- throw new Error("[remote-yara] FormData/Blob non disponibili (usa json-base64 oppure esegui in browser)");
1683
- }
1684
- const form = new FormDataCtor();
1685
- form.set(rulesField, new BlobCtor([rulesSource], { type: "text/plain" }), "rules.yar");
1686
- form.set(fileField, new BlobCtor([data], { type: "application/octet-stream" }), "sample.bin");
1687
- res = await fetchFn(endpoint, { method: "POST", body: form, headers });
1688
- }
1689
- else {
1690
- const b64 = base64FromBytes(data);
1691
- const payload = { [fileField]: b64 };
1692
- if (rulesAsBase64) {
1693
- payload["rulesB64"] = base64FromString(rulesSource);
1694
- }
1695
- else {
1696
- payload[rulesField] = rulesSource;
1697
- }
1698
- res = await fetchFn(endpoint, {
1699
- method: "POST",
1700
- headers: { "Content-Type": "application/json", ...headers },
1701
- body: JSON.stringify(payload),
1702
- });
1703
- }
1704
- if (!res.ok) {
1705
- throw new Error(`[remote-yara] HTTP ${res.status} ${res.statusText}`);
1706
- }
1707
- const json = await res.json().catch(() => null);
1708
- const arr = Array.isArray(json) ? json : (json?.matches ?? []);
1709
- return (arr ?? []).map((m) => ({
1710
- rule: m.rule ?? m.ruleIdentifier ?? "unknown",
1711
- tags: m.tags ?? [],
1712
- }));
1713
- },
1714
- };
1715
- },
1716
- };
1717
- return engine;
1718
- }
1719
- // Helpers
1720
- function base64FromBytes(bytes) {
1721
- // usa btoa se disponibile (browser); altrimenti fallback manuale
1722
- const btoaFn = globalThis.btoa;
1723
- let bin = "";
1724
- for (let i = 0; i < bytes.byteLength; i++)
1725
- bin += String.fromCharCode(bytes[i]);
1726
- return btoaFn ? btoaFn(bin) : Buffer.from(bin, "binary").toString("base64");
1727
- }
1728
- function base64FromString(s) {
1729
- const btoaFn = globalThis.btoa;
1730
- return btoaFn ? btoaFn(s) : Buffer.from(s, "utf8").toString("base64");
1731
- }
1732
-
1733
- // src/scan/remote.ts
1734
- /**
1735
- * Scansiona una lista di File nel browser usando il motore remoto via HTTP.
1736
- * Non richiede WASM né dipendenze native sul client.
1737
- */
1738
- async function scanFilesWithRemoteYara(files, rulesSource, remote) {
1739
- const engine = await createRemoteEngine(remote);
1740
- const compiled = await engine.compile(rulesSource);
1741
- const results = [];
1742
- for (const file of files) {
1743
- try {
1744
- const bytes = new Uint8Array(await file.arrayBuffer());
1745
- const matches = await compiled.scan(bytes);
1746
- results.push({ file, matches });
1747
- }
1748
- catch (err) {
1749
- console.warn("[remote-yara] scan error for", file.name, err);
1750
- results.push({ file, matches: [], error: String(err?.message ?? err) });
1751
- }
1752
- }
1753
- return results;
1754
- }
1755
-
1756
- const ARCHIVE_BOMB_DETECTED = "ARCHIVE_BOMB_DETECTED";
1757
- const SIG_LFH = 0x04034b50;
1758
- const SIG_CEN = 0x02014b50;
1759
- const DEFAULTS = {
1760
- maxEntries: 1000,
1761
- maxTotalUncompressedBytes: 500 * 1024 * 1024,
1762
- maxPerEntryUncompressedBytes: 100 * 1024 * 1024,
1763
- maxEntryNameLength: 255,
1764
- maxCompressionRatio: 100,
1765
- eocdSearchWindow: 70000,
1766
- };
1767
- function r16(buf, off) {
1768
- return buf.readUInt16LE(off);
1769
- }
1770
- function r32(buf, off) {
1771
- return buf.readUInt32LE(off);
1772
- }
1773
- function isZipLike(buf) {
1774
- return (buf.length >= 4 && buf[0] === 0x50 && buf[1] === 0x4b && buf[2] === 0x03 && buf[3] === 0x04);
1775
- }
1776
- function lastIndexOfEOCD(buf, window) {
1777
- const sig = Buffer.from([0x50, 0x4b, 0x05, 0x06]);
1778
- const start = Math.max(0, buf.length - window);
1779
- const idx = buf.lastIndexOf(sig, Math.min(buf.length - sig.length, buf.length - 1));
1780
- return idx >= start ? idx : -1;
1781
- }
1782
- function hasTraversal(name) {
1783
- return (name.includes("../") || name.includes("..\\") || name.startsWith("/") || /^[A-Za-z]:/.test(name));
1784
- }
1785
- function makeBombError() {
1786
- return Object.assign(new Error("Archive bomb detected: decompression limits exceeded"), {
1787
- code: ARCHIVE_BOMB_DETECTED,
1788
- });
1789
- }
1790
- /**
1791
- * Feeds `compressed` into a raw DEFLATE inflate stream and counts the actual
1792
- * output bytes. Resolves with bombed=true and aborts early if any limit fires:
1793
- * - decompressed bytes > maxPerEntry
1794
- * - totalSoFar + decompressed > maxTotal
1795
- * - decompressed / compressed > maxRatio (ratio measured on real bytes, not headers)
1796
- *
1797
- * Malformed DEFLATE is treated as safe (bombed=false, decompressed=0).
1798
- */
1799
- function streamInflate(compressed, maxPerEntry, maxTotal, alreadySeen, maxRatio) {
1800
- return new Promise((resolve) => {
1801
- const inf = createInflateRaw();
1802
- let out = 0;
1803
- const compBytes = compressed.length;
1804
- let done = false;
1805
- const finish = (bombed) => {
1806
- if (done)
1807
- return;
1808
- done = true;
1809
- inf.destroy();
1810
- resolve({ decompressed: out, bombed });
1811
- };
1812
- inf.on("data", (chunk) => {
1813
- out += chunk.length;
1814
- if (out > maxPerEntry ||
1815
- alreadySeen + out > maxTotal ||
1816
- (compBytes > 0 && out / compBytes > maxRatio)) {
1817
- finish(true);
1818
- }
1819
- });
1820
- inf.on("end", () => finish(false));
1821
- // Malformed DEFLATE stream → not a bomb, just corrupt
1822
- inf.on("error", () => finish(false));
1823
- inf.end(compressed);
1824
- });
1825
- }
1826
- function createZipBombGuard(opts = {}) {
1827
- const cfg = { ...DEFAULTS, ...opts };
1828
- return {
1829
- async scan(input) {
1830
- const buf = Buffer.from(input);
1831
- const matches = [];
1832
- if (!isZipLike(buf))
1833
- return matches;
1834
- // ── 1. Locate EOCD ──────────────────────────────────────────────────────
1835
- const eocdPos = lastIndexOfEOCD(buf, cfg.eocdSearchWindow);
1836
- if (eocdPos < 0 || eocdPos + 22 > buf.length) {
1837
- matches.push({ rule: "zip_eocd_not_found", severity: "medium" });
1838
- return matches;
1839
- }
1840
- const totalEntries = r16(buf, eocdPos + 10);
1841
- const cdSize = r32(buf, eocdPos + 12);
1842
- const cdOffset = r32(buf, eocdPos + 16);
1843
- if (cdOffset + cdSize > buf.length) {
1844
- matches.push({ rule: "zip_cd_out_of_bounds", severity: "medium" });
1845
- return matches;
1846
- }
1847
- const lfhIndex = [];
1848
- let ptr = cdOffset;
1849
- let seen = 0;
1850
- while (ptr + 46 <= cdOffset + cdSize && seen < totalEntries) {
1851
- if (r32(buf, ptr) !== SIG_CEN)
1852
- break;
1853
- const cdCompSize = r32(buf, ptr + 20);
1854
- const fnLen = r16(buf, ptr + 28);
1855
- const exLen = r16(buf, ptr + 30);
1856
- const cmLen = r16(buf, ptr + 32);
1857
- const lfhOffset = r32(buf, ptr + 42);
1858
- const nameEnd = ptr + 46 + fnLen;
1859
- if (nameEnd > buf.length)
1860
- break;
1861
- const name = buf.toString("utf8", ptr + 46, nameEnd);
1862
- seen++;
1863
- lfhIndex.push({ lfhOffset, cdCompSize });
1864
- if (name.length > cfg.maxEntryNameLength) {
1865
- matches.push({
1866
- rule: "zip_entry_name_too_long",
1867
- severity: "medium",
1868
- meta: { name, length: name.length },
1869
- });
1870
- }
1871
- if (hasTraversal(name)) {
1872
- matches.push({ rule: "zip_path_traversal_entry", severity: "medium", meta: { name } });
1873
- }
1874
- ptr = nameEnd + exLen + cmLen;
1875
- }
1876
- if (seen !== totalEntries) {
1877
- matches.push({
1878
- rule: "zip_cd_truncated",
1879
- severity: "medium",
1880
- meta: { seen, totalEntries },
1881
- });
1882
- }
1883
- if (seen > cfg.maxEntries) {
1884
- matches.push({
1885
- rule: "zip_too_many_entries",
1886
- severity: "medium",
1887
- meta: { seen, limit: cfg.maxEntries },
1888
- });
1889
- // Return early — decompressing thousands of entries would be a DoS vector
1890
- return matches;
1891
- }
1892
- // ── 3. True streaming decompression — archive bomb detection ────────────
1893
- // For every DEFLATE entry (method=8) we feed the raw compressed bytes into
1894
- // zlib.createInflateRaw() and count the bytes that come OUT. We abort the
1895
- // moment any limit fires; we NEVER trust the header-reported uncompressed
1896
- // size for the ratio decision.
1897
- //
1898
- // For STORED entries (method=0) compressed == uncompressed by spec, so the
1899
- // byte count is immediate.
1900
- let totalDecompressed = 0;
1901
- for (const { lfhOffset, cdCompSize } of lfhIndex) {
1902
- if (lfhOffset + 30 > buf.length)
1903
- continue;
1904
- if (r32(buf, lfhOffset) !== SIG_LFH)
1905
- continue;
1906
- const gpbf = r16(buf, lfhOffset + 6);
1907
- const method = r16(buf, lfhOffset + 8);
1908
- let lfhCompSz = r32(buf, lfhOffset + 18);
1909
- const fnLen = r16(buf, lfhOffset + 26);
1910
- const exLen = r16(buf, lfhOffset + 28);
1911
- const dataOff = lfhOffset + 30 + fnLen + exLen;
1912
- // If the data-descriptor flag is set (GPBF bit 3), the LFH sizes are 0.
1913
- // Fall back to the CD size purely for navigation — not for bomb detection.
1914
- if ((gpbf & 0x08) !== 0 && lfhCompSz === 0) {
1915
- lfhCompSz = cdCompSize;
1916
- }
1917
- if (dataOff + lfhCompSz > buf.length)
1918
- continue; // truncated entry — skip
1919
- if (method === 8 /* DEFLATE */) {
1920
- const compressed = buf.slice(dataOff, dataOff + lfhCompSz);
1921
- const { decompressed, bombed } = await streamInflate(compressed, cfg.maxPerEntryUncompressedBytes, cfg.maxTotalUncompressedBytes, totalDecompressed, cfg.maxCompressionRatio);
1922
- if (bombed)
1923
- throw makeBombError();
1924
- totalDecompressed += decompressed;
1925
- }
1926
- else if (method === 0 /* STORED */) {
1927
- // Compressed == uncompressed for stored entries
1928
- if (lfhCompSz > cfg.maxPerEntryUncompressedBytes)
1929
- throw makeBombError();
1930
- totalDecompressed += lfhCompSz;
1931
- if (totalDecompressed > cfg.maxTotalUncompressedBytes)
1932
- throw makeBombError();
1933
- }
1934
- // Other methods (bzip2=12, lzma=14, zstd=93, …) — skip; no built-in support
1935
- }
1936
- return matches;
1937
- },
1938
- };
1939
- }
1940
-
1941
- /** Decompilation-specific types for Pompelmi */
1942
- const SUSPICIOUS_PATTERNS = [
1943
- {
1944
- name: "syscall_direct",
1945
- description: "Direct system call without library wrapper",
1946
- severity: "medium",
1947
- pattern: /syscall|sysenter|int\s+0x80/i,
1948
- },
1949
- {
1950
- name: "process_injection",
1951
- description: "Process injection techniques",
1952
- severity: "high",
1953
- pattern: /CreateRemoteThread|WriteProcessMemory|VirtualAllocEx/i,
1954
- },
1955
- {
1956
- name: "anti_debug",
1957
- description: "Anti-debugging techniques",
1958
- severity: "medium",
1959
- pattern: /IsDebuggerPresent|CheckRemoteDebuggerPresent|OutputDebugString/i,
1960
- },
1961
- {
1962
- name: "obfuscation_xor",
1963
- description: "XOR-based obfuscation pattern",
1964
- severity: "medium",
1965
- pattern: /xor.*0x[0-9a-f]+.*xor/i,
1966
- },
1967
- {
1968
- name: "crypto_constants",
1969
- description: "Cryptographic constants",
1970
- severity: "low",
1971
- pattern: /0x67452301|0xefcdab89|0x98badcfe|0x10325476/i,
1972
- },
1973
- ];
1974
-
1975
- /**
1976
- * Batch scanning with concurrency control
1977
- * @module utils/batch-scanner
1978
- */
1979
- /**
1980
- * Batch file scanner with concurrency control and progress tracking
1981
- */
1982
- class BatchScanner {
1983
- constructor(options = {}) {
1984
- this.options = {
1985
- concurrency: 5,
1986
- continueOnError: true,
1987
- ...options,
1988
- };
1989
- }
1990
- /**
1991
- * Scan multiple files with controlled concurrency
1992
- */
1993
- async scanBatch(tasks) {
1994
- const startTime = Date.now();
1995
- const results = new Array(tasks.length);
1996
- const errors = [];
1997
- let successCount = 0;
1998
- let errorCount = 0;
1999
- let completedCount = 0;
2000
- const concurrency = this.options.concurrency ?? 5;
2001
- // Process tasks in chunks with controlled concurrency
2002
- const processingQueue = [];
2003
- let currentIndex = 0;
2004
- const processTask = async (index) => {
2005
- try {
2006
- const task = tasks[index];
2007
- const report = await scanBytes(task.content, {
2008
- ...this.options,
2009
- ctx: task.context,
2010
- });
2011
- results[index] = report;
2012
- successCount++;
2013
- completedCount++;
2014
- if (this.options.onProgress) {
2015
- this.options.onProgress(completedCount, tasks.length, report);
2016
- }
2017
- }
2018
- catch (error) {
2019
- errorCount++;
2020
- completedCount++;
2021
- const err = error instanceof Error ? error : new Error(String(error));
2022
- if (this.options.onError) {
2023
- this.options.onError(err, index);
2024
- }
2025
- errors.push({ index, error: err });
2026
- if (!this.options.continueOnError) {
2027
- throw err;
2028
- }
2029
- results[index] = null;
2030
- }
2031
- };
2032
- // Start initial batch of concurrent tasks
2033
- while (currentIndex < tasks.length) {
2034
- while (processingQueue.length < concurrency && currentIndex < tasks.length) {
2035
- const promise = processTask(currentIndex);
2036
- processingQueue.push(promise);
2037
- currentIndex++;
2038
- // Remove completed promises from queue
2039
- promise
2040
- .finally(() => {
2041
- const idx = processingQueue.indexOf(promise);
2042
- if (idx > -1)
2043
- processingQueue.splice(idx, 1);
2044
- })
2045
- .catch(() => {
2046
- // Rejections are handled by the main queue waits; swallow the cleanup chain.
2047
- });
2048
- }
2049
- // Wait for at least one task to complete before continuing
2050
- if (processingQueue.length >= concurrency) {
2051
- await Promise.race(processingQueue);
2052
- }
2053
- }
2054
- // Wait for all remaining tasks
2055
- await Promise.all(processingQueue);
2056
- const totalDurationMs = Date.now() - startTime;
2057
- return {
2058
- reports: results,
2059
- successCount,
2060
- errorCount,
2061
- totalDurationMs,
2062
- errors,
2063
- };
2064
- }
2065
- /**
2066
- * Scan files from File objects (browser environment)
2067
- */
2068
- async scanFiles(files) {
2069
- const tasks = await Promise.all(files.map(async (file) => ({
2070
- content: new Uint8Array(await file.arrayBuffer()),
2071
- context: {
2072
- filename: file.name,
2073
- mimeType: file.type,
2074
- size: file.size,
2075
- },
2076
- })));
2077
- return this.scanBatch(tasks);
2078
- }
2079
- /**
2080
- * Scan files from file paths (Node.js environment)
2081
- */
2082
- async scanFilePaths(filePaths) {
2083
- const fs = await import('fs/promises');
2084
- const path = await import('path');
2085
- const tasks = await Promise.all(filePaths.map(async (filePath) => {
2086
- const [content, stats] = await Promise.all([fs.readFile(filePath), fs.stat(filePath)]);
2087
- return {
2088
- content: new Uint8Array(content),
2089
- context: {
2090
- filename: path.basename(filePath),
2091
- size: stats.size,
2092
- },
2093
- };
2094
- }));
2095
- return this.scanBatch(tasks);
2096
- }
2097
- }
2098
- /**
2099
- * Quick helper for batch scanning with default options
2100
- */
2101
- async function batchScan(tasks, options) {
2102
- const scanner = new BatchScanner(options);
2103
- return scanner.scanBatch(tasks);
2104
- }
2105
-
2106
- /**
2107
- * Export utilities for scan results
2108
- * @module utils/export
2109
- */
2110
- /**
2111
- * Export scan results to various formats
2112
- */
2113
- class ScanResultExporter {
2114
- /**
2115
- * Export to JSON format
2116
- */
2117
- toJSON(reports, options = {}) {
2118
- const data = Array.isArray(reports) ? reports : [reports];
2119
- if (!options.includeDetails) {
2120
- // Simplified output
2121
- const simplified = data.map((r) => ({
2122
- verdict: r.verdict,
2123
- file: r.file?.name,
2124
- matches: r.matches.length,
2125
- durationMs: r.durationMs,
2126
- }));
2127
- return options.prettyPrint ? JSON.stringify(simplified, null, 2) : JSON.stringify(simplified);
2128
- }
2129
- return options.prettyPrint ? JSON.stringify(data, null, 2) : JSON.stringify(data);
2130
- }
2131
- /**
2132
- * Export to CSV format
2133
- */
2134
- toCSV(reports, options = {}) {
2135
- const data = Array.isArray(reports) ? reports : [reports];
2136
- const headers = [
2137
- "filename",
2138
- "verdict",
2139
- "matches_count",
2140
- "file_size",
2141
- "mime_type",
2142
- "duration_ms",
2143
- "engine",
2144
- ];
2145
- if (options.includeDetails) {
2146
- headers.push("reasons", "match_rules");
2147
- }
2148
- const rows = data.map((report) => {
2149
- const row = [
2150
- this.escapeCsv(report.file?.name || "unknown"),
2151
- report.verdict,
2152
- report.matches.length.toString(),
2153
- (report.file?.size || 0).toString(),
2154
- this.escapeCsv(report.file?.mimeType || "unknown"),
2155
- (report.durationMs || 0).toString(),
2156
- report.engine || "unknown",
2157
- ];
2158
- if (options.includeDetails) {
2159
- row.push(this.escapeCsv((report.reasons || []).join("; ")), this.escapeCsv(report.matches.map((m) => m.rule).join("; ")));
2160
- }
2161
- return row.join(",");
2162
- });
2163
- return [headers.join(","), ...rows].join("\n");
2164
- }
2165
- /**
2166
- * Export to Markdown format
2167
- */
2168
- toMarkdown(reports, options = {}) {
2169
- const data = Array.isArray(reports) ? reports : [reports];
2170
- let md = "# Scan Results\n\n";
2171
- md += `**Total Scans:** ${data.length}\n\n`;
2172
- const clean = data.filter((r) => r.verdict === "clean").length;
2173
- const suspicious = data.filter((r) => r.verdict === "suspicious").length;
2174
- const malicious = data.filter((r) => r.verdict === "malicious").length;
2175
- md += "## Summary\n\n";
2176
- md += `- ✅ Clean: ${clean}\n`;
2177
- md += `- ⚠️ Suspicious: ${suspicious}\n`;
2178
- md += `- ❌ Malicious: ${malicious}\n\n`;
2179
- md += "## Detailed Results\n\n";
2180
- for (const report of data) {
2181
- const icon = report.verdict === "clean" ? "✅" : report.verdict === "suspicious" ? "⚠️" : "❌";
2182
- md += `### ${icon} ${report.file?.name || "Unknown"}\n\n`;
2183
- md += `- **Verdict:** ${report.verdict}\n`;
2184
- md += `- **Size:** ${this.formatBytes(report.file?.size || 0)}\n`;
2185
- md += `- **MIME Type:** ${report.file?.mimeType || "unknown"}\n`;
2186
- md += `- **Duration:** ${report.durationMs || 0}ms\n`;
2187
- md += `- **Matches:** ${report.matches.length}\n`;
2188
- if (options.includeDetails && report.matches.length > 0) {
2189
- md += "\n**Match Details:**\n";
2190
- for (const match of report.matches) {
2191
- md += `- ${match.rule}`;
2192
- if (match.tags && match.tags.length > 0) {
2193
- md += ` (${match.tags.join(", ")})`;
2194
- }
2195
- md += "\n";
2196
- }
2197
- }
2198
- md += "\n";
2199
- }
2200
- return md;
2201
- }
2202
- /**
2203
- * Export to SARIF format (Static Analysis Results Interchange Format)
2204
- * Useful for CI/CD integration
2205
- */
2206
- toSARIF(reports, options = {}) {
2207
- const data = Array.isArray(reports) ? reports : [reports];
2208
- const results = data.flatMap((report) => {
2209
- if (report.verdict === "clean")
2210
- return [];
2211
- return report.matches.map((match) => ({
2212
- ruleId: match.rule,
2213
- level: report.verdict === "malicious" ? "error" : "warning",
2214
- message: {
2215
- text: `${match.rule} detected in ${report.file?.name || "unknown file"}`,
2216
- },
2217
- locations: [
2218
- {
2219
- physicalLocation: {
2220
- artifactLocation: {
2221
- uri: report.file?.name || "unknown",
2222
- },
2223
- },
2224
- },
2225
- ],
2226
- properties: {
2227
- tags: match.tags,
2228
- metadata: match.meta,
2229
- },
2230
- }));
2231
- });
2232
- const sarif = {
2233
- version: "2.1.0",
2234
- $schema: "https://raw.githubusercontent.com/oasis-tcs/sarif-spec/master/Schemata/sarif-schema-2.1.0.json",
2235
- runs: [
2236
- {
2237
- tool: {
2238
- driver: {
2239
- name: "Pompelmi",
2240
- version: "0.29.0",
2241
- informationUri: "https://pompelmi.github.io/pompelmi/",
2242
- },
2243
- },
2244
- results,
2245
- },
2246
- ],
2247
- };
2248
- return options.prettyPrint ? JSON.stringify(sarif, null, 2) : JSON.stringify(sarif);
2249
- }
2250
- /**
2251
- * Export to HTML format
2252
- */
2253
- toHTML(reports, options = {}) {
2254
- const data = Array.isArray(reports) ? reports : [reports];
2255
- const clean = data.filter((r) => r.verdict === "clean").length;
2256
- const suspicious = data.filter((r) => r.verdict === "suspicious").length;
2257
- const malicious = data.filter((r) => r.verdict === "malicious").length;
2258
- let html = `<!DOCTYPE html>
2259
- <html lang="en">
2260
- <head>
2261
- <meta charset="UTF-8">
2262
- <meta name="viewport" content="width=device-width, initial-scale=1.0">
2263
- <title>Pompelmi Scan Results</title>
2264
- <style>
2265
- body { font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif; max-width: 1200px; margin: 0 auto; padding: 20px; }
2266
- .summary { display: grid; grid-template-columns: repeat(3, 1fr); gap: 20px; margin: 20px 0; }
2267
- .card { padding: 20px; border-radius: 8px; text-align: center; }
2268
- .clean { background: #d4edda; color: #155724; }
2269
- .suspicious { background: #fff3cd; color: #856404; }
2270
- .malicious { background: #f8d7da; color: #721c24; }
2271
- .result { border: 1px solid #ddd; border-radius: 8px; padding: 15px; margin: 10px 0; }
2272
- .result h3 { margin-top: 0; }
2273
- .badge { display: inline-block; padding: 4px 8px; border-radius: 4px; font-size: 0.8em; margin: 2px; }
2274
- table { width: 100%; border-collapse: collapse; }
2275
- th, td { padding: 8px; text-align: left; border-bottom: 1px solid #ddd; }
2276
- </style>
2277
- </head>
2278
- <body>
2279
- <h1>🛡️ Pompelmi Scan Results</h1>
2280
- <div class="summary">
2281
- <div class="card clean"><h2>${clean}</h2><p>Clean Files</p></div>
2282
- <div class="card suspicious"><h2>${suspicious}</h2><p>Suspicious Files</p></div>
2283
- <div class="card malicious"><h2>${malicious}</h2><p>Malicious Files</p></div>
2284
- </div>
2285
- <h2>Detailed Results</h2>`;
2286
- for (const report of data) {
2287
- const statusClass = report.verdict;
2288
- html += `<div class="result ${statusClass}">`;
2289
- html += `<h3>${this.escapeHtml(report.file?.name || "Unknown")}</h3>`;
2290
- html += `<table>`;
2291
- html += `<tr><th>Verdict</th><td>${report.verdict.toUpperCase()}</td></tr>`;
2292
- html += `<tr><th>Size</th><td>${this.formatBytes(report.file?.size || 0)}</td></tr>`;
2293
- html += `<tr><th>MIME Type</th><td>${this.escapeHtml(report.file?.mimeType || "unknown")}</td></tr>`;
2294
- html += `<tr><th>Duration</th><td>${report.durationMs || 0}ms</td></tr>`;
2295
- html += `<tr><th>Matches</th><td>${report.matches.length}</td></tr>`;
2296
- html += `</table>`;
2297
- if (options.includeDetails && report.matches.length > 0) {
2298
- html += `<h4>Match Details:</h4><ul>`;
2299
- for (const match of report.matches) {
2300
- html += `<li><strong>${this.escapeHtml(match.rule)}</strong>`;
2301
- if (match.tags && match.tags.length > 0) {
2302
- html += ` ${match.tags.map((tag) => `<span class="badge">${this.escapeHtml(tag)}</span>`).join("")}`;
2303
- }
2304
- html += `</li>`;
2305
- }
2306
- html += `</ul>`;
2307
- }
2308
- html += `</div>`;
2309
- }
2310
- html += `</body></html>`;
2311
- return html;
2312
- }
2313
- /**
2314
- * Export to specified format
2315
- */
2316
- export(reports, format, options = {}) {
2317
- switch (format) {
2318
- case "json":
2319
- return this.toJSON(reports, options);
2320
- case "csv":
2321
- return this.toCSV(reports, options);
2322
- case "markdown":
2323
- return this.toMarkdown(reports, options);
2324
- case "html":
2325
- return this.toHTML(reports, options);
2326
- case "sarif":
2327
- return this.toSARIF(reports, options);
2328
- default:
2329
- throw new Error(`Unsupported export format: ${format}`);
2330
- }
2331
- }
2332
- escapeCsv(value) {
2333
- if (value.includes(",") || value.includes('"') || value.includes("\n")) {
2334
- return `"${value.replace(/"/g, '""')}"`;
2335
- }
2336
- return value;
2337
- }
2338
- escapeHtml(value) {
2339
- return value
2340
- .replace(/&/g, "&amp;")
2341
- .replace(/</g, "&lt;")
2342
- .replace(/>/g, "&gt;")
2343
- .replace(/"/g, "&quot;")
2344
- .replace(/'/g, "&#039;");
2345
- }
2346
- formatBytes(bytes) {
2347
- if (bytes === 0)
2348
- return "0 Bytes";
2349
- const k = 1024;
2350
- const sizes = ["Bytes", "KB", "MB", "GB"];
2351
- const i = Math.floor(Math.log(bytes) / Math.log(k));
2352
- return Math.round((bytes / k ** i) * 100) / 100 + " " + sizes[i];
2353
- }
2354
- }
2355
- /**
2356
- * Quick export helper
2357
- */
2358
- function exportScanResults(reports, format, options) {
2359
- const exporter = new ScanResultExporter();
2360
- return exporter.export(reports, format, options);
2361
- }
2362
-
2363
- /**
2364
- * Threat intelligence integration and enhanced detection
2365
- * @module utils/threat-intelligence
2366
- */
2367
- /**
2368
- * Built-in threat intelligence - known malware hashes
2369
- * In production, this would connect to real threat intel APIs
2370
- */
2371
- class LocalThreatIntelligence {
2372
- constructor() {
2373
- this.name = "Local Database";
2374
- this.knownThreats = new Map();
2375
- // Initialize with some example known threats (in production, load from database)
2376
- this.initializeKnownThreats();
2377
- }
2378
- initializeKnownThreats() {
2379
- // Example: EICAR test file hash
2380
- this.knownThreats.set("275a021bbfb6489e54d471899f7db9d1663fc695ec2fe2a2c4538aabf651fd0f", {
2381
- threatLevel: 100,
2382
- category: "test-malware",
2383
- source: "local",
2384
- metadata: { name: "EICAR Test File" },
2385
- });
2386
- }
2387
- async checkHash(hash) {
2388
- return this.knownThreats.get(hash.toLowerCase()) || null;
2389
- }
2390
- /**
2391
- * Add a known threat to the local database
2392
- */
2393
- addThreat(hash, info) {
2394
- this.knownThreats.set(hash.toLowerCase(), info);
2395
- }
2396
- /**
2397
- * Remove a threat from the local database
2398
- */
2399
- removeThreat(hash) {
2400
- return this.knownThreats.delete(hash.toLowerCase());
2401
- }
2402
- /**
2403
- * Get all known threats
2404
- */
2405
- getAllThreats() {
2406
- return new Map(this.knownThreats);
2407
- }
2408
- }
2409
- /**
2410
- * Threat intelligence aggregator
2411
- */
2412
- class ThreatIntelligenceAggregator {
2413
- constructor(sources) {
2414
- this.sources = [];
2415
- if (sources) {
2416
- this.sources = sources;
2417
- }
2418
- else {
2419
- // Default to local intelligence
2420
- this.sources = [new LocalThreatIntelligence()];
2421
- }
2422
- }
2423
- /**
2424
- * Add a threat intelligence source
2425
- */
2426
- addSource(source) {
2427
- this.sources.push(source);
2428
- }
2429
- /**
2430
- * Check file hash against all sources
2431
- */
2432
- async checkHash(hash) {
2433
- const results = await Promise.allSettled(this.sources.map((source) => source.checkHash(hash)));
2434
- const threats = [];
2435
- for (const result of results) {
2436
- if (result.status === "fulfilled" && result.value) {
2437
- threats.push(result.value);
2438
- }
2439
- }
2440
- return threats;
2441
- }
2442
- /**
2443
- * Enhance scan report with threat intelligence
2444
- */
2445
- async enhanceScanReport(content, report) {
2446
- // Calculate file hash
2447
- const hash = createHash("sha256").update(content).digest("hex");
2448
- // Check threat intelligence
2449
- const threatIntel = await this.checkHash(hash);
2450
- // Calculate risk score
2451
- const riskScore = this.calculateRiskScore(report, threatIntel);
2452
- return {
2453
- ...report,
2454
- fileHash: hash,
2455
- threatIntel: threatIntel.length > 0 ? threatIntel : undefined,
2456
- riskScore,
2457
- };
2458
- }
2459
- /**
2460
- * Calculate overall risk score based on scan results and threat intel
2461
- */
2462
- calculateRiskScore(report, threats) {
2463
- let score = 0;
2464
- // Base score from verdict
2465
- switch (report.verdict) {
2466
- case "malicious":
2467
- score += 70;
2468
- break;
2469
- case "suspicious":
2470
- score += 40;
2471
- break;
2472
- case "clean":
2473
- score += 0;
2474
- break;
2475
- }
2476
- // Add points for number of matches
2477
- score += Math.min(report.matches.length * 5, 20);
2478
- // Add points from threat intelligence
2479
- if (threats.length > 0) {
2480
- const maxThreat = Math.max(...threats.map((t) => t.threatLevel));
2481
- score = Math.max(score, maxThreat);
2482
- }
2483
- return Math.min(score, 100);
2484
- }
2485
- }
2486
- /**
2487
- * Create default threat intelligence aggregator
2488
- */
2489
- function createThreatIntelligence() {
2490
- return new ThreatIntelligenceAggregator();
2491
- }
2492
- /**
2493
- * Helper to get file hash
2494
- */
2495
- function getFileHash(content) {
2496
- return createHash("sha256").update(content).digest("hex");
2497
- }
2498
-
2499
- /**
2500
- * Validates a File by MIME type and size (max 5 MB).
2501
- */
2502
- function validateFile(file) {
2503
- const maxSize = 5 * 1024 * 1024;
2504
- const allowedTypes = ["text/plain", "application/json", "text/csv"];
2505
- if (!allowedTypes.includes(file.type)) {
2506
- return { valid: false, error: "Unsupported file type" };
2507
- }
2508
- if (file.size > maxSize) {
2509
- return { valid: false, error: "File too large (max 5 MB)" };
2510
- }
2511
- return { valid: true };
2512
- }
2513
-
2514
- function mapMatchesToVerdict(matches = []) {
2515
- if (!matches.length)
2516
- return "clean";
2517
- const malHints = ["trojan", "ransom", "worm", "spy", "rootkit", "keylog", "botnet"];
2518
- const tagSet = new Set(matches.flatMap((m) => (m.tags ?? []).map((t) => t.toLowerCase())));
2519
- const nameHit = (r) => malHints.some((h) => r.toLowerCase().includes(h));
2520
- const isMal = matches.some((m) => nameHit(m.rule)) || tagSet.has("malware") || tagSet.has("critical");
2521
- return isMal ? "malicious" : "suspicious";
2522
- }
2523
-
2524
- export { ARCHIVES, BatchScanner, CONFIG_PRESETS, CONSERVATIVE_DEFAULT, CommonHeuristicsScanner, ConfigManager, DEFAULT_CONFIG, DEFAULT_POLICY, DOCUMENTS_ONLY, HipaaTemp, IMAGES_ONLY, LocalThreatIntelligence, POLICY_PACKS, PerformanceTracker, STRICT_PUBLIC_UPLOAD, SUSPICIOUS_PATTERNS, ScanCacheManager, ScanResultExporter, ThreatIntelligenceAggregator, aggregateScanStats, analyzeNestedArchives, batchScan, composeScanners, createConfig, createHipaaError, createPresetScanner, createThreatIntelligence, createZipBombGuard, definePolicy, detectObfuscatedScripts, detectPolyglot, exportScanResults, getDefaultCache, getFileHash, getHipaaManager, getPolicyPack, getPresetConfig, initializeHipaaCompliance, mapMatchesToVerdict, resetDefaultCache, scanBytes, scanFile, scanFiles, scanFilesWithRemoteYara, validateFile };
2525
- //# sourceMappingURL=pompelmi.esm.js.map