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
27 changes: 0 additions & 27 deletions deps/undici/src/changelogs/v7.30.2.md

This file was deleted.

32 changes: 32 additions & 0 deletions deps/undici/src/docs/docs/api/Dispatcher.md
Original file line number Diff line number Diff line change
Expand Up @@ -871,6 +871,26 @@ Arguments:

Returns: `Dispatcher`.

Because interceptors wrap each other, ordering is the end-user's responsibility.
Certain built-in interceptors are order-sensitive and will throw an
`InvalidArgumentError` if composed in an unsafe order. In particular, the
`cache` interceptor must be composed **after** the `redirect` interceptor. When
`cache` is composed before `redirect`, the cache handler is wrapped *above* the
redirect handler, so it never observes the redirect history and its
cross-origin / credential-bearing redirect guards are silently disabled.
This allows an attacker-controlled or cross-principal redirect response to be
stored under the trusted origin's cache key and replayed to unrelated callers
(see GHSA-75VM-9G8F-99J4, GHSA-MQG3-3V4R-CM32, GHSA-4W7W-5XRC-9H26 and
GHSA-7XG3-FPHP-28HG).

```js
// Correct: cache is composed after redirect.
new Agent().compose(interceptors.redirect({ maxRedirections: 5 }), interceptors.cache({}))

// Throws an InvalidArgumentError: cache composed before redirect.
new Agent().compose(interceptors.cache({}), interceptors.redirect({ maxRedirections: 5 }))
```

#### Parameter: `Interceptor`

