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