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