verdaccio-security-filter 1.4.4 → 1.5.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,6 +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
65
  - **Security Audit Trail** - Detailed logging of all security decisions
65
66
  - **Customizable Output** - Log to stdout or file in JSON format
66
67
 
@@ -97,31 +98,26 @@ This plugin implements **two independent security layers** for complete protecti
97
98
  - API timeout protection
98
99
  - Graceful degradation on errors
99
100
 
100
- ### 🔮 Planned Features (Roadmap)
101
-
102
- #### Phase 3: Advanced Security
103
- - [ ] **Dependency Depth Limiting** - Limit dependency tree depth and total count
104
- - [ ] **Circular Dependency Detection** - Block packages with circular dependencies
105
- - [ ] **Rate Limiting** - Detect and block suspicious download patterns
106
- - [ ] **Typosquatting Detection** - AI-powered detection of similar package names
107
- - [ ] **Package Signing Verification** - PGP signature validation
108
- - [ ] **Custom Validation Scripts** - Execute custom security checks
109
-
110
- #### Phase 4: Enterprise Features
111
- - [ ] **Integration with Security Scanners** - npm audit, Snyk API, Sonatype
112
- - [ ] **Webhook Notifications** - Real-time alerts for security events
113
- - [ ] **Web Dashboard** - Visual interface for security analytics
114
- - [ ] **Email/Slack Notifications** - Alert channels for critical events
115
- - [ ] **Audit Reports** - Generate compliance reports (PDF, CSV, JSON)
116
- - [ ] **Multi-Registry Support** - Fallback to other registries
117
- - [ ] **ML-based Anomaly Detection** - Machine learning for threat detection
118
-
119
- #### Phase 5: Developer Experience
120
- - [x] **Dry Run Mode** - Test rules without actually blocking (`dryRun: true`)
121
- - [ ] **Auto-approve Criteria** - Automatic approval based on npm stats (downloads, stars)
122
- - [ ] **CLI Tool** - Command-line interface for rule management
123
- - [ ] **Visual Studio Code Extension** - IDE integration
124
- - [ ] **GitHub Action** - CI/CD integration
101
+ ### 🔮 Roadmap
102
+
103
+ #### Planned
104
+ - [ ] **Package signature verification** - check npm registry signatures and provenance attestations
105
+ - [ ] **Typosquatting detection** - flag names within a small edit distance of popular packages
106
+
107
+ #### Under consideration
108
+ These wait for a concrete request:
109
+ - **Snyk integration** - OSV already includes GitHub Security Advisories, so a second source only helps if it knows more
110
+ - **Auto-approve criteria** - approve by npm statistics; needs external requests on the request path
111
+ - **CLI tool** and **GitHub Action** for checking a rule set outside Verdaccio
112
+
113
+ #### Done
114
+ - [x] **Dry-run mode** - `dryRun: true`
115
+ - [x] **Webhook notifications** - `webhook`: block events as JSON or as a Slack message
116
+
117
+ #### Not planned
118
+ - **Rate limiting** and **multi-registry fallback** - Verdaccio already provides both (`rateLimit`, uplinks)
119
+ - **Dependency depth limits** and **circular dependency detection** - they need the whole dependency tree resolved inside the proxy on every request
120
+ - **Web dashboard**, **ML-based anomaly detection**, **VS Code extension**, **PDF audit reports**, **custom validation scripts** - outside the scope of a filter plugin; the JSON metrics output is the integration point
125
121
 
126
122
  ## 📦 Installation
127
123
 
@@ -422,7 +418,7 @@ While it is on:
422
418
  - every check runs as usual, including CVE lookups
423
419
  - nothing is blocked: metadata is served unchanged and every tarball can be downloaded
424
420
  - each decision is logged at `warn` with a `[DRY RUN]` marker, followed by a summary such as `lodash: would remove 115 of 117 version(s)`
