verdaccio-security-filter 1.8.0 → 1.9.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
@@ -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)
@@ -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*: 2 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)"
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
 
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;
@@ -34,6 +31,7 @@ export default class SecurityFilterPlugin implements IPluginMiddleware<SecurityC
34
31
  filter_metadata(packageInfo: Package): Promise<Package>;
35
32
  private _filterMetadata;
36
33
  private _versionBlockReason;
34
+ private _warnDue;
37
35
  private _checkPackageBlock;
38
36
  private _getAppliedRules;
39
37
  destroy(): void;
package/build/index.js CHANGED
@@ -63,15 +63,13 @@ 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;
67
68
  function forbiddenBody(packageName, reason, extra = {}) {
68
69
  return Object.assign(Object.assign({ error: `Package blocked by security filter: ${reason}`, package: packageName, reason }, extra), { timestamp: new Date().toISOString() });
69
70
  }
70
71
  class SecurityFilterPlugin {
71
72
  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
73
  this.config = config || {};
76
74
  if (!this.config.errorHandling) {
77
75
  this.config.errorHandling = {
@@ -375,7 +373,7 @@ class SecurityFilterPlugin {
375
373
  }
376
374
  _filterMetadata(packageInfo) {
377
375
  return __awaiter(this, void 0, void 0, function* () {
378
- var _a, _b, _c, _d, _e, _f, _g;
376
+ var _a, _b, _c, _d, _e;
379
377
  let pkg = packageInfo;
380
378
  const packageName = pkg.name;
381
379
  this.logger.debug(`[filter_metadata] --> Processing: ${packageName}`);
@@ -411,8 +409,9 @@ class SecurityFilterPlugin {
411
409
  return this._blockedPackage(pkg, reason);
412
410
  }
413
411
  }
414
- if (vulnerableVersions.length > 0 && !this.config.cveCheck.autoBlock) {
412
+ if (vulnerableVersions.length > 0 && !this.config.cveCheck.autoBlock && this._warnDue('cve', packageName)) {
415
413
  this.logger.warn(`[filter_metadata] CVE found in ${packageName}: ${vulnerableVersions.length} vulnerable version(s), autoBlock is off`);
414
+ this.metrics.recordWarning(packageName, `Package has ${vulnerableVersions.length} vulnerable version(s)`, vulnerableVersions);
416
415
  }
417
416
  if (this.config.cveCheck.autoBlock && vulnerableVersions.length > 0) {
418
417
  const reason = `Package has ${vulnerableVersions.length} vulnerable version(s)`;
@@ -448,15 +447,14 @@ class SecurityFilterPlugin {
448
447
  });
449
448
  const versionsWith = (match) => statuses.filter(([, r]) => match(r)).map(([v]) => v);
450
449
  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);
450
+ if (unsigned.length > 0 && this.signatureChecker.onMissing === 'warn' && this._warnDue('unsigned', packageName)) {
455
451
  this.logger.warn(`[filter_metadata] SIGNATURE WARNING: ${packageName}: ${unsigned.length} unsigned version(s)`);
452
+ this.metrics.recordWarning(packageName, 'Missing registry signature', unsigned);
456
453
  }
457
454
  const tolerated = versionsWith(r => r.status === 'invalid' && r.allowed);
458
- if (tolerated.length > 0) {
455
+ if (tolerated.length > 0 && this._warnDue('invalid-signature', packageName)) {
459
456
  this.logger.warn(`[filter_metadata] SIGNATURE WARNING: ${packageName}: invalid signature on ${tolerated.join(', ')} (warn-only mode)`);
457
+ this.metrics.recordWarning(packageName, 'Invalid registry signature', tolerated);
460
458
  }
461
459
  const invalid = versionsWith(r => !r.allowed && r.status === 'invalid');
462
460
  const missing = versionsWith(r => !r.allowed && r.status === 'missing');
@@ -480,10 +478,9 @@ class SecurityFilterPlugin {
480
478
  const remaining = new Set(Object.keys(pkg.versions || {}));
481
479
  const results = this.provenanceChecker.check(packageInfo).filter(r => remaining.has(r.version));
482
480
  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);
481
+ if (warned.length > 0 && this._warnDue('provenance', packageName)) {
486
482
  this.logger.warn(`[filter_metadata] PROVENANCE WARNING: ${packageName}: ${warned.length} version(s) - ${warned[0].reason}`);
483
+ this.metrics.recordWarning(packageName, warned[0].reason || 'Provenance check failed', warned.map(r => r.version));
487
484
  }
488
485
  const rejected = results.filter(r => !r.allowed);
489
486
  if (results.length > 0 && rejected.length === results.length) {
@@ -504,7 +501,7 @@ class SecurityFilterPlugin {
504
501
  }
505
502
  pkg = this._removeVersions(pkg, rejected.map(r => r.version));
506
503
  }
507
- if ((_e = this.config.packageAge) === null || _e === void 0 ? void 0 : _e.enabled) {
504
+ if ((_c = this.config.packageAge) === null || _c === void 0 ? void 0 : _c.enabled) {
508
505
  const ageResult = this.packageAgeChecker.checkPackageAge(pkg);
509
506
  if (!ageResult.allowed && !ageResult.warnOnly) {
510
507
  const reason = ageResult.reason || 'Package too new';
@@ -512,20 +509,28 @@ class SecurityFilterPlugin {
512
509
  this.metrics.recordBlock(packageName, '*', reason);
513
510
  return this._blockedPackage(pkg, reason, { ageDays: ageResult.ageDays });
514
511
  }
515
- else if (!ageResult.allowed && ageResult.warnOnly) {
512
+ else if (ageResult.warnOnly && this._warnDue('age', packageName)) {
516
513
  this.logger.warn(`[filter_metadata] AGE WARNING: ${packageName} - ${ageResult.reason} (warn-only mode)`);
514
+ this.metrics.recordWarning(packageName, ageResult.reason || 'Package too new');
517
515
  }
518
516
  if (this.config.packageAge.minVersionAgeDays) {
519
517
  const removedVersions = [];
518
+ const warnedVersions = [];
520
519
  for (const version of Object.keys(pkg.versions || {})) {
521
520
  const versionAgeResult = this.packageAgeChecker.checkVersionAge(pkg, version);
522
521
  if (!versionAgeResult.allowed && !versionAgeResult.warnOnly) {
523
522
  removedVersions.push(version);
524
523
  }
525
- else if (!versionAgeResult.allowed && versionAgeResult.warnOnly) {
526
- this.logger.warn(`[filter_metadata] VERSION AGE WARNING: ${packageName}@${version} - ${versionAgeResult.reason} (warn-only mode)`);
524
+ else if (versionAgeResult.warnOnly) {
525
+ warnedVersions.push([version, versionAgeResult.reason]);
527
526
  }
528
527
  }
528
+ if (warnedVersions.length > 0 && this._warnDue('version-age', packageName)) {
529
+ for (const [version, reason] of warnedVersions) {
530
+ this.logger.warn(`[filter_metadata] VERSION AGE WARNING: ${packageName}@${version} - ${reason} (warn-only mode)`);
531
+ }
532
+ this.metrics.recordWarning(packageName, 'Version too new', warnedVersions.map(([version]) => version));
533
+ }
529
534
  if (removedVersions.length > 0) {
530
535
  this.logger.warn(`[filter_metadata] VERSION AGE FILTERED: ${packageName}: ${removedVersions.join(', ')}`);
531
536
  this.metrics.recordFiltered(packageName, removedVersions, 'Version too new');
@@ -533,10 +538,11 @@ class SecurityFilterPlugin {
533
538
  }
534
539
  }
535
540
  }
536
- if ((_f = this.config.authorFilter) === null || _f === void 0 ? void 0 : _f.enabled) {
541
+ if ((_d = this.config.authorFilter) === null || _d === void 0 ? void 0 : _d.enabled) {
537
542
  const rejected = this._rejectedVersions(pkg, data => this.authorChecker.checkAuthor(data));
538
- if (rejected.versions.length > 0 && this.config.authorFilter.warnOnly) {
543
+ if (rejected.versions.length > 0 && this.config.authorFilter.warnOnly && this._warnDue('author', packageName)) {
539
544
  this.logger.warn(`[filter_metadata] AUTHOR WARNING: ${packageName}: ${rejected.versions.join(', ')} - ${rejected.first.reason} (warn-only mode)`);
545
+ this.metrics.recordWarning(packageName, rejected.first.reason || 'Author not allowed', rejected.versions);
540
546
  }
541
547
  else if (rejected.versions.length > 0) {
542
548
  const reason = rejected.first.reason || 'Author not allowed';
@@ -563,7 +569,7 @@ class SecurityFilterPlugin {
563
569
  }
564
570
  catch (error) {
565
571
  this.logger.error(`[filter_metadata] Error processing ${packageName}: ${error.message}`);
566
- const errorStrategy = ((_g = this.config.errorHandling) === null || _g === void 0 ? void 0 : _g.onFilterError) || 'fail-open';
572
+ const errorStrategy = ((_e = this.config.errorHandling) === null || _e === void 0 ? void 0 : _e.onFilterError) || 'fail-open';
567
573
  if (errorStrategy === 'fail-closed') {
568
574
  this.logger.warn(`[filter_metadata] Error handling: fail-closed - BLOCKING ${packageName}`);
569
575
  this.metrics.recordBlock(packageName, '*', `Error during processing: ${error.message}`);
@@ -581,9 +587,18 @@ class SecurityFilterPlugin {
581
587
  const rangeRule = this._getVersionRangeRule(packageName, version);
582
588
  return rangeRule ? `Version matches blocked range: ${rangeRule.range}` : null;
583
589
  }
590
+ _warnDue(kind, packageName) {
591
+ var _a;
592
+ const key = `${kind}|${packageName}`;
593
+ const now = Date.now();
594
+ if (now - ((_a = warnedAt.get(key)) !== null && _a !== void 0 ? _a : -Infinity) < WARN_REPEAT_MS) {
595
+ return false;
596
+ }
597
+ warnedAt.set(key, now);
598
+ return true;
599
+ }
584
600
  _checkPackageBlock(packageName, version) {
585
601
  return __awaiter(this, void 0, void 0, function* () {
586
- var _a;
587
602
  const whitelistMode = this.config.mode === 'whitelist';
588
603
  if (whitelistMode) {
589
604
  const whitelistCheck = this.whitelistChecker.isWhitelisted(packageName, version);
@@ -599,10 +614,9 @@ class SecurityFilterPlugin {
599
614
  }
600
615
  const typosquat = whitelistMode ? { allowed: true } : this.typosquatChecker.check(packageName);
601
616
  if (typosquat.warnOnly && typosquat.reason) {
602
- const now = Date.now();
603
- if (now - ((_a = this.typosquatWarnedAt.get(packageName)) !== null && _a !== void 0 ? _a : -Infinity) >= WARN_REPEAT_MS) {
604
- this.typosquatWarnedAt.set(packageName, now);
617
+ if (this._warnDue('typosquat', packageName)) {
605
618
  this.logger.warn(`TYPOSQUAT WARNING: ${packageName} - ${typosquat.reason} (warn-only mode)`);
619
+ this.metrics.recordWarning(packageName, typosquat.reason || 'Possible typosquat');
606
620
  }
607
621
  }
608
622
  else if (!typosquat.allowed) {
@@ -652,6 +666,7 @@ class SecurityFilterPlugin {
652
666
  return rules;
653
667
  }
654
668
  destroy() {
669
+ warnedAt.clear();
655
670
  this.logger.info('[Cleanup] Shutting down security filter plugin');
656
671
  try {
657
672
  this.cveChecker.destroy();
@@ -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>;
@@ -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;
@@ -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
  }
@@ -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.dryRun ? '[DRY RUN] would block' : 'blocked';
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.recent = new lru_cache_1.LRUCache(5000);
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
- if (!this.enabled) {
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
- if (this.repeatMs > 0 && now - ((_c = this.recent.get(key)) !== null && _c !== void 0 ? _c : -Infinity) < this.repeatMs) {
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
- this.recent.set(key, now);
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.8.0",
3
+ "version": "1.9.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",