@sogni-ai/sogni-creative-agent-skill 3.72.2 → 3.73.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/ssrf-guard.mjs CHANGED
@@ -1,24 +1,36 @@
1
1
  /**
2
2
  * SSRF Guard (ESM) — URL validator + guarded fetch to prevent Server-Side Request Forgery.
3
3
  *
4
- * `assertSafeUrl` blocks non-http(s) schemes, credentials in URLs, loopback /
5
- * RFC1918 / link-local / CGNAT / multicast / reserved IP ranges, and cloud
6
- * metadata endpoints, validating every A/AAAA record a hostname resolves to.
4
+ * `assertSafeUrl` blocks non-http(s) schemes, credentials in URLs, and every
5
+ * address that is not public unicast: loopback, RFC1918, link-local (cloud
6
+ * metadata), CGNAT, multicast, reserved and documentation ranges, and the IPv6
7
+ * forms that carry such an IPv4 address (mapped, translated, NAT64, 6to4). It
8
+ * validates every A/AAAA record a hostname resolves to.
7
9
  *
8
- * Known limitations (use `fetchSafeUrl` to close the first two):
9
- * - `assertSafeUrl` alone does not constrain what a later `fetch()` does:
10
- * a vetted public URL can 30x-redirect to a private address. `fetchSafeUrl`
11
- * fetches with `redirect: 'manual'` and re-validates every hop.
12
- * - `fetch()` performs its own DNS lookup after validation, so a rebinding
13
- * record that flips between the guard's lookup and the connect is a
14
- * residual TOCTOU window. Re-validating per hop narrows but cannot fully
15
- * eliminate it without a pinned-IP HTTP agent.
10
+ * `fetchSafeUrl` connects only to addresses it has checked. Its connection
11
+ * resolves the name through `guardedLookup`, which refuses the connection when
12
+ * any answer is blocked, so a name that answers a public address to the check
13
+ * and a private one to the connection (DNS rebinding) cannot reach the private
14
+ * one. It follows redirects itself and checks every hop the same way. A hop
15
+ * that Node's fetch() would or might send through a proxy from the environment
16
+ * (`fetchUsesEnvProxy`) still goes through fetch(): a proxy resolves the name,
17
+ * so no connection can be pinned, and `assertSafeUrl`'s own check of the name
18
+ * is the only one.
19
+ *
20
+ * `assertSafeUrl` alone constrains nothing a later request does: a caller that
21
+ * fetches with its own client must pin that client's connection itself.
22
+ *
23
+ * This module imports only Node built-ins: the desktop extension bundle ships
24
+ * it without the rest of the package.
16
25
  */
17
26
 
18
27
  import dns from 'node:dns';
28
+ import http from 'node:http';
29
+ import https from 'node:https';
19
30
  import net from 'node:net';
20
-
21
- const dnsPromises = dns.promises;
31
+ import { Readable, pipeline } from 'node:stream';
32
+ import { promisify } from 'node:util';
33
+ import zlib from 'node:zlib';
22
34
 
23
35
  // IPv4 CIDR blocks to reject. [networkAddress, prefixLength]
