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