@blamejs/core 0.7.4 → 0.7.18

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 (180) hide show
  1. package/CHANGELOG.md +423 -395
  2. package/README.md +150 -149
  3. package/bin/blamejs.js +0 -0
  4. package/index.js +308 -284
  5. package/lib/api-key.js +660 -663
  6. package/lib/api-snapshot.js +338 -338
  7. package/lib/app-shutdown.js +385 -385
  8. package/lib/app.js +365 -365
  9. package/lib/archive.js +250 -250
  10. package/lib/atomic-file.js +544 -544
  11. package/lib/audit-chain.js +177 -177
  12. package/lib/audit-sign.js +344 -344
  13. package/lib/audit-tools.js +677 -677
  14. package/lib/audit.js +766 -766
  15. package/lib/auth/jwt.js +311 -311
  16. package/lib/auth/lockout.js +436 -436
  17. package/lib/auth/oauth.js +721 -721
  18. package/lib/auth/passkey.js +181 -181
  19. package/lib/auth/password.js +594 -594
  20. package/lib/backup/bundle.js +217 -217
  21. package/lib/backup/crypto.js +176 -176
  22. package/lib/backup/index.js +515 -515
  23. package/lib/backup/manifest.js +282 -282
  24. package/lib/break-glass.js +1338 -1338
  25. package/lib/bundler.js +441 -441
  26. package/lib/cache-redis.js +256 -256
  27. package/lib/cache.js +1206 -1206
  28. package/lib/canonical-json.js +115 -115
  29. package/lib/chain-writer.js +234 -234
  30. package/lib/cli-helpers.js +206 -206
  31. package/lib/cli.js +2334 -2334
  32. package/lib/cluster-provider-db.js +317 -317
  33. package/lib/cluster-storage.js +226 -226
  34. package/lib/cluster.js +703 -703
  35. package/lib/codepoint-class.js +196 -0
  36. package/lib/config-drift.js +301 -301
  37. package/lib/consent.js +222 -222
  38. package/lib/constants.js +191 -191
  39. package/lib/cookies.js +315 -315
  40. package/lib/credential-hash.js +322 -322
  41. package/lib/crypto.js +266 -266
  42. package/lib/csv.js +275 -286
  43. package/lib/db-declare-row-policy.js +267 -267
  44. package/lib/db-declare-view.js +420 -421
  45. package/lib/db-query.js +406 -406
  46. package/lib/db-schema.js +319 -319
  47. package/lib/db.js +1288 -1288
  48. package/lib/deprecate.js +222 -222
  49. package/lib/dev.js +335 -335
  50. package/lib/dual-control.js +473 -473
  51. package/lib/error-page.js +420 -420
  52. package/lib/external-db-migrate.js +441 -441
  53. package/lib/external-db.js +1061 -1061
  54. package/lib/file-type.js +273 -273
  55. package/lib/file-upload.js +213 -10
  56. package/lib/forms.js +422 -422
  57. package/lib/framework-error.js +293 -215
  58. package/lib/framework-schema.js +717 -717
  59. package/lib/gate-contract.js +971 -0
  60. package/lib/guard-all.js +405 -0
  61. package/lib/guard-archive.js +739 -0
  62. package/lib/guard-csv.js +816 -0
  63. package/lib/guard-email.js +744 -0
  64. package/lib/guard-filename.js +724 -0
  65. package/lib/guard-html.js +976 -0
  66. package/lib/guard-json.js +729 -0
  67. package/lib/guard-markdown.js +586 -0
  68. package/lib/guard-svg.js +976 -0
  69. package/lib/guard-xml.js +405 -0
  70. package/lib/guard-yaml.js +529 -0
  71. package/lib/handlers.js +350 -350
  72. package/lib/http-client-cookie-jar.js +508 -508
  73. package/lib/http-client.js +1195 -1195
  74. package/lib/i18n.js +878 -878
  75. package/lib/jobs.js +185 -185
  76. package/lib/log-stream-cloudwatch.js +369 -369
  77. package/lib/log-stream-local.js +146 -146
  78. package/lib/log-stream-otlp-grpc.js +410 -410
  79. package/lib/log-stream-otlp.js +286 -286
  80. package/lib/log-stream-syslog.js +302 -302
  81. package/lib/log-stream-webhook.js +199 -199
  82. package/lib/log-stream.js +330 -330
  83. package/lib/log.js +500 -500
  84. package/lib/mail-bounce.js +528 -528
  85. package/lib/mail-dkim.js +369 -362
  86. package/lib/mail.js +981 -962
  87. package/lib/metrics.js +683 -683
  88. package/lib/middleware/api-encrypt.js +936 -936
  89. package/lib/middleware/attach-user.js +157 -157
  90. package/lib/middleware/body-parser.js +1170 -1091
  91. package/lib/middleware/bot-guard.js +178 -178
  92. package/lib/middleware/compression.js +452 -452
  93. package/lib/middleware/cors.js +314 -314
  94. package/lib/middleware/csp-nonce.js +348 -348
  95. package/lib/middleware/csrf-protect.js +316 -316
  96. package/lib/middleware/db-role-for.js +264 -264
  97. package/lib/middleware/health.js +392 -392
  98. package/lib/middleware/index.js +79 -79
  99. package/lib/middleware/rate-limit.js +358 -358
  100. package/lib/middleware/request-id.js +61 -61
  101. package/lib/middleware/request-log.js +168 -168
  102. package/lib/middleware/require-auth.js +104 -104
  103. package/lib/middleware/security-headers.js +116 -116
  104. package/lib/middleware/sse.js +166 -166
  105. package/lib/migrations.js +383 -383
  106. package/lib/mtls-ca.js +518 -518
  107. package/lib/mtls-engine-default.js +481 -481
  108. package/lib/network-dns.js +632 -632
  109. package/lib/network-heartbeat.js +290 -290
  110. package/lib/network-nts.js +574 -574
  111. package/lib/network-proxy.js +265 -265
  112. package/lib/network-tls.js +328 -328
  113. package/lib/network.js +233 -233
  114. package/lib/notify.js +612 -612
  115. package/lib/ntp-check.js +229 -229
  116. package/lib/numeric-bounds.js +111 -91
  117. package/lib/object-store/azure-blob-bucket-ops.js +349 -349
  118. package/lib/object-store/azure-blob.js +488 -488
  119. package/lib/object-store/gcs-bucket-ops.js +351 -351
  120. package/lib/object-store/gcs.js +519 -519
  121. package/lib/object-store/http-put.js +153 -153
  122. package/lib/object-store/index.js +197 -197
  123. package/lib/object-store/sigv4-bucket-ops.js +1092 -1092
  124. package/lib/object-store/sigv4.js +903 -903
  125. package/lib/observability.js +151 -151
  126. package/lib/otel-export.js +269 -269
  127. package/lib/pagination.js +464 -464
  128. package/lib/parsers/index.js +80 -80
  129. package/lib/parsers/safe-env.js +642 -642
  130. package/lib/parsers/safe-ini.js +292 -292
  131. package/lib/parsers/safe-toml.js +784 -784
  132. package/lib/parsers/safe-xml.js +390 -390
  133. package/lib/parsers/safe-yaml.js +1015 -1015
  134. package/lib/permissions.js +708 -708
  135. package/lib/pqc-agent.js +87 -87
  136. package/lib/pqc-gate.js +279 -279
  137. package/lib/protobuf-encoder.js +190 -190
  138. package/lib/protocol-dispatcher.js +161 -161
  139. package/lib/pubsub-redis.js +167 -167
  140. package/lib/pubsub.js +429 -429
  141. package/lib/queue-local.js +476 -476
  142. package/lib/queue-redis.js +745 -745
  143. package/lib/queue-sqs.js +319 -319
  144. package/lib/queue.js +695 -695
  145. package/lib/redis-client.js +519 -519
  146. package/lib/request-helpers.js +340 -340
  147. package/lib/restore-bundle.js +237 -237
  148. package/lib/restore-rollback.js +259 -259
  149. package/lib/restore.js +409 -409
  150. package/lib/retry.js +376 -376
  151. package/lib/router.js +748 -748
  152. package/lib/safe-async.js +735 -735
  153. package/lib/safe-buffer.js +237 -237
  154. package/lib/safe-json.js +541 -541
  155. package/lib/safe-schema.js +1266 -1266
  156. package/lib/safe-url.js +159 -159
  157. package/lib/scheduler.js +706 -706
  158. package/lib/security-assert.js +373 -373
  159. package/lib/seeders.js +618 -618
  160. package/lib/session.js +478 -478
  161. package/lib/slug.js +269 -269
  162. package/lib/ssrf-guard.js +401 -401
  163. package/lib/static.js +184 -4
  164. package/lib/storage.js +471 -471
  165. package/lib/subject.js +281 -281
  166. package/lib/template.js +791 -791
  167. package/lib/testing.js +798 -798
  168. package/lib/time.js +310 -310
  169. package/lib/totp.js +302 -302
  170. package/lib/tracing.js +494 -494
  171. package/lib/uuid.js +132 -132
  172. package/lib/validate-opts.js +340 -319
  173. package/lib/vault/index.js +308 -308
  174. package/lib/vault/rotate.js +784 -784
  175. package/lib/vault/wrap.js +296 -296
  176. package/lib/vendor/noble-ciphers.cjs +9 -9
  177. package/lib/webhook.js +595 -595
  178. package/lib/websocket.js +1048 -1048
  179. package/package.json +77 -77
  180. package/sbom.cyclonedx.json +7 -7