425
- - metrics events carry `"dryRun": true`
421
+ - metrics events and [webhook notifications](#webhook-options) carry `"dryRun": true`
426
422
  - one warning at start-up says that dry-run is active
427
423
 
428
424
  Recommended before turning on `cveCheck.autoBlock`, a license policy or the author filter on a registry that is already in use.
@@ -488,6 +484,71 @@ The license check runs when `licenses.allowed` or `licenses.blocked` is not empt
488
484
  | `metrics.output` | `string` | `stdout` | Output: `stdout` or `file` |
489
485
  | `metrics.filePath` | `string` | `./security-metrics.json` | Metrics file path |
490
486
 
487
+ ### Webhook Options
488
+
489
+ Sends every block event to an HTTP endpoint. It does not depend on `metrics.enabled`.
490
+
491
+ | Option | Type | Default | Description |
492
+ |--------|------|---------|-------------|
493
+ | `webhook.enabled` | `boolean` | `false` | Enable webhook notifications |
494
+ | `webhook.url` | `string` | - | Endpoint that receives a `POST` with a JSON body |
495
+ | `webhook.format` | `string` | `json` | `json`: the events as they are. `slack`: a `{ "text": ... }` message for Slack incoming webhooks and services that accept the same body (Mattermost, Rocket.Chat, Discord's `/slack` endpoint) |
496
+ | `webhook.headers` | `object` | `{}` | Extra request headers, for example `Authorization` |
497
+ | `webhook.timeoutMs` | `number` | `5000` | Timeout of one delivery attempt |
498
+ | `webhook.repeatIntervalMinutes` | `number` | `60` | The same event is sent at most once per interval; `0` sends every occurrence |
499
+
500
+ ```yaml
501
+ webhook:
502
+ enabled: true
503
+ url: ${SECURITY_WEBHOOK_URL}
504
+ format: slack
505
+ ```
506
+
507
+ ```yaml
508
+ webhook:
509
+ enabled: true
510
+ url: https://alerts.example.com/hooks/verdaccio
511
+ headers:
512
+ Authorization: Bearer ${SECURITY_WEBHOOK_TOKEN}
513
+ ```
514
+
515
+ **Secrets.** `${NAME}` in `url` and in header values is replaced with the environment variable `NAME`, so a token does not have to be written into `config.yaml`. If a referenced variable is not set, the webhook stays off and the log says which one. Log messages name only the host of the endpoint, never the full URL.
516
+
517
+ **Delivery.** Events are collected for 5 seconds and sent as one request, so a burst of blocks becomes one message. Sending happens in the background and never delays a response to npm. A failed request is retried twice (after 1 and 4 seconds) on network errors, `429` and `5xx`; after that the batch is dropped with a warning in the log. At most 1000 events wait for an endpoint that does not answer.
518
+
519
+ **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.
520
+
521
+ **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.
522
+
523
+ The `json` body. Each entry of `events` has the fields described in [Metrics & Monitoring](#-metrics--monitoring):
524
+
525
+ ```json
526
+ {
527
+ "source": "verdaccio-security-filter",
528
+ "version": "1.5.0",
529
+ "sentAt": "2026-01-15T10:30:05.000Z",
530
+ "events": [
531
+ {
532
+ "timestamp": "2026-01-15T10:30:00.000Z",
533
+ "event": "block",
534
+ "packageName": "evil-pkg",
535
+ "version": "*",
536
+ "reason": "Package name matches blocked pattern"
537
+ }
538
+ ]
539
+ }
540
+ ```
541
+
542
+ `dropped` is added when earlier events were discarded because the queue was full.
543
+
544
+ The `slack` body:
545
+
546
+ ```json
547
+ {
548
+ "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)"
549
+ }
550
+ ```
551
+
491
552
  ### Package Age Options
492
553
 
493
554
  | Option | Type | Default | Description |
package/build/index.d.ts CHANGED
@@ -8,6 +8,7 @@ export default class SecurityFilterPlugin implements IPluginMiddleware<SecurityC
8
8
  private readonly securityRules;
9
9
  private readonly blockedPatternRegexes;
10
10
  private readonly metrics;
11
+ private readonly webhook;
11
12
  private readonly whitelistChecker;
12
13
  private readonly cveChecker;
13
14
  private readonly licenseChecker;
@@ -33,6 +34,7 @@ export default class SecurityFilterPlugin implements IPluginMiddleware<SecurityC
33
34
  }
34
35
  export { SecurityLogger } from './lib/logger';
35
36
  export { MetricsCollector } from './lib/metrics';
37
+ export { WebhookNotifier } from './lib/webhook';
36
38
  export { WhitelistChecker } from './lib/whitelist-checker';
37
39
  export { CVEChecker } from './lib/cve-checker';
38
40
  export { LicenseChecker } from './lib/license-checker';
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.AuthorChecker = exports.PackageAgeChecker = exports.LicenseChecker = exports.CVEChecker = exports.WhitelistChecker = exports.MetricsCollector = exports.SecurityLogger = void 0;
48
+ 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,6 +57,7 @@ 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 lru_cache_1 = require("./lib/lru-cache");
60
+ const webhook_1 = require("./lib/webhook");
60
61
  const PLUGIN_VERSION = JSON.parse((0, fs_1.readFileSync)((0, path_1.join)(__dirname, '..', 'package.json'), 'utf8')).version;
61
62
  const filterBlocks = new lru_cache_1.LRUCache(1000);
62
63
  function forbiddenBody(packageName, reason, extra = {}) {
@@ -72,7 +73,8 @@ class SecurityFilterPlugin {
72
73
  };
73
74
  }
74
75
  this.logger = new logger_1.SecurityLogger(options.logger, this.config.logger, !!this.config.dryRun);
75
- this.metrics = new metrics_1.MetricsCollector(this.config.metrics, !!this.config.dryRun, this.logger);
76
+ this.webhook = new webhook_1.WebhookNotifier(this.config.webhook, PLUGIN_VERSION, this.logger);
77
+ this.metrics = new metrics_1.MetricsCollector(this.config.metrics, !!this.config.dryRun, this.logger, this.webhook);
76
78
  this.whitelistChecker = new whitelist_checker_1.WhitelistChecker(this.config.whitelist, this.logger);
77
79
  this.cveChecker = new cve_checker_1.CVEChecker(this.config.cveCheck, this.logger);
78
80
  this.licenseChecker = new license_checker_1.LicenseChecker(this.config.licenses);
@@ -136,6 +138,9 @@ class SecurityFilterPlugin {
136
138
  this.logger.debug(` ${rule.package} ${rule.range} [${rule.strategy}${fallback}]`);
137
139
  });
138
140
  }
