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