pompelmi: Fast, Private File Upload Malware Scanning for Node.js
Pompelmi is a privacy-first, high-performance Node.js library for malware scanning in file uploads, featuring YARA integration, deep ZIP inspection, and drop-in adapters for Express, Koa, and Next.js.
pompelmi offers fast file-upload malware scanning for Node.js. It features optional YARA integration, deep ZIP inspection, and convenient drop-in adapters for Express, Koa, and Next.js. Designed with privacy in mind, it is fully typed and boasts a tiny footprint.
Keywords: file upload security Β· malware detection Β· YARA Β· Node.js middleware Β· Express Β· Koa Β· Next.js Β· ZIP bomb protection
π Documentation β’ πΎ Install β’ β‘ Quick Start β’ π§© Adapters ⒠𧬠YARA β’ π€ CI/CD β’ β FAQ
Coverage badge reflects core library (src/**); adapters are measured separately.
π― Why Choose pompelmi?
- π Privacy First All scanning occurs in-process. There are no cloud calls or data leaks, ensuring your files never leave your infrastructure.
- β‘ Lightning Fast Benefit from in-process scanning with zero network latency. Configurable concurrency supports high-throughput scenarios.
- π¨ Developer Friendly Experience a TypeScript-first design, zero-config defaults, and drop-in middleware. Get started in under 5 minutes.
Table of Contents
- Overview
- Highlights
- Why pompelmi
- How it compares
- What Developers Say
- What Makes pompelmi Special
- Use Cases
- Installation
- Quick Start
- Configuration
- Security Notes
- Testing & Development
- FAQ
- Contributing
- License
π Overview
pompelmi is a tiny, TypeScript-first toolkit for Node.js that scans untrusted file uploads before they hit disk. It features composable scanners, deep ZIP inspection, and optional signature engines.
π― Key Features
- π Private by design β no outbound calls; bytes never leave your process.
- π§© Composable scanners β mix heuristics + signatures; set
stopOnand timeouts. - π¦ ZIP hardening β traversal/bomb guards, polyglot & macro hints.
- π Drop-in adapters β Express, Koa, Fastify, Next.js.
- π Typed & tiny β modern TS, minimal surface, tree-shakeable.
- β‘ Zero dependencies β core library has minimal dependencies, ensuring fast installation.
β¨ Highlights
- π‘οΈ Block risky uploads early β Classify uploads as
clean,suspicious, ormaliciousand prevent them at the edge. - β Real guards β Implement extension allow-lists, server-side MIME sniffing (magic bytes), per-file size caps, and deep ZIP traversal with anti-bomb limits.
- π Built-in scanners β Utilize the drop-in
CommonHeuristicsScanner(for PDF risky actions, Office macros, PE headers) andZip-bomb Guard; extend with your own or YARA via a simple{ scan(bytes) }contract. - βοΈ Compose scanning β Run multiple scanners in parallel or sequentially with timeouts and short-circuiting using
composeScanners(). - βοΈ Zero cloud β Scans run in-process, keeping bytes private. Ideal for GDPR/HIPAA compliance.
- π¨βπ» DX first β Benefit from TypeScript types, ESM/CJS builds, a tiny API, and adapters for popular web frameworks.
SEO Keywords: file upload security, malware detection, virus scanner, Node.js security, Express middleware, YARA integration, ZIP bomb protection, file validation, upload sanitization, threat detection, security scanner, antivirus Node.js, file scanning library, TypeScript security, Next.js security, Koa middleware, server-side validation, file integrity check, malware prevention, secure file upload
π§ Why pompelmi?
- On-device, private scanning β No outbound calls, no data sharing.
- Blocks early β Runs before you write to disk or persist anything.
- Fits your stack β Drop-in adapters for Express, Koa, Next.js (Fastify plugin in alpha).
- Defense-in-depth β ZIP traversal limits, ratio caps, server-side MIME sniffing, size caps.
- Pluggable detection β Bring your own engine (e.g., YARA) via a tiny
{ scan(bytes) }contract.
Who is it for?
- Teams who cannot send uploads to third-party AV APIs.
- Applications that require predictable, low-latency decisions inline.
- Developers seeking simple, typed building blocks instead of a daemon.
π How it compares
| Capability | pompelmi | ClamAV / nodeβclam | Cloud AV APIs |
|---|---|---|---|
| Runs fully inβprocess | β | β (separate daemon) | β (network calls) |
| Bytes stay private | β | β | β |
| Deep ZIP limits & MIME sniff | β | β (archive scan) | β varies |
| YARA integration | β optional | β* | β varies |
| Framework adapters | β Express/Koa/Next.js | β | β |
| Works in CI on artifacts | β | β | β varies |
| Licensing | MIT | GPL (engine) | Proprietary |
- You can run YARA alongside ClamAV, but itβs not builtβin.
π¬ What Developers Say
"pompelmi made it incredibly easy to add malware scanning to our Express API. The TypeScript support is fantastic!" β Developer using pompelmi in production
"Finally, a file scanning solution that doesn't require sending our users' data to third parties. Perfect for GDPR compliance." β Security Engineer at a healthcare startup
"The YARA integration is seamless. We went from prototype to production in less than a week." β DevSecOps Engineer
Want to share your experience? Open a discussion!
π What Makes pompelmi Special?
- π― Developer Experience Built with developers in mind from day one, pompelmi offers a simple API, comprehensive TypeScript types, and excellent documentation for integration in minutes. Hot module replacement support and detailed error messages streamline debugging.
- π Performance First Optimized for high-throughput with configurable concurrency, streaming support, and minimal memory overhead. Process thousands of files effortlessly, with in-process scans eliminating IPC overhead.
- π Security Without Compromise Multi-layered defense includes MIME type verification (magic bytes), extension validation, size limits, ZIP bomb protection, and optional YARA integration. Each layer is configurable to your threat model.
- π Privacy Guaranteed Your data remains within your infrastructure. No telemetry, no cloud dependencies, no third-party API calls. Ideal for regulated industries (healthcare, finance, government) and privacy-conscious applications.
π‘ Use Cases
pompelmi is trusted across diverse industries and use cases:
- π₯ Healthcare (HIPAA Compliance) Scan patient document uploads without sending Protected Health Information (PHI) to third-party services. Keep medical records and imaging files secure on your infrastructure.
- π¦ Financial Services (PCI DSS) Validate customer document uploads (ID verification, tax forms) without exposing sensitive financial data to external APIs.
- π Education Platforms Protect learning management systems from malicious file uploads while maintaining student privacy.
- π± SaaS Applications Add secure file upload capabilities to your multi-tenant platform with per-tenant policy customization.
- π’ Enterprise Document Management Scan files at ingestion for corporate file sharing platforms, wikis, and collaboration tools.
- π¨ Media & Creative Platforms Validate user-generated content uploads (images, videos, documents) before processing and storage.
π§ Installation
npm
npm install pompelmi
pnpm
pnpm add pompelmi
yarn
yarn add pompelmi
bun
bun add pompelmi
π¦ Optional Framework Adapters
# Express
npm i @pompelmi/express-middleware
# Koa
npm i @pompelmi/koa-middleware
# Next.js
npm i @pompelmi/next-upload
# Fastify (alpha)
npm i @pompelmi/fastify-plugin
Note: The core library works standalone. Install adapters only if using specific frameworks.
Optional dev dependencies used in the examples:
npm i -D tsx express multer @koa/router @koa/multer koa next
β‘ Quickβstart
At a glance (policy + scanners)
import {
CommonHeuristicsScanner,
createZipBombGuard,
composeScanners
} from 'pompelmi';
export const policy = {
includeExtensions: [
'zip',
'png',
'jpg',
'jpeg',
'pdf'
],
allowedMimeTypes: [
'application/zip',
'image/png',
'image/jpeg',
'application/pdf',
'text/plain'
],
maxFileSizeBytes: 20 * 1024 * 1024,
timeoutMs: 5000,
concurrency: 4,
failClosed: true,
onScanEvent: (ev: unknown) => console.log('[scan]', ev)
};
export const scanner = composeScanners(
[
[
'zipGuard',
createZipBombGuard({
maxEntries: 512,
maxTotalUncompressedBytes: 100 * 1024 * 1024,
maxCompressionRatio: 12
})
],
['heuristics', CommonHeuristicsScanner],
// ['yara', YourYaraScanner],
],
{
parallel: false,
stopOn: 'suspicious',
timeoutMsPerScanner: 1500,
tagSourceName: true
}
);
Minimal Node usage
import { scanFile } from 'pompelmi';
const res = await scanFile('path/to/file.zip');
// or any file
console.log(res.verdict); // "clean" | "suspicious" | "malicious"
See examples/scan-one-file.ts for a runnable script:
pnpm tsx examples/scan-one-file.ts ./path/to/file
Express
import express from 'express';
import multer from 'multer';
import { createUploadGuard } from '@pompelmi/express-middleware';
import { policy, scanner } from './security'; // the snippet above
const app = express();
const upload = multer({
storage: multer.memoryStorage(),
limits: {
fileSize: policy.maxFileSizeBytes
}
});
app.post('/upload',
upload.any(),
createUploadGuard({
...policy,
scanner
}),
(req, res) => {
res.json({
ok: true,
scan: (req as any).pompelmi ?? null
});
}
);
app.listen(3000, () => console.log('http://localhost:3000'));
Koa
import Koa from 'koa';
import Router from '@koa/router';
import multer from '@koa/multer';
import { createKoaUploadGuard } from '@pompelmi/koa-middleware';
import { policy, scanner } from './security';
const app = new Koa();
const router = new Router();
const upload = multer({
storage: multer.memoryStorage(),
limits: {
fileSize: policy.maxFileSizeBytes
}
});
router.post(
'/upload',
upload.any(),
createKoaUploadGuard({
...policy,
scanner
}),
(ctx) => {
ctx.body = {
ok: true,
scan: (ctx as any).pompelmi ?? null
};
}
);
app.use(router.routes()).use(router.allowedMethods());
app.listen(3003, () => console.log('http://localhost:3003'));
Next.js (App Router)
// app/api/upload/route.ts
import { createNextUploadHandler } from '@pompelmi/next-upload';
import { policy, scanner } from '@/lib/security';
export const runtime = 'nodejs';
export const dynamic = 'force-dynamic';
export const POST = createNextUploadHandler({
...policy,
scanner
});
π€ GitHub Action
Run pompelmi in CI to scan repository files or built artifacts.
Minimal usage
name: Security scan (pompelmi)
on: [push, pull_request]
jobs:
scan:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- name: Scan repository with pompelmi
uses: pompelmi/pompelmi/.github/actions/pompelmi-scan@v1
with:
path: .
deep_zip: true
fail_on_detect: true
Scan a single artifact
- uses: pompelmi/pompelmi/.github/actions/pompelmi-scan@v1
with:
artifact: build.zip
deep_zip: true
fail_on_detect: true
Inputs
| Input | Default | Description |
|---|---|---|
path | . | Directory to scan. |
artifact | "" | Single file/archive to scan. |
yara_rules | "" | Glob path to YARA rules (e.g., rules/*.yar). |
deep_zip | true | Enable deep nested-archive inspection. |
max_depth | 3 | Max nested-archive depth. |
fail_on_detect | true | Fail the job if detections occur. |
The Action lives in this repo at .github/actions/pompelmi-scan. When published to the Marketplace, consumers can copy the snippets above as-is.
π§© Adapters
Use the adapter that matches your web framework. All adapters share the same policy options and scanning contract.
| Framework | Package | Status |
|---|---|---|
| Express | @pompelmi/express-middleware | β alpha |
| Koa | @pompelmi/koa-middleware | β alpha |
| Next.js (App Router) | @pompelmi/next-upload | β alpha |
| Fastify | @pompelmi/fastify-plugin | π§ alpha |
| NestJS | nestjs | π planned |
| Remix | remix | π planned |
| hapi | hapi plugin | π planned |
| SvelteKit | sveltekit | π planned |
πΊοΈ Diagrams
Upload scanning flow
The diagram illustrates the process of file uploads through pompelmi, from client upload to final verdict, including pre-filters and ZIP inspection logic.
flowchart TD
A["Client uploads file(s)"] --> B["Web App Route"]
B --> C{"Pre-filters<br/>(ext, size, MIME)"}
C -- fail --> X["HTTP 4xx"]
C -- pass --> D{"Is ZIP?"}
D -- yes --> E["Iterate entries<br/>(limits & scan)"]
E --> F{"Verdict?"}
D -- no --> F{"Scan bytes"}
F -- malicious/suspicious --> Y["HTTP 422 blocked"]
F -- clean --> Z["HTTP 200 ok + results"]
Sequence (App β pompelmi β YARA)
This sequence diagram details the interaction between the user, application route, pompelmi adapter, and an optional YARA engine during a file upload scan.
sequenceDiagram
participant U as User
participant A as App Route (/upload)
participant P as pompelmi (adapter)
participant Y as YARA engine
U->>A: POST multipart/form-data
A->>P: guard(files, policies)
P->>P: MIME sniff + size + ext checks
alt ZIP archive
P->>P: unpack entries with limits
end
P->>Y: scan(bytes)
Y-->>P: matches[]
P-->>A: verdict (clean/suspicious/malicious)
A-->>U: 200 or 4xx/422 with reason
Components (monorepo)
This flowchart visualizes the modular structure of the pompelmi monorepo, showing the core library and its various framework adapters.
flowchart LR
subgraph Repo
core["pompelmi (core)"]
express["@pompelmi/express-middleware"]
koa["@pompelmi/koa-middleware"]
next["@pompelmi/next-upload"]
fastify(("fastify-plugin Β· planned"))
nest(("nestjs Β· planned"))
remix(("remix Β· planned"))
hapi(("hapi-plugin Β· planned"))
svelte(("sveltekit Β· planned"))
end
core --> express
core --> koa
core --> next
core -.-> fastify
core -.-> nest
core -.-> remix
core -.-> hapi
core -.-> svelte
βοΈ Configuration
All adapters accept a common set of options:
| Option | Type (TS) | Purpose |
|---|---|---|
scanner | { scan(bytes: Uint8Array): Promise<Match[]> } | Your scanning engine. Return [] when clean; nonβempty to flag. |
includeExtensions | string[] | Allowβlist of file extensions. Evaluated caseβinsensitively. |
allowedMimeTypes | string[] | Allowβlist of MIME types after magicβbyte sniffing. |
maxFileSizeBytes | number | Perβfile size cap. Oversize files are rejected early. |
timeoutMs | number | Perβfile scan timeout; guards against stuck scanners. |
concurrency | number | How many files to scan in parallel. |
failClosed | boolean | If true, errors/timeouts block the upload. |
onScanEvent | (event: unknown) => void | Optional telemetry hook for logging/metrics. |
Common recipes
Allow only images up to 5 MB:
includeExtensions: [
'png',
'jpg',
'jpeg',
'webp'
],
allowedMimeTypes: [
'image/png',
'image/jpeg',
'image/webp'
],
maxFileSizeBytes: 5 * 1024 * 1024,
failClosed: true,
β Production checklist
- Limit file size aggressively (
maxFileSizeBytes). - Restrict extensions & MIME to what your app truly needs.
- Set
failClosed: truein production to block on timeouts/errors. - Handle ZIPs carefully (enable deep ZIP, keep nesting low, cap entry sizes).
- Compose scanners with
composeScanners()and enablestopOnto fail fast on early detections. - Log scan events (
onScanEvent) and monitor for spikes. - Run scans in a separate process/container for defense-in-depth when possible.
- Sanitize file names and paths if you persist uploads.
- Prefer memory storage + post-processing; avoid writing untrusted bytes before policy passes.
- Add CI scanning with the GitHub Action to catch bad files in repos/artifacts.
𧬠YARA Getting Started
YARA enables the detection of suspicious or malicious content through pattern-matching rules. pompelmi treats YARA matches as signals that you can map to your own verdicts (e.g., mark high-confidence rules as malicious, heuristics as suspicious).
Status: Optional. You can run without YARA. If you adopt it, keep your rules small, time-bound, and tuned to your threat model.
Starter rules
Below are three example rules you can adapt:
rules/starter/eicar.yar
rule EICAR_Test_File
{
meta:
description = "EICAR antivirus test string (safe)"
reference = "https://www.eicar.org"
confidence = "high"
verdict = "malicious"
strings:
$eicar = "X5O!P%@AP[4\\PZX54(P^)7CC)7}$EICAR-STANDARD-ANTIVIRUS-TEST-FILE!$H+H*"
condition:
$eicar
}
rules/starter/pdf_js.yar
rule PDF_JavaScript_Embedded
{
meta:
description = "PDF contains embedded JavaScript (heuristic)"
confidence = "medium"
verdict = "suspicious"
strings:
$magic = {25 50 44 46} // "%PDF"
$js1 = "/JavaScript" ascii
$js2 = "/JS" ascii
$open = "/OpenAction" ascii
$aa = "/AA" ascii
condition:
uint32(0) == 0x25504446 and ($js1 or $js2) and ($open or $aa)
}
rules/starter/office_macros.yar
rule Office_Macro_Suspicious_Words
{
meta:
description = "Heuristic: suspicious VBA macro keywords"
confidence = "medium"
verdict = "suspicious"
strings:
$s1 = /Auto(Open|Close)/ nocase
$s2 = "Document_Open" nocase ascii
$s3 = "CreateObject(" nocase ascii
$s4 = "WScript.Shell" nocase ascii
$s5 = "Shell(" nocase ascii
$s6 = "Sub Workbook_Open()" nocase ascii
condition:
2 of ($s*)
}
These are examples. Expect some false positives; tune to your application's needs.
Minimal integration (adapter contract)
If you use a YARA binding (e.g., @automattic/yara), wrap it behind the scanner contract:
// Example YARA scanner adapter (pseudoβcode)
import * as Y from '@automattic/yara';
// Compile your rules from disk at boot (recommended)
// const sources = await fs.readFile('rules/starter/*.yar', 'utf8');
// const compiled = await Y.compile(sources);
export const YourYaraScanner = {
async scan(bytes: Uint8Array) {
// const matches = await compiled.scan(bytes, { timeout: 1500 });
const matches = []; // plug your engine here
// Map to the structure your app expects; return [] when clean.
return matches.map((m: any) => ({
rule: m.rule,
meta: m.meta ?? {},
tags: m.tags ?? [],
}));
}
};
Then include it in your composed scanner:
import {
composeScanners,
CommonHeuristicsScanner
} from 'pompelmi';
// import { YourYaraScanner } from './yara-scanner';
export const scanner = composeScanners(
[
['heuristics', CommonHeuristicsScanner],
// ['yara', YourYaraScanner],
],
{
parallel: false,
stopOn: 'suspicious',
timeoutMsPerScanner: 1500,
tagSourceName: true
}
);
Policy suggestion (mapping matches β verdict)
malicious: high-confidence rules (e.g.,EICAR_Test_File)suspicious: heuristic rules (e.g., PDF JavaScript, macro keywords)clean: no matches
Combine YARA with MIME sniffing, ZIP safety limits, and strict size/time caps.
π§ͺ Quick test (no EICAR)
Use the examples above, then send a minimal PDF that contains risky tokens (this triggers the built-in heuristics).
- Create a tiny PDF with risky actions
Linux:
printf '%%PDF-1.7
1 0 obj
<< /OpenAction 1 0 R /AA << /JavaScript (alert(1)) >> >>
endobj
%%EOF
' > risky.pdf
macOS:
printf '%%PDF-1.7
1 0 obj
<< /OpenAction 1 0 R /AA << /JavaScript (alert(1)) >> >>
endobj
%%EOF
' > risky.pdf
- Send it to your endpoint
Express (default from the Quick-start):
curl -F "file=@risky.pdf;type=application/pdf" http://localhost:3000/upload -i
You should see an HTTP 422 Unprocessable Entity (blocked by policy). Clean files return 200 OK. Pre-filter failures (size/ext/MIME) should return a 4xx. Adapt these conventions to your app as needed.
π Security notes
- The library reads bytes; it never executes files.
- YARA detections depend on the rules you provide; expect some false positives/negatives.
- ZIP scanning applies limits (entries, per-entry size, total uncompressed, nesting) to reduce archive-bomb risk.
- Prefer running scans in a dedicated process/container for defense-in-depth.
π Releases & security
- Changelog / releases: See GitHub Releases.
- Security disclosures: Please use GitHub Security Advisories. We'll coordinate a fix before public disclosure.
- Production users: Open a Discussion to share requirements or request adapters.
β Star history
π Community & Recognition
pompelmi has been featured in leading developer publications and is trusted by teams worldwide for secure file upload handling.
π€ Join the Community
- π¬ GitHub Discussions β Ask questions, share ideas.
- π Issue Tracker β Report bugs, request features.
- π Documentation β Comprehensive guides and API reference.
- π Security β Report security vulnerabilities privately.
π¬ FAQ
Do I need YARA?
No. The scanner is pluggable. The examples use a minimal scanner for clarity; you can call out to a YARA engine or any other detector you prefer.
Where do the results live?
In the examples, the guard attaches scan data to the request context (e.g., req.pompelmi in Express, ctx.pompelmi in Koa). In Next.js, include the results in your JSON response as you see fit.
Why 422 for blocked files?
Using 422 to signal a policy violation keeps it distinct from transport errors; itβs a common pattern. Use the codes that best match your API guidelines.
Are ZIP bombs handled?
Archives are traversed with limits to reduce archive-bomb risk. Keep your size limits conservative and prefer failClosed: true in production.
π§ͺ Tests & Coverage
Run tests locally with coverage:
pnpm vitest run --coverage --passWithNoTests
The badge tracks the core library (src/**). Adapters and engines are reported separately for now and will be folded into global coverage as their suites grow.
If you integrate Codecov in CI, upload coverage/lcov.info and you can use this Codecov badge:

π€ Contributing
PRs and issues are welcome! Start with:
pnpm -r build
pnpm -r lint
See CONTRIBUTING.md for detailed guidelines.
ποΈ Contributors
Thanks to all the amazing contributors who have helped make pompelmi better!
π Learning Resources
-
π Documentation
- Official Docs β Complete API reference and guides
- Examples β Real-world integration examples
- Security Guide β Security best practices and disclosure policy
-
π₯ Tutorials & Articles
- File Upload Security in Node.js β Best practices guide (coming soon)
- Integrating YARA with pompelmi β Advanced detection setup (coming soon)
- Zero-Trust File Uploads β Architecture patterns (coming soon)
-
π οΈ Tools & Integrations
- GitHub Action β CI/CD scanning
- Docker Images β Containerized scanning (coming soon)
- Cloud Functions β Serverless examples (coming soon)
π Project Stats
π Acknowledgments
pompelmi stands on the shoulders of giants. Special thanks to:
- The YARA project for powerful pattern matching
- The Node.js community for excellent tooling
- All our contributors and users
π Support
Need help? We're here for you!
- π Documentation
- π¬ GitHub Discussions
- π Issue Tracker
- π Security (for vulnerabilities)
For commercial support and consulting, contact the maintainers.
β Back to top
π License
MIT Β© 2025-present pompelmi contributors