verdaccio-security-filter 1.9.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 CHANGED
@@ -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
@@ -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,11 @@ 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 tarballDecisions = new lru_cache_1.LRUCache(5000);
71
+ const metadataLoads = new Map();
72
+ const loadAttempts = new lru_cache_1.LRUCache(10000);
68
73
  function forbiddenBody(packageName, reason, extra = {}) {
69
74
  return Object.assign(Object.assign({ error: `Package blocked by security filter: ${reason}`, package: packageName, reason }, extra), { timestamp: new Date().toISOString() });
70
75
  }
@@ -223,7 +228,7 @@ class SecurityFilterPlugin {
223
228
  }
224
229
  }) || null;
225
230
  }
226
- register_middlewares(app, _auth, _storage) {
231
+ register_middlewares(app, auth, storage) {
227
232
  this.logger.info('[Middleware] Registering security filter middleware');
228
233
  this.logger.info(`[Middleware] Config mode: ${this.config.mode || 'NOT SET'}`);
229
234
  app.use((req, res, next) => __awaiter(this, void 0, void 0, function* () {
@@ -262,6 +267,15 @@ class SecurityFilterPlugin {
262
267
  res.status(403).json(forbiddenBody(packageName, blockResult.reason, { version: version || 'all versions' }));
263
268
  return;
264
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
+ }
265
279
  this.logger.debug(`[Middleware] [OK] ALLOWED TARBALL: ${packageName}@${version || 'unknown'}`);
266
280
  }
267
281
  else {
@@ -356,10 +370,21 @@ class SecurityFilterPlugin {
356
370
  return __awaiter(this, void 0, void 0, function* () {
357
371
  const filtered = yield this._filterMetadata(packageInfo);
358
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
+ });
359
381
  const security = filtered.security;
360
382
  if (security === null || security === void 0 ? void 0 : security.blocked) {
361
383
  filterBlocks.set(packageInfo.name, { security, at: Date.now() });
362
384
  }
385
+ else {
386
+ filterBlocks.delete(packageInfo.name);
387
+ }
363
388
  return filtered;
364
389
  }
365
390
  if (filtered === packageInfo) {
@@ -587,6 +612,100 @@ class SecurityFilterPlugin {
587
612
  const rangeRule = this._getVersionRangeRule(packageName, version);
588
613
  return rangeRule ? `Version matches blocked range: ${rangeRule.range}` : null;
589
614
  }
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) {
681
+ return __awaiter(this, void 0, void 0, function* () {
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
+ }
590
709
  _warnDue(kind, packageName) {
591
710
  var _a;
592
711
  const key = `${kind}|${packageName}`;
@@ -667,6 +786,8 @@ class SecurityFilterPlugin {
667
786
  }
668
787
  destroy() {
669
788
  warnedAt.clear();
789
+ tarballDecisions.clear();
790
+ loadAttempts.clear();
670
791
  this.logger.info('[Cleanup] Shutting down security filter plugin');
671
792
  try {
672
793
  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.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",