deps: update undici to 8.2.0

PR-URL: https://github.com/nodejs/node/pull/63092
Reviewed-By: Chemi Atlow <chemi@atlow.co.il>
Reviewed-By: Antoine du Hamel <duhamelantoine1995@gmail.com>
Reviewed-By: Rafael Gonzaga <rafael.nunu@hotmail.com>
This commit is contained in:
Node.js GitHub Bot authored and GitHub committed 2026-05-05 01:47:50 +00:00
1 parent 711c022416
commit ee37fcea08
58 files changed
+2042 -995

No files matched your search

-8
View File
@@ -60,11 +60,6 @@ typings/
# next.js build output
.next
# lock files
package-lock.json
yarn.lock
pnpm-lock.yaml
# IDE files
.idea
.vscode
@@ -81,9 +76,6 @@ fuzz-results-*.json
undici-fetch.js
/test/imports/undici-import.js
# .npmrc has platform specific value for windows
.npmrc
.tap
# File generated by /test/request-timeout.js
+1
View File
@@ -0,0 +1 @@
min-release-age=1
+161 -2
View File
@@ -1,2 +1,161 @@
If you believe you have found a security issue in the software in this
repository, please consult https://github.com/nodejs/node/blob/HEAD/SECURITY.md.
# Security
## Reporting a vulnerability in undici
Report security bugs in undici via
[GitHub Security Advisories](https://github.com/nodejs/undici/security/advisories/new)
or [HackerOne](https://hackerone.com/nodejs).
Your report will normally be acknowledged within 5 days, and you will receive
a more detailed response within 10 days indicating the next steps in handling
your submission. These timelines may extend when our triage volunteers are
away, particularly at the end of the year.
After the initial reply to your report, the security team will endeavor to keep
you informed of the progress being made towards a fix and full announcement,
and may ask for additional information or guidance surrounding the reported
issue.
## Disclosure policy
* The security report is received and assigned a primary handler. The problem
is validated against all supported versions of undici. Once confirmed, a list
of all affected versions is determined. Code is audited to find any potential
similar problems. Fixes are prepared for all supported releases. These fixes
are not committed to the public repository but rather held locally pending
the announcement.
* Because undici is bundled into Node.js, security releases are often
coordinated with the Node.js project to avoid leaving Node.js users
vulnerable. As a result, fixed versions of undici are published to npm
before the corresponding CVE is disclosed, since the CVE will only be
published after the coordinated Node.js release. This delay is typically
a few days but can take up to a week.
## The undici threat model
Undici is an HTTP client library for Node.js. Its threat model is derived from
and aligned with the [Node.js threat model](https://github.com/nodejs/node/blob/HEAD/SECURITY.md#the-nodejs-threat-model).
### What constitutes a vulnerability
Being able to cause the following through control of the elements that undici
does not trust is considered a vulnerability:
* Disclosure or loss of integrity or confidentiality of data protected through
the correct use of undici APIs.
* The unavailability of the runtime, including the unbounded degradation of its
performance.
#### Denial of Service (DoS) vulnerabilities
For a behavior to be considered a DoS vulnerability, the proof of concept must
meet the following criteria:
* The API is being correctly used.
* The API is public and documented.
* The behavior is significant enough to cause a denial of service quickly
or in a context not controlled by the application developer (for example,
HTTP parsing).
* The behavior is directly exploitable by an untrusted source without requiring
application mistakes.
* The behavior cannot be reasonably mitigated through standard operational
practices (like process recycling).
* The attack demonstrates
[asymmetric resource consumption](https://cwe.mitre.org/data/definitions/405.html),
where the attacker expends significantly fewer resources than what is required
by the client to process the attack.
**Undici does NOT trust**:
* Data received from the remote end of HTTP connections (both inbound responses
and server-sent data) that is parsed or transformed by undici before being
passed to the application. This includes:
* HTTP response headers and status lines.
* HTTP response bodies when processed by undici (e.g., chunked transfer
decoding, content-encoding).
* WebSocket frames received from a server.
* Server-Sent Events (EventSource) data received from a server.
* TLS certificate validation performed by undici on behalf of the application.
**Undici trusts**:
* The application code that uses its APIs, including all configuration,
options, and callbacks provided by the application.
* The operating system and its network stack.
* The Node.js runtime undici is running on.
* Dependencies installed by the application.
* The DNS resolution results provided by the operating system or configured
resolvers.
In other words, if untrusted data passing through undici to the application
can trigger actions other than those documented for the APIs, there is likely
a security vulnerability. Examples of unwanted actions are polluting globals,
causing an unrecoverable crash, or any other unexpected side effects that can
lead to a loss of confidentiality, integrity, or availability.
### Examples of vulnerabilities
#### Improper Certificate Validation (CWE-295)
* Undici provides TLS connections to HTTPS endpoints. If certificates can be
crafted that result in incorrect validation by undici, that is considered
a vulnerability.
#### Inconsistent Interpretation of HTTP Responses (CWE-444)
* Undici parses HTTP responses received from servers. Bugs in parsing response
headers or transfer encoding which can result in response smuggling or
desynchronization are considered vulnerabilities.
#### HTTP Request Smuggling (CWE-444)
* Bugs that allow crafting requests that are interpreted differently by undici
and an upstream server, leading to request smuggling, are considered
vulnerabilities.
#### CRLF Injection in Request Headers (CWE-93)
* If untrusted input passed to undici APIs (such as header values or URLs)
can inject additional headers or corrupt the HTTP request stream, that is
considered a vulnerability.
### Examples of non-vulnerabilities
#### Malicious Third-Party Modules (CWE-1357)
* Application code and its dependencies are trusted by undici. Any scenario
that requires a malicious third-party module cannot result in a vulnerability
in undici.
#### Prototype Pollution Attacks (CWE-1321)
* Undici trusts the inputs provided to it by application code. It is up to the
application to sanitize appropriately. Any scenario that requires control
over user input passed directly by the application is not considered a
vulnerability in undici.
#### Uncontrolled Resource Consumption on Outbound Connections (CWE-400)
* If undici is asked to connect to a remote site and the response payload is
large enough to impact performance or cause the runtime to run out of
resources, that is not considered a vulnerability. Applications are
responsible for setting appropriate limits on response sizes.
#### Application Misconfiguration
* Issues arising from incorrect or insecure use of undici APIs (such as
disabling TLS verification, ignoring errors, or passing unsanitized user
input to request options) are the application's responsibility, not
vulnerabilities in undici.
## Receiving security updates
Security notifications will be distributed via
[GitHub Security Advisories](https://github.com/nodejs/undici/security/advisories).
## Comments on this policy
If you have suggestions on how this process could be improved, please open an
issue on the [nodejs/undici](https://github.com/nodejs/undici/issues)
repository or file a pull request.
+11 -11
View File
@@ -4,7 +4,7 @@
#define LLHTTP_VERSION_MAJOR 9
#define LLHTTP_VERSION_MINOR 3
#define LLHTTP_VERSION_PATCH 0
#define LLHTTP_VERSION_PATCH 1
#ifndef INCLUDE_LLHTTP_ITSELF_H_
#define INCLUDE_LLHTTP_ITSELF_H_
@@ -58,10 +58,8 @@ enum llhttp_errno {
HPE_OK = 0,
HPE_INTERNAL = 1,
HPE_STRICT = 2,
HPE_CR_EXPECTED = 25,
HPE_LF_EXPECTED = 3,
HPE_UNEXPECTED_CONTENT_LENGTH = 4,
HPE_UNEXPECTED_SPACE = 30,
HPE_CLOSED_CONNECTION = 5,
HPE_INVALID_METHOD = 6,
HPE_INVALID_URL = 7,
@@ -82,15 +80,17 @@ enum llhttp_errno {
HPE_PAUSED_UPGRADE = 22,
HPE_PAUSED_H2_UPGRADE = 23,
HPE_USER = 24,
HPE_CR_EXPECTED = 25,
HPE_CB_URL_COMPLETE = 26,
HPE_CB_STATUS_COMPLETE = 27,
HPE_CB_METHOD_COMPLETE = 32,
HPE_CB_VERSION_COMPLETE = 33,
HPE_CB_HEADER_FIELD_COMPLETE = 28,
HPE_CB_HEADER_VALUE_COMPLETE = 29,
HPE_UNEXPECTED_SPACE = 30,
HPE_CB_RESET = 31,
HPE_CB_METHOD_COMPLETE = 32,
HPE_CB_VERSION_COMPLETE = 33,
HPE_CB_CHUNK_EXTENSION_NAME_COMPLETE = 34,
HPE_CB_CHUNK_EXTENSION_VALUE_COMPLETE = 35,
HPE_CB_RESET = 31,
HPE_CB_PROTOCOL_COMPLETE = 38
};
typedef enum llhttp_errno llhttp_errno_t;
@@ -294,10 +294,8 @@ typedef enum llhttp_status llhttp_status_t;
XX(0, OK, OK) \
XX(1, INTERNAL, INTERNAL) \
XX(2, STRICT, STRICT) \
XX(25, CR_EXPECTED, CR_EXPECTED) \
XX(3, LF_EXPECTED, LF_EXPECTED) \
XX(4, UNEXPECTED_CONTENT_LENGTH, UNEXPECTED_CONTENT_LENGTH) \
XX(30, UNEXPECTED_SPACE, UNEXPECTED_SPACE) \
XX(5, CLOSED_CONNECTION, CLOSED_CONNECTION) \
XX(6, INVALID_METHOD, INVALID_METHOD) \
XX(7, INVALID_URL, INVALID_URL) \
@@ -318,15 +316,17 @@ typedef enum llhttp_status llhttp_status_t;
XX(22, PAUSED_UPGRADE, PAUSED_UPGRADE) \
XX(23, PAUSED_H2_UPGRADE, PAUSED_H2_UPGRADE) \
XX(24, USER, USER) \
XX(25, CR_EXPECTED, CR_EXPECTED) \
XX(26, CB_URL_COMPLETE, CB_URL_COMPLETE) \
XX(27, CB_STATUS_COMPLETE, CB_STATUS_COMPLETE) \
XX(32, CB_METHOD_COMPLETE, CB_METHOD_COMPLETE) \
XX(33, CB_VERSION_COMPLETE, CB_VERSION_COMPLETE) \
XX(28, CB_HEADER_FIELD_COMPLETE, CB_HEADER_FIELD_COMPLETE) \
XX(29, CB_HEADER_VALUE_COMPLETE, CB_HEADER_VALUE_COMPLETE) \
XX(30, UNEXPECTED_SPACE, UNEXPECTED_SPACE) \
XX(31, CB_RESET, CB_RESET) \
XX(32, CB_METHOD_COMPLETE, CB_METHOD_COMPLETE) \
XX(33, CB_VERSION_COMPLETE, CB_VERSION_COMPLETE) \
XX(34, CB_CHUNK_EXTENSION_NAME_COMPLETE, CB_CHUNK_EXTENSION_NAME_COMPLETE) \
XX(35, CB_CHUNK_EXTENSION_VALUE_COMPLETE, CB_CHUNK_EXTENSION_VALUE_COMPLETE) \
XX(31, CB_RESET, CB_RESET) \
XX(38, CB_PROTOCOL_COMPLETE, CB_PROTOCOL_COMPLETE) \
+13 -9
View File
@@ -10,7 +10,7 @@
#endif /* _MSC_VER */
#endif /* __SSE4_2__ */
#ifdef __ARM_NEON__
#if defined(__ARM_NEON__) || defined(__ARM_NEON)
#include <arm_neon.h>
#endif /* __ARM_NEON__ */
@@ -1542,7 +1542,7 @@ static llparse_state_t llhttp__internal__run(
1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 3, 1, 1, 1,
1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0,
1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
@@ -2625,7 +2625,7 @@ static llparse_state_t llhttp__internal__run(
goto s_n_llhttp__internal__n_header_value_otherwise;
}
#endif /* __SSE4_2__ */
#ifdef __ARM_NEON__
#if defined(__ARM_NEON__) || defined(__ARM_NEON)
while (endp - p >= 16) {
uint8x16_t input;
uint8x16_t single;
@@ -2639,19 +2639,23 @@ static llparse_state_t llhttp__internal__run(
/* Find first character that does not match `ranges` */
single = vceqq_u8(input, vdupq_n_u8(0x9));
mask = single;
single = vandq_u16(
single = vandq_u8(
vcgeq_u8(input, vdupq_n_u8(' ')),
vcleq_u8(input, vdupq_n_u8('~'))
);
mask = vorrq_u16(mask, single);
single = vandq_u16(
mask = vorrq_u8(mask, single);
single = vandq_u8(
vcgeq_u8(input, vdupq_n_u8(0x80)),
vcleq_u8(input, vdupq_n_u8(0xff))
);
mask = vorrq_u16(mask, single);
narrow = vshrn_n_u16(mask, 4);
mask = vorrq_u8(mask, single);
narrow = vshrn_n_u16(vreinterpretq_u16_u8(mask), 4);
match_mask = ~vget_lane_u64(vreinterpret_u64_u8(narrow), 0);
match_len = __builtin_ctzll(match_mask) >> 2;
if (match_mask == 0) {
match_len = 16;
} else {
match_len = __builtin_ctzll(match_mask) >> 2;
}
if (match_len != 16) {
p += match_len;
goto s_n_llhttp__internal__n_header_value_otherwise;
+2 -2
View File
@@ -1354,10 +1354,10 @@ Emitted when dispatcher is no longer busy.
## Parameter: `UndiciHeaders`
* `Record<string, string | string[] | undefined> | string[] | Iterable<[string, string | string[] | undefined]> | null`
* `Record<string, number | string | string[] | undefined> | string[] | Iterable<[string, string | string[] | undefined]> | null`
Header arguments such as `options.headers` in [`Client.dispatch`](/docs/docs/api/Client.md#clientdispatchoptions-handlers) can be specified in three forms:
* As an object specified by the `Record<string, string | string[] | undefined>` (`IncomingHttpHeaders`) type.
* As an object specified by the `Record<string, number | string | string[] | undefined>` (`OutgoingHttpHeaders`) type.
* As an array of strings. An array representation of a header list must have an even length, or an `InvalidArgumentError` will be thrown.
* As an iterable that can encompass `Headers`, `Map`, or a custom iterator returning key-value pairs.
Keys are lowercase and values are not modified.
+1 -1
View File
@@ -60,7 +60,7 @@ class ConnectHandler extends AsyncResource {
// Indicates is an HTTP2Session
if (responseHeaders != null) {
responseHeaders = this.responseHeaders === 'raw'
? (Array.isArray(rawHeaders) ? util.parseRawHeaders(rawHeaders) : [])
? util.parseRawHeaders(rawHeaders)
: headers
}
+2 -2
View File
@@ -167,7 +167,7 @@ class PipelineHandler extends AsyncResource {
if (this.onInfo) {
const rawHeaders = controller?.rawHeaders
const responseHeaders = this.responseHeaders === 'raw'
? (Array.isArray(rawHeaders) ? util.parseRawHeaders(rawHeaders) : [])
? util.parseRawHeaders(rawHeaders)
: headers
this.onInfo({ statusCode, headers: responseHeaders })
}
@@ -181,7 +181,7 @@ class PipelineHandler extends AsyncResource {
this.handler = null
const rawHeaders = controller?.rawHeaders
const responseHeaders = this.responseHeaders === 'raw'
? (Array.isArray(rawHeaders) ? util.parseRawHeaders(rawHeaders) : [])
? util.parseRawHeaders(rawHeaders)
: headers
body = this.runInAsyncScope(handler, null, {
statusCode,
+2 -2
View File
@@ -21,7 +21,7 @@ class RequestHandler extends AsyncResource {
throw new InvalidArgumentError('invalid callback')
}
if (highWaterMark && (typeof highWaterMark !== 'number' || highWaterMark < 0)) {
if (highWaterMark != null && (!Number.isFinite(highWaterMark) || highWaterMark < 0)) {
throw new InvalidArgumentError('invalid highWaterMark')
}
@@ -92,7 +92,7 @@ class RequestHandler extends AsyncResource {
const rawHeaders = controller?.rawHeaders
const responseHeaderData = responseHeaders === 'raw'
? (Array.isArray(rawHeaders) ? util.parseRawHeaders(rawHeaders) : [])
? util.parseRawHeaders(rawHeaders)
: headers
if (statusCode < 200) {
+1 -1
View File
@@ -85,7 +85,7 @@ class StreamHandler extends AsyncResource {
const rawHeaders = controller?.rawHeaders
const responseHeaderData = responseHeaders === 'raw'
? (Array.isArray(rawHeaders) ? util.parseRawHeaders(rawHeaders) : [])
? util.parseRawHeaders(rawHeaders)
: headers
if (statusCode < 200) {
+8 -2
View File
@@ -51,7 +51,13 @@ class UpgradeHandler extends AsyncResource {
}
onRequestUpgrade (controller, statusCode, headers, socket) {
assert(socket[kHTTP2Stream] === true ? statusCode === 200 : statusCode === 101)
const expectedStatusCode = socket[kHTTP2Stream] === true ? 200 : 101
if (statusCode !== expectedStatusCode) {
const socketInfo = socket[kHTTP2Stream] === true ? null : util.getSocketInfo(socket)
controller.abort(new SocketError('bad upgrade', socketInfo))
return
}
const { callback, opaque, context } = this
@@ -61,7 +67,7 @@ class UpgradeHandler extends AsyncResource {
const rawHeaders = controller?.rawHeaders
const responseHeaders = this.responseHeaders === 'raw'
? (Array.isArray(rawHeaders) ? util.parseRawHeaders(rawHeaders) : [])
? util.parseRawHeaders(rawHeaders)
: headers
this.runInAsyncScope(callback, null, null, {
+3 -2
View File
@@ -1,6 +1,7 @@
'use strict'
const assert = require('node:assert')
const { addAbortListener } = require('node:events')
const { Readable } = require('node:stream')
const { RequestAbortedError, NotSupportedError, InvalidArgumentError, AbortError } = require('../core/errors')
const util = require('../core/util')
@@ -293,10 +294,10 @@ class BodyReadable extends Readable {
const onAbort = () => {
this.destroy(signal.reason ?? new AbortError())
}
signal.addEventListener('abort', onAbort)
const abortListener = addAbortListener(signal, onAbort)
this
.on('close', function () {
signal.removeEventListener('abort', onAbort)
abortListener[Symbol.dispose]()
if (signal.aborted) {
reject(signal.reason ?? new AbortError())
} else {
+1 -1
View File
@@ -138,7 +138,7 @@ class MemoryCacheStore extends EventEmitter {
entry.size += chunk.byteLength
if (entry.size >= store.#maxEntrySize) {
if (entry.size > store.#maxEntrySize) {
this.destroy()
} else {
entry.body.push(chunk)
+6 -4
View File
@@ -173,6 +173,7 @@ module.exports = class SqliteCacheStore {
headers = ?,
etag = ?,
cacheControlDirectives = ?,
vary = ?,
cachedAt = ?,
staleAt = ?
WHERE
@@ -216,7 +217,7 @@ module.exports = class SqliteCacheStore {
SELECT
id
FROM cacheInterceptorV${VERSION}
ORDER BY cachedAt DESC
ORDER BY cachedAt ASC
LIMIT ?
)
`)
@@ -278,12 +279,12 @@ module.exports = class SqliteCacheStore {
value.headers ? JSON.stringify(value.headers) : null,
value.etag ? value.etag : null,
value.cacheControlDirectives ? JSON.stringify(value.cacheControlDirectives) : null,
value.vary ? JSON.stringify(value.vary) : null,
value.cachedAt,
value.staleAt,
existingValue.id
)
} else {
this.#prune()
// New response, let's insert it
this.#insertValueQuery.run(
url,
@@ -299,6 +300,7 @@ module.exports = class SqliteCacheStore {
value.cachedAt,
value.staleAt
)
this.#prune()
}
}
@@ -323,7 +325,7 @@ module.exports = class SqliteCacheStore {
write (chunk, encoding, callback) {
size += chunk.byteLength
if (size < store.#maxEntrySize) {
if (size <= store.#maxEntrySize) {
body.push(chunk)
} else {
this.destroy()
@@ -409,7 +411,7 @@ module.exports = class SqliteCacheStore {
const now = Date.now()
for (const value of values) {
if (now >= value.deleteAt && !canBeExpired) {
return undefined
continue
}
let matches = true
+16
View File
@@ -38,6 +38,22 @@ const SessionCache = class WeakSessionCache {
return
}
if (this._sessionCache.has(sessionKey)) {
this._sessionCache.delete(sessionKey)
} else if (this._sessionCache.size >= this._maxCachedSessions) {
for (const [key, ref] of this._sessionCache) {
if (ref.deref() === undefined) {
this._sessionCache.delete(key)
return
}
}
const oldest = this._sessionCache.keys().next()
if (!oldest.done) {
this._sessionCache.delete(oldest.value)
}
}
this._sessionCache.set(sessionKey, new WeakRef(session))
this._sessionRegistry.register(session, sessionKey)
}
+1 -24
View File
@@ -107,28 +107,6 @@ const headerNameLowerCasedRecord = {}
// Note: object prototypes should not be able to be referenced. e.g. `Object#hasOwnProperty`.
Object.setPrototypeOf(headerNameLowerCasedRecord, null)
/**
* @type {Record<Lowercase<typeof wellknownHeaderNames[number]>, Buffer>}
*/
const wellknownHeaderNameBuffers = {}
// Note: object prototypes should not be able to be referenced. e.g. `Object#hasOwnProperty`.
Object.setPrototypeOf(wellknownHeaderNameBuffers, null)
/**
* @param {string} header Lowercased header
* @returns {Buffer}
*/
function getHeaderNameAsBuffer (header) {
let buffer = wellknownHeaderNameBuffers[header]
if (buffer === undefined) {
buffer = Buffer.from(header)
}
return buffer
}
for (let i = 0; i < wellknownHeaderNames.length; ++i) {
const key = wellknownHeaderNames[i]
const lowerCasedKey = key.toLowerCase()
@@ -138,6 +116,5 @@ for (let i = 0; i < wellknownHeaderNames.length; ++i) {
module.exports = {
wellknownHeaderNames,
headerNameLowerCasedRecord,
getHeaderNameAsBuffer
headerNameLowerCasedRecord
}
+2 -2
View File
@@ -163,8 +163,8 @@ class RequestAbortedError extends AbortError {
const kInformationalError = Symbol.for('undici.error.UND_ERR_INFO')
class InformationalError extends UndiciError {
constructor (message) {
super(message)
constructor (message, options) {
super(message, options)
this.name = 'InformationalError'
this.message = message || 'Request information'
this.code = 'UND_ERR_INFO'
+17 -2
View File
@@ -28,6 +28,21 @@ const { headerNameLowerCasedRecord } = require('./constants')
// Verifies that a given path is valid does not contain control chars \x00 to \x20
const invalidPathRegex = /[^\u0021-\u00ff]/
function isValidContentLengthHeaderValue (val) {
if (typeof val !== 'string' || val.length === 0) {
return false
}
for (let i = 0; i < val.length; i++) {
const charCode = val.charCodeAt(i)
if (charCode < 48 || charCode > 57) {
return false
}
}
return true
}
const kHandler = Symbol('handler')
const kController = Symbol('controller')
const kResume = Symbol('resume')
@@ -484,10 +499,10 @@ function processHeader (request, key, val) {
if (request.contentLength !== null) {
throw new InvalidArgumentError('duplicate content-length header')
}
request.contentLength = parseInt(val, 10)
if (!Number.isFinite(request.contentLength)) {
if (!isValidContentLengthHeaderValue(val)) {
throw new InvalidArgumentError('invalid content-length header')
}
request.contentLength = parseInt(val, 10)
} else if (request.contentType === null && headerName === 'content-type') {
request.contentType = val
request.headers.push(key, val)
+24 -9
View File
@@ -7,6 +7,7 @@ const { debuglog } = require('node:util')
const { parseAddress } = require('./socks5-utils')
const debug = debuglog('undici:socks5')
const EMPTY_BUFFER = Buffer.alloc(0)
// SOCKS5 constants
const SOCKS_VERSION = 0x05
@@ -51,6 +52,7 @@ const STATES = {
INITIAL: 'initial',
HANDSHAKING: 'handshaking',
AUTHENTICATING: 'authenticating',
AUTHENTICATED: 'authenticated',
CONNECTING: 'connecting',
CONNECTED: 'connected',
ERROR: 'error',
@@ -72,7 +74,10 @@ class Socks5Client extends EventEmitter {
this.socket = socket
this.options = options
this.state = STATES.INITIAL
this.buffer = Buffer.alloc(0)
this.buffer = EMPTY_BUFFER
this.onSocketData = this.onData.bind(this)
this.onSocketError = this.onError.bind(this)
this.onSocketClose = this.onClose.bind(this)
// Authentication settings
this.authMethods = []
@@ -82,9 +87,9 @@ class Socks5Client extends EventEmitter {
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))
this.socket.on('data', this.onSocketData)
this.socket.on('error', this.onSocketError)
this.socket.on('close', this.onSocketClose)
}
/**
@@ -139,6 +144,11 @@ class Socks5Client extends EventEmitter {
}
}
markAuthenticated () {
this.state = STATES.AUTHENTICATED
this.emit('authenticated')
}
/**
* Start the SOCKS5 handshake
*/
@@ -189,7 +199,7 @@ class Socks5Client extends EventEmitter {
debug('server selected auth method', method)
if (method === AUTH_METHODS.NO_AUTH) {
this.emit('authenticated')
this.markAuthenticated()
} else if (method === AUTH_METHODS.USERNAME_PASSWORD) {
this.state = STATES.AUTHENTICATING
this.sendAuthRequest()
@@ -254,7 +264,7 @@ class Socks5Client extends EventEmitter {
this.buffer = this.buffer.subarray(2)
debug('authentication successful')
this.emit('authenticated')
this.markAuthenticated()
}
/**
@@ -263,8 +273,12 @@ class Socks5Client extends EventEmitter {
* @param {number} port - Target port
*/
connect (address, port) {
if (this.state === STATES.CONNECTED) {
throw new InvalidArgumentError('Already connected')
if (this.state === STATES.CONNECTING || this.state === STATES.CONNECTED) {
throw new InvalidArgumentError('Connection already in progress')
}
if (this.state !== STATES.AUTHENTICATED) {
throw new InvalidArgumentError('Client must be authenticated before CONNECT')
}
debug('connecting to', address, port)
@@ -363,8 +377,9 @@ class Socks5Client extends EventEmitter {
const boundPort = this.buffer.readUInt16BE(offset)
this.buffer = this.buffer.subarray(responseLength)
this.buffer = EMPTY_BUFFER
this.state = STATES.CONNECTED
this.socket.removeListener('data', this.onSocketData)
debug('connected, bound address:', boundAddress, 'port:', boundPort)
this.emit('connected', { address: boundAddress, port: boundPort })
+31 -22
View File
@@ -46,34 +46,43 @@ function parseAddress (address) {
*/
function parseIPv6 (address) {
const buffer = Buffer.alloc(16)
const parts = address.split(':')
let partIndex = 0
let bufferIndex = 0
let normalizedAddress = address
// Expand an embedded IPv4 tail into the last two IPv6 groups.
if (address.includes('.')) {
const lastColonIndex = address.lastIndexOf(':')
const ipv4Part = address.slice(lastColonIndex + 1)
if (net.isIPv4(ipv4Part)) {
const octets = ipv4Part.split('.').map(Number)
const high = ((octets[0] << 8) | octets[1]).toString(16)
const low = ((octets[2] << 8) | octets[3]).toString(16)
normalizedAddress = `${address.slice(0, lastColonIndex)}:${high}:${low}`
}
}
// Handle compressed notation (::)
const doubleColonIndex = address.indexOf('::')
const doubleColonIndex = normalizedAddress.indexOf('::')
if (doubleColonIndex !== -1) {
// Count non-empty parts
const nonEmptyParts = parts.filter(p => p.length > 0).length
const skipParts = 8 - nonEmptyParts
const before = normalizedAddress.slice(0, doubleColonIndex)
const after = normalizedAddress.slice(doubleColonIndex + 2)
const beforeParts = before === '' ? [] : before.split(':')
const afterParts = after === '' ? [] : after.split(':')
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
}
let bufferIndex = 0
for (const part of beforeParts) {
buffer.writeUInt16BE(parseInt(part, 16), bufferIndex)
bufferIndex += 2
}
bufferIndex = 16 - afterParts.length * 2
for (const part of afterParts) {
buffer.writeUInt16BE(parseInt(part, 16), 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++
const parts = normalizedAddress.split(':')
for (let i = 0; i < parts.length; i++) {
buffer.writeUInt16BE(parseInt(parts[i], 16), i * 2)
}
}
+28 -3
View File
@@ -6,7 +6,7 @@ const { IncomingMessage } = require('node:http')
const stream = require('node:stream')
const net = require('node:net')
const { stringify } = require('node:querystring')
const { EventEmitter: EE } = require('node:events')
const { EventEmitter: EE, addAbortListener: addAbortListenerNative } = require('node:events')
const timers = require('../util/timers')
const { InvalidArgumentError, ConnectTimeoutError } = require('./errors')
const { headerNameLowerCasedRecord } = require('./constants')
@@ -464,10 +464,30 @@ function parseHeaders (headers, obj) {
}
/**
* @param {Buffer[]} headers
* @param {Buffer[] | string[] | Record<string, string | string[]> | null | undefined} headers
* @returns {string[]}
*/
function parseRawHeaders (headers) {
if (headers == null) {
return []
}
if (!Array.isArray(headers)) {
const rawHeaders = []
for (const [name, value] of Object.entries(headers)) {
if (Array.isArray(value)) {
for (const entry of value) {
rawHeaders.push(name, `${entry}`)
}
} else {
rawHeaders.push(name, `${value}`)
}
}
return rawHeaders
}
const headersLength = headers.length
/**
* @type {string[]}
@@ -678,7 +698,12 @@ function isFormDataLike (object) {
}
function addAbortListener (signal, listener) {
if ('addEventListener' in signal) {
if (signal instanceof AbortSignal) {
const disposable = addAbortListenerNative(signal, listener)
return () => disposable[Symbol.dispose]()
}
if (typeof signal.addEventListener === 'function') {
signal.addEventListener('abort', listener, { once: true })
return () => signal.removeEventListener('abort', listener)
}
+39 -41
View File
@@ -1,7 +1,7 @@
'use strict'
const { InvalidArgumentError, MaxOriginsReachedError } = require('../core/errors')
const { kClients, kRunning, kClose, kDestroy, kDispatch, kUrl } = require('../core/symbols')
const { kBusy, kClients, kConnected, kRunning, kClose, kDestroy, kDispatch, kUrl } = require('../core/symbols')
const DispatcherBase = require('./dispatcher-base')
const Pool = require('./pool')
const Client = require('./client')
@@ -65,7 +65,7 @@ class Agent extends DispatcherBase {
get [kRunning] () {
let ret = 0
for (const { dispatcher } of this[kClients].values()) {
for (const dispatcher of this[kClients].values()) {
ret += dispatcher[kRunning]
}
return ret
@@ -86,54 +86,52 @@ class Agent extends DispatcherBase {
throw new MaxOriginsReachedError()
}
const result = this[kClients].get(key)
let dispatcher = result && result.dispatcher
let dispatcher = this[kClients].get(key)
if (!dispatcher) {
const closeClientIfUnused = (connected) => {
const result = this[kClients].get(key)
if (result) {
if (connected) result.count -= 1
if (result.count <= 0) {
this[kClients].delete(key)
if (!result.dispatcher.destroyed) {
result.dispatcher.close()
}
}
let hasOrigin = false
for (const entry of this[kClients].values()) {
if (entry.origin === origin) {
hasOrigin = true
break
}
}
if (!hasOrigin) {
this[kOrigins].delete(origin)
}
}
}
dispatcher = this[kFactory](opts.origin, allowH2 === false
? { ...this[kOptions], allowH2: false }
: this[kOptions])
.on('drain', this[kOnDrain])
.on('connect', (origin, targets) => {
const result = this[kClients].get(key)
if (result) {
result.count += 1
const closeClientIfUnused = () => {
if (this[kClients].get(key) !== dispatcher) {
return
}
if (dispatcher[kConnected] > 0 || dispatcher[kBusy]) {
return
}
this[kClients].delete(key)
if (!dispatcher.destroyed) {
dispatcher.close()
}
let hasOrigin = false
for (const client of this[kClients].values()) {
if (client[kUrl].origin === dispatcher[kUrl].origin) {
hasOrigin = true
break
}
this[kOnConnect](origin, targets)
})
}
if (!hasOrigin) {
this[kOrigins].delete(dispatcher[kUrl].origin)
}
}
dispatcher
.on('drain', this[kOnDrain])
.on('connect', this[kOnConnect])
.on('disconnect', (origin, targets, err) => {
closeClientIfUnused(true)
closeClientIfUnused()
this[kOnDisconnect](origin, targets, err)
})
.on('connectionError', (origin, targets, err) => {
closeClientIfUnused(false)
closeClientIfUnused()
this[kOnConnectionError](origin, targets, err)
})
this[kClients].set(key, { count: 0, dispatcher, origin })
this[kClients].set(key, dispatcher)
this[kOrigins].add(origin)
}
@@ -142,7 +140,7 @@ class Agent extends DispatcherBase {
[kClose] () {
const closePromises = []
for (const { dispatcher } of this[kClients].values()) {
for (const dispatcher of this[kClients].values()) {
closePromises.push(dispatcher.close())
}
this[kClients].clear()
@@ -152,7 +150,7 @@ class Agent extends DispatcherBase {
[kDestroy] (err) {
const destroyPromises = []
for (const { dispatcher } of this[kClients].values()) {
for (const dispatcher of this[kClients].values()) {
destroyPromises.push(dispatcher.destroy(err))
}
this[kClients].clear()
@@ -162,7 +160,7 @@ class Agent extends DispatcherBase {
get stats () {
const allClientStats = {}
for (const { dispatcher } of this[kClients].values()) {
for (const dispatcher of this[kClients].values()) {
if (dispatcher.stats) {
allClientStats[dispatcher[kUrl].origin] = dispatcher.stats
}
+21 -23
View File
@@ -164,35 +164,14 @@ class BalancedPool extends PoolBase {
throw new BalancedPoolMissingUpstreamError()
}
const dispatcher = this[kClients].find(dispatcher => (
!dispatcher[kNeedDrain] &&
dispatcher.closed !== true &&
dispatcher.destroyed !== true
))
if (!dispatcher) {
return
}
const allClientsBusy = this[kClients].map(pool => pool[kNeedDrain]).reduce((a, b) => a && b, true)
if (allClientsBusy) {
return
}
let counter = 0
let maxWeightIndex = this[kClients].findIndex(pool => !pool[kNeedDrain])
let maxWeightIndex = -1
while (counter++ < this[kClients].length) {
this[kIndex] = (this[kIndex] + 1) % this[kClients].length
const pool = this[kClients][this[kIndex]]
// find pool index with the largest weight
if (pool[kWeight] > this[kClients][maxWeightIndex][kWeight] && !pool[kNeedDrain]) {
maxWeightIndex = this[kIndex]
}
// decrease the current weight every `this[kClients].length`.
if (this[kIndex] === 0) {
// Set the current weight to the next lower weight.
@@ -202,11 +181,30 @@ class BalancedPool extends PoolBase {
this[kCurrentWeight] = this[kMaxWeightPerServer]
}
}
if (pool[kWeight] >= this[kCurrentWeight] && (!pool[kNeedDrain])) {
// Skip unavailable pools after updating the current weight for this cycle.
if (
pool[kNeedDrain] ||
pool.closed === true ||
pool.destroyed === true
) {
continue
}
// Track the best fallback if no pool matches the current weight.
if (maxWeightIndex === -1 || pool[kWeight] > this[kClients][maxWeightIndex][kWeight]) {
maxWeightIndex = this[kIndex]
}
if (pool[kWeight] >= this[kCurrentWeight]) {
return pool
}
}
if (maxWeightIndex === -1) {
return
}
this[kCurrentWeight] = this[kClients][maxWeightIndex][kWeight]
this[kIndex] = maxWeightIndex
return this[kClients][maxWeightIndex]
+34 -16
View File
@@ -69,9 +69,9 @@ function lazyllhttp () {
let useWasmSIMD = process.arch !== 'ppc64'
// The Env Variable UNDICI_NO_WASM_SIMD allows explicitly overriding the default behavior
if (process.env.UNDICI_NO_WASM_SIMD === '1') {
useWasmSIMD = true
} else if (process.env.UNDICI_NO_WASM_SIMD === '0') {
useWasmSIMD = false
} else if (process.env.UNDICI_NO_WASM_SIMD === '0') {
useWasmSIMD = true
}
if (useWasmSIMD) {
@@ -188,6 +188,7 @@ let currentBufferRef = null
*/
let currentBufferSize = 0
let currentBufferPtr = null
let currentBuffer = null
const USE_NATIVE_TIMER = 0
const USE_FAST_TIMER = 1
@@ -216,6 +217,7 @@ class Parser {
*/
this.socket = socket
this.timeout = null
this.timeoutWeakRef = new WeakRef(this)
this.timeoutValue = null
this.timeoutType = null
this.statusCode = 0
@@ -231,8 +233,8 @@ class Parser {
this.bytesRead = 0
this.keepAlive = ''
this.contentLength = ''
this.connection = ''
this.contentLength = -1
this.connectionKeepAlive = false
this.maxResponseSize = client[kMaxResponseSize]
}
@@ -253,9 +255,9 @@ class Parser {
if (delay) {
if (type & USE_FAST_TIMER) {
this.timeout = timers.setFastTimeout(onParserTimeout, delay, new WeakRef(this))
this.timeout = timers.setFastTimeout(onParserTimeout, delay, this.timeoutWeakRef)
} else {
this.timeout = setTimeout(onParserTimeout, delay, new WeakRef(this))
this.timeout = setTimeout(onParserTimeout, delay, this.timeoutWeakRef)
this.timeout?.unref()
}
}
@@ -322,7 +324,16 @@ class Parser {
currentBufferPtr = llhttp.malloc(currentBufferSize)
}
new Uint8Array(llhttp.memory.buffer, currentBufferPtr, currentBufferSize).set(chunk)
if (
currentBuffer === null ||
currentBuffer.buffer !== llhttp.memory.buffer ||
currentBuffer.byteOffset !== currentBufferPtr ||
currentBuffer.byteLength !== currentBufferSize
) {
currentBuffer = new Uint8Array(llhttp.memory.buffer, currentBufferPtr, currentBufferSize)
}
currentBuffer.set(chunk)
// Call `execute` on the wasm parser.
// We pass the `llhttp_parser` pointer address, the pointer address of buffer view data,
@@ -447,10 +458,17 @@ class Parser {
if (headerName === 'keep-alive') {
this.keepAlive += buf.toString()
} else if (headerName === 'connection') {
this.connection += buf.toString()
this.connectionKeepAlive =
this.headers[len - 1].length === 10 &&
util.bufferToLowerCasedHeaderName(this.headers[len - 1]) === 'keep-alive'
}
} else if (key.length === 14 && util.bufferToLowerCasedHeaderName(key) === 'content-length') {
this.contentLength += buf.toString()
if (this.contentLength === -1) {
this.contentLength = 0
}
for (let i = 0; i < buf.length; i++) {
this.contentLength = (this.contentLength * 10) + (buf[i] - 0x30)
}
}
this.trackHeader(buf.length)
@@ -554,7 +572,7 @@ class Parser {
this.shouldKeepAlive = (
shouldKeepAlive ||
// Override llhttp value which does not allow keepAlive for HEAD.
(request.method === 'HEAD' && !socket[kReset] && this.connection.toLowerCase() === 'keep-alive')
(request.method === 'HEAD' && !socket[kReset] && this.connectionKeepAlive)
)
if (this.statusCode >= 200) {
@@ -687,9 +705,9 @@ class Parser {
this.statusCode = 0
this.statusText = ''
this.bytesRead = 0
this.contentLength = ''
this.contentLength = -1
this.keepAlive = ''
this.connection = ''
this.connectionKeepAlive = false
this.headers = []
this.headersSize = 0
@@ -698,7 +716,7 @@ class Parser {
return 0
}
if (request.method !== 'HEAD' && contentLength && bytesRead !== parseInt(contentLength, 10)) {
if (request.method !== 'HEAD' && contentLength !== -1 && bytesRead !== contentLength) {
util.destroy(socket, new ResponseContentLengthMismatchError())
return -1
}
@@ -1106,7 +1124,7 @@ function writeH1 (client, request) {
socket[kReset] = reset
}
if (client[kMaxRequests] && socket[kCounter]++ >= client[kMaxRequests]) {
if (client[kMaxRequests] && ++socket[kCounter] >= client[kMaxRequests]) {
socket[kReset] = true
}
@@ -1477,7 +1495,7 @@ class AsyncWriter {
}
/**
* @param {Buffer} chunk
* @param {string|Uint8Array} chunk
* @returns
*/
write (chunk) {
@@ -1491,7 +1509,7 @@ class AsyncWriter {
return false
}
const len = Buffer.byteLength(chunk)
const len = chunk instanceof Uint8Array ? chunk.byteLength : Buffer.byteLength(chunk)
if (!len) {
return true
}
+405 -152
View File
@@ -41,6 +41,12 @@ const {
const { channels } = require('../core/diagnostics.js')
const kOpenStreams = Symbol('open streams')
const kRequestStreamId = Symbol('request stream id')
const kRequestStream = Symbol('request stream')
const kRequestStreamCleanup = Symbol('request stream cleanup')
const kRequestStreamOnData = Symbol('request stream on data')
const kRequestStreamOnCloseError = Symbol('request stream on close error')
const kReceivedGoAway = Symbol('received goaway')
let extractBody
@@ -63,29 +69,73 @@ const {
HTTP2_HEADER_EXPECT,
HTTP2_HEADER_STATUS,
HTTP2_HEADER_PROTOCOL,
NGHTTP2_REFUSED_STREAM,
NGHTTP2_CANCEL
NGHTTP2_NO_ERROR,
NGHTTP2_REFUSED_STREAM
}
} = http2
function parseH2Headers (headers) {
const result = []
function getGoAwayError (session, errorCode) {
return session[kError] ||
(errorCode === NGHTTP2_NO_ERROR
? new InformationalError(`HTTP/2: "GOAWAY" frame received with code ${errorCode}`)
: new SocketError(`HTTP/2: "GOAWAY" frame received with code ${errorCode}`, util.getSocketInfo(session[kSocket])))
}
for (const [name, value] of Object.entries(headers)) {
// h2 may concat the header value by array
// e.g. Set-Cookie
if (Array.isArray(value)) {
for (const subvalue of value) {
// we need to provide each header value of header name
// because the headers handler expect name-value pair
result.push(Buffer.from(name), Buffer.from(subvalue))
}
} else {
result.push(Buffer.from(name), Buffer.from(value))
function getGoAwayPendingIdx (client, lastStreamID) {
const maxAcceptedStreamID = Number.isInteger(lastStreamID) ? lastStreamID : Number.MAX_SAFE_INTEGER
for (let i = client[kRunningIdx]; i < client[kPendingIdx]; i++) {
const request = client[kQueue][i]
if (request == null) {
continue
}
if (typeof request[kRequestStreamId] !== 'number' || request[kRequestStreamId] > maxAcceptedStreamID) {
return i
}
}
return result
return client[kPendingIdx]
}
function detachRequestFromStream (request) {
request[kRequestStreamId] = null
request[kRequestStream] = null
request[kRequestStreamCleanup] = null
}
function bindRequestToStream (request, stream, cleanup) {
const previousCleanup = request[kRequestStreamCleanup]
detachRequestFromStream(request)
previousCleanup?.()
request[kRequestStreamId] = stream.id
request[kRequestStream] = stream
request[kRequestStreamCleanup] = cleanup
}
function clearRequestStream (request) {
const cleanup = request[kRequestStreamCleanup]
detachRequestFromStream(request)
cleanup?.()
}
function canRetryRequestAfterGoAway (request) {
const { body } = request
return body == null || util.isBuffer(body) || util.isBlobLike(body)
}
function closeRequestStream (request, code = NGHTTP2_REFUSED_STREAM) {
const stream = request[kRequestStream]
clearRequestStream(request)
if (stream != null && !stream.destroyed && !stream.closed) {
try {
stream.close(code)
} catch {}
}
}
function connectH2 (client, socket) {
@@ -113,6 +163,7 @@ function connectH2 (client, socket) {
interval: client[kPingInterval] === 0 ? null : setInterval(onHttp2SendPing, client[kPingInterval], session).unref()
}
}
session[kReceivedGoAway] = false
// We set it to true by default in a best-effort; however once connected to an H2 server
// we will check if extended CONNECT protocol is supported or not
// and set this value accordingly.
@@ -184,6 +235,14 @@ function connectH2 (client, socket) {
* @returns {boolean}
*/
busy (request) {
if (session[kRemoteSettings] === false && client[kRunning] > 0) {
return true
}
if (client[kRunning] >= client[kMaxConcurrentStreams]) {
return true
}
if (request != null) {
if (client[kRunning] > 0) {
// We are already processing requests
@@ -273,7 +332,7 @@ function onHttp2SendPing (session) {
function onPing (err, duration) {
const client = this[kClient]
const socket = this[kClient]
const socket = this[kSocket]
if (err != null) {
const error = new InformationalError(`HTTP/2: "PING" errored - type ${err.message}`)
@@ -313,48 +372,68 @@ function onHttp2SessionEnd () {
*
* @this {import('http2').ClientHttp2Session}
* @param {number} errorCode
* @param {number} lastStreamID
*/
function onHttp2SessionGoAway (errorCode) {
// TODO(mcollina): Verify if GOAWAY implements the spec correctly:
// https://datatracker.ietf.org/doc/html/rfc7540#section-6.8
// Specifically, we do not verify the "valid" stream id.
const err = this[kError] || new SocketError(`HTTP/2: "GOAWAY" frame received with code ${errorCode}`, util.getSocketInfo(this[kSocket]))
const client = this[kClient]
client[kSocket] = null
client[kHTTPContext] = null
// this is an HTTP2 session
this.close()
this[kHTTP2Session] = null
util.destroy(this[kSocket], err)
// Fail head of pipeline.
if (client[kRunningIdx] < client[kQueue].length) {
const request = client[kQueue][client[kRunningIdx]]
client[kQueue][client[kRunningIdx]++] = null
util.errorRequest(client, request, err)
client[kPendingIdx] = client[kRunningIdx]
function onHttp2SessionGoAway (errorCode, lastStreamID) {
if (this[kReceivedGoAway]) {
return
}
assert(client[kRunning] === 0)
this[kReceivedGoAway] = true
const err = getGoAwayError(this, errorCode)
const client = this[kClient]
const previousPendingIdx = client[kPendingIdx]
const pendingIdx = getGoAwayPendingIdx(client, lastStreamID)
const retriableRequests = []
for (let i = pendingIdx; i < previousPendingIdx; i++) {
const request = client[kQueue][i]
if (request != null) {
closeRequestStream(request)
if (canRetryRequestAfterGoAway(request)) {
retriableRequests.push(request)
} else {
util.errorRequest(client, request, err)
}
}
}
if (pendingIdx !== previousPendingIdx) {
const remainingPendingRequests = client[kQueue].slice(previousPendingIdx)
client[kQueue].length = pendingIdx
client[kQueue].push(...retriableRequests, ...remainingPendingRequests)
}
if (client[kHTTP2Session] === this) {
client[kSocket] = null
client[kHTTPContext] = null
client[kHTTP2Session] = null
}
if (!this.closed && !this.destroyed) {
this.close()
}
client[kPendingIdx] = pendingIdx
client.emit('disconnect', client[kUrl], [client], err)
client.emit('connectionError', client[kUrl], [client], err)
client[kResume]()
}
function onHttp2SessionClose () {
const { [kClient]: client, [kHTTP2SessionState]: state } = this
const { [kSocket]: socket } = client
const { [kClient]: client, [kHTTP2SessionState]: state, [kSocket]: socket } = this
const err = this[kSocket][kError] || this[kError] || new SocketError('closed', util.getSocketInfo(socket))
const err = socket[kError] || this[kError] || new SocketError('closed', util.getSocketInfo(socket))
client[kSocket] = null
client[kHTTPContext] = null
if (client[kHTTP2Session] === this) {
client[kSocket] = null
client[kHTTPContext] = null
client[kHTTP2Session] = null
}
if (state.ping.interval != null) {
clearInterval(state.ping.interval)
@@ -376,15 +455,27 @@ function onHttp2SessionClose () {
function onHttp2SocketClose () {
const err = this[kError] || new SocketError('closed', util.getSocketInfo(this))
const client = this[kHTTP2Session][kClient]
const session = this[kHTTP2Session]
const client = session[kClient]
if (client[kSocket] !== this) {
// Ignore stale socket closes from a detached GOAWAY session and from any
// session that has already been replaced. If the session was detached
// without a GOAWAY and there is no replacement yet, we still need the
// close event to flush the client state.
if (session[kReceivedGoAway] || (client[kHTTP2Session] != null && client[kHTTP2Session] !== session)) {
return
}
}
client[kSocket] = null
client[kHTTPContext] = null
if (this[kHTTP2Session] !== null) {
this[kHTTP2Session].destroy(err)
if (client[kHTTP2Session] === session) {
client[kHTTP2Session] = null
}
session.destroy(err)
client[kPendingIdx] = client[kRunningIdx]
assert(client[kRunning] === 0)
@@ -410,6 +501,37 @@ function onSocketClose () {
this[kClosed] = true
}
function noop () {}
function closeStreamSession (stream) {
const session = stream[kHTTP2Session]
stream[kHTTP2Session] = null
session[kOpenStreams] -= 1
if (session[kOpenStreams] === 0) {
session.unref()
}
}
function onUpgradeStreamClose () {
this.off('error', noop)
const failUpgradeStream = this[kRequestStreamOnCloseError]
this[kRequestStreamOnCloseError] = null
failUpgradeStream(new InformationalError('HTTP/2: stream closed before response headers'))
closeStreamSession(this)
}
function onRequestStreamClose () {
const onData = this[kRequestStreamOnData]
this[kRequestStreamOnData] = null
this.off('data', onData)
this.off('error', noop)
closeStreamSession(this)
}
// https://www.rfc-editor.org/rfc/rfc7230#section-3.3.2
function shouldSendContentLength (method) {
return method !== 'GET' && method !== 'HEAD' && method !== 'OPTIONS' && method !== 'TRACE' && method !== 'CONNECT'
@@ -464,7 +586,23 @@ function writeH2 (client, request) {
headers[HTTP2_HEADER_AUTHORITY] = host || `${hostname}${port ? `:${port}` : ''}`
headers[HTTP2_HEADER_METHOD] = method
const abort = (err) => {
let requestFinalized = false
const finalizeRequest = (resetPendingIdx = false) => {
if (requestFinalized) {
return
}
requestFinalized = true
client[kQueue][client[kRunningIdx]++] = null
if (resetPendingIdx) {
client[kPendingIdx] = client[kRunningIdx]
}
client[kResume]()
}
const abort = (err, resetPendingIdx = false) => {
if (request.aborted || request.completed) {
return
}
@@ -474,16 +612,14 @@ function writeH2 (client, request) {
util.errorRequest(client, request, err)
if (stream != null) {
// Some chunks might still come after abort,
// let's ignore them
stream.removeAllListeners('data')
clearRequestStream(request)
// On Abort, we close the stream to send RST_STREAM frame
stream.close()
// We move the running index to the next request
client[kOnError](err)
client[kResume]()
finalizeRequest(resetPendingIdx)
}
// We do not destroy the socket as we can continue using the session
@@ -491,6 +627,26 @@ function writeH2 (client, request) {
util.destroy(body, err)
}
const requestStream = (headers, options) => {
try {
return session.request(headers, options)
} catch (err) {
if (err?.code !== 'ERR_HTTP2_INVALID_CONNECTION_HEADERS') {
throw err
}
const wrappedErr = new InformationalError(err.message, { cause: err })
session[kError] = wrappedErr
session[kSocket][kError] = wrappedErr
session.destroy(wrappedErr)
util.destroy(session[kSocket], wrappedErr)
abort(wrappedErr)
return null
}
}
try {
// We are already connected, streams are pending.
// We can call on connect, and wait for abort
@@ -506,6 +662,84 @@ function writeH2 (client, request) {
if (upgrade || method === 'CONNECT') {
session.ref()
const setupUpgradeStream = (stream) => {
let responseReceived = false
const removeUpgradeStreamListeners = () => {
stream.off('response', onUpgradeResponse)
stream.off('error', onUpgradeStreamError)
stream.off('end', onUpgradeStreamEnd)
stream.off('timeout', onUpgradeStreamTimeout)
stream.off('error', noop)
}
const releaseUpgradeStream = () => {
if (request[kRequestStream] === stream) {
detachRequestFromStream(request)
}
removeUpgradeStreamListeners()
if (!stream.destroyed && !stream.closed) {
stream.once('error', noop)
}
}
const failUpgradeStream = (err) => {
if (responseReceived || request.aborted || request.completed) {
return
}
releaseUpgradeStream()
abort(err, true)
}
const onUpgradeStreamError = () => {
if (typeof stream.rstCode === 'number' && stream.rstCode !== 0) {
failUpgradeStream(new InformationalError(`HTTP/2: "stream error" received - code ${stream.rstCode}`))
} else {
failUpgradeStream(new InformationalError('HTTP/2: stream errored before response headers'))
}
}
const onUpgradeStreamEnd = () => {
failUpgradeStream(new InformationalError('HTTP/2: stream half-closed (remote)'))
}
const onUpgradeStreamTimeout = () => {
failUpgradeStream(new InformationalError(`HTTP/2: "stream timeout after ${requestTimeout}"`))
}
const onUpgradeResponse = (headers, _flags) => {
responseReceived = true
const statusCode = headers[HTTP2_HEADER_STATUS]
delete headers[HTTP2_HEADER_STATUS]
request.onRequestUpgrade(statusCode, headers, stream)
if (request.aborted || request.completed) {
return
}
removeUpgradeStreamListeners()
detachRequestFromStream(request)
finalizeRequest()
}
bindRequestToStream(request, stream, releaseUpgradeStream)
stream.once('response', onUpgradeResponse)
stream.on('error', onUpgradeStreamError)
stream.once('end', onUpgradeStreamEnd)
stream.on('timeout', onUpgradeStreamTimeout)
stream[kHTTP2Session] = session
stream[kRequestStreamOnCloseError] = failUpgradeStream
stream.once('close', onUpgradeStreamClose)
++session[kOpenStreams]
stream.setTimeout(requestTimeout)
}
if (upgrade === 'websocket') {
// We cannot upgrade to websocket if extended CONNECT protocol is not supported
if (session[kEnableConnectProtocol] === false) {
@@ -528,33 +762,13 @@ function writeH2 (client, request) {
headers[HTTP2_HEADER_SCHEME] = protocol === 'http:' ? 'http' : 'https'
}
stream = session.request(headers, { endStream: false, signal })
stream = requestStream(headers, { endStream: false, signal })
if (stream == null) {
session.unref()
return false
}
stream[kHTTP2Stream] = true
stream.once('response', (headers, _flags) => {
const { [HTTP2_HEADER_STATUS]: statusCode, ...realHeaders } = headers
request.onRequestUpgrade(statusCode, parseH2Headers(realHeaders), stream)
++session[kOpenStreams]
client[kQueue][client[kRunningIdx]++] = null
})
stream.on('error', () => {
if (stream.rstCode === NGHTTP2_REFUSED_STREAM || stream.rstCode === NGHTTP2_CANCEL) {
// NGHTTP2_REFUSED_STREAM (7) or NGHTTP2_CANCEL (8)
// We do not treat those as errors as the server might
// not support websockets and refuse the stream
abort(new InformationalError(`HTTP/2: "stream error" received - code ${stream.rstCode}`))
}
})
stream.once('close', () => {
session[kOpenStreams] -= 1
if (session[kOpenStreams] === 0) session.unref()
})
stream.setTimeout(requestTimeout)
setupUpgradeStream(stream)
return true
}
@@ -563,20 +777,13 @@ function writeH2 (client, request) {
// will create a new stream. We trigger a request to create the stream and wait until
// `ready` event is triggered
// We disabled endStream to allow the user to write to the stream
stream = session.request(headers, { endStream: false, signal })
stream = requestStream(headers, { endStream: false, signal })
if (stream == null) {
session.unref()
return false
}
stream[kHTTP2Stream] = true
stream.on('response', headers => {
const { [HTTP2_HEADER_STATUS]: statusCode, ...realHeaders } = headers
request.onRequestUpgrade(statusCode, parseH2Headers(realHeaders), stream)
++session[kOpenStreams]
client[kQueue][client[kRunningIdx]++] = null
})
stream.once('close', () => {
session[kOpenStreams] -= 1
if (session[kOpenStreams] === 0) session.unref()
})
stream.setTimeout(requestTimeout)
setupUpgradeStream(stream)
return true
}
@@ -622,7 +829,7 @@ function writeH2 (client, request) {
contentLength = request.contentLength
}
if (!expectsPayload) {
if (contentLength === 0 && !expectsPayload) {
// https://tools.ietf.org/html/rfc7230#section-3.3.2
// A user agent SHOULD NOT send a Content-Length header field when
// the request message does not contain a payload body and the method
@@ -658,21 +865,25 @@ function writeH2 (client, request) {
}
// TODO(metcoder95): add support for sending trailers
const shouldEndStream = method === 'GET' || method === 'HEAD' || body === null
const shouldEndStream = body === null
if (expectContinue) {
headers[HTTP2_HEADER_EXPECT] = '100-continue'
stream = session.request(headers, { endStream: shouldEndStream, signal })
stream = requestStream(headers, { endStream: shouldEndStream, signal })
if (stream == null) {
return false
}
stream[kHTTP2Stream] = true
stream.once('continue', writeBodyH2)
bindRequestToStream(request, stream, null)
} else {
stream = session.request(headers, {
stream = requestStream(headers, {
endStream: shouldEndStream,
signal
})
if (stream == null) {
return false
}
stream[kHTTP2Stream] = true
writeBodyH2()
bindRequestToStream(request, stream, null)
}
// Increment counter as we have new streams open
@@ -681,9 +892,46 @@ function writeH2 (client, request) {
// Track whether we received a response (headers)
let responseReceived = false
const onData = (chunk) => {
if (request.aborted || request.completed) {
return
}
stream.once('response', headers => {
const { [HTTP2_HEADER_STATUS]: statusCode, ...realHeaders } = headers
if (request.onResponseData(chunk) === false) {
stream.pause()
}
}
const removeRequestStreamListeners = () => {
stream.off('error', noop)
stream.off('continue', writeBodyH2)
stream.off('response', onResponse)
stream.off('end', onEnd)
stream.off('error', onError)
stream.off('frameError', onFrameError)
stream.off('aborted', onAborted)
stream.off('timeout', onTimeout)
stream.off('trailers', onTrailers)
stream.off('data', onData)
}
const releaseRequestStream = () => {
if (request[kRequestStream] === stream) {
detachRequestFromStream(request)
}
removeRequestStreamListeners()
if (!stream.destroyed && !stream.closed) {
stream.once('error', noop)
}
}
const onResponse = (headers) => {
stream.off('response', onResponse)
const statusCode = headers[HTTP2_HEADER_STATUS]
delete headers[HTTP2_HEADER_STATUS]
request.onResponseStarted()
responseReceived = true
@@ -693,86 +941,91 @@ function writeH2 (client, request) {
// for those scenarios, best effort is to destroy the stream immediately
// as there's no value to keep it open.
if (request.aborted) {
stream.removeAllListeners('data')
releaseRequestStream()
return
}
if (request.onResponseStart(Number(statusCode), parseH2Headers(realHeaders), stream.resume.bind(stream), '') === false) {
if (request.onResponseStart(Number(statusCode), headers, stream.resume.bind(stream), '') === false) {
stream.pause()
}
stream.on('data', (chunk) => {
if (request.aborted || request.completed) {
return
}
stream.on('data', onData)
}
if (request.onResponseData(chunk) === false) {
stream.pause()
}
})
})
const onEnd = () => {
stream.off('end', onEnd)
stream.once('end', () => {
stream.removeAllListeners('data')
releaseRequestStream()
// If we received a response, this is a normal completion
if (responseReceived) {
if (!request.aborted && !request.completed) {
request.onResponseEnd({})
}
client[kQueue][client[kRunningIdx]++] = null
client[kResume]()
finalizeRequest()
} else {
// Stream ended without receiving a response - this is an error
// (e.g., server destroyed the stream before sending headers)
abort(new InformationalError('HTTP/2: stream half-closed (remote)'))
client[kQueue][client[kRunningIdx]++] = null
client[kPendingIdx] = client[kRunningIdx]
client[kResume]()
abort(new InformationalError('HTTP/2: stream half-closed (remote)'), true)
}
})
}
stream.once('close', () => {
stream.removeAllListeners('data')
session[kOpenStreams] -= 1
if (session[kOpenStreams] === 0) {
session.unref()
}
})
stream[kHTTP2Session] = session
stream[kRequestStreamOnData] = onData
stream.once('close', onRequestStreamClose)
stream.once('error', function (err) {
stream.removeAllListeners('data')
const onError = function (err) {
stream.off('error', onError)
releaseRequestStream()
abort(err)
})
}
stream.once('frameError', (type, code) => {
stream.removeAllListeners('data')
const onFrameError = (type, code) => {
stream.off('frameError', onFrameError)
releaseRequestStream()
abort(new InformationalError(`HTTP/2: "frameError" received - type ${type}, code ${code}`))
})
}
stream.on('aborted', () => {
stream.removeAllListeners('data')
})
const onAborted = () => {
stream.off('data', onData)
}
const onTimeout = () => {
releaseRequestStream()
stream.on('timeout', () => {
const err = new InformationalError(`HTTP/2: "stream timeout after ${requestTimeout}"`)
stream.removeAllListeners('data')
session[kOpenStreams] -= 1
if (session[kOpenStreams] === 0) {
session.unref()
}
abort(err)
})
}
const onTrailers = (trailers) => {
stream.off('trailers', onTrailers)
stream.once('trailers', trailers => {
if (request.aborted || request.completed) {
return
}
releaseRequestStream()
request.onResponseEnd(trailers)
})
finalizeRequest()
}
bindRequestToStream(request, stream, releaseRequestStream)
if (expectContinue) {
stream.once('continue', writeBodyH2)
}
stream.once('response', onResponse)
stream.once('end', onEnd)
stream.once('error', onError)
stream.once('frameError', onFrameError)
stream.on('aborted', onAborted)
stream.on('timeout', onTimeout)
stream.once('trailers', onTrailers)
if (!expectContinue) {
writeBodyH2()
}
return true
+4 -4
View File
@@ -17,15 +17,15 @@ class H2CClient extends Client {
const { maxConcurrentStreams, pipelining, ...opts } =
clientOpts ?? {}
let defaultMaxConcurrentStreams = 100
const defaultMaxConcurrentStreams = maxConcurrentStreams ?? 100
let defaultPipelining = 100
if (
maxConcurrentStreams != null &&
Number.isInteger(maxConcurrentStreams) &&
maxConcurrentStreams > 0
(!Number.isInteger(maxConcurrentStreams) ||
maxConcurrentStreams < 1)
) {
defaultMaxConcurrentStreams = maxConcurrentStreams
throw new InvalidArgumentError('maxConcurrentStreams must be a positive integer, greater than 0')
}
if (pipelining != null && Number.isInteger(pipelining) && pipelining > 0) {
+6 -6
View File
@@ -189,12 +189,12 @@ class PoolBase extends DispatcherBase {
}
[kRemoveClient] (client) {
client.close(() => {
const idx = this[kClients].indexOf(client)
if (idx !== -1) {
this[kClients].splice(idx, 1)
}
})
const idx = this[kClients].indexOf(client)
if (idx !== -1) {
this[kClients].splice(idx, 1)
}
client.close(() => {})
this[kNeedDrain] = this[kClients].some(dispatcher => (
!dispatcher[kNeedDrain] &&
+7 -2
View File
@@ -36,6 +36,7 @@ class Pool extends PoolBase {
autoSelectFamily,
autoSelectFamilyAttemptTimeout,
allowH2,
useH2c,
clientTtl,
...options
} = {}) {
@@ -56,6 +57,7 @@ class Pool extends PoolBase {
...tls,
maxCachedSessions,
allowH2,
useH2c,
socketPath,
timeout: connectTimeout,
...(typeof autoSelectFamily === 'boolean' ? { autoSelectFamily, autoSelectFamilyAttemptTimeout } : undefined),
@@ -67,7 +69,7 @@ class Pool extends PoolBase {
this[kConnections] = connections || null
this[kUrl] = util.parseOrigin(origin)
this[kOptions] = { ...util.deepClone(options), connect, allowH2, clientTtl, socketPath }
this[kOptions] = { ...util.deepClone(options), connect, allowH2, useH2c, clientTtl, socketPath }
this[kFactory] = factory
this.on('connect', (origin, targets) => {
@@ -95,10 +97,13 @@ class Pool extends PoolBase {
[kGetDispatcher] () {
const clientTtlOption = this[kOptions].clientTtl
for (const client of this[kClients]) {
for (let i = 0; i < this[kClients].length; i++) {
const client = this[kClients][i]
// check ttl of client and if it's stale, remove it from the pool
if (clientTtlOption != null && clientTtlOption > 0 && client.ttl && ((Date.now() - client.ttl) > clientTtlOption)) {
this[kRemoveClient](client)
i--
} else if (!client[kNeedDrain]) {
return client
}
+2
View File
@@ -126,6 +126,8 @@ class ProxyAgent extends DispatcherBase {
this[kProxyHeaders]['proxy-authorization'] = opts.token
} else if (username && password) {
this[kProxyHeaders]['proxy-authorization'] = `Basic ${Buffer.from(`${decodeURIComponent(username)}:${decodeURIComponent(password)}`).toString('base64')}`
} else if (username) {
this[kProxyHeaders]['proxy-authorization'] = `Basic ${Buffer.from(`${decodeURIComponent(username)}:`).toString('base64')}`
}
const connect = buildConnector({ timeout: connectTimeout, ...opts.proxyTls })
+5 -6
View File
@@ -92,10 +92,9 @@ class RoundRobinPool extends PoolBase {
[kGetDispatcher] () {
const clientTtlOption = this[kOptions].clientTtl
const clientsLength = this[kClients].length
// If we have no clients yet, create one
if (clientsLength === 0) {
if (this[kClients].length === 0) {
const dispatcher = this[kFactory](this[kUrl], this[kOptions])
this[kAddClient](dispatcher)
return dispatcher
@@ -103,14 +102,14 @@ class RoundRobinPool extends PoolBase {
// Round-robin through existing clients
let checked = 0
while (checked < clientsLength) {
this[kIndex] = (this[kIndex] + 1) % clientsLength
while (checked < this[kClients].length) {
this[kIndex] = (this[kIndex] + 1) % this[kClients].length
const client = this[kClients][this[kIndex]]
// Check if client is stale (TTL expired)
if (clientTtlOption != null && clientTtlOption > 0 && client.ttl && ((Date.now() - client.ttl) > clientTtlOption)) {
this[kRemoveClient](client)
checked++
this[kIndex]--
continue
}
@@ -123,7 +122,7 @@ class RoundRobinPool extends PoolBase {
}
// All clients are busy, create a new one if we haven't reached the limit
if (!this[kConnections] || clientsLength < this[kConnections]) {
if (!this[kConnections] || this[kClients].length < this[kConnections]) {
const dispatcher = this[kFactory](this[kUrl], this[kOptions])
this[kAddClient](dispatcher)
return dispatcher
+23 -14
View File
@@ -6,7 +6,7 @@ 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 { Socks5Client, STATES } = require('../core/socks5-client')
const { kDispatch, kClose, kDestroy } = require('../core/symbols')
const Pool = require('./pool')
const buildConnector = require('../core/connect')
@@ -17,7 +17,7 @@ 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 kPools = Symbol('pools')
const kConnector = Symbol('connector')
// Static flag to ensure warning is only emitted once per process
@@ -65,8 +65,8 @@ class Socks5ProxyAgent extends DispatcherBase {
servername: options.proxyTls?.servername || url.hostname
})
// Pool for the actual HTTP connections (with SOCKS5 tunnel connect function)
this[kPool] = null
// Pools for the actual HTTP connections (with SOCKS5 tunnel connect function), keyed by origin
this[kPools] = new Map()
}
/**
@@ -133,7 +133,7 @@ class Socks5ProxyAgent extends DispatcherBase {
}
// Check if already authenticated (for NO_AUTH method)
if (socks5Client.state === 'authenticated') {
if (socks5Client.state === STATES.AUTHENTICATED) {
clearTimeout(authenticationTimeout)
authenticationReady.resolve()
} else {
@@ -183,9 +183,11 @@ class Socks5ProxyAgent extends DispatcherBase {
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, {
const originKey = String(origin)
let pool = this[kPools].get(originKey)
// Create a Pool per origin so requests are not routed to the wrong host
if (!pool || pool.destroyed || pool.closed) {
pool = new Pool(origin, {
pipelining: opts.pipelining,
connections: opts.connections,
connect: async (connectOpts, callback) => {
@@ -225,10 +227,11 @@ class Socks5ProxyAgent extends DispatcherBase {
}
}
})
this[kPools].set(originKey, pool)
}
// Dispatch the request through the pool
return this[kPool][kDispatch](opts, handler)
// Dispatch the request through the per-origin pool
return pool[kDispatch](opts, handler)
} catch (err) {
debug('dispatch error:', err)
if (typeof handler.onError === 'function') {
@@ -240,15 +243,21 @@ class Socks5ProxyAgent extends DispatcherBase {
}
async [kClose] () {
if (this[kPool]) {
await this[kPool].close()
const closePromises = []
for (const pool of this[kPools].values()) {
closePromises.push(pool.close())
}
this[kPools].clear()
await Promise.all(closePromises)
}
async [kDestroy] (err) {
if (this[kPool]) {
await this[kPool].destroy(err)
const destroyPromises = []
for (const pool of this[kPools].values()) {
destroyPromises.push(pool.destroy(err))
}
this[kPools].clear()
await Promise.all(destroyPromises)
}
}
+1 -1
View File
@@ -479,7 +479,7 @@ function determineStaleAt (cacheType, now, age, resHeaders, responseDate, cacheC
if (cacheControlDirectives.immutable) {
// https://www.rfc-editor.org/rfc/rfc8246.html#section-2.2
return 31536000
return 31536000000
}
return undefined
+4
View File
@@ -23,6 +23,10 @@ class RedirectHandler {
throw new InvalidArgumentError('maxRedirections must be a positive number')
}
if (opts.throwOnMaxRedirect != null && typeof opts.throwOnMaxRedirect !== 'boolean') {
throw new InvalidArgumentError('throwOnMaxRedirect must be a boolean')
}
this.dispatch = dispatch
this.location = null
const { maxRedirections: _, ...cleanOpts } = opts
+3 -3
View File
@@ -2,16 +2,16 @@
const RedirectHandler = require('../handler/redirect-handler')
function createRedirectInterceptor ({ maxRedirections: defaultMaxRedirections } = {}) {
function createRedirectInterceptor ({ maxRedirections: defaultMaxRedirections, throwOnMaxRedirect: defaultThrowOnMaxRedirect } = {}) {
return (dispatch) => {
return function Intercept (opts, handler) {
const { maxRedirections = defaultMaxRedirections, ...rest } = opts
const { maxRedirections = defaultMaxRedirections, throwOnMaxRedirect = defaultThrowOnMaxRedirect, ...rest } = opts
if (maxRedirections == null || maxRedirections === 0) {
return dispatch(opts, handler)
}
const dispatchOpts = { ...rest } // Stop sub dispatcher from also redirecting.
const dispatchOpts = { ...rest, throwOnMaxRedirect } // Stop sub dispatcher from also redirecting.
const redirectHandler = new RedirectHandler(dispatch, maxRedirections, dispatchOpts, handler)
return dispatch(dispatchOpts, redirectHandler)
}
View File
Whitespace-only changes.
+1 -1
View File
@@ -2,7 +2,7 @@
const { Buffer } = require('node:buffer')
const wasmBase64 = 'AGFzbQEAAAABJwdgAX8Bf2ADf39/AX9gAn9/AGABfwBgBH9/f38Bf2AAAGADf39/AALLAQgDZW52GHdhc21fb25faGVhZGVyc19jb21wbGV0ZQAEA2VudhV3YXNtX29uX21lc3NhZ2VfYmVnaW4AAANlbnYLd2FzbV9vbl91cmwAAQNlbnYOd2FzbV9vbl9zdGF0dXMAAQNlbnYUd2FzbV9vbl9oZWFkZXJfZmllbGQAAQNlbnYUd2FzbV9vbl9oZWFkZXJfdmFsdWUAAQNlbnYMd2FzbV9vbl9ib2R5AAEDZW52GHdhc21fb25fbWVzc2FnZV9jb21wbGV0ZQAAAzU0BQYAAAMAAAAAAAADAQMAAwMDAAACAAAAAAICAgICAgICAgIBAQEBAQEBAQEBAwAAAwAAAAQFAXABExMFAwEAAgYIAX8BQcDZBAsHxQcoBm1lbW9yeQIAC19pbml0aWFsaXplAAgZX19pbmRpcmVjdF9mdW5jdGlvbl90YWJsZQEAC2xsaHR0cF9pbml0AAkYbGxodHRwX3Nob3VsZF9rZWVwX2FsaXZlADcMbGxodHRwX2FsbG9jAAsGbWFsbG9jADkLbGxodHRwX2ZyZWUADARmcmVlAAwPbGxodHRwX2dldF90eXBlAA0VbGxodHRwX2dldF9odHRwX21ham9yAA4VbGxodHRwX2dldF9odHRwX21pbm9yAA8RbGxodHRwX2dldF9tZXRob2QAEBZsbGh0dHBfZ2V0X3N0YXR1c19jb2RlABESbGxodHRwX2dldF91cGdyYWRlABIMbGxodHRwX3Jlc2V0ABMObGxodHRwX2V4ZWN1dGUAFBRsbGh0dHBfc2V0dGluZ3NfaW5pdAAVDWxsaHR0cF9maW5pc2gAFgxsbGh0dHBfcGF1c2UAFw1sbGh0dHBfcmVzdW1lABgbbGxodHRwX3Jlc3VtZV9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AgQMAwtBACEACyAGRQ0AAkAgBSgCHCICQQJ0QfTXAGoiAygCACAFRgRAIAMgADYCACAADQFByNUAQcjVACgCAEF+IAJ3cTYCAAwCCyAGQRBBFCAGKAIQIAVGG2ogADYCACAARQ0BCyAAIAY2AhggBSgCECICBEAgACACNgIQIAIgADYCGAsgBUEUaigCACICRQ0AIABBFGogAjYCACACIAA2AhgLIAEgBGogBDYCACABIARBAXI2AgQgAUHY1QAoAgBHDQBBzNUAIAQ2AgAMAQsgBEH/AU0EQCAEQXhxQezVAGohAAJ/QcTVACgCACICQQEgBEEDdnQiA3FFBEBBxNUAIAIgA3I2AgAgAAwBCyAAKAIICyICIAE2AgwgACABNgIIIAEgADYCDCABIAI2AggMAQtBHyECIARB////B00EQCAEQSYgBEEIdmciAGt2QQFxIABBAXRrQT5qIQILIAEgAjYCHCABQgA3AhAgAkECdEH01wBqIQACQEHI1QAoAgAiA0EBIAJ0IgdxRQRAIAAgATYCAEHI1QAgAyAHcjYCACABIAA2AhggASABNgIIIAEgATYCDAwBCyAEQRkgAkEBdmtBACACQR9HG3QhAiAAKAIAIQACQANAIAAiAygCBEF4cSAERg0BIAJBHXYhACACQQF0IQIgAyAAQQRxakEQaiIHKAIAIgANAAsgByABNgIAIAEgAzYCGCABIAE2AgwgASABNgIIDAELIAMoAggiACABNgIMIAMgATYCCCABQQA2AhggASADNgIMIAEgADYCCAtB5NUAQeTVACgCAEEBayIAQX8gABs2AgALCwcAIAAtACgLBwAgAC0AKgsHACAALQArCwcAIAAtACkLBwAgAC8BNAsHACAALQAwC0ABBH8gACgCGCEBIAAvAS4hAiAALQAoIQMgACgCOCEEIAAQOCAAIAQ2AjggACADOgAoIAAgAjsBLiAAIAE2AhgL5YUCAgd/A34gASACaiEEAkAgACIDKAIMIgANACADKAIEBEAgAyABNgIECyMAQRBrIgkkAAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAn8CQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkAgAygCHCICQQJrDvwBAfkBAgMEBQYHCAkKCwwNDg8QERL4ARP3ARQV9gEWF/UBGBkaGxwdHh8g/QH7ASH0ASIjJCUmJygpKivzASwtLi8wMTL Line truncated
const wasmBase64 = 'AGFzbQEAAAABJwdgAX8Bf2ADf39/AX9gAn9/AGABfwBgBH9/f38Bf2AAAGADf39/AALLAQgDZW52GHdhc21fb25faGVhZGVyc19jb21wbGV0ZQAEA2VudhV3YXNtX29uX21lc3NhZ2VfYmVnaW4AAANlbnYLd2FzbV9vbl91cmwAAQNlbnYOd2FzbV9vbl9zdGF0dXMAAQNlbnYUd2FzbV9vbl9oZWFkZXJfZmllbGQAAQNlbnYUd2FzbV9vbl9oZWFkZXJfdmFsdWUAAQNlbnYMd2FzbV9vbl9ib2R5AAEDZW52GHdhc21fb25fbWVzc2FnZV9jb21wbGV0ZQAAAzU0BQYAAAMAAAAAAAADAQMAAwMDAAACAAAAAAICAgICAgICAgIBAQEBAQEBAQEBAwAAAwAA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AA2AhggASABNgIIIAEgATYCDAwBCyAEQRkgAkEBdmtBACACQR9HG3QhAiAAKAIAIQACQANAIAAiAygCBEF4cSAERg0BIAJBHXYhACACQQF0IQIgAyAAQQRxakEQaiIHKAIAIgANAAsgByABNgIAIAEgAzYCGCABIAE2AgwgASABNgIIDAELIAMoAggiACABNgIMIAMgATYCCCABQQA2AhggASADNgIMIAEgADYCCAtB5NUAQeTVACgCAEEBayIAQX8gABs2AgALCwcAIAAtACgLBwAgAC0AKgsHACAALQArCwcAIAAtACkLBwAgAC8BNAsHACAALQAwC0ABBH8gACgCGCEBIAAvAS4hAiAALQAoIQMgACgCOCEEIAAQOCAAIAQ2AjggACADOgAoIAAgAjsBLiAAIAE2AhgL5YUCAgd/A34gASACaiEEAkAgACIDKAIMIgANACADKAIEBEAgAyABNgIECyMAQRBrIgkkAAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAn8CQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkAgAygCHCICQQJrDvwBAfkBAgMEBQYHCAkKCwwNDg8QERL4ARP3ARQV9gEWF/UBGBkaGxwdHh8g/QH7ASH0ASIjJCUmJygpKivzASwtLi8wMTL Line truncated
let wasmBuffer
Binary file not shown.
+1 -1
View File
@@ -2,7 +2,7 @@
const { Buffer } = require('node:buffer')
const wasmBase64 = 'AGFzbQEAAAABJwdgAX8Bf2ADf39/AX9gAn9/AGABfwBgBH9/f38Bf2AAAGADf39/AALLAQgDZW52GHdhc21fb25faGVhZGVyc19jb21wbGV0ZQAEA2VudhV3YXNtX29uX21lc3NhZ2VfYmVnaW4AAANlbnYLd2FzbV9vbl91cmwAAQNlbnYOd2FzbV9vbl9zdGF0dXMAAQNlbnYUd2FzbV9vbl9oZWFkZXJfZmllbGQAAQNlbnYUd2FzbV9vbl9oZWFkZXJfdmFsdWUAAQNlbnYMd2FzbV9vbl9ib2R5AAEDZW52GHdhc21fb25fbWVzc2FnZV9jb21wbGV0ZQAAAzU0BQYAAAMAAAAAAAADAQMAAwMDAAACAAAAAAICAgICAgICAgIBAQEBAQEBAQEBAwAAAwAAAAQFAXABExMFAwEAAgYIAX8BQcDZBAsHxQcoBm1lbW9yeQIAC19pbml0aWFsaXplAAgZX19pbmRpcmVjdF9mdW5jdGlvbl90YWJsZQEAC2xsaHR0cF9pbml0AAkYbGxodHRwX3Nob3VsZF9rZWVwX2FsaXZlADcMbGxodHRwX2FsbG9jAAsGbWFsbG9jADkLbGxodHRwX2ZyZWUADARmcmVlAAwPbGxodHRwX2dldF90eXBlAA0VbGxodHRwX2dldF9odHRwX21ham9yAA4VbGxodHRwX2dldF9odHRwX21pbm9yAA8RbGxodHRwX2dldF9tZXRob2QAEBZsbGh0dHBfZ2V0X3N0YXR1c19jb2RlABESbGxodHRwX2dldF91cGdyYWRlABIMbGxodHRwX3Jlc2V0ABMObGxodHRwX2V4ZWN1dGUAFBRsbGh0dHBfc2V0dGluZ3NfaW5pdAAVDWxsaHR0cF9maW5pc2gA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DIAAoAhAiAg0ACyAHQQA2AgAMAgsgBSAAQX5xNgIEIAEgBGogBDYCACABIARBAXI2AgQMAwtBACEACyAGRQ0AAkAgBSgCHCICQQJ0QfTXAGoiAygCACAFRgRAIAMgADYCACAADQFByNUAQcjVACgCAEF+IAJ3cTYCAAwCCyAGQRBBFCAGKAIQIAVGG2ogADYCACAARQ0BCyAAIAY2AhggBSgCECICBEAgACACNgIQIAIgADYCGAsgBUEUaigCACICRQ0AIABBFGogAjYCACACIAA2AhgLIAEgBGogBDYCACABIARBAXI2AgQgAUHY1QAoAgBHDQBBzNUAIAQ2AgAMAQsgBEH/AU0EQCAEQXhxQezVAGohAAJ/QcTVACgCACICQQEgBEEDdnQiA3FFBEBBxNUAIAIgA3I2AgAgAAwBCyAAKAIICyICIAE2AgwgACABNgIIIAEgADYCDCABIAI2AggMAQtBHyECIARB////B00EQCAEQSYgBEEIdmciAGt2QQFxIABBAXRrQT5qIQILIAEgAjYCHCABQgA3AhAgAkECdEH01wBqIQACQEHI1QAoAgAiA0EBIAJ0IgdxRQRAIAAgATYCAEHI1QAgAyAHcjYCACABIAA2AhggASABNgIIIAEgATYCDAwBCyAEQRkgAkEBdmtBACACQR9HG3QhAiAAKAIAIQACQANAIAAiAygCBEF4cSAERg0BIAJBHXYhACACQQF0IQIgAyAAQQRxakEQaiIHKAIAIgANAAsgByABNgIAIAEgAzYCGCABIAE2AgwgASABNgIIDAELIAMoAggiACABNgIMIAMgATYCCCABQQA2AhggASADNgIMIAEgADYCCAtB5NUAQeTVACgCAEEBayIAQX8gABs2AgALCwcAIAAtACgLBwAgAC0AKgsHACAALQArCwcAIAAtACkLBwAgAC8BNAsHACAALQAwC0ABBH8gACgCGCEBIAAvAS4hAiAALQAoIQMgACgCOCEEIAAQOCAAIAQ2AjggACADOgAoIAAgAjsBLiAAIAE2AhgLhocCAwd/A34BeyABIAJqIQQCQCAAIgMoAgwiAA0AIAMoAgQEQCADIAE2AgQLIwBBEGsiCSQAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACfwJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQCADKAIcIgJBAmsO/AEB+QECAwQFBgcICQoLDA0ODxAREvgBE/cBFBX2ARYX9QEYGRobHB0eHyD9AfsBIfQBIiMkJSYnKCkqK/MBLC0uLzA Line truncated
const wasmBase64 = 'AGFzbQEAAAABJwdgAX8Bf2ADf39/AX9gAn9/AGABfwBgBH9/f38Bf2AAAGADf39/AALLAQgDZW52GHdhc21fb25faGVhZGVyc19jb21wbGV0ZQAEA2VudhV3YXNtX29uX21lc3NhZ2VfYmVnaW4AAANlbnYLd2FzbV9vbl91cmwAAQNlbnYOd2FzbV9vbl9zdGF0dXMAAQNlbnYUd2FzbV9vbl9oZWFkZXJfZmllbGQAAQNlbnYUd2FzbV9vbl9oZWFkZXJfdmFsdWUAAQNlbnYMd2FzbV9vbl9ib2R5AAEDZW52GHdhc21fb25fbWVzc2FnZV9jb21wbGV0ZQAAAz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EH01wBqIQACQEHI1QAoAgAiA0EBIAJ0IgdxRQRAIAAgATYCAEHI1QAgAyAHcjYCACABIAA2AhggASABNgIIIAEgATYCDAwBCyAEQRkgAkEBdmtBACACQR9HG3QhAiAAKAIAIQACQANAIAAiAygCBEF4cSAERg0BIAJBHXYhACACQQF0IQIgAyAAQQRxakEQaiIHKAIAIgANAAsgByABNgIAIAEgAzYCGCABIAE2AgwgASABNgIIDAELIAMoAggiACABNgIMIAMgATYCCCABQQA2AhggASADNgIMIAEgADYCCAtB5NUAQeTVACgCAEEBayIAQX8gABs2AgALCwcAIAAtACgLBwAgAC0AKgsHACAALQArCwcAIAAtACkLBwAgAC8BNAsHACAALQAwC0ABBH8gACgCGCEBIAAvAS4hAiAALQAoIQMgACgCOCEEIAAQOCAAIAQ2AjggACADOgAoIAAgAjsBLiAAIAE2AhgLhocCAwd/A34BeyABIAJqIQQCQCAAIgMoAgwiAA0AIAMoAgQEQCADIAE2AgQLIwBBEGsiCSQAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACfwJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQCADKAIcIgJBAmsO/AEB+QECAwQFBgcICQoLDA0ODxAREvgBE/cBFBX2ARYX9QEYGRobHB0eHyD9AfsBIfQBIiMkJSYnKCkqK/MBLC0uLzA Line truncated
let wasmBuffer
Binary file not shown.
+1 -1
View File
@@ -1,5 +1,5 @@
> undici@8.1.0 build:wasm
> undici@8.2.0 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
+8 -8
View File
@@ -167,7 +167,7 @@ class MockAgent extends Dispatcher {
}
[kMockAgentSet] (origin, dispatcher) {
this[kClients].set(origin, { count: 0, dispatcher })
this[kClients].set(origin, dispatcher)
}
[kFactory] (origin) {
@@ -179,9 +179,9 @@ class MockAgent extends Dispatcher {
[kMockAgentGet] (origin) {
// First check if we can immediately find it
const result = this[kClients].get(origin)
if (result?.dispatcher) {
return result.dispatcher
const dispatcher = this[kClients].get(origin)
if (dispatcher) {
return dispatcher
}
// If the origin is not a string create a dummy parent pool and return to user
@@ -192,11 +192,11 @@ class MockAgent extends Dispatcher {
}
// If we match, create a pool and assign the same dispatches
for (const [keyMatcher, result] of Array.from(this[kClients])) {
if (result && typeof keyMatcher !== 'string' && matchValue(keyMatcher, origin)) {
for (const [keyMatcher, nonExplicitDispatcher] of Array.from(this[kClients])) {
if (nonExplicitDispatcher && typeof keyMatcher !== 'string' && matchValue(keyMatcher, origin)) {
const dispatcher = this[kFactory](origin)
this[kMockAgentSet](origin, dispatcher)
dispatcher[kDispatches] = result.dispatcher[kDispatches]
dispatcher[kDispatches] = nonExplicitDispatcher[kDispatches]
return dispatcher
}
}
@@ -210,7 +210,7 @@ class MockAgent extends Dispatcher {
const mockAgentClients = this[kClients]
return Array.from(mockAgentClients.entries())
.flatMap(([origin, result]) => result.dispatcher[kDispatches].map(dispatch => ({ ...dispatch, origin })))
.flatMap(([origin, dispatcher]) => dispatcher[kDispatches].map(dispatch => ({ ...dispatch, origin })))
.filter(({ pending }) => pending)
}
+15 -15
View File
@@ -3,14 +3,14 @@
const { kMockCallHistoryAddLog } = require('./mock-symbols')
const { InvalidArgumentError } = require('../core/errors')
function handleFilterCallsWithOptions (criteria, options, handler, store) {
function handleFilterCallsWithOptions (criteria, options, handler, store, allLogs) {
switch (options.operator) {
case 'OR':
store.push(...handler(criteria))
store.push(...handler(criteria, allLogs))
return store
case 'AND':
return handler.call({ logs: store }, criteria)
return handler(criteria, store)
default:
// guard -- should never happens because buildAndValidateFilterCallsOptions is called before
throw new InvalidArgumentError('options.operator must to be a case insensitive string equal to \'OR\' or \'AND\'')
@@ -35,14 +35,14 @@ function buildAndValidateFilterCallsOptions (options = {}) {
}
function makeFilterCalls (parameterName) {
return (parameterValue) => {
return (parameterValue, logs) => {
if (typeof parameterValue === 'string' || parameterValue == null) {
return this.logs.filter((log) => {
return logs.filter((log) => {
return log[parameterName] === parameterValue
})
}
if (parameterValue instanceof RegExp) {
return this.logs.filter((log) => {
return logs.filter((log) => {
return parameterValue.test(log[parameterName])
})
}
@@ -175,30 +175,30 @@ class MockCallHistory {
const finalOptions = { operator: 'OR', ...buildAndValidateFilterCallsOptions(options) }
let maybeDuplicatedLogsFiltered = []
let maybeDuplicatedLogsFiltered = finalOptions.operator === 'AND' ? this.logs : []
if ('protocol' in criteria) {
maybeDuplicatedLogsFiltered = handleFilterCallsWithOptions(criteria.protocol, finalOptions, this.filterCallsByProtocol, maybeDuplicatedLogsFiltered)
maybeDuplicatedLogsFiltered = handleFilterCallsWithOptions(criteria.protocol, finalOptions, this.filterCallsByProtocol, maybeDuplicatedLogsFiltered, this.logs)
}
if ('host' in criteria) {
maybeDuplicatedLogsFiltered = handleFilterCallsWithOptions(criteria.host, finalOptions, this.filterCallsByHost, maybeDuplicatedLogsFiltered)
maybeDuplicatedLogsFiltered = handleFilterCallsWithOptions(criteria.host, finalOptions, this.filterCallsByHost, maybeDuplicatedLogsFiltered, this.logs)
}
if ('port' in criteria) {
maybeDuplicatedLogsFiltered = handleFilterCallsWithOptions(criteria.port, finalOptions, this.filterCallsByPort, maybeDuplicatedLogsFiltered)
maybeDuplicatedLogsFiltered = handleFilterCallsWithOptions(criteria.port, finalOptions, this.filterCallsByPort, maybeDuplicatedLogsFiltered, this.logs)
}
if ('origin' in criteria) {
maybeDuplicatedLogsFiltered = handleFilterCallsWithOptions(criteria.origin, finalOptions, this.filterCallsByOrigin, maybeDuplicatedLogsFiltered)
maybeDuplicatedLogsFiltered = handleFilterCallsWithOptions(criteria.origin, finalOptions, this.filterCallsByOrigin, maybeDuplicatedLogsFiltered, this.logs)
}
if ('path' in criteria) {
maybeDuplicatedLogsFiltered = handleFilterCallsWithOptions(criteria.path, finalOptions, this.filterCallsByPath, maybeDuplicatedLogsFiltered)
maybeDuplicatedLogsFiltered = handleFilterCallsWithOptions(criteria.path, finalOptions, this.filterCallsByPath, maybeDuplicatedLogsFiltered, this.logs)
}
if ('hash' in criteria) {
maybeDuplicatedLogsFiltered = handleFilterCallsWithOptions(criteria.hash, finalOptions, this.filterCallsByHash, maybeDuplicatedLogsFiltered)
maybeDuplicatedLogsFiltered = handleFilterCallsWithOptions(criteria.hash, finalOptions, this.filterCallsByHash, maybeDuplicatedLogsFiltered, this.logs)
}
if ('fullUrl' in criteria) {
maybeDuplicatedLogsFiltered = handleFilterCallsWithOptions(criteria.fullUrl, finalOptions, this.filterCallsByFullUrl, maybeDuplicatedLogsFiltered)
maybeDuplicatedLogsFiltered = handleFilterCallsWithOptions(criteria.fullUrl, finalOptions, this.filterCallsByFullUrl, maybeDuplicatedLogsFiltered, this.logs)
}
if ('method' in criteria) {
maybeDuplicatedLogsFiltered = handleFilterCallsWithOptions(criteria.method, finalOptions, this.filterCallsByMethod, maybeDuplicatedLogsFiltered)
maybeDuplicatedLogsFiltered = handleFilterCallsWithOptions(criteria.method, finalOptions, this.filterCallsByMethod, maybeDuplicatedLogsFiltered, this.logs)
}
const uniqLogsFiltered = [...new Set(maybeDuplicatedLogsFiltered)]
+1 -1
View File
@@ -18,7 +18,7 @@ function makeCacheKey (opts) {
let fullPath = opts.path || '/'
if (opts.query && !pathHasQueryOrFragment(opts.path)) {
if (opts.query && !pathHasQueryOrFragment(fullPath)) {
fullPath = serializePathWithQuery(fullPath, opts.query)
}
+245 -150
View File
@@ -23,6 +23,49 @@ const COLON = 0x3A
*/
const SPACE = 0x20
const DATA = Buffer.from('data')
const EVENT = Buffer.from('event')
const ID = Buffer.from('id')
const RETRY = Buffer.from('retry')
function isASCIINumberBytes (buffer, start) {
if (start >= buffer.length) {
return false
}
for (let i = start; i < buffer.length; i++) {
if (buffer[i] < 0x30 || buffer[i] > 0x39) {
return false
}
}
return true
}
function isValidLastEventIdBytes (buffer, start) {
for (let i = start; i < buffer.length; i++) {
if (buffer[i] === 0x00) {
return false
}
}
return true
}
function isFieldName (line, length, field) {
if (length !== field.length) {
return false
}
for (let i = 0; i < length; i++) {
if (line[i] !== field[i]) {
return false
}
}
return true
}
/**
* @typedef {object} EventSourceStreamEvent
* @type {object}
@@ -63,11 +106,14 @@ class EventSourceStream extends Transform {
eventEndCheck = false
/**
* @type {Buffer|null}
* @type {Buffer[]}
*/
buffer = null
chunks = []
chunkIndex = 0
pos = 0
lineChunkIndex = 0
linePos = 0
event = {
data: undefined,
@@ -107,92 +153,20 @@ class EventSourceStream extends Transform {
return
}
// Cache the chunk in the buffer, as the data might not be complete while
// processing it
// TODO: Investigate if there is a more performant way to handle
// incoming chunks
// see: https://github.com/nodejs/undici/issues/2630
if (this.buffer) {
this.buffer = Buffer.concat([this.buffer, chunk])
} else {
this.buffer = chunk
}
this.chunks.push(chunk)
// Strip leading byte-order-mark if we opened the stream and started
// the processing of the incoming data
if (this.checkBOM) {
switch (this.buffer.length) {
case 1:
// Check if the first byte is the same as the first byte of the BOM
if (this.buffer[0] === BOM[0]) {
// If it is, we need to wait for more data
callback()
return
}
// Set the checkBOM flag to false as we don't need to check for the
// BOM anymore
this.checkBOM = false
// The buffer only contains one byte so we need to wait for more data
callback()
return
case 2:
// Check if the first two bytes are the same as the first two bytes
// of the BOM
if (
this.buffer[0] === BOM[0] &&
this.buffer[1] === BOM[1]
) {
// If it is, we need to wait for more data, because the third byte
// is needed to determine if it is the BOM or not
callback()
return
}
// Set the checkBOM flag to false as we don't need to check for the
// BOM anymore
this.checkBOM = false
break
case 3:
// Check if the first three bytes are the same as the first three
// bytes of the BOM
if (
this.buffer[0] === BOM[0] &&
this.buffer[1] === BOM[1] &&
this.buffer[2] === BOM[2]
) {
// If it is, we can drop the buffered data, as it is only the BOM
this.buffer = Buffer.alloc(0)
// Set the checkBOM flag to false as we don't need to check for the
// BOM anymore
this.checkBOM = false
// Await more data
callback()
return
}
// If it is not the BOM, we can start processing the data
this.checkBOM = false
break
default:
// The buffer is longer than 3 bytes, so we can drop the BOM if it is
// present
if (
this.buffer[0] === BOM[0] &&
this.buffer[1] === BOM[1] &&
this.buffer[2] === BOM[2]
) {
// Remove the BOM from the buffer
this.buffer = this.buffer.subarray(3)
}
// Set the checkBOM flag to false as we don't need to check for the
this.checkBOM = false
break
if (this.handleBOM()) {
callback()
return
}
}
while (this.pos < this.buffer.length) {
while (this.hasCurrentByte()) {
const byte = this.currentByte()
// If the previous line ended with an end-of-line, we need to check
// if the next character is also an end-of-line.
if (this.eventEndCheck) {
@@ -205,10 +179,9 @@ class EventSourceStream extends Transform {
if (this.crlfCheck) {
// If the current character is a line feed, we can remove it
// from the buffer and reset the crlfCheck flag
if (this.buffer[this.pos] === LF) {
this.buffer = this.buffer.subarray(this.pos + 1)
this.pos = 0
if (byte === LF) {
this.crlfCheck = false
this.consumeCurrentByte()
// It is possible that the line feed is not the end of the
// event. We need to check if the next character is an
@@ -224,19 +197,17 @@ class EventSourceStream extends Transform {
this.crlfCheck = false
}
if (this.buffer[this.pos] === LF || this.buffer[this.pos] === CR) {
if (byte === LF || byte === CR) {
// If the current character is a carriage return, we need to
// set the crlfCheck flag to true, as we need to check if the
// next character is a line feed so we can remove it from the
// buffer
if (this.buffer[this.pos] === CR) {
if (byte === CR) {
this.crlfCheck = true
}
this.buffer = this.buffer.subarray(this.pos + 1)
this.pos = 0
if (
this.event.data !== undefined || this.event.event || this.event.id !== undefined || this.event.retry) {
this.consumeCurrentByte()
if (this.hasPendingEvent()) {
this.processEvent(this.event)
}
this.clearEvent()
@@ -250,22 +221,18 @@ class EventSourceStream extends Transform {
// If the current character is an end-of-line, we can process the
// line
if (this.buffer[this.pos] === LF || this.buffer[this.pos] === CR) {
if (byte === LF || byte === CR) {
// If the current character is a carriage return, we need to
// set the crlfCheck flag to true, as we need to check if the
// next character is a line feed
if (this.buffer[this.pos] === CR) {
if (byte === CR) {
this.crlfCheck = true
}
// In any case, we can process the line as we reached an
// end-of-line character
this.parseLine(this.buffer.subarray(0, this.pos), this.event)
// Remove the processed line from the buffer
this.buffer = this.buffer.subarray(this.pos + 1)
// Reset the position as we removed the processed line from the buffer
this.pos = 0
this.parseLine(this.readLine(), this.event)
this.consumeCurrentByte()
// A line was processed and this could be the end of the event. We need
// to check if the next line is empty to determine if the event is
// finished.
@@ -273,7 +240,7 @@ class EventSourceStream extends Transform {
continue
}
this.pos++
this.advanceCursor()
}
callback()
@@ -298,64 +265,53 @@ class EventSourceStream extends Transform {
return
}
let field = ''
let value = ''
let fieldLength = line.length
let valueStart = line.length
// If the line contains a U+003A COLON character (:)
if (colonPosition !== -1) {
// Collect the characters on the line before the first U+003A COLON
// character (:), and let field be that string.
// TODO: Investigate if there is a more performant way to extract the
// field
// see: https://github.com/nodejs/undici/issues/2630
field = line.subarray(0, colonPosition).toString('utf8')
fieldLength = colonPosition
// Collect the characters on the line after the first U+003A COLON
// character (:), and let value be that string.
// If value starts with a U+0020 SPACE character, remove it from value.
let valueStart = colonPosition + 1
valueStart = colonPosition + 1
if (line[valueStart] === SPACE) {
++valueStart
}
// TODO: Investigate if there is a more performant way to extract the
// value
// see: https://github.com/nodejs/undici/issues/2630
value = line.subarray(valueStart).toString('utf8')
// Otherwise, the string is not empty but does not contain a U+003A COLON
// character (:)
} else {
// Process the field using the steps described below, using the whole
// line as the field name, and the empty string as the field value.
field = line.toString('utf8')
value = ''
}
// Modify the event with the field name and value. The value is also
// decoded as UTF-8
switch (field) {
case 'data':
if (event[field] === undefined) {
event[field] = value
} else {
event[field] += `\n${value}`
}
break
case 'retry':
if (isASCIINumber(value)) {
event[field] = value
}
break
case 'id':
if (isValidLastEventId(value)) {
event[field] = value
}
break
case 'event':
if (value.length > 0) {
event[field] = value
}
break
if (isFieldName(line, fieldLength, DATA)) {
const value = line.toString('utf8', valueStart)
if (event.data === undefined) {
event.data = value
} else {
event.data += `\n${value}`
}
return
}
if (isFieldName(line, fieldLength, RETRY)) {
if (isASCIINumberBytes(line, valueStart)) {
event.retry = line.toString('utf8', valueStart)
}
return
}
if (isFieldName(line, fieldLength, ID)) {
if (isValidLastEventIdBytes(line, valueStart)) {
event.id = line.toString('utf8', valueStart)
}
return
}
if (isFieldName(line, fieldLength, EVENT)) {
const value = line.toString('utf8', valueStart)
if (value.length > 0) {
event.event = value
}
}
}
@@ -385,13 +341,152 @@ class EventSourceStream extends Transform {
}
clearEvent () {
this.event = {
data: undefined,
event: undefined,
id: undefined,
retry: undefined
this.event.data = undefined
this.event.event = undefined
this.event.id = undefined
this.event.retry = undefined
}
hasPendingEvent () {
return this.event.data !== undefined ||
this.event.event !== undefined ||
this.event.id !== undefined ||
this.event.retry !== undefined
}
hasCurrentByte () {
return this.chunkIndex < this.chunks.length &&
this.pos < this.chunks[this.chunkIndex].length
}
currentByte () {
return this.chunks[this.chunkIndex][this.pos]
}
consumeCurrentByte () {
this.advanceCursor()
this.syncLineStartToCursor()
}
advanceCursor () {
this.pos++
while (this.chunkIndex < this.chunks.length && this.pos >= this.chunks[this.chunkIndex].length) {
this.chunkIndex++
this.pos = 0
}
}
syncLineStartToCursor () {
this.lineChunkIndex = this.chunkIndex
this.linePos = this.pos
this.dropConsumedChunks()
}
dropConsumedChunks () {
while (this.lineChunkIndex > 0) {
this.chunks.shift()
this.lineChunkIndex--
this.chunkIndex--
}
if (this.chunkIndex === this.chunks.length) {
this.chunks.length = 0
this.chunkIndex = 0
this.pos = 0
this.lineChunkIndex = 0
this.linePos = 0
}
}
readLine () {
if (this.lineChunkIndex === this.chunkIndex) {
return this.chunks[this.chunkIndex].subarray(this.linePos, this.pos)
}
const chunks = []
let length = 0
for (let i = this.lineChunkIndex; i <= this.chunkIndex; i++) {
const chunk = this.chunks[i]
const start = i === this.lineChunkIndex ? this.linePos : 0
const end = i === this.chunkIndex ? this.pos : chunk.length
const slice = chunk.subarray(start, end)
length += slice.length
chunks.push(slice)
}
return Buffer.concat(chunks, length)
}
peekBufferedByte (offset) {
let chunkIndex = this.lineChunkIndex
let pos = this.linePos
while (chunkIndex < this.chunks.length) {
const chunk = this.chunks[chunkIndex]
const remaining = chunk.length - pos
if (offset < remaining) {
return chunk[pos + offset]
}
offset -= remaining
chunkIndex++
pos = 0
}
}
discardLeadingBytes (count) {
while (count > 0 && this.lineChunkIndex < this.chunks.length) {
const chunk = this.chunks[this.lineChunkIndex]
const remaining = chunk.length - this.linePos
if (count < remaining) {
this.linePos += count
count = 0
} else {
count -= remaining
this.lineChunkIndex++
this.linePos = 0
}
}
this.chunkIndex = this.lineChunkIndex
this.pos = this.linePos
this.dropConsumedChunks()
}
handleBOM () {
const first = this.peekBufferedByte(0)
const second = this.peekBufferedByte(1)
const third = this.peekBufferedByte(2)
if (second === undefined) {
if (first === BOM[0]) {
return true
}
this.checkBOM = false
return true
}
if (third === undefined) {
if (first === BOM[0] && second === BOM[1]) {
return true
}
this.checkBOM = false
return false
}
if (first === BOM[0] && second === BOM[1] && third === BOM[2]) {
this.discardLeadingBytes(3)
}
this.checkBOM = false
return !this.hasCurrentByte()
}
}
module.exports = {
+17 -6
View File
@@ -204,7 +204,7 @@ function multipartFormDataParser (input, mimeType) {
* Parses content-disposition attributes (e.g., name="value" or filename*=utf-8''encoded)
* @param {Buffer} input
* @param {{ position: number }} position
* @returns {{ name: string, value: string }}
* @returns {{ name: string, value: string, extended: boolean } | null}
*/
function parseContentDispositionAttribute (input, position) {
// Skip leading semicolon and whitespace
@@ -304,7 +304,7 @@ function parseContentDispositionAttribute (input, position) {
value = decoder.decode(tokenValue)
}
return { name: attrNameStr, value }
return { name: attrNameStr, value, extended: isExtended }
}
/**
@@ -368,6 +368,9 @@ function parseMultipartFormDataHeaders (input, position) {
switch (bufferToLowerCasedHeaderName(headerName)) {
case 'content-disposition': {
name = filename = null
// Track whether filename was set from the extended (RFC 5987) form so
// a subsequent legacy `filename` attribute does not override it.
let filenameIsExtended = false
// Collect the disposition type (should be "form-data")
const dispositionType = collectASequenceOfBytes(
@@ -383,8 +386,8 @@ function parseMultipartFormDataHeaders (input, position) {
// Parse attributes recursively until CRLF
while (
position.position < input.length &&
input[position.position] !== 0x0d &&
input[position.position + 1] !== 0x0a
(input[position.position] !== 0x0d ||
input[position.position + 1] !== 0x0a)
) {
const attribute = parseContentDispositionAttribute(input, position)
@@ -395,7 +398,15 @@ function parseMultipartFormDataHeaders (input, position) {
if (attribute.name === 'name') {
name = attribute.value
} else if (attribute.name === 'filename') {
filename = attribute.value
// Per RFC 5987 §4.1, when both legacy and extended forms of the
// same parameter are present, the extended (filename*) form takes
// precedence regardless of the order they appear in.
if (attribute.extended) {
filename = attribute.value
filenameIsExtended = true
} else if (!filenameIsExtended) {
filename = attribute.value
}
}
}
@@ -448,7 +459,7 @@ function parseMultipartFormDataHeaders (input, position) {
// 2.9. If position does not point to a sequence of bytes starting with 0x0D 0x0A
// (CR LF), return failure. Otherwise, advance position by 2 (past the newline).
if (input[position.position] !== 0x0d && input[position.position + 1] !== 0x0a) {
if (input[position.position] !== 0x0d || input[position.position + 1] !== 0x0a) {
throw parsingError('expected CRLF')
} else {
position.position += 2
+38 -28
View File
@@ -75,6 +75,35 @@ const defaultUserAgent = typeof __UNDICI_IS_NODE__ !== 'undefined' || typeof esb
/** @type {import('buffer').resolveObjectURL} */
let resolveObjectURL
function appendHeadersListFromResponseHeaders (headersList, headers, rawHeaders) {
if (Array.isArray(rawHeaders)) {
for (let i = 0; i < rawHeaders.length; i += 2) {
const nameStr = bufferToLowerCasedHeaderName(rawHeaders[i])
const value = rawHeaders[i + 1]
if (Array.isArray(value) && !Buffer.isBuffer(value)) {
for (const val of value) {
headersList.append(nameStr, val.toString('latin1'), true)
}
} else {
headersList.append(nameStr, value.toString('latin1'), true)
}
}
return
}
for (const [name, value] of Object.entries(headers ?? {})) {
if (Array.isArray(value)) {
for (const entry of value) {
headersList.append(name, `${entry}`, true)
}
} else {
headersList.append(name, `${value}`, true)
}
}
}
class Fetch extends EE {
constructor (dispatcher) {
super()
@@ -1025,7 +1054,7 @@ function fetchFinale (fetchParams, response) {
let responseStatus = 0
// 7. If fetchParams’s request’s mode is not "navigate" or response’s has-cross-origin-redirects is false:
if (fetchParams.request.mode !== 'navigator' || !response.hasCrossOriginRedirects) {
if (fetchParams.request.mode !== 'navigate' || !response.hasCrossOriginRedirects) {
// 1. Set responseStatus to response’s status.
responseStatus = response.status
@@ -1428,7 +1457,10 @@ async function httpNetworkOrCacheFetch (
// 8. If contentLengthHeaderValue is non-null, then append
// `Content-Length`/contentLengthHeaderValue to httpRequest’s header
// list.
if (contentLengthHeaderValue != null) {
if (
contentLengthHeaderValue != null &&
!httpRequest.headersList.contains('content-length', true)
) {
httpRequest.headersList.append('content-length', contentLengthHeaderValue, true)
}
@@ -2193,25 +2225,14 @@ async function httpNetworkFetch (
timingInfo.finalNetworkResponseStartTime = coarsenedSharedCurrentTime(fetchParams.crossOriginIsolatedCapability)
},
onResponseStart (controller, status, _headers, statusText) {
onResponseStart (controller, status, headers, statusText) {
if (status < 200) {
return
}
const rawHeaders = controller?.rawHeaders ?? []
const headersList = new HeadersList()
for (let i = 0; i < rawHeaders.length; i += 2) {
const nameStr = bufferToLowerCasedHeaderName(rawHeaders[i])
const value = rawHeaders[i + 1]
if (Array.isArray(value) && !Buffer.isBuffer(rawHeaders[i + 1])) {
for (const val of value) {
headersList.append(nameStr, val.toString('latin1'), true)
}
} else {
headersList.append(nameStr, value.toString('latin1'), true)
}
}
appendHeadersListFromResponseHeaders(headersList, headers, rawHeaders)
const location = headersList.get('location', true)
this.body = new Readable({ read: () => controller.resume() })
@@ -2346,7 +2367,7 @@ async function httpNetworkFetch (
reject(error)
},
onRequestUpgrade (controller, status, _headers, socket) {
onRequestUpgrade (controller, status, headers, socket) {
// We need to support 200 for websocket over h2 as per RFC-8441
// Absence of session means H1
if ((socket.session != null && status !== 200) || (socket.session == null && status !== 101)) {
@@ -2355,18 +2376,7 @@ async function httpNetworkFetch (
const rawHeaders = controller?.rawHeaders ?? []
const headersList = new HeadersList()
for (let i = 0; i < rawHeaders.length; i += 2) {
const nameStr = bufferToLowerCasedHeaderName(rawHeaders[i])
const value = rawHeaders[i + 1]
if (Array.isArray(value) && !Buffer.isBuffer(rawHeaders[i + 1])) {
for (const val of value) {
headersList.append(nameStr, val.toString('latin1'), true)
}
} else {
headersList.append(nameStr, value.toString('latin1'), true)
}
}
appendHeadersListFromResponseHeaders(headersList, headers, rawHeaders)
resolve({
status,
+5 -5
View File
@@ -188,10 +188,10 @@ webidl.util.ConvertToInt = function (V, bitLength, signedness, flags) {
} else {
// 3. Otherwise:
// 1. Let lowerBound be -2^bitLength − 1.
lowerBound = Math.pow(-2, bitLength) - 1
// 1. Let lowerBound be -2^(bitLength − 1).
lowerBound = -Math.pow(2, bitLength - 1)
// 2. Let upperBound be 2^bitLength − 1 − 1.
// 2. Let upperBound be 2^(bitLength − 1) − 1.
upperBound = Math.pow(2, bitLength - 1) - 1
}
@@ -270,9 +270,9 @@ webidl.util.ConvertToInt = function (V, bitLength, signedness, flags) {
// 10. Set x to x modulo 2^bitLength.
x = x % Math.pow(2, bitLength)
// 11. If signedness is "signed" and x ≥ 2^bitLength − 1,
// 11. If signedness is "signed" and x ≥ 2^(bitLength − 1),
// then return x − 2^bitLength.
if (signedness === 'signed' && x >= Math.pow(2, bitLength) - 1) {
if (signedness === 'signed' && x >= Math.pow(2, bitLength - 1)) {
return x - Math.pow(2, bitLength)
}
+1 -7
View File
@@ -10,13 +10,7 @@ let bufIdx = BUFFER_SIZE
const randomFillSync = runtimeFeatures.has('crypto')
? require('node:crypto').randomFillSync
// not full compatibility, but minimum.
: function randomFillSync (buffer, _offset, _size) {
for (let i = 0; i < buffer.length; ++i) {
buffer[i] = Math.random() * 255 | 0
}
return buffer
}
: null
function generateMask () {
if (bufIdx === BUFFER_SIZE) {
@@ -1,6 +1,7 @@
'use strict'
const { environmentSettingsObject } = require('../../fetch/util')
const { addAbortListener } = require('node:events')
const { environmentSettingsObject, readableStreamClose } = require('../../fetch/util')
const { states, opcodes, sentCloseFrameState } = require('../constants')
const { webidl } = require('../../webidl')
const { getURLRecord, isValidSubprotocol, isEstablished, utf8Decode } = require('../util')
@@ -132,7 +133,7 @@ class WebSocketStream {
}
// 8.3. Add the following abort steps to signal :
signal.addEventListener('abort', () => {
addAbortListener(signal, () => {
// 8.3.1. If the WebSocket connection is not yet established : [WSP]
if (!isEstablished(this.#handler.readyState)) {
// 8.3.1.1. Fail the WebSocket connection .
@@ -148,7 +149,7 @@ class WebSocketStream {
// Set this 's handshake aborted to true.
this.#handshakeAborted = true
}
}, { once: true })
})
}
// 9. Let client be this 's relevant settings object .
@@ -331,7 +332,7 @@ class WebSocketStream {
try {
chunk = utf8Decode(data)
} catch {
failWebsocketConnection(this.#handler, 'Received invalid UTF-8 in text frame.')
failWebsocketConnection(this.#handler, 1007, 'Received invalid UTF-8 in text frame.')
return
}
} else if (type === opcodes.BINARY) {
@@ -385,7 +386,7 @@ class WebSocketStream {
// 6. If the connection was closed cleanly ,
if (wasClean) {
// 6.1. Close stream ’s readable stream .
this.#readableStreamController.close()
readableStreamClose(this.#readableStreamController)
// 6.2. Error stream ’s writable stream with an " InvalidStateError " DOMException indicating that a closed WebSocketStream cannot be written to.
if (!this.#writableStream.locked) {
+2 -2
View File
@@ -1,12 +1,12 @@
{
"name": "undici",
"version": "8.1.0",
"version": "8.2.0",
"lockfileVersion": 3,
"requires": true,
"packages": {
"": {
"name": "undici",
"version": "8.1.0",
"version": "8.2.0",
"license": "MIT",
"devDependencies": {
"@fastify/busboy": "3.2.0",
+1 -1
View File
@@ -1,6 +1,6 @@
{
"name": "undici",
"version": "8.1.0",
"version": "8.2.0",
"description": "An HTTP/1.1 client, written from scratch for Node.js",
"homepage": "https://undici.nodejs.org",
"bugs": {
+4 -4
View File
@@ -2,7 +2,7 @@ import { URL } from 'node:url'
import { Duplex, Readable, Writable } from 'node:stream'
import { EventEmitter } from 'node:events'
import { Blob } from 'node:buffer'
import { IncomingHttpHeaders } from './header'
import { IncomingHttpHeaders, OutgoingHttpHeaders } from './header'
import BodyReadable from './readable'
import { FormData } from './formdata'
import Errors from './errors'
@@ -10,7 +10,7 @@ import { Autocomplete } from './utility'
export default Dispatcher
export type UndiciHeaders = Record<string, string | string[]> | IncomingHttpHeaders | string[] | Iterable<[string, string | string[] | undefined]> | null
export type UndiciHeaders = OutgoingHttpHeaders | string[] | Iterable<[string, string | string[] | undefined]> | null
/** Dispatcher is the core API used to dispatch requests. */
declare class Dispatcher extends EventEmitter {
@@ -210,8 +210,8 @@ declare namespace Dispatcher {
get aborted(): boolean
get paused(): boolean
get reason(): Error | null
rawHeaders?: Buffer[] | string[] | null
rawTrailers?: Buffer[] | string[] | null
rawHeaders?: Buffer[] | string[] | IncomingHttpHeaders | null
rawTrailers?: Buffer[] | string[] | IncomingHttpHeaders | null
abort(reason: Error): void
pause(): void
resume(): void
+5
View File
@@ -5,6 +5,11 @@ import { Autocomplete } from './utility'
*/
export type IncomingHttpHeaders = Record<string, string | string[] | undefined>
/**
* The header type declaration of `undici` for outgoing requests.
*/
export type OutgoingHttpHeaders = Record<string, number | string | string[] | undefined>
type HeaderNames = Autocomplete<
| 'Accept'
| 'Accept-CH'
+1 -1
View File
@@ -8,7 +8,7 @@ export default Interceptors
declare namespace Interceptors {
export type DumpInterceptorOpts = { maxSize?: number }
export type RetryInterceptorOpts = RetryHandler.RetryOptions
export type RedirectInterceptorOpts = { maxRedirections?: number }
export type RedirectInterceptorOpts = { maxRedirections?: number, throwOnMaxRedirect?: boolean }
export type DecompressInterceptorOpts = {
skipErrorResponses?: boolean
skipStatusCodes?: number[]
+2 -2
View File
@@ -1,7 +1,7 @@
import Agent from './agent'
import buildConnector from './connector'
import Dispatcher from './dispatcher'
import { IncomingHttpHeaders } from './header'
import { OutgoingHttpHeaders } from './header'
export default ProxyAgent
@@ -20,7 +20,7 @@ declare namespace ProxyAgent {
*/
auth?: string;
token?: string;
headers?: IncomingHttpHeaders;
headers?: OutgoingHttpHeaders;
requestTls?: buildConnector.BuildOptions;
proxyTls?: buildConnector.BuildOptions;
clientFactory?(origin: URL, opts: object): Dispatcher;
+2 -2
View File
@@ -1,6 +1,6 @@
import Dispatcher from './dispatcher'
import buildConnector from './connector'
import { IncomingHttpHeaders } from './header'
import { OutgoingHttpHeaders } from './header'
import Pool from './pool'
export default Socks5ProxyAgent
@@ -12,7 +12,7 @@ declare class Socks5ProxyAgent extends Dispatcher {
declare namespace Socks5ProxyAgent {
export interface Options extends Pool.Options {
/** Additional headers to send with the proxy connection */
headers?: IncomingHttpHeaders;
headers?: OutgoingHttpHeaders;
/** SOCKS5 proxy username for authentication */
username?: string;
/** SOCKS5 proxy password for authentication */
+800 -377
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 "8.1.0"
#define UNDICI_VERSION "8.2.0"
#endif // SRC_UNDICI_VERSION_H_