@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/README.md
CHANGED
|
@@ -13,6 +13,15 @@ A durable, type-safe workflow orchestration engine for Node.js with SQLite or Po
|
|
|
13
13
|
- **Multiple Storage Backends**: Choose SQLite for simplicity or PostgreSQL for distributed deployments
|
|
14
14
|
- **Planning System**: Rule-based recipe selection and dynamic plan generation
|
|
15
15
|
|
|
16
|
+
## Requirements
|
|
17
|
+
|
|
18
|
+
Node.js `^22.22.2 || ^24.15.0 || >=26.0.0`.
|
|
19
|
+
|
|
20
|
+
The `re2` native dependency — used by the `matches` condition operator to
|
|
21
|
+
evaluate user-supplied recipe conditions without ReDoS exposure — only ships
|
|
22
|
+
patched, installable builds for these versions. Node 20 is end-of-life (April
|
|
23
|
+
2026) and is no longer supported.
|
|
24
|
+
|
|
16
25
|
## Installation
|
|
17
26
|
|
|
18
27
|
This package is published to GitHub Packages. See [docs/github-packages-setup.md](docs/github-packages-setup.md) for authentication setup.
|
|
@@ -7,11 +7,13 @@ var MemoryEventTransport = class {
|
|
|
7
7
|
}
|
|
8
8
|
/**
|
|
9
9
|
* Emit an event to all subscribers.
|
|
10
|
+
* Each channel is isolated so a failing listener on one channel
|
|
11
|
+
* cannot prevent delivery to the others.
|
|
10
12
|
*/
|
|
11
13
|
emit(event) {
|
|
12
|
-
this.emitter.emit("event", event);
|
|
13
14
|
this.emitter.emit(`run:${event.runId}`, event);
|
|
14
15
|
this.emitter.emit(`type:${event.eventType}`, event);
|
|
16
|
+
this.emitter.emit("event", event);
|
|
15
17
|
}
|
|
16
18
|
/**
|
|
17
19
|
* Subscribe to events for a specific run.
|
|
@@ -218,18 +220,96 @@ var SocketIOEventTransport = class {
|
|
|
218
220
|
|
|
219
221
|
// src/events/webhook.ts
|
|
220
222
|
import { promises as dns } from "dns";
|
|
221
|
-
|
|
223
|
+
import { isIPv4, isIPv6 } from "net";
|
|
224
|
+
|
|
225
|
+
// src/utils/pinned-fetch.ts
|
|
226
|
+
import * as http from "http";
|
|
227
|
+
import * as https from "https";
|
|
228
|
+
function pinnedFetch(url, init, address, family = 4) {
|
|
229
|
+
const parsed = new URL(url);
|
|
230
|
+
const isHttps = parsed.protocol === "https:";
|
|
231
|
+
const lib = isHttps ? https : http;
|
|
232
|
+
const port = parsed.port ? Number(parsed.port) : isHttps ? 443 : 80;
|
|
233
|
+
const lookup = (_hostname, options, cb) => {
|
|
234
|
+
if (options && options.all === true) {
|
|
235
|
+
cb(null, [{ address, family }]);
|
|
236
|
+
} else {
|
|
237
|
+
cb(null, address, family);
|
|
238
|
+
}
|
|
239
|
+
};
|
|
240
|
+
return new Promise((resolve, reject) => {
|
|
241
|
+
const req = lib.request(
|
|
242
|
+
{
|
|
243
|
+
hostname: parsed.hostname,
|
|
244
|
+
port,
|
|
245
|
+
path: `${parsed.pathname || "/"}${parsed.search}`,
|
|
246
|
+
method: init.method ?? "GET",
|
|
247
|
+
headers: init.headers,
|
|
248
|
+
lookup,
|
|
249
|
+
servername: parsed.hostname
|
|
250
|
+
},
|
|
251
|
+
(res) => {
|
|
252
|
+
res.resume();
|
|
253
|
+
res.on("end", () => {
|
|
254
|
+
const status = res.statusCode ?? 0;
|
|
255
|
+
resolve({
|
|
256
|
+
ok: status >= 200 && status < 300,
|
|
257
|
+
status,
|
|
258
|
+
statusText: res.statusMessage ?? ""
|
|
259
|
+
});
|
|
260
|
+
});
|
|
261
|
+
res.on("error", reject);
|
|
262
|
+
}
|
|
263
|
+
);
|
|
264
|
+
req.on("error", reject);
|
|
265
|
+
if (init.signal) {
|
|
266
|
+
if (init.signal.aborted) {
|
|
267
|
+
req.destroy(new Error("Request aborted"));
|
|
268
|
+
} else {
|
|
269
|
+
init.signal.addEventListener(
|
|
270
|
+
"abort",
|
|
271
|
+
() => req.destroy(new Error("Request aborted")),
|
|
272
|
+
{ once: true }
|
|
273
|
+
);
|
|
274
|
+
}
|
|
275
|
+
}
|
|
276
|
+
if (init.body !== void 0) {
|
|
277
|
+
req.write(init.body);
|
|
278
|
+
}
|
|
279
|
+
req.end();
|
|
280
|
+
});
|
|
281
|
+
}
|
|
282
|
+
|
|
283
|
+
// src/events/webhook.ts
|
|
284
|
+
var WebhookEventTransport = class _WebhookEventTransport {
|
|
222
285
|
endpoints = /* @__PURE__ */ new Map();
|
|
223
286
|
defaultTimeout;
|
|
224
287
|
defaultRetries;
|
|
225
288
|
retryDelay;
|
|
226
289
|
fetchFn;
|
|
290
|
+
/**
|
|
291
|
+
* Whether `fetchFn` was caller-supplied. When `false` the default fetch is
|
|
292
|
+
* replaced with `pinnedFetch` so the TCP connection can target the IP that
|
|
293
|
+
* was just validated (closes the DNS-rebinding TOCTOU window). When `true`
|
|
294
|
+
* the custom fetch is used as-is so test injection still works.
|
|
295
|
+
*/
|
|
296
|
+
hasCustomFetch;
|
|
227
297
|
allowInsecureUrls;
|
|
228
298
|
maxPayloadBytes;
|
|
229
299
|
maxConcurrentRequests;
|
|
300
|
+
maxQueueDepth;
|
|
301
|
+
queueDropRetryAfterMs;
|
|
230
302
|
activeRequests = 0;
|
|
231
303
|
requestQueue = [];
|
|
304
|
+
droppedRequests = 0;
|
|
232
305
|
logger;
|
|
306
|
+
// DNS resolution cache with TTL — stores `family` so the pin can reuse it
|
|
307
|
+
// without a second lookup.
|
|
308
|
+
dnsCache = /* @__PURE__ */ new Map();
|
|
309
|
+
static DNS_CACHE_TTL_MS = 3e4;
|
|
310
|
+
// 30 seconds
|
|
311
|
+
static DNS_TIMEOUT_MS = 5e3;
|
|
312
|
+
// 5 seconds
|
|
233
313
|
// Local subscribers for server-side subscriptions
|
|
234
314
|
runSubscribers = /* @__PURE__ */ new Map();
|
|
235
315
|
globalSubscribers = /* @__PURE__ */ new Set();
|
|
@@ -237,6 +317,7 @@ var WebhookEventTransport = class {
|
|
|
237
317
|
this.defaultTimeout = config.defaultTimeout ?? 5e3;
|
|
238
318
|
this.defaultRetries = config.defaultRetries ?? 3;
|
|
239
319
|
this.retryDelay = config.retryDelay ?? 1e3;
|
|
320
|
+
this.hasCustomFetch = config.fetchFn !== void 0;
|
|
240
321
|
this.fetchFn = config.fetchFn ?? globalThis.fetch;
|
|
241
322
|
this.allowInsecureUrls = config.allowInsecureUrls ?? false;
|
|
242
323
|
this.maxPayloadBytes = config.maxPayloadBytes ?? 1048576;
|
|
@@ -244,6 +325,11 @@ var WebhookEventTransport = class {
|
|
|
244
325
|
if (this.maxConcurrentRequests <= 0) {
|
|
245
326
|
throw new Error("maxConcurrentRequests must be greater than 0");
|
|
246
327
|
}
|
|
328
|
+
this.maxQueueDepth = resolveMaxQueueDepth(config.maxQueueDepth);
|
|
329
|
+
if (this.maxQueueDepth < 0) {
|
|
330
|
+
throw new Error("maxQueueDepth must be >= 0 (0 disables the cap)");
|
|
331
|
+
}
|
|
332
|
+
this.queueDropRetryAfterMs = config.queueDropRetryAfterMs ?? 1e3;
|
|
247
333
|
this.logger = config.logger ?? {
|
|
248
334
|
debug() {
|
|
249
335
|
},
|
|
@@ -318,13 +404,33 @@ var WebhookEventTransport = class {
|
|
|
318
404
|
for (const endpoint of this.endpoints.values()) {
|
|
319
405
|
if (!endpoint.enabled) continue;
|
|
320
406
|
if (!this.matchesFilter(event, endpoint)) continue;
|
|
321
|
-
this.enqueueRequest(
|
|
407
|
+
const accepted = this.enqueueRequest(
|
|
322
408
|
() => this.sendWebhook(endpoint, event).catch((error) => {
|
|
323
409
|
this.logger.error(`Webhook ${endpoint.id} failed:`, error);
|
|
324
|
-
})
|
|
410
|
+
}),
|
|
411
|
+
endpoint.id
|
|
325
412
|
);
|
|
413
|
+
if (!accepted) {
|
|
414
|
+
this.droppedRequests++;
|
|
415
|
+
this.logger.warn(
|
|
416
|
+
`Webhook ${endpoint.id} delivery dropped: queue full (depth ${this.requestQueue.length}/${this.maxQueueDepth}, active ${this.activeRequests}/${this.maxConcurrentRequests}, total drops ${this.droppedRequests}, retryAfterMs ${this.queueDropRetryAfterMs})`
|
|
417
|
+
);
|
|
418
|
+
}
|
|
326
419
|
}
|
|
327
420
|
}
|
|
421
|
+
/**
|
|
422
|
+
* Number of webhook deliveries dropped due to queue overflow since startup.
|
|
423
|
+
* Useful for surfacing back-pressure to operators (metrics/health checks).
|
|
424
|
+
*/
|
|
425
|
+
getDroppedRequestCount() {
|
|
426
|
+
return this.droppedRequests;
|
|
427
|
+
}
|
|
428
|
+
/**
|
|
429
|
+
* Current depth of the pending request queue.
|
|
430
|
+
*/
|
|
431
|
+
getQueueDepth() {
|
|
432
|
+
return this.requestQueue.length;
|
|
433
|
+
}
|
|
328
434
|
/**
|
|
329
435
|
* Subscribe to events for a specific run (server-side).
|
|
330
436
|
*/
|
|
@@ -403,18 +509,23 @@ var WebhookEventTransport = class {
|
|
|
403
509
|
const signature = await this.signPayload(body, endpoint.secret);
|
|
404
510
|
headers["X-Webhook-Signature"] = signature;
|
|
405
511
|
}
|
|
406
|
-
await this.validateResolvedHost(endpoint.url);
|
|
407
512
|
let lastError;
|
|
408
513
|
for (let attempt = 0; attempt <= maxRetries; attempt++) {
|
|
409
514
|
try {
|
|
515
|
+
const pinned = await this.validateResolvedHost(endpoint.url);
|
|
410
516
|
const controller = new AbortController();
|
|
411
517
|
const timeoutId = setTimeout(() => controller.abort(), timeout);
|
|
412
|
-
const response = await this.fetchFn(endpoint.url, {
|
|
518
|
+
const response = this.hasCustomFetch || !pinned ? await this.fetchFn(endpoint.url, {
|
|
413
519
|
method: "POST",
|
|
414
520
|
headers,
|
|
415
521
|
body,
|
|
416
522
|
signal: controller.signal
|
|
417
|
-
})
|
|
523
|
+
}) : await pinnedFetch(
|
|
524
|
+
endpoint.url,
|
|
525
|
+
{ method: "POST", headers, body, signal: controller.signal },
|
|
526
|
+
pinned.address,
|
|
527
|
+
pinned.family
|
|
528
|
+
);
|
|
418
529
|
clearTimeout(timeoutId);
|
|
419
530
|
if (response.ok) {
|
|
420
531
|
return;
|
|
@@ -455,26 +566,65 @@ var WebhookEventTransport = class {
|
|
|
455
566
|
return new Promise((resolve) => setTimeout(resolve, ms));
|
|
456
567
|
}
|
|
457
568
|
/**
|
|
458
|
-
* Resolve
|
|
459
|
-
*
|
|
569
|
+
* Resolve a webhook URL's hostname exactly once, verify the resolved IP is
|
|
570
|
+
* not private/reserved, and return the address + family so the caller can
|
|
571
|
+
* pin the connection to it.
|
|
572
|
+
*
|
|
573
|
+
* Returns `null` for raw-IP URLs (already validated by `validateWebhookUrl`).
|
|
574
|
+
*
|
|
575
|
+
* Pinning the resolved IP closes the DNS rebinding TOCTOU window (audit M1):
|
|
576
|
+
* with the original implementation `fetch()` re-resolved the hostname,
|
|
577
|
+
* giving a hostile DNS server a chance to flip the answer to an internal
|
|
578
|
+
* address between SSRF validation and connect.
|
|
579
|
+
*
|
|
580
|
+
* Uses a short-TTL cache and per-call timeout to avoid blocking the event loop.
|
|
460
581
|
*/
|
|
461
582
|
async validateResolvedHost(url) {
|
|
462
583
|
const parsed = new URL(url);
|
|
463
584
|
const hostname = parsed.hostname.toLowerCase();
|
|
464
|
-
|
|
465
|
-
|
|
585
|
+
const stripped = hostname.startsWith("[") ? hostname.slice(1, -1) : hostname;
|
|
586
|
+
if (isIPv4(stripped) || isIPv6(stripped)) {
|
|
587
|
+
return null;
|
|
588
|
+
}
|
|
589
|
+
const cached = this.dnsCache.get(hostname);
|
|
590
|
+
if (cached && cached.expiresAt > Date.now()) {
|
|
591
|
+
if (isBlockedIp(cached.address)) {
|
|
592
|
+
throw new Error(
|
|
593
|
+
`Webhook URL hostname "${hostname}" resolves to blocked IP ${cached.address}`
|
|
594
|
+
);
|
|
595
|
+
}
|
|
596
|
+
return { address: cached.address, family: cached.family };
|
|
466
597
|
}
|
|
467
598
|
try {
|
|
468
|
-
const
|
|
599
|
+
const ac = new AbortController();
|
|
600
|
+
const timeoutId = setTimeout(() => ac.abort(), _WebhookEventTransport.DNS_TIMEOUT_MS);
|
|
601
|
+
let address;
|
|
602
|
+
let family;
|
|
603
|
+
try {
|
|
604
|
+
const result = await dns.lookup(hostname, { signal: ac.signal });
|
|
605
|
+
address = result.address;
|
|
606
|
+
family = result.family === 6 ? 6 : 4;
|
|
607
|
+
} finally {
|
|
608
|
+
clearTimeout(timeoutId);
|
|
609
|
+
}
|
|
610
|
+
this.dnsCache.set(hostname, {
|
|
611
|
+
address,
|
|
612
|
+
family,
|
|
613
|
+
expiresAt: Date.now() + _WebhookEventTransport.DNS_CACHE_TTL_MS
|
|
614
|
+
});
|
|
469
615
|
if (isBlockedIp(address)) {
|
|
470
616
|
throw new Error(
|
|
471
617
|
`Webhook URL hostname "${hostname}" resolves to blocked IP ${address}`
|
|
472
618
|
);
|
|
473
619
|
}
|
|
620
|
+
return { address, family };
|
|
474
621
|
} catch (error) {
|
|
475
622
|
if (error instanceof Error && error.message.includes("resolves to blocked IP")) {
|
|
476
623
|
throw error;
|
|
477
624
|
}
|
|
625
|
+
if (error instanceof Error && error.name === "AbortError") {
|
|
626
|
+
throw new Error(`DNS lookup for webhook URL hostname "${hostname}" timed out`);
|
|
627
|
+
}
|
|
478
628
|
throw new Error(`Failed to resolve webhook URL hostname "${hostname}": ${error}`);
|
|
479
629
|
}
|
|
480
630
|
}
|
|
@@ -504,9 +654,13 @@ var WebhookEventTransport = class {
|
|
|
504
654
|
}
|
|
505
655
|
}
|
|
506
656
|
/**
|
|
507
|
-
* Enqueue a webhook request with concurrency limiting.
|
|
657
|
+
* Enqueue a webhook request with concurrency limiting and a queue-depth cap.
|
|
658
|
+
* Returns `true` if the request was accepted (executed or queued), or
|
|
659
|
+
* `false` if the queue is full and the request was rejected. The caller is
|
|
660
|
+
* responsible for logging the drop and incrementing any drop metrics, since
|
|
661
|
+
* it has the endpoint context.
|
|
508
662
|
*/
|
|
509
|
-
enqueueRequest(fn) {
|
|
663
|
+
enqueueRequest(fn, _endpointId) {
|
|
510
664
|
const execute = () => {
|
|
511
665
|
this.activeRequests++;
|
|
512
666
|
fn().finally(() => {
|
|
@@ -517,55 +671,122 @@ var WebhookEventTransport = class {
|
|
|
517
671
|
};
|
|
518
672
|
if (this.activeRequests < this.maxConcurrentRequests) {
|
|
519
673
|
execute();
|
|
520
|
-
|
|
521
|
-
this.requestQueue.push(execute);
|
|
674
|
+
return true;
|
|
522
675
|
}
|
|
676
|
+
if (this.maxQueueDepth > 0 && this.requestQueue.length >= this.maxQueueDepth) {
|
|
677
|
+
return false;
|
|
678
|
+
}
|
|
679
|
+
this.requestQueue.push(execute);
|
|
680
|
+
return true;
|
|
523
681
|
}
|
|
524
682
|
};
|
|
683
|
+
function resolveMaxQueueDepth(configured) {
|
|
684
|
+
if (typeof configured === "number") return configured;
|
|
685
|
+
const env = typeof process !== "undefined" ? process.env?.STEPFLOW_WEBHOOK_MAX_QUEUE_DEPTH : void 0;
|
|
686
|
+
if (env !== void 0 && env !== "") {
|
|
687
|
+
const parsed = Number(env);
|
|
688
|
+
if (Number.isFinite(parsed) && parsed >= 0) return parsed;
|
|
689
|
+
}
|
|
690
|
+
return 1e3;
|
|
691
|
+
}
|
|
525
692
|
function isBlockedHost(hostname) {
|
|
526
|
-
if (hostname === "localhost"
|
|
527
|
-
|
|
693
|
+
if (hostname === "localhost") return true;
|
|
694
|
+
if (hostname.startsWith("[") && hostname.endsWith("]")) {
|
|
695
|
+
const bare = hostname.slice(1, -1);
|
|
696
|
+
return isIPv6(bare) ? isBlockedIPv6(bare) : true;
|
|
528
697
|
}
|
|
529
|
-
if (hostname
|
|
530
|
-
return
|
|
531
|
-
}
|
|
532
|
-
if (hostname === "169.254.169.254") {
|
|
533
|
-
return true;
|
|
698
|
+
if (isIPv6(hostname)) {
|
|
699
|
+
return isBlockedIPv6(hostname);
|
|
534
700
|
}
|
|
535
|
-
|
|
536
|
-
|
|
537
|
-
const [, a, b] = ipv4Match.map(Number);
|
|
538
|
-
if (a === 10) return true;
|
|
539
|
-
if (a === 172 && b >= 16 && b <= 31) return true;
|
|
540
|
-
if (a === 192 && b === 168) return true;
|
|
541
|
-
if (a === 127) return true;
|
|
542
|
-
if (a === 169 && b === 254) return true;
|
|
543
|
-
if (a === 0 && b === 0) return true;
|
|
544
|
-
}
|
|
545
|
-
if (hostname.startsWith("fe80:") || hostname.startsWith("[fe80:")) {
|
|
546
|
-
return true;
|
|
701
|
+
if (isIPv4(hostname)) {
|
|
702
|
+
return isBlockedIPv4(hostname);
|
|
547
703
|
}
|
|
548
704
|
return false;
|
|
549
705
|
}
|
|
550
706
|
function isBlockedIp(ip) {
|
|
551
|
-
|
|
552
|
-
if (
|
|
553
|
-
|
|
554
|
-
|
|
555
|
-
|
|
556
|
-
|
|
557
|
-
|
|
558
|
-
|
|
559
|
-
|
|
560
|
-
|
|
561
|
-
|
|
562
|
-
if (
|
|
707
|
+
if (isIPv4(ip)) return isBlockedIPv4(ip);
|
|
708
|
+
if (isIPv6(ip)) return isBlockedIPv6(ip);
|
|
709
|
+
return false;
|
|
710
|
+
}
|
|
711
|
+
function isBlockedIPv4(ip) {
|
|
712
|
+
const match = ip.match(/^(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})$/);
|
|
713
|
+
if (!match) return false;
|
|
714
|
+
const [, a, b] = match.map(Number);
|
|
715
|
+
return isBlockedIPv4Octets(a, b);
|
|
716
|
+
}
|
|
717
|
+
function isBlockedIPv4Octets(a, b) {
|
|
718
|
+
if (a === 0) return true;
|
|
719
|
+
if (a === 10) return true;
|
|
720
|
+
if (a === 100 && b >= 64 && b <= 127) return true;
|
|
721
|
+
if (a === 127) return true;
|
|
722
|
+
if (a === 169 && b === 254) return true;
|
|
723
|
+
if (a === 172 && b >= 16 && b <= 31) return true;
|
|
724
|
+
if (a === 192 && b === 168) return true;
|
|
725
|
+
if (a >= 224) return true;
|
|
563
726
|
return false;
|
|
564
727
|
}
|
|
728
|
+
function isBlockedIPv6(ip) {
|
|
729
|
+
const groups = expandIPv6(ip);
|
|
730
|
+
if (!groups) return false;
|
|
731
|
+
const allButLastZero = groups.slice(0, 7).every((g) => g === 0);
|
|
732
|
+
if (allButLastZero && groups[7] === 1) return true;
|
|
733
|
+
if (groups.every((g) => g === 0)) return true;
|
|
734
|
+
if (groups.slice(0, 5).every((g) => g === 0) && groups[5] === 65535) {
|
|
735
|
+
return isBlockedIPv4Octets(groups[6] >> 8 & 255, groups[6] & 255);
|
|
736
|
+
}
|
|
737
|
+
if (groups[0] === 100 && groups[1] === 65435 && groups.slice(2, 6).every((g) => g === 0)) {
|
|
738
|
+
return isBlockedIPv4Octets(groups[6] >> 8 & 255, groups[6] & 255);
|
|
739
|
+
}
|
|
740
|
+
if (groups[0] === 8194) {
|
|
741
|
+
return isBlockedIPv4Octets(groups[1] >> 8 & 255, groups[1] & 255);
|
|
742
|
+
}
|
|
743
|
+
if (groups[0] === 8193 && groups[1] === 0) return true;
|
|
744
|
+
if (groups[0] === 256 && groups.slice(1, 4).every((g) => g === 0)) return true;
|
|
745
|
+
if ((groups[0] & 65024) === 64512) return true;
|
|
746
|
+
if ((groups[0] & 65472) === 65152) return true;
|
|
747
|
+
if ((groups[0] & 65280) === 65280) return true;
|
|
748
|
+
return false;
|
|
749
|
+
}
|
|
750
|
+
function expandIPv6(addr) {
|
|
751
|
+
const noZone = addr.split("%")[0];
|
|
752
|
+
if (!isIPv6(noZone)) return null;
|
|
753
|
+
let normalized = noZone.toLowerCase();
|
|
754
|
+
const v4Tail = normalized.match(/^(.*:)(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})$/);
|
|
755
|
+
if (v4Tail) {
|
|
756
|
+
const a = parseInt(v4Tail[2], 10);
|
|
757
|
+
const b = parseInt(v4Tail[3], 10);
|
|
758
|
+
const c = parseInt(v4Tail[4], 10);
|
|
759
|
+
const d = parseInt(v4Tail[5], 10);
|
|
760
|
+
if ([a, b, c, d].some((n) => n > 255)) return null;
|
|
761
|
+
const hi = (a << 8 | b).toString(16);
|
|
762
|
+
const lo = (c << 8 | d).toString(16);
|
|
763
|
+
normalized = `${v4Tail[1]}${hi}:${lo}`;
|
|
764
|
+
}
|
|
765
|
+
const halves = normalized.split("::");
|
|
766
|
+
let parts;
|
|
767
|
+
if (halves.length === 1) {
|
|
768
|
+
parts = halves[0].split(":");
|
|
769
|
+
if (parts.length !== 8) return null;
|
|
770
|
+
} else if (halves.length === 2) {
|
|
771
|
+
const head = halves[0] ? halves[0].split(":") : [];
|
|
772
|
+
const tail = halves[1] ? halves[1].split(":") : [];
|
|
773
|
+
const missing = 8 - head.length - tail.length;
|
|
774
|
+
if (missing < 0) return null;
|
|
775
|
+
parts = [...head, ...Array(missing).fill("0"), ...tail];
|
|
776
|
+
} else {
|
|
777
|
+
return null;
|
|
778
|
+
}
|
|
779
|
+
const groups = [];
|
|
780
|
+
for (const part of parts) {
|
|
781
|
+
if (!/^[0-9a-f]{1,4}$/.test(part)) return null;
|
|
782
|
+
groups.push(parseInt(part, 16));
|
|
783
|
+
}
|
|
784
|
+
return groups;
|
|
785
|
+
}
|
|
565
786
|
|
|
566
787
|
export {
|
|
567
788
|
MemoryEventTransport,
|
|
568
789
|
SocketIOEventTransport,
|
|
569
790
|
WebhookEventTransport
|
|
570
791
|
};
|
|
571
|
-
//# sourceMappingURL=chunk-
|
|
792
|
+
//# sourceMappingURL=chunk-D5HW7VEG.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/events/memory.ts","../src/events/socketio.ts","../src/events/webhook.ts","../src/utils/pinned-fetch.ts"],"sourcesContent":["/**\n * In-memory event transport using Node.js EventEmitter.\n * Default transport for development and single-process deployments.\n *\n * NOTE: This adapter is intended for development and testing only. It stores\n * all state in-process with no persistence or multi-process safety guarantees.\n */\n\nimport { EventEmitter } from 'events';\nimport type {\n EventTransport,\n WorkflowEvent,\n WorkflowEventType,\n EventCallback,\n Unsubscribe,\n} from './types';\n\n/**\n * In-memory event transport implementation using EventEmitter.\n * Events are emitted to subscribers in the same process.\n */\nexport class MemoryEventTransport implements EventTransport {\n private emitter = new EventEmitter();\n\n constructor() {\n // Increase max listeners to avoid warnings in workflows with many steps\n this.emitter.setMaxListeners(100);\n }\n\n /**\n * Emit an event to all subscribers.\n * Each channel is isolated so a failing listener on one channel\n * cannot prevent delivery to the others.\n */\n emit(event: WorkflowEvent): void {\n // Emit to run-specific subscribers first (most targeted)\n this.emitter.emit(`run:${event.runId}`, event);\n\n // Emit to event-type subscribers\n this.emitter.emit(`type:${event.eventType}`, event);\n\n // Emit to global subscribers last (broadest, most likely to have side effects)\n this.emitter.emit('event', event);\n }\n\n /**\n * Subscribe to events for a specific run.\n */\n subscribe(runId: string, callback: EventCallback): Unsubscribe {\n const channel = `run:${runId}`;\n this.emitter.on(channel, callback);\n return () => {\n this.emitter.off(channel, callback);\n };\n }\n\n /**\n * Subscribe to all events.\n */\n subscribeAll(callback: EventCallback): Unsubscribe {\n this.emitter.on('event', callback);\n return () => {\n this.emitter.off('event', callback);\n };\n }\n\n /**\n * Subscribe to events of a specific type.\n */\n subscribeToType(eventType: WorkflowEventType, callback: EventCallback): Unsubscribe {\n const channel = `type:${eventType}`;\n this.emitter.on(channel, callback);\n return () => {\n this.emitter.off(channel, callback);\n };\n }\n\n /**\n * Close the transport and remove all listeners.\n */\n close(): void {\n this.emitter.removeAllListeners();\n }\n\n /**\n * Get the number of listeners for a channel (for testing).\n */\n getListenerCount(channel?: string): number {\n if (channel) {\n return this.emitter.listenerCount(channel);\n }\n return this.emitter.listenerCount('event');\n }\n}\n","/**\n * Socket.IO Event Transport\n *\n * Broadcasts workflow events to connected clients via Socket.IO.\n * Clients can subscribe to specific run IDs or receive all events.\n */\n\nimport type { EventTransport, EventCallback, Unsubscribe, WorkflowEvent } from './types';\nimport type { Logger } from '../core/types';\n\n/**\n * Minimal Socket.IO Server interface.\n * This allows using the adapter without a direct dependency on socket.io.\n */\nexport interface SocketIOServer {\n to(room: string): {\n emit(event: string, ...args: unknown[]): void;\n };\n emit(event: string, ...args: unknown[]): void;\n}\n\n/**\n * Minimal Socket.IO Socket interface.\n */\nexport interface SocketIOSocket {\n join(room: string): void;\n leave(room: string): void;\n on(event: string, callback: (...args: unknown[]) => void): void;\n}\n\n/**\n * Authorization callback for Socket.IO run subscriptions.\n * Return true to allow the subscription, false to deny it.\n */\nexport type SocketIOAuthorizeFn = (\n runId: string,\n socket: SocketIOSocket\n) => boolean | Promise<boolean>;\n\n/**\n * Configuration for SocketIOEventTransport.\n */\nexport interface SocketIOEventTransportConfig {\n /** Socket.IO server instance */\n io: SocketIOServer;\n\n /** Event name to use for workflow events (default: 'workflow:event') */\n eventName?: string;\n\n /** Room prefix for run-specific subscriptions (default: 'run:') */\n roomPrefix?: string;\n\n /** Whether to also broadcast to a global room (default: true) */\n broadcastGlobal?: boolean;\n\n /** Global room name (default: 'workflow:all') */\n globalRoom?: string;\n\n /** Logger for transport errors (default: console-based) */\n logger?: Logger;\n}\n\n/**\n * Socket.IO-based event transport for real-time workflow events.\n *\n * @example\n * ```typescript\n * import { Server } from 'socket.io';\n * import { SocketIOEventTransport } from 'stepflow';\n *\n * const io = new Server(httpServer);\n * const eventTransport = new SocketIOEventTransport({ io });\n *\n * const engine = new WorkflowEngine({\n * storage,\n * events: eventTransport,\n * });\n *\n * // Client-side:\n * // socket.emit('workflow:subscribe', runId);\n * // socket.on('workflow:event', (event) => console.log(event));\n * ```\n */\nexport class SocketIOEventTransport implements EventTransport {\n private io: SocketIOServer;\n private eventName: string;\n private roomPrefix: string;\n private broadcastGlobal: boolean;\n private globalRoom: string;\n private logger: Logger;\n\n // Local subscribers for server-side subscriptions\n private runSubscribers = new Map<string, Set<EventCallback>>();\n private globalSubscribers = new Set<EventCallback>();\n\n constructor(config: SocketIOEventTransportConfig) {\n this.io = config.io;\n this.eventName = config.eventName ?? 'workflow:event';\n this.roomPrefix = config.roomPrefix ?? 'run:';\n this.broadcastGlobal = config.broadcastGlobal ?? true;\n this.globalRoom = config.globalRoom ?? 'workflow:all';\n this.logger = config.logger ?? {\n debug() {},\n info() {},\n warn() {},\n error(message: string, ...args: unknown[]) { console.error(message, ...args); },\n };\n }\n\n /**\n * Emit an event to Socket.IO clients and local subscribers.\n */\n emit(event: WorkflowEvent): void {\n // Serialize the event (convert Date to ISO string for transport)\n const serializedEvent = {\n ...event,\n timestamp: event.timestamp.toISOString(),\n };\n\n // Emit to run-specific room\n const room = `${this.roomPrefix}${event.runId}`;\n this.io.to(room).emit(this.eventName, serializedEvent);\n\n // Emit to global room\n if (this.broadcastGlobal) {\n this.io.to(this.globalRoom).emit(this.eventName, serializedEvent);\n }\n\n // Notify local subscribers\n const runSubs = this.runSubscribers.get(event.runId);\n if (runSubs) {\n for (const callback of runSubs) {\n try {\n callback(event);\n } catch (error) {\n this.logger.error('Event callback error:', error);\n }\n }\n }\n\n for (const callback of this.globalSubscribers) {\n try {\n callback(event);\n } catch (error) {\n this.logger.error('Event callback error:', error);\n }\n }\n }\n\n /**\n * Subscribe to events for a specific run (server-side).\n */\n subscribe(runId: string, callback: EventCallback): Unsubscribe {\n let subs = this.runSubscribers.get(runId);\n if (!subs) {\n subs = new Set();\n this.runSubscribers.set(runId, subs);\n }\n subs.add(callback);\n\n return () => {\n subs!.delete(callback);\n if (subs!.size === 0) {\n this.runSubscribers.delete(runId);\n }\n };\n }\n\n /**\n * Subscribe to all events (server-side).\n */\n subscribeAll(callback: EventCallback): Unsubscribe {\n this.globalSubscribers.add(callback);\n return () => {\n this.globalSubscribers.delete(callback);\n };\n }\n\n /**\n * Set up client subscription handlers on a socket.\n * Call this when a client connects to enable subscription commands.\n *\n * An `authorize` callback is required to prevent unauthorized access to run events.\n * The callback receives the run ID (or `'*'` for global subscriptions) and the socket,\n * and must return `true` to allow or `false` to deny the subscription.\n *\n * @param socket - The Socket.IO socket to set up handlers on\n * @param authorize - Callback to check if a socket can access a run.\n *\n * @example\n * ```typescript\n * io.on('connection', (socket) => {\n * eventTransport.setupClientHandlers(socket, async (runId, sock) => {\n * // Check if the authenticated user owns this run\n * const userId = sock.data?.userId;\n * return userId ? await canUserAccessRun(userId, runId) : false;\n * });\n * });\n * ```\n */\n setupClientHandlers(\n socket: SocketIOSocket,\n authorize: SocketIOAuthorizeFn\n ): void {\n // Subscribe to a specific run\n socket.on('workflow:subscribe', async (...args: unknown[]) => {\n const runId = args[0];\n if (typeof runId !== 'string') return;\n\n try {\n const allowed = await authorize(runId, socket);\n if (!allowed) {\n this.logger.warn(`Subscription denied for run ${runId}`);\n return;\n }\n } catch (error) {\n this.logger.error('Authorization check failed:', error);\n return;\n }\n\n socket.join(`${this.roomPrefix}${runId}`);\n });\n\n // Unsubscribe from a specific run\n socket.on('workflow:unsubscribe', (...args: unknown[]) => {\n const runId = args[0];\n if (typeof runId === 'string') {\n socket.leave(`${this.roomPrefix}${runId}`);\n }\n });\n\n // Subscribe to all events (requires authorization to pass with '*' as runId)\n socket.on('workflow:subscribe:all', async () => {\n try {\n const allowed = await authorize('*', socket);\n if (!allowed) {\n this.logger.warn('Global subscription denied');\n return;\n }\n } catch (error) {\n this.logger.error('Authorization check failed:', error);\n return;\n }\n\n socket.join(this.globalRoom);\n });\n\n // Unsubscribe from all events\n socket.on('workflow:unsubscribe:all', () => {\n socket.leave(this.globalRoom);\n });\n }\n\n /**\n * Clear all in-process server-side subscribers.\n * The underlying Socket.IO server socket is not closed here — manage its lifecycle externally.\n */\n close(): void {\n this.runSubscribers.clear();\n this.globalSubscribers.clear();\n }\n}\n","/**\n * Webhook Event Transport\n *\n * Posts workflow events to HTTP endpoints via webhooks.\n * Supports multiple webhooks with optional filtering by event type.\n */\n\nimport { promises as dns } from 'node:dns';\nimport { isIPv4, isIPv6 } from 'node:net';\nimport { pinnedFetch } from '../utils/pinned-fetch';\nimport type { EventTransport, EventCallback, Unsubscribe, WorkflowEvent, WorkflowEventType } from './types';\nimport type { Logger } from '../core/types';\n\n/**\n * Webhook endpoint configuration.\n */\nexport interface WebhookEndpoint {\n /** Unique identifier for this endpoint */\n id: string;\n\n /** URL to POST events to */\n url: string;\n\n /** Optional secret for signing payloads (HMAC-SHA256) */\n secret?: string;\n\n /** Optional filter for specific event types (empty = all events) */\n eventTypes?: WorkflowEventType[];\n\n /** Optional filter for specific workflow kinds (empty = all kinds) */\n workflowKinds?: string[];\n\n /** Optional custom headers to include */\n headers?: Record<string, string>;\n\n /** Whether this endpoint is enabled (default: true) */\n enabled?: boolean;\n\n /** Timeout in milliseconds (default: 5000) */\n timeout?: number;\n\n /** Number of retry attempts on failure (default: 3) */\n retries?: number;\n}\n\n/**\n * Configuration for WebhookEventTransport.\n */\nexport interface WebhookEventTransportConfig {\n /** Initial webhook endpoints */\n endpoints?: WebhookEndpoint[];\n\n /** Default timeout for all webhooks in ms (default: 5000) */\n defaultTimeout?: number;\n\n /** Default retry attempts (default: 3) */\n defaultRetries?: number;\n\n /** Retry delay in ms (default: 1000) */\n retryDelay?: number;\n\n /** Custom fetch function (for testing or custom HTTP clients) */\n fetchFn?: typeof fetch;\n\n /**\n * Whether to allow non-HTTPS URLs (default: false).\n * Set to true only in development environments.\n */\n allowInsecureUrls?: boolean;\n\n /**\n * Maximum payload size in bytes (default: 1048576 = 1 MB).\n * Payloads exceeding this limit will be rejected.\n */\n maxPayloadBytes?: number;\n\n /**\n * Maximum concurrent webhook requests across all endpoints (default: 50).\n * Requests beyond this limit are queued.\n */\n maxConcurrentRequests?: number;\n\n /**\n * Maximum number of queued webhook deliveries waiting for a concurrency slot\n * (default: 1000, env override: `STEPFLOW_WEBHOOK_MAX_QUEUE_DEPTH`).\n *\n * When the queue is full, incoming `emit()` deliveries are dropped to\n * protect the process from memory exhaustion under burst traffic. Drops\n * are logged via `logger.warn` with the endpoint id, current queue depth,\n * and a recommended `retryAfterMs`. A value of `0` disables the cap (not\n * recommended in production).\n */\n maxQueueDepth?: number;\n\n /**\n * Suggested back-off in milliseconds reported on dropped deliveries\n * (default: 1000). Surfaced in the warning log so external orchestrators\n * (sidecars, sweeper jobs) can respect it like an HTTP `Retry-After`.\n */\n queueDropRetryAfterMs?: number;\n\n /** Logger for webhook transport errors (default: console-based) */\n logger?: import('../core/types').Logger;\n}\n\n/**\n * Webhook payload structure sent to external endpoints.\n */\nexport interface WebhookPayload {\n /**\n * The workflow event with `timestamp` serialized as an ISO 8601 string.\n * The `Date` is converted to a string before delivery so that JSON consumers\n * receive a portable, timezone-aware representation without needing Date parsing.\n */\n event: Omit<WorkflowEvent, 'timestamp'> & { timestamp: string };\n /** ISO 8601 timestamp of when this payload was delivered. */\n deliveredAt: string;\n /** ID of the webhook endpoint that received this delivery. */\n webhookId: string;\n}\n\n/**\n * Webhook-based event transport for integrating with external systems.\n *\n * @example\n * ```typescript\n * const webhookTransport = new WebhookEventTransport({\n * endpoints: [\n * {\n * id: 'slack-notifications',\n * url: 'https://hooks.slack.com/...',\n * eventTypes: ['run.completed', 'run.failed'],\n * },\n * {\n * id: 'analytics',\n * url: 'https://api.analytics.com/events',\n * secret: process.env.WEBHOOK_SECRET, // Use a cryptographically random secret (≥ 32 bytes)\n * },\n * ],\n * });\n *\n * const engine = new WorkflowEngine({\n * storage,\n * events: webhookTransport,\n * });\n * ```\n */\nexport class WebhookEventTransport implements EventTransport {\n private endpoints = new Map<string, WebhookEndpoint>();\n private defaultTimeout: number;\n private defaultRetries: number;\n private retryDelay: number;\n private fetchFn: typeof fetch;\n /**\n * Whether `fetchFn` was caller-supplied. When `false` the default fetch is\n * replaced with `pinnedFetch` so the TCP connection can target the IP that\n * was just validated (closes the DNS-rebinding TOCTOU window). When `true`\n * the custom fetch is used as-is so test injection still works.\n */\n private hasCustomFetch: boolean;\n private allowInsecureUrls: boolean;\n private maxPayloadBytes: number;\n private maxConcurrentRequests: number;\n private maxQueueDepth: number;\n private queueDropRetryAfterMs: number;\n private activeRequests = 0;\n private requestQueue: Array<() => void> = [];\n private droppedRequests = 0;\n private logger: Logger;\n\n // DNS resolution cache with TTL — stores `family` so the pin can reuse it\n // without a second lookup.\n private dnsCache = new Map<string, { address: string; family: 4 | 6; expiresAt: number }>();\n private static readonly DNS_CACHE_TTL_MS = 30_000; // 30 seconds\n private static readonly DNS_TIMEOUT_MS = 5_000; // 5 seconds\n\n // Local subscribers for server-side subscriptions\n private runSubscribers = new Map<string, Set<EventCallback>>();\n private globalSubscribers = new Set<EventCallback>();\n\n constructor(config: WebhookEventTransportConfig = {}) {\n this.defaultTimeout = config.defaultTimeout ?? 5000;\n this.defaultRetries = config.defaultRetries ?? 3;\n this.retryDelay = config.retryDelay ?? 1000;\n this.hasCustomFetch = config.fetchFn !== undefined;\n this.fetchFn = config.fetchFn ?? globalThis.fetch;\n this.allowInsecureUrls = config.allowInsecureUrls ?? false;\n this.maxPayloadBytes = config.maxPayloadBytes ?? 1_048_576; // 1 MB\n this.maxConcurrentRequests = config.maxConcurrentRequests ?? 50;\n if (this.maxConcurrentRequests <= 0) {\n throw new Error('maxConcurrentRequests must be greater than 0');\n }\n this.maxQueueDepth = resolveMaxQueueDepth(config.maxQueueDepth);\n if (this.maxQueueDepth < 0) {\n throw new Error('maxQueueDepth must be >= 0 (0 disables the cap)');\n }\n this.queueDropRetryAfterMs = config.queueDropRetryAfterMs ?? 1000;\n this.logger = config.logger ?? {\n debug() {},\n info() {},\n warn() {},\n error(message: string, ...args: unknown[]) { console.error(message, ...args); },\n };\n\n if (this.allowInsecureUrls) {\n this.logger.warn('WebhookEventTransport: allowInsecureUrls is enabled. Webhook payloads will be sent over HTTP. Do not use this setting in production.');\n }\n\n // Register initial endpoints (validates URLs)\n if (config.endpoints) {\n for (const endpoint of config.endpoints) {\n this.addEndpoint(endpoint);\n }\n }\n }\n\n /**\n * Add a webhook endpoint.\n * Validates the URL to prevent SSRF attacks.\n * @throws Error if the URL scheme is not allowed\n */\n addEndpoint(endpoint: WebhookEndpoint): void {\n this.validateWebhookUrl(endpoint.url);\n this.endpoints.set(endpoint.id, { enabled: true, ...endpoint });\n }\n\n /**\n * Remove a webhook endpoint.\n */\n removeEndpoint(id: string): boolean {\n return this.endpoints.delete(id);\n }\n\n /**\n * Get all registered endpoints.\n */\n getEndpoints(): WebhookEndpoint[] {\n return Array.from(this.endpoints.values());\n }\n\n /**\n * Enable or disable an endpoint.\n */\n setEndpointEnabled(id: string, enabled: boolean): void {\n const endpoint = this.endpoints.get(id);\n if (endpoint) {\n endpoint.enabled = enabled;\n }\n }\n\n /**\n * Emit an event to all matching webhook endpoints.\n */\n emit(event: WorkflowEvent): void {\n // Notify local subscribers first (synchronously)\n const runSubs = this.runSubscribers.get(event.runId);\n if (runSubs) {\n for (const callback of runSubs) {\n try {\n callback(event);\n } catch (error) {\n this.logger.error('Event callback error:', error);\n }\n }\n }\n\n for (const callback of this.globalSubscribers) {\n try {\n callback(event);\n } catch (error) {\n this.logger.error('Event callback error:', error);\n }\n }\n\n // Send to webhooks asynchronously with concurrency control\n for (const endpoint of this.endpoints.values()) {\n if (!endpoint.enabled) continue;\n if (!this.matchesFilter(event, endpoint)) continue;\n\n const accepted = this.enqueueRequest(\n () =>\n this.sendWebhook(endpoint, event).catch((error) => {\n this.logger.error(`Webhook ${endpoint.id} failed:`, error);\n }),\n endpoint.id\n );\n\n if (!accepted) {\n // Queue overflow — equivalent to a server returning 429 with Retry-After.\n // The delivery is dropped to protect the process from memory exhaustion.\n this.droppedRequests++;\n this.logger.warn(\n `Webhook ${endpoint.id} delivery dropped: queue full ` +\n `(depth ${this.requestQueue.length}/${this.maxQueueDepth}, ` +\n `active ${this.activeRequests}/${this.maxConcurrentRequests}, ` +\n `total drops ${this.droppedRequests}, retryAfterMs ${this.queueDropRetryAfterMs})`\n );\n }\n }\n }\n\n /**\n * Number of webhook deliveries dropped due to queue overflow since startup.\n * Useful for surfacing back-pressure to operators (metrics/health checks).\n */\n getDroppedRequestCount(): number {\n return this.droppedRequests;\n }\n\n /**\n * Current depth of the pending request queue.\n */\n getQueueDepth(): number {\n return this.requestQueue.length;\n }\n\n /**\n * Subscribe to events for a specific run (server-side).\n */\n subscribe(runId: string, callback: EventCallback): Unsubscribe {\n let subs = this.runSubscribers.get(runId);\n if (!subs) {\n subs = new Set();\n this.runSubscribers.set(runId, subs);\n }\n subs.add(callback);\n\n return () => {\n subs!.delete(callback);\n if (subs!.size === 0) {\n this.runSubscribers.delete(runId);\n }\n };\n }\n\n /**\n * Subscribe to all events (server-side).\n */\n subscribeAll(callback: EventCallback): Unsubscribe {\n this.globalSubscribers.add(callback);\n return () => {\n this.globalSubscribers.delete(callback);\n };\n }\n\n /**\n * Close the transport.\n */\n close(): void {\n this.runSubscribers.clear();\n this.globalSubscribers.clear();\n this.endpoints.clear();\n }\n\n /**\n * Check if an event matches an endpoint's filters.\n */\n private matchesFilter(event: WorkflowEvent, endpoint: WebhookEndpoint): boolean {\n // Check event type filter\n if (endpoint.eventTypes && endpoint.eventTypes.length > 0) {\n if (!endpoint.eventTypes.includes(event.eventType)) {\n return false;\n }\n }\n\n // Check workflow kind filter\n if (endpoint.workflowKinds && endpoint.workflowKinds.length > 0) {\n if (!endpoint.workflowKinds.includes(event.kind)) {\n return false;\n }\n }\n\n return true;\n }\n\n /**\n * Send a webhook with retry support.\n */\n private async sendWebhook(endpoint: WebhookEndpoint, event: WorkflowEvent): Promise<void> {\n const timeout = endpoint.timeout ?? this.defaultTimeout;\n const maxRetries = endpoint.retries ?? this.defaultRetries;\n\n const payload: WebhookPayload = {\n event: {\n ...event,\n timestamp: event.timestamp.toISOString(),\n },\n deliveredAt: new Date().toISOString(),\n webhookId: endpoint.id,\n };\n\n const body = JSON.stringify(payload);\n\n // Enforce payload size limit to prevent excessive memory use and network abuse\n if (body.length > this.maxPayloadBytes) {\n throw new Error(\n `Webhook payload exceeds maximum size (${body.length} bytes > ${this.maxPayloadBytes} bytes)`\n );\n }\n\n const headers: Record<string, string> = {\n 'Content-Type': 'application/json',\n ...endpoint.headers,\n };\n\n // Sign payload if secret is provided\n if (endpoint.secret) {\n const signature = await this.signPayload(body, endpoint.secret);\n headers['X-Webhook-Signature'] = signature;\n }\n\n let lastError: Error | undefined;\n\n for (let attempt = 0; attempt <= maxRetries; attempt++) {\n try {\n // Resolve the hostname once and validate the resulting IP is not\n // private/reserved (SSRF protection). When the default fetch is used,\n // the resolved IP is then pinned for the connection so a hostile DNS\n // server cannot rebind the hostname to a different address between\n // validation and connect (M1: rebinding TOCTOU). The lookup runs\n // inside the retry loop so DNS failures are retried along with\n // network errors.\n const pinned = await this.validateResolvedHost(endpoint.url);\n\n const controller = new AbortController();\n const timeoutId = setTimeout(() => controller.abort(), timeout);\n\n const response = this.hasCustomFetch || !pinned\n ? await this.fetchFn(endpoint.url, {\n method: 'POST',\n headers,\n body,\n signal: controller.signal,\n })\n : await pinnedFetch(\n endpoint.url,\n { method: 'POST', headers, body, signal: controller.signal },\n pinned.address,\n pinned.family,\n );\n\n clearTimeout(timeoutId);\n\n if (response.ok) {\n return; // Success\n }\n\n lastError = new Error(`Webhook returned ${response.status}: ${response.statusText}`);\n } catch (error) {\n lastError = error instanceof Error ? error : new Error(String(error));\n }\n\n // Wait before retrying (except on last attempt)\n if (attempt < maxRetries) {\n await this.sleep(this.retryDelay * Math.pow(2, attempt));\n }\n }\n\n throw lastError;\n }\n\n /**\n * Sign a payload using HMAC-SHA256.\n */\n private async signPayload(payload: string, secret: string): Promise<string> {\n // Use Web Crypto API for HMAC-SHA256\n const encoder = new TextEncoder();\n const keyData = encoder.encode(secret);\n const data = encoder.encode(payload);\n\n const key = await crypto.subtle.importKey(\n 'raw',\n keyData,\n { name: 'HMAC', hash: 'SHA-256' },\n false,\n ['sign']\n );\n\n const signature = await crypto.subtle.sign('HMAC', key, data);\n const hashArray = Array.from(new Uint8Array(signature));\n const hashHex = hashArray.map(b => b.toString(16).padStart(2, '0')).join('');\n\n return `sha256=${hashHex}`;\n }\n\n /**\n * Sleep helper.\n */\n private sleep(ms: number): Promise<void> {\n return new Promise(resolve => setTimeout(resolve, ms));\n }\n\n /**\n * Resolve a webhook URL's hostname exactly once, verify the resolved IP is\n * not private/reserved, and return the address + family so the caller can\n * pin the connection to it.\n *\n * Returns `null` for raw-IP URLs (already validated by `validateWebhookUrl`).\n *\n * Pinning the resolved IP closes the DNS rebinding TOCTOU window (audit M1):\n * with the original implementation `fetch()` re-resolved the hostname,\n * giving a hostile DNS server a chance to flip the answer to an internal\n * address between SSRF validation and connect.\n *\n * Uses a short-TTL cache and per-call timeout to avoid blocking the event loop.\n */\n private async validateResolvedHost(\n url: string,\n ): Promise<{ address: string; family: 4 | 6 } | null> {\n const parsed = new URL(url);\n const hostname = parsed.hostname.toLowerCase();\n\n // Skip DNS resolution for raw IP literals — already checked by isBlockedHost in validateWebhookUrl.\n // Node's URL parser wraps IPv6 literals in brackets (e.g., \"[2001:db8::1]\").\n const stripped = hostname.startsWith('[') ? hostname.slice(1, -1) : hostname;\n if (isIPv4(stripped) || isIPv6(stripped)) {\n return null;\n }\n\n // Check cache first\n const cached = this.dnsCache.get(hostname);\n if (cached && cached.expiresAt > Date.now()) {\n if (isBlockedIp(cached.address)) {\n throw new Error(\n `Webhook URL hostname \"${hostname}\" resolves to blocked IP ${cached.address}`\n );\n }\n return { address: cached.address, family: cached.family };\n }\n\n try {\n const ac = new AbortController();\n const timeoutId = setTimeout(() => ac.abort(), WebhookEventTransport.DNS_TIMEOUT_MS);\n\n let address: string;\n let family: 4 | 6;\n try {\n const result = await dns.lookup(hostname, { signal: ac.signal } as any);\n address = result.address;\n family = (result.family === 6 ? 6 : 4) as 4 | 6;\n } finally {\n clearTimeout(timeoutId);\n }\n\n // Cache the result\n this.dnsCache.set(hostname, {\n address,\n family,\n expiresAt: Date.now() + WebhookEventTransport.DNS_CACHE_TTL_MS,\n });\n\n if (isBlockedIp(address)) {\n throw new Error(\n `Webhook URL hostname \"${hostname}\" resolves to blocked IP ${address}`\n );\n }\n\n return { address, family };\n } catch (error) {\n if (error instanceof Error && error.message.includes('resolves to blocked IP')) {\n throw error;\n }\n if (error instanceof Error && error.name === 'AbortError') {\n throw new Error(`DNS lookup for webhook URL hostname \"${hostname}\" timed out`);\n }\n throw new Error(`Failed to resolve webhook URL hostname \"${hostname}\": ${error}`);\n }\n }\n\n /**\n * Validate a webhook URL to prevent SSRF attacks.\n * Blocks non-HTTPS schemes (unless allowInsecureUrls is set),\n * and rejects private/reserved IP ranges and cloud metadata endpoints.\n */\n private validateWebhookUrl(url: string): void {\n let parsed: URL;\n try {\n parsed = new URL(url);\n } catch {\n throw new Error(`Invalid webhook URL: ${url}`);\n }\n\n // Scheme check\n if (!this.allowInsecureUrls && parsed.protocol !== 'https:') {\n throw new Error(\n `Webhook URL must use HTTPS (got ${parsed.protocol}). Set allowInsecureUrls for development.`\n );\n }\n\n if (parsed.protocol !== 'https:' && parsed.protocol !== 'http:') {\n throw new Error(`Webhook URL must use HTTP(S) scheme (got ${parsed.protocol})`);\n }\n\n // Block dangerous hostnames\n const hostname = parsed.hostname.toLowerCase();\n if (isBlockedHost(hostname)) {\n throw new Error(`Webhook URL hostname is blocked (private/reserved): ${hostname}`);\n }\n }\n\n /**\n * Enqueue a webhook request with concurrency limiting and a queue-depth cap.\n * Returns `true` if the request was accepted (executed or queued), or\n * `false` if the queue is full and the request was rejected. The caller is\n * responsible for logging the drop and incrementing any drop metrics, since\n * it has the endpoint context.\n */\n private enqueueRequest(fn: () => Promise<void>, _endpointId: string): boolean {\n const execute = () => {\n this.activeRequests++;\n fn().finally(() => {\n this.activeRequests--;\n const next = this.requestQueue.shift();\n if (next) next();\n });\n };\n\n if (this.activeRequests < this.maxConcurrentRequests) {\n execute();\n return true;\n }\n\n if (this.maxQueueDepth > 0 && this.requestQueue.length >= this.maxQueueDepth) {\n return false;\n }\n\n this.requestQueue.push(execute);\n return true;\n }\n}\n\n/**\n * Resolve the effective `maxQueueDepth` from explicit config and the\n * `STEPFLOW_WEBHOOK_MAX_QUEUE_DEPTH` environment variable.\n *\n * Precedence: explicit config value > env var > default (1000).\n */\nfunction resolveMaxQueueDepth(configured: number | undefined): number {\n if (typeof configured === 'number') return configured;\n const env = typeof process !== 'undefined' ? process.env?.STEPFLOW_WEBHOOK_MAX_QUEUE_DEPTH : undefined;\n if (env !== undefined && env !== '') {\n const parsed = Number(env);\n if (Number.isFinite(parsed) && parsed >= 0) return parsed;\n }\n return 1000;\n}\n\n/**\n * Check if a hostname (as it appears in a URL) is blocked.\n * Handles bare hostnames, IPv4 literals, and bracketed IPv6 literals.\n */\nfunction isBlockedHost(hostname: string): boolean {\n if (hostname === 'localhost') return true;\n\n // IPv6 literals are wrapped in brackets by Node's URL parser, e.g. \"[::1]\".\n if (hostname.startsWith('[') && hostname.endsWith(']')) {\n const bare = hostname.slice(1, -1);\n return isIPv6(bare) ? isBlockedIPv6(bare) : true;\n }\n\n // Some callers (or legacy code paths) may pass an unwrapped IPv6 literal.\n if (isIPv6(hostname)) {\n return isBlockedIPv6(hostname);\n }\n\n if (isIPv4(hostname)) {\n return isBlockedIPv4(hostname);\n }\n\n return false;\n}\n\n/**\n * Check if a resolved IP address falls within a private/reserved range.\n * Used for runtime DNS resolution validation to prevent SSRF via DNS rebinding.\n */\nfunction isBlockedIp(ip: string): boolean {\n if (isIPv4(ip)) return isBlockedIPv4(ip);\n if (isIPv6(ip)) return isBlockedIPv6(ip);\n return false;\n}\n\n/**\n * Block IPv4 addresses in private, loopback, link-local, and cloud-metadata ranges.\n */\nfunction isBlockedIPv4(ip: string): boolean {\n const match = ip.match(/^(\\d{1,3})\\.(\\d{1,3})\\.(\\d{1,3})\\.(\\d{1,3})$/);\n if (!match) return false;\n const [, a, b] = match.map(Number);\n return isBlockedIPv4Octets(a, b);\n}\n\nfunction isBlockedIPv4Octets(a: number, b: number): boolean {\n // 0.0.0.0/8 — \"this network\"\n if (a === 0) return true;\n // 10.0.0.0/8 — RFC 1918 private\n if (a === 10) return true;\n // 100.64.0.0/10 — CGNAT\n if (a === 100 && b >= 64 && b <= 127) return true;\n // 127.0.0.0/8 — loopback\n if (a === 127) return true;\n // 169.254.0.0/16 — link-local (covers cloud metadata 169.254.169.254)\n if (a === 169 && b === 254) return true;\n // 172.16.0.0/12 — RFC 1918 private\n if (a === 172 && b >= 16 && b <= 31) return true;\n // 192.168.0.0/16 — RFC 1918 private\n if (a === 192 && b === 168) return true;\n // 224.0.0.0/4 multicast and 240.0.0.0/4 reserved (incl. 255.255.255.255 broadcast)\n if (a >= 224) return true;\n return false;\n}\n\n/**\n * Block IPv6 addresses in reserved, private, loopback, link-local, IPv4-mapped,\n * IPv4-translated, 6to4, and Teredo ranges. For mapped/embedded IPv4 forms,\n * the embedded IPv4 is decoded and rechecked against the IPv4 blocklist.\n */\nfunction isBlockedIPv6(ip: string): boolean {\n const groups = expandIPv6(ip);\n if (!groups) return false;\n\n // ::1 loopback and :: unspecified\n const allButLastZero = groups.slice(0, 7).every(g => g === 0);\n if (allButLastZero && groups[7] === 1) return true;\n if (groups.every(g => g === 0)) return true;\n\n // ::ffff:0:0/96 — IPv4-mapped IPv6 (decode embedded IPv4)\n if (groups.slice(0, 5).every(g => g === 0) && groups[5] === 0xffff) {\n return isBlockedIPv4Octets((groups[6] >> 8) & 0xff, groups[6] & 0xff);\n }\n\n // 64:ff9b::/96 — IPv4/IPv6 translation (RFC 6052) and 64:ff9b:1::/48 (RFC 8215)\n if (groups[0] === 0x64 && groups[1] === 0xff9b && groups.slice(2, 6).every(g => g === 0)) {\n return isBlockedIPv4Octets((groups[6] >> 8) & 0xff, groups[6] & 0xff);\n }\n\n // 2002::/16 — 6to4 (next 32 bits are the embedded IPv4)\n if (groups[0] === 0x2002) {\n return isBlockedIPv4Octets((groups[1] >> 8) & 0xff, groups[1] & 0xff);\n }\n\n // 2001::/32 — Teredo. Block conservatively; embedded server/client v4 fields\n // can mask private destinations and Teredo isn't a normal webhook target.\n if (groups[0] === 0x2001 && groups[1] === 0) return true;\n\n // 100::/64 — RFC 6666 Discard prefix\n if (groups[0] === 0x0100 && groups.slice(1, 4).every(g => g === 0)) return true;\n\n // fc00::/7 — Unique Local Addresses (fc00:: through fdff::)\n if ((groups[0] & 0xfe00) === 0xfc00) return true;\n\n // fe80::/10 — Link-local (fe80:: through febf::)\n if ((groups[0] & 0xffc0) === 0xfe80) return true;\n\n // ff00::/8 — Multicast\n if ((groups[0] & 0xff00) === 0xff00) return true;\n\n return false;\n}\n\n/**\n * Expand an IPv6 string into an array of 8 numeric hextets (0–0xffff).\n * Handles \"::\" abbreviation, embedded IPv4 dotted-quad, and zone IDs.\n * Returns null if the input is not a valid IPv6 address.\n */\nfunction expandIPv6(addr: string): number[] | null {\n // Strip zone identifier (e.g., \"fe80::1%eth0\")\n const noZone = addr.split('%')[0];\n if (!isIPv6(noZone)) return null;\n\n let normalized = noZone.toLowerCase();\n\n // Convert trailing dotted-quad (e.g., \"::ffff:192.168.0.1\") into two hextets.\n const v4Tail = normalized.match(/^(.*:)(\\d{1,3})\\.(\\d{1,3})\\.(\\d{1,3})\\.(\\d{1,3})$/);\n if (v4Tail) {\n const a = parseInt(v4Tail[2], 10);\n const b = parseInt(v4Tail[3], 10);\n const c = parseInt(v4Tail[4], 10);\n const d = parseInt(v4Tail[5], 10);\n if ([a, b, c, d].some(n => n > 255)) return null;\n const hi = ((a << 8) | b).toString(16);\n const lo = ((c << 8) | d).toString(16);\n normalized = `${v4Tail[1]}${hi}:${lo}`;\n }\n\n const halves = normalized.split('::');\n let parts: string[];\n if (halves.length === 1) {\n parts = halves[0].split(':');\n if (parts.length !== 8) return null;\n } else if (halves.length === 2) {\n const head = halves[0] ? halves[0].split(':') : [];\n const tail = halves[1] ? halves[1].split(':') : [];\n const missing = 8 - head.length - tail.length;\n if (missing < 0) return null;\n parts = [...head, ...Array(missing).fill('0'), ...tail];\n } else {\n return null;\n }\n\n const groups: number[] = [];\n for (const part of parts) {\n if (!/^[0-9a-f]{1,4}$/.test(part)) return null;\n groups.push(parseInt(part, 16));\n }\n return groups;\n}\n","/**\n * DNS-pinned fetch helper.\n *\n * Performs an HTTP(S) request that connects to a caller-supplied IP address\n * instead of re-resolving the URL hostname. Used by the webhook transport to\n * close the SSRF DNS-rebinding TOCTOU window: the hostname is resolved\n * exactly once (by the caller), the resolved IP is validated, and the\n * resolved IP is then pinned for the connection so the request cannot be\n * rerouted by a hostile DNS server.\n *\n * The original hostname is preserved for TLS SNI / certificate verification\n * and for the HTTP `Host` header.\n *\n * Audit: 2026-04-27 finding M1 — DNS TOCTOU between SSRF validation and\n * connect.\n */\n\nimport * as http from 'node:http';\nimport * as https from 'node:https';\nimport type { LookupAddress, LookupOptions } from 'node:dns';\n\n/** Minimal fetch-compatible Response surface used by the webhook transport. */\nexport interface PinnedFetchResponse {\n ok: boolean;\n status: number;\n statusText: string;\n}\n\n/** Subset of `RequestInit` accepted by `pinnedFetch`. */\nexport interface PinnedFetchInit {\n method?: string;\n headers?: Record<string, string>;\n body?: string;\n signal?: AbortSignal;\n}\n\n/**\n * Make an HTTP(S) request that connects to `address` instead of resolving\n * `url`'s hostname. Returns a minimal `Response`-shaped object compatible\n * with the webhook transport's status / ok checks.\n *\n * @throws Error on transport failure or abort\n */\nexport function pinnedFetch(\n url: string,\n init: PinnedFetchInit,\n address: string,\n family: 4 | 6 = 4,\n): Promise<PinnedFetchResponse> {\n const parsed = new URL(url);\n const isHttps = parsed.protocol === 'https:';\n const lib = isHttps ? https : http;\n const port = parsed.port ? Number(parsed.port) : isHttps ? 443 : 80;\n\n // `lookup` is called by the agent's socket-create path. By returning the\n // pre-validated address here we guarantee the TCP connection target is the\n // IP whose safety the caller already verified. Node may invoke this with\n // `{ all: true }` (expects an array result) or single-address mode\n // (expects positional address/family) — handle both for cross-version safety.\n const lookup = (\n _hostname: string,\n options: LookupOptions,\n cb: (err: NodeJS.ErrnoException | null, addr: string | LookupAddress[], fam?: number) => void,\n ): void => {\n if (options && options.all === true) {\n cb(null, [{ address, family }]);\n } else {\n cb(null, address, family);\n }\n };\n\n return new Promise<PinnedFetchResponse>((resolve, reject) => {\n const req = lib.request(\n {\n hostname: parsed.hostname,\n port,\n path: `${parsed.pathname || '/'}${parsed.search}`,\n method: init.method ?? 'GET',\n headers: init.headers,\n lookup,\n servername: parsed.hostname,\n },\n (res) => {\n // Drain the body — we only inspect status, but leaving the socket\n // half-read would leak it.\n res.resume();\n res.on('end', () => {\n const status = res.statusCode ?? 0;\n resolve({\n ok: status >= 200 && status < 300,\n status,\n statusText: res.statusMessage ?? '',\n });\n });\n res.on('error', reject);\n },\n );\n\n req.on('error', reject);\n\n if (init.signal) {\n if (init.signal.aborted) {\n req.destroy(new Error('Request aborted'));\n } else {\n init.signal.addEventListener(\n 'abort',\n () => req.destroy(new Error('Request aborted')),\n { once: true },\n );\n }\n }\n\n if (init.body !== undefined) {\n req.write(init.body);\n }\n req.end();\n });\n}\n"],"mappings":";AAQA,SAAS,oBAAoB;AAatB,IAAM,uBAAN,MAAqD;AAAA,EAClD,UAAU,IAAI,aAAa;AAAA,EAEnC,cAAc;AAEZ,SAAK,QAAQ,gBAAgB,GAAG;AAAA,EAClC;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAOA,KAAK,OAA4B;AAE/B,SAAK,QAAQ,KAAK,OAAO,MAAM,KAAK,IAAI,KAAK;AAG7C,SAAK,QAAQ,KAAK,QAAQ,MAAM,SAAS,IAAI,KAAK;AAGlD,SAAK,QAAQ,KAAK,SAAS,KAAK;AAAA,EAClC;AAAA;AAAA;AAAA;AAAA,EAKA,UAAU,OAAe,UAAsC;AAC7D,UAAM,UAAU,OAAO,KAAK;AAC5B,SAAK,QAAQ,GAAG,SAAS,QAAQ;AACjC,WAAO,MAAM;AACX,WAAK,QAAQ,IAAI,SAAS,QAAQ;AAAA,IACpC;AAAA,EACF;AAAA;AAAA;AAAA;AAAA,EAKA,aAAa,UAAsC;AACjD,SAAK,QAAQ,GAAG,SAAS,QAAQ;AACjC,WAAO,MAAM;AACX,WAAK,QAAQ,IAAI,SAAS,QAAQ;AAAA,IACpC;AAAA,EACF;AAAA;AAAA;AAAA;AAAA,EAKA,gBAAgB,WAA8B,UAAsC;AAClF,UAAM,UAAU,QAAQ,SAAS;AACjC,SAAK,QAAQ,GAAG,SAAS,QAAQ;AACjC,WAAO,MAAM;AACX,WAAK,QAAQ,IAAI,SAAS,QAAQ;AAAA,IACpC;AAAA,EACF;AAAA;AAAA;AAAA;AAAA,EAKA,QAAc;AACZ,SAAK,QAAQ,mBAAmB;AAAA,EAClC;AAAA;AAAA;AAAA;AAAA,EAKA,iBAAiB,SAA0B;AACzC,QAAI,SAAS;AACX,aAAO,KAAK,QAAQ,cAAc,OAAO;AA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