A function that takes a `dispatch` method and returns a `dispatch`-like function.
Expand Down Expand Up @@ -1215,6 +1235,18 @@ The `cache` interceptor implements client-side response caching as described in
- `cacheByDefault` - The default expiration time to cache responses by if they don't have an explicit expiration and cannot have an heuristic expiry computed. If this isn't present, responses neither with an explicit expiration nor heuristically cacheable will not be cached. Default `undefined`.
- `type` - The [type of cache](https://developer.mozilla.org/en-US/docs/Web/HTTP/Guides/Caching#types_of_caches) for Undici to act as. Can be `shared` or `private`. Default `shared`. `private` implies privately cacheable responses will be cached and potentially shared with other users of your application.

> **Ordering:** the `cache` interceptor must be composed **after** the
> `redirect` interceptor. When `cache` is composed before `redirect`, the cache
> handler is wrapped above the redirect handler, so it never observes the
> redirect history and its cross-origin / credential-bearing redirect guards are
> silently disabled, which lets an attacker-controlled or cross-principal
> redirect response be stored under the trusted origin's cache key and replayed
> to unrelated callers (GHSA-75VM-9G8F-99J4, GHSA-MQG3-3V4R-CM32,
> GHSA-4W7W-5XRC-9H26, GHSA-7XG3-FPHP-28HG). `compose()` throws an
> `InvalidArgumentError` for this unsafe order. The `deduplicate` interceptor
> participates in the same redirect-history contract and may be placed before or
> after `redirect`, as long as `cache` follows `redirect`.

**Usage with `fetch`**

```js
Expand Down
9 changes: 9 additions & 0 deletions deps/undici/src/docs/docs/api/EnvHttpProxyAgent.md
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,15 @@ Extends: [`AgentOptions`](/docs/docs/api/Agent.md#parameter-agentoptions)
* **httpsProxy** `string` (optional) - When set, it will override the `HTTPS_PROXY` environment variable.
* **noProxy** `string` (optional) - When set, it will override the `NO_PROXY` environment variable.

The TLS options for the connection to the target server, given as `requestTls`
or as a `connect` object, apply on every route: direct (no proxy configured),
hosts matching `noProxy`, and proxied through an HTTP, HTTPS, or SOCKS5 proxy.
When both are set they are merged key by key, and keys set in `connect` take
precedence over `requestTls` on every route. `proxyTls` applies only to the connection to the
proxy server, and the target TLS options are never applied to it. When `connect`
is a function it is used as-is on direct routes, where `requestTls` is then not
applied, and it is not used on proxied routes.

Examples:

```js
Expand Down
1 change: 1 addition & 0 deletions deps/undici/src/docs/docs/api/Errors.md
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,7 @@ import { errors } from 'undici'
| `InformationalError` | `UND_ERR_INFO` | expected error with reason |
| `ResponseExceededMaxSizeError` | `UND_ERR_RES_EXCEEDED_MAX_SIZE` | response body exceed the max size allowed |
| `SecureProxyConnectionError` | `UND_ERR_PRX_TLS` | tls connection to a proxy failed |
| `ProxyConnectionError` | `UND_ERR_PRX_CONN` | establishing the proxy `CONNECT` tunnel failed |
| `MessageSizeExceededError` | `UND_ERR_WS_MESSAGE_SIZE_EXCEEDED` | WebSocket decompressed message exceeded the maximum allowed size |

Be aware of the possible difference between the global dispatcher version and the actual undici version you might be using. We recommend to avoid the check `instanceof errors.UndiciError` and seek for the `error.code === '<error_code>'` instead to avoid inconsistencies.
Expand Down
11 changes: 9 additions & 2 deletions deps/undici/src/lib/api/api-stream.js
Original file line number Diff line number Diff line change
Expand Up @@ -56,6 +56,9 @@ class StreamHandler extends AsyncResource {
this.trailers = null
this.body = body
this.onInfo = onInfo || null
// Set once the factory's writable is tracked: from then on its lifecycle
// owns the callback, which must not be invoked from onError.
this.responseStarted = false

if (util.isStream(body)) {
body.on('error', (err) => {
Expand Down Expand Up @@ -122,13 +125,17 @@ class StreamHandler extends AsyncResource {
}

this.callback = null
this.runInAsyncScope(callback, null, err || null, { opaque, trailers })
if (callback) {
this.runInAsyncScope(callback, null, err || null, { opaque, trailers })
}

if (err) {
abort()
}
})

this.responseStarted = true

res.on('drain', resume)

this.res = res
Expand Down Expand Up @@ -170,7 +177,7 @@ class StreamHandler extends AsyncResource {
if (res) {
this.res = null
util.destroy(res, err)
} else if (callback) {
} else if (callback && !this.responseStarted) {
this.callback = null
queueMicrotask(() => {
this.runInAsyncScope(callback, null, err, { opaque })
Expand Down
2 changes: 1 addition & 1 deletion deps/undici/src/lib/api/readable.js
Original file line number Diff line number Diff line change
Expand Up @@ -88,7 +88,7 @@ class BodyReadable extends Readable {
}

if (err) {
this[kAbort]()
this[kAbort](err)
}

// Workaround for Node "bug". If the stream is destroyed in same
Expand Down
7 changes: 5 additions & 2 deletions deps/undici/src/lib/cache/memory-cache-store.js
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@

const { Writable } = require('node:stream')
const { EventEmitter } = require('node:events')
const { assertCacheKey, assertCacheValue } = require('../util/cache.js')
const { assertCacheKey, assertCacheValue, createBodyChunkCoalescer } = require('../util/cache.js')

/**
* @typedef {import('../../types/cache-interceptor.d.ts').default.CacheKey} CacheKey
Expand Down Expand Up @@ -129,6 +129,7 @@ class MemoryCacheStore extends EventEmitter {

const store = this
const entry = { ...key, ...val, body: [], size: 0 }
const coalescer = createBodyChunkCoalescer(entry.body)

return new Writable({
write (chunk, encoding, callback) {
Expand All @@ -141,12 +142,14 @@ class MemoryCacheStore extends EventEmitter {
if (entry.size >= store.#maxEntrySize) {
this.destroy()
} else {
entry.body.push(chunk)
coalescer.push(chunk)
}

callback(null)
},
final (callback) {
coalescer.flush()

let entries = store.#entries.get(topLevelKey)
if (!entries) {
entries = []
Expand Down
6 changes: 4 additions & 2 deletions deps/undici/src/lib/cache/sqlite-cache-store.js
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
'use strict'

const { Writable } = require('node:stream')
const { assertCacheKey, assertCacheValue } = require('../util/cache.js')
const { assertCacheKey, assertCacheValue, createBodyChunkCoalescer } = require('../util/cache.js')

let DatabaseSync

Expand Down Expand Up @@ -318,6 +318,7 @@ module.exports = class SqliteCacheStore {
* @type {Buffer[] | null}
*/
const body = []
const coalescer = createBodyChunkCoalescer(body)
const store = this

return new Writable({
Expand All @@ -326,14 +327,15 @@ module.exports = class SqliteCacheStore {
size += chunk.byteLength

if (size < store.#maxEntrySize) {
body.push(chunk)
coalescer.push(chunk)
} else {
this.destroy()
}

callback()
},
final (callback) {
coalescer.flush()
store.set(key, { ...value, body })
callback()
}
Expand Down
20 changes: 20 additions & 0 deletions deps/undici/src/lib/core/errors.js
Original file line number Diff line number Diff line change
Expand Up @@ -403,6 +403,25 @@ class SecureProxyConnectionError extends UndiciError {
}
}

const kProxyConnectionError = Symbol.for('undici.error.UND_ERR_PRX_CONN')
class ProxyConnectionError extends UndiciError {
constructor (cause, message, options = {}) {
super(message, { cause, ...options })
this.name = 'ProxyConnectionError'
this.message = message || 'Proxy Connection failed'
this.code = 'UND_ERR_PRX_CONN'
this.cause = cause
}

static [Symbol.hasInstance] (instance) {
return instance && instance[kProxyConnectionError] === true
}

get [kProxyConnectionError] () {
return true
}
}

const kMaxOriginsReachedError = Symbol.for('undici.error.UND_ERR_MAX_ORIGINS_REACHED')
class MaxOriginsReachedError extends UndiciError {
constructor (message) {
Expand Down Expand Up @@ -471,6 +490,7 @@ module.exports = {
RequestRetryError,
ResponseError,
SecureProxyConnectionError,
ProxyConnectionError,
MaxOriginsReachedError,
Socks5ProxyError,
MessageSizeExceededError
Expand Down
3 changes: 2 additions & 1 deletion deps/undici/src/lib/core/symbols.js
Original file line number Diff line number Diff line change
Expand Up @@ -72,5 +72,6 @@ module.exports = {
kNoProxyAgent: Symbol('no proxy agent'),
kHttpProxyAgent: Symbol('http proxy agent'),
kHttpsProxyAgent: Symbol('https proxy agent'),
kSocks5ProxyAgent: Symbol('socks5 proxy agent')
kSocks5ProxyAgent: Symbol('socks5 proxy agent'),
kInterceptorKind: Symbol('interceptor kind')
}
24 changes: 23 additions & 1 deletion deps/undici/src/lib/dispatcher/client-h1.js
Original file line number Diff line number Diff line change
Expand Up @@ -372,10 +372,32 @@ class Parser {
finish () {
assert(currentParser === null)
assert(this.ptr != null)
assert(!this.paused)

const { llhttp } = this

// The peer closed the connection. If the body parser was paused by
// backpressure we must finish parsing before signalling EOF, otherwise
// llhttp_finish() would crash (it used to assert !paused) or report a
// half-parsed message. Backpressure is advisory here: onData keeps buffering
// delivered bytes into the response stream, so resume across pauses and
// drain whatever is still buffered on the socket. A Content-Length/chunked
// body reaches on_message_complete during execute(); an EOF-delimited body
// stays paused (its length is unknown) and is completed by llhttp_finish().
if (this.paused) {
let data
do {
llhttp.llhttp_resume(this.ptr)
this.paused = false
data = this.socket.read() || EMPTY_BUF
this.execute(data)
} while (this.paused && data.length > 0)

if (this.paused) {
llhttp.llhttp_resume(this.ptr)
this.paused = false
}
}

let ret

try {
Expand Down
49 changes: 49 additions & 0 deletions deps/undici/src/lib/dispatcher/client-h2.js
Original file line number Diff line number Diff line change
Expand Up @@ -44,6 +44,11 @@ const {
const { channels } = require('../core/diagnostics.js')

const kOpenStreams = Symbol('open streams')
const kHeldReplayAttempts = Symbol('held replay attempts')

// How many times a request held without a stream may be replayed after the
// connection holding it goes away (see refuseHeldRequests).
const MAX_HELD_REPLAY_ATTEMPTS = 1

let extractBody

Expand Down Expand Up @@ -349,6 +354,44 @@ function completeRequest (client, request, resetPendingIdx = false) {
}
}

// Count a connection that went away while holding the request against its
// replay budget. A peer that refuses every connection must eventually surface
// an error to the caller rather than being retried forever.
function registerHeldRefusal (request) {
const attempts = (request[kHeldReplayAttempts] ?? 0) + 1
request[kHeldReplayAttempts] = attempts

return attempts <= MAX_HELD_REPLAY_ATTEMPTS
}

// Requests the session held back without opening a stream: a CONNECT or an
// extended CONNECT (WebSocket) waits for the peer's SETTINGS. No stream means
// no stream timeout ever applies to them. A connection that goes away in that
// state refused all of them, so count it against their replay budget.
// Otherwise a peer that keeps doing so turns one request into an unbounded
// reconnect loop.
function refuseHeldRequests (client, err) {
const queue = client[kQueue]
const failed = []
let j = client[kPendingIdx]

for (let i = client[kPendingIdx]; i < queue.length; i++) {
const request = queue[i]

if (request != null && !registerHeldRefusal(request)) {
failed.push(request)
} else {
queue[j++] = request
}
}

queue.length = j

for (let i = 0; i < failed.length; i++) {
util.errorRequest(client, failed[i], err)
}
}

function onHttp2SessionGoAway (errorCode) {
// TODO(mcollina): Verify if GOAWAY implements the spec correctly:
// https://datatracker.ietf.org/doc/html/rfc7540#section-6.8
Expand Down Expand Up @@ -424,10 +467,16 @@ function onHttp2SocketClose () {
this[kHTTP2Session].destroy(err)
}

const held = client[kRunning] === 0

client[kPendingIdx] = client[kRunningIdx]

assert(client[kRunning] === 0)

if (held) {
refuseHeldRequests(client, err)
}

client.emit('disconnect', client[kUrl], [client], err)

client[kResume]()
Expand Down
5 changes: 5 additions & 0 deletions deps/undici/src/lib/dispatcher/client.js
Original file line number Diff line number Diff line change
Expand Up @@ -629,6 +629,11 @@ function _resume (client, sync) {
return
}

if (request.aborted) {
client[kQueue].splice(client[kPendingIdx], 1)
continue
}

if (client[kUrl].protocol === 'https:' && client[kServerName] !== request.servername) {
if (client[kRunning] > 0) {
return
Expand Down
Loading
Loading