141
+ if (this.webhook.enabled) {
142
+ this.logger.info(`Webhook notifications enabled: ${this.webhook.destination}`);
143
+ }
139
144
  if (this.config.mode === 'whitelist') {
140
145
  const summary = this.whitelistChecker.getSummary();
141
146
  this.logger.info(`Whitelist mode: ${summary.totalPackages} packages, ${summary.totalPatterns} patterns`);
@@ -154,6 +159,8 @@ class SecurityFilterPlugin {
154
159
  features.push('whitelist-mode');
155
160
  if ((_a = this.config.metrics) === null || _a === void 0 ? void 0 : _a.enabled)
156
161
  features.push('metrics');
162
+ if (this.webhook.enabled)
163
+ features.push('webhook');
157
164
  if ((_b = this.config.cveCheck) === null || _b === void 0 ? void 0 : _b.enabled)
158
165
  features.push('cve-checking');
159
166
  if (this.licenseChecker.enabled)
@@ -248,6 +255,7 @@ class SecurityFilterPlugin {
248
255
  const blockResult = yield this._checkPackageBlock(packageName);
249
256
  if (blockResult.blocked) {
250
257
  this.logger.warn(`[Middleware] [X] BLOCKED METADATA: ${packageName} - ${blockResult.reason}`);
258
+ this.metrics.recordBlock(packageName, '*', blockResult.reason);
251
259
  if (this.config.dryRun) {
252
260
  return next();
253
261
  }
@@ -561,6 +569,8 @@ var logger_2 = require("./lib/logger");
561
569
  Object.defineProperty(exports, "SecurityLogger", { enumerable: true, get: function () { return logger_2.SecurityLogger; } });
562
570
  var metrics_2 = require("./lib/metrics");
563
571
  Object.defineProperty(exports, "MetricsCollector", { enumerable: true, get: function () { return metrics_2.MetricsCollector; } });
572
+ var webhook_2 = require("./lib/webhook");
573
+ Object.defineProperty(exports, "WebhookNotifier", { enumerable: true, get: function () { return webhook_2.WebhookNotifier; } });
564
574
  var whitelist_checker_2 = require("./lib/whitelist-checker");
565
575
  Object.defineProperty(exports, "WhitelistChecker", { enumerable: true, get: function () { return whitelist_checker_2.WhitelistChecker; } });
566
576
  var cve_checker_2 = require("./lib/cve-checker");
@@ -1,8 +1,10 @@
1
1
  import { MetricsConfig, MetricsData } from '../types';
2
2
  import { CheckerLog } from './logger';
3
+ import { WebhookNotifier } from './webhook';
3
4
  export declare class MetricsCollector {
4
5
  private readonly dryRun;
5
6
  private readonly log;
7
+ private readonly webhook?;
6
8
  private config;
7
9
  private metricsBuffer;
8
10
  private readonly bufferSize;
@@ -12,7 +14,7 @@ export declare class MetricsCollector {
12
14
  private readonly filteredRepeatMs;
13
15
  private recentlyFiltered;
14
16
  private counts;
15
- constructor(config?: MetricsConfig, dryRun?: boolean, log?: CheckerLog);
17
+ constructor(config?: MetricsConfig, dryRun?: boolean, log?: CheckerLog, webhook?: WebhookNotifier | undefined);
16
18
  record(event: MetricsData): void;
17
19
  recordBlock(packageName: string, version: string, reason: string, metadata?: Record<string, any>): void;
18
20
  recordFiltered(packageName: string, versions: string[], reason: string, event?: MetricsData['event'], metadata?: Record<string, any>): void;
@@ -38,9 +38,10 @@ const fs = __importStar(require("fs"));
38
38
  const path = __importStar(require("path"));
39
39
  const lru_cache_1 = require("./lru-cache");
40
40
  class MetricsCollector {
41
- constructor(config, dryRun = false, log = console) {
41
+ constructor(config, dryRun = false, log = console, webhook) {
42
42
  this.dryRun = dryRun;
43
43
  this.log = log;
44
+ this.webhook = webhook;
44
45
  this.metricsBuffer = [];
45
46
  this.bufferSize = 100;
46
47
  this.maxBufferSize = 500;
@@ -60,6 +61,9 @@ class MetricsCollector {
60
61
  }
61
62
  }
62
63
  record(event) {
64
+ var _a;
65
+ const recorded = this.dryRun ? Object.assign(Object.assign({}, event), { dryRun: true }) : event;
66
+ (_a = this.webhook) === null || _a === void 0 ? void 0 : _a.notify(recorded);
63
67
  if (!this.config.enabled) {
64
68
  return;
65
69
  }
@@ -67,7 +71,7 @@ class MetricsCollector {
67
71
  this.flush();
68
72
  }
69
73
  this.counts[event.event] = (this.counts[event.event] || 0) + 1;
70
- this.metricsBuffer.push(this.dryRun ? Object.assign(Object.assign({}, event), { dryRun: true }) : event);
74
+ this.metricsBuffer.push(recorded);
71
75
  if (this.metricsBuffer.length >= this.bufferSize) {
72
76
  this.flush();
73
77
  }
@@ -83,13 +87,13 @@ class MetricsCollector {
83
87
  });
84
88
  }
85
89
  recordFiltered(packageName, versions, reason, event = 'block', metadata = {}) {
86
- var _a;
87
- if (!this.config.enabled || versions.length === 0) {
90
+ var _a, _b;
91
+ if ((!this.config.enabled && !((_a = this.webhook) === null || _a === void 0 ? void 0 : _a.enabled)) || versions.length === 0) {
88
92
  return;
89
93
  }
90
94
  const key = `${event}|${packageName}|${reason}|${versions.join(',')}`;
91
95
  const now = Date.now();
92
- if (now - ((_a = this.recentlyFiltered.get(key)) !== null && _a !== void 0 ? _a : -Infinity) < this.filteredRepeatMs) {
96
+ if (now - ((_b = this.recentlyFiltered.get(key)) !== null && _b !== void 0 ? _b : -Infinity) < this.filteredRepeatMs) {
93
97
  return;
94
98
  }
95
99
  this.recentlyFiltered.set(key, now);
@@ -134,6 +138,8 @@ class MetricsCollector {
134
138
  return Object.assign({}, this.counts);
135
139
  }
136
140
  cleanup() {
141
+ var _a;
142
+ (_a = this.webhook) === null || _a === void 0 ? void 0 : _a.cleanup();
137
143
  if (this.flushTimer) {
138
144
  clearInterval(this.flushTimer);
139
145
  this.flushTimer = null;
@@ -0,0 +1,27 @@
1
+ import { MetricsData, WebhookConfig } from '../types';
2
+ import { CheckerLog } from './logger';
3
+ export declare function expandEnv(value: string, env?: NodeJS.ProcessEnv): string;
4
+ export declare function formatSlackText(events: MetricsData[], dropped?: number): string;
5
+ export declare class WebhookNotifier {
6
+ private readonly pluginVersion;
7
+ private readonly log;
8
+ private readonly url;
9
+ private readonly host;
10
+ private readonly format;
11
+ private readonly headers;
12
+ private readonly timeoutMs;
13
+ private readonly repeatMs;
14
+ private readonly recent;
15
+ private queue;
16
+ private dropped;
17
+ private timer;
18
+ private draining;
19
+ constructor(config?: WebhookConfig, pluginVersion?: string, log?: CheckerLog, env?: NodeJS.ProcessEnv);
20
+ get enabled(): boolean;
21
+ get destination(): string;
22
+ notify(event: MetricsData): void;
23
+ flush(): Promise<void>;
24
+ cleanup(): void;
25
+ private drain;
26
+ private deliver;
27
+ }
@@ -0,0 +1,207 @@
1
+ "use strict";
2
+ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
3
+ function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
4
+ return new (P || (P = Promise))(function (resolve, reject) {
5
+ function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
6
+ function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
7
+ function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
8
+ step((generator = generator.apply(thisArg, _arguments || [])).next());
9
+ });
10
+ };
11
+ Object.defineProperty(exports, "__esModule", { value: true });
12
+ exports.WebhookNotifier = void 0;
13
+ exports.expandEnv = expandEnv;
14
+ exports.formatSlackText = formatSlackText;
15
+ const lru_cache_1 = require("./lru-cache");
16
+ const BATCH_DELAY_MS = 5000;
17
+ const MAX_BATCH_SIZE = 50;
18
+ const MAX_QUEUE_SIZE = 1000;
19
+ const RETRY_DELAYS_MS = [1000, 4000];
20
+ const DEFAULT_TIMEOUT_MS = 5000;
21
+ const DEFAULT_REPEAT_INTERVAL_MINUTES = 60;
22
+ const SLACK_MAX_LINES = 20;
23
+ const SLACK_MAX_VERSIONS = 10;
24
+ class PermanentDeliveryError extends Error {
25
+ }
26
+ function expandEnv(value, env = process.env) {
27
+ return value.replace(/\$\{([A-Za-z_][A-Za-z0-9_]*)\}/g, (_match, name) => {
28
+ const resolved = env[name];
29
+ if (resolved === undefined || resolved === '') {
30
+ throw new Error(`environment variable ${name} is not set`);
31
+ }
32
+ return resolved;
33
+ });
34
+ }
35
+ function escapeSlack(text) {
36
+ return text.replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;').replace(/`/g, "'");
37
+ }
38
+ function describeTarget(event) {
39
+ var _a;
40
+ const name = escapeSlack(event.packageName);
41
+ const versions = (_a = event.metadata) === null || _a === void 0 ? void 0 : _a.versions;
42
+ if (!event.version && Array.isArray(versions)) {
43
+ const shown = versions.slice(0, SLACK_MAX_VERSIONS).map(version => escapeSlack(String(version))).join(', ');
44
+ const more = versions.length > SLACK_MAX_VERSIONS ? `, +${versions.length - SLACK_MAX_VERSIONS} more` : '';
45
+ return `\`${name}\` (${versions.length} version(s): ${shown}${more})`;
46
+ }
47
+ return event.version && event.version !== '*' ? `\`${name}@${escapeSlack(event.version)}\`` : `\`${name}\``;
48
+ }
49
+ function formatSlackText(events, dropped = 0) {
50
+ const lines = events.slice(0, SLACK_MAX_LINES).map(event => {
51
+ const action = event.dryRun ? '[DRY RUN] would block' : 'blocked';
52
+ return `• ${action} ${describeTarget(event)}: ${escapeSlack(event.reason)}`;
53
+ });
54
+ if (events.length > SLACK_MAX_LINES) {
55
+ lines.push(`…and ${events.length - SLACK_MAX_LINES} more event(s)`);
56
+ }
57
+ if (dropped > 0) {
58
+ lines.push(`_${dropped} earlier event(s) were dropped because the webhook was unreachable_`);
59
+ }
60
+ return [`*Verdaccio security filter*: ${events.length} event(s)`, ...lines].join('\n');
61
+ }
62
+ class WebhookNotifier {
63
+ constructor(config, pluginVersion = 'unknown', log = console, env = process.env) {
64
+ var _a;
65
+ this.pluginVersion = pluginVersion;
66
+ this.log = log;
67
+ this.url = null;
68
+ this.host = '';
69
+ this.headers = {};
70
+ this.recent = new lru_cache_1.LRUCache(5000);
71
+ this.queue = [];
72
+ this.dropped = 0;
73
+ this.timer = null;
74
+ this.draining = null;
75
+ this.format = (config === null || config === void 0 ? void 0 : config.format) === 'slack' ? 'slack' : 'json';
76
+ this.timeoutMs = (config === null || config === void 0 ? void 0 : config.timeoutMs) && config.timeoutMs > 0 ? config.timeoutMs : DEFAULT_TIMEOUT_MS;
77
+ this.repeatMs = ((_a = config === null || config === void 0 ? void 0 : config.repeatIntervalMinutes) !== null && _a !== void 0 ? _a : DEFAULT_REPEAT_INTERVAL_MINUTES) * 60000;
78
+ if (!(config === null || config === void 0 ? void 0 : config.enabled)) {
79
+ return;
80
+ }
81
+ if (config.format && config.format !== 'json' && config.format !== 'slack') {
82
+ this.log.warn(`Unknown webhook format "${config.format}", using "json"`);
83
+ }
84
+ try {
85
+ if (!config.url) {
86
+ throw new Error('webhook.url is not set');
87
+ }
88
+ const expanded = expandEnv(config.url, env);
89
+ if (!URL.canParse(expanded)) {
90
+ throw new Error('webhook.url is not a valid URL');
91
+ }
92
+ const url = new URL(expanded);
93
+ if (url.protocol !== 'https:' && url.protocol !== 'http:') {
94
+ throw new Error('webhook.url must be an http(s) URL');
95
+ }
96
+ for (const [name, value] of Object.entries(config.headers || {})) {
97
+ this.headers[name] = expandEnv(String(value), env);
98
+ }
99
+ this.url = url.toString();
100
+ this.host = url.host;
101
+ }
102
+ catch (error) {
103
+ this.log.error(`Webhook notifications are disabled: ${error.message}`);
104
+ }
105
+ }
106
+ get enabled() {
107
+ return this.url !== null;
108
+ }
109
+ get destination() {
110
+ return `${this.host} (${this.format})`;
111
+ }
112
+ notify(event) {
113
+ var _a, _b, _c;
114
+ if (!this.enabled) {
115
+ return;
116
+ }
117
+ 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
+ const key = `${event.event}|${event.packageName}|${versions}|${event.reason}|${event.dryRun ? 'dry' : ''}`;
119
+ const now = Date.now();
120
+ if (this.repeatMs > 0 && now - ((_c = this.recent.get(key)) !== null && _c !== void 0 ? _c : -Infinity) < this.repeatMs) {
121
+ return;
122
+ }
123
+ this.recent.set(key, now);
124
+ if (this.queue.length >= MAX_QUEUE_SIZE) {
125
+ this.queue.shift();
126
+ this.dropped++;
127
+ }
128
+ this.queue.push({ event, key });
129
+ if (this.queue.length >= MAX_BATCH_SIZE) {
130
+ void this.flush();
131
+ }
132
+ else if (!this.timer && !this.draining) {
133
+ this.timer = setTimeout(() => void this.flush(), BATCH_DELAY_MS);
134
+ this.timer.unref();
135
+ }
136
+ }
137
+ flush() {
138
+ if (this.timer) {
139
+ clearTimeout(this.timer);
140
+ this.timer = null;
141
+ }
142
+ if (!this.draining) {
143
+ this.draining = this.drain().finally(() => {
144
+ this.draining = null;
145
+ });
146
+ }
147
+ return this.draining;
148
+ }
149
+ cleanup() {
150
+ void this.flush();
151
+ }
152
+ drain() {
153
+ return __awaiter(this, void 0, void 0, function* () {
154
+ while (this.queue.length > 0) {
155
+ const batch = this.queue.splice(0, MAX_BATCH_SIZE);
156
+ const dropped = this.dropped;
157
+ this.dropped = 0;
158
+ try {
159
+ yield this.deliver(batch.map(item => item.event), dropped);
160
+ }
161
+ catch (error) {
162
+ batch.forEach(item => this.recent.delete(item.key));
163
+ const message = error instanceof Error ? error.message : String(error);
164
+ this.log.warn(`Webhook delivery to ${this.host} failed, ${batch.length} event(s) dropped: ${message}`);
165
+ }
166
+ }
167
+ });
168
+ }
169
+ deliver(events, dropped) {
170
+ return __awaiter(this, void 0, void 0, function* () {
171
+ var _a;
172
+ const payload = this.format === 'slack'
173
+ ? { text: formatSlackText(events, dropped) }
174
+ : Object.assign(Object.assign({ source: 'verdaccio-security-filter', version: this.pluginVersion, sentAt: new Date().toISOString() }, (dropped > 0 ? { dropped } : {})), { events });
175
+ const body = JSON.stringify(payload);
176
+ for (let attempt = 0;; attempt++) {
177
+ try {
178
+ const response = yield fetch(this.url, {
179
+ method: 'POST',
180
+ headers: Object.assign({ 'Content-Type': 'application/json', 'User-Agent': `verdaccio-security-filter/${this.pluginVersion}` }, this.headers),
181
+ body,
182
+ signal: AbortSignal.timeout(this.timeoutMs),
183
+ });
184
+ yield ((_a = response.body) === null || _a === void 0 ? void 0 : _a.cancel().catch(() => undefined));
185
+ if (response.ok) {
186
+ this.log.debug(`Webhook delivered ${events.length} event(s) to ${this.host}`);
187
+ return;
188
+ }
189
+ const failure = `HTTP ${response.status}`;
190
+ if (response.status !== 429 && response.status < 500) {
191
+ throw new PermanentDeliveryError(failure);
192
+ }
193
+ throw new Error(failure);
194
+ }
195
+ catch (error) {
196
+ if (error instanceof PermanentDeliveryError || attempt >= RETRY_DELAYS_MS.length) {
197
+ throw error;
198
+ }
199
+ yield new Promise(resolve => {
200
+ setTimeout(resolve, RETRY_DELAYS_MS[attempt]).unref();
201
+ });
202
+ }
203
+ }
204
+ });
205
+ }
206
+ }
207
+ exports.WebhookNotifier = WebhookNotifier;
package/build/types.d.ts CHANGED
@@ -34,6 +34,14 @@ export interface MetricsConfig {
34
34
  output?: 'stdout' | 'file';
35
35
  filePath?: string;
36
36
  }
37
+ export interface WebhookConfig {
38
+ enabled: boolean;
39
+ url: string;
40
+ format?: 'json' | 'slack';
41
+ headers?: Record<string, string>;
42
+ timeoutMs?: number;
43
+ repeatIntervalMinutes?: number;
44
+ }
37
45
  export interface PackageAgeConfig {
38
46
  enabled: boolean;
39
47
  minPackageAgeDays: number;
@@ -64,6 +72,7 @@ export interface SecurityConfig extends Config {
64
72
  cveCheck?: CVECheckConfig;
65
73
  logger?: LoggerConfig;
66
74
  metrics?: MetricsConfig;
75
+ webhook?: WebhookConfig;
67
76
  packageAge?: PackageAgeConfig;
68
77
  authorFilter?: AuthorFilterConfig;
69
78
  errorHandling?: {
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "verdaccio-security-filter",
3
- "version": "1.4.4",
3
+ "version": "1.5.0",
4
4
  "description": "Advanced security filter plugin for Verdaccio with version range blocking and fallback strategies",
5
5
  "main": "build/index.js",
6
6
  "types": "build/index.d.ts",