verdaccio-security-filter 1.6.1 → 1.8.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
@@ -71,6 +71,8 @@ This plugin implements **two independent security layers** for complete protecti
71
71
  - **Minimum Package Age** - Require packages to exist for a minimum number of days
72
72
  - **Minimum Version Age** - Require specific versions to exist for a minimum number of days
73
73
  - **Warn-Only Mode** - Log warnings without blocking
74
+ - **Registry Signature Verification** - Remove versions whose npm registry signature does not verify
75
+ - **Provenance Downgrade Detection** - Remove versions published without npm provenance after the package started publishing with it
74
76
  - **Typosquatting Detection** - Block names one typo away from a popular npm package or your own protected names (`lodahs`, `expres`)
75
77
  - **Author Filtering** - Block packages based on author information
76
78
  - **Block by Author Name** - Block specific author names or patterns
@@ -102,16 +104,19 @@ This plugin implements **two independent security layers** for complete protecti
102
104
  ### 🔮 Roadmap
103
105
 
104
106
  #### Planned
105
- - [ ] **Package signature verification** - check npm registry signatures and provenance attestations
107
+ Nothing right now; open an issue with a request.
106
108
 
107
109
  #### Under consideration
108
110
  These wait for a concrete request:
109
111
  - **Snyk integration** - OSV already includes GitHub Security Advisories, so a second source only helps if it knows more
110
112
  - **Auto-approve criteria** - approve by npm statistics; needs external requests on the request path
113
+ - **Sigstore verification of provenance** - verify the attestation bundle itself; needs a new dependency and requests to the registry
111
114
  - **CLI tool** and **GitHub Action** for checking a rule set outside Verdaccio
112
115
 
113
116
  #### Done
114
117
  - [x] **Dry-run mode** - `dryRun: true`
118
+ - [x] **Registry signature verification** - `signatures`: npm registry signatures (ECDSA)
119
+ - [x] **Provenance attestations** - `provenance`: presence and downgrade detection
115
120
  - [x] **Typosquatting detection** - `typosquatting`: names within a small edit distance of popular packages
116
121
  - [x] **Webhook notifications** - `webhook`: block events as JSON or as a Slack message
117
122
 
@@ -595,6 +600,44 @@ typosquatting:
595
600
  ignore: ['lodash-ext']
