pompelmi 0.33.0 → 0.34.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +351 -987
- package/dist/pompelmi.audit.cjs +130 -0
- package/dist/pompelmi.audit.cjs.map +1 -0
- package/dist/pompelmi.audit.esm.js +109 -0
- package/dist/pompelmi.audit.esm.js.map +1 -0
- package/dist/pompelmi.browser.cjs +1455 -0
- package/dist/pompelmi.browser.cjs.map +1 -0
- package/dist/pompelmi.browser.esm.js +1429 -0
- package/dist/pompelmi.browser.esm.js.map +1 -0
- package/dist/pompelmi.cjs +1333 -3044
- package/dist/pompelmi.cjs.map +1 -1
- package/dist/pompelmi.esm.js +1327 -3042
- package/dist/pompelmi.esm.js.map +1 -1
- package/dist/pompelmi.hooks.cjs +75 -0
- package/dist/pompelmi.hooks.cjs.map +1 -0
- package/dist/pompelmi.hooks.esm.js +72 -0
- package/dist/pompelmi.hooks.esm.js.map +1 -0
- package/dist/pompelmi.policy-packs.cjs +239 -0
- package/dist/pompelmi.policy-packs.cjs.map +1 -0
- package/dist/pompelmi.policy-packs.esm.js +231 -0
- package/dist/pompelmi.policy-packs.esm.js.map +1 -0
- package/dist/pompelmi.quarantine.cjs +315 -0
- package/dist/pompelmi.quarantine.cjs.map +1 -0
- package/dist/pompelmi.quarantine.esm.js +291 -0
- package/dist/pompelmi.quarantine.esm.js.map +1 -0
- package/dist/pompelmi.react.cjs +1486 -0
- package/dist/pompelmi.react.cjs.map +1 -0
- package/dist/pompelmi.react.esm.js +1459 -0
- package/dist/pompelmi.react.esm.js.map +1 -0
- package/dist/types/audit.d.ts +84 -0
- package/dist/types/browser-index.d.ts +28 -2
- package/dist/types/config.d.ts +3 -2
- package/dist/types/hooks.d.ts +89 -0
- package/dist/types/index.d.ts +17 -9
- package/dist/types/policy-packs.d.ts +98 -0
- package/dist/types/quarantine/index.d.ts +18 -0
- package/dist/types/quarantine/storage.d.ts +77 -0
- package/dist/types/quarantine/types.d.ts +78 -0
- package/dist/types/quarantine/workflow.d.ts +97 -0
- package/dist/types/react-index.d.ts +13 -0
- package/dist/types/types.d.ts +0 -1
- package/package.json +54 -3
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"pompelmi.policy-packs.esm.js","sources":["../src/policy.ts","../src/policy-packs.ts"],"sourcesContent":["export interface Policy {\n includeExtensions: string[];\n allowedMimeTypes: string[];\n maxFileSizeBytes: number;\n timeoutMs: number;\n concurrency: number;\n failClosed: boolean;\n onScanEvent?: (ev: unknown) => void;\n}\nexport type PolicyInput = Partial<Policy>;\n\nconst MB = 1024 * 1024;\n\nexport const DEFAULT_POLICY: Policy = {\n includeExtensions: ['zip','png','jpg','jpeg','pdf'],\n allowedMimeTypes: ['application/zip','image/png','image/jpeg','application/pdf','text/plain'],\n maxFileSizeBytes: 20 * MB,\n timeoutMs: 5000,\n concurrency: 4,\n failClosed: true\n};\n\nexport function definePolicy(input: PolicyInput = {}): Policy {\n const p: Policy = { ...DEFAULT_POLICY, ...input };\n if (!Array.isArray(p.includeExtensions)) throw new TypeError('includeExtensions must be string[]');\n if (!Array.isArray(p.allowedMimeTypes)) throw new TypeError('allowedMimeTypes must be string[]');\n if (!(Number.isFinite(p.maxFileSizeBytes) && p.maxFileSizeBytes > 0)) throw new TypeError('maxFileSizeBytes must be > 0');\n if (!(Number.isFinite(p.timeoutMs) && p.timeoutMs > 0)) throw new TypeError('timeoutMs must be > 0');\n if (!(Number.isInteger(p.concurrency) && p.concurrency > 0)) throw new TypeError('concurrency must be > 0');\n return p;\n}\n","/**\n * Policy packs for Pompelmi.\n *\n * Pre-configured, named policies for common upload scenarios. Each pack\n * defines the file type allowlist, size limits, and timeout appropriate for\n * its use case.\n *\n * All packs are built on `definePolicy` and are fully overridable:\n *\n * ```ts\n * import { POLICY_PACKS } from 'pompelmi/policy-packs';\n *\n * // Use a pack as-is:\n * const policy = POLICY_PACKS['images-only'];\n *\n * // Or override individual fields:\n * import { definePolicy } from 'pompelmi';\n * const custom = definePolicy({ ...POLICY_PACKS['documents-only'], maxFileSizeBytes: 5 * 1024 * 1024 });\n * ```\n *\n * These packs are *deterministic* and *descriptor-based* — they do not\n * depend on any external threat intelligence feed.\n *\n * @module policy-packs\n */\n\nimport { definePolicy, type Policy } from './policy';\n\nconst KB = 1024;\nconst MB = 1024 * KB;\n\n// ── Policy packs ──────────────────────────────────────────────────────────────\n\n/**\n * Documents-only policy.\n *\n * Appropriate for: document management APIs, PDF/Office file upload endpoints,\n * data import pipelines.\n *\n * Allowed: PDF, Word (.docx/.doc), Excel (.xlsx/.xls), PowerPoint (.pptx/.ppt),\n * CSV, plain text, JSON, YAML, ODT/ODS/ODP (OpenDocument).\n * Max size: 25 MB.\n */\nexport const DOCUMENTS_ONLY: Policy = definePolicy({\n includeExtensions: [\n 'pdf',\n 'doc', 'docx',\n 'xls', 'xlsx',\n 'ppt', 'pptx',\n 'odt', 'ods', 'odp',\n 'csv',\n 'txt',\n 'json',\n 'yaml', 'yml',\n 'md',\n ],\n allowedMimeTypes: [\n 'application/pdf',\n 'application/msword',\n 'application/vnd.openxmlformats-officedocument.wordprocessingml.document',\n 'application/vnd.ms-excel',\n 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',\n 'application/vnd.ms-powerpoint',\n 'application/vnd.openxmlformats-officedocument.presentationml.presentation',\n 'application/vnd.oasis.opendocument.text',\n 'application/vnd.oasis.opendocument.spreadsheet',\n 'application/vnd.oasis.opendocument.presentation',\n 'text/csv',\n 'text/plain',\n 'application/json',\n 'text/yaml',\n 'text/markdown',\n ],\n maxFileSizeBytes: 25 * MB,\n timeoutMs: 10_000,\n concurrency: 4,\n failClosed: true,\n});\n\n/**\n * Images-only policy.\n *\n * Appropriate for: avatar uploads, product image APIs, content platforms with\n * user-generated imagery.\n *\n * Allowed: JPEG, PNG, GIF, WebP, AVIF, TIFF, BMP, ICO.\n * Max size: 10 MB.\n * Note: SVG is intentionally excluded — inline SVGs can contain scripts.\n */\nexport const IMAGES_ONLY: Policy = definePolicy({\n includeExtensions: ['jpg', 'jpeg', 'png', 'gif', 'webp', 'avif', 'tiff', 'tif', 'bmp', 'ico'],\n allowedMimeTypes: [\n 'image/jpeg',\n 'image/png',\n 'image/gif',\n 'image/webp',\n 'image/avif',\n 'image/tiff',\n 'image/bmp',\n 'image/x-icon',\n 'image/vnd.microsoft.icon',\n ],\n maxFileSizeBytes: 10 * MB,\n timeoutMs: 5_000,\n concurrency: 8,\n failClosed: true,\n});\n\n/**\n * Strict public-upload policy.\n *\n * Appropriate for: anonymous or low-trust upload endpoints, public APIs,\n * any surface exposed to untrusted users.\n *\n * Aggressive size limit (5 MB), short timeout, fail-closed, narrow MIME\n * allowlist. Only allows plain images and PDF.\n */\nexport const STRICT_PUBLIC_UPLOAD: Policy = definePolicy({\n includeExtensions: ['jpg', 'jpeg', 'png', 'webp', 'pdf'],\n allowedMimeTypes: [\n 'image/jpeg',\n 'image/png',\n 'image/webp',\n 'application/pdf',\n ],\n maxFileSizeBytes: 5 * MB,\n timeoutMs: 4_000,\n concurrency: 2,\n failClosed: true,\n});\n\n/**\n * Conservative default policy.\n *\n * A hardened version of the built-in `DEFAULT_POLICY` suitable for\n * production without further customisation. Stricter size limit and\n * shorter timeout than the permissive default.\n */\nexport const CONSERVATIVE_DEFAULT: Policy = definePolicy({\n includeExtensions: ['zip', 'png', 'jpg', 'jpeg', 'pdf', 'txt', 'csv', 'docx', 'xlsx'],\n allowedMimeTypes: [\n 'application/zip',\n 'image/png',\n 'image/jpeg',\n 'application/pdf',\n 'text/plain',\n 'text/csv',\n 'application/vnd.openxmlformats-officedocument.wordprocessingml.document',\n 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',\n ],\n maxFileSizeBytes: 10 * MB,\n timeoutMs: 8_000,\n concurrency: 4,\n failClosed: true,\n});\n\n/**\n * Archives policy.\n *\n * Appropriate for: endpoints that accept ZIP, tar, or compressed archives.\n * Combines a generous size allowance with a longer timeout for deep inspection.\n *\n * NOTE: Pair this policy with `createZipBombGuard()` to defend against\n * decompression-bomb attacks:\n *\n * ```ts\n * import { composeScanners, createZipBombGuard, CommonHeuristicsScanner } from 'pompelmi';\n * const scanner = composeScanners(\n * [['zipGuard', createZipBombGuard()], ['heuristics', CommonHeuristicsScanner]]\n * );\n * ```\n */\nexport const ARCHIVES: Policy = definePolicy({\n includeExtensions: ['zip', 'tar', 'gz', 'tgz', 'bz2', 'xz', '7z', 'rar'],\n allowedMimeTypes: [\n 'application/zip',\n 'application/x-tar',\n 'application/gzip',\n 'application/x-bzip2',\n 'application/x-xz',\n 'application/x-7z-compressed',\n 'application/x-rar-compressed',\n ],\n maxFileSizeBytes: 100 * MB,\n timeoutMs: 30_000,\n concurrency: 2,\n failClosed: true,\n});\n\n// ── Named map ────────────────────────────────────────────────────────────────\n\nexport type PolicyPackName =\n | 'documents-only'\n | 'images-only'\n | 'strict-public-upload'\n | 'conservative-default'\n | 'archives';\n\n/**\n * Named map of all built-in policy packs.\n *\n * ```ts\n * import { POLICY_PACKS } from 'pompelmi/policy-packs';\n * const policy = POLICY_PACKS['strict-public-upload'];\n * ```\n */\nexport const POLICY_PACKS: Record<PolicyPackName, Policy> = {\n 'documents-only': DOCUMENTS_ONLY,\n 'images-only': IMAGES_ONLY,\n 'strict-public-upload': STRICT_PUBLIC_UPLOAD,\n 'conservative-default': CONSERVATIVE_DEFAULT,\n 'archives': ARCHIVES,\n};\n\n/**\n * Look up a policy pack by name.\n * Throws if the name is not recognised.\n */\nexport function getPolicyPack(name: PolicyPackName): Policy {\n const policy = POLICY_PACKS[name];\n if (!policy) throw new Error(`Unknown policy pack: '${name}'. Valid names: ${Object.keys(POLICY_PACKS).join(', ')}`);\n return policy;\n}\n"],"names":["MB"],"mappings":"AAWA,MAAMA,IAAE,GAAG,IAAI,GAAG,IAAI;AAEf,MAAM,cAAc,GAAW;IACpC,iBAAiB,EAAE,CAAC,KAAK,EAAC,KAAK,EAAC,KAAK,EAAC,MAAM,EAAC,KAAK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AU,EAAE,IAAI;AACjB,CAAA;AAWD;;;;;;;AAOG;AACI,MAAM,YAAY,GAAmC;AAC1D,IAAA,gBAAgB,EAAE,cAAc;AAChC,IAAA,aAAa,EAAE,WAAW;AAC1B,IAAA,sBAAsB,EAAE,oBAAoB;AAC5C,IAAA,sBAAsB,EAAE,oBAAoB;AAC5C,IAAA,UAAU,EAAE,QAAQ;;AAGtB;;;AAGG;AACG,SAAU,aAAa,CAAC,IAAoB,EAAA;AAChD,IAAA,MAAM,MAAM,GAAG,YAAY,CAAC,IAAI,CAAC;AACjC,IAAA,IAAI,CAAC,MAAM;AAAE,QAAA,MAAM,IAAI,KAAK,CAAC,yBAAyB,IAAI,CAAA,gBAAA,EAAmB,MAAM,CAAC,IAAI,CAAC,YAAY,CAAC,CAAC,IAAI,CAAC,IAAI,CAAC,CAAA,CAAE,CAAC;AACpH,IAAA,OAAO,MAAM;AACf;;;;"}
|
|
@@ -0,0 +1,315 @@
|
|
|
1
|
+
'use strict';
|
|
2
|
+
|
|
3
|
+
var crypto = require('crypto');
|
|
4
|
+
var fs = require('fs');
|
|
5
|
+
var path = require('path');
|
|
6
|
+
|
|
7
|
+
function _interopNamespaceDefault(e) {
|
|
8
|
+
var n = Object.create(null);
|
|
9
|
+
if (e) {
|
|
10
|
+
Object.keys(e).forEach(function (k) {
|
|
11
|
+
if (k !== 'default') {
|
|
12
|
+
var d = Object.getOwnPropertyDescriptor(e, k);
|
|
13
|
+
Object.defineProperty(n, k, d.get ? d : {
|
|
14
|
+
enumerable: true,
|
|
15
|
+
get: function () { return e[k]; }
|
|
16
|
+
});
|
|
17
|
+
}
|
|
18
|
+
});
|
|
19
|
+
}
|
|
20
|
+
n.default = e;
|
|
21
|
+
return Object.freeze(n);
|
|
22
|
+
}
|
|
23
|
+
|
|
24
|
+
var crypto__namespace = /*#__PURE__*/_interopNamespaceDefault(crypto);
|
|
25
|
+
var fs__namespace = /*#__PURE__*/_interopNamespaceDefault(fs);
|
|
26
|
+
var path__namespace = /*#__PURE__*/_interopNamespaceDefault(path);
|
|
27
|
+
|
|
28
|
+
/**
|
|
29
|
+
* Quarantine workflow — core API for the quarantine/review/resolve lifecycle.
|
|
30
|
+
*
|
|
31
|
+
* Usage (Node.js):
|
|
32
|
+
*
|
|
33
|
+
* ```ts
|
|
34
|
+
* import { scanBytes } from 'pompelmi';
|
|
35
|
+
* import { QuarantineManager, FilesystemQuarantineStorage } from 'pompelmi/quarantine';
|
|
36
|
+
*
|
|
37
|
+
* const quarantine = new QuarantineManager({
|
|
38
|
+
* storage: new FilesystemQuarantineStorage({ dir: './quarantine' }),
|
|
39
|
+
* });
|
|
40
|
+
*
|
|
41
|
+
* const report = await scanBytes(fileBytes, { ctx: { filename: file.name } });
|
|
42
|
+
*
|
|
43
|
+
* if (report.verdict !== 'clean') {
|
|
44
|
+
* const entry = await quarantine.quarantine(fileBytes, report, {
|
|
45
|
+
* originalName: file.name,
|
|
46
|
+
* sizeBytes: fileBytes.length,
|
|
47
|
+
* uploadedBy: req.user?.id,
|
|
48
|
+
* });
|
|
49
|
+
* console.log('Quarantined:', entry.id);
|
|
50
|
+
* }
|
|
51
|
+
* ```
|
|
52
|
+
*
|
|
53
|
+
* @module quarantine/workflow
|
|
54
|
+
*/
|
|
55
|
+
// ── Manager ───────────────────────────────────────────────────────────────────
|
|
56
|
+
/**
|
|
57
|
+
* Manages the full lifecycle of quarantined files:
|
|
58
|
+
* scan → quarantine → review → promote | delete
|
|
59
|
+
*/
|
|
60
|
+
class QuarantineManager {
|
|
61
|
+
constructor(options) {
|
|
62
|
+
this.storage = options.storage;
|
|
63
|
+
this.quarantineSuspicious = options.quarantineSuspicious ?? true;
|
|
64
|
+
this.quarantineMalicious = options.quarantineMalicious ?? true;
|
|
65
|
+
}
|
|
66
|
+
/**
|
|
67
|
+
* Determine whether a scan report should trigger quarantine per the
|
|
68
|
+
* configured policy.
|
|
69
|
+
*/
|
|
70
|
+
shouldQuarantine(report) {
|
|
71
|
+
if (report.verdict === 'malicious')
|
|
72
|
+
return this.quarantineMalicious;
|
|
73
|
+
if (report.verdict === 'suspicious')
|
|
74
|
+
return this.quarantineSuspicious;
|
|
75
|
+
return false;
|
|
76
|
+
}
|
|
77
|
+
/**
|
|
78
|
+
* Quarantine a file: save the bytes in storage, create the metadata entry,
|
|
79
|
+
* and return the entry.
|
|
80
|
+
*
|
|
81
|
+
* @param bytes Raw file bytes.
|
|
82
|
+
* @param report The scan report that triggered quarantine.
|
|
83
|
+
* @param fileInfo Partial metadata; `sha256` is derived from `bytes` if omitted.
|
|
84
|
+
*/
|
|
85
|
+
async quarantine(bytes, report, fileInfo) {
|
|
86
|
+
const id = generateId();
|
|
87
|
+
const sha256 = fileInfo.sha256 ?? computeSha256(bytes);
|
|
88
|
+
const now = new Date().toISOString();
|
|
89
|
+
const storageKey = await this.storage.saveFile(id, bytes);
|
|
90
|
+
const entry = {
|
|
91
|
+
id,
|
|
92
|
+
storageKey,
|
|
93
|
+
file: { ...fileInfo, sha256 },
|
|
94
|
+
scanReport: report,
|
|
95
|
+
quarantinedAt: now,
|
|
96
|
+
status: 'pending',
|
|
97
|
+
updatedAt: now,
|
|
98
|
+
};
|
|
99
|
+
await this.storage.saveEntry(entry);
|
|
100
|
+
return entry;
|
|
101
|
+
}
|
|
102
|
+
/**
|
|
103
|
+
* Mark an entry as being actively reviewed.
|
|
104
|
+
*/
|
|
105
|
+
async startReview(id, reviewedBy) {
|
|
106
|
+
return this.storage.updateEntry(id, {
|
|
107
|
+
status: 'reviewing',
|
|
108
|
+
reviewedBy,
|
|
109
|
+
updatedAt: new Date().toISOString(),
|
|
110
|
+
});
|
|
111
|
+
}
|
|
112
|
+
/**
|
|
113
|
+
* Resolve a quarantine entry with a final decision.
|
|
114
|
+
*
|
|
115
|
+
* - `promote`: the file is cleared — bytes remain in storage for the caller
|
|
116
|
+
* to move to its final destination.
|
|
117
|
+
* - `delete`: the bytes are permanently removed from quarantine storage.
|
|
118
|
+
*/
|
|
119
|
+
async resolve(id, review) {
|
|
120
|
+
const entry = await this.storage.getEntry(id);
|
|
121
|
+
if (!entry)
|
|
122
|
+
throw new Error(`Quarantine entry not found: ${id}`);
|
|
123
|
+
if (entry.status === 'promoted' || entry.status === 'deleted') {
|
|
124
|
+
throw new Error(`Quarantine entry ${id} is already resolved (${entry.status}).`);
|
|
125
|
+
}
|
|
126
|
+
const now = new Date().toISOString();
|
|
127
|
+
const newStatus = review.decision === 'promote' ? 'promoted' : 'deleted';
|
|
128
|
+
if (review.decision === 'delete') {
|
|
129
|
+
await this.storage.deleteFile(entry.storageKey);
|
|
130
|
+
}
|
|
131
|
+
return this.storage.updateEntry(id, {
|
|
132
|
+
status: newStatus,
|
|
133
|
+
reviewedBy: review.reviewedBy,
|
|
134
|
+
reviewNote: review.reviewNote,
|
|
135
|
+
resolvedAt: now,
|
|
136
|
+
updatedAt: now,
|
|
137
|
+
});
|
|
138
|
+
}
|
|
139
|
+
/**
|
|
140
|
+
* Retrieve the raw bytes of a promoted file so the caller can move it to
|
|
141
|
+
* permanent storage. Returns `null` if the entry is not found or has been
|
|
142
|
+
* deleted.
|
|
143
|
+
*/
|
|
144
|
+
async getFile(id) {
|
|
145
|
+
const entry = await this.storage.getEntry(id);
|
|
146
|
+
if (!entry)
|
|
147
|
+
return null;
|
|
148
|
+
return this.storage.getFile(entry.storageKey);
|
|
149
|
+
}
|
|
150
|
+
// ── Query helpers ───────────────────────────────────────────────────────────
|
|
151
|
+
getEntry(id) {
|
|
152
|
+
return this.storage.getEntry(id);
|
|
153
|
+
}
|
|
154
|
+
listEntries(filter) {
|
|
155
|
+
return this.storage.listEntries(filter);
|
|
156
|
+
}
|
|
157
|
+
listPending() {
|
|
158
|
+
return this.storage.listEntries({ status: 'pending' });
|
|
159
|
+
}
|
|
160
|
+
countEntries(filter) {
|
|
161
|
+
return this.storage.countEntries(filter);
|
|
162
|
+
}
|
|
163
|
+
// ── Reporting ───────────────────────────────────────────────────────────────
|
|
164
|
+
/**
|
|
165
|
+
* Generate a structured JSON report of all quarantine entries matching the
|
|
166
|
+
* filter — suitable for audit logs and dashboards.
|
|
167
|
+
*/
|
|
168
|
+
async report(filter) {
|
|
169
|
+
const entries = await this.storage.listEntries(filter);
|
|
170
|
+
const byStatus = { pending: 0, reviewing: 0, promoted: 0, deleted: 0 };
|
|
171
|
+
for (const e of entries)
|
|
172
|
+
byStatus[e.status]++;
|
|
173
|
+
return {
|
|
174
|
+
generatedAt: new Date().toISOString(),
|
|
175
|
+
totalEntries: entries.length,
|
|
176
|
+
byStatus,
|
|
177
|
+
entries,
|
|
178
|
+
};
|
|
179
|
+
}
|
|
180
|
+
}
|
|
181
|
+
// ── Helpers ───────────────────────────────────────────────────────────────────
|
|
182
|
+
function generateId() {
|
|
183
|
+
return crypto__namespace.randomUUID();
|
|
184
|
+
}
|
|
185
|
+
function computeSha256(bytes) {
|
|
186
|
+
return crypto__namespace.createHash('sha256').update(bytes).digest('hex');
|
|
187
|
+
}
|
|
188
|
+
|
|
189
|
+
/**
|
|
190
|
+
* Quarantine storage adapter interface and filesystem reference implementation.
|
|
191
|
+
*
|
|
192
|
+
* The `QuarantineStorage` interface decouples the quarantine workflow from any
|
|
193
|
+
* specific persistence layer. You can implement it for S3, GCS, a database,
|
|
194
|
+
* or any other backend.
|
|
195
|
+
*
|
|
196
|
+
* The built-in `FilesystemQuarantineStorage` stores files and metadata as JSON
|
|
197
|
+
* in a local directory — suitable for development, self-hosted, and on-premise
|
|
198
|
+
* deployments where data must not leave the machine.
|
|
199
|
+
*
|
|
200
|
+
* @module quarantine/storage
|
|
201
|
+
*/
|
|
202
|
+
/**
|
|
203
|
+
* Reference implementation of `QuarantineStorage` backed by the local filesystem.
|
|
204
|
+
*
|
|
205
|
+
* File layout:
|
|
206
|
+
* <dir>/files/<storageKey> — raw file bytes
|
|
207
|
+
* <dir>/meta/<id>.json — QuarantineEntry JSON
|
|
208
|
+
*
|
|
209
|
+
* Suitable for single-process servers. For multi-process or distributed
|
|
210
|
+
* deployments, implement `QuarantineStorage` against a shared backend.
|
|
211
|
+
*/
|
|
212
|
+
class FilesystemQuarantineStorage {
|
|
213
|
+
constructor(options) {
|
|
214
|
+
this.filesDir = path__namespace.join(options.dir, 'files');
|
|
215
|
+
this.metaDir = path__namespace.join(options.dir, 'meta');
|
|
216
|
+
if (options.createIfMissing !== false) {
|
|
217
|
+
fs__namespace.mkdirSync(this.filesDir, { recursive: true });
|
|
218
|
+
fs__namespace.mkdirSync(this.metaDir, { recursive: true });
|
|
219
|
+
}
|
|
220
|
+
}
|
|
221
|
+
async saveFile(id, bytes) {
|
|
222
|
+
// Use a safe, collision-resistant filename derived from the entry id.
|
|
223
|
+
const storageKey = `${id}-${crypto__namespace.randomBytes(4).toString('hex')}`;
|
|
224
|
+
const filePath = path__namespace.join(this.filesDir, storageKey);
|
|
225
|
+
await fs__namespace.promises.writeFile(filePath, bytes);
|
|
226
|
+
return storageKey;
|
|
227
|
+
}
|
|
228
|
+
async getFile(storageKey) {
|
|
229
|
+
const filePath = path__namespace.join(this.filesDir, safeBasename(storageKey));
|
|
230
|
+
try {
|
|
231
|
+
const buf = await fs__namespace.promises.readFile(filePath);
|
|
232
|
+
return new Uint8Array(buf);
|
|
233
|
+
}
|
|
234
|
+
catch {
|
|
235
|
+
return null;
|
|
236
|
+
}
|
|
237
|
+
}
|
|
238
|
+
async deleteFile(storageKey) {
|
|
239
|
+
const filePath = path__namespace.join(this.filesDir, safeBasename(storageKey));
|
|
240
|
+
await fs__namespace.promises.unlink(filePath).catch(() => { });
|
|
241
|
+
}
|
|
242
|
+
async saveEntry(entry) {
|
|
243
|
+
const metaPath = path__namespace.join(this.metaDir, `${safeBasename(entry.id)}.json`);
|
|
244
|
+
await fs__namespace.promises.writeFile(metaPath, JSON.stringify(entry, null, 2), 'utf8');
|
|
245
|
+
}
|
|
246
|
+
async getEntry(id) {
|
|
247
|
+
const metaPath = path__namespace.join(this.metaDir, `${safeBasename(id)}.json`);
|
|
248
|
+
try {
|
|
249
|
+
const raw = await fs__namespace.promises.readFile(metaPath, 'utf8');
|
|
250
|
+
return JSON.parse(raw);
|
|
251
|
+
}
|
|
252
|
+
catch {
|
|
253
|
+
return null;
|
|
254
|
+
}
|
|
255
|
+
}
|
|
256
|
+
async updateEntry(id, patch) {
|
|
257
|
+
const existing = await this.getEntry(id);
|
|
258
|
+
if (!existing)
|
|
259
|
+
throw new Error(`Quarantine entry not found: ${id}`);
|
|
260
|
+
const updated = { ...existing, ...patch };
|
|
261
|
+
await this.saveEntry(updated);
|
|
262
|
+
return updated;
|
|
263
|
+
}
|
|
264
|
+
async listEntries(filter) {
|
|
265
|
+
const files = await fs__namespace.promises.readdir(this.metaDir).catch(() => []);
|
|
266
|
+
const entries = [];
|
|
267
|
+
for (const file of files) {
|
|
268
|
+
if (!file.endsWith('.json'))
|
|
269
|
+
continue;
|
|
270
|
+
try {
|
|
271
|
+
const raw = await fs__namespace.promises.readFile(path__namespace.join(this.metaDir, file), 'utf8');
|
|
272
|
+
entries.push(JSON.parse(raw));
|
|
273
|
+
}
|
|
274
|
+
catch {
|
|
275
|
+
// Skip unreadable entries.
|
|
276
|
+
}
|
|
277
|
+
}
|
|
278
|
+
return applyFilter(entries, filter);
|
|
279
|
+
}
|
|
280
|
+
async countEntries(filter) {
|
|
281
|
+
const entries = await this.listEntries(filter);
|
|
282
|
+
return entries.length;
|
|
283
|
+
}
|
|
284
|
+
}
|
|
285
|
+
// ── Helpers ───────────────────────────────────────────────────────────────────
|
|
286
|
+
/**
|
|
287
|
+
* Strip directory separators to prevent path-traversal attacks when using
|
|
288
|
+
* user-supplied or derived keys as filenames.
|
|
289
|
+
*/
|
|
290
|
+
function safeBasename(key) {
|
|
291
|
+
return path__namespace.basename(key).replace(/[^a-zA-Z0-9._-]/g, '_');
|
|
292
|
+
}
|
|
293
|
+
function applyFilter(entries, filter) {
|
|
294
|
+
if (!filter)
|
|
295
|
+
return entries;
|
|
296
|
+
let result = entries;
|
|
297
|
+
if (filter.status !== undefined) {
|
|
298
|
+
const statuses = Array.isArray(filter.status) ? filter.status : [filter.status];
|
|
299
|
+
result = result.filter((e) => statuses.includes(e.status));
|
|
300
|
+
}
|
|
301
|
+
if (filter.after) {
|
|
302
|
+
result = result.filter((e) => e.quarantinedAt >= filter.after);
|
|
303
|
+
}
|
|
304
|
+
if (filter.before) {
|
|
305
|
+
result = result.filter((e) => e.quarantinedAt <= filter.before);
|
|
306
|
+
}
|
|
307
|
+
if (filter.limit !== undefined) {
|
|
308
|
+
result = result.slice(0, filter.limit);
|
|
309
|
+
}
|
|
310
|
+
return result;
|
|
311
|
+
}
|
|
312
|
+
|
|
313
|
+
exports.FilesystemQuarantineStorage = FilesystemQuarantineStorage;
|
|
314
|
+
exports.QuarantineManager = QuarantineManager;
|
|
315
|
+
//# sourceMappingURL=pompelmi.quarantine.cjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"pompelmi.quarantine.cjs","sources":["../src/quarantine/workflow.ts","../src/quarantine/storage.ts"],"sourcesContent":["/**\n * Quarantine workflow — core API for the quarantine/review/resolve lifecycle.\n *\n * Usage (Node.js):\n *\n * ```ts\n * import { scanBytes } from 'pompelmi';\n * import { QuarantineManager, FilesystemQuarantineStorage } from 'pompelmi/quarantine';\n *\n * const quarantine = new QuarantineManager({\n * storage: new FilesystemQuarantineStorage({ dir: './quarantine' }),\n * });\n *\n * const report = await scanBytes(fileBytes, { ctx: { filename: file.name } });\n *\n * if (report.verdict !== 'clean') {\n * const entry = await quarantine.quarantine(fileBytes, report, {\n * originalName: file.name,\n * sizeBytes: fileBytes.length,\n * uploadedBy: req.user?.id,\n * });\n * console.log('Quarantined:', entry.id);\n * }\n * ```\n *\n * @module quarantine/workflow\n */\n\nimport * as crypto from 'crypto';\nimport type { ScanReport } from '../types';\nimport type {\n QuarantineEntry,\n QuarantineFilter,\n QuarantineReport,\n QuarantineReview,\n QuarantineStatus,\n QuarantinedFileInfo,\n} from './types';\nimport type { QuarantineStorage } from './storage';\n\n// ── Options ───────────────────────────────────────────────────────────────────\n\nexport interface QuarantineManagerOptions {\n /** Storage adapter — use `FilesystemQuarantineStorage` for local deployments. */\n storage: QuarantineStorage;\n\n /**\n * If true, files with a 'suspicious' verdict are also quarantined.\n * Default: true.\n */\n quarantineSuspicious?: boolean;\n\n /**\n * If true, files with a 'malicious' verdict are also quarantined.\n * Default: true.\n */\n quarantineMalicious?: boolean;\n}\n\n// ── Manager ───────────────────────────────────────────────────────────────────\n\n/**\n * Manages the full lifecycle of quarantined files:\n * scan → quarantine → review → promote | delete\n */\nexport class QuarantineManager {\n private readonly storage: QuarantineStorage;\n private readonly quarantineSuspicious: boolean;\n private readonly quarantineMalicious: boolean;\n\n constructor(options: QuarantineManagerOptions) {\n this.storage = options.storage;\n this.quarantineSuspicious = options.quarantineSuspicious ?? true;\n this.quarantineMalicious = options.quarantineMalicious ?? true;\n }\n\n /**\n * Determine whether a scan report should trigger quarantine per the\n * configured policy.\n */\n shouldQuarantine(report: ScanReport): boolean {\n if (report.verdict === 'malicious') return this.quarantineMalicious;\n if (report.verdict === 'suspicious') return this.quarantineSuspicious;\n return false;\n }\n\n /**\n * Quarantine a file: save the bytes in storage, create the metadata entry,\n * and return the entry.\n *\n * @param bytes Raw file bytes.\n * @param report The scan report that triggered quarantine.\n * @param fileInfo Partial metadata; `sha256` is derived from `bytes` if omitted.\n */\n async quarantine(\n bytes: Uint8Array,\n report: ScanReport,\n fileInfo: Omit<QuarantinedFileInfo, 'sha256'> & { sha256?: string },\n ): Promise<QuarantineEntry> {\n const id = generateId();\n const sha256 = fileInfo.sha256 ?? computeSha256(bytes);\n const now = new Date().toISOString();\n\n const storageKey = await this.storage.saveFile(id, bytes);\n\n const entry: QuarantineEntry = {\n id,\n storageKey,\n file: { ...fileInfo, sha256 },\n scanReport: report,\n quarantinedAt: now,\n status: 'pending',\n updatedAt: now,\n };\n\n await this.storage.saveEntry(entry);\n return entry;\n }\n\n /**\n * Mark an entry as being actively reviewed.\n */\n async startReview(id: string, reviewedBy?: string): Promise<QuarantineEntry> {\n return this.storage.updateEntry(id, {\n status: 'reviewing',\n reviewedBy,\n updatedAt: new Date().toISOString(),\n });\n }\n\n /**\n * Resolve a quarantine entry with a final decision.\n *\n * - `promote`: the file is cleared — bytes remain in storage for the caller\n * to move to its final destination.\n * - `delete`: the bytes are permanently removed from quarantine storage.\n */\n async resolve(id: string, review: QuarantineReview): Promise<QuarantineEntry> {\n const entry = await this.storage.getEntry(id);\n if (!entry) throw new Error(`Quarantine entry not found: ${id}`);\n if (entry.status === 'promoted' || entry.status === 'deleted') {\n throw new Error(`Quarantine entry ${id} is already resolved (${entry.status}).`);\n }\n\n const now = new Date().toISOString();\n const newStatus: QuarantineStatus = review.decision === 'promote' ? 'promoted' : 'deleted';\n\n if (review.decision === 'delete') {\n await this.storage.deleteFile(entry.storageKey);\n }\n\n return this.storage.updateEntry(id, {\n status: newStatus,\n reviewedBy: review.reviewedBy,\n reviewNote: review.reviewNote,\n resolvedAt: now,\n updatedAt: now,\n });\n }\n\n /**\n * Retrieve the raw bytes of a promoted file so the caller can move it to\n * permanent storage. Returns `null` if the entry is not found or has been\n * deleted.\n */\n async getFile(id: string): Promise<Uint8Array | null> {\n const entry = await this.storage.getEntry(id);\n if (!entry) return null;\n return this.storage.getFile(entry.storageKey);\n }\n\n // ── Query helpers ───────────────────────────────────────────────────────────\n\n getEntry(id: string): Promise<QuarantineEntry | null> {\n return this.storage.getEntry(id);\n }\n\n listEntries(filter?: QuarantineFilter): Promise<QuarantineEntry[]> {\n return this.storage.listEntries(filter);\n }\n\n listPending(): Promise<QuarantineEntry[]> {\n return this.storage.listEntries({ status: 'pending' });\n }\n\n countEntries(filter?: QuarantineFilter): Promise<number> {\n return this.storage.countEntries(filter);\n }\n\n // ── Reporting ───────────────────────────────────────────────────────────────\n\n /**\n * Generate a structured JSON report of all quarantine entries matching the\n * filter — suitable for audit logs and dashboards.\n */\n async report(filter?: QuarantineFilter): Promise<QuarantineReport> {\n const entries = await this.storage.listEntries(filter);\n const byStatus = { pending: 0, reviewing: 0, promoted: 0, deleted: 0 };\n for (const e of entries) byStatus[e.status]++;\n return {\n generatedAt: new Date().toISOString(),\n totalEntries: entries.length,\n byStatus,\n entries,\n };\n }\n}\n\n// ── Helpers ───────────────────────────────────────────────────────────────────\n\nfunction generateId(): string {\n return crypto.randomUUID();\n}\n\nfunction computeSha256(bytes: Uint8Array): string {\n return crypto.createHash('sha256').update(bytes).digest('hex');\n}\n","/**\n * Quarantine storage adapter interface and filesystem reference implementation.\n *\n * The `QuarantineStorage` interface decouples the quarantine workflow from any\n * specific persistence layer. You can implement it for S3, GCS, a database,\n * or any other backend.\n *\n * The built-in `FilesystemQuarantineStorage` stores files and metadata as JSON\n * in a local directory — suitable for development, self-hosted, and on-premise\n * deployments where data must not leave the machine.\n *\n * @module quarantine/storage\n */\n\nimport * as fs from 'fs';\nimport * as path from 'path';\nimport * as crypto from 'crypto';\nimport type { QuarantineEntry, QuarantineFilter } from './types';\n\n// ── Adapter interface ─────────────────────────────────────────────────────────\n\n/**\n * Storage adapter for the quarantine workflow.\n * Implement this interface to support any backend (S3, GCS, DB, etc.).\n */\nexport interface QuarantineStorage {\n /**\n * Persist the raw bytes of a quarantined file.\n * Returns a `storageKey` that can later be used to retrieve or delete the bytes.\n */\n saveFile(id: string, bytes: Uint8Array): Promise<string>;\n\n /**\n * Retrieve the raw bytes of a quarantined file.\n * Returns `null` if the file is not found.\n */\n getFile(storageKey: string): Promise<Uint8Array | null>;\n\n /**\n * Permanently remove the raw bytes of a quarantined file.\n * No-op if already removed.\n */\n deleteFile(storageKey: string): Promise<void>;\n\n /** Persist a quarantine entry (metadata + scan report). */\n saveEntry(entry: QuarantineEntry): Promise<void>;\n\n /** Load a quarantine entry by id. Returns `null` if not found. */\n getEntry(id: string): Promise<QuarantineEntry | null>;\n\n /** Update an existing quarantine entry (partial update). */\n updateEntry(id: string, patch: Partial<QuarantineEntry>): Promise<QuarantineEntry>;\n\n /** List quarantine entries matching the given filter. */\n listEntries(filter?: QuarantineFilter): Promise<QuarantineEntry[]>;\n\n /** Return the total count of quarantine entries matching the filter. */\n countEntries(filter?: QuarantineFilter): Promise<number>;\n}\n\n// ── Filesystem implementation ─────────────────────────────────────────────────\n\nexport interface FilesystemQuarantineStorageOptions {\n /**\n * Root directory for quarantine storage.\n * Two subdirectories are created: `files/` (raw bytes) and `meta/` (JSON).\n */\n dir: string;\n /** Create the directory if it does not exist (default: true). */\n createIfMissing?: boolean;\n}\n\n/**\n * Reference implementation of `QuarantineStorage` backed by the local filesystem.\n *\n * File layout:\n * <dir>/files/<storageKey> — raw file bytes\n * <dir>/meta/<id>.json — QuarantineEntry JSON\n *\n * Suitable for single-process servers. For multi-process or distributed\n * deployments, implement `QuarantineStorage` against a shared backend.\n */\nexport class FilesystemQuarantineStorage implements QuarantineStorage {\n private readonly filesDir: string;\n private readonly metaDir: string;\n\n constructor(options: FilesystemQuarantineStorageOptions) {\n this.filesDir = path.join(options.dir, 'files');\n this.metaDir = path.join(options.dir, 'meta');\n if (options.createIfMissing !== false) {\n fs.mkdirSync(this.filesDir, { recursive: true });\n fs.mkdirSync(this.metaDir, { recursive: true });\n }\n }\n\n async saveFile(id: string, bytes: Uint8Array): Promise<string> {\n // Use a safe, collision-resistant filename derived from the entry id.\n const storageKey = `${id}-${crypto.randomBytes(4).toString('hex')}`;\n const filePath = path.join(this.filesDir, storageKey);\n await fs.promises.writeFile(filePath, bytes);\n return storageKey;\n }\n\n async getFile(storageKey: string): Promise<Uint8Array | null> {\n const filePath = path.join(this.filesDir, safeBasename(storageKey));\n try {\n const buf = await fs.promises.readFile(filePath);\n return new Uint8Array(buf);\n } catch {\n return null;\n }\n }\n\n async deleteFile(storageKey: string): Promise<void> {\n const filePath = path.join(this.filesDir, safeBasename(storageKey));\n await fs.promises.unlink(filePath).catch(() => {/* already gone */});\n }\n\n async saveEntry(entry: QuarantineEntry): Promise<void> {\n const metaPath = path.join(this.metaDir, `${safeBasename(entry.id)}.json`);\n await fs.promises.writeFile(metaPath, JSON.stringify(entry, null, 2), 'utf8');\n }\n\n async getEntry(id: string): Promise<QuarantineEntry | null> {\n const metaPath = path.join(this.metaDir, `${safeBasename(id)}.json`);\n try {\n const raw = await fs.promises.readFile(metaPath, 'utf8');\n return JSON.parse(raw) as QuarantineEntry;\n } catch {\n return null;\n }\n }\n\n async updateEntry(id: string, patch: Partial<QuarantineEntry>): Promise<QuarantineEntry> {\n const existing = await this.getEntry(id);\n if (!existing) throw new Error(`Quarantine entry not found: ${id}`);\n const updated: QuarantineEntry = { ...existing, ...patch };\n await this.saveEntry(updated);\n return updated;\n }\n\n async listEntries(filter?: QuarantineFilter): Promise<QuarantineEntry[]> {\n const files = await fs.promises.readdir(this.metaDir).catch(() => [] as string[]);\n const entries: QuarantineEntry[] = [];\n\n for (const file of files) {\n if (!file.endsWith('.json')) continue;\n try {\n const raw = await fs.promises.readFile(path.join(this.metaDir, file), 'utf8');\n entries.push(JSON.parse(raw) as QuarantineEntry);\n } catch {\n // Skip unreadable entries.\n }\n }\n\n return applyFilter(entries, filter);\n }\n\n async countEntries(filter?: QuarantineFilter): Promise<number> {\n const entries = await this.listEntries(filter);\n return entries.length;\n }\n}\n\n// ── Helpers ───────────────────────────────────────────────────────────────────\n\n/**\n * Strip directory separators to prevent path-traversal attacks when using\n * user-supplied or derived keys as filenames.\n */\nfunction safeBasename(key: string): string {\n return path.basename(key).replace(/[^a-zA-Z0-9._-]/g, '_');\n}\n\nfunction applyFilter(entries: QuarantineEntry[], filter?: QuarantineFilter): QuarantineEntry[] {\n if (!filter) return entries;\n\n let result = entries;\n\n if (filter.status !== undefined) {\n const statuses = Array.isArray(filter.status) ? filter.status : [filter.status];\n result = result.filter((e) => statuses.includes(e.status));\n }\n if (filter.after) {\n result = result.filter((e) => e.quarantinedAt >= filter.after!);\n }\n if (filter.before) {\n result = result.filter((e) => e.quarantinedAt <= filter.before!);\n }\n if (filter.limit !== undefined) {\n result = result.slice(0, filter.limit);\n }\n\n return result;\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