@multiplier-labs/stepflow 0.3.3 → 0.3.6
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 +9 -0
- package/dist/{chunk-GYPNJBDP.js → chunk-D5HW7VEG.js} +269 -48
- package/dist/chunk-D5HW7VEG.js.map +1 -0
- package/dist/{chunk-KHTUWLVZ.js → chunk-FMPJBK2N.js} +55 -10
- package/dist/chunk-FMPJBK2N.js.map +1 -0
- package/dist/{chunk-ML35PIHX.js → chunk-JPXPB7U5.js} +52 -2
- package/dist/chunk-JPXPB7U5.js.map +1 -0
- package/dist/{chunk-4VOKMGP6.js → chunk-JUPZEBR3.js} +519 -522
- package/dist/chunk-JUPZEBR3.js.map +1 -0
- package/dist/events/index.d.ts +58 -3
- package/dist/events/index.js +1 -1
- package/dist/{index-Dzr437iW.d.ts → index-Cd0IZ40L.d.ts} +50 -11
- package/dist/index.d.ts +2 -12
- package/dist/index.js +764 -485
- package/dist/index.js.map +1 -1
- package/dist/scheduler/index.d.ts +1 -1
- package/dist/scheduler/index.js +2 -2
- package/dist/storage/index.d.ts +313 -47
- package/dist/storage/index.js +4 -2
- package/package.json +27 -13
- package/.codekin/reports/comments/2026-04-04_comment-assessment.md +0 -179
- package/.codekin/reports/complexity/2026-04-03_complexity-report.md +0 -152
- package/.codekin/reports/dependencies/2026-04-04_dependency-health.md +0 -94
- package/.codekin/reports/docs-audit/2026-04-04_docs-audit.md +0 -10
- package/.codekin/reports/security/2026-04-03_security-audit.md +0 -208
- package/.github/CODEOWNERS +0 -15
- package/.github/dependabot.yml +0 -23
- package/.github/workflows/ci.yml +0 -38
- package/.github/workflows/publish.yml +0 -36
- package/.github/workflows/security.yml +0 -29
- package/CHANGELOG.md +0 -34
- package/SECURITY.md +0 -40
- package/dist/chunk-4VOKMGP6.js.map +0 -1
- package/dist/chunk-GYPNJBDP.js.map +0 -1
- package/dist/chunk-KHTUWLVZ.js.map +0 -1
- package/dist/chunk-ML35PIHX.js.map +0 -1
- package/docs/github-packages-setup.md +0 -97
- package/docs/stepflow-api-reference.md +0 -1661
- package/src/core/engine.test.ts +0 -1365
- package/src/core/engine.ts +0 -692
- package/src/core/index.ts +0 -7
- package/src/core/orchestrator.ts +0 -571
- package/src/core/types.ts +0 -220
- package/src/events/index.ts +0 -8
- package/src/events/memory.test.ts +0 -107
- package/src/events/memory.ts +0 -92
- package/src/events/socketio.test.ts +0 -378
- package/src/events/socketio.ts +0 -262
- package/src/events/types.ts +0 -118
- package/src/events/webhook.test.ts +0 -657
- package/src/events/webhook.ts +0 -564
- package/src/index.ts +0 -270
- package/src/planning/index.ts +0 -55
- package/src/planning/planner.ts +0 -576
- package/src/planning/planning.test.ts +0 -727
- package/src/planning/registry.test.ts +0 -398
- package/src/planning/registry.ts +0 -365
- package/src/planning/types.ts +0 -566
- package/src/scheduler/cron.test.ts +0 -471
- package/src/scheduler/cron.ts +0 -414
- package/src/scheduler/index.ts +0 -8
- package/src/scheduler/postgres-persistence.ts +0 -518
- package/src/scheduler/sqlite-persistence.test.ts +0 -235
- package/src/scheduler/sqlite-persistence.ts +0 -261
- package/src/scheduler/types.ts +0 -73
- package/src/storage/index.ts +0 -27
- package/src/storage/memory.test.ts +0 -349
- package/src/storage/memory.ts +0 -227
- package/src/storage/postgres.ts +0 -1354
- package/src/storage/sqlite.test.ts +0 -466
- package/src/storage/sqlite.ts +0 -627
- package/src/storage/types.ts +0 -343
- package/src/utils/errors.test.ts +0 -150
- package/src/utils/errors.ts +0 -161
- package/src/utils/id.ts +0 -21
- package/src/utils/index.ts +0 -8
- package/src/utils/logger.test.ts +0 -121
- package/src/utils/logger.ts +0 -96
- package/src/utils/postgres-deps.ts +0 -63
- package/src/utils/retry.test.ts +0 -177
- package/src/utils/retry.ts +0 -121
- package/tsconfig.json +0 -21
- package/tsup.config.ts +0 -14
- package/vitest.config.ts +0 -9
package/src/events/webhook.ts
DELETED
|
@@ -1,564 +0,0 @@
|
|
|
1
|
-
/**
|
|
2
|
-
* Webhook Event Transport
|
|
3
|
-
*
|
|
4
|
-
* Posts workflow events to HTTP endpoints via webhooks.
|
|
5
|
-
* Supports multiple webhooks with optional filtering by event type.
|
|
6
|
-
*/
|
|
7
|
-
|
|
8
|
-
import { promises as dns } from 'node:dns';
|
|
9
|
-
import type { EventTransport, EventCallback, Unsubscribe, WorkflowEvent, WorkflowEventType } from './types';
|
|
10
|
-
import type { Logger } from '../core/types';
|
|
11
|
-
|
|
12
|
-
/**
|
|
13
|
-
* Webhook endpoint configuration.
|
|
14
|
-
*/
|
|
15
|
-
export interface WebhookEndpoint {
|
|
16
|
-
/** Unique identifier for this endpoint */
|
|
17
|
-
id: string;
|
|
18
|
-
|
|
19
|
-
/** URL to POST events to */
|
|
20
|
-
url: string;
|
|
21
|
-
|
|
22
|
-
/** Optional secret for signing payloads (HMAC-SHA256) */
|
|
23
|
-
secret?: string;
|
|
24
|
-
|
|
25
|
-
/** Optional filter for specific event types (empty = all events) */
|
|
26
|
-
eventTypes?: WorkflowEventType[];
|
|
27
|
-
|
|
28
|
-
/** Optional filter for specific workflow kinds (empty = all kinds) */
|
|
29
|
-
workflowKinds?: string[];
|
|
30
|
-
|
|
31
|
-
/** Optional custom headers to include */
|
|
32
|
-
headers?: Record<string, string>;
|
|
33
|
-
|
|
34
|
-
/** Whether this endpoint is enabled (default: true) */
|
|
35
|
-
enabled?: boolean;
|
|
36
|
-
|
|
37
|
-
/** Timeout in milliseconds (default: 5000) */
|
|
38
|
-
timeout?: number;
|
|
39
|
-
|
|
40
|
-
/** Number of retry attempts on failure (default: 3) */
|
|
41
|
-
retries?: number;
|
|
42
|
-
}
|
|
43
|
-
|
|
44
|
-
/**
|
|
45
|
-
* Configuration for WebhookEventTransport.
|
|
46
|
-
*/
|
|
47
|
-
export interface WebhookEventTransportConfig {
|
|
48
|
-
/** Initial webhook endpoints */
|
|
49
|
-
endpoints?: WebhookEndpoint[];
|
|
50
|
-
|
|
51
|
-
/** Default timeout for all webhooks in ms (default: 5000) */
|
|
52
|
-
defaultTimeout?: number;
|
|
53
|
-
|
|
54
|
-
/** Default retry attempts (default: 3) */
|
|
55
|
-
defaultRetries?: number;
|
|
56
|
-
|
|
57
|
-
/** Retry delay in ms (default: 1000) */
|
|
58
|
-
retryDelay?: number;
|
|
59
|
-
|
|
60
|
-
/** Custom fetch function (for testing or custom HTTP clients) */
|
|
61
|
-
fetchFn?: typeof fetch;
|
|
62
|
-
|
|
63
|
-
/**
|
|
64
|
-
* Whether to allow non-HTTPS URLs (default: false).
|
|
65
|
-
* Set to true only in development environments.
|
|
66
|
-
*/
|
|
67
|
-
allowInsecureUrls?: boolean;
|
|
68
|
-
|
|
69
|
-
/**
|
|
70
|
-
* Maximum payload size in bytes (default: 1048576 = 1 MB).
|
|
71
|
-
* Payloads exceeding this limit will be rejected.
|
|
72
|
-
*/
|
|
73
|
-
maxPayloadBytes?: number;
|
|
74
|
-
|
|
75
|
-
/**
|
|
76
|
-
* Maximum concurrent webhook requests across all endpoints (default: 50).
|
|
77
|
-
* Requests beyond this limit are queued.
|
|
78
|
-
*/
|
|
79
|
-
maxConcurrentRequests?: number;
|
|
80
|
-
|
|
81
|
-
/** Logger for webhook transport errors (default: console-based) */
|
|
82
|
-
logger?: import('../core/types').Logger;
|
|
83
|
-
}
|
|
84
|
-
|
|
85
|
-
/**
|
|
86
|
-
* Webhook payload structure sent to external endpoints.
|
|
87
|
-
*/
|
|
88
|
-
export interface WebhookPayload {
|
|
89
|
-
/**
|
|
90
|
-
* The workflow event with `timestamp` serialized as an ISO 8601 string.
|
|
91
|
-
* The `Date` is converted to a string before delivery so that JSON consumers
|
|
92
|
-
* receive a portable, timezone-aware representation without needing Date parsing.
|
|
93
|
-
*/
|
|
94
|
-
event: Omit<WorkflowEvent, 'timestamp'> & { timestamp: string };
|
|
95
|
-
/** ISO 8601 timestamp of when this payload was delivered. */
|
|
96
|
-
deliveredAt: string;
|
|
97
|
-
/** ID of the webhook endpoint that received this delivery. */
|
|
98
|
-
webhookId: string;
|
|
99
|
-
}
|
|
100
|
-
|
|
101
|
-
/**
|
|
102
|
-
* Webhook-based event transport for integrating with external systems.
|
|
103
|
-
*
|
|
104
|
-
* @example
|
|
105
|
-
* ```typescript
|
|
106
|
-
* const webhookTransport = new WebhookEventTransport({
|
|
107
|
-
* endpoints: [
|
|
108
|
-
* {
|
|
109
|
-
* id: 'slack-notifications',
|
|
110
|
-
* url: 'https://hooks.slack.com/...',
|
|
111
|
-
* eventTypes: ['run.completed', 'run.failed'],
|
|
112
|
-
* },
|
|
113
|
-
* {
|
|
114
|
-
* id: 'analytics',
|
|
115
|
-
* url: 'https://api.analytics.com/events',
|
|
116
|
-
* secret: process.env.WEBHOOK_SECRET, // Use a cryptographically random secret (≥ 32 bytes)
|
|
117
|
-
* },
|
|
118
|
-
* ],
|
|
119
|
-
* });
|
|
120
|
-
*
|
|
121
|
-
* const engine = new WorkflowEngine({
|
|
122
|
-
* storage,
|
|
123
|
-
* events: webhookTransport,
|
|
124
|
-
* });
|
|
125
|
-
* ```
|
|
126
|
-
*/
|
|
127
|
-
export class WebhookEventTransport implements EventTransport {
|
|
128
|
-
private endpoints = new Map<string, WebhookEndpoint>();
|
|
129
|
-
private defaultTimeout: number;
|
|
130
|
-
private defaultRetries: number;
|
|
131
|
-
private retryDelay: number;
|
|
132
|
-
private fetchFn: typeof fetch;
|
|
133
|
-
private allowInsecureUrls: boolean;
|
|
134
|
-
private maxPayloadBytes: number;
|
|
135
|
-
private maxConcurrentRequests: number;
|
|
136
|
-
private activeRequests = 0;
|
|
137
|
-
private requestQueue: Array<() => void> = [];
|
|
138
|
-
private logger: Logger;
|
|
139
|
-
|
|
140
|
-
// Local subscribers for server-side subscriptions
|
|
141
|
-
private runSubscribers = new Map<string, Set<EventCallback>>();
|
|
142
|
-
private globalSubscribers = new Set<EventCallback>();
|
|
143
|
-
|
|
144
|
-
constructor(config: WebhookEventTransportConfig = {}) {
|
|
145
|
-
this.defaultTimeout = config.defaultTimeout ?? 5000;
|
|
146
|
-
this.defaultRetries = config.defaultRetries ?? 3;
|
|
147
|
-
this.retryDelay = config.retryDelay ?? 1000;
|
|
148
|
-
this.fetchFn = config.fetchFn ?? globalThis.fetch;
|
|
149
|
-
this.allowInsecureUrls = config.allowInsecureUrls ?? false;
|
|
150
|
-
this.maxPayloadBytes = config.maxPayloadBytes ?? 1_048_576; // 1 MB
|
|
151
|
-
this.maxConcurrentRequests = config.maxConcurrentRequests ?? 50;
|
|
152
|
-
if (this.maxConcurrentRequests <= 0) {
|
|
153
|
-
throw new Error('maxConcurrentRequests must be greater than 0');
|
|
154
|
-
}
|
|
155
|
-
this.logger = config.logger ?? {
|
|
156
|
-
debug() {},
|
|
157
|
-
info() {},
|
|
158
|
-
warn() {},
|
|
159
|
-
error(message: string, ...args: unknown[]) { console.error(message, ...args); },
|
|
160
|
-
};
|
|
161
|
-
|
|
162
|
-
if (this.allowInsecureUrls) {
|
|
163
|
-
this.logger.warn('WebhookEventTransport: allowInsecureUrls is enabled. Webhook payloads will be sent over HTTP. Do not use this setting in production.');
|
|
164
|
-
}
|
|
165
|
-
|
|
166
|
-
// Register initial endpoints (validates URLs)
|
|
167
|
-
if (config.endpoints) {
|
|
168
|
-
for (const endpoint of config.endpoints) {
|
|
169
|
-
this.addEndpoint(endpoint);
|
|
170
|
-
}
|
|
171
|
-
}
|
|
172
|
-
}
|
|
173
|
-
|
|
174
|
-
/**
|
|
175
|
-
* Add a webhook endpoint.
|
|
176
|
-
* Validates the URL to prevent SSRF attacks.
|
|
177
|
-
* @throws Error if the URL scheme is not allowed
|
|
178
|
-
*/
|
|
179
|
-
addEndpoint(endpoint: WebhookEndpoint): void {
|
|
180
|
-
this.validateWebhookUrl(endpoint.url);
|
|
181
|
-
this.endpoints.set(endpoint.id, { enabled: true, ...endpoint });
|
|
182
|
-
}
|
|
183
|
-
|
|
184
|
-
/**
|
|
185
|
-
* Remove a webhook endpoint.
|
|
186
|
-
*/
|
|
187
|
-
removeEndpoint(id: string): boolean {
|
|
188
|
-
return this.endpoints.delete(id);
|
|
189
|
-
}
|
|
190
|
-
|
|
191
|
-
/**
|
|
192
|
-
* Get all registered endpoints.
|
|
193
|
-
*/
|
|
194
|
-
getEndpoints(): WebhookEndpoint[] {
|
|
195
|
-
return Array.from(this.endpoints.values());
|
|
196
|
-
}
|
|
197
|
-
|
|
198
|
-
/**
|
|
199
|
-
* Enable or disable an endpoint.
|
|
200
|
-
*/
|
|
201
|
-
setEndpointEnabled(id: string, enabled: boolean): void {
|
|
202
|
-
const endpoint = this.endpoints.get(id);
|
|
203
|
-
if (endpoint) {
|
|
204
|
-
endpoint.enabled = enabled;
|
|
205
|
-
}
|
|
206
|
-
}
|
|
207
|
-
|
|
208
|
-
/**
|
|
209
|
-
* Emit an event to all matching webhook endpoints.
|
|
210
|
-
*/
|
|
211
|
-
emit(event: WorkflowEvent): void {
|
|
212
|
-
// Notify local subscribers first (synchronously)
|
|
213
|
-
const runSubs = this.runSubscribers.get(event.runId);
|
|
214
|
-
if (runSubs) {
|
|
215
|
-
for (const callback of runSubs) {
|
|
216
|
-
try {
|
|
217
|
-
callback(event);
|
|
218
|
-
} catch (error) {
|
|
219
|
-
this.logger.error('Event callback error:', error);
|
|
220
|
-
}
|
|
221
|
-
}
|
|
222
|
-
}
|
|
223
|
-
|
|
224
|
-
for (const callback of this.globalSubscribers) {
|
|
225
|
-
try {
|
|
226
|
-
callback(event);
|
|
227
|
-
} catch (error) {
|
|
228
|
-
this.logger.error('Event callback error:', error);
|
|
229
|
-
}
|
|
230
|
-
}
|
|
231
|
-
|
|
232
|
-
// Send to webhooks asynchronously with concurrency control
|
|
233
|
-
for (const endpoint of this.endpoints.values()) {
|
|
234
|
-
if (!endpoint.enabled) continue;
|
|
235
|
-
if (!this.matchesFilter(event, endpoint)) continue;
|
|
236
|
-
|
|
237
|
-
this.enqueueRequest(() =>
|
|
238
|
-
this.sendWebhook(endpoint, event).catch((error) => {
|
|
239
|
-
this.logger.error(`Webhook ${endpoint.id} failed:`, error);
|
|
240
|
-
})
|
|
241
|
-
);
|
|
242
|
-
}
|
|
243
|
-
}
|
|
244
|
-
|
|
245
|
-
/**
|
|
246
|
-
* Subscribe to events for a specific run (server-side).
|
|
247
|
-
*/
|
|
248
|
-
subscribe(runId: string, callback: EventCallback): Unsubscribe {
|
|
249
|
-
let subs = this.runSubscribers.get(runId);
|
|
250
|
-
if (!subs) {
|
|
251
|
-
subs = new Set();
|
|
252
|
-
this.runSubscribers.set(runId, subs);
|
|
253
|
-
}
|
|
254
|
-
subs.add(callback);
|
|
255
|
-
|
|
256
|
-
return () => {
|
|
257
|
-
subs!.delete(callback);
|
|
258
|
-
if (subs!.size === 0) {
|
|
259
|
-
this.runSubscribers.delete(runId);
|
|
260
|
-
}
|
|
261
|
-
};
|
|
262
|
-
}
|
|
263
|
-
|
|
264
|
-
/**
|
|
265
|
-
* Subscribe to all events (server-side).
|
|
266
|
-
*/
|
|
267
|
-
subscribeAll(callback: EventCallback): Unsubscribe {
|
|
268
|
-
this.globalSubscribers.add(callback);
|
|
269
|
-
return () => {
|
|
270
|
-
this.globalSubscribers.delete(callback);
|
|
271
|
-
};
|
|
272
|
-
}
|
|
273
|
-
|
|
274
|
-
/**
|
|
275
|
-
* Close the transport.
|
|
276
|
-
*/
|
|
277
|
-
close(): void {
|
|
278
|
-
this.runSubscribers.clear();
|
|
279
|
-
this.globalSubscribers.clear();
|
|
280
|
-
this.endpoints.clear();
|
|
281
|
-
}
|
|
282
|
-
|
|
283
|
-
/**
|
|
284
|
-
* Check if an event matches an endpoint's filters.
|
|
285
|
-
*/
|
|
286
|
-
private matchesFilter(event: WorkflowEvent, endpoint: WebhookEndpoint): boolean {
|
|
287
|
-
// Check event type filter
|
|
288
|
-
if (endpoint.eventTypes && endpoint.eventTypes.length > 0) {
|
|
289
|
-
if (!endpoint.eventTypes.includes(event.eventType)) {
|
|
290
|
-
return false;
|
|
291
|
-
}
|
|
292
|
-
}
|
|
293
|
-
|
|
294
|
-
// Check workflow kind filter
|
|
295
|
-
if (endpoint.workflowKinds && endpoint.workflowKinds.length > 0) {
|
|
296
|
-
if (!endpoint.workflowKinds.includes(event.kind)) {
|
|
297
|
-
return false;
|
|
298
|
-
}
|
|
299
|
-
}
|
|
300
|
-
|
|
301
|
-
return true;
|
|
302
|
-
}
|
|
303
|
-
|
|
304
|
-
/**
|
|
305
|
-
* Send a webhook with retry support.
|
|
306
|
-
*/
|
|
307
|
-
private async sendWebhook(endpoint: WebhookEndpoint, event: WorkflowEvent): Promise<void> {
|
|
308
|
-
const timeout = endpoint.timeout ?? this.defaultTimeout;
|
|
309
|
-
const maxRetries = endpoint.retries ?? this.defaultRetries;
|
|
310
|
-
|
|
311
|
-
const payload: WebhookPayload = {
|
|
312
|
-
event: {
|
|
313
|
-
...event,
|
|
314
|
-
timestamp: event.timestamp.toISOString(),
|
|
315
|
-
},
|
|
316
|
-
deliveredAt: new Date().toISOString(),
|
|
317
|
-
webhookId: endpoint.id,
|
|
318
|
-
};
|
|
319
|
-
|
|
320
|
-
const body = JSON.stringify(payload);
|
|
321
|
-
|
|
322
|
-
// Enforce payload size limit to prevent excessive memory use and network abuse
|
|
323
|
-
if (body.length > this.maxPayloadBytes) {
|
|
324
|
-
throw new Error(
|
|
325
|
-
`Webhook payload exceeds maximum size (${body.length} bytes > ${this.maxPayloadBytes} bytes)`
|
|
326
|
-
);
|
|
327
|
-
}
|
|
328
|
-
|
|
329
|
-
const headers: Record<string, string> = {
|
|
330
|
-
'Content-Type': 'application/json',
|
|
331
|
-
...endpoint.headers,
|
|
332
|
-
};
|
|
333
|
-
|
|
334
|
-
// Sign payload if secret is provided
|
|
335
|
-
if (endpoint.secret) {
|
|
336
|
-
const signature = await this.signPayload(body, endpoint.secret);
|
|
337
|
-
headers['X-Webhook-Signature'] = signature;
|
|
338
|
-
}
|
|
339
|
-
|
|
340
|
-
// Resolve hostname and validate the resolved IP is not private/reserved (SSRF protection).
|
|
341
|
-
// This prevents DNS rebinding attacks where a hostname initially resolves to a public IP
|
|
342
|
-
// but later resolves to a private IP.
|
|
343
|
-
await this.validateResolvedHost(endpoint.url);
|
|
344
|
-
|
|
345
|
-
let lastError: Error | undefined;
|
|
346
|
-
|
|
347
|
-
for (let attempt = 0; attempt <= maxRetries; attempt++) {
|
|
348
|
-
try {
|
|
349
|
-
const controller = new AbortController();
|
|
350
|
-
const timeoutId = setTimeout(() => controller.abort(), timeout);
|
|
351
|
-
|
|
352
|
-
const response = await this.fetchFn(endpoint.url, {
|
|
353
|
-
method: 'POST',
|
|
354
|
-
headers,
|
|
355
|
-
body,
|
|
356
|
-
signal: controller.signal,
|
|
357
|
-
});
|
|
358
|
-
|
|
359
|
-
clearTimeout(timeoutId);
|
|
360
|
-
|
|
361
|
-
if (response.ok) {
|
|
362
|
-
return; // Success
|
|
363
|
-
}
|
|
364
|
-
|
|
365
|
-
lastError = new Error(`Webhook returned ${response.status}: ${response.statusText}`);
|
|
366
|
-
} catch (error) {
|
|
367
|
-
lastError = error instanceof Error ? error : new Error(String(error));
|
|
368
|
-
}
|
|
369
|
-
|
|
370
|
-
// Wait before retrying (except on last attempt)
|
|
371
|
-
if (attempt < maxRetries) {
|
|
372
|
-
await this.sleep(this.retryDelay * Math.pow(2, attempt));
|
|
373
|
-
}
|
|
374
|
-
}
|
|
375
|
-
|
|
376
|
-
throw lastError;
|
|
377
|
-
}
|
|
378
|
-
|
|
379
|
-
/**
|
|
380
|
-
* Sign a payload using HMAC-SHA256.
|
|
381
|
-
*/
|
|
382
|
-
private async signPayload(payload: string, secret: string): Promise<string> {
|
|
383
|
-
// Use Web Crypto API for HMAC-SHA256
|
|
384
|
-
const encoder = new TextEncoder();
|
|
385
|
-
const keyData = encoder.encode(secret);
|
|
386
|
-
const data = encoder.encode(payload);
|
|
387
|
-
|
|
388
|
-
const key = await crypto.subtle.importKey(
|
|
389
|
-
'raw',
|
|
390
|
-
keyData,
|
|
391
|
-
{ name: 'HMAC', hash: 'SHA-256' },
|
|
392
|
-
false,
|
|
393
|
-
['sign']
|
|
394
|
-
);
|
|
395
|
-
|
|
396
|
-
const signature = await crypto.subtle.sign('HMAC', key, data);
|
|
397
|
-
const hashArray = Array.from(new Uint8Array(signature));
|
|
398
|
-
const hashHex = hashArray.map(b => b.toString(16).padStart(2, '0')).join('');
|
|
399
|
-
|
|
400
|
-
return `sha256=${hashHex}`;
|
|
401
|
-
}
|
|
402
|
-
|
|
403
|
-
/**
|
|
404
|
-
* Sleep helper.
|
|
405
|
-
*/
|
|
406
|
-
private sleep(ms: number): Promise<void> {
|
|
407
|
-
return new Promise(resolve => setTimeout(resolve, ms));
|
|
408
|
-
}
|
|
409
|
-
|
|
410
|
-
/**
|
|
411
|
-
* Resolve the hostname from a URL and verify the resolved IP is not private/reserved.
|
|
412
|
-
* Prevents DNS rebinding attacks where a public hostname resolves to a private IP at send time.
|
|
413
|
-
*/
|
|
414
|
-
private async validateResolvedHost(url: string): Promise<void> {
|
|
415
|
-
const parsed = new URL(url);
|
|
416
|
-
const hostname = parsed.hostname.toLowerCase();
|
|
417
|
-
|
|
418
|
-
// Skip DNS resolution for raw IP addresses — already checked by isBlockedHost in validateWebhookUrl
|
|
419
|
-
if (/^(\d{1,3}\.){3}\d{1,3}$/.test(hostname)) {
|
|
420
|
-
return;
|
|
421
|
-
}
|
|
422
|
-
|
|
423
|
-
try {
|
|
424
|
-
const { address } = await dns.lookup(hostname);
|
|
425
|
-
if (isBlockedIp(address)) {
|
|
426
|
-
throw new Error(
|
|
427
|
-
`Webhook URL hostname "${hostname}" resolves to blocked IP ${address}`
|
|
428
|
-
);
|
|
429
|
-
}
|
|
430
|
-
} catch (error) {
|
|
431
|
-
if (error instanceof Error && error.message.includes('resolves to blocked IP')) {
|
|
432
|
-
throw error;
|
|
433
|
-
}
|
|
434
|
-
throw new Error(`Failed to resolve webhook URL hostname "${hostname}": ${error}`);
|
|
435
|
-
}
|
|
436
|
-
}
|
|
437
|
-
|
|
438
|
-
/**
|
|
439
|
-
* Validate a webhook URL to prevent SSRF attacks.
|
|
440
|
-
* Blocks non-HTTPS schemes (unless allowInsecureUrls is set),
|
|
441
|
-
* and rejects private/reserved IP ranges and cloud metadata endpoints.
|
|
442
|
-
*/
|
|
443
|
-
private validateWebhookUrl(url: string): void {
|
|
444
|
-
let parsed: URL;
|
|
445
|
-
try {
|
|
446
|
-
parsed = new URL(url);
|
|
447
|
-
} catch {
|
|
448
|
-
throw new Error(`Invalid webhook URL: ${url}`);
|
|
449
|
-
}
|
|
450
|
-
|
|
451
|
-
// Scheme check
|
|
452
|
-
if (!this.allowInsecureUrls && parsed.protocol !== 'https:') {
|
|
453
|
-
throw new Error(
|
|
454
|
-
`Webhook URL must use HTTPS (got ${parsed.protocol}). Set allowInsecureUrls for development.`
|
|
455
|
-
);
|
|
456
|
-
}
|
|
457
|
-
|
|
458
|
-
if (parsed.protocol !== 'https:' && parsed.protocol !== 'http:') {
|
|
459
|
-
throw new Error(`Webhook URL must use HTTP(S) scheme (got ${parsed.protocol})`);
|
|
460
|
-
}
|
|
461
|
-
|
|
462
|
-
// Block dangerous hostnames
|
|
463
|
-
const hostname = parsed.hostname.toLowerCase();
|
|
464
|
-
if (isBlockedHost(hostname)) {
|
|
465
|
-
throw new Error(`Webhook URL hostname is blocked (private/reserved): ${hostname}`);
|
|
466
|
-
}
|
|
467
|
-
}
|
|
468
|
-
|
|
469
|
-
/**
|
|
470
|
-
* Enqueue a webhook request with concurrency limiting.
|
|
471
|
-
*/
|
|
472
|
-
private enqueueRequest(fn: () => Promise<void>): void {
|
|
473
|
-
const execute = () => {
|
|
474
|
-
this.activeRequests++;
|
|
475
|
-
fn().finally(() => {
|
|
476
|
-
this.activeRequests--;
|
|
477
|
-
const next = this.requestQueue.shift();
|
|
478
|
-
if (next) next();
|
|
479
|
-
});
|
|
480
|
-
};
|
|
481
|
-
|
|
482
|
-
if (this.activeRequests < this.maxConcurrentRequests) {
|
|
483
|
-
execute();
|
|
484
|
-
} else {
|
|
485
|
-
this.requestQueue.push(execute);
|
|
486
|
-
}
|
|
487
|
-
}
|
|
488
|
-
}
|
|
489
|
-
|
|
490
|
-
/**
|
|
491
|
-
* Check if a hostname resolves to a blocked (private/reserved) address.
|
|
492
|
-
* Blocks loopback, RFC 1918 private ranges, link-local, and cloud metadata IPs.
|
|
493
|
-
*/
|
|
494
|
-
function isBlockedHost(hostname: string): boolean {
|
|
495
|
-
// Loopback (Node's URL parser wraps IPv6 in brackets, e.g. "[::1]")
|
|
496
|
-
if (hostname === 'localhost' || hostname === '127.0.0.1' || hostname === '::1' || hostname === '[::1]') {
|
|
497
|
-
return true;
|
|
498
|
-
}
|
|
499
|
-
|
|
500
|
-
// Block all IPv6 address literals (wrapped in brackets by URL parser)
|
|
501
|
-
if (hostname.startsWith('[')) {
|
|
502
|
-
return true;
|
|
503
|
-
}
|
|
504
|
-
|
|
505
|
-
// Cloud metadata endpoint
|
|
506
|
-
if (hostname === '169.254.169.254') {
|
|
507
|
-
return true;
|
|
508
|
-
}
|
|
509
|
-
|
|
510
|
-
// Check for IP addresses in private/reserved ranges
|
|
511
|
-
const ipv4Match = hostname.match(/^(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})$/);
|
|
512
|
-
if (ipv4Match) {
|
|
513
|
-
const [, a, b] = ipv4Match.map(Number);
|
|
514
|
-
// 10.0.0.0/8
|
|
515
|
-
if (a === 10) return true;
|
|
516
|
-
// 172.16.0.0/12
|
|
517
|
-
if (a === 172 && b >= 16 && b <= 31) return true;
|
|
518
|
-
// 192.168.0.0/16
|
|
519
|
-
if (a === 192 && b === 168) return true;
|
|
520
|
-
// 127.0.0.0/8
|
|
521
|
-
if (a === 127) return true;
|
|
522
|
-
// 169.254.0.0/16 (link-local)
|
|
523
|
-
if (a === 169 && b === 254) return true;
|
|
524
|
-
// 0.0.0.0
|
|
525
|
-
if (a === 0 && b === 0) return true;
|
|
526
|
-
}
|
|
527
|
-
|
|
528
|
-
// IPv6 link-local (fe80::)
|
|
529
|
-
if (hostname.startsWith('fe80:') || hostname.startsWith('[fe80:')) {
|
|
530
|
-
return true;
|
|
531
|
-
}
|
|
532
|
-
|
|
533
|
-
return false;
|
|
534
|
-
}
|
|
535
|
-
|
|
536
|
-
/**
|
|
537
|
-
* Check if a resolved IP address falls within a private/reserved range.
|
|
538
|
-
* Used for runtime DNS resolution validation to prevent SSRF via DNS rebinding.
|
|
539
|
-
*/
|
|
540
|
-
function isBlockedIp(ip: string): boolean {
|
|
541
|
-
const ipv4Match = ip.match(/^(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})$/);
|
|
542
|
-
if (ipv4Match) {
|
|
543
|
-
const [, a, b] = ipv4Match.map(Number);
|
|
544
|
-
// 127.0.0.0/8 (loopback)
|
|
545
|
-
if (a === 127) return true;
|
|
546
|
-
// 10.0.0.0/8
|
|
547
|
-
if (a === 10) return true;
|
|
548
|
-
// 172.16.0.0/12
|
|
549
|
-
if (a === 172 && b >= 16 && b <= 31) return true;
|
|
550
|
-
// 192.168.0.0/16
|
|
551
|
-
if (a === 192 && b === 168) return true;
|
|
552
|
-
// 169.254.0.0/16 (link-local, including cloud metadata 169.254.169.254)
|
|
553
|
-
if (a === 169 && b === 254) return true;
|
|
554
|
-
// 0.0.0.0
|
|
555
|
-
if (a === 0 && b === 0) return true;
|
|
556
|
-
}
|
|
557
|
-
|
|
558
|
-
// IPv6 loopback
|
|
559
|
-
if (ip === '::1') return true;
|
|
560
|
-
// IPv6 link-local
|
|
561
|
-
if (ip.startsWith('fe80:')) return true;
|
|
562
|
-
|
|
563
|
-
return false;
|
|
564
|
-
}
|