596
601
  ```
597
602
 
603
+ ### Signature Options
604
+
605
+ | Option | Type | Default | Description |
606
+ |--------|------|---------|-------------|
607
+ | `signatures.enabled` | `boolean` | `false` | Verify npm registry signatures |
608
+ | `signatures.onMissing` | `'allow' \| 'warn' \| 'block'` | `'warn'` | What to do with versions that have no verifiable signature |
609
+ | `signatures.warnOnly` | `boolean` | `false` | Log invalid signatures instead of removing the version |
610
+ | `signatures.keys` | `{ keyid, key, expires }[]` | npm's keys | Replaces the bundled keys, in the shape of `registry.npmjs.org/-/npm/v1/keys` |
611
+
612
+ 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
+
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. Tarball requests are not checked because they carry no metadata, the same as license and author filtering.
615
+
616
+ ```yaml
617
+ signatures:
618
+ enabled: true
619
+ onMissing: warn
620
+ ```
621
+
622
+ ### Provenance Options
623
+
624
+ | Option | Type | Default | Description |
625
+ |--------|------|---------|-------------|
626
+ | `provenance.enabled` | `boolean` | `false` | Check npm provenance attestations |
627
+ | `provenance.onDowngrade` | `'allow' \| 'warn' \| 'block'` | `'block'` | Versions without provenance published after the first version with it |
628
+ | `provenance.onMissing` | `'allow' \| 'warn' \| 'block'` | `'allow'` | Packages that never published with provenance |
629
+
630
+ 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
+
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, and tarball requests are not checked, the same as registry signatures.
633
+
634
+ ```yaml
635
+ provenance:
636
+ enabled: true
637
+ onDowngrade: block
638
+ onMissing: allow
639
+ ```
640
+
598
641
  ### Error Handling Options
599
642
 
600
643
  | Option | Type | Default | Description |
package/build/index.d.ts CHANGED
@@ -15,6 +15,10 @@ export default class SecurityFilterPlugin implements IPluginMiddleware<SecurityC
15
15
  private readonly packageAgeChecker;
16
16
  private readonly authorChecker;
17
17
  private readonly typosquatChecker;
18
+ private readonly signatureChecker;
19
+ private readonly provenanceChecker;
20
+ private readonly unsignedWarnedAt;
21
+ private readonly provenanceWarnedAt;
18
22
  private readonly typosquatWarnedAt;
19
23
  constructor(config: SecurityConfig, options: PluginOptions<SecurityConfig>);
20
24
  private _parseVersionRangeRules;
@@ -43,4 +47,6 @@ export { LicenseChecker } from './lib/license-checker';
43
47
  export { PackageAgeChecker } from './lib/package-age-checker';
44
48
  export { AuthorChecker } from './lib/author-checker';
45
49
  export { TyposquatChecker } from './lib/typosquat-checker';
50
+ export { SignatureChecker } from './lib/signature-checker';
51
+ export { ProvenanceChecker } from './lib/provenance-checker';
46
52
  export * from './types';
package/build/index.js CHANGED
@@ -45,7 +45,7 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, ge
45
45
  });
46
46
  };
47
47
  Object.defineProperty(exports, "__esModule", { value: true });
48
- exports.TyposquatChecker = exports.AuthorChecker = exports.PackageAgeChecker = exports.LicenseChecker = exports.CVEChecker = exports.WhitelistChecker = exports.WebhookNotifier = exports.MetricsCollector = exports.SecurityLogger = void 0;
48
+ exports.ProvenanceChecker = exports.SignatureChecker = exports.TyposquatChecker = exports.AuthorChecker = exports.PackageAgeChecker = exports.LicenseChecker = exports.CVEChecker = exports.WhitelistChecker = exports.WebhookNotifier = exports.MetricsCollector = exports.SecurityLogger = void 0;
49
49
  const semver = __importStar(require("semver"));
50
50
  const fs_1 = require("fs");
51
51
  const path_1 = require("path");
@@ -57,16 +57,20 @@ const license_checker_1 = require("./lib/license-checker");
57
57
  const package_age_checker_1 = require("./lib/package-age-checker");
58
58
  const author_checker_1 = require("./lib/author-checker");
59
59
  const typosquat_checker_1 = require("./lib/typosquat-checker");
60
+ const signature_checker_1 = require("./lib/signature-checker");
61
+ const provenance_checker_1 = require("./lib/provenance-checker");
60
62
  const lru_cache_1 = require("./lib/lru-cache");
61
63
  const webhook_1 = require("./lib/webhook");
62
64
  const PLUGIN_VERSION = JSON.parse((0, fs_1.readFileSync)((0, path_1.join)(__dirname, '..', 'package.json'), 'utf8')).version;
63
65
  const filterBlocks = new lru_cache_1.LRUCache(1000);
64
- const TYPOSQUAT_WARN_REPEAT_MS = 10 * 60 * 1000;
66
+ const WARN_REPEAT_MS = 10 * 60 * 1000;
65
67
  function forbiddenBody(packageName, reason, extra = {}) {
66
68
  return Object.assign(Object.assign({ error: `Package blocked by security filter: ${reason}`, package: packageName, reason }, extra), { timestamp: new Date().toISOString() });
67
69
  }
68
70
  class SecurityFilterPlugin {
69
71
  constructor(config, options) {
72
+ this.unsignedWarnedAt = new lru_cache_1.LRUCache(5000);
73
+ this.provenanceWarnedAt = new lru_cache_1.LRUCache(5000);
70
74
  this.typosquatWarnedAt = new lru_cache_1.LRUCache(5000);
71
75
  this.config = config || {};
72
76
  if (!this.config.errorHandling) {
@@ -84,6 +88,8 @@ class SecurityFilterPlugin {
84
88
  this.packageAgeChecker = new package_age_checker_1.PackageAgeChecker(this.config.packageAge);
85
89
  this.authorChecker = new author_checker_1.AuthorChecker(this.config.authorFilter);
86
90
  this.typosquatChecker = new typosquat_checker_1.TyposquatChecker(this.config.typosquatting);
91
+ this.signatureChecker = new signature_checker_1.SignatureChecker(this.config.signatures);
92
+ this.provenanceChecker = new provenance_checker_1.ProvenanceChecker(this.config.provenance);
87
93
  this.securityRules = {
88
94
  blockedVersions: this.config.blockedVersions || [],
89
95
  blockedPatterns: this.config.blockedPatterns || [],
@@ -155,7 +161,7 @@ class SecurityFilterPlugin {
155
161
  }
156
162
  }
157
163
  _getEnabledFeatures() {
158
- var _a, _b, _c, _d, _e;
164
+ var _a, _b, _c, _d, _e, _f, _g;
159
165
  const features = [];
160
166
  if (this.config.dryRun)
161
167
  features.push('dry-run');
@@ -175,6 +181,10 @@ class SecurityFilterPlugin {
175
181
  features.push('author-filtering');
176
182
  if ((_e = this.config.typosquatting) === null || _e === void 0 ? void 0 : _e.enabled)
177
183
  features.push('typosquat-detection');
184
+ if ((_f = this.config.signatures) === null || _f === void 0 ? void 0 : _f.enabled)
185
+ features.push('registry-signatures');
186
+ if ((_g = this.config.provenance) === null || _g === void 0 ? void 0 : _g.enabled)
187
+ features.push('provenance');
178
188
  if (this.securityRules.versionRangeRules.length > 0)
179
189
  features.push('version-range-rules');
180
190
  if (this.securityRules.blockedPatterns.length > 0)
@@ -365,7 +375,7 @@ class SecurityFilterPlugin {
365
375
  }
366
376
  _filterMetadata(packageInfo) {
367
377
  return __awaiter(this, void 0, void 0, function* () {
368
- var _a, _b, _c, _d, _e;
378
+ var _a, _b, _c, _d, _e, _f, _g;
369
379
  let pkg = packageInfo;
370
380
  const packageName = pkg.name;
371
381
  this.logger.debug(`[filter_metadata] --> Processing: ${packageName}`);
@@ -430,7 +440,71 @@ class SecurityFilterPlugin {
430
440
  pkg = this._removeVersions(pkg, rejected.versions);
431
441
  }
432
442
  }
433
- if ((_c = this.config.packageAge) === null || _c === void 0 ? void 0 : _c.enabled) {
443
+ if (this.signatureChecker.enabled) {
444
+ const statuses = Object.entries(pkg.versions || {}).map(([version, data]) => {
445
+ var _a;
446
+ return [version,
447
+ this.signatureChecker.check(packageName, Object.assign(Object.assign({}, data), { version }), (_a = pkg.time) === null || _a === void 0 ? void 0 : _a[version])];
448
+ });
449
+ const versionsWith = (match) => statuses.filter(([, r]) => match(r)).map(([v]) => v);
450
+ const unsigned = versionsWith(r => r.status === 'missing');
451
+ const now = Date.now();
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);
455
+ this.logger.warn(`[filter_metadata] SIGNATURE WARNING: ${packageName}: ${unsigned.length} unsigned version(s)`);
456
+ }
457
+ const tolerated = versionsWith(r => r.status === 'invalid' && r.allowed);
458
+ if (tolerated.length > 0) {
459
+ this.logger.warn(`[filter_metadata] SIGNATURE WARNING: ${packageName}: invalid signature on ${tolerated.join(', ')} (warn-only mode)`);
460
+ }
461
+ const invalid = versionsWith(r => !r.allowed && r.status === 'invalid');
462
+ const missing = versionsWith(r => !r.allowed && r.status === 'missing');
463
+ if (statuses.length > 0 && invalid.length + missing.length === statuses.length) {
464
+ const reason = invalid.length > 0 ? 'Invalid registry signature' : 'Missing registry signature';
465
+ this.logger.warn(`[filter_metadata] SIGNATURE BLOCKED: ${packageName} - ${reason}`);
466
+ this.metrics.recordBlock(packageName, '*', reason);
467
+ return this._blockedPackage(pkg, reason);
468
+ }
469
+ for (const [versions, reason] of [[invalid, 'Invalid registry signature'], [missing, 'Missing registry signature']]) {
470
+ if (versions.length > 0) {
471
+ this.logger.warn(`[filter_metadata] SIGNATURE FILTERED: ${packageName}: ${versions.join(', ')} - ${reason}`);
472
+ this.metrics.recordFiltered(packageName, versions, reason);
473
+ }
474
+ }
475
+ pkg = this._removeVersions(pkg, [...invalid, ...missing]);
476
+ }
477
+ if (this.provenanceChecker.enabled
478
+ && !(this.config.mode !== 'whitelist' && this.config.whitelist
479
+ && this.whitelistChecker.isWhitelisted(packageName).allowed)) {
480
+ const remaining = new Set(Object.keys(pkg.versions || {}));
481
+ const results = this.provenanceChecker.check(packageInfo).filter(r => remaining.has(r.version));
482
+ const warned = results.filter(r => r.warn);
483
+ const now = Date.now();
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);
486
+ this.logger.warn(`[filter_metadata] PROVENANCE WARNING: ${packageName}: ${warned.length} version(s) - ${warned[0].reason}`);
487
+ }
488
+ const rejected = results.filter(r => !r.allowed);
489
+ if (results.length > 0 && rejected.length === results.length) {
490
+ const reason = rejected[0].reason || 'Provenance check failed';
491
+ this.logger.warn(`[filter_metadata] PROVENANCE BLOCKED: ${packageName} - ${reason}`);
492
+ this.metrics.recordBlock(packageName, '*', reason);
493
+ return this._blockedPackage(pkg, reason);
494
+ }
495
+ const byReason = new Map();
496
+ rejected.forEach((r) => {
497
+ var _a;
498
+ const reason = r.reason || 'Provenance check failed';
499
+ byReason.set(reason, [...((_a = byReason.get(reason)) !== null && _a !== void 0 ? _a : []), r.version]);
500
+ });
501
+ for (const [reason, versions] of byReason) {
502
+ this.logger.warn(`[filter_metadata] PROVENANCE FILTERED: ${packageName}: ${versions.join(', ')} - ${reason}`);
503
+ this.metrics.recordFiltered(packageName, versions, reason);
504
+ }
505
+ pkg = this._removeVersions(pkg, rejected.map(r => r.version));
506
+ }
507
+ if ((_e = this.config.packageAge) === null || _e === void 0 ? void 0 : _e.enabled) {
434
508
  const ageResult = this.packageAgeChecker.checkPackageAge(pkg);
435
509
  if (!ageResult.allowed && !ageResult.warnOnly) {
436
510
  const reason = ageResult.reason || 'Package too new';
@@ -459,7 +533,7 @@ class SecurityFilterPlugin {
459
533
  }
460
534
  }
461
535
  }
462
- if ((_d = this.config.authorFilter) === null || _d === void 0 ? void 0 : _d.enabled) {
536
+ if ((_f = this.config.authorFilter) === null || _f === void 0 ? void 0 : _f.enabled) {
463
537
  const rejected = this._rejectedVersions(pkg, data => this.authorChecker.checkAuthor(data));
464
538
  if (rejected.versions.length > 0 && this.config.authorFilter.warnOnly) {
465
539
  this.logger.warn(`[filter_metadata] AUTHOR WARNING: ${packageName}: ${rejected.versions.join(', ')} - ${rejected.first.reason} (warn-only mode)`);
@@ -489,7 +563,7 @@ class SecurityFilterPlugin {
489
563
  }
490
564
  catch (error) {
491
565
  this.logger.error(`[filter_metadata] Error processing ${packageName}: ${error.message}`);
492
- const errorStrategy = ((_e = this.config.errorHandling) === null || _e === void 0 ? void 0 : _e.onFilterError) || 'fail-open';
566
+ const errorStrategy = ((_g = this.config.errorHandling) === null || _g === void 0 ? void 0 : _g.onFilterError) || 'fail-open';
493
567
  if (errorStrategy === 'fail-closed') {
494
568
  this.logger.warn(`[filter_metadata] Error handling: fail-closed - BLOCKING ${packageName}`);
495
569
  this.metrics.recordBlock(packageName, '*', `Error during processing: ${error.message}`);
@@ -526,7 +600,7 @@ class SecurityFilterPlugin {
526
600
  const typosquat = whitelistMode ? { allowed: true } : this.typosquatChecker.check(packageName);
527
601
  if (typosquat.warnOnly && typosquat.reason) {
528
602
  const now = Date.now();
529
- if (now - ((_a = this.typosquatWarnedAt.get(packageName)) !== null && _a !== void 0 ? _a : -Infinity) >= TYPOSQUAT_WARN_REPEAT_MS) {
603
+ if (now - ((_a = this.typosquatWarnedAt.get(packageName)) !== null && _a !== void 0 ? _a : -Infinity) >= WARN_REPEAT_MS) {
530
604
  this.typosquatWarnedAt.set(packageName, now);
531
605
  this.logger.warn(`TYPOSQUAT WARNING: ${packageName} - ${typosquat.reason} (warn-only mode)`);
532
606
  }
@@ -608,4 +682,8 @@ var author_checker_2 = require("./lib/author-checker");
608
682
  Object.defineProperty(exports, "AuthorChecker", { enumerable: true, get: function () { return author_checker_2.AuthorChecker; } });
609
683
  var typosquat_checker_2 = require("./lib/typosquat-checker");
610
684
  Object.defineProperty(exports, "TyposquatChecker", { enumerable: true, get: function () { return typosquat_checker_2.TyposquatChecker; } });
685
+ var signature_checker_2 = require("./lib/signature-checker");
686
+ Object.defineProperty(exports, "SignatureChecker", { enumerable: true, get: function () { return signature_checker_2.SignatureChecker; } });
687
+ var provenance_checker_2 = require("./lib/provenance-checker");
688
+ Object.defineProperty(exports, "ProvenanceChecker", { enumerable: true, get: function () { return provenance_checker_2.ProvenanceChecker; } });
611
689
  __exportStar(require("./types"), exports);
@@ -0,0 +1,2 @@
1
+ import { RegistryKey } from '../types';
2
+ export declare const NPM_REGISTRY_KEYS: readonly RegistryKey[];
@@ -0,0 +1,15 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.NPM_REGISTRY_KEYS = void 0;
4
+ exports.NPM_REGISTRY_KEYS = [
5
+ {
6
+ expires: '2025-01-29T00:00:00.000Z',
7
+ keyid: 'SHA256:jl3bwswu80PjjokCgh0o2w5c2U4LhQAE57gj9cz1kzA',
8
+ key: 'MFkwEwYHKoZIzj0CAQYIKoZIzj0DAQcDQgAE1Olb3zMAFFxXKHiIkQO5cJ3Yhl5i6UPp+IhuteBJbuHcA5UogKo0EWtlWwW6KSaKoTNEYL7JlCQiVnkhBktUgg==',
9
+ },
10
+ {
11
+ expires: null,
12
+ keyid: 'SHA256:DhQ8wR5APBvFHLF/+Tc+AYvPOdTpcIDqOhxsBHRwC7U',
13
+ key: 'MFkwEwYHKoZIzj0CAQYIKoZIzj0DAQcDQgAEY6Ya7W++7aUPzvMTrezH6Ycx3c+HOKYCcNGybJZSCJq/fd7Qa8uuAKtdIkUQtQiEKERhAmE5lMMJhP8OkDOa2g==',
14
+ },
15
+ ];
@@ -0,0 +1,17 @@
1
+ import { Package } from '@verdaccio/types';
2
+ import { ProvenanceConfig } from '../types';
3
+ export type ProvenanceStatus = 'present' | 'downgrade' | 'missing';
4
+ export interface ProvenanceResult {
5
+ version: string;
6
+ status: ProvenanceStatus;
7
+ allowed: boolean;
8
+ warn: boolean;
9
+ reason?: string;
10
+ }
11
+ export declare class ProvenanceChecker {
12
+ readonly enabled: boolean;
13
+ private readonly actions;
14
+ constructor(config?: ProvenanceConfig);
15
+ check(pkg: Package): ProvenanceResult[];
16
+ private result;
17
+ }
@@ -0,0 +1,57 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.ProvenanceChecker = void 0;
4
+ const SLSA_PROVENANCE = 'https://slsa.dev/provenance/';
5
+ const REASONS = {
6
+ present: undefined,
7
+ downgrade: 'Provenance downgrade',
8
+ missing: 'Missing provenance',
9
+ };
10
+ class ProvenanceChecker {
11
+ constructor(config) {
12
+ var _a, _b, _c;
13
+ this.enabled = (_a = config === null || config === void 0 ? void 0 : config.enabled) !== null && _a !== void 0 ? _a : false;
14
+ this.actions = {
15
+ present: 'allow',
16
+ downgrade: (_b = config === null || config === void 0 ? void 0 : config.onDowngrade) !== null && _b !== void 0 ? _b : 'block',
17
+ missing: (_c = config === null || config === void 0 ? void 0 : config.onMissing) !== null && _c !== void 0 ? _c : 'allow',
18
+ };
19
+ }
20
+ check(pkg) {
21
+ const versions = Object.entries(pkg.versions || {}).map(([version, data]) => {
22
+ var _a, _b;
23
+ return ({
24
+ version,
25
+ attested: hasProvenance(data),
26
+ published: Date.parse((_b = (_a = pkg.time) === null || _a === void 0 ? void 0 : _a[version]) !== null && _b !== void 0 ? _b : ''),
27
+ });
28
+ });
29
+ const attested = versions.filter(v => v.attested);
30
+ const baseline = Math.min(...attested.map(v => (Number.isNaN(v.published) ? -Infinity : v.published)));
31
+ return versions.map(({ version, attested: hasIt, published }) => {
32
+ let status;
33
+ if (attested.length === 0) {
34
+ status = 'missing';
35
+ }
36
+ else if (hasIt) {
37
+ status = 'present';
38
+ }
39
+ else {
40
+ status = (Number.isNaN(published) ? Infinity : published) > baseline ? 'downgrade' : 'present';
41
+ }
42
+ return this.result(version, status);
43
+ });
44
+ }
45
+ result(version, status) {
46
+ const action = this.actions[status];
47
+ const reason = REASONS[status];
48
+ const result = { version, status, allowed: action !== 'block', warn: action === 'warn' };
49
+ return reason ? Object.assign(Object.assign({}, result), { reason }) : result;
50
+ }
51
+ }
52
+ exports.ProvenanceChecker = ProvenanceChecker;
53
+ function hasProvenance(data) {
54
+ var _a, _b, _c;
55
+ const predicateType = (_c = (_b = (_a = data === null || data === void 0 ? void 0 : data.dist) === null || _a === void 0 ? void 0 : _a.attestations) === null || _b === void 0 ? void 0 : _b.provenance) === null || _c === void 0 ? void 0 : _c.predicateType;
56
+ return typeof predicateType === 'string' && predicateType.startsWith(SLSA_PROVENANCE);
57
+ }
@@ -0,0 +1,19 @@
1
+ import { Version } from '@verdaccio/types';
2
+ import { SignatureConfig } from '../types';
3
+ export type SignatureStatus = 'valid' | 'invalid' | 'missing';
4
+ export interface SignatureResult {
5
+ allowed: boolean;
6
+ status: SignatureStatus;
7
+ reason?: string;
8
+ }
9
+ export declare class SignatureChecker {
10
+ readonly enabled: boolean;
11
+ readonly onMissing: 'allow' | 'warn' | 'block';
12
+ private readonly warnOnly;
13
+ private readonly keys;
14
+ private readonly statuses;
15
+ constructor(config?: SignatureConfig);
16
+ check(name: string, data: Version, publishedAt?: string): SignatureResult;
17
+ private status;
18
+ private verify;
19
+ }
@@ -0,0 +1,103 @@
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
+ })();
35
+ Object.defineProperty(exports, "__esModule", { value: true });
36
+ exports.SignatureChecker = void 0;
37
+ const crypto = __importStar(require("crypto"));
38
+ const npm_keys_1 = require("./npm-keys");
39
+ const lru_cache_1 = require("./lru-cache");
40
+ const REASONS = {
41
+ valid: undefined,
42
+ invalid: 'Invalid registry signature',
43
+ missing: 'Missing registry signature',
44
+ };
45
+ class SignatureChecker {
46
+ constructor(config) {
47
+ var _a, _b, _c, _d;
48
+ this.statuses = new lru_cache_1.LRUCache(100000);
49
+ this.enabled = (_a = config === null || config === void 0 ? void 0 : config.enabled) !== null && _a !== void 0 ? _a : false;
50
+ this.onMissing = (_b = config === null || config === void 0 ? void 0 : config.onMissing) !== null && _b !== void 0 ? _b : 'warn';
51
+ this.warnOnly = (_c = config === null || config === void 0 ? void 0 : config.warnOnly) !== null && _c !== void 0 ? _c : false;
52
+ this.keys = new Map(((_d = config === null || config === void 0 ? void 0 : config.keys) !== null && _d !== void 0 ? _d : npm_keys_1.NPM_REGISTRY_KEYS).map((k) => [k.keyid, {
53
+ key: crypto.createPublicKey({ key: Buffer.from(k.key, 'base64'), format: 'der', type: 'spki' }),
54
+ expires: k.expires ? Date.parse(k.expires) : Infinity,
55
+ }]));
56
+ }
57
+ check(name, data, publishedAt) {
58
+ if (!this.enabled) {
59
+ return { allowed: true, status: 'valid' };
60
+ }
61
+ const status = this.status(name, data, publishedAt);
62
+ const allowed = status === 'valid'
63
+ || (status === 'invalid' && this.warnOnly)
64
+ || (status === 'missing' && this.onMissing !== 'block');
65
+ const reason = REASONS[status];
66
+ return reason ? { allowed, status, reason } : { allowed, status };
67
+ }
68
+ status(name, data, publishedAt) {
69
+ var _a, _b, _c;
70
+ const integrity = (_a = data.dist) === null || _a === void 0 ? void 0 : _a.integrity;
71
+ const signatures = (_c = (_b = data.dist) === null || _b === void 0 ? void 0 : _b.signatures) !== null && _c !== void 0 ? _c : [];
72
+ const cacheKey = crypto.createHash('sha256')
73
+ .update(JSON.stringify([name, data.version, integrity, publishedAt, signatures.map(s => [s.keyid, s.sig])]))
74
+ .digest('base64');
75
+ let status = this.statuses.get(cacheKey);
76
+ if (status === undefined) {
77
+ status = this.verify(`${name}@${data.version}:${integrity}`, integrity, signatures, publishedAt);
78
+ this.statuses.set(cacheKey, status);
79
+ }
80
+ return status;
81
+ }
82
+ verify(message, integrity, signatures, publishedAt) {
83
+ const published = publishedAt ? Date.parse(publishedAt) : NaN;
84
+ const usable = signatures.flatMap(s => {
85
+ const key = this.keys.get(s.keyid);
86
+ const inDate = key && (key.expires === Infinity || published < key.expires);
87
+ return key && inDate ? [{ key: key.key, sig: s.sig }] : [];
88
+ });
89
+ if (!integrity || usable.length === 0) {
90
+ return 'missing';
91
+ }
92
+ const valid = usable.some(({ key, sig }) => {
93
+ try {
94
+ return crypto.verify('sha256', Buffer.from(message), key, Buffer.from(sig, 'base64'));
95
+ }
96
+ catch (_a) {
97
+ return false;
98
+ }
99
+ });
100
+ return valid ? 'valid' : 'invalid';
101
+ }
102
+ }
103
+ exports.SignatureChecker = SignatureChecker;
package/build/types.d.ts CHANGED
@@ -42,6 +42,11 @@ export interface WebhookConfig {
42
42
  timeoutMs?: number;
43
43
  repeatIntervalMinutes?: number;
44
44
  }
45
+ export interface ProvenanceConfig {
46
+ enabled: boolean;
47
+ onDowngrade?: 'allow' | 'warn' | 'block';
48
+ onMissing?: 'allow' | 'warn' | 'block';
49
+ }
45
50
  export interface PackageAgeConfig {
46
51
  enabled: boolean;
47
52
  minPackageAgeDays: number;
@@ -56,6 +61,17 @@ export interface TyposquatConfig {
56
61
  ignore?: string[];
57
62
  warnOnly?: boolean;
58
63
  }
64
+ export interface RegistryKey {
65
+ keyid: string;
66
+ key: string;
67
+ expires: string | null;
68
+ }
69
+ export interface SignatureConfig {
70
+ enabled: boolean;
71
+ onMissing?: 'allow' | 'warn' | 'block';
72
+ warnOnly?: boolean;
73
+ keys?: RegistryKey[];
74
+ }
59
75
  export interface AuthorFilterConfig {
60
76
  enabled: boolean;
61
77
  blockedAuthors?: string[];
@@ -81,9 +97,11 @@ export interface SecurityConfig extends Config {
81
97
  logger?: LoggerConfig;
82
98
  metrics?: MetricsConfig;
83
99
  webhook?: WebhookConfig;
100
+ provenance?: ProvenanceConfig;
84
101
  packageAge?: PackageAgeConfig;
85
102
  authorFilter?: AuthorFilterConfig;
86
103
  typosquatting?: TyposquatConfig;
104
+ signatures?: SignatureConfig;
87
105
  errorHandling?: {
88
106
  onFilterError?: 'fail-open' | 'fail-closed';
89
107
  onCveCheckError?: 'fail-open' | 'fail-closed';
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "verdaccio-security-filter",
3
- "version": "1.6.1",
3
+ "version": "1.8.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",