verdaccio-security-filter 1.4.4 → 1.5.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 +88 -28
- package/build/index.d.ts +2 -0
- package/build/index.js +12 -2
- package/build/lib/metrics.d.ts +3 -1
- package/build/lib/metrics.js +11 -5
- package/build/lib/webhook.d.ts +27 -0
- package/build/lib/webhook.js +207 -0
- package/build/types.d.ts +9 -0
- package/package.json +13 -4
package/README.md
CHANGED
|
@@ -6,9 +6,8 @@ Advanced security filter plugin for Verdaccio with **dual-layer protection archi
|
|
|
6
6
|
[](https://www.npmjs.com/package/verdaccio-security-filter)
|
|
7
7
|
[](https://www.npmjs.com/package/verdaccio-security-filter)
|
|
8
8
|
[](https://github.com/ponomarenko/verdaccio-security-filter/actions/workflows/ci.yml)
|
|
9
|
-
[](./tests)
|
|
10
9
|
[]()
|
|
11
|
-
[](./package.json)
|
|
12
11
|
[]()
|
|
13
12
|
|
|
14
13
|
## 🏗️ Dual-Layer Architecture
|
|
@@ -61,6 +60,7 @@ This plugin implements **two independent security layers** for complete protecti
|
|
|
61
60
|
#### 📊 Monitoring & Observability
|
|
62
61
|
- **Enhanced Logging** - Configurable log levels (`debug`, `info`, `warn`, `error`)
|
|
63
62
|
- **Metrics Collection** - Track security events (blocks with their reason, author blocks)
|
|
63
|
+
- **Webhook Notifications** - POST block events to any HTTP endpoint or a Slack-compatible incoming webhook
|
|
64
64
|
- **Security Audit Trail** - Detailed logging of all security decisions
|
|
65
65
|
- **Customizable Output** - Log to stdout or file in JSON format
|
|
66
66
|
|
|
@@ -97,31 +97,26 @@ This plugin implements **two independent security layers** for complete protecti
|
|
|
97
97
|
- API timeout protection
|
|
98
98
|
- Graceful degradation on errors
|
|
99
99
|
|
|
100
|
-
### 🔮
|
|
101
|
-
|
|
102
|
-
####
|
|
103
|
-
- [ ] **
|
|
104
|
-
- [ ] **
|
|
105
|
-
|
|
106
|
-
|
|
107
|
-
|
|
108
|
-
-
|
|
109
|
-
|
|
110
|
-
|
|
111
|
-
|
|
112
|
-
|
|
113
|
-
- [
|
|
114
|
-
- [
|
|
115
|
-
|
|
116
|
-
|
|
117
|
-
-
|
|
118
|
-
|
|
119
|
-
|
|
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
|
|
100
|
+
### 🔮 Roadmap
|
|
101
|
+
|
|
102
|
+
#### Planned
|
|
103
|
+
- [ ] **Package signature verification** - check npm registry signatures and provenance attestations
|
|
104
|
+
- [ ] **Typosquatting detection** - flag names within a small edit distance of popular packages
|
|
105
|
+
|
|
106
|
+
#### Under consideration
|
|
107
|
+
These wait for a concrete request:
|
|
108
|
+
- **Snyk integration** - OSV already includes GitHub Security Advisories, so a second source only helps if it knows more
|
|
109
|
+
- **Auto-approve criteria** - approve by npm statistics; needs external requests on the request path
|
|
110
|
+
- **CLI tool** and **GitHub Action** for checking a rule set outside Verdaccio
|
|
111
|
+
|
|
112
|
+
#### Done
|
|
113
|
+
- [x] **Dry-run mode** - `dryRun: true`
|
|
114
|
+
- [x] **Webhook notifications** - `webhook`: block events as JSON or as a Slack message
|
|
115
|
+
|
|
116
|
+
#### Not planned
|
|
117
|
+
- **Rate limiting** and **multi-registry fallback** - Verdaccio already provides both (`rateLimit`, uplinks)
|
|
118
|
+
- **Dependency depth limits** and **circular dependency detection** - they need the whole dependency tree resolved inside the proxy on every request
|
|
119
|
+
- **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
120
|
|
|
126
121
|
## 📦 Installation
|
|
127
122
|
|
|
@@ -422,7 +417,7 @@ While it is on:
|
|
|
422
417
|
- every check runs as usual, including CVE lookups
|
|
423
418
|
- nothing is blocked: metadata is served unchanged and every tarball can be downloaded
|
|
424
419
|
- 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`
|
|
420
|
+
- metrics events and [webhook notifications](#webhook-options) carry `"dryRun": true`
|
|
426
421
|
- one warning at start-up says that dry-run is active
|
|
427
422
|
|
|
428
423
|
Recommended before turning on `cveCheck.autoBlock`, a license policy or the author filter on a registry that is already in use.
|
|
@@ -488,6 +483,71 @@ The license check runs when `licenses.allowed` or `licenses.blocked` is not empt
|
|
|
488
483
|
| `metrics.output` | `string` | `stdout` | Output: `stdout` or `file` |
|
|
489
484
|
| `metrics.filePath` | `string` | `./security-metrics.json` | Metrics file path |
|
|
490
485
|
|
|
486
|
+
### Webhook Options
|
|
487
|
+
|
|
488
|
+
Sends every block event to an HTTP endpoint. It does not depend on `metrics.enabled`.
|
|
489
|
+
|
|
490
|
+
| Option | Type | Default | Description |
|
|
491
|
+
|--------|------|---------|-------------|
|
|
492
|
+
| `webhook.enabled` | `boolean` | `false` | Enable webhook notifications |
|
|
493
|
+
| `webhook.url` | `string` | - | Endpoint that receives a `POST` with a JSON body |
|
|
494
|
+
| `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) |
|
|
495
|
+
| `webhook.headers` | `object` | `{}` | Extra request headers, for example `Authorization` |
|
|
496
|
+
| `webhook.timeoutMs` | `number` | `5000` | Timeout of one delivery attempt |
|
|
497
|
+
| `webhook.repeatIntervalMinutes` | `number` | `60` | The same event is sent at most once per interval; `0` sends every occurrence |
|
|
498
|
+
|
|
499
|
+
```yaml
|
|
500
|
+
webhook:
|
|
501
|
+
enabled: true
|
|
502
|
+
url: ${SECURITY_WEBHOOK_URL}
|
|
503
|
+
format: slack
|
|
504
|
+
```
|
|
505
|
+
|
|
506
|
+
```yaml
|
|
507
|
+
webhook:
|
|
508
|
+
enabled: true
|
|
509
|
+
url: https://alerts.example.com/hooks/verdaccio
|
|
510
|
+
headers:
|
|
511
|
+
Authorization: Bearer ${SECURITY_WEBHOOK_TOKEN}
|
|
512
|
+
```
|
|
513
|
+
|
|
514
|
+
**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.
|
|
515
|
+
|
|
516
|
+
**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.
|
|
517
|
+
|
|
518
|
+
**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.
|
|
519
|
+
|
|
520
|
+
**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.
|
|
521
|
+
|
|
522
|
+
The `json` body. Each entry of `events` has the fields described in [Metrics & Monitoring](#-metrics--monitoring):
|
|
523
|
+
|
|
524
|
+
```json
|
|
525
|
+
{
|
|
526
|
+
"source": "verdaccio-security-filter",
|
|
527
|
+
"version": "1.5.0",
|
|
528
|
+
"sentAt": "2026-01-15T10:30:05.000Z",
|
|
529
|
+
"events": [
|
|
530
|
+
{
|
|
531
|
+
"timestamp": "2026-01-15T10:30:00.000Z",
|
|
532
|
+
"event": "block",
|
|
533
|
+
"packageName": "evil-pkg",
|
|
534
|
+
"version": "*",
|
|
535
|
+
"reason": "Package name matches blocked pattern"
|
|
536
|
+
}
|
|
537
|
+
]
|
|
538
|
+
}
|
|
539
|
+
```
|
|
540
|
+
|
|
541
|
+
`dropped` is added when earlier events were discarded because the queue was full.
|
|
542
|
+
|
|
543
|
+
The `slack` body:
|
|
544
|
+
|
|
545
|
+
```json
|
|
546
|
+
{
|
|
547
|
+
"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)"
|
|
548
|
+
}
|
|
549
|
+
```
|
|
550
|
+
|
|
491
551
|
### Package Age Options
|
|
492
552
|
|
|
493
553
|
| 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.
|
|
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");
|
package/build/lib/metrics.d.ts
CHANGED
|
@@ -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;
|
package/build/lib/metrics.js
CHANGED
|
@@ -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(
|
|
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 - ((
|
|
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, '&').replace(/</g, '<').replace(/>/g, '>').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,19 +1,28 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "verdaccio-security-filter",
|
|
3
|
-
"version": "1.
|
|
4
|
-
"description": "
|
|
3
|
+
"version": "1.5.1",
|
|
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",
|
|
7
7
|
"keywords": [
|
|
8
8
|
"verdaccio",
|
|
9
|
+
"verdaccio-plugin",
|
|
9
10
|
"plugin",
|
|
10
|
-
"filter",
|
|
11
11
|
"security",
|
|
12
12
|
"npm",
|
|
13
|
+
"npm-security",
|
|
13
14
|
"registry",
|
|
15
|
+
"private-registry",
|
|
16
|
+
"npm-proxy",
|
|
17
|
+
"supply-chain",
|
|
18
|
+
"supply-chain-security",
|
|
14
19
|
"vulnerability",
|
|
20
|
+
"cve",
|
|
21
|
+
"osv",
|
|
22
|
+
"malware",
|
|
23
|
+
"license-compliance",
|
|
15
24
|
"semver",
|
|
16
|
-
"
|
|
25
|
+
"filter"
|
|
17
26
|
],
|
|
18
27
|
"publishConfig": {
|
|
19
28
|
"access": "public"
|