pompelmi 0.33.0 → 0.34.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 (42) hide show
  1. package/README.md +351 -987
  2. package/dist/pompelmi.audit.cjs +130 -0
  3. package/dist/pompelmi.audit.cjs.map +1 -0
  4. package/dist/pompelmi.audit.esm.js +109 -0
  5. package/dist/pompelmi.audit.esm.js.map +1 -0
  6. package/dist/pompelmi.browser.cjs +1455 -0
  7. package/dist/pompelmi.browser.cjs.map +1 -0
  8. package/dist/pompelmi.browser.esm.js +1429 -0
  9. package/dist/pompelmi.browser.esm.js.map +1 -0
  10. package/dist/pompelmi.cjs +1333 -3044
  11. package/dist/pompelmi.cjs.map +1 -1
  12. package/dist/pompelmi.esm.js +1327 -3042
  13. package/dist/pompelmi.esm.js.map +1 -1
  14. package/dist/pompelmi.hooks.cjs +75 -0
  15. package/dist/pompelmi.hooks.cjs.map +1 -0
  16. package/dist/pompelmi.hooks.esm.js +72 -0
  17. package/dist/pompelmi.hooks.esm.js.map +1 -0
  18. package/dist/pompelmi.policy-packs.cjs +239 -0
  19. package/dist/pompelmi.policy-packs.cjs.map +1 -0
  20. package/dist/pompelmi.policy-packs.esm.js +231 -0
  21. package/dist/pompelmi.policy-packs.esm.js.map +1 -0
  22. package/dist/pompelmi.quarantine.cjs +315 -0
  23. package/dist/pompelmi.quarantine.cjs.map +1 -0
  24. package/dist/pompelmi.quarantine.esm.js +291 -0
  25. package/dist/pompelmi.quarantine.esm.js.map +1 -0
  26. package/dist/pompelmi.react.cjs +1486 -0
  27. package/dist/pompelmi.react.cjs.map +1 -0
  28. package/dist/pompelmi.react.esm.js +1459 -0
  29. package/dist/pompelmi.react.esm.js.map +1 -0
  30. package/dist/types/audit.d.ts +84 -0
  31. package/dist/types/browser-index.d.ts +28 -2
  32. package/dist/types/config.d.ts +3 -2
  33. package/dist/types/hooks.d.ts +89 -0
  34. package/dist/types/index.d.ts +17 -9
  35. package/dist/types/policy-packs.d.ts +98 -0
  36. package/dist/types/quarantine/index.d.ts +18 -0
  37. package/dist/types/quarantine/storage.d.ts +77 -0
  38. package/dist/types/quarantine/types.d.ts +78 -0
  39. package/dist/types/quarantine/workflow.d.ts +97 -0
  40. package/dist/types/react-index.d.ts +13 -0
  41. package/dist/types/types.d.ts +0 -1
  42. package/package.json +54 -3