24
36
  const BLOCKED_V4_CIDRS = [
@@ -52,9 +64,7 @@ function ipv4ToInt(ip) {
52
64
  return n >>> 0;
53
65
  }
54
66
 
55
- function isBlockedV4(ip) {
56
- const ipInt = ipv4ToInt(ip);
57
- if (ipInt === null) return true; // unparseable -> block
67
+ function isBlockedV4Int(ipInt) {
58
68
  for (const [base, bits] of BLOCKED_V4_CIDRS) {
59
69
  const baseInt = ipv4ToInt(base);
60
70
  if (baseInt === null) continue;
@@ -62,25 +72,88 @@ function isBlockedV4(ip) {
62
72
  bits === 0 ? 0 :
63
73
  bits === 32 ? 0xffffffff :
64
74
  (~0 << (32 - bits)) >>> 0;
65
- if ((ipInt & mask) === (baseInt & mask)) return true;
75
+ if (((ipInt & mask) >>> 0) === ((baseInt & mask) >>> 0)) return true;
66
76
  }
67
77
  return false;
68
78
  }
69
79
 
80
+ function isBlockedV4(ip) {
81
+ const ipInt = ipv4ToInt(ip);
82
+ if (ipInt === null) return true; // unparseable -> block
83
+ return isBlockedV4Int(ipInt);
84
+ }
85
+
86
+ /**
87
+ * The 128-bit value of an IPv6 address in any textual form (compressed, full,
88
+ * dotted IPv4 tail, zone suffix), or null when it does not parse.
89
+ */
90
+ function ipv6ToBigInt(ip) {
91
+ let text = ip.toLowerCase();
92
+ const zone = text.indexOf('%');
93
+ if (zone !== -1) text = text.slice(0, zone);
94
+ let tail = [];
95
+ const lastColon = text.lastIndexOf(':');
96
+ if (lastColon === -1) return null;
97
+ if (text.slice(lastColon + 1).includes('.')) {
98
+ const v4 = ipv4ToInt(text.slice(lastColon + 1));
99
+ if (v4 === null) return null;
100
+ tail = [v4 >>> 16, v4 & 0xffff];
101
+ text = text.slice(0, lastColon);
102
+ if (text.endsWith(':')) text += ':';
103
+ }
104
+ const halves = text.split('::');
105
+ if (halves.length > 2) return null;
106
+ const groupsOf = (part) => (part === ''
107
+ ? []
108
+ : part.split(':').map((group) => (/^[0-9a-f]{1,4}$/.test(group) ? Number.parseInt(group, 16) : Number.NaN)));
109
+ const head = groupsOf(halves[0]);
110
+ const rest = halves.length === 2 ? groupsOf(halves[1]) : [];
111
+ const missing = 8 - head.length - rest.length - tail.length;
112
+ if (halves.length === 2 ? missing < 1 : missing !== 0) return null;
113
+ const groups = [...head, ...new Array(halves.length === 2 ? missing : 0).fill(0), ...rest, ...tail];
114
+ if (groups.some(Number.isNaN)) return null;
115
+ return groups.reduce((value, group) => (value << 16n) | BigInt(group), 0n);
116
+ }
117
+
118
+ function v6Cidr(base, bits) {
119
+ return { base: ipv6ToBigInt(base), shift: BigInt(128 - bits) };
120
+ }
121
+
122
+ function inV6Cidr(addr, { base, shift }) {
123
+ return (addr >> shift) === (base >> shift);
124
+ }
125
+
126
+ // IPv6 forms whose connection reaches an embedded IPv4 host, so that host's
127
+ // address decides: [range, bit offset of the IPv4 address].
128
+ const EMBEDDED_V4_V6_CIDRS = [
129
+ [v6Cidr('::ffff:0:0', 96), 0n], // IPv4-mapped
130
+ [v6Cidr('::ffff:0:0:0', 96), 0n], // IPv4-translated (RFC 6145)
131
+ [v6Cidr('64:ff9b::', 96), 0n], // NAT64 well-known prefix (RFC 6052)
132
+ [v6Cidr('2002::', 16), 80n], // 6to4 (RFC 3056): 2002:AABB:CCDD::/48
133
+ ];
134
+
135
+ // Every public IPv6 host is in 2000::/3. Outside it lie the unspecified and
136
+ // loopback addresses, IPv4-compatible ::/96, the 100::/64 discard prefix,
137
+ // local-use NAT64 64:ff9b:1::/48, unique-local fc00::/7, link-local fe80::/10,
138
+ // site-local fec0::/10 and multicast ff00::/8.
139
+ const V6_GLOBAL_UNICAST = v6Cidr('2000::', 3);
140
+
141
+ // Inside 2000::/3 but never a public web host.
142
+ const BLOCKED_V6_CIDRS = [
143
+ v6Cidr('2001::', 32), // Teredo (RFC 4380): tunnels to an IPv4 client
144
+ v6Cidr('2001:2::', 48), // benchmarking (RFC 5180)
145
+ v6Cidr('2001:db8::', 32), // documentation (RFC 3849)
146
+ v6Cidr('3fff::', 20), // documentation (RFC 9637)
147
+ ];
148
+
70
149
  function isBlockedV6(ip) {
71
- const lc = ip.toLowerCase();
72
- if (lc === '::1' || lc === '::') return true; // loopback / unspecified
73
- if (lc.startsWith('::ffff:')) { // IPv4-mapped -> check the v4
74
- const v4 = lc.slice(7);
75
- if (net.isIPv4(v4)) return isBlockedV4(v4);
76
- return true;
77
- }
78
- if (/^f[cd][0-9a-f]{2}:/.test(lc)) return true; // fc00::/7 unique-local
79
- if (/^fe[89ab][0-9a-f]:/.test(lc)) return true; // fe80::/10 link-local
80
- if (/^ff[0-9a-f]{2}:/.test(lc)) return true; // ff00::/8 multicast
81
- if (lc.startsWith('2001:db8:')) return true; // documentation
82
- if (lc.startsWith('64:ff9b:')) return true; // NAT64
83
- return false;
150
+ const addr = ipv6ToBigInt(ip);
151
+ if (addr === null) return true; // unparseable -> block
152
+ for (const [cidr, offset] of EMBEDDED_V4_V6_CIDRS) {
153
+ if (inV6Cidr(addr, cidr)) return isBlockedV4Int(Number((addr >> offset) & 0xffffffffn));
154
+ }
155
+ if (!inV6Cidr(addr, V6_GLOBAL_UNICAST)) return true;
156
+ return BLOCKED_V6_CIDRS.some((cidr) => inV6Cidr(addr, cidr));
84
157
  }
85
158
 
86
159
  function isBlockedIp(ip) {
@@ -98,11 +171,13 @@ function isBlockedIp(ip) {
98
171
  * @param {object} [options]
99
172
  * @param {string[]} [options.allowedProtocols=['http:','https:']]
100
173
  * @param {string[]} [options.allowedHosts] - optional exact-match hostname allowlist (lowercase)
174
+ * @param {Function} [options.lookup=dns.lookup] - dns.lookup-compatible resolver
101
175
  * @returns {Promise<URL>}
102
176
  */
103
177
  export async function assertSafeUrl(input, options = {}) {
104
178
  const allowedProtocols = options.allowedProtocols || ['http:', 'https:'];
105
179
  const allowedHosts = options.allowedHosts;
180
+ const lookup = options.lookup || dns.lookup;
106
181
 
107
182
  if (typeof input !== 'string' || input.length === 0) {
108
183
  throw new Error('SSRF guard: URL must be a non-empty string');
@@ -145,11 +220,11 @@ export async function assertSafeUrl(input, options = {}) {
145
220
  return parsed;
146
221
  }
147
222
 
148
- // Resolve all A/AAAA records and validate every one (defense vs DNS rebinding
149
- // and split-horizon DNS that returns mixed public/private addresses).
223
+ // Resolve all A/AAAA records and validate every one (split-horizon DNS can
224
+ // return mixed public/private addresses).
150
225
  let addrs;
151
226
  try {
152
- addrs = await dnsPromises.lookup(hostname, { all: true, verbatim: true });
227
+ addrs = await promisify(lookup)(hostname, { all: true, verbatim: true });
153
228
  } catch {
154
229
  throw new Error(`SSRF guard: DNS lookup failed for ${hostname}`);
155
230
  }
@@ -165,10 +240,243 @@ export async function assertSafeUrl(input, options = {}) {
165
240
  return parsed;
166
241
  }
167
242
 
243
+ /**
244
+ * Wraps a dns.lookup-compatible resolver for a socket's `lookup` option: the
245
+ * connection gets the resolver's answers only when every one of them is
246
+ * allowed, and fails with the SSRF guard error otherwise. A socket that
247
+ * resolves through it can reach no blocked address, however the name's
248
+ * answers change between lookups.
249
+ *
250
+ * @param {Function} [resolve=dns.lookup]
251
+ * @returns {Function} lookup(hostname, options, callback) for net/http/https
252
+ */
253
+ export function guardedLookup(resolve = dns.lookup) {
254
+ return function lookup(hostname, options, callback) {
255
+ if (typeof options === 'function') {
256
+ callback = options;
257
+ options = {};
258
+ }
259
+ const settings = typeof options === 'number' ? { family: options } : (options || {});
260
+ const query = { all: true, verbatim: true };
261
+ if (settings.family) query.family = settings.family;
262
+ if (settings.hints) query.hints = settings.hints;
263
+ resolve(hostname, query, (error, addresses) => {
264
+ if (error) {
265
+ callback(error);
266
+ return;
267
+ }
268
+ const answers = Array.isArray(addresses) ? addresses : [];
269
+ if (answers.length === 0) {
270
+ callback(Object.assign(new Error(`SSRF guard: no DNS records for ${hostname}`), { code: 'ENOTFOUND' }));
271
+ return;
272
+ }
273
+ const blocked = answers.find(({ address }) => isBlockedIp(address));
274
+ if (blocked) {
275
+ callback(Object.assign(
276
+ new Error(`SSRF guard: ${hostname} resolves to blocked IP ${blocked.address}`),
277
+ { code: 'SSRF_BLOCKED' },
278
+ ));
279
+ return;
280
+ }
281
+ if (settings.all) callback(null, answers);
282
+ else callback(null, answers[0].address, answers[0].family);
283
+ });
284
+ };
285
+ }
286
+
287
+ // The request headers Node's own fetch() adds, so servers answer this client
288
+ // as they answered the fetch() it replaces.
289
+ function defaultRequestHeaders(url) {
290
+ return {
291
+ accept: '*/*',
292
+ 'accept-language': '*',
293
+ 'sec-fetch-mode': 'cors',
294
+ 'user-agent': 'node',
295
+ 'accept-encoding': url.protocol === 'https:' ? 'br, gzip, deflate' : 'gzip, deflate',
296
+ };
297
+ }
298
+
299
+ const NULL_BODY_STATUSES = new Set([204, 205, 304]);
300
+ const REDIRECT_STATUSES = new Set([301, 302, 303, 307, 308]);
301
+
302
+ // Undo the content codings Node's fetch() undoes; a body with any other
303
+ // coding stays as sent, as fetch() leaves it.
304
+ function decodedBody(res) {
305
+ const codings = String(res.headers['content-encoding'] || '')
306
+ .toLowerCase().split(',').map((coding) => coding.trim()).filter(Boolean);
307
+ const decoders = [];
308
+ for (const coding of codings.reverse()) {
309
+ if (coding === 'gzip' || coding === 'x-gzip') {
310
+ decoders.push(zlib.createGunzip({ flush: zlib.constants.Z_SYNC_FLUSH, finishFlush: zlib.constants.Z_SYNC_FLUSH }));
311
+ } else if (coding === 'deflate') {
312
+ decoders.push(zlib.createInflate({ flush: zlib.constants.Z_SYNC_FLUSH, finishFlush: zlib.constants.Z_SYNC_FLUSH }));
313
+ } else if (coding === 'br') {
314
+ decoders.push(zlib.createBrotliDecompress({
315
+ flush: zlib.constants.BROTLI_OPERATION_FLUSH,
316
+ finishFlush: zlib.constants.BROTLI_OPERATION_FLUSH,
317
+ }));
318
+ } else {
319
+ return res;
320
+ }
321
+ }
322
+ if (decoders.length === 0) return res;
323
+ // pipeline destroys every stream when one fails or closes early, so a
324
+ // cancelled body closes the socket and a socket error reaches the body.
325
+ return pipeline(res, ...decoders, () => {});
326
+ }
327
+
328
+ // How Node's fetch() turns on the proxy from the environment, as observed on
329
+ // Node 22.11.0, 22.21.0, 22.23.4, 24.0.0, 24.4.1, 24.5.0, 24.22.3 and 26.6.0:
330
+ // 'none' never (before 22.21); 'env' any non-empty NODE_USE_ENV_PROXY (24.0 to
331
+ // 24.4); 'flag' the last --use-env-proxy or --no-use-env-proxy in NODE_OPTIONS
332
+ // then the command line, else NODE_USE_ENV_PROXY=1 (22.21+, 24.5+, 26). Null:
333
+ // a version whose rule is not known (23, 25, 27 and later).
334
+ function envProxyRule(nodeVersion) {
335
+ const [major, minor] = String(nodeVersion).split('.').map(Number);
336
+ if (major < 22) return 'none';
337
+ if (major === 22) return minor >= 21 ? 'flag' : 'none';
338
+ if (major === 24) return minor >= 5 ? 'flag' : 'env';
339
+ if (major === 26) return 'flag';
340
+ return null;
341
+ }
342
+
343
+ function envProxyEnabled(rule, env, execArgv) {
344
+ if (rule === 'none') return false;
345
+ if (rule === 'env') return Boolean(env.NODE_USE_ENV_PROXY);
346
+ let flag;
347
+ for (const token of [...String(env.NODE_OPTIONS || '').split(/\s+/), ...execArgv]) {
348
+ if (token === '--use-env-proxy') flag = true;
349
+ else if (token === '--no-use-env-proxy') flag = false;
350
+ }
351
+ return flag ?? env.NODE_USE_ENV_PROXY === '1';
352
+ }
353
+
354
+ // Whether NO_PROXY sends `hostname` direct under both NO_PROXY rules of the
355
+ // undici versions Node bundles. Older ones (Node 22, early 24) match a plain
356
+ // entry exactly and an entry starting with "." or "*" as a suffix; newer ones
357
+ // match an entry, without its leading "*." or ".", exactly or as a parent domain.
358
+ function noProxySendsDirect(hostname, port, noProxy) {
359
+ const entries = noProxy.split(/[,\s]/).filter(Boolean).map((entry) => {
360
+ const withPort = entry.match(/^(.+):(\d+)$/);
361
+ return { hostname: (withPort ? withPort[1] : entry).toLowerCase(), port: withPort ? Number.parseInt(withPort[2], 10) : 0 };
362
+ });
363
+ if (entries.length === 0) return false;
364
+ if (noProxy === '*') return true;
365
+ const onPort = entries.filter((entry) => !entry.port || entry.port === port);
366
+ const older = onPort.some((entry) => (/^[.*]/.test(entry.hostname)
367
+ ? hostname.endsWith(entry.hostname.replace(/^\*/, ''))
368
+ : hostname === entry.hostname));
369
+ const newer = onPort.some((entry) => {
370
+ const domain = entry.hostname.replace(/^\*?\./, '');
371
+ return hostname === domain || hostname.endsWith(`.${domain}`);
372
+ });
373
+ return older && newer;
374
+ }
375
+
376
+ const DEFAULT_PORTS = { 'http:': 80, 'https:': 443 };
377
+
378
+ /**
379
+ * Whether `fetchSafeUrl` leaves a request for `input` to Node's own fetch():
380
+ * true when fetch() would, or might, send it through a proxy from the
381
+ * environment. Node does that when HTTP_PROXY, HTTPS_PROXY, http_proxy or
382
+ * https_proxy is set and --use-env-proxy or NODE_USE_ENV_PROXY turns it on
383
+ * (`envProxyRule` gives each version's rule), through undici's
384
+ * EnvHttpProxyAgent: http_proxy before HTTP_PROXY; for https, https_proxy, then
385
+ * HTTPS_PROXY, then the http proxy; no proxy for a host NO_PROXY exempts, or
386
+ * for every host when it is "*". Where versions differ, so a request might
387
+ * still use the proxy, it is left to fetch(), as it is on a Node version whose
388
+ * rule is not known whenever a proxy variable is set. The `context` defaults
389
+ * are this process's.
390
+ *
391
+ * @param {string|URL} input
392
+ * @param {{env?: object, execArgv?: string[], nodeVersion?: string}} [context]
393
+ * @returns {boolean}
394
+ */
395
+ export function fetchUsesEnvProxy(input, {
396
+ env = process.env,
397
+ execArgv = process.execArgv,
398
+ nodeVersion = process.versions.node,
399
+ } = {}) {
400
+ if (!env.HTTP_PROXY && !env.HTTPS_PROXY && !env.http_proxy && !env.https_proxy) return false;
401
+ const rule = envProxyRule(nodeVersion);
402
+ if (rule === null) return true;
403
+ if (!envProxyEnabled(rule, env, execArgv)) return false;
404
+ const url = new URL(input);
405
+ const httpProxy = env.http_proxy ?? env.HTTP_PROXY;
406
+ const httpsProxy = (env.https_proxy ?? env.HTTPS_PROXY) || httpProxy;
407
+ if (!(url.protocol === 'https:' ? httpsProxy : httpProxy)) return false;
408
+ // Brackets stay on an IPv6 host, as NO_PROXY writes it.
409
+ const hostname = url.host.replace(/:\d*$/, '').toLowerCase();
410
+ const port = Number.parseInt(url.port, 10) || DEFAULT_PORTS[url.protocol] || 0;
411
+ return !noProxySendsDirect(hostname, port, env.no_proxy ?? env.NO_PROXY ?? '');
412
+ }
413
+
414
+ /**
415
+ * One GET or HEAD over node:http(s), resolving the host with `lookup` and
416
+ * never following a redirect, answered as a WHATWG Response. A fresh socket
417
+ * per request (no pooling) keeps every connection on the lookup's answer.
418
+ * Cancelling the Response body closes the socket.
419
+ *
420
+ * @param {string|URL} input
421
+ * @param {{method?: string, headers?: HeadersInit, signal?: AbortSignal}} [init]
422
+ * @param {Function} lookup - socket lookup, as `guardedLookup` returns
423
+ * @returns {Promise<Response>}
424
+ */
425
+ export function requestWithLookup(input, init = {}, lookup) {
426
+ const url = new URL(input);
427
+ if (url.protocol !== 'http:' && url.protocol !== 'https:') {
428
+ throw new TypeError(`requestWithLookup: protocol ${url.protocol} is not http or https`);
429
+ }
430
+ const method = String(init.method || 'GET').toUpperCase();
431
+ if ((method !== 'GET' && method !== 'HEAD') || init.body != null) {
432
+ throw new TypeError('requestWithLookup sends only GET and HEAD requests without a body');
433
+ }
434
+ const headers = new Headers(init.headers);
435
+ for (const [name, value] of Object.entries(defaultRequestHeaders(url))) {
436
+ if (!headers.has(name)) headers.set(name, value);
437
+ }
438
+ const transport = url.protocol === 'https:' ? https : http;
439
+ return new Promise((resolve, reject) => {
440
+ const req = transport.request(url, {
441
+ method,
442
+ headers: Object.fromEntries(headers),
443
+ lookup,
444
+ agent: false,
445
+ signal: init.signal,
446
+ }, (res) => {
447
+ const status = res.statusCode;
448
+ if (!(status >= 200 && status <= 599)) {
449
+ res.destroy();
450
+ reject(new Error(`Server answered an invalid HTTP status (${status})`));
451
+ return;
452
+ }
453
+ const responseHeaders = new Headers();
454
+ for (let i = 0; i + 1 < res.rawHeaders.length; i += 2) {
455
+ responseHeaders.append(res.rawHeaders[i], res.rawHeaders[i + 1]);
456
+ }
457
+ const responseInit = { status, statusText: res.statusMessage || '', headers: responseHeaders };
458
+ if (method === 'HEAD' || NULL_BODY_STATUSES.has(status)) {
459
+ res.destroy();
460
+ resolve(new Response(null, responseInit));
461
+ return;
462
+ }
463
+ const body = REDIRECT_STATUSES.has(status) ? res : decodedBody(res);
464
+ resolve(new Response(Readable.toWeb(body), responseInit));
465
+ });
466
+ req.on('error', reject);
467
+ req.end();
468
+ });
469
+ }
470
+
168
471
  /**
169
472
  * fetch() a validated URL without trusting redirects: every hop is re-run
170
473
  * through `assertSafeUrl` before it is followed, so a public host cannot
171
- * bounce the request to a private/metadata address.
474
+ * bounce the request to a private/metadata address. Without `fetchImpl`, each
475
+ * request connects through `guardedLookup`, so DNS rebinding cannot reach a
476
+ * blocked address either, except a hop `fetchUsesEnvProxy` leaves to Node's
477
+ * fetch() and its environment proxy, which resolves the name itself. A
478
+ * `fetchImpl` replaces both: tests and callers that pin their own connections
479
+ * pass one.
172
480
  *
173
481
  * Intended for GET-style media downloads (redirect responses are followed as
174
482
  * GETs, matching standard fetch semantics for 301/302/303 on bodyless
@@ -177,7 +485,8 @@ export async function assertSafeUrl(input, options = {}) {
177
485
  * @param {string} input
178
486
  * @param {RequestInit} [init]
179
487
  * @param {object} [options]
180
- * @param {Function} [options.fetchImpl=fetch] - injectable for tests/timeouts
488
+ * @param {Function} [options.fetchImpl] - fetch-compatible request function
489
+ * @param {Function} [options.lookup=dns.lookup] - dns.lookup-compatible resolver
181
490
  * @param {number} [options.maxRedirects=5]
182
491
  * @param {string[]} [options.allowedProtocols]
183
492
  * @param {string[]} [options.allowedHosts]
@@ -185,22 +494,29 @@ export async function assertSafeUrl(input, options = {}) {
185
494
  */
186
495
  export async function fetchSafeUrl(input, init = {}, options = {}) {
187
496
  const {
188
- fetchImpl = fetch,
497
+ fetchImpl = null,
498
+ lookup = dns.lookup,
189
499
  maxRedirects = 5,
190
500
  allowedProtocols,
191
501
  allowedHosts,
192
502
  } = options;
193
- const guardOptions = {};
503
+ const guardOptions = { lookup };
194
504
  if (allowedProtocols) guardOptions.allowedProtocols = allowedProtocols;
195
505
  if (allowedHosts) guardOptions.allowedHosts = allowedHosts;
506
+ const pinnedLookup = guardedLookup(lookup);
507
+ const request = fetchImpl || ((url, requestInit) => (fetchUsesEnvProxy(url)
508
+ ? fetch(url, requestInit)
509
+ : requestWithLookup(url, requestInit, pinnedLookup)));
196
510
 
197
511
  let current = (await assertSafeUrl(input, guardOptions)).toString();
198
512
  for (let hop = 0; hop <= maxRedirects; hop++) {
199
- const response = await fetchImpl(current, { ...init, redirect: 'manual' });
513
+ const response = await request(current, { ...init, redirect: 'manual' });
200
514
  const status = response.status;
201
515
  if (status < 300 || status >= 400) return response;
202
516
  const location = response.headers.get('location');
203
517
  if (!location) return response;
518
+ // Close the redirect's connection before the next hop opens another.
519
+ await response.body?.cancel?.().catch(() => {});
204
520
  let nextUrl;
205
521
  try {
206
522
  nextUrl = new URL(location, current).toString();
@@ -213,4 +529,69 @@ export async function fetchSafeUrl(input, init = {}, options = {}) {
213
529
  throw new Error(`SSRF guard: too many redirects (more than ${maxRedirects})`);
214
530
  }
215
531
 
532
+ /**
533
+ * Read a Response body into one Buffer, refusing a body longer than
534
+ * `maxBytes` (`code: 'BODY_TOO_LARGE'`, before any byte is read when
535
+ * Content-Length already says so) and one that sends no bytes for `stallMs`
536
+ * (`code: 'BODY_STALLED'`). Either refusal cancels the body, which closes a
537
+ * `requestWithLookup` connection.
538
+ *
539
+ * @param {Response} response
540
+ * @param {{maxBytes?: number, stallMs?: number}} [limits] - stallMs 0 waits forever
541
+ * @returns {Promise<Buffer>}
542
+ */
543
+ export async function readResponseBody(response, { maxBytes = Infinity, stallMs = 0 } = {}) {
544
+ const tooLarge = () => Object.assign(
545
+ new Error(`Response body is larger than ${maxBytes} bytes`),
546
+ { code: 'BODY_TOO_LARGE', maxBytes },
547
+ );
548
+ const declared = Number(response.headers.get('content-length') ?? Number.NaN);
549
+ if (!response.headers.get('content-encoding') && Number.isFinite(declared) && declared > maxBytes) {
550
+ await response.body?.cancel?.().catch(() => {});
551
+ throw tooLarge();
552
+ }
553
+ if (!response.body) return Buffer.alloc(0);
554
+ const reader = response.body.getReader();
555
+ const chunks = [];
556
+ let length = 0;
557
+ let stalled = false;
558
+ let timer = null;
559
+ const stalledError = () => Object.assign(
560
+ new Error(`Response body sent no data for ${stallMs} ms`),
561
+ { code: 'BODY_STALLED', stallMs },
562
+ );
563
+ const armStallTimer = () => {
564
+ if (!(stallMs > 0)) return;
565
+ clearTimeout(timer);
566
+ timer = setTimeout(() => {
567
+ stalled = true;
568
+ reader.cancel().catch(() => {});
569
+ }, stallMs);
570
+ };
571
+ try {
572
+ armStallTimer();
573
+ for (;;) {
574
+ let chunk;
575
+ try {
576
+ chunk = await reader.read();
577
+ } catch (error) {
578
+ if (stalled) throw stalledError();
579
+ throw error;
580
+ }
581
+ if (stalled) throw stalledError();
582
+ if (chunk.done) break;
583
+ length += chunk.value.byteLength;
584
+ if (length > maxBytes) {
585
+ await reader.cancel().catch(() => {});
586
+ throw tooLarge();
587
+ }
588
+ chunks.push(chunk.value);
589
+ armStallTimer();
590
+ }
591
+ } finally {
592
+ clearTimeout(timer);
593
+ }
594
+ return Buffer.concat(chunks, length);
595
+ }
596
+
216
597
  export { isBlockedIp };
package/version.mjs CHANGED
@@ -1 +1 @@
1
- export const PACKAGE_VERSION = '3.72.2';
1
+ export const PACKAGE_VERSION = '3.73.1';