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