verdaccio-security-filter 1.8.0 → 1.9.1
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 +39 -7
- package/build/index.d.ts +7 -4
- package/build/index.js +161 -25
- package/build/lib/metrics.d.ts +1 -0
- package/build/lib/metrics.js +9 -0
- package/build/lib/webhook.d.ts +3 -0
- package/build/lib/webhook.js +77 -7
- package/build/types.d.ts +3 -1
- package/package.json +1 -1
package/README.md
CHANGED
|
@@ -61,7 +61,7 @@ This plugin implements **two independent security layers** for complete protecti
|
|
|
61
61
|
#### 📊 Monitoring & Observability
|
|
62
62
|
- **Enhanced Logging** - Configurable log levels (`debug`, `info`, `warn`, `error`)
|
|
63
63
|
- **Metrics Collection** - Track security events (blocks with their reason, author blocks)
|
|
64
|
-
- **Webhook Notifications** - POST block events to any HTTP endpoint or a Slack-compatible incoming webhook
|
|
64
|
+
- **Webhook Notifications** - POST block and optionally warn-only events to any HTTP endpoint or a Slack-compatible incoming webhook, signed with HMAC-SHA256 on request
|
|
65
65
|
- **Security Audit Trail** - Detailed logging of all security decisions
|
|
66
66
|
- **Customizable Output** - Log to stdout or file in JSON format
|
|
67
67
|
|
|
@@ -118,7 +118,7 @@ These wait for a concrete request:
|
|
|
118
118
|
- [x] **Registry signature verification** - `signatures`: npm registry signatures (ECDSA)
|
|
119
119
|
- [x] **Provenance attestations** - `provenance`: presence and downgrade detection
|
|
120
120
|
- [x] **Typosquatting detection** - `typosquatting`: names within a small edit distance of popular packages
|
|
121
|
-
- [x] **Webhook notifications** - `webhook`: block events as JSON or as a Slack message
|
|
121
|
+
- [x] **Webhook notifications** - `webhook`: block and warn events as JSON or as a Slack message, optional HMAC signature
|
|
122
122
|
|
|
123
123
|
#### Not planned
|
|
124
124
|
- **Rate limiting** and **multi-registry fallback** - Verdaccio already provides both (`rateLimit`, uplinks)
|
|
@@ -165,7 +165,7 @@ npm then resolves ranges against the versions that are left.
|
|
|
165
165
|
### Layer 2: Middleware (`register_middlewares`)
|
|
166
166
|
Runs first on every `GET` request:
|
|
167
167
|
1. Blocks packages by name: whitelist, patterns, scopes
|
|
168
|
-
2. Blocks tarball downloads of blocked versions, even if a client has stale metadata or a lockfile
|
|
168
|
+
2. Blocks tarball downloads of blocked versions, even if a client has stale metadata or a lockfile. This covers the versions layer 1 removed (CVE, license, signatures, provenance, age, author): `npm ci` downloads the tarballs pinned in `package-lock.json` without asking for the metadata, so for a tarball without a decision younger than 5 minutes, or one for a version published after the decision, the middleware loads the package metadata through Verdaccio's storage, which runs layer 1. Parallel requests for a package share one load, and only clients that may read the package trigger it. The cost is one metadata load per package per 5 minutes during `npm ci`, which reaches the uplink when Verdaccio's cached copy is older than the uplink's `maxage`. If the metadata cannot be loaded, the tarball is served, or refused with `errorHandling.onFilterError: fail-closed`; the load is retried after 30 seconds. Needs both layers configured.
|
|
169
169
|
3. Turns a whole-package block from layer 1 into an HTTP error that carries the reason
|
|
170
170
|
|
|
171
171
|
### What a client sees
|
|
@@ -492,7 +492,7 @@ The license check runs when `licenses.allowed` or `licenses.blocked` is not empt
|
|
|
492
492
|
|
|
493
493
|
### Webhook Options
|
|
494
494
|
|
|
495
|
-
Sends every block event to an HTTP endpoint. It does not depend on `metrics.enabled`.
|
|
495
|
+
Sends every block event, and on request every warn-only decision, to an HTTP endpoint. It does not depend on `metrics.enabled`.
|
|
496
496
|
|
|
497
497
|
| Option | Type | Default | Description |
|
|
498
498
|
|--------|------|---------|-------------|
|
|
@@ -502,6 +502,8 @@ Sends every block event to an HTTP endpoint. It does not depend on `metrics.enab
|
|
|
502
502
|
| `webhook.headers` | `object` | `{}` | Extra request headers, for example `Authorization` |
|
|
503
503
|
| `webhook.timeoutMs` | `number` | `5000` | Timeout of one delivery attempt |
|
|
504
504
|
| `webhook.repeatIntervalMinutes` | `number` | `60` | The same event is sent at most once per interval; `0` sends every occurrence |
|
|
505
|
+
| `webhook.secret` | `string` | - | Signs every request with HMAC-SHA256, see [Signature](#webhook-signature) |
|
|
506
|
+
| `webhook.events` | `('block' \| 'warn')[]` | `['block']` | `warn` adds the decisions that are only logged: warn-only modes, unsigned versions, provenance warnings, CVEs with `autoBlock` off |
|
|
505
507
|
|
|
506
508
|
```yaml
|
|
507
509
|
webhook:
|
|
@@ -524,6 +526,29 @@ webhook:
|
|
|
524
526
|
|
|
525
527
|
**Repeats.** A blocked package is requested again on every `npm install`. An event with the same package, version(s) and reason is therefore sent once per `repeatIntervalMinutes`; the metrics output still records every attempt.
|
|
526
528
|
|
|
529
|
+
**Warnings.** With `events: [block, warn]`, every decision that is only logged is sent as an event with `"event": "warn"`: `warnOnly` of age, author, typosquatting and signatures, `onMissing: warn` of signatures and provenance, `onDowngrade: warn`, and CVEs found while `autoBlock` is off. Each kind of warning about a package is logged and sent at most once per 10 minutes, shared by both layers, and then once per `repeatIntervalMinutes` by the webhook. Warnings go to the webhook only; the metrics output and its counters keep block events alone. `events: [warn]` sends warnings without blocks, for example to a separate channel.
|
|
530
|
+
|
|
531
|
+
<a id="webhook-signature"></a>**Signature.** With `secret` set (`${NAME}` works here too), every request carries two headers:
|
|
532
|
+
|
|
533
|
+
- `X-Webhook-Timestamp`: Unix time in seconds when the request was sent
|
|
534
|
+
- `X-Webhook-Signature`: `sha256=` and the hex HMAC-SHA256 of `<timestamp>.<raw body>` with the secret
|
|
535
|
+
|
|
536
|
+
Every attempt, retries included, is signed afresh. The receiver recomputes the HMAC over the raw body, compares in constant time and rejects old timestamps, so a captured request cannot be replayed later:
|
|
537
|
+
|
|
538
|
+
```js
|
|
539
|
+
const crypto = require('crypto');
|
|
540
|
+
|
|
541
|
+
function verify(rawBody, headers, secret, toleranceSeconds = 300) {
|
|
542
|
+
const timestamp = headers['x-webhook-timestamp'];
|
|
543
|
+
const received = Buffer.from(String(headers['x-webhook-signature'] || ''));
|
|
544
|
+
const expected = Buffer.from('sha256=' + crypto.createHmac('sha256', secret).update(`${timestamp}.${rawBody}`).digest('hex'));
|
|
545
|
+
const fresh = Math.abs(Date.now() / 1000 - Number(timestamp)) <= toleranceSeconds;
|
|
546
|
+
return fresh && received.length === expected.length && crypto.timingSafeEqual(received, expected);
|
|
547
|
+
}
|
|
548
|
+
```
|
|
549
|
+
|
|
550
|
+
Slack incoming webhooks ignore the headers; signing matters for your own receivers.
|
|
551
|
+
|
|
527
552
|
**With both layers configured**, put `webhook` in the `filters` and the `middlewares` block, like the rest of the configuration: name, scope and tarball blocks are reported by the middleware, removed versions by the filter.
|
|
528
553
|
|
|
529
554
|
The `json` body. Each entry of `events` has the fields described in [Metrics & Monitoring](#-metrics--monitoring):
|
|
@@ -540,6 +565,13 @@ The `json` body. Each entry of `events` has the fields described in [Metrics & M
|
|
|
540
565
|
"packageName": "evil-pkg",
|
|
541
566
|
"version": "*",
|
|
542
567
|
"reason": "Package name matches blocked pattern"
|
|
568
|
+
},
|
|
569
|
+
{
|
|
570
|
+
"timestamp": "2026-01-15T10:30:02.000Z",
|
|
571
|
+
"event": "warn",
|
|
572
|
+
"packageName": "left-pad",
|
|
573
|
+
"reason": "Missing provenance",
|
|
574
|
+
"metadata": { "versions": ["1.0.0", "1.1.0"] }
|
|
543
575
|
}
|
|
544
576
|
]
|
|
545
577
|
}
|
|
@@ -551,7 +583,7 @@ The `slack` body:
|
|
|
551
583
|
|
|
552
584
|
```json
|
|
553
585
|
{
|
|
554
|
-
"text": "*Verdaccio security filter*:
|
|
586
|
+
"text": "*Verdaccio security filter*: 3 event(s)\n• blocked `evil-pkg`: Package name matches blocked pattern\n• blocked `lodash` (2 version(s): 4.17.19, 4.17.20): Package has 2 vulnerable version(s)\n• warning `left-pad` (2 version(s): 1.0.0, 1.1.0): Missing provenance"
|
|
555
587
|
}
|
|
556
588
|
```
|
|
557
589
|
|
|
@@ -611,7 +643,7 @@ typosquatting:
|
|
|
611
643
|
|
|
612
644
|
npm signs every version: the signature covers `<name>@<version>:<integrity>`. A version whose signature does not verify is removed from the metadata, and the package is blocked when no version is left. This catches accidental or naive corruption of `integrity` in Verdaccio's cache or on the way from the registry. Someone who can rewrite metadata deliberately can also delete the signature or point it at an unknown key, which turns the version into an *unsigned* one: only `onMissing: block` stops that. A signed manifest copied under another version number fails, because the version number is part of the signed text. The check does not catch a compromised author account, because npm signs those versions honestly.
|
|
613
645
|
|
|
614
|
-
A version is *unsigned* when it has no signature, no `integrity`, or only signatures by unknown keys. Packages published straight to Verdaccio are unsigned. With the default `onMissing: warn` they are served, and one warning per package is logged at most every 10 minutes. An unknown key never blocks, so a key rotation at npm does not break installs; add the new key to `keys` to verify it. An expired key is accepted only for versions published before it expired.
|
|
646
|
+
A version is *unsigned* when it has no signature, no `integrity`, or only signatures by unknown keys. Packages published straight to Verdaccio are unsigned. With the default `onMissing: warn` they are served, and one warning per package is logged at most every 10 minutes. An unknown key never blocks, so a key rotation at npm does not break installs; add the new key to `keys` to verify it. An expired key is accepted only for versions published before it expired. A tarball of a removed version is refused like every other removed version, see [Layer 2](#layer-2-middleware-register_middlewares).
|
|
615
647
|
|
|
616
648
|
```yaml
|
|
617
649
|
signatures:
|
|
@@ -629,7 +661,7 @@ signatures:
|
|
|
629
661
|
|
|
630
662
|
A version published from CI with `npm publish --provenance` carries a [provenance attestation](https://docs.npmjs.com/generating-provenance-statements) (`dist.attestations`, SLSA predicate type). Registry signatures do not help when an author's account or token is stolen: npm signs such a version honestly. A stolen token is usually used outside the project's CI, so the new version arrives without provenance while earlier versions had it. That is a *downgrade*: a version without provenance published after the earliest version with it. With the default `onDowngrade: block` it is removed from the metadata, so npm resolves the previous version; the package is blocked only when no version is left.
|
|
631
663
|
|
|
632
|
-
Versions published before the package adopted provenance are kept. A version without a publish time counts as published last, and when any attested version has no publish time, every version without provenance counts as a downgrade. Most packages have never published with provenance, hence `onMissing: allow`; `warn` logs one warning per package at most every 10 minutes. A maintainer who once publishes by hand triggers a downgrade: in blacklist mode, add the package to `whitelist.packages` or `whitelist.patterns` to skip the check. In whitelist mode every served package is on the list, so all of them are checked; use `onDowngrade: warn` there if a skip is needed. The attestation is detected, not cryptographically verified
|
|
664
|
+
Versions published before the package adopted provenance are kept. A version without a publish time counts as published last, and when any attested version has no publish time, every version without provenance counts as a downgrade. Most packages have never published with provenance, hence `onMissing: allow`; `warn` logs one warning per package at most every 10 minutes. A maintainer who once publishes by hand triggers a downgrade: in blacklist mode, add the package to `whitelist.packages` or `whitelist.patterns` to skip the check. In whitelist mode every served package is on the list, so all of them are checked; use `onDowngrade: warn` there if a skip is needed. The attestation is detected, not cryptographically verified. A tarball of a removed version is refused, see [Layer 2](#layer-2-middleware-register_middlewares).
|
|
633
665
|
|
|
634
666
|
```yaml
|
|
635
667
|
provenance:
|
package/build/index.d.ts
CHANGED
|
@@ -17,9 +17,6 @@ export default class SecurityFilterPlugin implements IPluginMiddleware<SecurityC
|
|
|
17
17
|
private readonly typosquatChecker;
|
|
18
18
|
private readonly signatureChecker;
|
|
19
19
|
private readonly provenanceChecker;
|
|
20
|
-
private readonly unsignedWarnedAt;
|
|
21
|
-
private readonly provenanceWarnedAt;
|
|
22
|
-
private readonly typosquatWarnedAt;
|
|
23
20
|
constructor(config: SecurityConfig, options: PluginOptions<SecurityConfig>);
|
|
24
21
|
private _parseVersionRangeRules;
|
|
25
22
|
private _logInitialization;
|
|
@@ -27,13 +24,19 @@ export default class SecurityFilterPlugin implements IPluginMiddleware<SecurityC
|
|
|
27
24
|
private _isBlockedByPattern;
|
|
28
25
|
private _isScopeAllowed;
|
|
29
26
|
private _getVersionRangeRule;
|
|
30
|
-
register_middlewares(app: Application,
|
|
27
|
+
register_middlewares(app: Application, auth: IBasicAuth<SecurityConfig>, storage: IStorageManager<SecurityConfig>): void;
|
|
31
28
|
private _blockedPackage;
|
|
32
29
|
private _removeVersions;
|
|
33
30
|
private _rejectedVersions;
|
|
34
31
|
filter_metadata(packageInfo: Package): Promise<Package>;
|
|
35
32
|
private _filterMetadata;
|
|
36
33
|
private _versionBlockReason;
|
|
34
|
+
private _removedByFilter;
|
|
35
|
+
private _unchecked;
|
|
36
|
+
private _canAccess;
|
|
37
|
+
private _loadMetadataOnce;
|
|
38
|
+
private _loadMetadata;
|
|
39
|
+
private _warnDue;
|
|
37
40
|
private _checkPackageBlock;
|
|
38
41
|
private _getAppliedRules;
|
|
39
42
|
destroy(): void;
|
package/build/index.js
CHANGED
|
@@ -63,15 +63,18 @@ const lru_cache_1 = require("./lib/lru-cache");
|
|
|
63
63
|
const webhook_1 = require("./lib/webhook");
|
|
64
64
|
const PLUGIN_VERSION = JSON.parse((0, fs_1.readFileSync)((0, path_1.join)(__dirname, '..', 'package.json'), 'utf8')).version;
|
|
65
65
|
const filterBlocks = new lru_cache_1.LRUCache(1000);
|
|
66
|
+
const warnedAt = new lru_cache_1.LRUCache(10000);
|
|
66
67
|
const WARN_REPEAT_MS = 10 * 60 * 1000;
|
|
68
|
+
const TARBALL_DECISION_MS = 5 * 60 * 1000;
|
|
69
|
+
const RETRY_LOAD_MS = 30 * 1000;
|
|
70
|
+
const tarballDecisions = new lru_cache_1.LRUCache(5000);
|
|
71
|
+
const metadataLoads = new Map();
|
|
72
|
+
const loadAttempts = new lru_cache_1.LRUCache(10000);
|
|
67
73
|
function forbiddenBody(packageName, reason, extra = {}) {
|
|
68
74
|
return Object.assign(Object.assign({ error: `Package blocked by security filter: ${reason}`, package: packageName, reason }, extra), { timestamp: new Date().toISOString() });
|
|
69
75
|
}
|
|
70
76
|
class SecurityFilterPlugin {
|
|
71
77
|
constructor(config, options) {
|
|
72
|
-
this.unsignedWarnedAt = new lru_cache_1.LRUCache(5000);
|
|
73
|
-
this.provenanceWarnedAt = new lru_cache_1.LRUCache(5000);
|
|
74
|
-
this.typosquatWarnedAt = new lru_cache_1.LRUCache(5000);
|
|
75
78
|
this.config = config || {};
|
|
76
79
|
if (!this.config.errorHandling) {
|
|
77
80
|
this.config.errorHandling = {
|
|
@@ -225,7 +228,7 @@ class SecurityFilterPlugin {
|
|
|
225
228
|
}
|
|
226
229
|
}) || null;
|
|
227
230
|
}
|
|
228
|
-
register_middlewares(app,
|
|
231
|
+
register_middlewares(app, auth, storage) {
|
|
229
232
|
this.logger.info('[Middleware] Registering security filter middleware');
|
|
230
233
|
this.logger.info(`[Middleware] Config mode: ${this.config.mode || 'NOT SET'}`);
|
|
231
234
|
app.use((req, res, next) => __awaiter(this, void 0, void 0, function* () {
|
|
@@ -264,6 +267,15 @@ class SecurityFilterPlugin {
|
|
|
264
267
|
res.status(403).json(forbiddenBody(packageName, blockResult.reason, { version: version || 'all versions' }));
|
|
265
268
|
return;
|
|
266
269
|
}
|
|
270
|
+
const removedReason = version && !this.config.dryRun
|
|
271
|
+
? yield this._removedByFilter(packageName, version, storage, auth, req)
|
|
272
|
+
: null;
|
|
273
|
+
if (removedReason) {
|
|
274
|
+
this.logger.warn(`[Middleware] [X] BLOCKED TARBALL: ${packageName}@${version} - ${removedReason}`);
|
|
275
|
+
this.metrics.recordBlock(packageName, version, removedReason);
|
|
276
|
+
res.status(403).json(forbiddenBody(packageName, removedReason, { version }));
|
|
277
|
+
return;
|
|
278
|
+
}
|
|
267
279
|
this.logger.debug(`[Middleware] [OK] ALLOWED TARBALL: ${packageName}@${version || 'unknown'}`);
|
|
268
280
|
}
|
|
269
281
|
else {
|
|
@@ -358,10 +370,21 @@ class SecurityFilterPlugin {
|
|
|
358
370
|
return __awaiter(this, void 0, void 0, function* () {
|
|
359
371
|
const filtered = yield this._filterMetadata(packageInfo);
|
|
360
372
|
if (!this.config.dryRun) {
|
|
373
|
+
const left = filtered.versions || {};
|
|
374
|
+
const seen = Object.keys(packageInfo.versions || {});
|
|
375
|
+
tarballDecisions.set(packageInfo.name, {
|
|
376
|
+
seen: new Set(seen),
|
|
377
|
+
removed: new Set(seen.filter(version => !(version in left))),
|
|
378
|
+
filtered: true,
|
|
379
|
+
at: Date.now(),
|
|
380
|
+
});
|
|
361
381
|
const security = filtered.security;
|
|
362
382
|
if (security === null || security === void 0 ? void 0 : security.blocked) {
|
|
363
383
|
filterBlocks.set(packageInfo.name, { security, at: Date.now() });
|
|
364
384
|
}
|
|
385
|
+
else {
|
|
386
|
+
filterBlocks.delete(packageInfo.name);
|
|
387
|
+
}
|
|
365
388
|
return filtered;
|
|
366
389
|
}
|
|
367
390
|
if (filtered === packageInfo) {
|
|
@@ -375,7 +398,7 @@ class SecurityFilterPlugin {
|
|
|
375
398
|
}
|
|
376
399
|
_filterMetadata(packageInfo) {
|
|
377
400
|
return __awaiter(this, void 0, void 0, function* () {
|
|
378
|
-
var _a, _b, _c, _d, _e
|
|
401
|
+
var _a, _b, _c, _d, _e;
|
|
379
402
|
let pkg = packageInfo;
|
|
380
403
|
const packageName = pkg.name;
|
|
381
404
|
this.logger.debug(`[filter_metadata] --> Processing: ${packageName}`);
|
|
@@ -411,8 +434,9 @@ class SecurityFilterPlugin {
|
|
|
411
434
|
return this._blockedPackage(pkg, reason);
|
|
412
435
|
}
|
|
413
436
|
}
|
|
414
|
-
if (vulnerableVersions.length > 0 && !this.config.cveCheck.autoBlock) {
|
|
437
|
+
if (vulnerableVersions.length > 0 && !this.config.cveCheck.autoBlock && this._warnDue('cve', packageName)) {
|
|
415
438
|
this.logger.warn(`[filter_metadata] CVE found in ${packageName}: ${vulnerableVersions.length} vulnerable version(s), autoBlock is off`);
|
|
439
|
+
this.metrics.recordWarning(packageName, `Package has ${vulnerableVersions.length} vulnerable version(s)`, vulnerableVersions);
|
|
416
440
|
}
|
|
417
441
|
if (this.config.cveCheck.autoBlock && vulnerableVersions.length > 0) {
|
|
418
442
|
const reason = `Package has ${vulnerableVersions.length} vulnerable version(s)`;
|
|
@@ -448,15 +472,14 @@ class SecurityFilterPlugin {
|
|
|
448
472
|
});
|
|
449
473
|
const versionsWith = (match) => statuses.filter(([, r]) => match(r)).map(([v]) => v);
|
|
450
474
|
const unsigned = versionsWith(r => r.status === 'missing');
|
|
451
|
-
|
|
452
|
-
if (unsigned.length > 0 && this.signatureChecker.onMissing === 'warn'
|
|
453
|
-
&& now - ((_c = this.unsignedWarnedAt.get(packageName)) !== null && _c !== void 0 ? _c : -Infinity) >= WARN_REPEAT_MS) {
|
|
454
|
-
this.unsignedWarnedAt.set(packageName, now);
|
|
475
|
+
if (unsigned.length > 0 && this.signatureChecker.onMissing === 'warn' && this._warnDue('unsigned', packageName)) {
|
|
455
476
|
this.logger.warn(`[filter_metadata] SIGNATURE WARNING: ${packageName}: ${unsigned.length} unsigned version(s)`);
|
|
477
|
+
this.metrics.recordWarning(packageName, 'Missing registry signature', unsigned);
|
|
456
478
|
}
|
|
457
479
|
const tolerated = versionsWith(r => r.status === 'invalid' && r.allowed);
|
|
458
|
-
if (tolerated.length > 0) {
|
|
480
|
+
if (tolerated.length > 0 && this._warnDue('invalid-signature', packageName)) {
|
|
459
481
|
this.logger.warn(`[filter_metadata] SIGNATURE WARNING: ${packageName}: invalid signature on ${tolerated.join(', ')} (warn-only mode)`);
|
|
482
|
+
this.metrics.recordWarning(packageName, 'Invalid registry signature', tolerated);
|
|
460
483
|
}
|
|
461
484
|
const invalid = versionsWith(r => !r.allowed && r.status === 'invalid');
|
|
462
485
|
const missing = versionsWith(r => !r.allowed && r.status === 'missing');
|
|
@@ -480,10 +503,9 @@ class SecurityFilterPlugin {
|
|
|
480
503
|
const remaining = new Set(Object.keys(pkg.versions || {}));
|
|
481
504
|
const results = this.provenanceChecker.check(packageInfo).filter(r => remaining.has(r.version));
|
|
482
505
|
const warned = results.filter(r => r.warn);
|
|
483
|
-
|
|
484
|
-
if (warned.length > 0 && now - ((_d = this.provenanceWarnedAt.get(packageName)) !== null && _d !== void 0 ? _d : -Infinity) >= WARN_REPEAT_MS) {
|
|
485
|
-
this.provenanceWarnedAt.set(packageName, now);
|
|
506
|
+
if (warned.length > 0 && this._warnDue('provenance', packageName)) {
|
|
486
507
|
this.logger.warn(`[filter_metadata] PROVENANCE WARNING: ${packageName}: ${warned.length} version(s) - ${warned[0].reason}`);
|
|
508
|
+
this.metrics.recordWarning(packageName, warned[0].reason || 'Provenance check failed', warned.map(r => r.version));
|
|
487
509
|
}
|
|
488
510
|
const rejected = results.filter(r => !r.allowed);
|
|
489
511
|
if (results.length > 0 && rejected.length === results.length) {
|
|
@@ -504,7 +526,7 @@ class SecurityFilterPlugin {
|
|
|
504
526
|
}
|
|
505
527
|
pkg = this._removeVersions(pkg, rejected.map(r => r.version));
|
|
506
528
|
}
|
|
507
|
-
if ((
|
|
529
|
+
if ((_c = this.config.packageAge) === null || _c === void 0 ? void 0 : _c.enabled) {
|
|
508
530
|
const ageResult = this.packageAgeChecker.checkPackageAge(pkg);
|
|
509
531
|
if (!ageResult.allowed && !ageResult.warnOnly) {
|
|
510
532
|
const reason = ageResult.reason || 'Package too new';
|
|
@@ -512,19 +534,27 @@ class SecurityFilterPlugin {
|
|
|
512
534
|
this.metrics.recordBlock(packageName, '*', reason);
|
|
513
535
|
return this._blockedPackage(pkg, reason, { ageDays: ageResult.ageDays });
|
|
514
536
|
}
|
|
515
|
-
else if (
|
|
537
|
+
else if (ageResult.warnOnly && this._warnDue('age', packageName)) {
|
|
516
538
|
this.logger.warn(`[filter_metadata] AGE WARNING: ${packageName} - ${ageResult.reason} (warn-only mode)`);
|
|
539
|
+
this.metrics.recordWarning(packageName, ageResult.reason || 'Package too new');
|
|
517
540
|
}
|
|
518
541
|
if (this.config.packageAge.minVersionAgeDays) {
|
|
519
542
|
const removedVersions = [];
|
|
543
|
+
const warnedVersions = [];
|
|
520
544
|
for (const version of Object.keys(pkg.versions || {})) {
|
|
521
545
|
const versionAgeResult = this.packageAgeChecker.checkVersionAge(pkg, version);
|
|
522
546
|
if (!versionAgeResult.allowed && !versionAgeResult.warnOnly) {
|
|
523
547
|
removedVersions.push(version);
|
|
524
548
|
}
|
|
525
|
-
else if (
|
|
526
|
-
|
|
549
|
+
else if (versionAgeResult.warnOnly) {
|
|
550
|
+
warnedVersions.push([version, versionAgeResult.reason]);
|
|
551
|
+
}
|
|
552
|
+
}
|
|
553
|
+
if (warnedVersions.length > 0 && this._warnDue('version-age', packageName)) {
|
|
554
|
+
for (const [version, reason] of warnedVersions) {
|
|
555
|
+
this.logger.warn(`[filter_metadata] VERSION AGE WARNING: ${packageName}@${version} - ${reason} (warn-only mode)`);
|
|
527
556
|
}
|
|
557
|
+
this.metrics.recordWarning(packageName, 'Version too new', warnedVersions.map(([version]) => version));
|
|
528
558
|
}
|
|
529
559
|
if (removedVersions.length > 0) {
|
|
530
560
|
this.logger.warn(`[filter_metadata] VERSION AGE FILTERED: ${packageName}: ${removedVersions.join(', ')}`);
|
|
@@ -533,10 +563,11 @@ class SecurityFilterPlugin {
|
|
|
533
563
|
}
|
|
534
564
|
}
|
|
535
565
|
}
|
|
536
|
-
if ((
|
|
566
|
+
if ((_d = this.config.authorFilter) === null || _d === void 0 ? void 0 : _d.enabled) {
|
|
537
567
|
const rejected = this._rejectedVersions(pkg, data => this.authorChecker.checkAuthor(data));
|
|
538
|
-
if (rejected.versions.length > 0 && this.config.authorFilter.warnOnly) {
|
|
568
|
+
if (rejected.versions.length > 0 && this.config.authorFilter.warnOnly && this._warnDue('author', packageName)) {
|
|
539
569
|
this.logger.warn(`[filter_metadata] AUTHOR WARNING: ${packageName}: ${rejected.versions.join(', ')} - ${rejected.first.reason} (warn-only mode)`);
|
|
570
|
+
this.metrics.recordWarning(packageName, rejected.first.reason || 'Author not allowed', rejected.versions);
|
|
540
571
|
}
|
|
541
572
|
else if (rejected.versions.length > 0) {
|
|
542
573
|
const reason = rejected.first.reason || 'Author not allowed';
|
|
@@ -563,7 +594,7 @@ class SecurityFilterPlugin {
|
|
|
563
594
|
}
|
|
564
595
|
catch (error) {
|
|
565
596
|
this.logger.error(`[filter_metadata] Error processing ${packageName}: ${error.message}`);
|
|
566
|
-
const errorStrategy = ((
|
|
597
|
+
const errorStrategy = ((_e = this.config.errorHandling) === null || _e === void 0 ? void 0 : _e.onFilterError) || 'fail-open';
|
|
567
598
|
if (errorStrategy === 'fail-closed') {
|
|
568
599
|
this.logger.warn(`[filter_metadata] Error handling: fail-closed - BLOCKING ${packageName}`);
|
|
569
600
|
this.metrics.recordBlock(packageName, '*', `Error during processing: ${error.message}`);
|
|
@@ -581,9 +612,112 @@ class SecurityFilterPlugin {
|
|
|
581
612
|
const rangeRule = this._getVersionRangeRule(packageName, version);
|
|
582
613
|
return rangeRule ? `Version matches blocked range: ${rangeRule.range}` : null;
|
|
583
614
|
}
|
|
584
|
-
|
|
615
|
+
_removedByFilter(packageName, version, storage, auth, req) {
|
|
616
|
+
return __awaiter(this, void 0, void 0, function* () {
|
|
617
|
+
var _a, _b;
|
|
618
|
+
const isFresh = (d) => !!d && Date.now() - d.at < TARBALL_DECISION_MS;
|
|
619
|
+
let decision = tarballDecisions.get(packageName);
|
|
620
|
+
if (!isFresh(decision) || (decision.filtered && !decision.seen.has(version))) {
|
|
621
|
+
const attemptKey = isFresh(decision) ? `${packageName}@${version}` : packageName;
|
|
622
|
+
const attempt = loadAttempts.get(attemptKey);
|
|
623
|
+
if (attempt && Date.now() - attempt.at < RETRY_LOAD_MS) {
|
|
624
|
+
if (attempt.failed) {
|
|
625
|
+
return this._unchecked();
|
|
626
|
+
}
|
|
627
|
+
}
|
|
628
|
+
else {
|
|
629
|
+
if (!(yield this._canAccess(packageName, version, auth, req))) {
|
|
630
|
+
return null;
|
|
631
|
+
}
|
|
632
|
+
try {
|
|
633
|
+
yield this._loadMetadataOnce(packageName, storage, req);
|
|
634
|
+
loadAttempts.set(attemptKey, { at: Date.now(), failed: false });
|
|
635
|
+
}
|
|
636
|
+
catch (error) {
|
|
637
|
+
loadAttempts.set(attemptKey, { at: Date.now(), failed: true });
|
|
638
|
+
if (this._warnDue('tarball-check', packageName)) {
|
|
639
|
+
const message = error instanceof Error ? error.message : String(error);
|
|
640
|
+
this.logger.warn(`[Middleware] Cannot check removed versions of ${packageName}: ${message}`);
|
|
641
|
+
}
|
|
642
|
+
return this._unchecked();
|
|
643
|
+
}
|
|
644
|
+
}
|
|
645
|
+
decision = tarballDecisions.get(packageName);
|
|
646
|
+
if (!isFresh(decision)) {
|
|
647
|
+
tarballDecisions.set(packageName, { seen: new Set(), removed: new Set(), filtered: false, at: Date.now() });
|
|
648
|
+
return null;
|
|
649
|
+
}
|
|
650
|
+
}
|
|
651
|
+
if (!decision.removed.has(version)) {
|
|
652
|
+
return null;
|
|
653
|
+
}
|
|
654
|
+
return ((_b = (_a = filterBlocks.get(packageName)) === null || _a === void 0 ? void 0 : _a.security) === null || _b === void 0 ? void 0 : _b.reason) || `Version ${version} was removed by the security filter`;
|
|
655
|
+
});
|
|
656
|
+
}
|
|
657
|
+
_unchecked() {
|
|
658
|
+
var _a;
|
|
659
|
+
return ((_a = this.config.errorHandling) === null || _a === void 0 ? void 0 : _a.onFilterError) === 'fail-closed'
|
|
660
|
+
? 'Package metadata could not be checked (fail-closed mode)'
|
|
661
|
+
: null;
|
|
662
|
+
}
|
|
663
|
+
_canAccess(packageName, version, auth, req) {
|
|
664
|
+
const allowAccess = auth === null || auth === void 0 ? void 0 : auth.allow_access;
|
|
665
|
+
if (typeof allowAccess !== 'function') {
|
|
666
|
+
return Promise.resolve(true);
|
|
667
|
+
}
|
|
668
|
+
return new Promise(resolve => {
|
|
669
|
+
allowAccess.call(auth, { packageName, packageVersion: version }, req.remote_user, (error, allowed) => resolve(!error && !!allowed));
|
|
670
|
+
});
|
|
671
|
+
}
|
|
672
|
+
_loadMetadataOnce(packageName, storage, req) {
|
|
673
|
+
let load = metadataLoads.get(packageName);
|
|
674
|
+
if (!load) {
|
|
675
|
+
load = this._loadMetadata(packageName, storage, req).finally(() => metadataLoads.delete(packageName));
|
|
676
|
+
metadataLoads.set(packageName, load);
|
|
677
|
+
}
|
|
678
|
+
return load;
|
|
679
|
+
}
|
|
680
|
+
_loadMetadata(packageName, storage, req) {
|
|
585
681
|
return __awaiter(this, void 0, void 0, function* () {
|
|
586
682
|
var _a;
|
|
683
|
+
const store = storage;
|
|
684
|
+
if (typeof (store === null || store === void 0 ? void 0 : store.getPackageByOptions) === 'function') {
|
|
685
|
+
yield store.getPackageByOptions({
|
|
686
|
+
name: packageName,
|
|
687
|
+
uplinksLook: true,
|
|
688
|
+
requestOptions: {
|
|
689
|
+
host: req.host,
|
|
690
|
+
protocol: req.protocol,
|
|
691
|
+
headers: req.headers,
|
|
692
|
+
remoteAddress: (_a = req.socket) === null || _a === void 0 ? void 0 : _a.remoteAddress,
|
|
693
|
+
},
|
|
694
|
+
});
|
|
695
|
+
}
|
|
696
|
+
else if (typeof (store === null || store === void 0 ? void 0 : store.getPackage) === 'function') {
|
|
697
|
+
const getPackage = store.getPackage.bind(store);
|
|
698
|
+
yield new Promise((resolve, reject) => {
|
|
699
|
+
getPackage({
|
|
700
|
+
name: packageName,
|
|
701
|
+
uplinksLook: true,
|
|
702
|
+
req,
|
|
703
|
+
callback: (error) => (error ? reject(error) : resolve()),
|
|
704
|
+
});
|
|
705
|
+
});
|
|
706
|
+
}
|
|
707
|
+
});
|
|
708
|
+
}
|
|
709
|
+
_warnDue(kind, packageName) {
|
|
710
|
+
var _a;
|
|
711
|
+
const key = `${kind}|${packageName}`;
|
|
712
|
+
const now = Date.now();
|
|
713
|
+
if (now - ((_a = warnedAt.get(key)) !== null && _a !== void 0 ? _a : -Infinity) < WARN_REPEAT_MS) {
|
|
714
|
+
return false;
|
|
715
|
+
}
|
|
716
|
+
warnedAt.set(key, now);
|
|
717
|
+
return true;
|
|
718
|
+
}
|
|
719
|
+
_checkPackageBlock(packageName, version) {
|
|
720
|
+
return __awaiter(this, void 0, void 0, function* () {
|
|
587
721
|
const whitelistMode = this.config.mode === 'whitelist';
|
|
588
722
|
if (whitelistMode) {
|
|
589
723
|
const whitelistCheck = this.whitelistChecker.isWhitelisted(packageName, version);
|
|
@@ -599,10 +733,9 @@ class SecurityFilterPlugin {
|
|
|
599
733
|
}
|
|
600
734
|
const typosquat = whitelistMode ? { allowed: true } : this.typosquatChecker.check(packageName);
|
|
601
735
|
if (typosquat.warnOnly && typosquat.reason) {
|
|
602
|
-
|
|
603
|
-
if (now - ((_a = this.typosquatWarnedAt.get(packageName)) !== null && _a !== void 0 ? _a : -Infinity) >= WARN_REPEAT_MS) {
|
|
604
|
-
this.typosquatWarnedAt.set(packageName, now);
|
|
736
|
+
if (this._warnDue('typosquat', packageName)) {
|
|
605
737
|
this.logger.warn(`TYPOSQUAT WARNING: ${packageName} - ${typosquat.reason} (warn-only mode)`);
|
|
738
|
+
this.metrics.recordWarning(packageName, typosquat.reason || 'Possible typosquat');
|
|
606
739
|
}
|
|
607
740
|
}
|
|
608
741
|
else if (!typosquat.allowed) {
|
|
@@ -652,6 +785,9 @@ class SecurityFilterPlugin {
|
|
|
652
785
|
return rules;
|
|
653
786
|
}
|
|
654
787
|
destroy() {
|
|
788
|
+
warnedAt.clear();
|
|
789
|
+
tarballDecisions.clear();
|
|
790
|
+
loadAttempts.clear();
|
|
655
791
|
this.logger.info('[Cleanup] Shutting down security filter plugin');
|
|
656
792
|
try {
|
|
657
793
|
this.cveChecker.destroy();
|
package/build/lib/metrics.d.ts
CHANGED
|
@@ -18,6 +18,7 @@ export declare class MetricsCollector {
|
|
|
18
18
|
record(event: MetricsData): void;
|
|
19
19
|
recordBlock(packageName: string, version: string, reason: string, metadata?: Record<string, any>): void;
|
|
20
20
|
recordFiltered(packageName: string, versions: string[], reason: string, event?: MetricsData['event'], metadata?: Record<string, any>): void;
|
|
21
|
+
recordWarning(packageName: string, reason: string, versions?: string[]): void;
|
|
21
22
|
flush(): void;
|
|
22
23
|
private writeToFile;
|
|
23
24
|
getSummary(): Record<string, number>;
|
package/build/lib/metrics.js
CHANGED
|
@@ -105,6 +105,15 @@ class MetricsCollector {
|
|
|
105
105
|
metadata: Object.assign(Object.assign({}, metadata), { versions }),
|
|
106
106
|
});
|
|
107
107
|
}
|
|
108
|
+
recordWarning(packageName, reason, versions) {
|
|
109
|
+
var _a;
|
|
110
|
+
if (!((_a = this.webhook) === null || _a === void 0 ? void 0 : _a.enabled)) {
|
|
111
|
+
return;
|
|
112
|
+
}
|
|
113
|
+
const event = Object.assign({ timestamp: new Date().toISOString(), event: 'warn', packageName,
|
|
114
|
+
reason }, (versions && versions.length > 0 ? { metadata: { versions } } : { version: '*' }));
|
|
115
|
+
this.webhook.notify(this.dryRun ? Object.assign(Object.assign({}, event), { dryRun: true }) : event);
|
|
116
|
+
}
|
|
108
117
|
flush() {
|
|
109
118
|
if (this.metricsBuffer.length === 0) {
|
|
110
119
|
return;
|
package/build/lib/webhook.d.ts
CHANGED
|
@@ -11,6 +11,8 @@ export declare class WebhookNotifier {
|
|
|
11
11
|
private readonly headers;
|
|
12
12
|
private readonly timeoutMs;
|
|
13
13
|
private readonly repeatMs;
|
|
14
|
+
private readonly secret;
|
|
15
|
+
private readonly events;
|
|
14
16
|
private readonly recent;
|
|
15
17
|
private queue;
|
|
16
18
|
private dropped;
|
|
@@ -23,5 +25,6 @@ export declare class WebhookNotifier {
|
|
|
23
25
|
flush(): Promise<void>;
|
|
24
26
|
cleanup(): void;
|
|
25
27
|
private drain;
|
|
28
|
+
private signatureHeaders;
|
|
26
29
|
private deliver;
|
|
27
30
|
}
|
package/build/lib/webhook.js
CHANGED
|
@@ -1,4 +1,37 @@
|
|
|
1
1
|
"use strict";
|
|
2
|
+
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
|
|
3
|
+
if (k2 === undefined) k2 = k;
|
|
4
|
+
var desc = Object.getOwnPropertyDescriptor(m, k);
|
|
5
|
+
if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
|
|
6
|
+
desc = { enumerable: true, get: function() { return m[k]; } };
|
|
7
|
+
}
|
|
8
|
+
Object.defineProperty(o, k2, desc);
|
|
9
|
+
}) : (function(o, m, k, k2) {
|
|
10
|
+
if (k2 === undefined) k2 = k;
|
|
11
|
+
o[k2] = m[k];
|
|
12
|
+
}));
|
|
13
|
+
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
|
|
14
|
+
Object.defineProperty(o, "default", { enumerable: true, value: v });
|
|
15
|
+
}) : function(o, v) {
|
|
16
|
+
o["default"] = v;
|
|
17
|
+
});
|
|
18
|
+
var __importStar = (this && this.__importStar) || (function () {
|
|
19
|
+
var ownKeys = function(o) {
|
|
20
|
+
ownKeys = Object.getOwnPropertyNames || function (o) {
|
|
21
|
+
var ar = [];
|
|
22
|
+
for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
|
|
23
|
+
return ar;
|
|
24
|
+
};
|
|
25
|
+
return ownKeys(o);
|
|
26
|
+
};
|
|
27
|
+
return function (mod) {
|
|
28
|
+
if (mod && mod.__esModule) return mod;
|
|
29
|
+
var result = {};
|
|
30
|
+
if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
|
|
31
|
+
__setModuleDefault(result, mod);
|
|
32
|
+
return result;
|
|
33
|
+
};
|
|
34
|
+
})();
|
|
2
35
|
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
|
|
3
36
|
function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
|
|
4
37
|
return new (P || (P = Promise))(function (resolve, reject) {
|
|
@@ -12,6 +45,7 @@ Object.defineProperty(exports, "__esModule", { value: true });
|
|
|
12
45
|
exports.WebhookNotifier = void 0;
|
|
13
46
|
exports.expandEnv = expandEnv;
|
|
14
47
|
exports.formatSlackText = formatSlackText;
|
|
48
|
+
const crypto = __importStar(require("crypto"));
|
|
15
49
|
const lru_cache_1 = require("./lru-cache");
|
|
16
50
|
const BATCH_DELAY_MS = 5000;
|
|
17
51
|
const MAX_BATCH_SIZE = 50;
|
|
@@ -48,7 +82,9 @@ function describeTarget(event) {
|
|
|
48
82
|
}
|
|
49
83
|
function formatSlackText(events, dropped = 0) {
|
|
50
84
|
const lines = events.slice(0, SLACK_MAX_LINES).map(event => {
|
|
51
|
-
const action = event.
|
|
85
|
+
const action = event.event === 'warn'
|
|
86
|
+
? (event.dryRun ? '[DRY RUN] warning' : 'warning')
|
|
87
|
+
: (event.dryRun ? '[DRY RUN] would block' : 'blocked');
|
|
52
88
|
return `• ${action} ${describeTarget(event)}: ${escapeSlack(event.reason)}`;
|
|
53
89
|
});
|
|
54
90
|
if (events.length > SLACK_MAX_LINES) {
|
|
@@ -67,7 +103,12 @@ class WebhookNotifier {
|
|
|
67
103
|
this.url = null;
|
|
68
104
|
this.host = '';
|
|
69
105
|
this.headers = {};
|
|
70
|
-
this.
|
|
106
|
+
this.secret = null;
|
|
107
|
+
this.events = new Set(['block']);
|
|
108
|
+
this.recent = {
|
|
109
|
+
block: new lru_cache_1.LRUCache(5000),
|
|
110
|
+
warn: new lru_cache_1.LRUCache(5000),
|
|
111
|
+
};
|
|
71
112
|
this.queue = [];
|
|
72
113
|
this.dropped = 0;
|
|
73
114
|
this.timer = null;
|
|
@@ -81,6 +122,20 @@ class WebhookNotifier {
|
|
|
81
122
|
if (config.format && config.format !== 'json' && config.format !== 'slack') {
|
|
82
123
|
this.log.warn(`Unknown webhook format "${config.format}", using "json"`);
|
|
83
124
|
}
|
|
125
|
+
if (config.events !== undefined) {
|
|
126
|
+
this.events.clear();
|
|
127
|
+
for (const kind of [].concat(config.events)) {
|
|
128
|
+
if (kind === 'block' || kind === 'warn') {
|
|
129
|
+
this.events.add(kind);
|
|
130
|
+
}
|
|
131
|
+
else {
|
|
132
|
+
this.log.warn(`Unknown webhook event "${String(kind)}" ignored; use "block" or "warn"`);
|
|
133
|
+
}
|
|
134
|
+
}
|
|
135
|
+
if (this.events.size === 0) {
|
|
136
|
+
this.log.warn('webhook.events selects no events; nothing will be sent');
|
|
137
|
+
}
|
|
138
|
+
}
|
|
84
139
|
try {
|
|
85
140
|
if (!config.url) {
|
|
86
141
|
throw new Error('webhook.url is not set');
|
|
@@ -96,6 +151,11 @@ class WebhookNotifier {
|
|
|
96
151
|
for (const [name, value] of Object.entries(config.headers || {})) {
|
|
97
152
|
this.headers[name] = expandEnv(String(value), env);
|
|
98
153
|
}
|
|
154
|
+
if ('secret' in config && !config.secret) {
|
|
155
|
+
throw new Error('webhook.secret is empty');
|
|
156
|
+
}
|
|
157
|
+
const secret = config.secret ? expandEnv(String(config.secret), env) : null;
|
|
158
|
+
this.secret = secret;
|
|
99
159
|
this.url = url.toString();
|
|
100
160
|
this.host = url.host;
|
|
101
161
|
}
|
|
@@ -111,16 +171,18 @@ class WebhookNotifier {
|
|
|
111
171
|
}
|
|
112
172
|
notify(event) {
|
|
113
173
|
var _a, _b, _c;
|
|
114
|
-
|
|
174
|
+
const kind = event.event === 'warn' ? 'warn' : 'block';
|
|
175
|
+
if (!this.enabled || !this.events.has(kind)) {
|
|
115
176
|
return;
|
|
116
177
|
}
|
|
117
178
|
const versions = (_a = event.version) !== null && _a !== void 0 ? _a : (Array.isArray((_b = event.metadata) === null || _b === void 0 ? void 0 : _b.versions) ? event.metadata.versions.join(',') : '');
|
|
118
179
|
const key = `${event.event}|${event.packageName}|${versions}|${event.reason}|${event.dryRun ? 'dry' : ''}`;
|
|
119
180
|
const now = Date.now();
|
|
120
|
-
|
|
181
|
+
const recent = this.recent[kind];
|
|
182
|
+
if (this.repeatMs > 0 && now - ((_c = recent.get(key)) !== null && _c !== void 0 ? _c : -Infinity) < this.repeatMs) {
|
|
121
183
|
return;
|
|
122
184
|
}
|
|
123
|
-
|
|
185
|
+
recent.set(key, now);
|
|
124
186
|
if (this.queue.length >= MAX_QUEUE_SIZE) {
|
|
125
187
|
this.queue.shift();
|
|
126
188
|
this.dropped++;
|
|
@@ -159,13 +221,21 @@ class WebhookNotifier {
|
|
|
159
221
|
yield this.deliver(batch.map(item => item.event), dropped);
|
|
160
222
|
}
|
|
161
223
|
catch (error) {
|
|
162
|
-
batch.forEach(item => this.recent.delete(item.key));
|
|
224
|
+
batch.forEach(item => this.recent[item.event.event === 'warn' ? 'warn' : 'block'].delete(item.key));
|
|
163
225
|
const message = error instanceof Error ? error.message : String(error);
|
|
164
226
|
this.log.warn(`Webhook delivery to ${this.host} failed, ${batch.length} event(s) dropped: ${message}`);
|
|
165
227
|
}
|
|
166
228
|
}
|
|
167
229
|
});
|
|
168
230
|
}
|
|
231
|
+
signatureHeaders(body) {
|
|
232
|
+
if (!this.secret) {
|
|
233
|
+
return {};
|
|
234
|
+
}
|
|
235
|
+
const timestamp = String(Math.floor(Date.now() / 1000));
|
|
236
|
+
const signature = crypto.createHmac('sha256', this.secret).update(`${timestamp}.${body}`).digest('hex');
|
|
237
|
+
return { 'X-Webhook-Timestamp': timestamp, 'X-Webhook-Signature': `sha256=${signature}` };
|
|
238
|
+
}
|
|
169
239
|
deliver(events, dropped) {
|
|
170
240
|
return __awaiter(this, void 0, void 0, function* () {
|
|
171
241
|
var _a;
|
|
@@ -177,7 +247,7 @@ class WebhookNotifier {
|
|
|
177
247
|
try {
|
|
178
248
|
const response = yield fetch(this.url, {
|
|
179
249
|
method: 'POST',
|
|
180
|
-
headers: Object.assign({ 'Content-Type': 'application/json', 'User-Agent': `verdaccio-security-filter/${this.pluginVersion}` }, this.headers),
|
|
250
|
+
headers: Object.assign(Object.assign({ 'Content-Type': 'application/json', 'User-Agent': `verdaccio-security-filter/${this.pluginVersion}` }, this.headers), this.signatureHeaders(body)),
|
|
181
251
|
body,
|
|
182
252
|
signal: AbortSignal.timeout(this.timeoutMs),
|
|
183
253
|
});
|
package/build/types.d.ts
CHANGED
|
@@ -41,6 +41,8 @@ export interface WebhookConfig {
|
|
|
41
41
|
headers?: Record<string, string>;
|
|
42
42
|
timeoutMs?: number;
|
|
43
43
|
repeatIntervalMinutes?: number;
|
|
44
|
+
secret?: string;
|
|
45
|
+
events?: ('block' | 'warn')[];
|
|
44
46
|
}
|
|
45
47
|
export interface ProvenanceConfig {
|
|
46
48
|
enabled: boolean;
|
|
@@ -132,7 +134,7 @@ export interface CVECheckResult {
|
|
|
132
134
|
}
|
|
133
135
|
export interface MetricsData {
|
|
134
136
|
timestamp: string;
|
|
135
|
-
event: 'block' | 'author_blocked';
|
|
137
|
+
event: 'block' | 'author_blocked' | 'warn';
|
|
136
138
|
packageName: string;
|
|
137
139
|
version?: string;
|
|
138
140
|
reason: string;
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "verdaccio-security-filter",
|
|
3
|
-
"version": "1.
|
|
3
|
+
"version": "1.9.1",
|
|
4
4
|
"description": "Verdaccio security plugin: block vulnerable (CVE/OSV), malicious and newly published npm packages in your private registry to stop supply chain attacks",
|
|
5
5
|
"main": "build/index.js",
|
|
6
6
|
"types": "build/index.d.ts",
|