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