@@ -0,0 +1,1486 @@
1
+ 'use strict';
2
+
3
+ var crypto = require('crypto');
4
+ var react = require('react');
5
+
6
+ function hasAsciiToken(buf, token) {
7
+ // Use latin1 so we can safely search binary
8
+ return buf.indexOf(token, 0, 'latin1') !== -1;
9
+ }
10
+ function startsWith(buf, bytes) {
11
+ if (buf.length < bytes.length)
12
+ return false;
13
+ for (let i = 0; i < bytes.length; i++)
14
+ if (buf[i] !== bytes[i])
15
+ return false;
16
+ return true;
17
+ }
18
+ function isPDF(buf) {
19
+ // %PDF-
20
+ return startsWith(buf, [0x25, 0x50, 0x44, 0x46, 0x2d]);
21
+ }
22
+ function isOleCfb(buf) {
23
+ // D0 CF 11 E0 A1 B1 1A E1
24
+ const sig = [0xD0, 0xCF, 0x11, 0xE0, 0xA1, 0xB1, 0x1A, 0xE1];
25
+ return startsWith(buf, sig);
26
+ }
27
+ function isZipLike$1(buf) {
28
+ // PK\x03\x04
29
+ return startsWith(buf, [0x50, 0x4b, 0x03, 0x04]);
30
+ }
31
+ function isPeExecutable(buf) {
32
+ // "MZ"
33
+ return startsWith(buf, [0x4d, 0x5a]);
34
+ }
35
+ /** OOXML macro hint via filename token in ZIP container */
36
+ function hasOoxmlMacros(buf) {
37
+ if (!isZipLike$1(buf))
38
+ return false;
39
+ return hasAsciiToken(buf, 'vbaProject.bin');
40
+ }
41
+ /** PDF risky features (/JavaScript, /OpenAction, /AA, /Launch) */
42
+ function pdfRiskTokens(buf) {
43
+ const tokens = ['/JavaScript', '/OpenAction', '/AA', '/Launch'];
44
+ return tokens.filter(t => hasAsciiToken(buf, t));
45
+ }
46
+ const CommonHeuristicsScanner = {
47
+ async scan(input) {
48
+ const buf = Buffer.from(input);
49
+ const matches = [];
50
+ // Office macros (OLE / OOXML)
51
+ if (isOleCfb(buf)) {
52
+ matches.push({ rule: 'office_ole_container', severity: 'suspicious' });
53
+ }
54
+ if (hasOoxmlMacros(buf)) {
55
+ matches.push({ rule: 'office_ooxml_macros', severity: 'suspicious' });
56
+ }
57
+ // PDF risky tokens
58
+ if (isPDF(buf)) {
59
+ const toks = pdfRiskTokens(buf);
60
+ if (toks.length) {
61
+ matches.push({
62
+ rule: 'pdf_risky_actions',
63
+ severity: 'suspicious',
64
+ meta: { tokens: toks }
65
+ });
66
+ }
67
+ }
68
+ // Executable header
69
+ if (isPeExecutable(buf)) {
70
+ matches.push({ rule: 'pe_executable_signature', severity: 'suspicious' });
71
+ }
72
+ // EICAR test file
73
+ const EICAR_NEEDLE = "X5O!P%@AP[4\\PZX54(P^)7CC)7}$EICAR-STANDARD-ANTIVIRUS-TEST-FILE!";
74
+ if (hasAsciiToken(buf, EICAR_NEEDLE)) {
75
+ matches.push({ rule: 'eicar_test_file', severity: 'high', meta: { note: 'EICAR standard antivirus test file detected' } });
76
+ }
77
+ return matches;
78
+ }
79
+ };
80
+
81
+ function toScanFn(s) {
82
+ return (typeof s === "function" ? s : s.scan);
83
+ }
84
+ /** Map a Match's severity field to a Verdict for stopOn comparison. */
85
+ function matchToVerdict(m) {
86
+ const s = m.severity;
87
+ if (s === "critical" || s === "high" || s === "malicious")
88
+ return "malicious";
89
+ if (s === "medium" || s === "low" || s === "suspicious" || s === "info")
90
+ return "suspicious";
91
+ return "clean";
92
+ }
93
+ /** Highest verdict across all matches in the list. */
94
+ function highestSeverity(matches) {
95
+ if (matches.length === 0)
96
+ return null;
97
+ if (matches.some((m) => matchToVerdict(m) === "malicious"))
98
+ return "malicious";
99
+ if (matches.some((m) => matchToVerdict(m) === "suspicious"))
100
+ return "suspicious";
101
+ return "clean";
102
+ }
103
+ const SEVERITY_RANK = { malicious: 2, suspicious: 1, clean: 0 };
104
+ function shouldStop(matches, stopOn) {
105
+ if (!stopOn)
106
+ return false;
107
+ const highest = highestSeverity(matches);
108
+ if (!highest)
109
+ return false;
110
+ return SEVERITY_RANK[highest] >= SEVERITY_RANK[stopOn];
111
+ }
112
+ async function runWithTimeout(fn, timeoutMs) {
113
+ if (!timeoutMs)
114
+ return fn();
115
+ return new Promise((resolve, reject) => {
116
+ const timer = setTimeout(() => reject(new Error("scanner timeout")), timeoutMs);
117
+ fn().then((v) => { clearTimeout(timer); resolve(v); }, (e) => { clearTimeout(timer); reject(e); });
118
+ });
119
+ }
120
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
121
+ function composeScanners(...args) {
122
+ const first = args[0];
123
+ const rest = args.slice(1);
124
+ // ── Named-scanner array form ──────────────────────────────────────────────
125
+ if (Array.isArray(first) &&
126
+ (first.length === 0 || (Array.isArray(first[0]) && typeof first[0][0] === "string"))) {
127
+ const entries = first;
128
+ const opts = rest.length > 0 && !Array.isArray(rest[0]) && typeof rest[0] !== "function" &&
129
+ !(typeof rest[0] === "object" && rest[0] !== null && "scan" in rest[0])
130
+ ? rest[0]
131
+ : {};
132
+ return async (input, ctx) => {
133
+ const all = [];
134
+ if (opts.parallel) {
135
+ // Parallel execution — collect all results then return
136
+ const results = await Promise.allSettled(entries.map(([name, scanner]) => runWithTimeout(() => toScanFn(scanner)(input, ctx), opts.timeoutMsPerScanner)));
137
+ for (let i = 0; i < results.length; i++) {
138
+ const result = results[i];
139
+ if (result.status === "fulfilled" && Array.isArray(result.value)) {
140
+ const matches = opts.tagSourceName
141
+ ? result.value.map((m) => ({
142
+ ...m,
143
+ meta: { ...m.meta, _sourceName: entries[i][0] },
144
+ }))
145
+ : result.value;
146
+ all.push(...matches);
147
+ }
148
+ }
149
+ }
150
+ else {
151
+ // Sequential execution with optional stopOn short-circuit
152
+ for (const [name, scanner] of entries) {
153
+ try {
154
+ const out = await runWithTimeout(() => toScanFn(scanner)(input, ctx), opts.timeoutMsPerScanner);
155
+ if (Array.isArray(out)) {
156
+ const matches = opts.tagSourceName
157
+ ? out.map((m) => ({ ...m, meta: { ...m.meta, _sourceName: name } }))
158
+ : out;
159
+ all.push(...matches);
160
+ if (shouldStop(all, opts.stopOn))
161
+ break;
162
+ }
163
+ }
164
+ catch {
165
+ // individual scanner failure is non-fatal
166
+ }
167
+ }
168
+ }
169
+ return all;
170
+ };
171
+ }
172
+ // ── Variadic form (backward-compatible) ───────────────────────────────────
173
+ const scanners = [first, ...rest].filter(Boolean);
174
+ return async (input, ctx) => {
175
+ const all = [];
176
+ for (const s of scanners) {
177
+ try {
178
+ const out = await toScanFn(s)(input, ctx);
179
+ if (Array.isArray(out))
180
+ all.push(...out);
181
+ }
182
+ catch {
183
+ // ignore individual scanner failures
184
+ }
185
+ }
186
+ return all;
187
+ };
188
+ }
189
+ function createPresetScanner(preset, opts = {}) {
190
+ const scanners = [];
191
+ // Always include heuristics (EICAR, PHP webshells, JS obfuscation, PE hints, etc.)
192
+ scanners.push(CommonHeuristicsScanner);
193
+ // Add decompilation scanners based on preset
194
+ if (preset === 'decompilation-basic' || preset === 'decompilation-deep' ||
195
+ preset === 'malware-analysis' || opts.enableDecompilation) {
196
+ const depth = preset === 'decompilation-deep' ? 'deep' :
197
+ preset === 'decompilation-basic' ? 'basic' :
198
+ opts.decompilationDepth || 'basic';
199
+ if (!opts.decompilationEngine || opts.decompilationEngine === 'binaryninja-hlil' || opts.decompilationEngine === 'both') {
200
+ try {
201
+ // Dynamic import to avoid bundling issues - using Function to bypass TypeScript type checking
202
+ const importModule = new Function('specifier', 'return import(specifier)');
203
+ importModule('@pompelmi/engine-binaryninja').then((mod) => {
204
+ const binjaScanner = mod.createBinaryNinjaScanner({
205
+ timeout: opts.decompilationTimeout || opts.timeout || 30000,
206
+ depth,
207
+ pythonPath: opts.pythonPath,
208
+ binaryNinjaPath: opts.binaryNinjaPath
209
+ });
210
+ scanners.push(binjaScanner);
211
+ }).catch(() => {
212
+ // Binary Ninja engine not available - silently skip
213
+ });
214
+ }
215
+ catch {
216
+ // Engine not installed
217
+ }
218
+ }
219
+ if (!opts.decompilationEngine || opts.decompilationEngine === 'ghidra-pcode' || opts.decompilationEngine === 'both') {
220
+ try {
221
+ // Dynamic import for Ghidra engine (when implemented) - using Function to bypass TypeScript type checking
222
+ const importModule = new Function('specifier', 'return import(specifier)');
223
+ importModule('@pompelmi/engine-ghidra').then((mod) => {
224
+ const ghidraScanner = mod.createGhidraScanner({
225
+ timeout: opts.decompilationTimeout || opts.timeout || 30000,
226
+ depth,
227
+ ghidraPath: opts.ghidraPath,
228
+ analyzeHeadless: opts.analyzeHeadless
229
+ });
230
+ scanners.push(ghidraScanner);
231
+ }).catch(() => {
232
+ // Ghidra engine not available - silently skip
233
+ });
234
+ }
235
+ catch {
236
+ // Engine not installed
237
+ }
238
+ }
239
+ }
240
+ if (scanners.length === 0) {
241
+ // Fallback scanner that returns no matches
242
+ return async (_input, _ctx) => {
243
+ return [];
244
+ };
245
+ }
246
+ return composeScanners(...scanners);
247
+ }
248
+
249
+ /**
250
+ * Performance monitoring utilities for pompelmi scans
251
+ * @module utils/performance-metrics
252
+ */
253
+ /**
254
+ * Track performance metrics for a scan operation
255
+ */
256
+ class PerformanceTracker {
257
+ constructor() {
258
+ this.checkpoints = new Map();
259
+ this.startTime = Date.now();
260
+ }
261
+ /**
262
+ * Mark a checkpoint in the scan process
263
+ */
264
+ checkpoint(name) {
265
+ this.checkpoints.set(name, Date.now());
266
+ }
267
+ /**
268
+ * Get duration since start or since a specific checkpoint
269
+ */
270
+ getDuration(since) {
271
+ const now = Date.now();
272
+ if (since && this.checkpoints.has(since)) {
273
+ return now - (this.checkpoints.get(since) ?? now);
274
+ }
275
+ return now - this.startTime;
276
+ }
277
+ /**
278
+ * Generate final metrics report
279
+ */
280
+ getMetrics(bytesScanned) {
281
+ const totalDuration = this.getDuration();
282
+ const throughput = totalDuration > 0 ? (bytesScanned / totalDuration) * 1000 : 0;
283
+ return {
284
+ totalDurationMs: totalDuration,
285
+ heuristicsDurationMs: this.checkpoints.has('heuristics_end')
286
+ ? (this.checkpoints.get('heuristics_end') ?? 0) - (this.checkpoints.get('heuristics_start') ?? 0)
287
+ : undefined,
288
+ yaraDurationMs: this.checkpoints.has('yara_end')
289
+ ? (this.checkpoints.get('yara_end') ?? 0) - (this.checkpoints.get('yara_start') ?? 0)
290
+ : undefined,
291
+ prepDurationMs: this.checkpoints.has('prep_end')
292
+ ? (this.checkpoints.get('prep_end') ?? 0) - this.startTime
293
+ : undefined,
294
+ throughputBps: throughput,
295
+ bytesScanned,
296
+ startedAt: this.startTime,
297
+ completedAt: Date.now(),
298
+ };
299
+ }
300
+ }
301
+ /**
302
+ * Aggregate statistics from multiple scan reports
303
+ */
304
+ function aggregateScanStats(reports) {
305
+ let cleanCount = 0;
306
+ let suspiciousCount = 0;
307
+ let maliciousCount = 0;
308
+ let totalDuration = 0;
309
+ let totalBytes = 0;
310
+ let validDurationCount = 0;
311
+ for (const report of reports) {
312
+ if (report.verdict === 'clean')
313
+ cleanCount++;
314
+ else if (report.verdict === 'suspicious')
315
+ suspiciousCount++;
316
+ else if (report.verdict === 'malicious')
317
+ maliciousCount++;
318
+ if (report.durationMs !== undefined) {
319
+ totalDuration += report.durationMs;
320
+ validDurationCount++;
321
+ }
322
+ if (report.file?.size !== undefined) {
323
+ totalBytes += report.file.size;
324
+ }
325
+ }
326
+ const avgDuration = validDurationCount > 0 ? totalDuration / validDurationCount : 0;
327
+ const avgThroughput = totalDuration > 0 ? (totalBytes / totalDuration) * 1000 : 0;
328
+ return {
329
+ totalScans: reports.length,
330
+ cleanCount,
331
+ suspiciousCount,
332
+ maliciousCount,
333
+ avgDurationMs: avgDuration,
334
+ avgThroughputBps: avgThroughput,
335
+ totalBytesScanned: totalBytes,
336
+ };
337
+ }
338
+
339
+ /**
340
+ * Advanced threat detection utilities
341
+ * @module utils/advanced-detection
342
+ */
343
+ /**
344
+ * Enhanced polyglot file detection
345
+ * Detects files that can be interpreted as multiple formats
346
+ */
347
+ function detectPolyglot(bytes) {
348
+ const matches = [];
349
+ // Check for PDF/ZIP polyglot
350
+ if (isPDFZipPolyglot(bytes)) {
351
+ matches.push({
352
+ rule: 'polyglot_pdf_zip',
353
+ severity: 'high',
354
+ meta: { description: 'File can be interpreted as both PDF and ZIP' },
355
+ });
356
+ }
357
+ // Check for image/script polyglot
358
+ if (isImageScriptPolyglot(bytes)) {
359
+ matches.push({
360
+ rule: 'polyglot_image_script',
361
+ severity: 'high',
362
+ meta: { description: 'Image file contains executable script content' },
363
+ });
364
+ }
365
+ // Check for GIFAR (GIF/JAR polyglot)
366
+ if (isGIFAR(bytes)) {
367
+ matches.push({
368
+ rule: 'polyglot_gifar',
369
+ severity: 'critical',
370
+ meta: { description: 'GIF file contains Java archive' },
371
+ });
372
+ }
373
+ return matches;
374
+ }
375
+ /**
376
+ * Detect obfuscated JavaScript/VBScript
377
+ */
378
+ function detectObfuscatedScripts(bytes) {
379
+ const matches = [];
380
+ const text = new TextDecoder('utf-8', { fatal: false }).decode(bytes.slice(0, Math.min(64 * 1024, bytes.length)));
381
+ // Check for common obfuscation patterns
382
+ const obfuscationPatterns = [
383
+ /eval\s*\(\s*unescape\s*\(/gi,
384
+ /eval\s*\(\s*atob\s*\(/gi,
385
+ /String\.fromCharCode\s*\(\s*\d+(?:\s*,\s*\d+){10,}/gi,
386
+ /[a-z0-9]{100,}/gi, // Long encoded strings
387
+ /\\x[0-9a-f]{2}/gi, // Hex escapes
388
+ ];
389
+ for (const pattern of obfuscationPatterns) {
390
+ if (pattern.test(text)) {
391
+ matches.push({
392
+ rule: 'obfuscated_script',
393
+ severity: 'medium',
394
+ meta: {
395
+ description: 'Detected obfuscated script content',
396
+ pattern: pattern.source,
397
+ },
398
+ });
399
+ break;
400
+ }
401
+ }
402
+ return matches;
403
+ }
404
+ /**
405
+ * Enhanced nested archive detection with depth limits
406
+ */
407
+ function analyzeNestedArchives(bytes, maxDepth = 10) {
408
+ let depth = 0;
409
+ let currentBytes = bytes;
410
+ while (depth < maxDepth) {
411
+ if (isArchive(currentBytes)) {
412
+ depth++;
413
+ {
414
+ break;
415
+ }
416
+ }
417
+ else {
418
+ break;
419
+ }
420
+ }
421
+ return {
422
+ depth,
423
+ hasExcessiveNesting: depth >= 5,
424
+ };
425
+ }
426
+ // Helper functions
427
+ function isPDFZipPolyglot(bytes) {
428
+ if (bytes.length < 8)
429
+ return false;
430
+ // Check for PDF signature
431
+ const hasPDF = bytes[0] === 0x25 && bytes[1] === 0x50 && bytes[2] === 0x44 && bytes[3] === 0x46;
432
+ // Check for ZIP signature anywhere in the file
433
+ let hasZIP = false;
434
+ for (let i = 0; i < Math.min(bytes.length - 4, 1024); i++) {
435
+ if (bytes[i] === 0x50 && bytes[i + 1] === 0x4B && bytes[i + 2] === 0x03 && bytes[i + 3] === 0x04) {
436
+ hasZIP = true;
437
+ break;
438
+ }
439
+ }
440
+ return hasPDF && hasZIP;
441
+ }
442
+ function isImageScriptPolyglot(bytes) {
443
+ if (bytes.length < 100)
444
+ return false;
445
+ // Check for image signatures
446
+ const isImage = ((bytes[0] === 0xFF && bytes[1] === 0xD8) || // JPEG
447
+ (bytes[0] === 0x89 && bytes[1] === 0x50 && bytes[2] === 0x4E && bytes[3] === 0x47) || // PNG
448
+ (bytes[0] === 0x47 && bytes[1] === 0x49 && bytes[2] === 0x46) // GIF
449
+ );
450
+ if (!isImage)
451
+ return false;
452
+ // Check for script content
453
+ const text = new TextDecoder('utf-8', { fatal: false }).decode(bytes);
454
+ return /<script|javascript:|eval\(|function\s*\(/i.test(text);
455
+ }
456
+ function isGIFAR(bytes) {
457
+ if (bytes.length < 100)
458
+ return false;
459
+ // Check for GIF signature
460
+ const isGIF = bytes[0] === 0x47 && bytes[1] === 0x49 && bytes[2] === 0x46;
461
+ // Check for ZIP/JAR signature
462
+ let hasZIP = false;
463
+ for (let i = 0; i < Math.min(bytes.length - 4, 1024); i++) {
464
+ if (bytes[i] === 0x50 && bytes[i + 1] === 0x4B && bytes[i + 2] === 0x03 && bytes[i + 3] === 0x04) {
465
+ hasZIP = true;
466
+ break;
467
+ }
468
+ }
469
+ return isGIF && hasZIP;
470
+ }
471
+ function isArchive(bytes) {
472
+ if (bytes.length < 4)
473
+ return false;
474
+ return (
475
+ // ZIP
476
+ (bytes[0] === 0x50 && bytes[1] === 0x4B && bytes[2] === 0x03 && bytes[3] === 0x04) ||
477
+ // RAR
478
+ (bytes[0] === 0x52 && bytes[1] === 0x61 && bytes[2] === 0x72 && bytes[3] === 0x21) ||
479
+ // 7z
480
+ (bytes[0] === 0x37 && bytes[1] === 0x7A && bytes[2] === 0xBC && bytes[3] === 0xAF) ||
481
+ // tar.gz
482
+ (bytes[0] === 0x1F && bytes[1] === 0x8B));
483
+ }
484
+
485
+ /**
486
+ * Cache management system for scan results
487
+ * @module utils/cache-manager
488
+ */
489
+ /**
490
+ * LRU cache for scan results with TTL support
491
+ */
492
+ class ScanCacheManager {
493
+ constructor(options = {}) {
494
+ this.cache = new Map();
495
+ // Statistics
496
+ this.stats = {
497
+ hits: 0,
498
+ misses: 0,
499
+ evictions: 0,
500
+ };
501
+ this.maxSize = options.maxSize ?? 1000;
502
+ this.ttl = options.ttl ?? 3600000; // 1 hour default
503
+ this.enableLRU = options.enableLRU ?? true;
504
+ this.enableStats = options.enableStats ?? false;
505
+ }
506
+ /**
507
+ * Generate cache key from file content
508
+ */
509
+ generateKey(content, preset) {
510
+ const hash = crypto.createHash('sha256')
511
+ .update(content)
512
+ .update(preset || 'default')
513
+ .digest('hex');
514
+ return hash;
515
+ }
516
+ /**
517
+ * Check if cache entry is still valid
518
+ */
519
+ isValid(entry) {
520
+ return Date.now() - entry.timestamp < this.ttl;
521
+ }
522
+ /**
523
+ * Evict oldest or least-used entry when cache is full
524
+ */
525
+ evict() {
526
+ if (this.cache.size === 0)
527
+ return;
528
+ let targetKey = null;
529
+ let oldestTime = Infinity;
530
+ let lowestAccess = Infinity;
531
+ for (const [key, entry] of this.cache.entries()) {
532
+ if (this.enableLRU) {
533
+ // LRU: evict least recently used
534
+ if (entry.timestamp < oldestTime) {
535
+ oldestTime = entry.timestamp;
536
+ targetKey = key;
537
+ }
538
+ }
539
+ else {
540
+ // LFU: evict least frequently used
541
+ if (entry.accessCount < lowestAccess) {
542
+ lowestAccess = entry.accessCount;
543
+ targetKey = key;
544
+ }
545
+ }
546
+ }
547
+ if (targetKey) {
548
+ this.cache.delete(targetKey);
549
+ if (this.enableStats)
550
+ this.stats.evictions++;
551
+ }
552
+ }
553
+ /**
554
+ * Store scan result in cache
555
+ */
556
+ set(content, report, preset) {
557
+ const key = this.generateKey(content, preset);
558
+ // Evict if necessary
559
+ if (this.cache.size >= this.maxSize) {
560
+ this.evict();
561
+ }
562
+ this.cache.set(key, {
563
+ report,
564
+ timestamp: Date.now(),
565
+ accessCount: 0,
566
+ });
567
+ }
568
+ /**
569
+ * Retrieve scan result from cache
570
+ */
571
+ get(content, preset) {
572
+ const key = this.generateKey(content, preset);
573
+ const entry = this.cache.get(key);
574
+ if (!entry) {
575
+ if (this.enableStats)
576
+ this.stats.misses++;
577
+ return null;
578
+ }
579
+ if (!this.isValid(entry)) {
580
+ this.cache.delete(key);
581
+ if (this.enableStats)
582
+ this.stats.misses++;
583
+ return null;
584
+ }
585
+ // Update access tracking
586
+ entry.accessCount++;
587
+ entry.timestamp = Date.now(); // Update for LRU
588
+ if (this.enableStats)
589
+ this.stats.hits++;
590
+ return entry.report;
591
+ }
592
+ /**
593
+ * Check if result exists in cache
594
+ */
595
+ has(content, preset) {
596
+ const key = this.generateKey(content, preset);
597
+ const entry = this.cache.get(key);
598
+ return entry !== undefined && this.isValid(entry);
599
+ }
600
+ /**
601
+ * Clear entire cache
602
+ */
603
+ clear() {
604
+ this.cache.clear();
605
+ if (this.enableStats) {
606
+ this.stats.hits = 0;
607
+ this.stats.misses = 0;
608
+ this.stats.evictions = 0;
609
+ }
610
+ }
611
+ /**
612
+ * Remove expired entries
613
+ */
614
+ prune() {
615
+ let removed = 0;
616
+ for (const [key, entry] of this.cache.entries()) {
617
+ if (!this.isValid(entry)) {
618
+ this.cache.delete(key);
619
+ removed++;
620
+ }
621
+ }
622
+ return removed;
623
+ }
624
+ /**
625
+ * Get cache statistics
626
+ */
627
+ getStats() {
628
+ const total = this.stats.hits + this.stats.misses;
629
+ const hitRate = total > 0 ? (this.stats.hits / total) * 100 : 0;
630
+ return {
631
+ hits: this.stats.hits,
632
+ misses: this.stats.misses,
633
+ size: this.cache.size,
634
+ hitRate,
635
+ evictions: this.stats.evictions,
636
+ };
637
+ }
638
+ /**
639
+ * Get current cache size
640
+ */
641
+ get size() {
642
+ return this.cache.size;
643
+ }
644
+ }
645
+ // Export singleton instance for convenience
646
+ let defaultCache = null;
647
+ /**
648
+ * Get or create the default cache instance
649
+ */
650
+ function getDefaultCache(options) {
651
+ if (!defaultCache) {
652
+ defaultCache = new ScanCacheManager(options);
653
+ }
654
+ return defaultCache;
655
+ }
656
+
657
+ /** Mappa veloce estensione -> mime (basic) */
658
+ function guessMimeByExt(name) {
659
+ if (!name)
660
+ return;
661
+ const ext = name.toLowerCase().split('.').pop();
662
+ switch (ext) {
663
+ case 'zip': return 'application/zip';
664
+ case 'png': return 'image/png';
665
+ case 'jpg':
666
+ case 'jpeg': return 'image/jpeg';
667
+ case 'pdf': return 'application/pdf';
668
+ case 'txt': return 'text/plain';
669
+ default: return;
670
+ }
671
+ }
672
+ /** Heuristica semplice per verdetto */
673
+ function computeVerdict(matches) {
674
+ if (!matches.length)
675
+ return 'clean';
676
+ // se la regola contiene 'zip_' lo marchiamo "suspicious"
677
+ const anyHigh = matches.some(m => (m.tags ?? []).includes('critical') || (m.tags ?? []).includes('high'));
678
+ return anyHigh ? 'malicious' : 'suspicious';
679
+ }
680
+ /** Converte i Match (heuristics) in YaraMatch-like per uniformare l'output */
681
+ function toYaraMatches(ms) {
682
+ return ms.map(m => ({
683
+ rule: m.rule,
684
+ namespace: 'heuristics',
685
+ tags: ['heuristics'].concat(m.severity ? [m.severity] : []),
686
+ meta: m.meta,
687
+ }));
688
+ }
689
+ /** Scan di bytes (browser/node) usando preset (default: zip-basic) */
690
+ async function scanBytes(input, opts = {}) {
691
+ // Check cache first if enabled
692
+ if (opts.enableCache || opts.config?.performance?.enableCache) {
693
+ const cache = getDefaultCache(opts.config?.performance?.cacheOptions);
694
+ const cached = cache.get(input, opts.preset);
695
+ if (cached) {
696
+ return cached;
697
+ }
698
+ }
699
+ const perfTracker = (opts.enablePerformanceTracking || opts.config?.performance?.enablePerformanceTracking)
700
+ ? new PerformanceTracker()
701
+ : null;
702
+ perfTracker?.checkpoint('prep_start');
703
+ const preset = opts.preset ?? opts.config?.defaultPreset ?? 'zip-basic';
704
+ const ctx = {
705
+ ...opts.ctx,
706
+ mimeType: opts.ctx?.mimeType ?? guessMimeByExt(opts.ctx?.filename),
707
+ size: opts.ctx?.size ?? input.byteLength,
708
+ };
709
+ perfTracker?.checkpoint('prep_end');
710
+ perfTracker?.checkpoint('heuristics_start');
711
+ const scanFn = createPresetScanner(preset);
712
+ const matchesH = await (typeof scanFn === "function" ? scanFn : scanFn.scan)(input, ctx);
713
+ let allMatches = [...matchesH];
714
+ perfTracker?.checkpoint('heuristics_end');
715
+ // Advanced detection (enabled by default, can be overridden by config)
716
+ const advancedEnabled = opts.enableAdvancedDetection ?? opts.config?.advanced?.enablePolyglotDetection ?? true;
717
+ if (advancedEnabled) {
718
+ perfTracker?.checkpoint('advanced_start');
719
+ // Detect polyglot files
720
+ if (opts.config?.advanced?.enablePolyglotDetection !== false) {
721
+ const polyglotMatches = detectPolyglot(input);
722
+ allMatches.push(...polyglotMatches);
723
+ }
724
+ // Detect obfuscated scripts
725
+ if (opts.config?.advanced?.enableObfuscationDetection !== false) {
726
+ const obfuscatedMatches = detectObfuscatedScripts(input);
727
+ allMatches.push(...obfuscatedMatches);
728
+ }
729
+ // Check for excessive nesting in archives
730
+ if (opts.config?.advanced?.enableNestedArchiveAnalysis !== false) {
731
+ const nestingAnalysis = analyzeNestedArchives(input);
732
+ const maxDepth = opts.config?.advanced?.maxArchiveDepth ?? 5;
733
+ if (nestingAnalysis.hasExcessiveNesting || (nestingAnalysis.depth > maxDepth)) {
734
+ allMatches.push({
735
+ rule: 'excessive_archive_nesting',
736
+ severity: 'high',
737
+ meta: {
738
+ description: 'Excessive archive nesting detected',
739
+ depth: nestingAnalysis.depth,
740
+ maxAllowed: maxDepth,
741
+ },
742
+ });
743
+ }
744
+ }
745
+ perfTracker?.checkpoint('advanced_end');
746
+ }
747
+ const matches = toYaraMatches(allMatches);
748
+ const verdict = computeVerdict(matches);
749
+ perfTracker ? perfTracker.getDuration() : Date.now();
750
+ const durationMs = perfTracker ? perfTracker.getDuration() : 0;
751
+ const report = {
752
+ ok: verdict === 'clean',
753
+ verdict,
754
+ matches,
755
+ reasons: matches.map(m => m.rule),
756
+ file: { name: ctx.filename, mimeType: ctx.mimeType, size: ctx.size },
757
+ durationMs,
758
+ engine: 'heuristics',
759
+ truncated: false,
760
+ timedOut: false,
761
+ };
762
+ // Add performance metrics if tracking enabled
763
+ if (perfTracker && (opts.enablePerformanceTracking || opts.config?.performance?.enablePerformanceTracking)) {
764
+ report.performanceMetrics = perfTracker.getMetrics(input.byteLength);
765
+ }
766
+ // Cache result if enabled
767
+ if (opts.enableCache || opts.config?.performance?.enableCache) {
768
+ const cache = getDefaultCache(opts.config?.performance?.cacheOptions);
769
+ cache.set(input, report, opts.preset);
770
+ }
771
+ // Invoke callbacks if configured
772
+ opts.config?.callbacks?.onScanComplete?.(report);
773
+ return report;
774
+ }
775
+ /** Scan di un file su disco (Node). Import dinamico per non vincolare il bundle browser. */
776
+ async function scanFile(filePath, opts = {}) {
777
+ const [{ readFile, stat }, path] = await Promise.all([
778
+ import('fs/promises'),
779
+ import('path'),
780
+ ]);
781
+ const [buf, st] = await Promise.all([readFile(filePath), stat(filePath)]);
782
+ const ctx = {
783
+ filename: path.basename(filePath),
784
+ mimeType: guessMimeByExt(filePath),
785
+ size: st.size,
786
+ };
787
+ return scanBytes(new Uint8Array(buf.buffer, buf.byteOffset, buf.byteLength), { ...opts, ctx });
788
+ }
789
+ /** Scan multipli File (browser) usando scanBytes + preset di default */
790
+ async function scanFiles(files, opts = {}) {
791
+ const list = Array.from(files);
792
+ const out = [];
793
+ for (const f of list) {
794
+ const buf = new Uint8Array(await f.arrayBuffer());
795
+ const rep = await scanBytes(buf, {
796
+ ...opts,
797
+ ctx: { filename: f.name, mimeType: f.type || guessMimeByExt(f.name), size: f.size },
798
+ });
799
+ out.push(rep);
800
+ }
801
+ return out;
802
+ }
803
+
804
+ /**
805
+ * Validates a File by MIME type and size (max 5 MB).
806
+ */
807
+ function validateFile(file) {
808
+ const maxSize = 5 * 1024 * 1024;
809
+ const allowedTypes = ['text/plain', 'application/json', 'text/csv'];
810
+ if (!allowedTypes.includes(file.type)) {
811
+ return { valid: false, error: 'Unsupported file type' };
812
+ }
813
+ if (file.size > maxSize) {
814
+ return { valid: false, error: 'File too large (max 5 MB)' };
815
+ }
816
+ return { valid: true };
817
+ }
818
+
819
+ const SIG_CEN = 0x02014b50;
820
+ const DEFAULTS = {
821
+ maxEntries: 1000,
822
+ maxTotalUncompressedBytes: 500 * 1024 * 1024,
823
+ maxEntryNameLength: 255,
824
+ maxCompressionRatio: 1000,
825
+ eocdSearchWindow: 70000,
826
+ };
827
+ function r16(buf, off) {
828
+ return buf.readUInt16LE(off);
829
+ }
830
+ function r32(buf, off) {
831
+ return buf.readUInt32LE(off);
832
+ }
833
+ function isZipLike(buf) {
834
+ // local file header at start is common
835
+ return buf.length >= 4 && buf[0] === 0x50 && buf[1] === 0x4b && buf[2] === 0x03 && buf[3] === 0x04;
836
+ }
837
+ function lastIndexOfEOCD(buf, window) {
838
+ const sig = Buffer.from([0x50, 0x4b, 0x05, 0x06]);
839
+ const start = Math.max(0, buf.length - window);
840
+ const idx = buf.lastIndexOf(sig, Math.min(buf.length - sig.length, buf.length - 1));
841
+ return idx >= start ? idx : -1;
842
+ }
843
+ function hasTraversal(name) {
844
+ return name.includes('../') || name.includes('..\\') || name.startsWith('/') || /^[A-Za-z]:/.test(name);
845
+ }
846
+ function createZipBombGuard(opts = {}) {
847
+ const cfg = { ...DEFAULTS, ...opts };
848
+ return {
849
+ async scan(input) {
850
+ const buf = Buffer.from(input);
851
+ const matches = [];
852
+ if (!isZipLike(buf))
853
+ return matches;
854
+ // Find EOCD near the end
855
+ const eocdPos = lastIndexOfEOCD(buf, cfg.eocdSearchWindow);
856
+ if (eocdPos < 0 || eocdPos + 22 > buf.length) {
857
+ // ZIP but no EOCD — malformed or polyglot → suspicious
858
+ matches.push({ rule: 'zip_eocd_not_found', severity: 'medium' });
859
+ return matches;
860
+ }
861
+ const totalEntries = r16(buf, eocdPos + 10);
862
+ const cdSize = r32(buf, eocdPos + 12);
863
+ const cdOffset = r32(buf, eocdPos + 16);
864
+ // Bounds check
865
+ if (cdOffset + cdSize > buf.length) {
866
+ matches.push({ rule: 'zip_cd_out_of_bounds', severity: 'medium' });
867
+ return matches;
868
+ }
869
+ // Iterate central directory entries
870
+ let ptr = cdOffset;
871
+ let seen = 0;
872
+ let sumComp = 0;
873
+ let sumUnc = 0;
874
+ while (ptr + 46 <= cdOffset + cdSize && seen < totalEntries) {
875
+ const sig = r32(buf, ptr);
876
+ if (sig !== SIG_CEN)
877
+ break; // stop if structure breaks
878
+ const compSize = r32(buf, ptr + 20);
879
+ const uncSize = r32(buf, ptr + 24);
880
+ const fnLen = r16(buf, ptr + 28);
881
+ const exLen = r16(buf, ptr + 30);
882
+ const cmLen = r16(buf, ptr + 32);
883
+ const nameStart = ptr + 46;
884
+ const nameEnd = nameStart + fnLen;
885
+ if (nameEnd > buf.length)
886
+ break;
887
+ const name = buf.toString('utf8', nameStart, nameEnd);
888
+ sumComp += compSize;
889
+ sumUnc += uncSize;
890
+ seen++;
891
+ if (name.length > cfg.maxEntryNameLength) {
892
+ matches.push({ rule: 'zip_entry_name_too_long', severity: 'medium', meta: { name, length: name.length } });
893
+ }
894
+ if (hasTraversal(name)) {
895
+ matches.push({ rule: 'zip_path_traversal_entry', severity: 'medium', meta: { name } });
896
+ }
897
+ // move to next entry
898
+ ptr = nameEnd + exLen + cmLen;
899
+ }
900
+ if (seen !== totalEntries) {
901
+ // central dir truncated/odd, still report what we found
902
+ matches.push({ rule: 'zip_cd_truncated', severity: 'medium', meta: { seen, totalEntries } });
903
+ }
904
+ // Heuristics thresholds
905
+ if (seen > cfg.maxEntries) {
906
+ matches.push({ rule: 'zip_too_many_entries', severity: 'medium', meta: { seen, limit: cfg.maxEntries } });
907
+ }
908
+ if (sumUnc > cfg.maxTotalUncompressedBytes) {
909
+ matches.push({
910
+ rule: 'zip_total_uncompressed_too_large',
911
+ severity: 'medium',
912
+ meta: { totalUncompressed: sumUnc, limit: cfg.maxTotalUncompressedBytes }
913
+ });
914
+ }
915
+ if (sumComp === 0 && sumUnc > 0) {
916
+ matches.push({ rule: 'zip_suspicious_ratio', severity: 'medium', meta: { ratio: Infinity } });
917
+ }
918
+ else if (sumComp > 0) {
919
+ const ratio = sumUnc / Math.max(1, sumComp);
920
+ if (ratio >= cfg.maxCompressionRatio) {
921
+ matches.push({ rule: 'zip_suspicious_ratio', severity: 'medium', meta: { ratio, limit: cfg.maxCompressionRatio } });
922
+ }
923
+ }
924
+ return matches;
925
+ }
926
+ };
927
+ }
928
+
929
+ const MB$1 = 1024 * 1024;
930
+ const DEFAULT_POLICY = {
931
+ includeExtensions: ['zip', 'png', 'jpg', 'jpeg', 'pdf'],
932
+ allowedMimeTypes: ['application/zip', 'image/png', 'image/jpeg', 'application/pdf', 'text/plain'],
933
+ maxFileSizeBytes: 20 * MB$1,
934
+ timeoutMs: 5000,
935
+ concurrency: 4,
936
+ failClosed: true
937
+ };
938
+ function definePolicy(input = {}) {
939
+ const p = { ...DEFAULT_POLICY, ...input };
940
+ if (!Array.isArray(p.includeExtensions))
941
+ throw new TypeError('includeExtensions must be string[]');
942
+ if (!Array.isArray(p.allowedMimeTypes))
943
+ throw new TypeError('allowedMimeTypes must be string[]');
944
+ if (!(Number.isFinite(p.maxFileSizeBytes) && p.maxFileSizeBytes > 0))
945
+ throw new TypeError('maxFileSizeBytes must be > 0');
946
+ if (!(Number.isFinite(p.timeoutMs) && p.timeoutMs > 0))
947
+ throw new TypeError('timeoutMs must be > 0');
948
+ if (!(Number.isInteger(p.concurrency) && p.concurrency > 0))
949
+ throw new TypeError('concurrency must be > 0');
950
+ return p;
951
+ }
952
+
953
+ /**
954
+ * Policy packs for Pompelmi.
955
+ *
956
+ * Pre-configured, named policies for common upload scenarios. Each pack
957
+ * defines the file type allowlist, size limits, and timeout appropriate for
958
+ * its use case.
959
+ *
960
+ * All packs are built on `definePolicy` and are fully overridable:
961
+ *
962
+ * ```ts
963
+ * import { POLICY_PACKS } from 'pompelmi/policy-packs';
964
+ *
965
+ * // Use a pack as-is:
966
+ * const policy = POLICY_PACKS['images-only'];
967
+ *
968
+ * // Or override individual fields:
969
+ * import { definePolicy } from 'pompelmi';
970
+ * const custom = definePolicy({ ...POLICY_PACKS['documents-only'], maxFileSizeBytes: 5 * 1024 * 1024 });
971
+ * ```
972
+ *
973
+ * These packs are *deterministic* and *descriptor-based* — they do not
974
+ * depend on any external threat intelligence feed.
975
+ *
976
+ * @module policy-packs
977
+ */
978
+ const KB = 1024;
979
+ const MB = 1024 * KB;
980
+ // ── Policy packs ──────────────────────────────────────────────────────────────
981
+ /**
982
+ * Documents-only policy.
983
+ *
984
+ * Appropriate for: document management APIs, PDF/Office file upload endpoints,
985
+ * data import pipelines.
986
+ *
987
+ * Allowed: PDF, Word (.docx/.doc), Excel (.xlsx/.xls), PowerPoint (.pptx/.ppt),
988
+ * CSV, plain text, JSON, YAML, ODT/ODS/ODP (OpenDocument).
989
+ * Max size: 25 MB.
990
+ */
991
+ const DOCUMENTS_ONLY = definePolicy({
992
+ includeExtensions: [
993
+ 'pdf',
994
+ 'doc', 'docx',
995
+ 'xls', 'xlsx',
996
+ 'ppt', 'pptx',
997
+ 'odt', 'ods', 'odp',
998
+ 'csv',
999
+ 'txt',
1000
+ 'json',
1001
+ 'yaml', 'yml',
1002
+ 'md',
1003
+ ],
1004
+ allowedMimeTypes: [
1005
+ 'application/pdf',
1006
+ 'application/msword',
1007
+ 'application/vnd.openxmlformats-officedocument.wordprocessingml.document',
1008
+ 'application/vnd.ms-excel',
1009
+ 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
1010
+ 'application/vnd.ms-powerpoint',
1011
+ 'application/vnd.openxmlformats-officedocument.presentationml.presentation',
1012
+ 'application/vnd.oasis.opendocument.text',
1013
+ 'application/vnd.oasis.opendocument.spreadsheet',
1014
+ 'application/vnd.oasis.opendocument.presentation',
1015
+ 'text/csv',
1016
+ 'text/plain',
1017
+ 'application/json',
1018
+ 'text/yaml',
1019
+ 'text/markdown',
1020
+ ],
1021
+ maxFileSizeBytes: 25 * MB,
1022
+ timeoutMs: 10000,
1023
+ concurrency: 4,
1024
+ failClosed: true,
1025
+ });
1026
+ /**
1027
+ * Images-only policy.
1028
+ *
1029
+ * Appropriate for: avatar uploads, product image APIs, content platforms with
1030
+ * user-generated imagery.
1031
+ *
1032
+ * Allowed: JPEG, PNG, GIF, WebP, AVIF, TIFF, BMP, ICO.
1033
+ * Max size: 10 MB.
1034
+ * Note: SVG is intentionally excluded — inline SVGs can contain scripts.
1035
+ */
1036
+ const IMAGES_ONLY = definePolicy({
1037
+ includeExtensions: ['jpg', 'jpeg', 'png', 'gif', 'webp', 'avif', 'tiff', 'tif', 'bmp', 'ico'],
1038
+ allowedMimeTypes: [
1039
+ 'image/jpeg',
1040
+ 'image/png',
1041
+ 'image/gif',
1042
+ 'image/webp',
1043
+ 'image/avif',
1044
+ 'image/tiff',
1045
+ 'image/bmp',
1046
+ 'image/x-icon',
1047
+ 'image/vnd.microsoft.icon',
1048
+ ],
1049
+ maxFileSizeBytes: 10 * MB,
1050
+ timeoutMs: 5000,
1051
+ concurrency: 8,
1052
+ failClosed: true,
1053
+ });
1054
+ /**
1055
+ * Strict public-upload policy.
1056
+ *
1057
+ * Appropriate for: anonymous or low-trust upload endpoints, public APIs,
1058
+ * any surface exposed to untrusted users.
1059
+ *
1060
+ * Aggressive size limit (5 MB), short timeout, fail-closed, narrow MIME
1061
+ * allowlist. Only allows plain images and PDF.
1062
+ */
1063
+ const STRICT_PUBLIC_UPLOAD = definePolicy({
1064
+ includeExtensions: ['jpg', 'jpeg', 'png', 'webp', 'pdf'],
1065
+ allowedMimeTypes: [
1066
+ 'image/jpeg',
1067
+ 'image/png',
1068
+ 'image/webp',
1069
+ 'application/pdf',
1070
+ ],
1071
+ maxFileSizeBytes: 5 * MB,
1072
+ timeoutMs: 4000,
1073
+ concurrency: 2,
1074
+ failClosed: true,
1075
+ });
1076
+ /**
1077
+ * Conservative default policy.
1078
+ *
1079
+ * A hardened version of the built-in `DEFAULT_POLICY` suitable for
1080
+ * production without further customisation. Stricter size limit and
1081
+ * shorter timeout than the permissive default.
1082
+ */
1083
+ const CONSERVATIVE_DEFAULT = definePolicy({
1084
+ includeExtensions: ['zip', 'png', 'jpg', 'jpeg', 'pdf', 'txt', 'csv', 'docx', 'xlsx'],
1085
+ allowedMimeTypes: [
1086
+ 'application/zip',
1087
+ 'image/png',
1088
+ 'image/jpeg',
1089
+ 'application/pdf',
1090
+ 'text/plain',
1091
+ 'text/csv',
1092
+ 'application/vnd.openxmlformats-officedocument.wordprocessingml.document',
1093
+ 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
1094
+ ],
1095
+ maxFileSizeBytes: 10 * MB,
1096
+ timeoutMs: 8000,
1097
+ concurrency: 4,
1098
+ failClosed: true,
1099
+ });
1100
+ /**
1101
+ * Archives policy.
1102
+ *
1103
+ * Appropriate for: endpoints that accept ZIP, tar, or compressed archives.
1104
+ * Combines a generous size allowance with a longer timeout for deep inspection.
1105
+ *
1106
+ * NOTE: Pair this policy with `createZipBombGuard()` to defend against
1107
+ * decompression-bomb attacks:
1108
+ *
1109
+ * ```ts
1110
+ * import { composeScanners, createZipBombGuard, CommonHeuristicsScanner } from 'pompelmi';
1111
+ * const scanner = composeScanners(
1112
+ * [['zipGuard', createZipBombGuard()], ['heuristics', CommonHeuristicsScanner]]
1113
+ * );
1114
+ * ```
1115
+ */
1116
+ const ARCHIVES = definePolicy({
1117
+ includeExtensions: ['zip', 'tar', 'gz', 'tgz', 'bz2', 'xz', '7z', 'rar'],
1118
+ allowedMimeTypes: [
1119
+ 'application/zip',
1120
+ 'application/x-tar',
1121
+ 'application/gzip',
1122
+ 'application/x-bzip2',
1123
+ 'application/x-xz',
1124
+ 'application/x-7z-compressed',
1125
+ 'application/x-rar-compressed',
1126
+ ],
1127
+ maxFileSizeBytes: 100 * MB,
1128
+ timeoutMs: 30000,
1129
+ concurrency: 2,
1130
+ failClosed: true,
1131
+ });
1132
+ /**
1133
+ * Named map of all built-in policy packs.
1134
+ *
1135
+ * ```ts
1136
+ * import { POLICY_PACKS } from 'pompelmi/policy-packs';
1137
+ * const policy = POLICY_PACKS['strict-public-upload'];
1138
+ * ```
1139
+ */
1140
+ const POLICY_PACKS = {
1141
+ 'documents-only': DOCUMENTS_ONLY,
1142
+ 'images-only': IMAGES_ONLY,
1143
+ 'strict-public-upload': STRICT_PUBLIC_UPLOAD,
1144
+ 'conservative-default': CONSERVATIVE_DEFAULT,
1145
+ 'archives': ARCHIVES,
1146
+ };
1147
+ /**
1148
+ * Look up a policy pack by name.
1149
+ * Throws if the name is not recognised.
1150
+ */
1151
+ function getPolicyPack(name) {
1152
+ const policy = POLICY_PACKS[name];
1153
+ if (!policy)
1154
+ throw new Error(`Unknown policy pack: '${name}'. Valid names: ${Object.keys(POLICY_PACKS).join(', ')}`);
1155
+ return policy;
1156
+ }
1157
+
1158
+ function mapMatchesToVerdict(matches = []) {
1159
+ if (!matches.length)
1160
+ return 'clean';
1161
+ const malHints = ['trojan', 'ransom', 'worm', 'spy', 'rootkit', 'keylog', 'botnet'];
1162
+ const tagSet = new Set(matches.flatMap(m => (m.tags ?? []).map(t => t.toLowerCase())));
1163
+ const nameHit = (r) => malHints.some(h => r.toLowerCase().includes(h));
1164
+ const isMal = matches.some(m => nameHit(m.rule)) || tagSet.has('malware') || tagSet.has('critical');
1165
+ return isMal ? 'malicious' : 'suspicious';
1166
+ }
1167
+
1168
+ /**
1169
+ * Export utilities for scan results
1170
+ * @module utils/export
1171
+ */
1172
+ /**
1173
+ * Export scan results to various formats
1174
+ */
1175
+ class ScanResultExporter {
1176
+ /**
1177
+ * Export to JSON format
1178
+ */
1179
+ toJSON(reports, options = {}) {
1180
+ const data = Array.isArray(reports) ? reports : [reports];
1181
+ if (!options.includeDetails) {
1182
+ // Simplified output
1183
+ const simplified = data.map(r => ({
1184
+ verdict: r.verdict,
1185
+ file: r.file?.name,
1186
+ matches: r.matches.length,
1187
+ durationMs: r.durationMs,
1188
+ }));
1189
+ return options.prettyPrint
1190
+ ? JSON.stringify(simplified, null, 2)
1191
+ : JSON.stringify(simplified);
1192
+ }
1193
+ return options.prettyPrint
1194
+ ? JSON.stringify(data, null, 2)
1195
+ : JSON.stringify(data);
1196
+ }
1197
+ /**
1198
+ * Export to CSV format
1199
+ */
1200
+ toCSV(reports, options = {}) {
1201
+ const data = Array.isArray(reports) ? reports : [reports];
1202
+ const headers = [
1203
+ 'filename',
1204
+ 'verdict',
1205
+ 'matches_count',
1206
+ 'file_size',
1207
+ 'mime_type',
1208
+ 'duration_ms',
1209
+ 'engine',
1210
+ ];
1211
+ if (options.includeDetails) {
1212
+ headers.push('reasons', 'match_rules');
1213
+ }
1214
+ const rows = data.map(report => {
1215
+ const row = [
1216
+ this.escapeCsv(report.file?.name || 'unknown'),
1217
+ report.verdict,
1218
+ report.matches.length.toString(),
1219
+ (report.file?.size || 0).toString(),
1220
+ this.escapeCsv(report.file?.mimeType || 'unknown'),
1221
+ (report.durationMs || 0).toString(),
1222
+ report.engine || 'unknown',
1223
+ ];
1224
+ if (options.includeDetails) {
1225
+ row.push(this.escapeCsv((report.reasons || []).join('; ')), this.escapeCsv(report.matches.map(m => m.rule).join('; ')));
1226
+ }
1227
+ return row.join(',');
1228
+ });
1229
+ return [headers.join(','), ...rows].join('\n');
1230
+ }
1231
+ /**
1232
+ * Export to Markdown format
1233
+ */
1234
+ toMarkdown(reports, options = {}) {
1235
+ const data = Array.isArray(reports) ? reports : [reports];
1236
+ let md = '# Scan Results\n\n';
1237
+ md += `**Total Scans:** ${data.length}\n\n`;
1238
+ const clean = data.filter(r => r.verdict === 'clean').length;
1239
+ const suspicious = data.filter(r => r.verdict === 'suspicious').length;
1240
+ const malicious = data.filter(r => r.verdict === 'malicious').length;
1241
+ md += '## Summary\n\n';
1242
+ md += `- ✅ Clean: ${clean}\n`;
1243
+ md += `- ⚠️ Suspicious: ${suspicious}\n`;
1244
+ md += `- ❌ Malicious: ${malicious}\n\n`;
1245
+ md += '## Detailed Results\n\n';
1246
+ for (const report of data) {
1247
+ const icon = report.verdict === 'clean' ? '✅' : report.verdict === 'suspicious' ? '⚠️' : '❌';
1248
+ md += `### ${icon} ${report.file?.name || 'Unknown'}\n\n`;
1249
+ md += `- **Verdict:** ${report.verdict}\n`;
1250
+ md += `- **Size:** ${this.formatBytes(report.file?.size || 0)}\n`;
1251
+ md += `- **MIME Type:** ${report.file?.mimeType || 'unknown'}\n`;
1252
+ md += `- **Duration:** ${report.durationMs || 0}ms\n`;
1253
+ md += `- **Matches:** ${report.matches.length}\n`;
1254
+ if (options.includeDetails && report.matches.length > 0) {
1255
+ md += '\n**Match Details:**\n';
1256
+ for (const match of report.matches) {
1257
+ md += `- ${match.rule}`;
1258
+ if (match.tags && match.tags.length > 0) {
1259
+ md += ` (${match.tags.join(', ')})`;
1260
+ }
1261
+ md += '\n';
1262
+ }
1263
+ }
1264
+ md += '\n';
1265
+ }
1266
+ return md;
1267
+ }
1268
+ /**
1269
+ * Export to SARIF format (Static Analysis Results Interchange Format)
1270
+ * Useful for CI/CD integration
1271
+ */
1272
+ toSARIF(reports, options = {}) {
1273
+ const data = Array.isArray(reports) ? reports : [reports];
1274
+ const results = data.flatMap(report => {
1275
+ if (report.verdict === 'clean')
1276
+ return [];
1277
+ return report.matches.map(match => ({
1278
+ ruleId: match.rule,
1279
+ level: report.verdict === 'malicious' ? 'error' : 'warning',
1280
+ message: {
1281
+ text: `${match.rule} detected in ${report.file?.name || 'unknown file'}`,
1282
+ },
1283
+ locations: [
1284
+ {
1285
+ physicalLocation: {
1286
+ artifactLocation: {
1287
+ uri: report.file?.name || 'unknown',
1288
+ },
1289
+ },
1290
+ },
1291
+ ],
1292
+ properties: {
1293
+ tags: match.tags,
1294
+ metadata: match.meta,
1295
+ },
1296
+ }));
1297
+ });
1298
+ const sarif = {
1299
+ version: '2.1.0',
1300
+ $schema: 'https://raw.githubusercontent.com/oasis-tcs/sarif-spec/master/Schemata/sarif-schema-2.1.0.json',
1301
+ runs: [
1302
+ {
1303
+ tool: {
1304
+ driver: {
1305
+ name: 'Pompelmi',
1306
+ version: '0.29.0',
1307
+ informationUri: 'https://pompelmi.github.io/pompelmi/',
1308
+ },
1309
+ },
1310
+ results,
1311
+ },
1312
+ ],
1313
+ };
1314
+ return options.prettyPrint
1315
+ ? JSON.stringify(sarif, null, 2)
1316
+ : JSON.stringify(sarif);
1317
+ }
1318
+ /**
1319
+ * Export to HTML format
1320
+ */
1321
+ toHTML(reports, options = {}) {
1322
+ const data = Array.isArray(reports) ? reports : [reports];
1323
+ const clean = data.filter(r => r.verdict === 'clean').length;
1324
+ const suspicious = data.filter(r => r.verdict === 'suspicious').length;
1325
+ const malicious = data.filter(r => r.verdict === 'malicious').length;
1326
+ let html = `<!DOCTYPE html>
1327
+ <html lang="en">
1328
+ <head>
1329
+ <meta charset="UTF-8">
1330
+ <meta name="viewport" content="width=device-width, initial-scale=1.0">
1331
+ <title>Pompelmi Scan Results</title>
1332
+ <style>
1333
+ body { font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif; max-width: 1200px; margin: 0 auto; padding: 20px; }
1334
+ .summary { display: grid; grid-template-columns: repeat(3, 1fr); gap: 20px; margin: 20px 0; }
1335
+ .card { padding: 20px; border-radius: 8px; text-align: center; }
1336
+ .clean { background: #d4edda; color: #155724; }
1337
+ .suspicious { background: #fff3cd; color: #856404; }
1338
+ .malicious { background: #f8d7da; color: #721c24; }
1339
+ .result { border: 1px solid #ddd; border-radius: 8px; padding: 15px; margin: 10px 0; }
1340
+ .result h3 { margin-top: 0; }
1341
+ .badge { display: inline-block; padding: 4px 8px; border-radius: 4px; font-size: 0.8em; margin: 2px; }
1342
+ table { width: 100%; border-collapse: collapse; }
1343
+ th, td { padding: 8px; text-align: left; border-bottom: 1px solid #ddd; }
1344
+ </style>
1345
+ </head>
1346
+ <body>
1347
+ <h1>🛡️ Pompelmi Scan Results</h1>
1348
+ <div class="summary">
1349
+ <div class="card clean"><h2>${clean}</h2><p>Clean Files</p></div>
1350
+ <div class="card suspicious"><h2>${suspicious}</h2><p>Suspicious Files</p></div>
1351
+ <div class="card malicious"><h2>${malicious}</h2><p>Malicious Files</p></div>
1352
+ </div>
1353
+ <h2>Detailed Results</h2>`;
1354
+ for (const report of data) {
1355
+ const statusClass = report.verdict;
1356
+ html += `<div class="result ${statusClass}">`;
1357
+ html += `<h3>${this.escapeHtml(report.file?.name || 'Unknown')}</h3>`;
1358
+ html += `<table>`;
1359
+ html += `<tr><th>Verdict</th><td>${report.verdict.toUpperCase()}</td></tr>`;
1360
+ html += `<tr><th>Size</th><td>${this.formatBytes(report.file?.size || 0)}</td></tr>`;
1361
+ html += `<tr><th>MIME Type</th><td>${this.escapeHtml(report.file?.mimeType || 'unknown')}</td></tr>`;
1362
+ html += `<tr><th>Duration</th><td>${report.durationMs || 0}ms</td></tr>`;
1363
+ html += `<tr><th>Matches</th><td>${report.matches.length}</td></tr>`;
1364
+ html += `</table>`;
1365
+ if (options.includeDetails && report.matches.length > 0) {
1366
+ html += `<h4>Match Details:</h4><ul>`;
1367
+ for (const match of report.matches) {
1368
+ html += `<li><strong>${this.escapeHtml(match.rule)}</strong>`;
1369
+ if (match.tags && match.tags.length > 0) {
1370
+ html += ` ${match.tags.map(tag => `<span class="badge">${this.escapeHtml(tag)}</span>`).join('')}`;
1371
+ }
1372
+ html += `</li>`;
1373
+ }
1374
+ html += `</ul>`;
1375
+ }
1376
+ html += `</div>`;
1377
+ }
1378
+ html += `</body></html>`;
1379
+ return html;
1380
+ }
1381
+ /**
1382
+ * Export to specified format
1383
+ */
1384
+ export(reports, format, options = {}) {
1385
+ switch (format) {
1386
+ case 'json':
1387
+ return this.toJSON(reports, options);
1388
+ case 'csv':
1389
+ return this.toCSV(reports, options);
1390
+ case 'markdown':
1391
+ return this.toMarkdown(reports, options);
1392
+ case 'html':
1393
+ return this.toHTML(reports, options);
1394
+ case 'sarif':
1395
+ return this.toSARIF(reports, options);
1396
+ default:
1397
+ throw new Error(`Unsupported export format: ${format}`);
1398
+ }
1399
+ }
1400
+ escapeCsv(value) {
1401
+ if (value.includes(',') || value.includes('"') || value.includes('\n')) {
1402
+ return `"${value.replace(/"/g, '""')}"`;
1403
+ }
1404
+ return value;
1405
+ }
1406
+ escapeHtml(value) {
1407
+ return value
1408
+ .replace(/&/g, '&amp;')
1409
+ .replace(/</g, '&lt;')
1410
+ .replace(/>/g, '&gt;')
1411
+ .replace(/"/g, '&quot;')
1412
+ .replace(/'/g, '&#039;');
1413
+ }
1414
+ formatBytes(bytes) {
1415
+ if (bytes === 0)
1416
+ return '0 Bytes';
1417
+ const k = 1024;
1418
+ const sizes = ['Bytes', 'KB', 'MB', 'GB'];
1419
+ const i = Math.floor(Math.log(bytes) / Math.log(k));
1420
+ return Math.round(bytes / Math.pow(k, i) * 100) / 100 + ' ' + sizes[i];
1421
+ }
1422
+ }
1423
+ /**
1424
+ * Quick export helper
1425
+ */
1426
+ function exportScanResults(reports, format, options) {
1427
+ const exporter = new ScanResultExporter();
1428
+ return exporter.export(reports, format, options);
1429
+ }
1430
+
1431
+ /**
1432
+ * React Hook: handles <input type="file" onChange> with validation + scanning.
1433
+ */
1434
+ function useFileScanner() {
1435
+ const [results, setResults] = react.useState([]);
1436
+ const [errors, setErrors] = react.useState([]);
1437
+ const onChange = react.useCallback(async (e) => {
1438
+ const fileList = Array.from(e.target.files || []);
1439
+ const good = [];
1440
+ const bad = [];
1441
+ for (const file of fileList) {
1442
+ const { valid, error } = validateFile(file);
1443
+ if (valid)
1444
+ good.push(file);
1445
+ else
1446
+ bad.push({ file, error: error });
1447
+ }
1448
+ setErrors(bad);
1449
+ if (good.length) {
1450
+ const scanned = await scanFiles(good);
1451
+ setResults(scanned.map((r, i) => ({ file: good[i], report: r })));
1452
+ }
1453
+ else {
1454
+ setResults([]);
1455
+ }
1456
+ }, []);
1457
+ return { results, errors, onChange };
1458
+ }
1459
+
1460
+ exports.ARCHIVES = ARCHIVES;
1461
+ exports.CONSERVATIVE_DEFAULT = CONSERVATIVE_DEFAULT;
1462
+ exports.CommonHeuristicsScanner = CommonHeuristicsScanner;
1463
+ exports.DEFAULT_POLICY = DEFAULT_POLICY;
1464
+ exports.DOCUMENTS_ONLY = DOCUMENTS_ONLY;
1465
+ exports.IMAGES_ONLY = IMAGES_ONLY;
1466
+ exports.POLICY_PACKS = POLICY_PACKS;
1467
+ exports.PerformanceTracker = PerformanceTracker;
1468
+ exports.STRICT_PUBLIC_UPLOAD = STRICT_PUBLIC_UPLOAD;
1469
+ exports.ScanResultExporter = ScanResultExporter;
1470
+ exports.aggregateScanStats = aggregateScanStats;
1471
+ exports.analyzeNestedArchives = analyzeNestedArchives;
1472
+ exports.composeScanners = composeScanners;
1473
+ exports.createPresetScanner = createPresetScanner;
1474
+ exports.createZipBombGuard = createZipBombGuard;
1475
+ exports.definePolicy = definePolicy;
1476
+ exports.detectObfuscatedScripts = detectObfuscatedScripts;
1477
+ exports.detectPolyglot = detectPolyglot;
1478
+ exports.exportScanResults = exportScanResults;
1479
+ exports.getPolicyPack = getPolicyPack;
1480
+ exports.mapMatchesToVerdict = mapMatchesToVerdict;
1481
+ exports.scanBytes = scanBytes;
1482
+ exports.scanFile = scanFile;
1483
+ exports.scanFiles = scanFiles;
1484
+ exports.useFileScanner = useFileScanner;
1485
+ exports.validateFile = validateFile;
1486
+ //# sourceMappingURL=pompelmi.react.cjs.map