pompelmi 0.35.5 → 1.0.0

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