package/lib/ssrf-guard.js CHANGED
@@ -1,401 +1,401 @@
1
- "use strict";
2
- /**
3
- * ssrf-guard — outbound URL gate against private / loopback / link-local /
4
- * cloud-metadata / reserved IP ranges.
5
- *
6
- * Wired as default-on in b.httpClient.request. Operators with internal
7
- * mesh calls opt out per call:
8
- *
9
- * b.httpClient.request({ url: "http://internal.svc", allowInternal: true });
10
- * b.httpClient.request({ url: "http://10.0.5.1", allowInternal: ["10.0.0.0/8"] });
11
- *
12
- * Standalone use:
13
- *
14
- * var ssrf = b.ssrfGuard;
15
- * await ssrf.checkUrl("https://example.com"); // throws SsrfError on hit
16
- * ssrf.classify("169.254.169.254"); // → "cloud-metadata"
17
- * ssrf.cidrContains("10.0.0.0/8", "10.1.2.3"); // → true
18
- *
19
- * What's blocked by default:
20
- * - IPv4 private (RFC 1918): 10/8, 172.16/12, 192.168/16
21
- * - IPv4 loopback: 127/8
22
- * - IPv4 link-local: 169.254/16
23
- * - IPv4 reserved/broadcast: 0/8, 100.64/10 (CGNAT), 224/4 (multicast),
24
- * 240/4, 255.255.255.255
25
- * - IPv4 documentation/test: 192.0.2/24, 198.51.100/24, 203.0.113/24, 198.18/15
26
- * - IPv6 loopback: ::1
27
- * - IPv6 ULA (private): fc00::/7
28
- * - IPv6 link-local: fe80::/10
29
- * - Cloud metadata IPs: 169.254.169.254 (AWS/GCP/Azure),
30
- * 169.254.170.2 (AWS ECS task role),
31
- * fd00:ec2::254
32
- *
33
- * Hostnames are resolved via dns.lookup before classification, so a
34
- * malicious hostname pointing at a private IP fails the guard.
35
- *
36
- * The validated IPs are returned in the result and `b.httpClient` pins
37
- * the actual TCP connect to those exact addresses (via a custom
38
- * `lookup` callback passed to https / http2 connect). A hostile DNS
39
- * server cannot rebind between guard-check and connect to redirect
40
- * traffic at a private / metadata address.
41
- */
42
-
43
- var dns = require("node:dns").promises;
44
- var net = require("node:net");
45
-
46
- var C = require("./constants");
47
- var lazyRequire = require("./lazy-require");
48
- var safeUrl = require("./safe-url");
49
- var validateOpts = require("./validate-opts");
50
-
51
- var { FrameworkError } = require("./framework-error");
52
-
53
- var networkDns = lazyRequire(function () { return require("./network-dns"); });
54
-
55
- // IP address bit-widths (RFC 791 §3.1 IPv4, RFC 4291 §2.5 IPv6) and
56
- // CIDR prefix arithmetic constants. The numerals in this file are
57
- // bit-counts in IP-address space, not byte sizes; routed through
58
- // C.BYTES.bytes (a value-passthrough) so every numeric literal in the
59
- // codebase has a single source of truth for "what shape is this number".
60
- var IPV4_BITS = C.BYTES.bytes(32);
61
- var IPV6_BITS = C.BYTES.bytes(128);
62
- var BITS_PER_BYTE = C.BYTES.bytes(8);
63
- var IPV6_BYTES = C.BYTES.bytes(16); // 128 bits / 8 bits-per-byte
64
- var IPV6_GROUPS = C.BYTES.bytes(8); // hex groups
65
- var HEX_RADIX = C.BYTES.bytes(16); // parseInt / toString radix
66
-
67
- class SsrfError extends FrameworkError {
68
- constructor(message, code, ctx) {
69
- super(message, code);
70
- this.name = "SsrfError";
71
- this.permanent = true;
72
- this.isSsrfError = true;
73
- if (ctx) {
74
- this.url = ctx.url || null;
75
- this.ip = ctx.ip || null;
76
- this.category = ctx.category || null;
77
- }
78
- }
79
- }
80
-
81
- // ---- IPv4 ranges (as numeric prefix tables for fast match) ----
82
- // Each entry: [networkInt, prefixLen]
83
- var IPV4_PRIVATE = [
84
- [_ipv4ToInt("10.0.0.0"), C.BYTES.bytes(8)],
85
- [_ipv4ToInt("172.16.0.0"), C.BYTES.bytes(12)],
86
- [_ipv4ToInt("192.168.0.0"), C.BYTES.bytes(16)],
87
- ];
88
- var IPV4_LOOPBACK = [
89
- [_ipv4ToInt("127.0.0.0"), C.BYTES.bytes(8)],
90
- ];
91
- var IPV4_LINK_LOCAL = [
92
- [_ipv4ToInt("169.254.0.0"), C.BYTES.bytes(16)],
93
- ];
94
- var IPV4_RESERVED = [
95
- [_ipv4ToInt("0.0.0.0"), C.BYTES.bytes(8)], // "this network"
96
- [_ipv4ToInt("100.64.0.0"), C.BYTES.bytes(10)], // CGNAT (RFC 6598)
97
- [_ipv4ToInt("192.0.0.0"), C.BYTES.bytes(24)], // IETF protocol assignments
98
- [_ipv4ToInt("192.0.2.0"), C.BYTES.bytes(24)], // TEST-NET-1
99
- [_ipv4ToInt("198.18.0.0"), C.BYTES.bytes(15)], // network benchmark
100
- [_ipv4ToInt("198.51.100.0"), C.BYTES.bytes(24)], // TEST-NET-2
101
- [_ipv4ToInt("203.0.113.0"), C.BYTES.bytes(24)], // TEST-NET-3
102
- [_ipv4ToInt("224.0.0.0"), C.BYTES.bytes(4)], // multicast
103
- [_ipv4ToInt("240.0.0.0"), C.BYTES.bytes(4)], // reserved + 255.255.255.255
104
- ];
105
-
106
- // ---- IPv6 ranges (as 16-byte prefix tables) ----
107
- var IPV6_LOOPBACK_BYTES = _ipv6ToBytes("::1");
108
- var IPV6_UNSPECIFIED_BYTES = _ipv6ToBytes("::");
109
- var IPV6_PRIVATE_PREFIX = _ipv6ToBytes("fc00::");
110
- var IPV6_LINK_LOCAL_PREFIX = _ipv6ToBytes("fe80::");
111
- var IPV6_DOC_PREFIX = _ipv6ToBytes("2001:db8::"); // documentation
112
- // IPv4-mapped IPv6 (::ffff:0:0 with C.BYTES.bytes(96)-bit prefix)
113
- var IPV6_V4_MAPPED_PREFIX = _ipv6ToBytes("::ffff:0:0");
114
- // Multicast ff00::/8 — RFC 4291 §2.7. Refused for outbound HTTP same as
115
- // IPv4 multicast 224/4 — there's no legitimate fetch from a multicast
116
- // destination on a production gateway.
117
- var IPV6_MULTICAST_PREFIX = _ipv6ToBytes("ff00::");
118
- // NAT64 well-known prefix 64:ff9b::/96 — RFC 6052. Translates to IPv4
119
- // embedded in the lower 32 bits; the framework refuses since the
120
- // underlying v4 address is what gets contacted and might be private.
121
- // (Operators with NAT64 deployments flip allowInternal.)
122
- var IPV6_NAT64_PREFIX = _ipv6ToBytes("64:ff9b::");
123
- // 6to4 2002::/16 — RFC 3056. Carries an embedded IPv4 in bytes 2-5;
124
- // hostile use is to tunnel through to a v4 destination the v4 guard
125
- // would have refused. Refused.
126
- var IPV6_6TO4_PREFIX = _ipv6ToBytes("2002::");
127
- // Discard prefix 100::/64 — RFC 6666. Dropped by routers; fetching
128
- // from it is operationally meaningless and a likely sign of mis-config
129
- // or attempted exfil to a sinkhole.
130
- var IPV6_DISCARD_PREFIX = _ipv6ToBytes("100::");
131
-
132
- // ---- Cloud metadata addresses (string-equality, exact match) ----
133
- var CLOUD_METADATA_IPS = [
134
- "169.254.169.254", // AWS, GCP, Azure, OpenStack, DO
135
- "169.254.170.2", // AWS ECS task role
136
- "fd00:ec2::254", // AWS IMDS over IPv6
137
- ];
138
-
139
- // ---- Helpers ----
140
-
141
- function _ipv4ToInt(ip) {
142
- var parts = ip.split(".");
143
- return ((parts[0] | 0) << 24 >>> 0) +
144
- ((parts[1] | 0) << 16) +
145
- ((parts[2] | 0) << 8) +
146
- (parts[3] | 0);
147
- }
148
-
149
- function _ipv6ToBytes(ip) {
150
- // Node's net.isIPv6 returns 6 for valid IPv6; we then expand
151
- // shorthand via manual parsing. node:net doesn't export an
152
- // ipv6-to-bytes helper, but the URL constructor + Buffer dance
153
- // is reliable for canonicalizing.
154
- var groups = _expandIpv6(ip);
155
- var out = Buffer.alloc(IPV6_BYTES);
156
- for (var i = 0; i < IPV6_GROUPS; i++) {
157
- var v = parseInt(groups[i], HEX_RADIX) || 0;
158
- out[i * 2] = (v >> 8) & 0xff;
159
- out[i * 2 + 1] = v & 0xff;
160
- }
161
- return out;
162
- }
163
-
164
- function _expandIpv6(ip) {
165
- // Handle "::" zero-elision + IPv4-mapped suffix ("::ffff:1.2.3.4").
166
- var lower = ip.toLowerCase();
167
- // IPv4-mapped: convert trailing dotted-quad to two hex groups
168
- var dot = lower.lastIndexOf(":");
169
- if (dot !== -1 && lower.indexOf(".", dot) !== -1) {
170
- var v4 = lower.slice(dot + 1);
171
- var ipv4Int = _ipv4ToInt(v4);
172
- var hi = (ipv4Int >>> 16) & 0xffff;
173
- var lo = ipv4Int & 0xffff;
174
- lower = lower.slice(0, dot + 1) + hi.toString(HEX_RADIX) + ":" + lo.toString(HEX_RADIX);
175
- }
176
- var doubleColon = lower.indexOf("::");
177
- var leftStr, rightStr;
178
- if (doubleColon === -1) {
179
- leftStr = lower;
180
- rightStr = "";
181
- } else {
182
- leftStr = lower.slice(0, doubleColon);
183
- rightStr = lower.slice(doubleColon + 2);
184
- }
185
- var left = leftStr.length ? leftStr.split(":") : [];
186
- var right = rightStr.length ? rightStr.split(":") : [];
187
- var missing = IPV6_GROUPS - left.length - right.length;
188
- var fill = [];
189
- for (var i = 0; i < missing; i++) fill.push("0");
190
- return left.concat(fill).concat(right);
191
- }
192
-
193
- function _cidrIpv4Match(cidr, ip) {
194
- var slash = cidr.indexOf("/");
195
- if (slash === -1) return false;
196
- var network = _ipv4ToInt(cidr.slice(0, slash));
197
- var prefix = parseInt(cidr.slice(slash + 1), 10);
198
- if (!Number.isFinite(prefix) || prefix < 0 || prefix > IPV4_BITS) return false;
199
- var ipInt = _ipv4ToInt(ip);
200
- if (prefix === 0) return true;
201
- var mask = (0xffffffff << (IPV4_BITS - prefix)) >>> 0;
202
- return (ipInt & mask) === (network & mask);
203
- }
204
-
205
- function _cidrIpv6Match(cidr, ip) {
206
- var slash = cidr.indexOf("/");
207
- if (slash === -1) return false;
208
- var network = _ipv6ToBytes(cidr.slice(0, slash));
209
- var prefix = parseInt(cidr.slice(slash + 1), 10);
210
- if (!Number.isFinite(prefix) || prefix < 0 || prefix > IPV6_BITS) return false;
211
- var bytes = _ipv6ToBytes(ip);
212
- var fullBytes = Math.floor(prefix / BITS_PER_BYTE);
213
- var remainingBits = prefix % BITS_PER_BYTE;
214
- for (var i = 0; i < fullBytes; i++) {
215
- if (bytes[i] !== network[i]) return false;
216
- }
217
- if (remainingBits > 0) {
218
- var mask = (0xff << (BITS_PER_BYTE - remainingBits)) & 0xff;
219
- if ((bytes[fullBytes] & mask) !== (network[fullBytes] & mask)) return false;
220
- }
221
- return true;
222
- }
223
-
224
- function _ipv4PrefixMatch(prefixTable, ipInt) {
225
- for (var i = 0; i < prefixTable.length; i++) {
226
- var net4 = prefixTable[i][0];
227
- var prefix = prefixTable[i][1];
228
- var mask = prefix === 0 ? 0 : (0xffffffff << (IPV4_BITS - prefix)) >>> 0;
229
- if ((ipInt & mask) === (net4 & mask)) return true;
230
- }
231
- return false;
232
- }
233
-
234
- function _ipv6PrefixMatch(prefixBytes, prefixLen, ipBytes) {
235
- var fullBytes = Math.floor(prefixLen / BITS_PER_BYTE);
236
- var remainingBits = prefixLen % BITS_PER_BYTE;
237
- for (var i = 0; i < fullBytes; i++) {
238
- if (ipBytes[i] !== prefixBytes[i]) return false;
239
- }
240
- if (remainingBits > 0) {
241
- var mask = (0xff << (BITS_PER_BYTE - remainingBits)) & 0xff;
242
- if ((ipBytes[fullBytes] & mask) !== (prefixBytes[fullBytes] & mask)) return false;
243
- }
244
- return true;
245
- }
246
-
247
- // ---- Public classification API ----
248
-
249
- function classify(ip) {
250
- if (typeof ip !== "string") return null;
251
- var family = net.isIP(ip);
252
- if (family === 0) return null;
253
-
254
- if (CLOUD_METADATA_IPS.indexOf(ip) !== -1) return "cloud-metadata";
255
-
256
- if (family === 4) {
257
- var ipInt = _ipv4ToInt(ip);
258
- if (_ipv4PrefixMatch(IPV4_LOOPBACK, ipInt)) return "loopback";
259
- if (_ipv4PrefixMatch(IPV4_LINK_LOCAL, ipInt)) return "link-local";
260
- if (_ipv4PrefixMatch(IPV4_PRIVATE, ipInt)) return "private";
261
- if (_ipv4PrefixMatch(IPV4_RESERVED, ipInt)) return "reserved";
262
- return null;
263
- }
264
-
265
- // IPv6
266
- var bytes = _ipv6ToBytes(ip);
267
- if (_bufEqual(bytes, IPV6_LOOPBACK_BYTES)) return "loopback";
268
- if (_bufEqual(bytes, IPV6_UNSPECIFIED_BYTES)) return "reserved";
269
- if (_ipv6PrefixMatch(IPV6_LINK_LOCAL_PREFIX, C.BYTES.bytes(10), bytes)) return "link-local";
270
- if (_ipv6PrefixMatch(IPV6_PRIVATE_PREFIX, 7, bytes)) return "private";
271
- if (_ipv6PrefixMatch(IPV6_DOC_PREFIX, C.BYTES.bytes(32), bytes)) return "reserved";
272
- if (_ipv6PrefixMatch(IPV6_MULTICAST_PREFIX, C.BYTES.bytes(8), bytes)) return "reserved";
273
- if (_ipv6PrefixMatch(IPV6_DISCARD_PREFIX, C.BYTES.bytes(64), bytes)) return "reserved";
274
- // 6to4 prefix embeds a v4 address in bytes 2–5; classify the
275
- // embedded v4 so a 6to4-wrapped private/metadata address is refused
276
- // for the same reason its v4 form would be.
277
- if (_ipv6PrefixMatch(IPV6_6TO4_PREFIX, C.BYTES.bytes(16), bytes)) {
278
- var v4From6to4 = bytes[2] + "." + bytes[3] + "." + bytes[4] + "." + bytes[5];
279
- return classify(v4From6to4) || "reserved";
280
- }
281
- // NAT64 well-known prefix embeds v4 in the lower bytes.
282
- if (_ipv6PrefixMatch(IPV6_NAT64_PREFIX, C.BYTES.bytes(96), bytes)) {
283
- var v4FromNat64 = bytes[12] + "." + bytes[13] + "." + bytes[14] + "." + bytes[15];
284
- return classify(v4FromNat64) || "reserved";
285
- }
286
- // IPv4-mapped addresses (::ffff:a.b.c.d): re-classify the v4 portion.
287
- if (_ipv6PrefixMatch(IPV6_V4_MAPPED_PREFIX, C.BYTES.bytes(96), bytes)) {
288
- var mappedV4 = bytes[12] + "." + bytes[13] + "." + bytes[14] + "." + bytes[15];
289
- return classify(mappedV4);
290
- }
291
- return null;
292
- }
293
-
294
- function _bufEqual(a, b) {
295
- // Compares Buffer-like byte arrays for equality. The buffers here
296
- // are IP addresses, not secrets, so the comparison doesn't need
297
- // constant-time semantics — Buffer.compare uses native memcmp.
298
- return Buffer.compare(a, b) === 0;
299
- }
300
-
301
- function cidrContains(cidr, ip) {
302
- if (typeof cidr !== "string" || typeof ip !== "string") return false;
303
- var slash = cidr.indexOf("/");
304
- if (slash === -1) return false;
305
- var network = cidr.slice(0, slash);
306
- var nFamily = net.isIP(network);
307
- var iFamily = net.isIP(ip);
308
- if (nFamily === 0 || iFamily === 0 || nFamily !== iFamily) return false;
309
- return nFamily === 4 ? _cidrIpv4Match(cidr, ip) : _cidrIpv6Match(cidr, ip);
310
- }
311
-
312
- // ---- URL check (DNS-resolving) ----
313
-
314
- async function checkUrl(url, opts) {
315
- opts = opts || {};
316
- validateOpts(opts, ["allowInternal", "errorClass", "dnsLookup"], "ssrfGuard.checkUrl");
317
-
318
- var ErrorClass = opts.errorClass || SsrfError;
319
- var allowInternal = opts.allowInternal === true ? true :
320
- Array.isArray(opts.allowInternal) ? opts.allowInternal :
321
- false;
322
-
323
- var parsed = url instanceof URL ? url : safeUrl.parse(String(url), {
324
- allowedProtocols: safeUrl.ALLOW_HTTP_ALL,
325
- errorClass: ErrorClass,
326
- });
327
- if (!parsed.hostname) {
328
- throw new ErrorClass("URL '" + parsed.toString() + "' has no hostname",
329
- "ssrf-guard/no-hostname", { url: parsed.toString() });
330
- }
331
-
332
- // Strip IPv6 brackets — net.isIP doesn't accept "[::1]" form, only "::1"
333
- var hostForCheck = parsed.hostname.replace(/^\[|\]$/g, "");
334
-
335
- var ips;
336
- if (net.isIP(hostForCheck)) {
337
- ips = [{ address: hostForCheck, family: net.isIP(hostForCheck) }];
338
- } else {
339
- var lookup = opts.dnsLookup || function (host) {
340
- try {
341
- var nd = networkDns();
342
- if (nd && typeof nd.lookup === "function") {
343
- return nd.lookup(host, { all: true });
344
- }
345
- } catch (_e) { /* fall through to native */ }
346
- return dns.lookup(host, { all: true });
347
- };
348
- ips = await lookup(hostForCheck);
349
- if (!Array.isArray(ips)) ips = [ips];
350
- }
351
-
352
- for (var i = 0; i < ips.length; i++) {
353
- var addr = ips[i].address;
354
- var category = classify(addr);
355
- if (!category) continue;
356
-
357
- // Cloud-metadata IPs are NEVER allowed — they leak instance
358
- // credentials (AWS IMDS, GCP metadata, Azure IMDS) and a blanket
359
- // allowInternal bypass would let any compromised request exfiltrate
360
- // them. Operators with a legitimate need to talk to the metadata
361
- // service do it through the cloud SDK with explicit IAM, never
362
- // through the framework's outbound HTTP. Same hard-deny applies
363
- // to allowInternal=[cidr-list]: the list grants exception for
364
- // private ranges, not for the metadata IP that happens to fall
365
- // inside link-local.
366
- if (category === "cloud-metadata") {
367
- throw new ErrorClass(
368
- "URL '" + parsed.toString() + "' resolves to " + addr +
369
- " (cloud-metadata) — blocked unconditionally; allowInternal does NOT override " +
370
- "this class because metadata IPs leak instance credentials",
371
- "ssrf-guard/blocked-cloud-metadata",
372
- { url: parsed.toString(), ip: addr, category: category }
373
- );
374
- }
375
-
376
- if (allowInternal === true) continue;
377
- if (Array.isArray(allowInternal) && allowInternal.some(function (cidr) {
378
- return cidrContains(cidr, addr);
379
- })) continue;
380
-
381
- throw new ErrorClass(
382
- "URL '" + parsed.toString() + "' resolves to " + addr +
383
- " in the " + category + " range — pass allowInternal:true to override",
384
- "ssrf-guard/blocked-" + category,
385
- { url: parsed.toString(), ip: addr, category: category }
386
- );
387
- }
388
- return { url: parsed, ips: ips };
389
- }
390
-
391
- module.exports = {
392
- classify: classify,
393
- cidrContains: cidrContains,
394
- checkUrl: checkUrl,
395
- isPrivate: function (ip) { return classify(ip) === "private"; },
396
- isLoopback: function (ip) { return classify(ip) === "loopback"; },
397
- isLinkLocal: function (ip) { return classify(ip) === "link-local"; },
398
- isCloudMetadata: function (ip) { return classify(ip) === "cloud-metadata"; },
399
- isReserved: function (ip) { return classify(ip) === "reserved"; },
400
- SsrfError: SsrfError,
401
- };
1
+ "use strict";
2
+ /**
3
+ * ssrf-guard — outbound URL gate against private / loopback / link-local /
4
+ * cloud-metadata / reserved IP ranges.
5
+ *
6
+ * Wired as default-on in b.httpClient.request. Operators with internal
7
+ * mesh calls opt out per call:
8
+ *
9
+ * b.httpClient.request({ url: "http://internal.svc", allowInternal: true });
10
+ * b.httpClient.request({ url: "http://10.0.5.1", allowInternal: ["10.0.0.0/8"] });
11
+ *
12
+ * Standalone use:
13
+ *
14
+ * var ssrf = b.ssrfGuard;
15
+ * await ssrf.checkUrl("https://example.com"); // throws SsrfError on hit
16
+ * ssrf.classify("169.254.169.254"); // → "cloud-metadata"
17
+ * ssrf.cidrContains("10.0.0.0/8", "10.1.2.3"); // → true
18
+ *
19
+ * What's blocked by default:
20
+ * - IPv4 private (RFC 1918): 10/8, 172.16/12, 192.168/16
21
+ * - IPv4 loopback: 127/8
22
+ * - IPv4 link-local: 169.254/16
23
+ * - IPv4 reserved/broadcast: 0/8, 100.64/10 (CGNAT), 224/4 (multicast),
24
+ * 240/4, 255.255.255.255
25
+ * - IPv4 documentation/test: 192.0.2/24, 198.51.100/24, 203.0.113/24, 198.18/15
26
+ * - IPv6 loopback: ::1
27
+ * - IPv6 ULA (private): fc00::/7
28
+ * - IPv6 link-local: fe80::/10
29
+ * - Cloud metadata IPs: 169.254.169.254 (AWS/GCP/Azure),
30
+ * 169.254.170.2 (AWS ECS task role),
31
+ * fd00:ec2::254
32
+ *
33
+ * Hostnames are resolved via dns.lookup before classification, so a
34
+ * malicious hostname pointing at a private IP fails the guard.
35
+ *
36
+ * The validated IPs are returned in the result and `b.httpClient` pins
37
+ * the actual TCP connect to those exact addresses (via a custom
38
+ * `lookup` callback passed to https / http2 connect). A hostile DNS
39
+ * server cannot rebind between guard-check and connect to redirect
40
+ * traffic at a private / metadata address.
41
+ */
42
+
43
+ var dns = require("node:dns").promises;
44
+ var net = require("node:net");
45
+
46
+ var C = require("./constants");
47
+ var lazyRequire = require("./lazy-require");
48
+ var safeUrl = require("./safe-url");
49
+ var validateOpts = require("./validate-opts");
50
+
51
+ var { FrameworkError } = require("./framework-error");
52
+
53
+ var networkDns = lazyRequire(function () { return require("./network-dns"); });
54
+
55
+ // IP address bit-widths (RFC 791 §3.1 IPv4, RFC 4291 §2.5 IPv6) and
56
+ // CIDR prefix arithmetic constants. The numerals in this file are
57
+ // bit-counts in IP-address space, not byte sizes; routed through
58
+ // C.BYTES.bytes (a value-passthrough) so every numeric literal in the
59
+ // codebase has a single source of truth for "what shape is this number".
60
+ var IPV4_BITS = C.BYTES.bytes(32);
61
+ var IPV6_BITS = C.BYTES.bytes(128);
62
+ var BITS_PER_BYTE = C.BYTES.bytes(8);
63
+ var IPV6_BYTES = C.BYTES.bytes(16); // 128 bits / 8 bits-per-byte
64
+ var IPV6_GROUPS = C.BYTES.bytes(8); // hex groups
65
+ var HEX_RADIX = C.BYTES.bytes(16); // parseInt / toString radix
66
+
67
+ class SsrfError extends FrameworkError {
68
+ constructor(message, code, ctx) {
69
+ super(message, code);
70
+ this.name = "SsrfError";
71
+ this.permanent = true;
72
+ this.isSsrfError = true;
73
+ if (ctx) {
74
+ this.url = ctx.url || null;
75
+ this.ip = ctx.ip || null;
76
+ this.category = ctx.category || null;
77
+ }
78
+ }
79
+ }
80
+
81
+ // ---- IPv4 ranges (as numeric prefix tables for fast match) ----
82
+ // Each entry: [networkInt, prefixLen]
83
+ var IPV4_PRIVATE = [
84
+ [_ipv4ToInt("10.0.0.0"), C.BYTES.bytes(8)],
85
+ [_ipv4ToInt("172.16.0.0"), C.BYTES.bytes(12)],
86
+ [_ipv4ToInt("192.168.0.0"), C.BYTES.bytes(16)],
87
+ ];
88
+ var IPV4_LOOPBACK = [
89
+ [_ipv4ToInt("127.0.0.0"), C.BYTES.bytes(8)],
90
+ ];
91
+ var IPV4_LINK_LOCAL = [
92
+ [_ipv4ToInt("169.254.0.0"), C.BYTES.bytes(16)],
93
+ ];
94
+ var IPV4_RESERVED = [
95
+ [_ipv4ToInt("0.0.0.0"), C.BYTES.bytes(8)], // "this network"
96
+ [_ipv4ToInt("100.64.0.0"), C.BYTES.bytes(10)], // CGNAT (RFC 6598)
97
+ [_ipv4ToInt("192.0.0.0"), C.BYTES.bytes(24)], // IETF protocol assignments
98
+ [_ipv4ToInt("192.0.2.0"), C.BYTES.bytes(24)], // TEST-NET-1
99
+ [_ipv4ToInt("198.18.0.0"), C.BYTES.bytes(15)], // network benchmark
100
+ [_ipv4ToInt("198.51.100.0"), C.BYTES.bytes(24)], // TEST-NET-2
101
+ [_ipv4ToInt("203.0.113.0"), C.BYTES.bytes(24)], // TEST-NET-3
102
+ [_ipv4ToInt("224.0.0.0"), C.BYTES.bytes(4)], // multicast
103
+ [_ipv4ToInt("240.0.0.0"), C.BYTES.bytes(4)], // reserved + 255.255.255.255
104
+ ];
105
+
106
+ // ---- IPv6 ranges (as 16-byte prefix tables) ----
107
+ var IPV6_LOOPBACK_BYTES = _ipv6ToBytes("::1");
108
+ var IPV6_UNSPECIFIED_BYTES = _ipv6ToBytes("::");
109
+ var IPV6_PRIVATE_PREFIX = _ipv6ToBytes("fc00::");
110
+ var IPV6_LINK_LOCAL_PREFIX = _ipv6ToBytes("fe80::");
111
+ var IPV6_DOC_PREFIX = _ipv6ToBytes("2001:db8::"); // documentation
112
+ // IPv4-mapped IPv6 (::ffff:0:0 with C.BYTES.bytes(96)-bit prefix)
113
+ var IPV6_V4_MAPPED_PREFIX = _ipv6ToBytes("::ffff:0:0");
114
+ // Multicast ff00::/8 — RFC 4291 §2.7. Refused for outbound HTTP same as
115
+ // IPv4 multicast 224/4 — there's no legitimate fetch from a multicast
116
+ // destination on a production gateway.
117
+ var IPV6_MULTICAST_PREFIX = _ipv6ToBytes("ff00::");
118
+ // NAT64 well-known prefix 64:ff9b::/96 — RFC 6052. Translates to IPv4
119
+ // embedded in the lower 32 bits; the framework refuses since the
120
+ // underlying v4 address is what gets contacted and might be private.
121
+ // (Operators with NAT64 deployments flip allowInternal.)
122
+ var IPV6_NAT64_PREFIX = _ipv6ToBytes("64:ff9b::");
123
+ // 6to4 2002::/16 — RFC 3056. Carries an embedded IPv4 in bytes 2-5;
124
+ // hostile use is to tunnel through to a v4 destination the v4 guard
125
+ // would have refused. Refused.
126
+ var IPV6_6TO4_PREFIX = _ipv6ToBytes("2002::");
127
+ // Discard prefix 100::/64 — RFC 6666. Dropped by routers; fetching
128
+ // from it is operationally meaningless and a likely sign of mis-config
129
+ // or attempted exfil to a sinkhole.
130
+ var IPV6_DISCARD_PREFIX = _ipv6ToBytes("100::");
131
+
132
+ // ---- Cloud metadata addresses (string-equality, exact match) ----
133
+ var CLOUD_METADATA_IPS = [
134
+ "169.254.169.254", // AWS, GCP, Azure, OpenStack, DO
135
+ "169.254.170.2", // AWS ECS task role
136
+ "fd00:ec2::254", // AWS IMDS over IPv6
137
+ ];
138
+
139
+ // ---- Helpers ----
140
+
141
+ function _ipv4ToInt(ip) {
142
+ var parts = ip.split(".");
143
+ return ((parts[0] | 0) << 24 >>> 0) +
144
+ ((parts[1] | 0) << 16) +
145
+ ((parts[2] | 0) << 8) +
146
+ (parts[3] | 0);
147
+ }
148
+
149
+ function _ipv6ToBytes(ip) {
150
+ // Node's net.isIPv6 returns 6 for valid IPv6; we then expand
151
+ // shorthand via manual parsing. node:net doesn't export an
152
+ // ipv6-to-bytes helper, but the URL constructor + Buffer dance
153
+ // is reliable for canonicalizing.
154
+ var groups = _expandIpv6(ip);
155
+ var out = Buffer.alloc(IPV6_BYTES);
156
+ for (var i = 0; i < IPV6_GROUPS; i++) {
157
+ var v = parseInt(groups[i], HEX_RADIX) || 0;
158
+ out[i * 2] = (v >> 8) & 0xff;
159
+ out[i * 2 + 1] = v & 0xff;
160
+ }
161
+ return out;
162
+ }
163
+
164
+ function _expandIpv6(ip) {
165
+ // Handle "::" zero-elision + IPv4-mapped suffix ("::ffff:1.2.3.4").
166
+ var lower = ip.toLowerCase();
167
+ // IPv4-mapped: convert trailing dotted-quad to two hex groups
168
+ var dot = lower.lastIndexOf(":");
169
+ if (dot !== -1 && lower.indexOf(".", dot) !== -1) {
170
+ var v4 = lower.slice(dot + 1);
171
+ var ipv4Int = _ipv4ToInt(v4);
172
+ var hi = (ipv4Int >>> 16) & 0xffff;
173
+ var lo = ipv4Int & 0xffff;
174
+ lower = lower.slice(0, dot + 1) + hi.toString(HEX_RADIX) + ":" + lo.toString(HEX_RADIX);
175
+ }
176
+ var doubleColon = lower.indexOf("::");
177
+ var leftStr, rightStr;
178
+ if (doubleColon === -1) {
179
+ leftStr = lower;
180
+ rightStr = "";
181
+ } else {
182
+ leftStr = lower.slice(0, doubleColon);
183
+ rightStr = lower.slice(doubleColon + 2);
184
+ }
185
+ var left = leftStr.length ? leftStr.split(":") : [];
186
+ var right = rightStr.length ? rightStr.split(":") : [];
187
+ var missing = IPV6_GROUPS - left.length - right.length;
188
+ var fill = [];
189
+ for (var i = 0; i < missing; i++) fill.push("0");
190
+ return left.concat(fill).concat(right);
191
+ }
192
+
193
+ function _cidrIpv4Match(cidr, ip) {
194
+ var slash = cidr.indexOf("/");
195
+ if (slash === -1) return false;
196
+ var network = _ipv4ToInt(cidr.slice(0, slash));
197
+ var prefix = parseInt(cidr.slice(slash + 1), 10);
198
+ if (!Number.isFinite(prefix) || prefix < 0 || prefix > IPV4_BITS) return false;
199
+ var ipInt = _ipv4ToInt(ip);
200
+ if (prefix === 0) return true;
201
+ var mask = (0xffffffff << (IPV4_BITS - prefix)) >>> 0;
202
+ return (ipInt & mask) === (network & mask);
203
+ }
204
+
205
+ function _cidrIpv6Match(cidr, ip) {
206
+ var slash = cidr.indexOf("/");
207
+ if (slash === -1) return false;
208
+ var network = _ipv6ToBytes(cidr.slice(0, slash));
209
+ var prefix = parseInt(cidr.slice(slash + 1), 10);
210
+ if (!Number.isFinite(prefix) || prefix < 0 || prefix > IPV6_BITS) return false;
211
+ var bytes = _ipv6ToBytes(ip);
212
+ var fullBytes = Math.floor(prefix / BITS_PER_BYTE);
213
+ var remainingBits = prefix % BITS_PER_BYTE;
214
+ for (var i = 0; i < fullBytes; i++) {
215
+ if (bytes[i] !== network[i]) return false;
216
+ }
217
+ if (remainingBits > 0) {
218
+ var mask = (0xff << (BITS_PER_BYTE - remainingBits)) & 0xff;
219
+ if ((bytes[fullBytes] & mask) !== (network[fullBytes] & mask)) return false;
220
+ }
221
+ return true;
222
+ }
223
+
224
+ function _ipv4PrefixMatch(prefixTable, ipInt) {
225
+ for (var i = 0; i < prefixTable.length; i++) {
226
+ var net4 = prefixTable[i][0];
227
+ var prefix = prefixTable[i][1];
228
+ var mask = prefix === 0 ? 0 : (0xffffffff << (IPV4_BITS - prefix)) >>> 0;
229
+ if ((ipInt & mask) === (net4 & mask)) return true;
230
+ }
231
+ return false;
232
+ }
233
+
234
+ function _ipv6PrefixMatch(prefixBytes, prefixLen, ipBytes) {
235
+ var fullBytes = Math.floor(prefixLen / BITS_PER_BYTE);
236
+ var remainingBits = prefixLen % BITS_PER_BYTE;
237
+ for (var i = 0; i < fullBytes; i++) {
238
+ if (ipBytes[i] !== prefixBytes[i]) return false;
239
+ }
240
+ if (remainingBits > 0) {
241
+ var mask = (0xff << (BITS_PER_BYTE - remainingBits)) & 0xff;
242
+ if ((ipBytes[fullBytes] & mask) !== (prefixBytes[fullBytes] & mask)) return false;
243
+ }
244
+ return true;
245
+ }
246
+
247
+ // ---- Public classification API ----
248
+
249
+ function classify(ip) {
250
+ if (typeof ip !== "string") return null;
251
+ var family = net.isIP(ip);
252
+ if (family === 0) return null;
253
+
254
+ if (CLOUD_METADATA_IPS.indexOf(ip) !== -1) return "cloud-metadata";
255
+
256
+ if (family === 4) {
257
+ var ipInt = _ipv4ToInt(ip);
258
+ if (_ipv4PrefixMatch(IPV4_LOOPBACK, ipInt)) return "loopback";
259
+ if (_ipv4PrefixMatch(IPV4_LINK_LOCAL, ipInt)) return "link-local";
260
+ if (_ipv4PrefixMatch(IPV4_PRIVATE, ipInt)) return "private";
261
+ if (_ipv4PrefixMatch(IPV4_RESERVED, ipInt)) return "reserved";
262
+ return null;
263
+ }
264
+
265
+ // IPv6
266
+ var bytes = _ipv6ToBytes(ip);
267
+ if (_bufEqual(bytes, IPV6_LOOPBACK_BYTES)) return "loopback";
268
+ if (_bufEqual(bytes, IPV6_UNSPECIFIED_BYTES)) return "reserved";
269
+ if (_ipv6PrefixMatch(IPV6_LINK_LOCAL_PREFIX, C.BYTES.bytes(10), bytes)) return "link-local";
270
+ if (_ipv6PrefixMatch(IPV6_PRIVATE_PREFIX, 7, bytes)) return "private";
271
+ if (_ipv6PrefixMatch(IPV6_DOC_PREFIX, C.BYTES.bytes(32), bytes)) return "reserved";
272
+ if (_ipv6PrefixMatch(IPV6_MULTICAST_PREFIX, C.BYTES.bytes(8), bytes)) return "reserved";
273
+ if (_ipv6PrefixMatch(IPV6_DISCARD_PREFIX, C.BYTES.bytes(64), bytes)) return "reserved";
274
+ // 6to4 prefix embeds a v4 address in bytes 2–5; classify the
275
+ // embedded v4 so a 6to4-wrapped private/metadata address is refused
276
+ // for the same reason its v4 form would be.
277
+ if (_ipv6PrefixMatch(IPV6_6TO4_PREFIX, C.BYTES.bytes(16), bytes)) {
278
+ var v4From6to4 = bytes[2] + "." + bytes[3] + "." + bytes[4] + "." + bytes[5];
279
+ return classify(v4From6to4) || "reserved";
280
+ }
281
+ // NAT64 well-known prefix embeds v4 in the lower bytes.
282
+ if (_ipv6PrefixMatch(IPV6_NAT64_PREFIX, C.BYTES.bytes(96), bytes)) {
283
+ var v4FromNat64 = bytes[12] + "." + bytes[13] + "." + bytes[14] + "." + bytes[15];
284
+ return classify(v4FromNat64) || "reserved";
285
+ }
286
+ // IPv4-mapped addresses (::ffff:a.b.c.d): re-classify the v4 portion.
287
+ if (_ipv6PrefixMatch(IPV6_V4_MAPPED_PREFIX, C.BYTES.bytes(96), bytes)) {
288
+ var mappedV4 = bytes[12] + "." + bytes[13] + "." + bytes[14] + "." + bytes[15];
289
+ return classify(mappedV4);
290
+ }
291
+ return null;
292
+ }
293
+
294
+ function _bufEqual(a, b) {
295
+ // Compares Buffer-like byte arrays for equality. The buffers here
296
+ // are IP addresses, not secrets, so the comparison doesn't need
297
+ // constant-time semantics — Buffer.compare uses native memcmp.
298
+ return Buffer.compare(a, b) === 0;
299
+ }
300
+
301
+ function cidrContains(cidr, ip) {
302
+ if (typeof cidr !== "string" || typeof ip !== "string") return false;
303
+ var slash = cidr.indexOf("/");
304
+ if (slash === -1) return false;
305
+ var network = cidr.slice(0, slash);
306
+ var nFamily = net.isIP(network);
307
+ var iFamily = net.isIP(ip);
308
+ if (nFamily === 0 || iFamily === 0 || nFamily !== iFamily) return false;
309
+ return nFamily === 4 ? _cidrIpv4Match(cidr, ip) : _cidrIpv6Match(cidr, ip);
310
+ }
311
+
312
+ // ---- URL check (DNS-resolving) ----
313
+
314
+ async function checkUrl(url, opts) {
315
+ opts = opts || {};
316
+ validateOpts(opts, ["allowInternal", "errorClass", "dnsLookup"], "ssrfGuard.checkUrl");
317
+
318
+ var ErrorClass = opts.errorClass || SsrfError;
319
+ var allowInternal = opts.allowInternal === true ? true :
320
+ Array.isArray(opts.allowInternal) ? opts.allowInternal :
321
+ false;
322
+
323
+ var parsed = url instanceof URL ? url : safeUrl.parse(String(url), {
324
+ allowedProtocols: safeUrl.ALLOW_HTTP_ALL,
325
+ errorClass: ErrorClass,
326
+ });
327
+ if (!parsed.hostname) {
328
+ throw new ErrorClass("URL '" + parsed.toString() + "' has no hostname",
329
+ "ssrf-guard/no-hostname", { url: parsed.toString() });
330
+ }
331
+
332
+ // Strip IPv6 brackets — net.isIP doesn't accept "[::1]" form, only "::1"
333
+ var hostForCheck = parsed.hostname.replace(/^\[|\]$/g, "");
334
+
335
+ var ips;
336
+ if (net.isIP(hostForCheck)) {
337
+ ips = [{ address: hostForCheck, family: net.isIP(hostForCheck) }];
338
+ } else {
339
+ var lookup = opts.dnsLookup || function (host) {
340
+ try {
341
+ var nd = networkDns();
342
+ if (nd && typeof nd.lookup === "function") {
343
+ return nd.lookup(host, { all: true });
344
+ }
345
+ } catch (_e) { /* fall through to native */ }
346
+ return dns.lookup(host, { all: true });
347
+ };
348
+ ips = await lookup(hostForCheck);
349
+ if (!Array.isArray(ips)) ips = [ips];
350
+ }
351
+
352
+ for (var i = 0; i < ips.length; i++) {
353
+ var addr = ips[i].address;
354
+ var category = classify(addr);
355
+ if (!category) continue;
356
+
357
+ // Cloud-metadata IPs are NEVER allowed — they leak instance
358
+ // credentials (AWS IMDS, GCP metadata, Azure IMDS) and a blanket
359
+ // allowInternal bypass would let any compromised request exfiltrate
360
+ // them. Operators with a legitimate need to talk to the metadata
361
+ // service do it through the cloud SDK with explicit IAM, never
362
+ // through the framework's outbound HTTP. Same hard-deny applies
363
+ // to allowInternal=[cidr-list]: the list grants exception for
364
+ // private ranges, not for the metadata IP that happens to fall
365
+ // inside link-local.
366
+ if (category === "cloud-metadata") {
367
+ throw new ErrorClass(
368
+ "URL '" + parsed.toString() + "' resolves to " + addr +
369
+ " (cloud-metadata) — blocked unconditionally; allowInternal does NOT override " +
370
+ "this class because metadata IPs leak instance credentials",
371
+ "ssrf-guard/blocked-cloud-metadata",
372
+ { url: parsed.toString(), ip: addr, category: category }
373
+ );
374
+ }
375
+
376
+ if (allowInternal === true) continue;
377
+ if (Array.isArray(allowInternal) && allowInternal.some(function (cidr) {
378
+ return cidrContains(cidr, addr);
379
+ })) continue;
380
+
381
+ throw new ErrorClass(
382
+ "URL '" + parsed.toString() + "' resolves to " + addr +
383
+ " in the " + category + " range — pass allowInternal:true to override",
384
+ "ssrf-guard/blocked-" + category,
385
+ { url: parsed.toString(), ip: addr, category: category }
386
+ );
387
+ }
388
+ return { url: parsed, ips: ips };
389
+ }
390
+
391
+ module.exports = {
392
+ classify: classify,
393
+ cidrContains: cidrContains,
394
+ checkUrl: checkUrl,
395
+ isPrivate: function (ip) { return classify(ip) === "private"; },
396
+ isLoopback: function (ip) { return classify(ip) === "loopback"; },
397
+ isLinkLocal: function (ip) { return classify(ip) === "link-local"; },
398
+ isCloudMetadata: function (ip) { return classify(ip) === "cloud-metadata"; },
399
+ isReserved: function (ip) { return classify(ip) === "reserved"; },
400
+ SsrfError: SsrfError,
401
+ };