verdaccio-security-filter 1.9.0 → 1.10.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 CHANGED
@@ -130,7 +130,7 @@ These wait for a concrete request:
130
130
  ### Prerequisites
131
131
 
132
132
  - Node.js >= 22.0.0
133
- - Verdaccio >= 5.0.0; 7.x recommended. Verdaccio 6 depends on a `minimatch` version with a known denial-of-service issue ([GHSA-g3hv-75wg-m249](https://github.com/advisories/GHSA-g3hv-75wg-m249)), fixed in Verdaccio 7.
133
+ - Verdaccio >= 5.0.0; 7.x or 6.11.4+ recommended. Verdaccio 6 releases before 6.11.4 depend on a `minimatch` version with known denial-of-service issues ([GHSA-g3hv-75wg-m249](https://github.com/advisories/GHSA-g3hv-75wg-m249)); 6.11.4 ships `minimatch` 11.0.9, outside the affected ranges.
134
134
 
135
135
  ```bash
136
136
  npm install -g verdaccio
@@ -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. The 403 names the check that removed the version, e.g. `Version 1.0.0 was removed by the security filter: License 'GPL-3.0' is not in allowed list`. 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
@@ -643,7 +643,7 @@ typosquatting:
643
643
 
644
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.
645
645
 
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. Tarball requests are not checked because they carry no metadata, the same as license and author filtering.
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).
647
647
 
648
648
  ```yaml
649
649
  signatures:
@@ -661,7 +661,7 @@ signatures:
661
661
 
662
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.
663
663
 
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, and tarball requests are not checked, the same as registry signatures.
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).
665
665
 
666
666
  ```yaml
667
667
  provenance:
package/build/index.d.ts CHANGED
@@ -24,13 +24,18 @@ export default class SecurityFilterPlugin implements IPluginMiddleware<SecurityC
24
24
  private _isBlockedByPattern;
25
25
  private _isScopeAllowed;
26
26
  private _getVersionRangeRule;
27
- register_middlewares(app: Application, _auth: IBasicAuth<SecurityConfig>, _storage: IStorageManager<SecurityConfig>): void;
27
+ register_middlewares(app: Application, auth: IBasicAuth<SecurityConfig>, storage: IStorageManager<SecurityConfig>): void;
28
28
  private _blockedPackage;
29
29
  private _removeVersions;
30
30
  private _rejectedVersions;
31
31
  filter_metadata(packageInfo: Package): Promise<Package>;
32
32
  private _filterMetadata;
33
33
  private _versionBlockReason;
34
+ private _removedByFilter;
35
+ private _unchecked;
36
+ private _canAccess;
37
+ private _loadMetadataOnce;
38
+ private _loadMetadata;
34
39
  private _warnDue;
35
40
  private _checkPackageBlock;
36
41
  private _getAppliedRules;
package/build/index.js CHANGED
@@ -65,6 +65,12 @@ const PLUGIN_VERSION = JSON.parse((0, fs_1.readFileSync)((0, path_1.join)(__dirn
65
65
  const filterBlocks = new lru_cache_1.LRUCache(1000);
66
66
  const warnedAt = new lru_cache_1.LRUCache(10000);
67
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 REMOVAL_REASONS = Symbol('removalReasons');
71
+ const tarballDecisions = new lru_cache_1.LRUCache(5000);
72
+ const metadataLoads = new Map();
73
+ const loadAttempts = new lru_cache_1.LRUCache(10000);
68
74
  function forbiddenBody(packageName, reason, extra = {}) {
69
75
  return Object.assign(Object.assign({ error: `Package blocked by security filter: ${reason}`, package: packageName, reason }, extra), { timestamp: new Date().toISOString() });
70
76
  }
@@ -223,7 +229,7 @@ class SecurityFilterPlugin {
223
229
  }
224
230
  }) || null;
225
231
  }
226
- register_middlewares(app, _auth, _storage) {
232
+ register_middlewares(app, auth, storage) {
227
233
  this.logger.info('[Middleware] Registering security filter middleware');
228
234
  this.logger.info(`[Middleware] Config mode: ${this.config.mode || 'NOT SET'}`);
229
235
  app.use((req, res, next) => __awaiter(this, void 0, void 0, function* () {
@@ -262,6 +268,15 @@ class SecurityFilterPlugin {
262
268
  res.status(403).json(forbiddenBody(packageName, blockResult.reason, { version: version || 'all versions' }));
263
269
  return;
264
270
  }
271
+ const removedReason = version && !this.config.dryRun
272
+ ? yield this._removedByFilter(packageName, version, storage, auth, req)
273
+ : null;
274
+ if (removedReason) {
275
+ this.logger.warn(`[Middleware] [X] BLOCKED TARBALL: ${packageName}@${version} - ${removedReason}`);
276
+ this.metrics.recordBlock(packageName, version, removedReason);
277
+ res.status(403).json(forbiddenBody(packageName, removedReason, { version }));
278
+ return;
279
+ }
265
280
  this.logger.debug(`[Middleware] [OK] ALLOWED TARBALL: ${packageName}@${version || 'unknown'}`);
266
281
  }
267
282
  else {
@@ -320,10 +335,14 @@ class SecurityFilterPlugin {
320
335
  mode: this.config.mode || 'blacklist',
321
336
  }, blockedAt: new Date().toISOString() }) });
322
337
  }
323
- _removeVersions(pkg, removed) {
338
+ _removeVersions(pkg, removed, reason) {
324
339
  if (removed.length === 0) {
325
340
  return pkg;
326
341
  }
342
+ const reasons = Object.assign({}, pkg[REMOVAL_REASONS]);
343
+ for (const version of removed) {
344
+ reasons[version] = typeof reason === 'function' ? reason(version) : reason;
345
+ }
327
346
  const gone = new Set(removed);
328
347
  const versions = Object.assign({}, pkg.versions);
329
348
  for (const version of gone) {
@@ -336,7 +355,7 @@ class SecurityFilterPlugin {
336
355
  this.logger.debug(`[filter_metadata] Removed dist-tag "${tag}" pointing to filtered version ${tagVersion}`);
337
356
  }
338
357
  }
339
- return Object.assign(Object.assign({}, pkg), { versions, 'dist-tags': distTags });
358
+ return Object.assign(Object.assign({}, pkg), { versions, 'dist-tags': distTags, [REMOVAL_REASONS]: reasons });
340
359
  }
341
360
  _rejectedVersions(pkg, check) {
342
361
  var _a;
@@ -354,12 +373,25 @@ class SecurityFilterPlugin {
354
373
  }
355
374
  filter_metadata(packageInfo) {
356
375
  return __awaiter(this, void 0, void 0, function* () {
376
+ var _a;
357
377
  const filtered = yield this._filterMetadata(packageInfo);
358
378
  if (!this.config.dryRun) {
379
+ const left = filtered.versions || {};
380
+ const seen = Object.keys(packageInfo.versions || {});
381
+ const reasons = (_a = filtered[REMOVAL_REASONS]) !== null && _a !== void 0 ? _a : {};
382
+ tarballDecisions.set(packageInfo.name, {
383
+ seen: new Set(seen),
384
+ removed: new Map(seen.filter(version => !(version in left)).map(version => { var _a; return [version, (_a = reasons[version]) !== null && _a !== void 0 ? _a : '']; })),
385
+ filtered: true,
386
+ at: Date.now(),
387
+ });
359
388
  const security = filtered.security;
360
389
  if (security === null || security === void 0 ? void 0 : security.blocked) {
361
390
  filterBlocks.set(packageInfo.name, { security, at: Date.now() });
362
391
  }
392
+ else {
393
+ filterBlocks.delete(packageInfo.name);
394
+ }
363
395
  return filtered;
364
396
  }
365
397
  if (filtered === packageInfo) {
@@ -391,7 +423,7 @@ class SecurityFilterPlugin {
391
423
  if (ruleBlocked.length > 0) {
392
424
  this.logger.warn(`[filter_metadata] RULE FILTERED: ${packageName}: ${ruleBlocked.join(', ')}`);
393
425
  this.metrics.recordFiltered(packageName, ruleBlocked, 'Version blocked by rules');
394
- pkg = this._removeVersions(pkg, ruleBlocked);
426
+ pkg = this._removeVersions(pkg, ruleBlocked, 'Version blocked by rules');
395
427
  }
396
428
  }
397
429
  if ((_a = this.config.cveCheck) === null || _a === void 0 ? void 0 : _a.enabled) {
@@ -422,7 +454,7 @@ class SecurityFilterPlugin {
422
454
  }
423
455
  this.logger.warn(`[filter_metadata] CVE FILTERED: ${packageName} - ${reason}: ${vulnerableVersions.join(', ')}`);
424
456
  this.metrics.recordFiltered(packageName, vulnerableVersions, reason);
425
- pkg = this._removeVersions(pkg, vulnerableVersions);
457
+ pkg = this._removeVersions(pkg, vulnerableVersions, reason);
426
458
  }
427
459
  }
428
460
  if (this.licenseChecker.enabled) {
@@ -436,7 +468,8 @@ class SecurityFilterPlugin {
436
468
  if (rejected.versions.length > 0) {
437
469
  this.logger.warn(`[filter_metadata] LICENSE FILTERED: ${packageName}: ${rejected.versions.join(', ')}`);
438
470
  this.metrics.recordFiltered(packageName, rejected.versions, 'License not allowed');
439
- pkg = this._removeVersions(pkg, rejected.versions);
471
+ const licenseReasons = new Map(rejected.results.map(([version, result]) => [version, result.reason]));
472
+ pkg = this._removeVersions(pkg, rejected.versions, version => licenseReasons.get(version) || 'License not allowed');
440
473
  }
441
474
  }
442
475
  if (this.signatureChecker.enabled) {
@@ -468,9 +501,9 @@ class SecurityFilterPlugin {
468
501
  if (versions.length > 0) {
469
502
  this.logger.warn(`[filter_metadata] SIGNATURE FILTERED: ${packageName}: ${versions.join(', ')} - ${reason}`);
470
503
  this.metrics.recordFiltered(packageName, versions, reason);
504
+ pkg = this._removeVersions(pkg, versions, reason);
471
505
  }
472
506
  }
473
- pkg = this._removeVersions(pkg, [...invalid, ...missing]);
474
507
  }
475
508
  if (this.provenanceChecker.enabled
476
509
  && !(this.config.mode !== 'whitelist' && this.config.whitelist
@@ -498,8 +531,8 @@ class SecurityFilterPlugin {
498
531
  for (const [reason, versions] of byReason) {
499
532
  this.logger.warn(`[filter_metadata] PROVENANCE FILTERED: ${packageName}: ${versions.join(', ')} - ${reason}`);
500
533
  this.metrics.recordFiltered(packageName, versions, reason);
534
+ pkg = this._removeVersions(pkg, versions, reason);
501
535
  }
502
- pkg = this._removeVersions(pkg, rejected.map(r => r.version));
503
536
  }
504
537
  if ((_c = this.config.packageAge) === null || _c === void 0 ? void 0 : _c.enabled) {
505
538
  const ageResult = this.packageAgeChecker.checkPackageAge(pkg);
@@ -534,7 +567,7 @@ class SecurityFilterPlugin {
534
567
  if (removedVersions.length > 0) {
535
568
  this.logger.warn(`[filter_metadata] VERSION AGE FILTERED: ${packageName}: ${removedVersions.join(', ')}`);
536
569
  this.metrics.recordFiltered(packageName, removedVersions, 'Version too new');
537
- pkg = this._removeVersions(pkg, removedVersions);
570
+ pkg = this._removeVersions(pkg, removedVersions, 'Version too new');
538
571
  }
539
572
  }
540
573
  }
@@ -561,7 +594,8 @@ class SecurityFilterPlugin {
561
594
  }
562
595
  this.logger.warn(`[filter_metadata] AUTHOR FILTERED: ${packageName}: ${rejected.versions.join(', ')}`);
563
596
  this.metrics.recordFiltered(packageName, rejected.versions, reason, 'author_blocked', details);
564
- pkg = this._removeVersions(pkg, rejected.versions);
597
+ const authorReasons = new Map(rejected.results.map(([version, result]) => [version, result.reason]));
598
+ pkg = this._removeVersions(pkg, rejected.versions, version => authorReasons.get(version) || reason);
565
599
  }
566
600
  }
567
601
  this.logger.debug(`[filter_metadata] [OK] ALLOWED: ${packageName}`);
@@ -587,6 +621,103 @@ class SecurityFilterPlugin {
587
621
  const rangeRule = this._getVersionRangeRule(packageName, version);
588
622
  return rangeRule ? `Version matches blocked range: ${rangeRule.range}` : null;
589
623
  }
624
+ _removedByFilter(packageName, version, storage, auth, req) {
625
+ return __awaiter(this, void 0, void 0, function* () {
626
+ var _a, _b;
627
+ const isFresh = (d) => !!d && Date.now() - d.at < TARBALL_DECISION_MS;
628
+ let decision = tarballDecisions.get(packageName);
629
+ if (!isFresh(decision) || (decision.filtered && !decision.seen.has(version))) {
630
+ const attemptKey = isFresh(decision) ? `${packageName}@${version}` : packageName;
631
+ const attempt = loadAttempts.get(attemptKey);
632
+ if (attempt && Date.now() - attempt.at < RETRY_LOAD_MS) {
633
+ if (attempt.failed) {
634
+ return this._unchecked();
635
+ }
636
+ }
637
+ else {
638
+ if (!(yield this._canAccess(packageName, version, auth, req))) {
639
+ return null;
640
+ }
641
+ try {
642
+ yield this._loadMetadataOnce(packageName, storage, req);
643
+ loadAttempts.set(attemptKey, { at: Date.now(), failed: false });
644
+ }
645
+ catch (error) {
646
+ loadAttempts.set(attemptKey, { at: Date.now(), failed: true });
647
+ if (this._warnDue('tarball-check', packageName)) {
648
+ const message = error instanceof Error ? error.message : String(error);
649
+ this.logger.warn(`[Middleware] Cannot check removed versions of ${packageName}: ${message}`);
650
+ }
651
+ return this._unchecked();
652
+ }
653
+ }
654
+ decision = tarballDecisions.get(packageName);
655
+ if (!isFresh(decision)) {
656
+ tarballDecisions.set(packageName, { seen: new Set(), removed: new Map(), filtered: false, at: Date.now() });
657
+ return null;
658
+ }
659
+ }
660
+ if (!decision.removed.has(version)) {
661
+ return null;
662
+ }
663
+ const reason = decision.removed.get(version) || ((_b = (_a = filterBlocks.get(packageName)) === null || _a === void 0 ? void 0 : _a.security) === null || _b === void 0 ? void 0 : _b.reason);
664
+ return reason
665
+ ? `Version ${version} was removed by the security filter: ${reason}`
666
+ : `Version ${version} was removed by the security filter`;
667
+ });
668
+ }
669
+ _unchecked() {
670
+ var _a;
671
+ return ((_a = this.config.errorHandling) === null || _a === void 0 ? void 0 : _a.onFilterError) === 'fail-closed'
672
+ ? 'Package metadata could not be checked (fail-closed mode)'
673
+ : null;
674
+ }
675
+ _canAccess(packageName, version, auth, req) {
676
+ const allowAccess = auth === null || auth === void 0 ? void 0 : auth.allow_access;
677
+ if (typeof allowAccess !== 'function') {
678
+ return Promise.resolve(true);
679
+ }
680
+ return new Promise(resolve => {
681
+ allowAccess.call(auth, { packageName, packageVersion: version }, req.remote_user, (error, allowed) => resolve(!error && !!allowed));
682
+ });
683
+ }
684
+ _loadMetadataOnce(packageName, storage, req) {
685
+ let load = metadataLoads.get(packageName);
686
+ if (!load) {
687
+ load = this._loadMetadata(packageName, storage, req).finally(() => metadataLoads.delete(packageName));
688
+ metadataLoads.set(packageName, load);
689
+ }
690
+ return load;
691
+ }
692
+ _loadMetadata(packageName, storage, req) {
693
+ return __awaiter(this, void 0, void 0, function* () {
694
+ var _a;
695
+ const store = storage;
696
+ if (typeof (store === null || store === void 0 ? void 0 : store.getPackageByOptions) === 'function') {
697
+ yield store.getPackageByOptions({
698
+ name: packageName,
699
+ uplinksLook: true,
700
+ requestOptions: {
701
+ host: req.host,
702
+ protocol: req.protocol,
703
+ headers: req.headers,
704
+ remoteAddress: (_a = req.socket) === null || _a === void 0 ? void 0 : _a.remoteAddress,
705
+ },
706
+ });
707
+ }
708
+ else if (typeof (store === null || store === void 0 ? void 0 : store.getPackage) === 'function') {
709
+ const getPackage = store.getPackage.bind(store);
710
+ yield new Promise((resolve, reject) => {
711
+ getPackage({
712
+ name: packageName,
713
+ uplinksLook: true,
714
+ req,
715
+ callback: (error) => (error ? reject(error) : resolve()),
716
+ });
717
+ });
718
+ }
719
+ });
720
+ }
590
721
  _warnDue(kind, packageName) {
591
722
  var _a;
592
723
  const key = `${kind}|${packageName}`;
@@ -667,6 +798,8 @@ class SecurityFilterPlugin {
667
798
  }
668
799
  destroy() {
669
800
  warnedAt.clear();
801
+ tarballDecisions.clear();
802
+ loadAttempts.clear();
670
803
  this.logger.info('[Cleanup] Shutting down security filter plugin');
671
804
  try {
672
805
  this.cveChecker.destroy();
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "verdaccio-security-filter",
3
- "version": "1.9.0",
3
+ "version": "1.10.0",
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",