diff --git a/deps/undici/src/README.md b/deps/undici/src/README.md index 7662b905bdff..e5af5f7ec8b9 100644 --- a/deps/undici/src/README.md +++ b/deps/undici/src/README.md @@ -668,7 +668,7 @@ The [Fetch Standard](https://fetch.spec.whatwg.org) requires implementations to * https://www.rfc-editor.org/rfc/rfc9110#field.content-encoding -Undici limits the number of `Content-Encoding` layers in a response to **5** to prevent resource exhaustion attacks. If a server responds with more than 5 content-encodings (e.g., `Content-Encoding: gzip, gzip, gzip, gzip, gzip, gzip`), the fetch will be rejected with an error. This limit matches the approach taken by [curl](https://curl.se/docs/CVE-2022-32206.html) and [urllib3](https://github.com/advisories/GHSA-gm62-xv2j-4rw9). +Undici limits the number of `Content-Encoding` layers in a response to **5** to prevent resource exhaustion attacks. If a server responds with more than 5 content-encodings (e.g., `Content-Encoding: gzip, gzip, gzip, gzip, gzip, gzip`), the fetch will be rejected with an error. This limit matches the approach taken by [curl](https://curl.se/docs/CVE-2022-32206.html) and [urllib3](https://github.com/advisories/GHSA-gm62-xv2j-4w53). #### `undici.upgrade([url, options]): Promise` diff --git a/deps/undici/src/docs/docs/api/Client.md b/deps/undici/src/docs/docs/api/Client.md index 402e050351dc..36f6a4f24656 100644 --- a/deps/undici/src/docs/docs/api/Client.md +++ b/deps/undici/src/docs/docs/api/Client.md @@ -131,7 +131,11 @@ added: v1.0.0 streams for a single session. Once h2 is negotiated this — not `pipelining`, which is HTTP/1.1 only — is the ceiling used to dispatch in-flight requests. The server's `SETTINGS_MAX_CONCURRENT_STREAMS` can lower this limit, but - not raise it. **Default:** `100`. + not raise it. Until the server's SETTINGS frame is received on a new + connection, requests whose body can be replayed are dispatched up to the + lower of this limit and `100`, and a stream refused by a lower server limit + is retried once; a request with a streaming body waits for the SETTINGS + frame while another request is in flight. **Default:** `100`. * `connectionWindowSize` {number} The HTTP/2 connection-level flow-control window size set via `ClientHttp2Session.setLocalWindowSize()`. Must be a positive integer. **Default:** `524288`. @@ -171,6 +175,9 @@ eagerly. > * The server must support HTTP/2 and select it during ALPN negotiation, and > must not give HTTP/1.1 a higher priority than HTTP/2. > * `PUSH` frames are not supported. +> * Aborting a request, for example through its `signal`, resets its stream +> with `RST_STREAM` and the `CANCEL` error code, including when part of the +> request body has not been sent yet. ```mjs displayName="Basic instantiation" import { Client } from 'undici' diff --git a/deps/undici/src/docs/docs/api/Dispatcher.md b/deps/undici/src/docs/docs/api/Dispatcher.md index 8265bee52d6b..b278f328ce1b 100644 --- a/deps/undici/src/docs/docs/api/Dispatcher.md +++ b/deps/undici/src/docs/docs/api/Dispatcher.md @@ -831,7 +831,7 @@ For the full reference of built-in interceptors (`dump`, `retry`, `redirect`, see [Interceptors](Interceptors.md). [Fastify]: https://fastify.dev -[GOAWAY frame]: https://webconcepts.info/concepts/http2-frame-type/0x7 +[GOAWAY frame]: https://www.rfc-editor.org/rfc/rfc9113.html#section-6.8 [HTTP `CONNECT`]: https://developer.mozilla.org/en-US/docs/Web/HTTP/Methods/CONNECT [MDN: Protocol upgrade mechanism]: https://developer.mozilla.org/en-US/docs/Web/HTTP/Protocol_upgrade_mechanism [`.arrayBuffer()`]: https://fetch.spec.whatwg.org/#dom-body-arraybuffer diff --git a/deps/undici/src/docs/docs/api/H2CClient.md b/deps/undici/src/docs/docs/api/H2CClient.md index 2a48dc037d99..9f218b92cdfe 100644 --- a/deps/undici/src/docs/docs/api/H2CClient.md +++ b/deps/undici/src/docs/docs/api/H2CClient.md @@ -56,8 +56,12 @@ added: v7.7.0 * `options` {H2CClientOptions} (optional) * `maxConcurrentStreams` {number} The maximum number of concurrent HTTP/2 streams for the session. The server's `SETTINGS_MAX_CONCURRENT_STREAMS` can - lower this limit, but not raise it. Must be a positive integer. - **Default:** `100`. + lower this limit, but not raise it. Until the server's SETTINGS frame is + received on a new connection, requests whose body can be replayed are + dispatched up to the lower of this limit and `100`, and a stream refused by a + lower server limit is retried once; a request with a streaming body waits for + the SETTINGS frame while another request is in flight. Must be a positive + integer. **Default:** `100`. * `pipelining` {number} The number of concurrent requests multiplexed over the single connection. For an `H2CClient` this is aliased to `maxConcurrentStreams` and may not exceed it. Must be a positive integer. diff --git a/deps/undici/src/docs/docs/api/Interceptors.md b/deps/undici/src/docs/docs/api/Interceptors.md index 3d3ae902fb0e..1ac3592e3de1 100644 --- a/deps/undici/src/docs/docs/api/Interceptors.md +++ b/deps/undici/src/docs/docs/api/Interceptors.md @@ -204,6 +204,9 @@ and `x-compress`, is left untouched, matching `fetch()`. As required by [RFC 9659](https://www.rfc-editor.org/rfc/rfc9659.html), a `zstd` frame that requires a window size larger than 8 MB fails to decode. +By default, decompression removes `Content-Encoding` and `Content-Length` from +both the response headers and `controller.rawHeaders`. + **Parameters** * `opts` {Object} (optional) @@ -211,6 +214,11 @@ requires a window size larger than 8 MB fails to decode. skipped. **Default:** `[204, 304]`. * `skipErrorResponses` {boolean} When `true`, responses with a status code >= 400 are not decompressed. **Default:** `true`. + * `preserveHeaders` {boolean} When `true`, keeps `Content-Encoding` and + `Content-Length` in both the response headers and `controller.rawHeaders` + while still decompressing the body. These headers describe the encoded + response, so `Content-Length` is the compressed size, not the decoded size. + Useful for implementing Fetch or XMLHttpRequest semantics. **Default:** `false`. * `maxSize` {number} Maximum decompressed response size in bytes for each decompression stage. The request fails with a `ResponseExceededMaxSizeError` if a stage exceeds this limit. Set to `0` to @@ -386,6 +394,8 @@ const agent = new Agent().compose( Deduplicates concurrent identical requests so that only one is sent over the wire. All waiting callers receive the same response once the in-flight request completes. Only safe HTTP methods (e.g. `GET`, `HEAD`) may be deduplicated. +Requests that carry a body are never deduplicated, since the body is not part +of the deduplication key. **Parameters** diff --git a/deps/undici/src/docs/docs/api/RetryHandler.md b/deps/undici/src/docs/docs/api/RetryHandler.md index 3557ab733345..66a86b8f3fc0 100644 --- a/deps/undici/src/docs/docs/api/RetryHandler.md +++ b/deps/undici/src/docs/docs/api/RetryHandler.md @@ -64,6 +64,11 @@ changes: attempt and propagated to the inner handler; when `false`, the failing response is passed through instead, which is useful when the error body is needed or a custom error handler is in place. **Default:** `true`. +* `resume` {boolean} When `false`, a response that fails after its headers were + received is not resumed with a `Range` request: the error is passed to the + inner handler, and only failures before the response headers are retried. This + suits proxies that stream the response downstream as it arrives. + **Default:** `true`. * `retry` {Function} Callback invoked on every retry iteration to decide whether another attempt should be made. It receives the error, the retry context, and a callback. Call the callback with an `Error` to stop retrying, or with `null` to diff --git a/deps/undici/src/docs/docs/index.md b/deps/undici/src/docs/docs/index.md index dee24547d53d..15c2af616113 100644 --- a/deps/undici/src/docs/docs/index.md +++ b/deps/undici/src/docs/docs/index.md @@ -640,7 +640,7 @@ The [Fetch Standard](https://fetch.spec.whatwg.org) requires implementations to * https://www.rfc-editor.org/rfc/rfc9110#field.content-encoding -Undici limits the number of `Content-Encoding` layers in a response to **5** to prevent resource exhaustion attacks. If a server responds with more than 5 content-encodings (e.g., `Content-Encoding: gzip, gzip, gzip, gzip, gzip, gzip`), the fetch will be rejected with an error. This limit matches the approach taken by [curl](https://curl.se/docs/CVE-2022-32206.html) and [urllib3](https://github.com/advisories/GHSA-gm62-xv2j-4rw9). +Undici limits the number of `Content-Encoding` layers in a response to **5** to prevent resource exhaustion attacks. If a server responds with more than 5 content-encodings (e.g., `Content-Encoding: gzip, gzip, gzip, gzip, gzip, gzip`), the fetch will be rejected with an error. This limit matches the approach taken by [curl](https://curl.se/docs/CVE-2022-32206.html) and [urllib3](https://github.com/advisories/GHSA-gm62-xv2j-4w53). #### `undici.upgrade([url, options])` diff --git a/deps/undici/src/lib/api/api-request.js b/deps/undici/src/lib/api/api-request.js index c857e213d3f9..73782a0f2d3e 100644 --- a/deps/undici/src/lib/api/api-request.js +++ b/deps/undici/src/lib/api/api-request.js @@ -164,7 +164,7 @@ class RequestHandler extends AsyncResource { return } - if (this.res.push(chunk) === false) { + if (this.runInAsyncScope(() => this.res.push(chunk)) === false) { controller.pause() } } diff --git a/deps/undici/src/lib/core/socks5-utils.js b/deps/undici/src/lib/core/socks5-utils.js index e6098bef05fc..5aeb75609c80 100644 --- a/deps/undici/src/lib/core/socks5-utils.js +++ b/deps/undici/src/lib/core/socks5-utils.js @@ -4,15 +4,37 @@ const { Buffer } = require('node:buffer') const net = require('node:net') const { InvalidArgumentError } = require('./errors') +/** + * Strip surrounding brackets from an IPv6 literal host (e.g. "[::1]" -> "::1"). + * Non-IPv6 inputs are returned unchanged. + * @param {string} address + * @returns {string} + */ +function stripIPv6Brackets (address) { + if ( + address.length >= 2 && + address.charCodeAt(0) === 91 && + address.charCodeAt(address.length - 1) === 93 + ) { + const unbracketed = address.slice(1, -1) + if (net.isIPv6(unbracketed)) { + return unbracketed + } + } + return address +} + /** * Parse an address and determine its type * @param {string} address - The address to parse * @returns {{type: number, buffer: Buffer}} Address type and buffer */ function parseAddress (address) { + const normalizedAddress = stripIPv6Brackets(address) + // Check if it's an IPv4 address - if (net.isIPv4(address)) { - const parts = address.split('.').map(Number) + if (net.isIPv4(normalizedAddress)) { + const parts = normalizedAddress.split('.').map(Number) return { type: 0x01, // IPv4 buffer: Buffer.from(parts) @@ -20,10 +42,10 @@ function parseAddress (address) { } // Check if it's an IPv6 address - if (net.isIPv6(address)) { + if (net.isIPv6(normalizedAddress)) { return { type: 0x04, // IPv6 - buffer: parseIPv6(address) + buffer: parseIPv6(normalizedAddress) } } @@ -46,18 +68,18 @@ function parseAddress (address) { */ function parseIPv6 (address) { const buffer = Buffer.alloc(16) - let normalizedAddress = address + let normalizedAddress = stripIPv6Brackets(address) // Expand an embedded IPv4 tail into the last two IPv6 groups. - if (address.includes('.')) { - const lastColonIndex = address.lastIndexOf(':') - const ipv4Part = address.slice(lastColonIndex + 1) + if (normalizedAddress.includes('.')) { + const lastColonIndex = normalizedAddress.lastIndexOf(':') + const ipv4Part = normalizedAddress.slice(lastColonIndex + 1) if (net.isIPv4(ipv4Part)) { const octets = ipv4Part.split('.').map(Number) const high = ((octets[0] << 8) | octets[1]).toString(16) const low = ((octets[2] << 8) | octets[3]).toString(16) - normalizedAddress = `${address.slice(0, lastColonIndex)}:${high}:${low}` + normalizedAddress = `${normalizedAddress.slice(0, lastColonIndex)}:${high}:${low}` } } @@ -204,6 +226,7 @@ function createReplyError (replyCode) { } module.exports = { + stripIPv6Brackets, parseAddress, parseIPv6, buildAddressBuffer, diff --git a/deps/undici/src/lib/core/util.js b/deps/undici/src/lib/core/util.js index db654c247d27..43ea414ab765 100644 --- a/deps/undici/src/lib/core/util.js +++ b/deps/undici/src/lib/core/util.js @@ -960,6 +960,11 @@ const kEnumerableProperty = { enumerable: true } +const kNonEnumerableProperty = { + __proto__: null, + enumerable: false +} + const normalizedMethodRecordsBase = { delete: 'DELETE', DELETE: 'DELETE', @@ -989,6 +994,7 @@ Object.setPrototypeOf(normalizedMethodRecords, null) module.exports = { kEnumerableProperty, + kNonEnumerableProperty, isDisturbed, isBlobLike, parseOrigin, diff --git a/deps/undici/src/lib/dispatcher/client-h1.js b/deps/undici/src/lib/dispatcher/client-h1.js index 13bc66f9372d..fe53d1180814 100644 --- a/deps/undici/src/lib/dispatcher/client-h1.js +++ b/deps/undici/src/lib/dispatcher/client-h1.js @@ -1006,6 +1006,11 @@ function onHttpSocketError (err) { this[kError] = err + // Some sockets (e.g. TLSSocket on ERR_SSL_* record/alert errors) emit 'error' + // without destroying themselves. Destroy without an error argument so 'close' + // runs without emitting a duplicate 'error' event. + util.destroy(this) + this[kClient][kOnError](err) } diff --git a/deps/undici/src/lib/dispatcher/client-h2.js b/deps/undici/src/lib/dispatcher/client-h2.js index 418ef37e922b..e70b5deb9eba 100644 --- a/deps/undici/src/lib/dispatcher/client-h2.js +++ b/deps/undici/src/lib/dispatcher/client-h2.js @@ -90,6 +90,7 @@ const { HTTP2_HEADER_EXPECT, HTTP2_HEADER_STATUS, HTTP2_HEADER_PROTOCOL, + NGHTTP2_CANCEL, NGHTTP2_NO_ERROR, NGHTTP2_PROTOCOL_ERROR, NGHTTP2_REFUSED_STREAM @@ -314,6 +315,17 @@ function connectH2 (client, socket) { // States whether or not we have received the remote settings from the server session[kRemoteSettings] = false + // Until the server's SETTINGS frame arrives we do not know its + // SETTINGS_MAX_CONCURRENT_STREAMS. RFC 9113 section 3.4 lets a client send + // requests right after the connection preface, and section 6.5.2 recommends + // servers allow at least 100 concurrent streams, so dispatch optimistically + // up to that many (capped by the client's own limit) instead of serializing + // every request behind the first response. A server advertising a lower + // limit refuses the extra streams with REFUSED_STREAM, which section 8.7 + // permits retrying. onHttp2RemoteSettings replaces this with the confirmed + // limit once SETTINGS arrive. + client[kMaxConcurrentStreams] = Math.min(client[kHTTP2Options].maxConcurrentStreams, 100) + // Apply connection-level flow control once connected (if supported). if (http2ConnectionWindowSize) { util.addListener(session, 'connect', applyConnectionWindowSize.bind(session, http2ConnectionWindowSize)) @@ -377,8 +389,15 @@ function connectH2 (client, socket) { * @returns {boolean} */ busy (request) { - if (session[kRemoteSettings] === false && client[kRunning] > 0) { - return true + // Before SETTINGS, the client takes one request at a time from a Pool, + // and only dispatches alongside a running request when a REFUSED_STREAM + // from a lower peer limit can still be retried. + if (session[kRemoteSettings] === false) { + if (request == null) { + if (client[kSize] > 0) return true + } else if (client[kRunning] > 0 && (request[kRefusedStreamRetry] || !canReplayRequest(request))) { + return true + } } // Do not open streams on a connection that may be dead. @@ -637,7 +656,12 @@ function onHttp2RemoteSettings (settings) { // ceiling. The server's SETTINGS_MAX_CONCURRENT_STREAMS can lower it, but // must not raise it: a default Node.js server advertises 2^32-1. const localMaxConcurrentStreams = client[kHTTP2Options].maxConcurrentStreams - const remoteMaxConcurrentStreams = settings.maxConcurrentStreams ?? client[kMaxConcurrentStreams] ?? localMaxConcurrentStreams + // Before the first SETTINGS, client[kMaxConcurrentStreams] holds the + // optimistic pre-SETTINGS ceiling (see connectH2), not a server-confirmed + // value, so only fall back to a previously confirmed value once SETTINGS + // have been received. + const remoteMaxConcurrentStreams = settings.maxConcurrentStreams ?? + (this[kRemoteSettings] ? client[kMaxConcurrentStreams] : localMaxConcurrentStreams) client[kMaxConcurrentStreams] = Math.min(remoteMaxConcurrentStreams, localMaxConcurrentStreams) /** * From RFC-8441 @@ -1182,9 +1206,12 @@ function writeH2 (client, request) { if (state.stream != null) { clearRequestStream(request) - // On Abort, we close the stream to send RST_STREAM frame. + // On Abort, we close the stream to send RST_STREAM frame. Use CANCEL, + // the code for a stream that is no longer needed: with NO_ERROR, Node + // defers the RST_STREAM until a still-queued request body finishes, + // and the synchronous destroy below means that never happens. const stream = state.stream - stream.close() + stream.close(NGHTTP2_CANCEL) // close() alone leaves cleanup waiting on the 'close' event; on a busy, // long-lived multiplexed session that event can fail to fire, leaving the diff --git a/deps/undici/src/lib/dispatcher/socks5-proxy-agent.js b/deps/undici/src/lib/dispatcher/socks5-proxy-agent.js index e380005ffb61..1a511c6c923b 100644 --- a/deps/undici/src/lib/dispatcher/socks5-proxy-agent.js +++ b/deps/undici/src/lib/dispatcher/socks5-proxy-agent.js @@ -6,10 +6,11 @@ let tls // include tls conditionally since it is not always available const DispatcherBase = require('./dispatcher-base') const { ConnectTimeoutError, InvalidArgumentError } = require('../core/errors') const { Socks5Client, STATES } = require('../core/socks5-client') +const { stripIPv6Brackets } = require('../core/socks5-utils') const { kBusy, kConnected, kDispatch, kClose, kDestroy } = require('../core/symbols') const Pool = require('./pool') const buildConnector = require('../core/connect') -const { setupConnectTimeout } = require('../core/util') +const { setupConnectTimeout, getServerName } = require('../core/util') const { debuglog } = require('node:util') const debug = debuglog('undici:socks5-proxy') @@ -94,7 +95,7 @@ class Socks5ProxyAgent extends DispatcherBase { this[kConnector] = options.connect || buildConnector({ ...options.proxyTls, timeout: proxyTlsTimeout, - servername: options.proxyTls?.servername || url.hostname + servername: options.proxyTls?.servername || getServerName(url.hostname) || undefined }) // Pools for the actual HTTP connections (with SOCKS5 tunnel connect function), keyed by origin @@ -105,7 +106,7 @@ class Socks5ProxyAgent extends DispatcherBase { * Create a SOCKS5 connection to the proxy */ async createSocks5Connection (targetHost, targetPort) { - const proxyHost = this[kProxyUrl].hostname + const proxyHost = stripIPv6Brackets(this[kProxyUrl].hostname) const proxyPort = parseInt(this[kProxyUrl].port) || 1080 debug('creating SOCKS5 connection to', proxyHost, proxyPort) @@ -238,7 +239,7 @@ class Socks5ProxyAgent extends DispatcherBase { connect: async (connectOpts, callback) => { try { const url = new URL(origin) - const targetHost = url.hostname + const targetHost = stripIPv6Brackets(url.hostname) const targetPort = parseInt(url.port) || (url.protocol === 'https:' ? 443 : 80) debug('establishing SOCKS5 connection to', targetHost, targetPort) diff --git a/deps/undici/src/lib/handler/retry-handler.js b/deps/undici/src/lib/handler/retry-handler.js index 19d2585f5192..d251a7b1c2a9 100644 --- a/deps/undici/src/lib/handler/retry-handler.js +++ b/deps/undici/src/lib/handler/retry-handler.js @@ -117,7 +117,8 @@ class RetryHandler { errorCodes, retryAfter, statusCodes, - throwOnError + throwOnError, + resume } = retryOptions ?? {} this.error = null @@ -126,6 +127,8 @@ class RetryHandler { this.opts = { ...dispatchOpts, body: wrapRequestBody(opts.body) } this.retryOpts = { throwOnError: throwOnError ?? true, + // Whether a response cut after its headers is resumed with a Range request + resume: resume ?? true, retry: retryFn ?? RetryHandler[kRetryHandlerDefaultRetry], retryAfter: retryAfter ?? true, maxTimeout: maxTimeout ?? 30 * 1000, // 30s, @@ -595,7 +598,7 @@ class RetryHandler { // controller is THIS failed connection (not the proxy): we inspect whether // the consumer aborted it to decide retry-vs-propagate. - if (controller?.aborted || isDisturbed(this.opts.body) || (this.headersSent && !this.resume)) { + if (controller?.aborted || isDisturbed(this.opts.body) || (this.headersSent && (!this.resume || !this.retryOpts.resume))) { this.handler.onResponseError?.(this.controllerProxy, err) return } diff --git a/deps/undici/src/lib/interceptor/decompress.js b/deps/undici/src/lib/interceptor/decompress.js index 835c9fa7794f..c8f5ff1d4ba4 100644 --- a/deps/undici/src/lib/interceptor/decompress.js +++ b/deps/undici/src/lib/interceptor/decompress.js @@ -109,6 +109,7 @@ function createMaxSizeLimiter (maxSize) { * @typedef {Object} DecompressHandlerOptions * @property {number[]|Readonly} [skipStatusCodes=[204, 304]] - List of status codes to skip decompression for * @property {boolean} [skipErrorResponses] - Whether to skip decompression for error responses (status codes >= 400) + * @property {boolean} [preserveHeaders=false] - Whether to preserve the original response headers after decompression * @property {number} [maxSize=0] - Maximum decompressed response size in bytes. 0 disables the limit */ @@ -121,6 +122,8 @@ class DecompressHandler extends DecoratorHandler { #skipStatusCodes /** @type {boolean} */ #skipErrorResponses + /** @type {boolean} */ + #preserveHeaders /** @type {number} */ #maxSize /** @type {number} */ @@ -144,7 +147,7 @@ class DecompressHandler extends DecoratorHandler { /** @type {DecompressController} */ #controller - constructor (handler, { skipStatusCodes = defaultSkipStatusCodes, skipErrorResponses = true, maxSize = defaultMaxSize } = {}) { + constructor (handler, { skipStatusCodes = defaultSkipStatusCodes, skipErrorResponses = true, preserveHeaders = false, maxSize = defaultMaxSize } = {}) { if (!Number.isSafeInteger(maxSize) || maxSize < 0) { throw new InvalidArgumentError('maxSize must be a non-negative integer') } @@ -152,6 +155,7 @@ class DecompressHandler extends DecoratorHandler { super(handler) this.#skipStatusCodes = skipStatusCodes this.#skipErrorResponses = skipErrorResponses + this.#preserveHeaders = preserveHeaders this.#maxSize = maxSize this.#controller = new DecompressController( () => this.#onDownstreamPause(), @@ -452,10 +456,13 @@ class DecompressHandler extends DecoratorHandler { this.#decompressors = decompressors - // Remove compression headers since we're decompressing - const { 'content-encoding': _, 'content-length': __, ...newHeaders } = headers + let newHeaders = headers + if (!this.#preserveHeaders) { + const { 'content-encoding': _, 'content-length': __, ...decodedHeaders } = headers + newHeaders = decodedHeaders + } - if (this.#controller.rawHeaders) { + if (!this.#preserveHeaders && this.#controller.rawHeaders) { const rawHeaders = this.#controller.rawHeaders if (Array.isArray(rawHeaders)) { diff --git a/deps/undici/src/lib/interceptor/deduplicate.js b/deps/undici/src/lib/interceptor/deduplicate.js index c8e5b934c5a6..d2f2aa255b26 100644 --- a/deps/undici/src/lib/interceptor/deduplicate.js +++ b/deps/undici/src/lib/interceptor/deduplicate.js @@ -65,6 +65,13 @@ module.exports = (opts = {}) => { return dispatch(opts, handler) } + // The request body is not part of the deduplication key, so two + // requests that only differ in their body (e.g. a GET with a search + // query in it) would share one response. Send them independently. + if (opts.body != null) { + return dispatch(opts, handler) + } + opts = { ...opts, headers: normalizeHeaders(opts) diff --git a/deps/undici/src/lib/web/cache/cache.js b/deps/undici/src/lib/web/cache/cache.js index a8f1606041b7..7e030a17291a 100644 --- a/deps/undici/src/lib/web/cache/cache.js +++ b/deps/undici/src/lib/web/cache/cache.js @@ -658,10 +658,12 @@ class Cache { return resultList } catch (e) { // 5. // 5.1 - this.#relevantRequestResponseList.length = 0 + cache.length = 0 // 5.2 - this.#relevantRequestResponseList = backupCache + for (let i = 0; i < backupCache.length; i++) { + cache.push(backupCache[i]) + } // 5.3 throw e diff --git a/deps/undici/src/lib/web/fetch/index.js b/deps/undici/src/lib/web/fetch/index.js index f65afa1f9cb2..6c2f8ddf276b 100644 --- a/deps/undici/src/lib/web/fetch/index.js +++ b/deps/undici/src/lib/web/fetch/index.js @@ -136,7 +136,7 @@ class Fetch extends EE { // 2. Let fallbackError be an "AbortError" DOMException. // 3. Set error to fallbackError if it is not given. - if (!error) { + if (error === undefined) { error = new DOMException('The operation was aborted.', 'AbortError') } diff --git a/deps/undici/src/lib/web/websocket/websocket.js b/deps/undici/src/lib/web/websocket/websocket.js index e83343bb4d83..b29da937af35 100644 --- a/deps/undici/src/lib/web/websocket/websocket.js +++ b/deps/undici/src/lib/web/websocket/websocket.js @@ -18,7 +18,7 @@ const { } = require('./util') const { establishWebSocketConnection, closeWebSocketConnection, failWebsocketConnection } = require('./connection') const { ByteParser } = require('./receiver') -const { kEnumerableProperty } = require('../../core/util') +const { kEnumerableProperty, kNonEnumerableProperty } = require('../../core/util') const { getGlobalDispatcher } = require('../../global') const { ErrorEvent, CloseEvent, createFastMessageEvent } = require('./events') const { SendQueue } = require('./sender') @@ -202,12 +202,14 @@ class WebSocket extends EventTarget { // TODO: remove this [kRef] () { + webidl.brandCheck(this, webidl.is.WebSocket) this.#refed = true this.#handler.socket?.ref?.() } // TODO: remove this [kUnref] () { + webidl.brandCheck(this, webidl.is.WebSocket) this.#refed = false this.#handler.socket?.unref?.() } @@ -694,6 +696,8 @@ WebSocket.CLOSING = WebSocket.prototype.CLOSING = states.CLOSING WebSocket.CLOSED = WebSocket.prototype.CLOSED = states.CLOSED Object.defineProperties(WebSocket.prototype, { + [kRef]: kNonEnumerableProperty, + [kUnref]: kNonEnumerableProperty, CONNECTING: staticPropertyDescriptors, OPEN: staticPropertyDescriptors, CLOSING: staticPropertyDescriptors, diff --git a/deps/undici/src/package-lock.json b/deps/undici/src/package-lock.json index f2c4547fb1aa..820433c95816 100644 --- a/deps/undici/src/package-lock.json +++ b/deps/undici/src/package-lock.json @@ -1,15 +1,15 @@ { "name": "undici", - "version": "8.13.1", + "version": "8.14.0", "lockfileVersion": 3, "requires": true, "packages": { "": { "name": "undici", - "version": "8.13.1", + "version": "8.14.0", "license": "MIT", "devDependencies": { - "@fastify/busboy": "3.2.5", + "@fastify/busboy": "3.2.6", "@matteo.collina/tspl": "^0.2.0", "@metcoder95/https-pem": "^1.0.0", "@sinonjs/fake-timers": "^12.0.0", @@ -1213,9 +1213,9 @@ } }, "node_modules/@fastify/busboy": { - "version": "3.2.5", - "resolved": "https://registry.npmjs.org/@fastify/busboy/-/busboy-3.2.5.tgz", - "integrity": "sha512-y8MTAeBlEQUNVnskmZQwpseZN3EgCksQNOULlfxWY6o6VEqh01+oExMgbM7gN6YLQ8pNDYeweNPKJRt8jQm2ZQ==", + "version": "3.2.6", + "resolved": "https://registry.npmjs.org/@fastify/busboy/-/busboy-3.2.6.tgz", + "integrity": "sha512-UPXdyAMbz/gNvjS8HONpJR2TDaHM3wQKMtSRPFkoh2LTeRRtnm+ICVYKgBYkTwlPOVzDNynOd34EH8qapwfelQ==", "dev": true, "license": "MIT" }, @@ -3618,14 +3618,14 @@ } }, "node_modules/borp": { - "version": "1.0.0", - "resolved": "https://registry.npmjs.org/borp/-/borp-1.0.0.tgz", - "integrity": "sha512-ooi3bLC8hQRGfthud3BWqS1A98X7NuQqAgGgX6mn5l6Gu6aeHJ7sjpS9gQhHLx+ju026hcc0BEPLRg1obxB1gw==", + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/borp/-/borp-1.0.1.tgz", + "integrity": "sha512-MPXiMQRjgIr+VXHgygkaDklx2WJIKyRxG/WbZGAPwP9VSRam7liUveaYbw3tPhRyNdONgSg7KGPtNdE3juSJlw==", "dev": true, "license": "MIT", "dependencies": { "@reporters/github": "^1.5.4", - "c8": "^10.0.0", + "c8": "^11.0.0", "execa": "^9.3.0", "find-up": "^7.0.0", "glob": "^10.3.10", @@ -3639,9 +3639,9 @@ } }, "node_modules/borp/node_modules/c8": { - "version": "10.1.3", - "resolved": "https://registry.npmjs.org/c8/-/c8-10.1.3.tgz", - "integrity": "sha512-LvcyrOAaOnrrlMpW22n690PUvxiq4Uf9WMhQwNJ9vgagkL/ph1+D4uvjvDA5XCbykrc0sx+ay6pVi9YZ1GnhyA==", + "version": "11.0.0", + "resolved": "https://registry.npmjs.org/c8/-/c8-11.0.0.tgz", + "integrity": "sha512-e/uRViGHSVIJv7zsaDKM7VRn2390TgHXqUSvYwPHBQaU6L7E9L0n9JbdkwdYPvshDT0KymBmmlwSpms3yBaMNg==", "dev": true, "license": "ISC", "dependencies": { @@ -3652,7 +3652,7 @@ "istanbul-lib-coverage": "^3.2.0", "istanbul-lib-report": "^3.0.1", "istanbul-reports": "^3.1.6", - "test-exclude": "^7.0.1", + "test-exclude": "^8.0.0", "v8-to-istanbul": "^9.0.0", "yargs": "^17.7.2", "yargs-parser": "^21.1.1" @@ -3661,7 +3661,7 @@ "c8": "bin/c8.js" }, "engines": { - "node": ">=18" + "node": "20 || >=22" }, "peerDependencies": { "monocart-coverage-reports": "^2" @@ -3731,21 +3731,6 @@ "node": ">=8" } }, - "node_modules/borp/node_modules/test-exclude": { - "version": "7.0.2", - "resolved": "https://registry.npmjs.org/test-exclude/-/test-exclude-7.0.2.tgz", - "integrity": "sha512-u9E6A+ZDYdp7a4WnarkXPZOx8Ilz46+kby6p1yZ8zsGTz9gYa6FIS7lj2oezzNKmtdyyJNNmmXDppga5GB7kSw==", - "dev": true, - "license": "ISC", - "dependencies": { - "@istanbuljs/schema": "^0.1.2", - "glob": "^10.4.1", - "minimatch": "^10.2.2" - }, - "engines": { - "node": ">=18" - } - }, "node_modules/brace-expansion": { "version": "5.0.12", "resolved": "https://registry.npmjs.org/brace-expansion/-/brace-expansion-5.0.12.tgz", @@ -5153,9 +5138,9 @@ } }, "node_modules/fast-check": { - "version": "4.10.2", - "resolved": "https://registry.npmjs.org/fast-check/-/fast-check-4.10.2.tgz", - "integrity": "sha512-iK2f+YrcmoeGqk6fA0ea2bptcu/itMIm4NfEozq6N25+aG6h7s5HZbB/k1aV7b5w5sFLMCbbtRUsTVR+BgC3xw==", + "version": "4.10.3", + "resolved": "https://registry.npmjs.org/fast-check/-/fast-check-4.10.3.tgz", + "integrity": "sha512-SBaU6nhh+sXxb05r2IHAKfxnR/1Pu6MqtHYaewM1BY6V5xzOxOk+4yoWO7WfeeyZG1iArFE6/DO/7iLYMUuOJg==", "dev": true, "funding": [ { diff --git a/deps/undici/src/package.json b/deps/undici/src/package.json index ba9f11bd61e0..64d9987eae28 100644 --- a/deps/undici/src/package.json +++ b/deps/undici/src/package.json @@ -1,6 +1,6 @@ { "name": "undici", - "version": "8.13.1", + "version": "8.14.0", "description": "An HTTP/1.1 client, written from scratch for Node.js", "homepage": "https://undici.nodejs.org", "bugs": { @@ -111,7 +111,7 @@ "prepare": "husky && node ./scripts/platform-shell.js" }, "devDependencies": { - "@fastify/busboy": "3.2.5", + "@fastify/busboy": "3.2.6", "@matteo.collina/tspl": "^0.2.0", "@metcoder95/https-pem": "^1.0.0", "@sinonjs/fake-timers": "^12.0.0", diff --git a/deps/undici/src/types/interceptors.d.ts b/deps/undici/src/types/interceptors.d.ts index 10db9ef91a7c..a83d1315af61 100644 --- a/deps/undici/src/types/interceptors.d.ts +++ b/deps/undici/src/types/interceptors.d.ts @@ -12,6 +12,8 @@ declare namespace Interceptors { export type DecompressInterceptorOpts = { skipErrorResponses?: boolean skipStatusCodes?: number[] + /** Preserve the original response headers after decompression, including `controller.rawHeaders`. @default false */ + preserveHeaders?: boolean /** Maximum decompressed response size in bytes per stage. 0 disables the limit. @default 0 */ maxSize?: number } diff --git a/deps/undici/src/types/retry-handler.d.ts b/deps/undici/src/types/retry-handler.d.ts index ccb73c86282f..aba422abf8c1 100644 --- a/deps/undici/src/types/retry-handler.d.ts +++ b/deps/undici/src/types/retry-handler.d.ts @@ -44,6 +44,16 @@ declare namespace RetryHandler { * @default true */ throwOnError?: boolean; + /** + * If false, a response that fails after its headers were received is not + * resumed with a `Range` request: the error is passed through, and only + * failures before the response headers are retried. + * + * @type {boolean} + * @memberof RetryOptions + * @default true + */ + resume?: boolean; /** * Callback to be invoked on every retry iteration. * It receives the error, current state of the retry object and the options object diff --git a/deps/undici/undici.js b/deps/undici/undici.js index f2aca61248ba..55eaae3423b0 100644 --- a/deps/undici/undici.js +++ b/deps/undici/undici.js @@ -2305,6 +2305,10 @@ var require_util = __commonJS({ __proto__: null, enumerable: true }; + var kNonEnumerableProperty = { + __proto__: null, + enumerable: false + }; var normalizedMethodRecordsBase = { delete: "DELETE", DELETE: "DELETE", @@ -2330,6 +2334,7 @@ var require_util = __commonJS({ Object.setPrototypeOf(normalizedMethodRecords, null); module2.exports = { kEnumerableProperty, + kNonEnumerableProperty, isDisturbed, isBlobLike, parseOrigin, @@ -8079,6 +8084,7 @@ var require_client_h1 = __commonJS({ return; } this[kError] = err; + util.destroy(this); this[kClient][kOnError](err); } __name(onHttpSocketError, "onHttpSocketError"); @@ -8762,6 +8768,7 @@ var require_client_h2 = __commonJS({ HTTP2_HEADER_EXPECT, HTTP2_HEADER_STATUS, HTTP2_HEADER_PROTOCOL, + NGHTTP2_CANCEL, NGHTTP2_NO_ERROR, NGHTTP2_PROTOCOL_ERROR, NGHTTP2_REFUSED_STREAM @@ -8937,6 +8944,7 @@ var require_client_h2 = __commonJS({ session[kReceivedGoAway] = false; session[kEnableConnectProtocol] = false; session[kRemoteSettings] = false; + client[kMaxConcurrentStreams] = Math.min(client[kHTTP2Options].maxConcurrentStreams, 100); if (http2ConnectionWindowSize) { util.addListener(session, "connect", applyConnectionWindowSize.bind(session, http2ConnectionWindowSize)); } @@ -8991,8 +8999,12 @@ var require_client_h2 = __commonJS({ * @returns {boolean} */ busy(request) { - if (session[kRemoteSettings] === false && client[kRunning] > 0) { - return true; + if (session[kRemoteSettings] === false) { + if (request == null) { + if (client[kSize] > 0) return true; + } else if (client[kRunning] > 0 && (request[kRefusedStreamRetry] || !canReplayRequest(request))) { + return true; + } } if (session[kHTTP2SessionState].probeTimeout != null) { return true; @@ -9179,7 +9191,7 @@ var require_client_h2 = __commonJS({ function onHttp2RemoteSettings(settings) { const client = this[kClient]; const localMaxConcurrentStreams = client[kHTTP2Options].maxConcurrentStreams; - const remoteMaxConcurrentStreams = settings.maxConcurrentStreams ?? client[kMaxConcurrentStreams] ?? localMaxConcurrentStreams; + const remoteMaxConcurrentStreams = settings.maxConcurrentStreams ?? (this[kRemoteSettings] ? client[kMaxConcurrentStreams] : localMaxConcurrentStreams); client[kMaxConcurrentStreams] = Math.min(remoteMaxConcurrentStreams, localMaxConcurrentStreams); if (this[kRemoteSettings] === true && this[kEnableConnectProtocol] === true && settings.enableConnectProtocol === false) { const err = new InformationalError("HTTP/2: Server disabled extended CONNECT protocol against RFC-8441"); @@ -9589,7 +9601,7 @@ var require_client_h2 = __commonJS({ if (state.stream != null) { clearRequestStream(request); const stream2 = state.stream; - stream2.close(); + stream2.close(NGHTTP2_CANCEL); if (!stream2.destroyed) { util.destroy(stream2); } @@ -11381,20 +11393,31 @@ var require_socks5_utils = __commonJS({ var { Buffer: Buffer2 } = require("node:buffer"); var net = require("node:net"); var { InvalidArgumentError } = require_errors(); + function stripIPv6Brackets(address) { + if (address.length >= 2 && address.charCodeAt(0) === 91 && address.charCodeAt(address.length - 1) === 93) { + const unbracketed = address.slice(1, -1); + if (net.isIPv6(unbracketed)) { + return unbracketed; + } + } + return address; + } + __name(stripIPv6Brackets, "stripIPv6Brackets"); function parseAddress(address) { - if (net.isIPv4(address)) { - const parts = address.split(".").map(Number); + const normalizedAddress = stripIPv6Brackets(address); + if (net.isIPv4(normalizedAddress)) { + const parts = normalizedAddress.split(".").map(Number); return { type: 1, // IPv4 buffer: Buffer2.from(parts) }; } - if (net.isIPv6(address)) { + if (net.isIPv6(normalizedAddress)) { return { type: 4, // IPv6 - buffer: parseIPv6(address) + buffer: parseIPv6(normalizedAddress) }; } const domainBuffer = Buffer2.from(address, "utf8"); @@ -11410,15 +11433,15 @@ var require_socks5_utils = __commonJS({ __name(parseAddress, "parseAddress"); function parseIPv6(address) { const buffer = Buffer2.alloc(16); - let normalizedAddress = address; - if (address.includes(".")) { - const lastColonIndex = address.lastIndexOf(":"); - const ipv4Part = address.slice(lastColonIndex + 1); + let normalizedAddress = stripIPv6Brackets(address); + if (normalizedAddress.includes(".")) { + const lastColonIndex = normalizedAddress.lastIndexOf(":"); + const ipv4Part = normalizedAddress.slice(lastColonIndex + 1); if (net.isIPv4(ipv4Part)) { const octets = ipv4Part.split(".").map(Number); const high = (octets[0] << 8 | octets[1]).toString(16); const low = (octets[2] << 8 | octets[3]).toString(16); - normalizedAddress = `${address.slice(0, lastColonIndex)}:${high}:${low}`; + normalizedAddress = `${normalizedAddress.slice(0, lastColonIndex)}:${high}:${low}`; } } const doubleColonIndex = normalizedAddress.indexOf("::"); @@ -11531,6 +11554,7 @@ var require_socks5_utils = __commonJS({ } __name(createReplyError, "createReplyError"); module2.exports = { + stripIPv6Brackets, parseAddress, parseIPv6, buildAddressBuffer, @@ -11885,10 +11909,11 @@ var require_socks5_proxy_agent = __commonJS({ var DispatcherBase = require_dispatcher_base(); var { ConnectTimeoutError, InvalidArgumentError } = require_errors(); var { Socks5Client, STATES } = require_socks5_client(); + var { stripIPv6Brackets } = require_socks5_utils(); var { kBusy, kConnected, kDispatch, kClose, kDestroy } = require_symbols(); var Pool = require_pool(); var buildConnector = require_connect(); - var { setupConnectTimeout } = require_util(); + var { setupConnectTimeout, getServerName } = require_util(); var { debuglog } = require("node:util"); var debug = debuglog("undici:socks5-proxy"); var DEFAULT_SOCKS5_CONNECT_TIMEOUT = 5e3; @@ -11954,7 +11979,7 @@ var require_socks5_proxy_agent = __commonJS({ this[kConnector] = options.connect || buildConnector({ ...options.proxyTls, timeout: proxyTlsTimeout, - servername: options.proxyTls?.servername || url.hostname + servername: options.proxyTls?.servername || getServerName(url.hostname) || void 0 }); this[kPools] = /* @__PURE__ */ new Map(); } @@ -11962,7 +11987,7 @@ var require_socks5_proxy_agent = __commonJS({ * Create a SOCKS5 connection to the proxy */ async createSocks5Connection(targetHost, targetPort) { - const proxyHost = this[kProxyUrl].hostname; + const proxyHost = stripIPv6Brackets(this[kProxyUrl].hostname); const proxyPort = parseInt(this[kProxyUrl].port) || 1080; debug("creating SOCKS5 connection to", proxyHost, proxyPort); const socketReady = Promise.withResolvers(); @@ -12058,7 +12083,7 @@ var require_socks5_proxy_agent = __commonJS({ connect: /* @__PURE__ */ __name(async (connectOpts, callback) => { try { const url = new URL2(origin); - const targetHost = url.hostname; + const targetHost = stripIPv6Brackets(url.hostname); const targetPort = parseInt(url.port) || (url.protocol === "https:" ? 443 : 80); debug("establishing SOCKS5 connection to", targetHost, targetPort); const socket = await this.createSocks5Connection(targetHost, targetPort); @@ -14534,7 +14559,7 @@ var require_fetch = __commonJS({ return; } this.state = "aborted"; - if (!error) { + if (error === void 0) { error = new DOMException("The operation was aborted.", "AbortError"); } this.serializedAbortReason = error; @@ -16990,7 +17015,7 @@ var require_websocket = __commonJS({ } = require_util3(); var { establishWebSocketConnection, closeWebSocketConnection, failWebsocketConnection } = require_connection(); var { ByteParser } = require_receiver(); - var { kEnumerableProperty } = require_util(); + var { kEnumerableProperty, kNonEnumerableProperty } = require_util(); var { getGlobalDispatcher: getGlobalDispatcher2 } = require_global2(); var { ErrorEvent: ErrorEvent2, CloseEvent: CloseEvent2, createFastMessageEvent: createFastMessageEvent2 } = require_events(); var { SendQueue } = require_sender(); @@ -17107,11 +17132,13 @@ var require_websocket = __commonJS({ } // TODO: remove this [kRef]() { + webidl.brandCheck(this, webidl.is.WebSocket); this.#refed = true; this.#handler.socket?.ref?.(); } // TODO: remove this [kUnref]() { + webidl.brandCheck(this, webidl.is.WebSocket); this.#refed = false; this.#handler.socket?.unref?.(); } @@ -17399,6 +17426,8 @@ var require_websocket = __commonJS({ WebSocket.CLOSING = WebSocket.prototype.CLOSING = states.CLOSING; WebSocket.CLOSED = WebSocket.prototype.CLOSED = states.CLOSED; Object.defineProperties(WebSocket.prototype, { + [kRef]: kNonEnumerableProperty, + [kUnref]: kNonEnumerableProperty, CONNECTING: staticPropertyDescriptors, OPEN: staticPropertyDescriptors, CLOSING: staticPropertyDescriptors, @@ -18919,7 +18948,7 @@ var require_api_request = __commonJS({ if (!this.res) { return; } - if (this.res.push(chunk) === false) { + if (this.runInAsyncScope(() => this.res.push(chunk)) === false) { controller.pause(); } } diff --git a/src/undici_version.h b/src/undici_version.h index 81bfc11bb62e..d1ca15c7924a 100644 --- a/src/undici_version.h +++ b/src/undici_version.h @@ -2,5 +2,5 @@ // Refer to tools/dep_updaters/update-undici.sh #ifndef SRC_UNDICI_VERSION_H_ #define SRC_UNDICI_VERSION_H_ -#define UNDICI_VERSION "8.13.1" +#define UNDICI_VERSION "8.14.0" #endif // SRC_UNDICI_VERSION_H_