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