Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion deps/undici/src/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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`

Expand Down
9 changes: 8 additions & 1 deletion deps/undici/src/docs/docs/api/Client.md
Original file line number Diff line number Diff line change
Expand Up @@ -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`.
Expand Down Expand Up @@ -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'
Expand Down
2 changes: 1 addition & 1 deletion deps/undici/src/docs/docs/api/Dispatcher.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
8 changes: 6 additions & 2 deletions deps/undici/src/docs/docs/api/H2CClient.md
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand Down
10 changes: 10 additions & 0 deletions deps/undici/src/docs/docs/api/Interceptors.md
Original file line number Diff line number Diff line change
Expand Up @@ -204,13 +204,21 @@ 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)
* `skipStatusCodes` {number[]} Status codes for which decompression is
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
Expand Down Expand Up @@ -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**

Expand Down
5 changes: 5 additions & 0 deletions deps/undici/src/docs/docs/api/RetryHandler.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
2 changes: 1 addition & 1 deletion deps/undici/src/docs/docs/index.md
Original file line number Diff line number Diff line change
Expand Up @@ -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])`

Expand Down
2 changes: 1 addition & 1 deletion deps/undici/src/lib/api/api-request.js
Original file line number Diff line number Diff line change
Expand Up @@ -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()
}
}
Expand Down
41 changes: 32 additions & 9 deletions deps/undici/src/lib/core/socks5-utils.js
Original file line number Diff line number Diff line change
Expand Up @@ -4,26 +4,48 @@ 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)
}
}

// 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)
}
}

Expand All @@ -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}`
}
}

Expand Down Expand Up @@ -204,6 +226,7 @@ function createReplyError (replyCode) {
}

module.exports = {
stripIPv6Brackets,
parseAddress,
parseIPv6,
buildAddressBuffer,
Expand Down
6 changes: 6 additions & 0 deletions deps/undici/src/lib/core/util.js
Original file line number Diff line number Diff line change
Expand Up @@ -960,6 +960,11 @@ const kEnumerableProperty = {
enumerable: true
}

const kNonEnumerableProperty = {
__proto__: null,
enumerable: false
}

const normalizedMethodRecordsBase = {
delete: 'DELETE',
DELETE: 'DELETE',
Expand Down Expand Up @@ -989,6 +994,7 @@ Object.setPrototypeOf(normalizedMethodRecords, null)

module.exports = {
kEnumerableProperty,
kNonEnumerableProperty,
isDisturbed,
isBlobLike,
parseOrigin,
Expand Down
5 changes: 5 additions & 0 deletions deps/undici/src/lib/dispatcher/client-h1.js
Original file line number Diff line number Diff line change
Expand Up @@ -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)
}

Expand Down
37 changes: 32 additions & 5 deletions deps/undici/src/lib/dispatcher/client-h2.js
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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))
Expand Down Expand Up @@ -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.
Expand Down Expand Up @@ -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
Expand Down Expand Up @@ -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
Expand Down
9 changes: 5 additions & 4 deletions deps/undici/src/lib/dispatcher/socks5-proxy-agent.js
Original file line number Diff line number Diff line change
Expand Up @@ -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')
Expand Down Expand Up @@ -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
Expand All @@ -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)
Expand Down Expand Up @@ -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)
Expand Down
7 changes: 5 additions & 2 deletions deps/undici/src/lib/handler/retry-handler.js
Original file line number Diff line number Diff line change
Expand Up @@ -117,7 +117,8 @@ class RetryHandler {
errorCodes,
retryAfter,
statusCodes,
throwOnError
throwOnError,
resume
} = retryOptions ?? {}

this.error = null
Expand All @@ -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,
Expand Down Expand Up @@ -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
}
Expand Down
Loading
Loading