deps: update undici to 7.24.3

PR-URL: https://github.com/nodejs/node/pull/62233
Reviewed-By: Antoine du Hamel <duhamelantoine1995@gmail.com>
Reviewed-By: Matthew Aitken <maitken033380023@gmail.com>
Reviewed-By: Trivikram Kamat <trivikr.dev@gmail.com>
Reviewed-By: Matteo Collina <matteo.collina@gmail.com>
Reviewed-By: Colin Ihrig <cjihrig@gmail.com>
This commit is contained in:
Node.js GitHub Bot authored and GitHub committed 2026-03-15 23:59:22 +00:00
1 parent 1bc0fdd922
commit 4579957ee9
46 files changed
+3540 -796

No files matched your search

+6
View File
@@ -92,3 +92,9 @@ test/request-timeout.10mb.bin
# Claude files
CLAUDE.md
.claude
# Ignore .pi
.pi
# Ignore .githuman
.githuman
+2 -2
View File
@@ -103,7 +103,7 @@ const response = await fetch('https://api.example.com/data');
- Superior performance, especially with `undici.request`
- HTTP/1.1 pipelining support
- Custom interceptors and middleware
- Advanced features like `ProxyAgent`, `MockAgent`
- Advanced features like `ProxyAgent`, `Socks5Agent`, `MockAgent`
**Cons:**
- Additional dependency to manage
@@ -122,7 +122,7 @@ const response = await fetch('https://api.example.com/data');
#### Use Undici Module When:
- You need the latest undici features and performance improvements
- You require advanced connection pooling configuration
- You need APIs not available in the built-in fetch (`ProxyAgent`, `MockAgent`, etc.)
- You need APIs not available in the built-in fetch (`ProxyAgent`, `Socks5Agent`, `MockAgent`, etc.)
- Performance is critical (use `undici.request` for maximum speed)
- You want better error handling and debugging capabilities
- You need HTTP/1.1 pipelining or advanced interceptors
+36 -9
View File
@@ -207,7 +207,7 @@ Returns: `Boolean` - `false` if dispatcher is busy and further dispatch calls wo
* **onRequestStart** `(controller: DispatchController, context: object) => void` - Invoked before request is dispatched on socket. May be invoked multiple times when a request is retried when the request at the head of the pipeline fails.
* **onRequestUpgrade** `(controller: DispatchController, statusCode: number, headers: Record<string, string | string[]>, socket: Duplex) => void` (optional) - Invoked when request is upgraded. Required if `DispatchOptions.upgrade` is defined or `DispatchOptions.method === 'CONNECT'`.
* **onResponseStart** `(controller: DispatchController, statusCode: number, headers: Record<string, string | string []>, statusMessage?: string) => void` - Invoked when statusCode and headers have been received. May be invoked multiple times due to 1xx informational headers. Not required for `upgrade` requests.
* **onResponseStart** `(controller: DispatchController, statusCode: number, headers: Record<string, string | string []>, statusMessage?: string) => void` - Invoked when statusCode and headers have been received. May be invoked multiple times due to 1xx informational headers. Not required for `upgrade` requests. Any return value is ignored.
* **onResponseData** `(controller: DispatchController, chunk: Buffer) => void` - Invoked when response payload data is received. Not required for `upgrade` requests.
* **onResponseEnd** `(controller: DispatchController, trailers: Record<string, string | string[]>) => void` - Invoked when response payload and trailers have been received and the request has completed. Not required for `upgrade` requests.
* **onResponseError** `(controller: DispatchController, error: Error) => void` - Invoked when an error has occurred. May not throw.
@@ -962,7 +962,7 @@ It accepts the same arguments as the [`RedirectHandler` constructor](/docs/docs/
const { Client, interceptors } = require("undici");
const { redirect } = interceptors;
const client = new Client("http://example.com").compose(
const client = new Client("http://service.example").compose(
redirect({ maxRedirections: 3, throwOnMaxRedirects: true })
);
client.request({ path: "/" })
@@ -980,7 +980,7 @@ It accepts the same arguments as the [`RetryHandler` constructor](/docs/docs/api
const { Client, interceptors } = require("undici");
const { retry } = interceptors;
const client = new Client("http://example.com").compose(
const client = new Client("http://service.example").compose(
retry({
maxRetries: 3,
minTimeout: 1000,
@@ -1006,7 +1006,7 @@ The `dump` interceptor enables you to dump the response body from a request upon
const { Client, interceptors } = require("undici");
const { dump } = interceptors;
const client = new Client("http://example.com").compose(
const client = new Client("http://service.example").compose(
dump({
maxSize: 1024,
})
@@ -1132,7 +1132,7 @@ The `responseError` interceptor throws an error for responses with status code e
const { Client, interceptors } = require("undici");
const { responseError } = interceptors;
const client = new Client("http://example.com").compose(
const client = new Client("http://service.example").compose(
responseError()
);
@@ -1160,7 +1160,7 @@ The `decompress` interceptor automatically decompresses response bodies that are
const { Client, interceptors } = require("undici");
const { decompress } = interceptors;
const client = new Client("http://example.com").compose(
const client = new Client("http://service.example").compose(
decompress()
);
@@ -1177,7 +1177,7 @@ const response = await client.request({
const { Client, interceptors } = require("undici");
const { decompress } = interceptors;
const client = new Client("http://example.com").compose(
const client = new Client("http://service.example").compose(
decompress({
skipErrorResponses: false, // Decompress 5xx responses
skipStatusCodes: [204, 304, 201] // Skip these status codes
@@ -1214,6 +1214,28 @@ 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.
**Usage with `fetch`**
```js
const { Agent, cacheStores, interceptors, setGlobalDispatcher } = require('undici')
const client = new Agent().compose(interceptors.cache({
store: new cacheStores.MemoryCacheStore({
maxSize: 100 * 1024 * 1024, // 100MB
maxCount: 1000,
maxEntrySize: 5 * 1024 * 1024 // 5MB
})
}))
setGlobalDispatcher(client)
// First request goes to the network and is cached when cache headers allow it.
const first = await fetch('https://example.com/data')
// Second request can be served from cache according to RFC9111 rules.
const second = await fetch('https://example.com/data')
```
##### `Deduplicate Interceptor`
The `deduplicate` interceptor deduplicates concurrent identical requests. When multiple identical requests are made while one is already in-flight, only one request is sent to the origin server, and all waiting handlers receive the same response. This reduces server load and improves performance.
@@ -1223,6 +1245,7 @@ The `deduplicate` interceptor deduplicates concurrent identical requests. When m
- `methods` - The [**safe** HTTP methods](https://www.rfc-editor.org/rfc/rfc9110#section-9.2.1) to deduplicate. Default `['GET']`.
- `skipHeaderNames` - Header names that, if present in a request, will cause the request to skip deduplication entirely. Useful for headers like `idempotency-key` where presence indicates unique processing. Header name matching is case-insensitive. Default `[]`.
- `excludeHeaderNames` - Header names to exclude from the deduplication key. Requests with different values for these headers will still be deduplicated together. Useful for headers like `x-request-id` that vary per request but shouldn't affect deduplication. Header name matching is case-insensitive. Default `[]`.
- `maxBufferSize` - Maximum bytes buffered per paused waiting deduplicated handler. If a waiting handler remains paused and exceeds this threshold, it is failed with an abort error to prevent unbounded memory growth. Default `5 * 1024 * 1024`.
**Usage**
@@ -1231,12 +1254,12 @@ const { Client, interceptors } = require("undici");
const { deduplicate, cache } = interceptors;
// Deduplicate only
const client = new Client("http://example.com").compose(
const client = new Client("http://service.example").compose(
deduplicate()
);
// Deduplicate with caching
const clientWithCache = new Client("http://example.com").compose(
const clientWithCache = new Client("http://service.example").compose(
deduplicate(),
cache()
);
@@ -1304,6 +1327,10 @@ Header arguments such as `options.headers` in [`Client.dispatch`](/docs/docs/api
* As an iterable that can encompass `Headers`, `Map`, or a custom iterator returning key-value pairs.
Keys are lowercase and values are not modified.
Undici validates header syntax at the protocol level (for example, invalid header names and invalid control characters in string values), but it does not sanitize untrusted application input. Validate and sanitize any user-provided header names and values before passing them to Undici to prevent header/body injection vulnerabilities.
When using the array header format (`string[]`), Undici processes only indexed elements. Additional properties assigned to the array object are ignored.
Response headers will derive a `host` from the `url` of the [Client](/docs/docs/api/Client.md#class-client) instance if no `host` header was previously specified.
### Example 1 - Object
+1
View File
@@ -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 |
| `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.
### `SocketError`
+274
View File
@@ -0,0 +1,274 @@
# Class: Socks5ProxyAgent
Extends: `undici.Dispatcher`
A SOCKS5 proxy wrapper class that implements the Dispatcher API. It enables HTTP requests to be routed through a SOCKS5 proxy server, providing connection tunneling and authentication support.
## `new Socks5ProxyAgent(proxyUrl[, options])`
Arguments:
* **proxyUrl** `string | URL` (required) - The SOCKS5 proxy server URL. Must use `socks5://` or `socks://` protocol.
* **options** `Socks5ProxyAgent.Options` (optional) - Additional configuration options.
Returns: `Socks5ProxyAgent`
### Parameter: `Socks5ProxyAgent.Options`
Extends: [`PoolOptions`](/docs/docs/api/Pool.md#parameter-pooloptions)
* **headers** `IncomingHttpHeaders` (optional) - Additional headers to send with proxy connections.
* **username** `string` (optional) - SOCKS5 proxy username for authentication. Can also be provided in the proxy URL.
* **password** `string` (optional) - SOCKS5 proxy password for authentication. Can also be provided in the proxy URL.
* **connect** `Function` (optional) - Custom connector function for the proxy connection.
* **proxyTls** `BuildOptions` (optional) - TLS options for the proxy connection (when using SOCKS5 over TLS).
Examples:
```js
import { Socks5ProxyAgent } from 'undici'
const socks5Proxy = new Socks5ProxyAgent('socks5://localhost:1080')
// or with authentication
const socks5ProxyWithAuth = new Socks5ProxyAgent('socks5://user:pass@localhost:1080')
// or with options
const socks5ProxyWithOptions = new Socks5ProxyAgent('socks5://localhost:1080', {
username: 'user',
password: 'pass',
connections: 10
})
```
#### Example - Basic SOCKS5 Proxy instantiation
This will instantiate the Socks5ProxyAgent. It will not do anything until registered as the dispatcher to use with requests.
```js
import { Socks5ProxyAgent } from 'undici'
const socks5Proxy = new Socks5ProxyAgent('socks5://localhost:1080')
```
#### Example - Basic SOCKS5 Proxy Request with global dispatcher
```js
import { setGlobalDispatcher, request, Socks5ProxyAgent } from 'undici'
const socks5Proxy = new Socks5ProxyAgent('socks5://localhost:1080')
setGlobalDispatcher(socks5Proxy)
const { statusCode, body } = await request('http://localhost:3000/foo')
console.log('response received', statusCode) // response received 200
for await (const data of body) {
console.log('data', data.toString('utf8')) // data foo
}
```
#### Example - Basic SOCKS5 Proxy Request with local dispatcher
```js
import { Socks5ProxyAgent, request } from 'undici'
const socks5Proxy = new Socks5ProxyAgent('socks5://localhost:1080')
const {
statusCode,
body
} = await request('http://localhost:3000/foo', { dispatcher: socks5Proxy })
console.log('response received', statusCode) // response received 200
for await (const data of body) {
console.log('data', data.toString('utf8')) // data foo
}
```
#### Example - SOCKS5 Proxy Request with authentication
```js
import { setGlobalDispatcher, request, Socks5ProxyAgent } from 'undici'
// Authentication via URL
const socks5Proxy = new Socks5ProxyAgent('socks5://username:password@localhost:1080')
// Or authentication via options
// const socks5Proxy = new Socks5ProxyAgent('socks5://localhost:1080', {
// username: 'username',
// password: 'password'
// })
setGlobalDispatcher(socks5Proxy)
const { statusCode, body } = await request('http://localhost:3000/foo')
console.log('response received', statusCode) // response received 200
for await (const data of body) {
console.log('data', data.toString('utf8')) // data foo
}
```
#### Example - SOCKS5 Proxy with HTTPS requests
SOCKS5 proxy supports both HTTP and HTTPS requests through tunneling:
```js
import { Socks5ProxyAgent, request } from 'undici'
const socks5Proxy = new Socks5ProxyAgent('socks5://localhost:1080')
const response = await request('https://api.example.com/data', {
dispatcher: socks5Proxy,
method: 'GET'
})
console.log('Response status:', response.statusCode)
console.log('Response data:', await response.body.json())
```
#### Example - SOCKS5 Proxy with Fetch
```js
import { Socks5ProxyAgent, fetch } from 'undici'
const socks5Proxy = new Socks5ProxyAgent('socks5://localhost:1080')
const response = await fetch('http://localhost:3000/api/users', {
dispatcher: socks5Proxy,
method: 'GET'
})
console.log('Response status:', response.status)
console.log('Response data:', await response.text())
```
#### Example - Connection Pooling
SOCKS5ProxyWrapper automatically manages connection pooling for better performance:
```js
import { Socks5ProxyAgent, request } from 'undici'
const socks5Proxy = new Socks5ProxyAgent('socks5://localhost:1080', {
connections: 10, // Allow up to 10 concurrent connections
pipelining: 1 // Enable HTTP/1.1 pipelining
})
// Multiple requests will reuse connections through the SOCKS5 tunnel
const responses = await Promise.all([
request('http://api.example.com/endpoint1', { dispatcher: socks5Proxy }),
request('http://api.example.com/endpoint2', { dispatcher: socks5Proxy }),
request('http://api.example.com/endpoint3', { dispatcher: socks5Proxy })
])
console.log('All requests completed through the same SOCKS5 proxy')
```
### `Socks5ProxyAgent.close()`
Closes the SOCKS5 proxy wrapper and waits for all underlying pools and connections to close before resolving.
Returns: `Promise<void>`
#### Example - clean up after tests are complete
```js
import { Socks5ProxyAgent, setGlobalDispatcher } from 'undici'
const socks5Proxy = new Socks5ProxyAgent('socks5://localhost:1080')
setGlobalDispatcher(socks5Proxy)
// ... make requests
await socks5Proxy.close()
```
### `Socks5ProxyAgent.destroy([err])`
Destroys the SOCKS5 proxy wrapper and all underlying connections immediately.
Arguments:
* **err** `Error` (optional) - The error that caused the destruction.
Returns: `Promise<void>`
#### Example - force close all connections
```js
import { Socks5ProxyAgent } from 'undici'
const socks5Proxy = new Socks5ProxyAgent('socks5://localhost:1080')
// Force close all connections
await socks5Proxy.destroy()
```
### `Socks5ProxyAgent.dispatch(options, handlers)`
Implements [`Dispatcher.dispatch(options, handlers)`](/docs/docs/api/Dispatcher.md#dispatcherdispatchoptions-handlers).
### `Socks5ProxyAgent.request(options[, callback])`
See [`Dispatcher.request(options [, callback])`](/docs/docs/api/Dispatcher.md#dispatcherrequestoptions-callback).
## Debugging
SOCKS5 proxy connections can be debugged using Node.js diagnostics:
```sh
NODE_DEBUG=undici:socks5 node script.js
```
This will output detailed information about the SOCKS5 handshake, authentication, and connection establishment.
## SOCKS5 Protocol Support
The Socks5ProxyAgent supports the following SOCKS5 features:
### Authentication Methods
- **No Authentication** (`0x00`) - For public or internal proxies
- **Username/Password** (`0x02`) - RFC 1929 authentication
### Address Types
- **IPv4** (`0x01`) - Standard IPv4 addresses
- **Domain Name** (`0x03`) - Domain names (recommended for flexibility)
- **IPv6** (`0x04`) - IPv6 addresses (full support for standard and compressed notation)
### Commands
- **CONNECT** (`0x01`) - Establish TCP connection (primary use case for HTTP)
### Error Handling
The wrapper handles various SOCKS5 error conditions:
- Connection refused by proxy
- Authentication failures
- Network unreachable
- Host unreachable
- Unsupported address types or commands
## Performance Considerations
- **Connection Pooling**: Automatically pools connections through the SOCKS5 tunnel for better performance
- **HTTP/1.1 Pipelining**: Supports pipelining when enabled
- **DNS Resolution**: Domain names are resolved by the SOCKS5 proxy, reducing local DNS queries
- **TLS Termination**: HTTPS connections are encrypted end-to-end, with the SOCKS5 proxy only handling the TCP tunnel
## Security Notes
1. **Authentication**: Credentials are sent to the SOCKS5 proxy in plaintext unless using SOCKS5 over TLS
2. **DNS Leaks**: All DNS resolution happens on the proxy server, preventing DNS leaks
3. **End-to-end Encryption**: HTTPS traffic remains encrypted between client and final destination
4. **Connection Security**: Consider using authenticated proxies and secure networks
## Compatibility
- **Protocol**: SOCKS5 (RFC 1928) with Username/Password Authentication (RFC 1929)
- **Transport**: TCP only (UDP support not implemented)
- **Node.js**: Compatible with all supported Node.js versions
- **HTTP Versions**: Works with HTTP/1.1 and HTTP/2 over the tunnel
+8
View File
@@ -11,6 +11,14 @@ Arguments:
* **url** `URL | string`
* **protocol** `string | string[] | WebSocketInit` (optional) - Subprotocol(s) to request the server use, or a [`Dispatcher`](/docs/docs/api/Dispatcher.md).
### WebSocketInit
When passing an object as the second argument, the following options are available:
* **protocols** `string | string[]` (optional) - Subprotocol(s) to request the server use.
* **dispatcher** `Dispatcher` (optional) - A custom [`Dispatcher`](/docs/docs/api/Dispatcher.md) to use for the connection.
* **headers** `HeadersInit` (optional) - Custom headers to include in the WebSocket handshake request.
### Example:
This example will not work in browsers or other platforms that don't allow passing an object.
@@ -0,0 +1,137 @@
# Undici Module vs. Node.js Built-in Fetch
Node.js has shipped a built-in `fetch()` implementation powered by undici since
Node.js v18. This guide explains the relationship between the `undici` npm
package and the built-in `fetch`, and when you should install one versus relying
on the other.
## Background
The `fetch()`, `Request`, `Response`, `Headers`, and `FormData` globals in
Node.js v18+ are provided by a version of undici that is bundled into Node.js
itself. You can check which version is bundled with:
```js
console.log(process.versions.undici); // e.g., "7.5.0"
```
When you install undici from npm, you get the full library with all of its
additional APIs, and potentially a newer release than what your Node.js version
bundles.
## When you do NOT need to install undici
If all of the following are true, you can rely on the built-in globals and skip
adding undici to your dependencies:
- You only need the standard Fetch API (`fetch`, `Request`, `Response`,
`Headers`, `FormData`).
- You are running Node.js v18 or later.
- You do not depend on features or bug fixes introduced in a version of undici
newer than the one bundled with your Node.js release.
- You want zero additional runtime dependencies.
- You want cross-platform interoperability with browsers and other runtimes
(Deno, Bun, Cloudflare Workers, etc.) using the same Fetch API surface.
This is common in applications that make straightforward HTTP requests or in
libraries that target multiple JavaScript runtimes.
## When you SHOULD install undici
Install undici from npm when you need capabilities beyond the standard Fetch API:
### Advanced HTTP APIs
undici exposes `request`, `stream`, `pipeline`, and `connect` methods that
provide lower-level control and significantly better performance than `fetch`:
```js
import { request } from 'undici';
const { statusCode, headers, body } = await request('https://example.com');
const data = await body.json();
```
### Connection pooling and dispatchers
`Client`, `Pool`, `BalancedPool`, `Agent`, and their configuration options
let you manage connection lifecycle, keep-alive behavior, pipelining depth,
and concurrency limits:
```js
import { Pool } from 'undici';
const pool = new Pool('https://example.com', { connections: 10 });
const { body } = await pool.request({ path: '/', method: 'GET' });
```
### Proxy support
`ProxyAgent` and `EnvHttpProxyAgent` handle HTTP(S) proxying. Note that
Node.js v22.21.0+ and v24.0.0+ support environment-variable-based proxy
configuration for the built-in `fetch` via the `--use-env-proxy` flag (or
`NODE_USE_ENV_PROXY=1`). However, undici's `ProxyAgent` still provides
programmatic control through the dispatcher API:
```js
import { ProxyAgent, fetch } from 'undici';
const proxyAgent = new ProxyAgent('https://my-proxy.example.com:8080');
const response = await fetch('https://example.com', { dispatcher: proxyAgent });
```
### Testing and mocking
`MockAgent`, `MockClient`, and `MockPool` let you intercept and mock HTTP
requests without patching globals or depending on external libraries:
```js
import { MockAgent, setGlobalDispatcher, fetch } from 'undici';
const mockAgent = new MockAgent();
setGlobalDispatcher(mockAgent);
const pool = mockAgent.get('https://example.com');
pool.intercept({ path: '/api' }).reply(200, { message: 'mocked' });
```
### Interceptors and middleware
Custom dispatchers and interceptors (retry, redirect, cache, DNS) give you
fine-grained control over how requests are processed.
### Newer version than what Node.js bundles
The npm package often includes features, performance improvements, and bug fixes
that have not yet landed in a Node.js release. If you need a specific fix or
feature, you can install a newer version directly.
## Version compatibility
| Node.js version | Bundled undici version | Notes |
|---|---|---|
| v18.x | ~5.x | `fetch` is experimental (behind `--experimental-fetch` in early v18) |
| v20.x | ~6.x | `fetch` is stable |
| v22.x | ~6.x / ~7.x | `fetch` is stable |
| v24.x | ~7.x | `fetch` is stable; env-proxy support via `--use-env-proxy` |
You can always check the exact bundled version at runtime with
`process.versions.undici`.
Installing undici from npm does not replace the built-in globals. If you want
your installed version to override the global `fetch`, use
[`setGlobalDispatcher`](/docs/api/GlobalInstallation.md) or import `fetch`
directly from `'undici'`:
```js
import { fetch } from 'undici'; // uses your installed version, not the built-in
```
## Further reading
- [API Reference: Fetch](/docs/api/Fetch.md)
- [API Reference: Client](/docs/api/Client.md)
- [API Reference: Pool](/docs/api/Pool.md)
- [API Reference: ProxyAgent](/docs/api/ProxyAgent.md)
- [API Reference: MockAgent](/docs/api/MockAgent.md)
- [API Reference: Global Installation](/docs/api/GlobalInstallation.md)
+2
View File
@@ -7,6 +7,7 @@ const BalancedPool = require('./lib/dispatcher/balanced-pool')
const RoundRobinPool = require('./lib/dispatcher/round-robin-pool')
const Agent = require('./lib/dispatcher/agent')
const ProxyAgent = require('./lib/dispatcher/proxy-agent')
const Socks5ProxyAgent = require('./lib/dispatcher/socks5-proxy-agent')
const EnvHttpProxyAgent = require('./lib/dispatcher/env-http-proxy-agent')
const RetryAgent = require('./lib/dispatcher/retry-agent')
const H2CClient = require('./lib/dispatcher/h2c-client')
@@ -35,6 +36,7 @@ module.exports.BalancedPool = BalancedPool
module.exports.RoundRobinPool = RoundRobinPool
module.exports.Agent = Agent
module.exports.ProxyAgent = ProxyAgent
module.exports.Socks5ProxyAgent = Socks5ProxyAgent
module.exports.EnvHttpProxyAgent = EnvHttpProxyAgent
module.exports.RetryAgent = RetryAgent
module.exports.H2CClient = H2CClient
+30 -1
View File
@@ -421,6 +421,33 @@ class MaxOriginsReachedError extends UndiciError {
}
}
class Socks5ProxyError extends UndiciError {
constructor (message, code) {
super(message)
this.name = 'Socks5ProxyError'
this.message = message || 'SOCKS5 proxy error'
this.code = code || 'UND_ERR_SOCKS5'
}
}
const kMessageSizeExceededError = Symbol.for('undici.error.UND_ERR_WS_MESSAGE_SIZE_EXCEEDED')
class MessageSizeExceededError extends UndiciError {
constructor (message) {
super(message)
this.name = 'MessageSizeExceededError'
this.message = message || 'Max decompressed message size exceeded'
this.code = 'UND_ERR_WS_MESSAGE_SIZE_EXCEEDED'
}
static [Symbol.hasInstance] (instance) {
return instance && instance[kMessageSizeExceededError] === true
}
get [kMessageSizeExceededError] () {
return true
}
}
module.exports = {
AbortError,
HTTPParserError,
@@ -444,5 +471,7 @@ module.exports = {
RequestRetryError,
ResponseError,
SecureProxyConnectionError,
MaxOriginsReachedError
MaxOriginsReachedError,
Socks5ProxyError,
MessageSizeExceededError
}
+22 -4
View File
@@ -13,6 +13,7 @@ const {
isBuffer,
isFormDataLike,
isIterable,
hasSafeIterator,
isBlobLike,
serializePathWithQuery,
assertRequestHandler,
@@ -44,7 +45,8 @@ class Request {
expectContinue,
servername,
throwOnError,
maxRedirections
maxRedirections,
typeOfService
}, handler) {
if (typeof path !== 'string') {
throw new InvalidArgumentError('path must be a string')
@@ -68,6 +70,10 @@ class Request {
throw new InvalidArgumentError('upgrade must be a string')
}
if (upgrade && !isValidHeaderValue(upgrade)) {
throw new InvalidArgumentError('invalid upgrade header')
}
if (headersTimeout != null && (!Number.isFinite(headersTimeout) || headersTimeout < 0)) {
throw new InvalidArgumentError('invalid headersTimeout')
}
@@ -92,12 +98,18 @@ class Request {
throw new InvalidArgumentError('maxRedirections is not supported, use the redirect interceptor')
}
if (typeOfService != null && (!Number.isInteger(typeOfService) || typeOfService < 0 || typeOfService > 255)) {
throw new InvalidArgumentError('typeOfService must be an integer between 0 and 255')
}
this.headersTimeout = headersTimeout
this.bodyTimeout = bodyTimeout
this.method = method
this.typeOfService = typeOfService ?? 0
this.abort = null
if (body == null) {
@@ -174,7 +186,7 @@ class Request {
processHeader(this, headers[i], headers[i + 1])
}
} else if (headers && typeof headers === 'object') {
if (headers[Symbol.iterator]) {
if (hasSafeIterator(headers)) {
for (const header of headers) {
if (!Array.isArray(header) || header.length !== 2) {
throw new InvalidArgumentError('headers must be in key-value pair format')
@@ -377,13 +389,19 @@ function processHeader (request, key, val) {
val = `${val}`
}
if (request.host === null && headerName === 'host') {
if (headerName === 'host') {
if (request.host !== null) {
throw new InvalidArgumentError('duplicate host header')
}
if (typeof val !== 'string') {
throw new InvalidArgumentError('invalid host header')
}
// Consumed by Client
request.host = val
} else if (request.contentLength === null && headerName === 'content-length') {
} else if (headerName === 'content-length') {
if (request.contentLength !== null) {
throw new InvalidArgumentError('duplicate content-length header')
}
request.contentLength = parseInt(val, 10)
if (!Number.isFinite(request.contentLength)) {
throw new InvalidArgumentError('invalid content-length header')
+407
View File
@@ -0,0 +1,407 @@
'use strict'
const { EventEmitter } = require('node:events')
const { Buffer } = require('node:buffer')
const { InvalidArgumentError, Socks5ProxyError } = require('./errors')
const { debuglog } = require('node:util')
const { parseAddress } = require('./socks5-utils')
const debug = debuglog('undici:socks5')
// SOCKS5 constants
const SOCKS_VERSION = 0x05
// Authentication methods
const AUTH_METHODS = {
NO_AUTH: 0x00,
GSSAPI: 0x01,
USERNAME_PASSWORD: 0x02,
NO_ACCEPTABLE: 0xFF
}
// SOCKS5 commands
const COMMANDS = {
CONNECT: 0x01,
BIND: 0x02,
UDP_ASSOCIATE: 0x03
}
// Address types
const ADDRESS_TYPES = {
IPV4: 0x01,
DOMAIN: 0x03,
IPV6: 0x04
}
// Reply codes
const REPLY_CODES = {
SUCCEEDED: 0x00,
GENERAL_FAILURE: 0x01,
CONNECTION_NOT_ALLOWED: 0x02,
NETWORK_UNREACHABLE: 0x03,
HOST_UNREACHABLE: 0x04,
CONNECTION_REFUSED: 0x05,
TTL_EXPIRED: 0x06,
COMMAND_NOT_SUPPORTED: 0x07,
ADDRESS_TYPE_NOT_SUPPORTED: 0x08
}
// State machine states
const STATES = {
INITIAL: 'initial',
HANDSHAKING: 'handshaking',
AUTHENTICATING: 'authenticating',
CONNECTING: 'connecting',
CONNECTED: 'connected',
ERROR: 'error',
CLOSED: 'closed'
}
/**
* SOCKS5 client implementation
* Handles SOCKS5 protocol negotiation and connection establishment
*/
class Socks5Client extends EventEmitter {
constructor (socket, options = {}) {
super()
if (!socket) {
throw new InvalidArgumentError('socket is required')
}
this.socket = socket
this.options = options
this.state = STATES.INITIAL
this.buffer = Buffer.alloc(0)
// Authentication settings
this.authMethods = []
if (options.username && options.password) {
this.authMethods.push(AUTH_METHODS.USERNAME_PASSWORD)
}
this.authMethods.push(AUTH_METHODS.NO_AUTH)
// Socket event handlers
this.socket.on('data', this.onData.bind(this))
this.socket.on('error', this.onError.bind(this))
this.socket.on('close', this.onClose.bind(this))
}
/**
* Handle incoming data from the socket
*/
onData (data) {
debug('received data', data.length, 'bytes in state', this.state)
this.buffer = Buffer.concat([this.buffer, data])
try {
switch (this.state) {
case STATES.HANDSHAKING:
this.handleHandshakeResponse()
break
case STATES.AUTHENTICATING:
this.handleAuthResponse()
break
case STATES.CONNECTING:
this.handleConnectResponse()
break
}
} catch (err) {
this.onError(err)
}
}
/**
* Handle socket errors
*/
onError (err) {
debug('socket error', err)
this.state = STATES.ERROR
this.emit('error', err)
this.destroy()
}
/**
* Handle socket close
*/
onClose () {
debug('socket closed')
this.state = STATES.CLOSED
this.emit('close')
}
/**
* Destroy the client and underlying socket
*/
destroy () {
if (this.socket && !this.socket.destroyed) {
this.socket.destroy()
}
}
/**
* Start the SOCKS5 handshake
*/
handshake () {
if (this.state !== STATES.INITIAL) {
throw new InvalidArgumentError('Handshake already started')
}
debug('starting handshake with', this.authMethods.length, 'auth methods')
this.state = STATES.HANDSHAKING
// Build handshake request
// +----+----------+----------+
// |VER | NMETHODS | METHODS |
// +----+----------+----------+
// | 1 | 1 | 1 to 255 |
// +----+----------+----------+
const request = Buffer.alloc(2 + this.authMethods.length)
request[0] = SOCKS_VERSION
request[1] = this.authMethods.length
this.authMethods.forEach((method, i) => {
request[2 + i] = method
})
this.socket.write(request)
}
/**
* Handle handshake response from server
*/
handleHandshakeResponse () {
if (this.buffer.length < 2) {
return // Not enough data yet
}
const version = this.buffer[0]
const method = this.buffer[1]
if (version !== SOCKS_VERSION) {
throw new Socks5ProxyError(`Invalid SOCKS version: ${version}`, 'UND_ERR_SOCKS5_VERSION')
}
if (method === AUTH_METHODS.NO_ACCEPTABLE) {
throw new Socks5ProxyError('No acceptable authentication method', 'UND_ERR_SOCKS5_AUTH_REJECTED')
}
this.buffer = this.buffer.subarray(2)
debug('server selected auth method', method)
if (method === AUTH_METHODS.NO_AUTH) {
this.emit('authenticated')
} else if (method === AUTH_METHODS.USERNAME_PASSWORD) {
this.state = STATES.AUTHENTICATING
this.sendAuthRequest()
} else {
throw new Socks5ProxyError(`Unsupported authentication method: ${method}`, 'UND_ERR_SOCKS5_AUTH_METHOD')
}
}
/**
* Send username/password authentication request
*/
sendAuthRequest () {
const { username, password } = this.options
if (!username || !password) {
throw new InvalidArgumentError('Username and password required for authentication')
}
debug('sending username/password auth')
// Username/Password authentication request (RFC 1929)
// +----+------+----------+------+----------+
// |VER | ULEN | UNAME | PLEN | PASSWD |
// +----+------+----------+------+----------+
// | 1 | 1 | 1 to 255 | 1 | 1 to 255 |
// +----+------+----------+------+----------+
const usernameBuffer = Buffer.from(username)
const passwordBuffer = Buffer.from(password)
if (usernameBuffer.length > 255 || passwordBuffer.length > 255) {
throw new InvalidArgumentError('Username or password too long')
}
const request = Buffer.alloc(3 + usernameBuffer.length + passwordBuffer.length)
request[0] = 0x01 // Sub-negotiation version
request[1] = usernameBuffer.length
usernameBuffer.copy(request, 2)
request[2 + usernameBuffer.length] = passwordBuffer.length
passwordBuffer.copy(request, 3 + usernameBuffer.length)
this.socket.write(request)
}
/**
* Handle authentication response
*/
handleAuthResponse () {
if (this.buffer.length < 2) {
return // Not enough data yet
}
const version = this.buffer[0]
const status = this.buffer[1]
if (version !== 0x01) {
throw new Socks5ProxyError(`Invalid auth sub-negotiation version: ${version}`, 'UND_ERR_SOCKS5_AUTH_VERSION')
}
if (status !== 0x00) {
throw new Socks5ProxyError('Authentication failed', 'UND_ERR_SOCKS5_AUTH_FAILED')
}
this.buffer = this.buffer.subarray(2)
debug('authentication successful')
this.emit('authenticated')
}
/**
* Send CONNECT command
* @param {string} address - Target address (IP or domain)
* @param {number} port - Target port
*/
connect (address, port) {
if (this.state === STATES.CONNECTED) {
throw new InvalidArgumentError('Already connected')
}
debug('connecting to', address, port)
this.state = STATES.CONNECTING
const request = this.buildConnectRequest(COMMANDS.CONNECT, address, port)
this.socket.write(request)
}
/**
* Build a SOCKS5 request
*/
buildConnectRequest (command, address, port) {
// Parse address to determine type and buffer
const { type: addressType, buffer: addressBuffer } = parseAddress(address)
// Build request
// +----+-----+-------+------+----------+----------+
// |VER | CMD | RSV | ATYP | DST.ADDR | DST.PORT |
// +----+-----+-------+------+----------+----------+
// | 1 | 1 | X'00' | 1 | Variable | 2 |
// +----+-----+-------+------+----------+----------+
const request = Buffer.alloc(4 + addressBuffer.length + 2)
request[0] = SOCKS_VERSION
request[1] = command
request[2] = 0x00 // Reserved
request[3] = addressType
addressBuffer.copy(request, 4)
request.writeUInt16BE(port, 4 + addressBuffer.length)
return request
}
/**
* Handle CONNECT response
*/
handleConnectResponse () {
if (this.buffer.length < 4) {
return // Not enough data for header
}
const version = this.buffer[0]
const reply = this.buffer[1]
const addressType = this.buffer[3]
if (version !== SOCKS_VERSION) {
throw new Socks5ProxyError(`Invalid SOCKS version in reply: ${version}`, 'UND_ERR_SOCKS5_REPLY_VERSION')
}
// Calculate the expected response length
let responseLength = 4 // VER + REP + RSV + ATYP
if (addressType === ADDRESS_TYPES.IPV4) {
responseLength += 4 + 2 // IPv4 + port
} else if (addressType === ADDRESS_TYPES.DOMAIN) {
if (this.buffer.length < 5) {
return // Need domain length byte
}
responseLength += 1 + this.buffer[4] + 2 // length byte + domain + port
} else if (addressType === ADDRESS_TYPES.IPV6) {
responseLength += 16 + 2 // IPv6 + port
} else {
throw new Socks5ProxyError(`Invalid address type in reply: ${addressType}`, 'UND_ERR_SOCKS5_ADDR_TYPE')
}
if (this.buffer.length < responseLength) {
return // Not enough data for full response
}
if (reply !== REPLY_CODES.SUCCEEDED) {
const errorMessage = this.getReplyErrorMessage(reply)
throw new Socks5ProxyError(`SOCKS5 connection failed: ${errorMessage}`, `UND_ERR_SOCKS5_REPLY_${reply}`)
}
// Parse bound address and port
let boundAddress
let offset = 4
if (addressType === ADDRESS_TYPES.IPV4) {
boundAddress = Array.from(this.buffer.subarray(offset, offset + 4)).join('.')
offset += 4
} else if (addressType === ADDRESS_TYPES.DOMAIN) {
const domainLength = this.buffer[offset]
offset += 1
boundAddress = this.buffer.subarray(offset, offset + domainLength).toString()
offset += domainLength
} else if (addressType === ADDRESS_TYPES.IPV6) {
// Parse IPv6 address from 16-byte buffer
const parts = []
for (let i = 0; i < 8; i++) {
const value = this.buffer.readUInt16BE(offset + i * 2)
parts.push(value.toString(16))
}
boundAddress = parts.join(':')
offset += 16
}
const boundPort = this.buffer.readUInt16BE(offset)
this.buffer = this.buffer.subarray(responseLength)
this.state = STATES.CONNECTED
debug('connected, bound address:', boundAddress, 'port:', boundPort)
this.emit('connected', { address: boundAddress, port: boundPort })
}
/**
* Get human-readable error message for reply code
*/
getReplyErrorMessage (reply) {
switch (reply) {
case REPLY_CODES.GENERAL_FAILURE:
return 'General SOCKS server failure'
case REPLY_CODES.CONNECTION_NOT_ALLOWED:
return 'Connection not allowed by ruleset'
case REPLY_CODES.NETWORK_UNREACHABLE:
return 'Network unreachable'
case REPLY_CODES.HOST_UNREACHABLE:
return 'Host unreachable'
case REPLY_CODES.CONNECTION_REFUSED:
return 'Connection refused'
case REPLY_CODES.TTL_EXPIRED:
return 'TTL expired'
case REPLY_CODES.COMMAND_NOT_SUPPORTED:
return 'Command not supported'
case REPLY_CODES.ADDRESS_TYPE_NOT_SUPPORTED:
return 'Address type not supported'
default:
return `Unknown error code: ${reply}`
}
}
}
module.exports = {
Socks5Client,
AUTH_METHODS,
COMMANDS,
ADDRESS_TYPES,
REPLY_CODES,
STATES
}
+203
View File
@@ -0,0 +1,203 @@
'use strict'
const { Buffer } = require('node:buffer')
const net = require('node:net')
const { InvalidArgumentError } = require('./errors')
/**
* 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) {
// Check if it's an IPv4 address
if (net.isIPv4(address)) {
const parts = address.split('.').map(Number)
return {
type: 0x01, // IPv4
buffer: Buffer.from(parts)
}
}
// Check if it's an IPv6 address
if (net.isIPv6(address)) {
return {
type: 0x04, // IPv6
buffer: parseIPv6(address)
}
}
// Otherwise, treat as domain name
const domainBuffer = Buffer.from(address, 'utf8')
if (domainBuffer.length > 255) {
throw new InvalidArgumentError('Domain name too long (max 255 bytes)')
}
return {
type: 0x03, // Domain
buffer: Buffer.concat([Buffer.from([domainBuffer.length]), domainBuffer])
}
}
/**
* Parse IPv6 address to buffer
* @param {string} address - IPv6 address string
* @returns {Buffer} 16-byte buffer
*/
function parseIPv6 (address) {
const buffer = Buffer.alloc(16)
const parts = address.split(':')
let partIndex = 0
let bufferIndex = 0
// Handle compressed notation (::)
const doubleColonIndex = address.indexOf('::')
if (doubleColonIndex !== -1) {
// Count non-empty parts
const nonEmptyParts = parts.filter(p => p.length > 0).length
const skipParts = 8 - nonEmptyParts
for (let i = 0; i < parts.length; i++) {
if (parts[i] === '' && i === doubleColonIndex / 3) {
// Skip empty parts for ::
bufferIndex += skipParts * 2
} else if (parts[i] !== '') {
const value = parseInt(parts[i], 16)
buffer.writeUInt16BE(value, bufferIndex)
bufferIndex += 2
}
}
} else {
// No compression, parse normally
for (const part of parts) {
if (part === '') continue
const value = parseInt(part, 16)
buffer.writeUInt16BE(value, partIndex * 2)
partIndex++
}
}
return buffer
}
/**
* Build a SOCKS5 address buffer
* @param {number} type - Address type (1=IPv4, 3=Domain, 4=IPv6)
* @param {Buffer} addressBuffer - The address data
* @param {number} port - Port number
* @returns {Buffer} Complete address buffer including type, address, and port
*/
function buildAddressBuffer (type, addressBuffer, port) {
const portBuffer = Buffer.allocUnsafe(2)
portBuffer.writeUInt16BE(port, 0)
return Buffer.concat([
Buffer.from([type]),
addressBuffer,
portBuffer
])
}
/**
* Parse address from SOCKS5 response
* @param {Buffer} buffer - Buffer containing the address
* @param {number} offset - Starting offset in buffer
* @returns {{address: string, port: number, bytesRead: number}}
*/
function parseResponseAddress (buffer, offset = 0) {
if (buffer.length < offset + 1) {
throw new InvalidArgumentError('Buffer too small to contain address type')
}
const addressType = buffer[offset]
let address
let currentOffset = offset + 1
switch (addressType) {
case 0x01: { // IPv4
if (buffer.length < currentOffset + 6) {
throw new InvalidArgumentError('Buffer too small for IPv4 address')
}
address = Array.from(buffer.subarray(currentOffset, currentOffset + 4)).join('.')
currentOffset += 4
break
}
case 0x03: { // Domain
if (buffer.length < currentOffset + 1) {
throw new InvalidArgumentError('Buffer too small for domain length')
}
const domainLength = buffer[currentOffset]
currentOffset += 1
if (buffer.length < currentOffset + domainLength + 2) {
throw new InvalidArgumentError('Buffer too small for domain address')
}
address = buffer.subarray(currentOffset, currentOffset + domainLength).toString('utf8')
currentOffset += domainLength
break
}
case 0x04: { // IPv6
if (buffer.length < currentOffset + 18) {
throw new InvalidArgumentError('Buffer too small for IPv6 address')
}
// Convert buffer to IPv6 string
const parts = []
for (let i = 0; i < 8; i++) {
const value = buffer.readUInt16BE(currentOffset + i * 2)
parts.push(value.toString(16))
}
address = parts.join(':')
currentOffset += 16
break
}
default:
throw new InvalidArgumentError(`Invalid address type: ${addressType}`)
}
// Parse port
if (buffer.length < currentOffset + 2) {
throw new InvalidArgumentError('Buffer too small for port')
}
const port = buffer.readUInt16BE(currentOffset)
currentOffset += 2
return {
address,
port,
bytesRead: currentOffset - offset
}
}
/**
* Create error for SOCKS5 reply code
* @param {number} replyCode - SOCKS5 reply code
* @returns {Error} Appropriate error object
*/
function createReplyError (replyCode) {
const messages = {
0x01: 'General SOCKS server failure',
0x02: 'Connection not allowed by ruleset',
0x03: 'Network unreachable',
0x04: 'Host unreachable',
0x05: 'Connection refused',
0x06: 'TTL expired',
0x07: 'Command not supported',
0x08: 'Address type not supported'
}
const message = messages[replyCode] || `Unknown SOCKS5 error code: ${replyCode}`
const error = new Error(message)
error.code = `SOCKS5_${replyCode}`
return error
}
module.exports = {
parseAddress,
parseIPv6,
buildAddressBuffer,
parseResponseAddress,
createReplyError
}
+2 -1
View File
@@ -70,5 +70,6 @@ module.exports = {
kPingInterval: Symbol('ping interval'),
kNoProxyAgent: Symbol('no proxy agent'),
kHttpProxyAgent: Symbol('http proxy agent'),
kHttpsProxyAgent: Symbol('https proxy agent')
kHttpsProxyAgent: Symbol('https proxy agent'),
kSocks5ProxyAgent: Symbol('socks5 proxy agent')
}
+15
View File
@@ -327,6 +327,20 @@ function isIterable (obj) {
return !!(obj != null && (typeof obj[Symbol.iterator] === 'function' || typeof obj[Symbol.asyncIterator] === 'function'))
}
/**
* Checks whether an object has a safe Symbol.iterator — i.e. one that is
* either own or inherited from a non-Object.prototype chain. This prevents
* prototype-pollution attacks from injecting a fake iterator on
* Object.prototype.
* @param {object} obj
* @returns {boolean}
*/
function hasSafeIterator (obj) {
const prototype = Object.getPrototypeOf(obj)
const ownIterator = Object.prototype.hasOwnProperty.call(obj, Symbol.iterator)
return ownIterator || (prototype != null && prototype !== Object.prototype && typeof obj[Symbol.iterator] === 'function')
}
/**
* @param {Blob|Buffer|import ('stream').Stream} body
* @returns {number|null}
@@ -918,6 +932,7 @@ module.exports = {
getServerName,
isStream,
isIterable,
hasSafeIterator,
isAsyncIterable,
isDestroyed,
headerNameToString,
+9 -6
View File
@@ -14,7 +14,7 @@ const {
} = require('./pool-base')
const Pool = require('./pool')
const { kUrl } = require('../core/symbols')
const { parseOrigin } = require('../core/util')
const util = require('../core/util')
const kFactory = Symbol('factory')
const kOptions = Symbol('options')
@@ -56,7 +56,10 @@ class BalancedPool extends PoolBase {
super()
this[kOptions] = opts
this[kOptions] = { ...util.deepClone(opts) }
this[kOptions].interceptors = opts.interceptors
? { ...opts.interceptors }
: undefined
this[kIndex] = -1
this[kCurrentWeight] = 0
@@ -76,7 +79,7 @@ class BalancedPool extends PoolBase {
}
addUpstream (upstream) {
const upstreamOrigin = parseOrigin(upstream).origin
const upstreamOrigin = util.parseOrigin(upstream).origin
if (this[kClients].find((pool) => (
pool[kUrl].origin === upstreamOrigin &&
@@ -85,7 +88,7 @@ class BalancedPool extends PoolBase {
))) {
return this
}
const pool = this[kFactory](upstreamOrigin, Object.assign({}, this[kOptions]))
const pool = this[kFactory](upstreamOrigin, this[kOptions])
this[kAddClient](pool)
pool.on('connect', () => {
@@ -125,7 +128,7 @@ class BalancedPool extends PoolBase {
}
removeUpstream (upstream) {
const upstreamOrigin = parseOrigin(upstream).origin
const upstreamOrigin = util.parseOrigin(upstream).origin
const pool = this[kClients].find((pool) => (
pool[kUrl].origin === upstreamOrigin &&
@@ -141,7 +144,7 @@ class BalancedPool extends PoolBase {
}
getUpstream (upstream) {
const upstreamOrigin = parseOrigin(upstream).origin
const upstreamOrigin = util.parseOrigin(upstream).origin
return this[kClients].find((pool) => (
pool[kUrl].origin === upstreamOrigin &&
+4
View File
@@ -1114,6 +1114,10 @@ function writeH1 (client, request) {
socket[kBlocking] = true
}
if (socket.setTypeOfService) {
socket.setTypeOfService(request.typeOfService)
}
let header = `${method} ${path} HTTP/1.1\r\n`
if (typeof host === 'string') {
+10 -5
View File
@@ -700,12 +700,16 @@ function writeH2 (client, request) {
if (request.onHeaders(Number(statusCode), parseH2Headers(realHeaders), stream.resume.bind(stream), '') === false) {
stream.pause()
}
})
stream.on('data', (chunk) => {
if (request.onData(chunk) === false) {
stream.pause()
}
stream.on('data', (chunk) => {
if (request.aborted || request.completed) {
return
}
if (request.onData(chunk) === false) {
stream.pause()
}
})
})
stream.once('end', () => {
@@ -767,6 +771,7 @@ function writeH2 (client, request) {
return
}
stream.removeAllListeners('data')
request.onComplete(trailers)
})
+8 -1
View File
@@ -69,7 +69,7 @@ const getDefaultNodeMaxHeaderSize = http &&
? () => http.maxHeaderSize
: () => { throw new InvalidArgumentError('http module not available or http.maxHeaderSize invalid') }
const noop = () => {}
const noop = () => { }
function getPipelining (client) {
return client[kPipelining] ?? client[kHTTPContext]?.defaultPipelining ?? 1
@@ -235,6 +235,9 @@ class Client extends DispatcherBase {
...(typeof autoSelectFamily === 'boolean' ? { autoSelectFamily, autoSelectFamilyAttemptTimeout } : undefined),
...connect
})
} else if (socketPath != null) {
const customConnect = connect
connect = (opts, callback) => customConnect({ ...opts, socketPath }, callback)
}
this[kUrl] = util.parseOrigin(url)
@@ -607,6 +610,10 @@ function _resume (client, sync) {
const request = client[kQueue][client[kPendingIdx]]
if (request === null) {
return
}
if (client[kUrl].protocol === 'https:' && client[kServerName] !== request.servername) {
if (client[kRunning] > 0) {
return
+1 -1
View File
@@ -67,7 +67,7 @@ class Pool extends PoolBase {
this[kConnections] = connections || null
this[kUrl] = util.parseOrigin(origin)
this[kOptions] = { ...util.deepClone(options), connect, allowH2, clientTtl }
this[kOptions] = { ...util.deepClone(options), connect, allowH2, clientTtl, socketPath }
this[kOptions].interceptors = options.interceptors
? { ...options.interceptors }
: undefined
+40 -9
View File
@@ -8,6 +8,7 @@ const { InvalidArgumentError, RequestAbortedError, SecureProxyConnectionError }
const buildConnector = require('../core/connect')
const Client = require('./client')
const { channels } = require('../core/diagnostics')
const Socks5ProxyAgent = require('./socks5-proxy-agent')
const kAgent = Symbol('proxy agent')
const kClient = Symbol('proxy client')
@@ -132,6 +133,19 @@ class ProxyAgent extends DispatcherBase {
const agentFactory = opts.factory || defaultAgentFactory
const factory = (origin, options) => {
const { protocol } = new URL(origin)
// Handle SOCKS5 proxy
if (this[kProxy].protocol === 'socks5:' || this[kProxy].protocol === 'socks:') {
return new Socks5ProxyAgent(this[kProxy].uri, {
headers: this[kProxyHeaders],
connect,
factory: agentFactory,
username: opts.username || username,
password: opts.password || password,
proxyTls: opts.proxyTls
})
}
if (!this[kTunnelProxy] && protocol === 'http:' && this[kProxy].protocol === 'http:') {
return new Http1ProxyWrapper(this[kProxy].uri, {
headers: this[kProxyHeaders],
@@ -141,11 +155,26 @@ class ProxyAgent extends DispatcherBase {
}
return agentFactory(origin, options)
}
this[kClient] = clientFactory(url, { connect })
// For SOCKS5 proxies, we don't need a client to the proxy itself
// The SOCKS5 connection is handled within Socks5ProxyAgent
if (protocol === 'socks5:' || protocol === 'socks:') {
this[kClient] = null
} else {
this[kClient] = clientFactory(url, { connect })
}
this[kAgent] = new Agent({
...opts,
factory,
connect: async (opts, callback) => {
// SOCKS5 proxies handle their own connections via Socks5ProxyAgent,
// so this connect function should never be called for them.
if (!this[kClient]) {
callback(new InvalidArgumentError('Cannot establish tunnel connection without a proxy client'))
return
}
let requestedPath = opts.host
if (!opts.port) {
requestedPath += `:${defaultProtocolPort(opts.protocol)}`
@@ -233,17 +262,19 @@ class ProxyAgent extends DispatcherBase {
}
[kClose] () {
return Promise.all([
this[kAgent].close(),
this[kClient].close()
])
const promises = [this[kAgent].close()]
if (this[kClient]) {
promises.push(this[kClient].close())
}
return Promise.all(promises)
}
[kDestroy] () {
return Promise.all([
this[kAgent].destroy(),
this[kClient].destroy()
])
const promises = [this[kAgent].destroy()]
if (this[kClient]) {
promises.push(this[kClient].destroy())
}
return Promise.all(promises)
}
}
+1 -1
View File
@@ -68,7 +68,7 @@ class RoundRobinPool extends PoolBase {
this[kConnections] = connections || null
this[kUrl] = util.parseOrigin(origin)
this[kOptions] = { ...util.deepClone(options), connect, allowH2, clientTtl }
this[kOptions] = { ...util.deepClone(options), connect, allowH2, clientTtl, socketPath }
this[kOptions].interceptors = options.interceptors
? { ...options.interceptors }
: undefined
+249
View File
@@ -0,0 +1,249 @@
'use strict'
const net = require('node:net')
const { URL } = require('node:url')
let tls // include tls conditionally since it is not always available
const DispatcherBase = require('./dispatcher-base')
const { InvalidArgumentError } = require('../core/errors')
const { Socks5Client } = require('../core/socks5-client')
const { kDispatch, kClose, kDestroy } = require('../core/symbols')
const Pool = require('./pool')
const buildConnector = require('../core/connect')
const { debuglog } = require('node:util')
const debug = debuglog('undici:socks5-proxy')
const kProxyUrl = Symbol('proxy url')
const kProxyHeaders = Symbol('proxy headers')
const kProxyAuth = Symbol('proxy auth')
const kPool = Symbol('pool')
const kConnector = Symbol('connector')
// Static flag to ensure warning is only emitted once per process
let experimentalWarningEmitted = false
/**
* SOCKS5 proxy agent for dispatching requests through a SOCKS5 proxy
*/
class Socks5ProxyAgent extends DispatcherBase {
constructor (proxyUrl, options = {}) {
super()
// Emit experimental warning only once
if (!experimentalWarningEmitted) {
process.emitWarning(
'SOCKS5 proxy support is experimental and subject to change',
'ExperimentalWarning'
)
experimentalWarningEmitted = true
}
if (!proxyUrl) {
throw new InvalidArgumentError('Proxy URL is mandatory')
}
// Parse proxy URL
const url = typeof proxyUrl === 'string' ? new URL(proxyUrl) : proxyUrl
if (url.protocol !== 'socks5:' && url.protocol !== 'socks:') {
throw new InvalidArgumentError('Proxy URL must use socks5:// or socks:// protocol')
}
this[kProxyUrl] = url
this[kProxyHeaders] = options.headers || {}
// Extract auth from URL or options
this[kProxyAuth] = {
username: options.username || (url.username ? decodeURIComponent(url.username) : null),
password: options.password || (url.password ? decodeURIComponent(url.password) : null)
}
// Create connector for proxy connection
this[kConnector] = options.connect || buildConnector({
...options.proxyTls,
servername: options.proxyTls?.servername || url.hostname
})
// Pool for the actual HTTP connections (with SOCKS5 tunnel connect function)
this[kPool] = null
}
/**
* Create a SOCKS5 connection to the proxy
*/
async createSocks5Connection (targetHost, targetPort) {
const proxyHost = this[kProxyUrl].hostname
const proxyPort = parseInt(this[kProxyUrl].port) || 1080
debug('creating SOCKS5 connection to', proxyHost, proxyPort)
// Connect to the SOCKS5 proxy
const socket = await new Promise((resolve, reject) => {
const onConnect = () => {
socket.removeListener('error', onError)
resolve(socket)
}
const onError = (err) => {
socket.removeListener('connect', onConnect)
reject(err)
}
const socket = net.connect({
host: proxyHost,
port: proxyPort
})
socket.once('connect', onConnect)
socket.once('error', onError)
})
// Create SOCKS5 client
const socks5Client = new Socks5Client(socket, this[kProxyAuth])
// Handle SOCKS5 errors
socks5Client.on('error', (err) => {
debug('SOCKS5 error:', err)
socket.destroy()
})
// Perform SOCKS5 handshake
await socks5Client.handshake()
// Wait for authentication (if required)
await new Promise((resolve, reject) => {
const timeout = setTimeout(() => {
reject(new Error('SOCKS5 authentication timeout'))
}, 5000)
const onAuthenticated = () => {
clearTimeout(timeout)
socks5Client.removeListener('error', onError)
resolve()
}
const onError = (err) => {
clearTimeout(timeout)
socks5Client.removeListener('authenticated', onAuthenticated)
reject(err)
}
// Check if already authenticated (for NO_AUTH method)
if (socks5Client.state === 'authenticated') {
clearTimeout(timeout)
resolve()
} else {
socks5Client.once('authenticated', onAuthenticated)
socks5Client.once('error', onError)
}
})
// Send CONNECT command
await socks5Client.connect(targetHost, targetPort)
// Wait for connection
await new Promise((resolve, reject) => {
const timeout = setTimeout(() => {
reject(new Error('SOCKS5 connection timeout'))
}, 5000)
const onConnected = (info) => {
debug('SOCKS5 tunnel established to', targetHost, targetPort, 'via', info)
clearTimeout(timeout)
socks5Client.removeListener('error', onError)
resolve()
}
const onError = (err) => {
clearTimeout(timeout)
socks5Client.removeListener('connected', onConnected)
reject(err)
}
socks5Client.once('connected', onConnected)
socks5Client.once('error', onError)
})
return socket
}
/**
* Dispatch a request through the SOCKS5 proxy
*/
async [kDispatch] (opts, handler) {
const { origin } = opts
debug('dispatching request to', origin, 'via SOCKS5')
try {
// Create Pool with custom connect function if we don't have one yet
if (!this[kPool] || this[kPool].destroyed || this[kPool].closed) {
this[kPool] = new Pool(origin, {
pipelining: opts.pipelining,
connections: opts.connections,
connect: async (connectOpts, callback) => {
try {
const url = new URL(origin)
const targetHost = url.hostname
const targetPort = parseInt(url.port) || (url.protocol === 'https:' ? 443 : 80)
debug('establishing SOCKS5 connection to', targetHost, targetPort)
// Create SOCKS5 tunnel
const socket = await this.createSocks5Connection(targetHost, targetPort)
// Handle TLS if needed
let finalSocket = socket
if (url.protocol === 'https:') {
if (!tls) {
tls = require('node:tls')
}
debug('upgrading to TLS')
finalSocket = tls.connect({
socket,
servername: targetHost,
...connectOpts.tls || {}
})
await new Promise((resolve, reject) => {
finalSocket.once('secureConnect', resolve)
finalSocket.once('error', reject)
})
}
callback(null, finalSocket)
} catch (err) {
debug('SOCKS5 connection error:', err)
callback(err)
}
}
})
}
// Dispatch the request through the pool
return this[kPool][kDispatch](opts, handler)
} catch (err) {
debug('dispatch error:', err)
if (typeof handler.onError === 'function') {
handler.onError(err)
} else {
throw err
}
}
}
async [kClose] () {
if (this[kPool]) {
await this[kPool].close()
}
}
async [kDestroy] (err) {
if (this[kPool]) {
await this[kPool].destroy(err)
}
}
}
module.exports = Socks5ProxyAgent
+306 -62
View File
@@ -1,11 +1,25 @@
'use strict'
const { RequestAbortedError } = require('../core/errors')
/**
* @typedef {import('../../types/dispatcher.d.ts').default.DispatchHandler} DispatchHandler
*/
const DEFAULT_MAX_BUFFER_SIZE = 5 * 1024 * 1024
/**
* Handler that buffers response data and notifies multiple waiting handlers.
* @typedef {Object} WaitingHandler
* @property {DispatchHandler} handler
* @property {import('../../types/dispatcher.d.ts').default.DispatchController} controller
* @property {Buffer[]} bufferedChunks
* @property {number} bufferedBytes
* @property {object | null} pendingTrailers
* @property {boolean} done
*/
/**
* Handler that forwards response events to multiple waiting handlers.
* Used for request deduplication.
*
* @implements {DispatchHandler}
@@ -17,14 +31,14 @@ class DeduplicationHandler {
#primaryHandler
/**
* @type {DispatchHandler[]}
* @type {WaitingHandler[]}
*/
#waitingHandlers = []
/**
* @type {Buffer[]}
* @type {number}
*/
#chunks = []
#maxBufferSize = DEFAULT_MAX_BUFFER_SIZE
/**
* @type {number}
@@ -46,6 +60,21 @@ class DeduplicationHandler {
*/
#aborted = false
/**
* @type {boolean}
*/
#responseStarted = false
/**
* @type {boolean}
*/
#responseDataStarted = false
/**
* @type {boolean}
*/
#completed = false
/**
* @type {import('../../types/dispatcher.d.ts').default.DispatchController | null}
*/
@@ -59,22 +88,60 @@ class DeduplicationHandler {
/**
* @param {DispatchHandler} primaryHandler The primary handler
* @param {() => void} onComplete Callback when request completes
* @param {number} [maxBufferSize] Maximum paused buffer size per waiting handler
*/
constructor (primaryHandler, onComplete) {
constructor (primaryHandler, onComplete, maxBufferSize = DEFAULT_MAX_BUFFER_SIZE) {
this.#primaryHandler = primaryHandler
this.#onComplete = onComplete
this.#maxBufferSize = maxBufferSize
}
/**
* Add a waiting handler that will receive the buffered response
* Add a waiting handler that will receive response events.
* Returns false if deduplication can no longer safely attach this handler.
*
* @param {DispatchHandler} handler
* @returns {boolean}
*/
addWaitingHandler (handler) {
this.#waitingHandlers.push(handler)
if (this.#completed || this.#responseDataStarted) {
return false
}
const waitingHandler = this.#createWaitingHandler(handler)
const waitingController = waitingHandler.controller
try {
handler.onRequestStart?.(waitingController, null)
if (waitingController.aborted) {
waitingHandler.done = true
return true
}
if (this.#responseStarted) {
handler.onResponseStart?.(
waitingController,
this.#statusCode,
this.#headers,
this.#statusMessage
)
}
} catch {
// Ignore errors from waiting handlers
waitingHandler.done = true
return true
}
if (!waitingController.aborted) {
this.#waitingHandlers.push(waitingHandler)
}
return true
}
/**
* @param {() => void} abort
* @param {import('../../types/dispatcher.d.ts').default.DispatchController} controller
* @param {any} context
*/
onRequestStart (controller, context) {
@@ -99,10 +166,38 @@ class DeduplicationHandler {
* @param {string} statusMessage
*/
onResponseStart (controller, statusCode, headers, statusMessage) {
this.#responseStarted = true
this.#statusCode = statusCode
this.#headers = headers
this.#statusMessage = statusMessage
this.#primaryHandler.onResponseStart?.(controller, statusCode, headers, statusMessage)
for (const waitingHandler of this.#waitingHandlers) {
const { handler, controller: waitingController } = waitingHandler
if (waitingHandler.done || waitingController.aborted) {
waitingHandler.done = true
continue
}
try {
handler.onResponseStart?.(
waitingController,
statusCode,
headers,
statusMessage
)
} catch {
// Ignore errors from waiting handlers
}
if (waitingController.aborted) {
waitingHandler.done = true
}
}
this.#pruneDoneWaitingHandlers()
}
/**
@@ -110,9 +205,41 @@ class DeduplicationHandler {
* @param {Buffer} chunk
*/
onResponseData (controller, chunk) {
// Buffer the chunk for waiting handlers
this.#chunks.push(Buffer.from(chunk))
if (this.#aborted || this.#completed) {
return
}
this.#responseDataStarted = true
this.#primaryHandler.onResponseData?.(controller, chunk)
for (const waitingHandler of this.#waitingHandlers) {
const { handler, controller: waitingController } = waitingHandler
if (waitingHandler.done || waitingController.aborted) {
waitingHandler.done = true
continue
}
if (waitingController.paused) {
this.#bufferWaitingChunk(waitingHandler, chunk)
continue
}
try {
handler.onResponseData?.(waitingController, chunk)
} catch {
// Ignore errors from waiting handlers
}
if (waitingController.aborted) {
waitingHandler.done = true
waitingHandler.bufferedChunks = []
waitingHandler.bufferedBytes = 0
}
}
this.#pruneDoneWaitingHandlers()
}
/**
@@ -120,8 +247,41 @@ class DeduplicationHandler {
* @param {object} trailers
*/
onResponseEnd (controller, trailers) {
if (this.#aborted || this.#completed) {
return
}
this.#completed = true
this.#primaryHandler.onResponseEnd?.(controller, trailers)
this.#notifyWaitingHandlers()
for (const waitingHandler of this.#waitingHandlers) {
if (waitingHandler.done || waitingHandler.controller.aborted) {
waitingHandler.done = true
continue
}
this.#flushWaitingHandler(waitingHandler)
if (waitingHandler.done || waitingHandler.controller.aborted) {
waitingHandler.done = true
continue
}
if (waitingHandler.controller.paused && waitingHandler.bufferedChunks.length > 0) {
waitingHandler.pendingTrailers = trailers
continue
}
try {
waitingHandler.handler.onResponseEnd?.(waitingHandler.controller, trailers)
} catch {
// Ignore errors from waiting handlers
}
waitingHandler.done = true
}
this.#pruneDoneWaitingHandlers()
this.#onComplete?.()
}
@@ -130,86 +290,170 @@ class DeduplicationHandler {
* @param {Error} err
*/
onResponseError (controller, err) {
if (this.#completed) {
return
}
this.#aborted = true
this.#completed = true
this.#primaryHandler.onResponseError?.(controller, err)
this.#notifyWaitingHandlersError(err)
for (const waitingHandler of this.#waitingHandlers) {
this.#errorWaitingHandler(waitingHandler, err)
}
this.#waitingHandlers = []
this.#onComplete?.()
}
/**
* Notify all waiting handlers with the buffered response
* @param {DispatchHandler} handler
* @returns {WaitingHandler}
*/
#notifyWaitingHandlers () {
const body = Buffer.concat(this.#chunks)
#createWaitingHandler (handler) {
/** @type {WaitingHandler} */
const waitingHandler = {
handler,
controller: null,
bufferedChunks: [],
bufferedBytes: 0,
pendingTrailers: null,
done: false
}
for (const handler of this.#waitingHandlers) {
// Create a simple controller for each waiting handler
const waitingController = {
resume () {},
pause () {},
get paused () { return false },
get aborted () { return false },
get reason () { return null },
abort () {}
}
const state = {
aborted: false,
paused: false,
reason: null
}
try {
handler.onRequestStart?.(waitingController, null)
if (waitingController.aborted) {
continue
waitingHandler.controller = {
resume: () => {
if (state.aborted) {
return
}
handler.onResponseStart?.(
waitingController,
this.#statusCode,
this.#headers,
this.#statusMessage
)
state.paused = false
this.#flushWaitingHandler(waitingHandler)
if (waitingController.aborted) {
continue
if (
this.#completed &&
waitingHandler.pendingTrailers &&
waitingHandler.bufferedChunks.length === 0 &&
!state.paused &&
!state.aborted
) {
try {
waitingHandler.handler.onResponseEnd?.(waitingHandler.controller, waitingHandler.pendingTrailers)
} catch {
// Ignore errors from waiting handlers
}
waitingHandler.pendingTrailers = null
waitingHandler.done = true
}
if (body.length > 0) {
handler.onResponseData?.(waitingController, body)
this.#pruneDoneWaitingHandlers()
},
pause: () => {
if (!state.aborted) {
state.paused = true
}
handler.onResponseEnd?.(waitingController, {})
} catch {
// Ignore errors from waiting handlers
},
get paused () { return state.paused },
get aborted () { return state.aborted },
get reason () { return state.reason },
abort: (reason) => {
state.aborted = true
state.reason = reason ?? null
waitingHandler.done = true
waitingHandler.pendingTrailers = null
waitingHandler.bufferedChunks = []
waitingHandler.bufferedBytes = 0
}
}
this.#waitingHandlers = []
this.#chunks = []
return waitingHandler
}
/**
* Notify all waiting handlers of an error
* @param {Error} err
* @param {WaitingHandler} waitingHandler
* @param {Buffer} chunk
*/
#notifyWaitingHandlersError (err) {
for (const handler of this.#waitingHandlers) {
const waitingController = {
resume () {},
pause () {},
get paused () { return false },
get aborted () { return true },
get reason () { return err },
abort () {}
}
#bufferWaitingChunk (waitingHandler, chunk) {
if (waitingHandler.done || waitingHandler.controller.aborted) {
waitingHandler.done = true
waitingHandler.bufferedChunks = []
waitingHandler.bufferedBytes = 0
return
}
const bufferedChunk = Buffer.from(chunk)
waitingHandler.bufferedChunks.push(bufferedChunk)
waitingHandler.bufferedBytes += bufferedChunk.length
if (waitingHandler.bufferedBytes > this.#maxBufferSize) {
const err = new RequestAbortedError(`Deduplicated waiting handler exceeded maxBufferSize (${this.#maxBufferSize} bytes) while paused`)
this.#errorWaitingHandler(waitingHandler, err)
}
}
/**
* @param {WaitingHandler} waitingHandler
*/
#flushWaitingHandler (waitingHandler) {
const { handler, controller } = waitingHandler
while (
!waitingHandler.done &&
!controller.aborted &&
!controller.paused &&
waitingHandler.bufferedChunks.length > 0
) {
const bufferedChunk = waitingHandler.bufferedChunks.shift()
waitingHandler.bufferedBytes -= bufferedChunk.length
try {
handler.onRequestStart?.(waitingController, null)
handler.onResponseError?.(waitingController, err)
handler.onResponseData?.(controller, bufferedChunk)
} catch {
// Ignore errors from waiting handlers
}
if (controller.aborted) {
waitingHandler.done = true
waitingHandler.pendingTrailers = null
waitingHandler.bufferedChunks = []
waitingHandler.bufferedBytes = 0
break
}
}
}
/**
* @param {WaitingHandler} waitingHandler
* @param {Error} err
*/
#errorWaitingHandler (waitingHandler, err) {
if (waitingHandler.done) {
return
}
this.#waitingHandlers = []
this.#chunks = []
waitingHandler.done = true
waitingHandler.pendingTrailers = null
waitingHandler.bufferedChunks = []
waitingHandler.bufferedBytes = 0
try {
waitingHandler.controller.abort(err)
waitingHandler.handler.onResponseError?.(waitingHandler.controller, err)
} catch {
// Ignore errors from waiting handlers
}
}
#pruneDoneWaitingHandlers () {
this.#waitingHandlers = this.#waitingHandlers.filter(waitingHandler => waitingHandler.done === false)
}
}
+2 -1
View File
@@ -222,7 +222,8 @@ function cleanRequestHeaders (headers, removeContent, unknownOrigin) {
}
}
} else if (headers && typeof headers === 'object') {
const entries = typeof headers[Symbol.iterator] === 'function' ? headers : Object.entries(headers)
const entries = util.hasSafeIterator(headers) ? headers : Object.entries(headers)
for (const [key, value] of entries) {
if (!shouldRemoveHeader(key, removeContent, unknownOrigin)) {
ret.push(key, value)
+4
View File
@@ -67,6 +67,10 @@ module.exports = class UnwrapHandler {
this.#handler.onRequestStart?.(this.#controller, context)
}
onResponseStarted () {
return this.#handler.onResponseStarted?.()
}
onUpgrade (statusCode, rawHeaders, socket) {
this.#handler.onRequestUpgrade?.(this.#controller, statusCode, parseHeaders(rawHeaders), socket)
}
+13 -3
View File
@@ -20,6 +20,10 @@ module.exports = class WrapHandler {
return this.#handler.onConnect?.(abort, context)
}
onResponseStarted () {
return this.#handler.onResponseStarted?.()
}
onHeaders (statusCode, rawHeaders, resume, statusMessage) {
return this.#handler.onHeaders?.(statusCode, rawHeaders, resume, statusMessage)
}
@@ -53,7 +57,7 @@ module.exports = class WrapHandler {
onRequestUpgrade (controller, statusCode, headers, socket) {
const rawHeaders = []
for (const [key, val] of Object.entries(headers)) {
rawHeaders.push(Buffer.from(key), Array.isArray(val) ? val.map(v => Buffer.from(v)) : Buffer.from(val))
rawHeaders.push(Buffer.from(key, 'latin1'), toRawHeaderValue(val))
}
this.#handler.onUpgrade?.(statusCode, rawHeaders, socket)
@@ -62,7 +66,7 @@ module.exports = class WrapHandler {
onResponseStart (controller, statusCode, headers, statusMessage) {
const rawHeaders = []
for (const [key, val] of Object.entries(headers)) {
rawHeaders.push(Buffer.from(key), Array.isArray(val) ? val.map(v => Buffer.from(v)) : Buffer.from(val))
rawHeaders.push(Buffer.from(key, 'latin1'), toRawHeaderValue(val))
}
if (this.#handler.onHeaders?.(statusCode, rawHeaders, () => controller.resume(), statusMessage) === false) {
@@ -79,7 +83,7 @@ module.exports = class WrapHandler {
onResponseEnd (controller, trailers) {
const rawTrailers = []
for (const [key, val] of Object.entries(trailers)) {
rawTrailers.push(Buffer.from(key), Array.isArray(val) ? val.map(v => Buffer.from(v)) : Buffer.from(val))
rawTrailers.push(Buffer.from(key, 'latin1'), toRawHeaderValue(val))
}
this.#handler.onComplete?.(rawTrailers)
@@ -93,3 +97,9 @@ module.exports = class WrapHandler {
this.#handler.onError?.(err)
}
}
function toRawHeaderValue (value) {
return Array.isArray(value)
? value.map((item) => Buffer.from(item, 'latin1'))
: Buffer.from(value, 'latin1')
}
+15 -5
View File
@@ -15,7 +15,8 @@ module.exports = (opts = {}) => {
const {
methods = ['GET'],
skipHeaderNames = [],
excludeHeaderNames = []
excludeHeaderNames = [],
maxBufferSize = 5 * 1024 * 1024
} = opts
if (typeof opts !== 'object' || opts === null) {
@@ -40,6 +41,10 @@ module.exports = (opts = {}) => {
throw new TypeError(`expected opts.excludeHeaderNames to be an array, got ${typeof excludeHeaderNames}`)
}
if (!Number.isFinite(maxBufferSize) || maxBufferSize <= 0) {
throw new TypeError(`expected opts.maxBufferSize to be a positive finite number, got ${maxBufferSize}`)
}
// Convert to lowercase Set for case-insensitive header matching
const skipHeaderNamesSet = new Set(skipHeaderNames.map(name => name.toLowerCase()))
@@ -78,9 +83,13 @@ module.exports = (opts = {}) => {
// Check if there's already a pending request for this key
const pendingHandler = pendingRequests.get(dedupeKey)
if (pendingHandler) {
// Add this handler to the waiting list
pendingHandler.addWaitingHandler(handler)
return true
// Add this handler to the waiting list when safe.
// If body streaming has already started, this request must be sent independently.
if (pendingHandler.addWaitingHandler(handler)) {
return true
}
return dispatch(opts, handler)
}
// Create a new deduplication handler
@@ -92,7 +101,8 @@ module.exports = (opts = {}) => {
if (pendingRequestsChannel.hasSubscribers) {
pendingRequestsChannel.publish({ size: pendingRequests.size, key: dedupeKey, type: 'removed' })
}
}
},
maxBufferSize
)
// Register the pending request
+103 -6
View File
@@ -5,6 +5,105 @@ const DecoratorHandler = require('../handler/decorator-handler')
const { InvalidArgumentError, InformationalError } = require('../core/errors')
const maxInt = Math.pow(2, 31) - 1
function hasSafeIterator (headers) {
const prototype = Object.getPrototypeOf(headers)
const ownIterator = Object.prototype.hasOwnProperty.call(headers, Symbol.iterator)
return ownIterator || (prototype != null && prototype !== Object.prototype && typeof headers[Symbol.iterator] === 'function')
}
function isHostHeader (key) {
return typeof key === 'string' && key.toLowerCase() === 'host'
}
function normalizeHeaders (headers) {
if (headers == null) {
return null
}
if (Array.isArray(headers)) {
if (headers.length === 0 || !Array.isArray(headers[0])) {
return headers
}
const normalized = []
for (const header of headers) {
if (Array.isArray(header) && header.length === 2) {
normalized.push(header[0], header[1])
} else {
normalized.push(header)
}
}
return normalized
}
if (typeof headers === 'object' && hasSafeIterator(headers)) {
const normalized = []
for (const header of headers) {
if (Array.isArray(header) && header.length === 2) {
normalized.push(header[0], header[1])
} else {
normalized.push(header)
}
}
return normalized
}
return headers
}
function hasHostHeader (headers) {
if (headers == null) {
return false
}
if (Array.isArray(headers)) {
if (headers.length === 0) {
return false
}
for (let i = 0; i < headers.length; i += 2) {
if (isHostHeader(headers[i])) {
return true
}
}
return false
}
if (typeof headers === 'object') {
for (const key in headers) {
if (isHostHeader(key)) {
return true
}
}
}
return false
}
function withHostHeader (host, headers) {
const normalizedHeaders = normalizeHeaders(headers)
if (hasHostHeader(normalizedHeaders)) {
return normalizedHeaders
}
if (Array.isArray(normalizedHeaders)) {
return ['host', host, ...normalizedHeaders]
}
if (normalizedHeaders && typeof normalizedHeaders === 'object') {
return {
host,
...normalizedHeaders
}
}
return { host }
}
class DNSStorage {
#maxItems = 0
#records = new Map()
@@ -333,8 +432,9 @@ class DNSDispatchHandler extends DecoratorHandler {
const dispatchOpts = {
...this.#opts,
origin: `${this.#origin.protocol}//${
ip.family === 6 ? `[${ip.address}]` : ip.address
}${port}`
ip.family === 6 ? `[${ip.address}]` : ip.address
}${port}`,
headers: withHostHeader(this.#origin.host, this.#opts.headers)
}
this.#dispatch(dispatchOpts, this)
return
@@ -453,10 +553,7 @@ module.exports = interceptorOpts => {
...origDispatchOpts,
servername: origin.hostname, // For SNI on TLS
origin: newOrigin.origin,
headers: {
host: origin.host,
...origDispatchOpts.headers
}
headers: withHostHeader(origin.host, origDispatchOpts.headers)
}
dispatch(
+1 -1
View File
@@ -1,5 +1,5 @@
> undici@7.22.0 build:wasm
> undici@7.24.3 build:wasm
> node build/wasm.js --docker
> docker run --rm --platform=linux/x86_64 --user 1001:1001 --mount type=bind,source=/home/runner/work/node/node/deps/undici/src/lib/llhttp,target=/home/node/build/lib/llhttp --mount type=bind,source=/home/runner/work/node/node/deps/undici/src/build,target=/home/node/build/build --mount type=bind,source=/home/runner/work/node/node/deps/undici/src/deps,target=/home/node/build/deps -t ghcr.io/nodejs/wasm-builder@sha256:975f391d907e42a75b8c72eb77c782181e941608687d4d8694c3e9df415a0970 node build/wasm.js
+17 -15
View File
@@ -2,7 +2,8 @@
const {
safeHTTPMethods,
pathHasQueryOrFragment
pathHasQueryOrFragment,
hasSafeIterator
} = require('../core/util')
const { serializePathWithQuery } = require('../core/util')
@@ -37,23 +38,24 @@ function normalizeHeaders (opts) {
let headers
if (opts.headers == null) {
headers = {}
} else if (typeof opts.headers[Symbol.iterator] === 'function') {
headers = {}
for (const x of opts.headers) {
if (!Array.isArray(x)) {
throw new Error('opts.headers is not a valid header map')
}
const [key, val] = x
if (typeof key !== 'string' || typeof val !== 'string') {
throw new Error('opts.headers is not a valid header map')
}
headers[key.toLowerCase()] = val
}
} else if (typeof opts.headers === 'object') {
headers = {}
for (const key of Object.keys(opts.headers)) {
headers[key.toLowerCase()] = opts.headers[key]
if (hasSafeIterator(opts.headers)) {
for (const x of opts.headers) {
if (!Array.isArray(x)) {
throw new Error('opts.headers is not a valid header map')
}
const [key, val] = x
if (typeof key !== 'string' || typeof val !== 'string') {
throw new Error('opts.headers is not a valid header map')
}
headers[key.toLowerCase()] = val
}
} else {
for (const key of Object.keys(opts.headers)) {
headers[key.toLowerCase()] = opts.headers[key]
}
}
} else {
throw new Error('opts.headers is not an object')
+10 -4
View File
@@ -251,7 +251,10 @@ function fetch (input, init = undefined) {
request,
processResponseEndOfBody: handleFetchDone,
processResponse,
dispatcher: getRequestDispatcher(requestObject) // undici
dispatcher: getRequestDispatcher(requestObject), // undici
// Keep requestObject alive to prevent its AbortController from being GC'd
// See https://github.com/nodejs/undici/issues/4627
requestObject
})
// 14. Return p.
@@ -370,7 +373,8 @@ function fetching ({
processResponseEndOfBody,
processResponseConsumeBody,
useParallelQueue = false,
dispatcher = getGlobalDispatcher() // undici
dispatcher = getGlobalDispatcher(), // undici
requestObject = null // Keep alive to prevent AbortController GC, see #4627
}) {
// Ensure that the dispatcher is set accordingly
assert(dispatcher)
@@ -424,7 +428,9 @@ function fetching ({
processResponseConsumeBody,
processResponseEndOfBody,
taskDestination,
crossOriginIsolatedCapability
crossOriginIsolatedCapability,
// Keep requestObject alive to prevent its AbortController from being GC'd
requestObject
}
// 7. If request’s body is a byte sequence, then set request’s body to
@@ -2128,7 +2134,7 @@ async function httpNetworkFetch (
return new Promise((resolve, reject) => agent.dispatch(
{
path: url.pathname + url.search,
path: url.href.slice(url.href.indexOf(url.host) + url.host.length, url.hash.length ? -url.hash.length : undefined),
origin: url.origin,
method: request.method,
body: agent.isMockActive ? request.body && (request.body.source || request.body.stream) : body,
+3
View File
@@ -452,6 +452,9 @@ webidl.interfaceConverter = function (TypeCheck, name) {
}
webidl.dictionaryConverter = function (converters) {
// "For each dictionary member member declared on dictionary, in lexicographical order:"
converters.sort((a, b) => (a.key > b.key) - (a.key < b.key))
return (dictionary, prefix, argument) => {
const dict = {}
+50 -2
View File
@@ -2,17 +2,30 @@
const { createInflateRaw, Z_DEFAULT_WINDOWBITS } = require('node:zlib')
const { isValidClientWindowBits } = require('./util')
const { MessageSizeExceededError } = require('../../core/errors')
const tail = Buffer.from([0x00, 0x00, 0xff, 0xff])
const kBuffer = Symbol('kBuffer')
const kLength = Symbol('kLength')
// Default maximum decompressed message size: 4 MB
const kDefaultMaxDecompressedSize = 4 * 1024 * 1024
class PerMessageDeflate {
/** @type {import('node:zlib').InflateRaw} */
#inflate
#options = {}
/** @type {boolean} */
#aborted = false
/** @type {Function|null} */
#currentCallback = null
/**
* @param {Map<string, string>} extensions
*/
constructor (extensions) {
this.#options.serverNoContextTakeover = extensions.has('server_no_context_takeover')
this.#options.serverMaxWindowBits = extensions.get('server_max_window_bits')
@@ -24,6 +37,11 @@ class PerMessageDeflate {
// payload of the message.
// 2. Decompress the resulting data using DEFLATE.
if (this.#aborted) {
callback(new MessageSizeExceededError())
return
}
if (!this.#inflate) {
let windowBits = Z_DEFAULT_WINDOWBITS
@@ -36,13 +54,37 @@ class PerMessageDeflate {
windowBits = Number.parseInt(this.#options.serverMaxWindowBits)
}
this.#inflate = createInflateRaw({ windowBits })
try {
this.#inflate = createInflateRaw({ windowBits })
} catch (err) {
callback(err)
return
}
this.#inflate[kBuffer] = []
this.#inflate[kLength] = 0
this.#inflate.on('data', (data) => {
this.#inflate[kBuffer].push(data)
if (this.#aborted) {
return
}
this.#inflate[kLength] += data.length
if (this.#inflate[kLength] > kDefaultMaxDecompressedSize) {
this.#aborted = true
this.#inflate.removeAllListeners()
this.#inflate.destroy()
this.#inflate = null
if (this.#currentCallback) {
const cb = this.#currentCallback
this.#currentCallback = null
cb(new MessageSizeExceededError())
}
return
}
this.#inflate[kBuffer].push(data)
})
this.#inflate.on('error', (err) => {
@@ -51,16 +93,22 @@ class PerMessageDeflate {
})
}
this.#currentCallback = callback
this.#inflate.write(chunk)
if (fin) {
this.#inflate.write(tail)
}
this.#inflate.flush(() => {
if (this.#aborted || !this.#inflate) {
return
}
const full = Buffer.concat(this.#inflate[kBuffer], this.#inflate[kLength])
this.#inflate[kBuffer].length = 0
this.#inflate[kLength] = 0
this.#currentCallback = null
callback(null, full)
})
+11 -5
View File
@@ -15,6 +15,7 @@ const {
const { failWebsocketConnection } = require('./connection')
const { WebsocketFrameSend } = require('./frame')
const { PerMessageDeflate } = require('./permessage-deflate')
const { MessageSizeExceededError } = require('../../core/errors')
// This code was influenced by ws released under the MIT license.
// Copyright (c) 2011 Einar Otto Stangvik <einaros@gmail.com>
@@ -38,6 +39,10 @@ class ByteParser extends Writable {
/** @type {import('./websocket').Handler} */
#handler
/**
* @param {import('./websocket').Handler} handler
* @param {Map<string, string>|null} extensions
*/
constructor (handler, extensions) {
super()
@@ -180,6 +185,7 @@ class ByteParser extends Writable {
const buffer = this.consume(8)
const upper = buffer.readUInt32BE(0)
const lower = buffer.readUInt32BE(4)
// 2^31 is the maximum bytes an arraybuffer can contain
// on 32-bit systems. Although, on 64-bit systems, this is
@@ -187,14 +193,12 @@ class ByteParser extends Writable {
// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Errors/Invalid_array_length
// https://source.chromium.org/chromium/chromium/src/+/main:v8/src/common/globals.h;drc=1946212ac0100668f14eb9e2843bdd846e510a1e;bpv=1;bpt=1;l=1275
// https://source.chromium.org/chromium/chromium/src/+/main:v8/src/objects/js-array-buffer.h;l=34;drc=1946212ac0100668f14eb9e2843bdd846e510a1e
if (upper > 2 ** 31 - 1) {
if (upper !== 0 || lower > 2 ** 31 - 1) {
failWebsocketConnection(this.#handler, 1009, 'Received payload length > 2^31 bytes.')
return
}
const lower = buffer.readUInt32BE(4)
this.#info.payloadLength = (upper << 8) + lower
this.#info.payloadLength = lower
this.#state = parserStates.READ_DATA
} else if (this.#state === parserStates.READ_DATA) {
if (this.#byteOffset < this.#info.payloadLength) {
@@ -222,7 +226,9 @@ class ByteParser extends Writable {
} else {
this.#extensions.get('permessage-deflate').decompress(body, this.#info.fin, (error, data) => {
if (error) {
failWebsocketConnection(this.#handler, 1007, error.message)
// Use 1009 (Message Too Big) for decompression size limit errors
const code = error instanceof MessageSizeExceededError ? 1009 : 1007
failWebsocketConnection(this.#handler, code, error.message)
return
}
+9 -1
View File
@@ -227,6 +227,12 @@ function parseExtensions (extensions) {
* @returns {boolean}
*/
function isValidClientWindowBits (value) {
// Must have at least one character
if (value.length === 0) {
return false
}
// Check all characters are ASCII digits
for (let i = 0; i < value.length; i++) {
const byte = value.charCodeAt(i)
@@ -235,7 +241,9 @@ function isValidClientWindowBits (value) {
}
}
return true
// Check numeric range: zlib requires windowBits in range 8-15
const num = Number.parseInt(value, 10)
return num >= 8 && num <= 15
}
/**
+1 -1
View File
@@ -452,7 +452,7 @@ class WebSocket extends EventTarget {
* @see https://websockets.spec.whatwg.org/#feedback-from-the-protocol
*/
#onConnectionEstablished (response, parsedExtensions) {
// processResponse is called when the "response’s header list has been received and initialized."
// processResponse is called when the "response's header list has been received and initialized."
// once this happens, the connection is open
this.#handler.socket = response.socket
+603 -606
View File
File diff suppressed because it is too large. Load diff
+1 -1
View File
@@ -1,6 +1,6 @@
{
"name": "undici",
"version": "7.22.0",
"version": "7.24.3",
"description": "An HTTP/1.1 client, written from scratch for Node.js",
"homepage": "https://undici.nodejs.org",
"bugs": {
+2
View File
@@ -13,6 +13,7 @@ declare namespace buildConnector {
port?: number;
keepAlive?: boolean | null;
keepAliveInitialDelay?: number | null;
typeOfService?: number | null;
}
export interface Options {
@@ -22,6 +23,7 @@ declare namespace buildConnector {
port: string
servername?: string
localAddress?: string | null
socketPath?: string | null
httpSocket?: Socket
}
+7 -5
View File
@@ -96,7 +96,7 @@ declare class Dispatcher extends EventEmitter {
}
declare namespace Dispatcher {
export interface ComposedDispatcher extends Dispatcher {}
export interface ComposedDispatcher extends Dispatcher { }
export type Dispatch = Dispatcher['dispatch']
export type DispatcherComposeInterceptor = (dispatch: Dispatch) => Dispatch
export interface DispatchOptions {
@@ -113,6 +113,8 @@ declare namespace Dispatcher {
idempotent?: boolean;
/** Whether the response is expected to take a long time and would end up blocking the pipeline. When this is set to `true` further pipelining will be avoided on the same connection until headers have been received. Defaults to `method !== 'HEAD'`. */
blocking?: boolean;
/** The IP Type of Service (ToS) value for the request socket. Must be an integer between 0 and 255. Default: `0` */
typeOfService?: number | null;
/** Upgrade the request. Should be used to specify the kind of upgrade i.e. `'Websocket'`. Default: `method === 'CONNECT' || null`. */
upgrade?: boolean | string | null;
/** The amount of time, in milliseconds, the parser will wait to receive the complete HTTP headers. Defaults to 300 seconds. */
@@ -213,10 +215,10 @@ declare namespace Dispatcher {
export type StreamFactory<TOpaque = null> = (data: StreamFactoryData<TOpaque>) => Writable
export interface DispatchController {
get aborted () : boolean
get paused () : boolean
get reason () : Error | null
abort (reason: Error): void
get aborted(): boolean
get paused(): boolean
get reason(): Error | null
abort(reason: Error): void
pause(): void
resume(): void
}
+17 -1
View File
@@ -154,8 +154,24 @@ declare namespace Errors {
code: 'UND_ERR_PRX_TLS'
}
class MaxOriginsReachedError extends UndiciError {
export class MaxOriginsReachedError extends UndiciError {
name: 'MaxOriginsReachedError'
code: 'UND_ERR_MAX_ORIGINS_REACHED'
}
/** SOCKS5 proxy related error. */
export class Socks5ProxyError extends UndiciError {
constructor (
message?: string,
code?: string
)
name: 'Socks5ProxyError'
code: string
}
/** WebSocket decompressed message exceeded maximum size. */
export class MessageSizeExceededError extends UndiciError {
name: 'MessageSizeExceededError'
code: 'UND_ERR_WS_MESSAGE_SIZE_EXCEEDED'
}
}
+4 -1
View File
@@ -18,6 +18,7 @@ import { SnapshotAgent } from './snapshot-agent'
import { MockCallHistory, MockCallHistoryLog } from './mock-call-history'
import mockErrors from './mock-errors'
import ProxyAgent from './proxy-agent'
import Socks5ProxyAgent from './socks5-proxy-agent'
import EnvHttpProxyAgent from './env-http-proxy-agent'
import RetryHandler from './retry-handler'
import RetryAgent from './retry-agent'
@@ -43,7 +44,7 @@ export { Interceptable } from './mock-interceptor'
declare function globalThisInstall (): void
export { Dispatcher, BalancedPool, RoundRobinPool, Pool, Client, buildConnector, errors, Agent, request, stream, pipeline, connect, upgrade, setGlobalDispatcher, getGlobalDispatcher, setGlobalOrigin, getGlobalOrigin, interceptors, cacheStores, MockClient, MockPool, MockAgent, SnapshotAgent, MockCallHistory, MockCallHistoryLog, mockErrors, ProxyAgent, EnvHttpProxyAgent, RedirectHandler, DecoratorHandler, RetryHandler, RetryAgent, H2CClient, globalThisInstall as install }
export { Dispatcher, BalancedPool, RoundRobinPool, Pool, Client, buildConnector, errors, Agent, request, stream, pipeline, connect, upgrade, setGlobalDispatcher, getGlobalDispatcher, setGlobalOrigin, getGlobalOrigin, interceptors, cacheStores, MockClient, MockPool, MockAgent, SnapshotAgent, MockCallHistory, MockCallHistoryLog, mockErrors, ProxyAgent, Socks5ProxyAgent, EnvHttpProxyAgent, RedirectHandler, DecoratorHandler, RetryHandler, RetryAgent, H2CClient, globalThisInstall as install }
export default Undici
declare namespace Undici {
@@ -73,6 +74,8 @@ declare namespace Undici {
const MockCallHistory: typeof import('./mock-call-history').MockCallHistory
const MockCallHistoryLog: typeof import('./mock-call-history').MockCallHistoryLog
const mockErrors: typeof import('./mock-errors').default
const ProxyAgent: typeof import('./proxy-agent').default
const Socks5ProxyAgent: typeof import('./socks5-proxy-agent').default
const fetch: typeof import('./fetch').fetch
const Headers: typeof import('./fetch').Headers
const Response: typeof import('./fetch').Response
+7
View File
@@ -60,6 +60,13 @@ declare namespace Interceptors {
* @default []
*/
excludeHeaderNames?: string[]
/**
* Maximum bytes buffered per paused waiting deduplicated handler.
* If a waiting handler remains paused and exceeds this threshold,
* it is failed with an abort error to prevent unbounded memory growth.
* @default 5 * 1024 * 1024
*/
maxBufferSize?: number
}
export function dump (opts?: DumpInterceptorOpts): Dispatcher.DispatcherComposeInterceptor
+25
View File
@@ -0,0 +1,25 @@
import Dispatcher from './dispatcher'
import buildConnector from './connector'
import { IncomingHttpHeaders } from './header'
import Pool from './pool'
export default Socks5ProxyAgent
declare class Socks5ProxyAgent extends Dispatcher {
constructor (proxyUrl: string | URL, options?: Socks5ProxyAgent.Options)
}
declare namespace Socks5ProxyAgent {
export interface Options extends Pool.Options {
/** Additional headers to send with the proxy connection */
headers?: IncomingHttpHeaders;
/** SOCKS5 proxy username for authentication */
username?: string;
/** SOCKS5 proxy password for authentication */
password?: string;
/** Custom connector function for proxy connection */
connect?: buildConnector.connector;
/** TLS options for the proxy connection (for SOCKS5 over TLS) */
proxyTls?: buildConnector.BuildOptions;
}
}
+861 -35
View File
File diff suppressed because it is too large. Load diff
+1 -1
View File
@@ -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 "7.22.0"
#define UNDICI_VERSION "7.24.3"
#endif // SRC_UNDICI_VERSION_H_