From a94feb5b6c0a7e35a5ba3ca0b1d96c4e8f7c04bb Mon Sep 17 00:00:00 2001 From: robobun <117481402+robobun@users.noreply.github.com> Date: Fri, 14 Aug 2026 19:02:02 +0000 Subject: [PATCH 1/2] node:http2: build getUnpackedSettings/respondWithFD ERR_INVALID_ARG_TYPE through the shared error machinery getUnpackedSettings() and Http2Stream#respondWithFD() assembled their ERR_INVALID_ARG_TYPE messages by hand through a private receivedValueLabel() helper. It JSON.stringify'd bigints (so getUnpackedSettings(1n) threw a plain "JSON.stringify cannot serialize BigInt." TypeError with no code), did not truncate long strings, did not switch to double quotes for strings containing a quote, rendered null-prototype objects as "an instance of Object" and undefined as "type undefined (undefined)". Both sites now throw $ERR_INVALID_ARG_TYPE with the same expected-type lists node passes (['Buffer', 'TypedArray'] and ['number', 'FileHandle']); the native renderer already groups those into node's "of type ... or an instance of ..." wording and describes the received value like node. getUnpackedSettings(undefined) now throws like node instead of returning the defaults; getDefaultSettings() builds the defaults itself. respondWithFD() only unwraps a real FileHandle (instanceof, as node does) rather than any object with a numeric fd property, and the FileHandle branch further down, unreachable since the descriptor is unwrapped up front, is removed. --- src/js/node/http2.ts | 55 ++++--------------- test/js/node/http2/node-http2.test.js | 79 ++++++++++++++++++++++++++- 2 files changed, 88 insertions(+), 46 deletions(-) diff --git a/src/js/node/http2.ts b/src/js/node/http2.ts index ff7409618401..d78571204ad4 100644 --- a/src/js/node/http2.ts +++ b/src/js/node/http2.ts @@ -284,20 +284,9 @@ function getPackedSettings(settings?: any): Buffer { return buf; } -function getUnpackedSettings(buf?: any, options?: any): any { - if (buf === undefined) { - return { ...kDefaultSettings }; - } - - if (!Buffer.isBuffer(buf) && !isTypedArray(buf)) { - { - // node renders this as instance-of (class names), not of-type. - const err = new TypeError( - `The "buf" argument must be an instance of Buffer or TypedArray. Received ` + receivedValueLabel(buf), - ); - err.code = "ERR_INVALID_ARG_TYPE"; - throw err; - } +function getUnpackedSettings(buf: any, options?: any): any { + if (!isTypedArray(buf)) { + throw $ERR_INVALID_ARG_TYPE("buf", ["Buffer", "TypedArray"], buf); } if (buf.length % 6 !== 0) { @@ -3564,18 +3553,10 @@ class ServerHttp2Stream extends Http2Stream { fs.open(path, "r", afterOpen.bind(this, options || {}, headers)); } respondWithFD(fd, headers, options) { - if (typeof fd !== "number") { - // node accepts a FileHandle too; unwrap its descriptor. - if (fd !== null && typeof fd === "object" && typeof fd.fd === "number") { - fd = fd.fd; - } else { - const err = new TypeError( - `The "fd" argument must be of type number or an instance of FileHandle.` + - ` Received ${receivedValueLabel(fd)}`, - ); - err.code = "ERR_INVALID_ARG_TYPE"; - throw err; - } + if (fd instanceof FileHandle) { + fd = fd.fd; + } else if (typeof fd !== "number") { + throw $ERR_INVALID_ARG_TYPE("fd", ["number", "FileHandle"], fd); } if (this.destroyed) { throw $ERR_HTTP2_INVALID_STREAM(); @@ -3628,11 +3609,7 @@ class ServerHttp2Stream extends Http2Stream { // stream.end() right after it is a no-op instead of ending the stream before the file. closeWritableForFileResponse(this); } - if (fd instanceof FileHandle) { - fs.fstat(fd.fd, doSendFileFD.bind(this, options, fd, headers)); - } else { - fs.fstat(fd, doSendFileFD.bind(this, options, fd, headers)); - } + fs.fstat(fd, doSendFileFD.bind(this, options, fd, headers)); } additionalHeaders(headers) { if (this.destroyed || this.closed || this.session === undefined) { @@ -4035,17 +4012,6 @@ function assertSingleValueHeaders(headers) { } } -// Renders a received value the way node's determineSpecificType does for error messages. -function receivedValueLabel(value) { - if (value === null) return "null"; - if (typeof value === "object") return "an instance of " + (value.constructor?.name || "Object"); - if (typeof value === "function") return `function ${value.name}`; - if (typeof value === "string") return `type string ('${value}')`; - if (typeof value === "symbol") return `type symbol (${String(value)})`; - if (typeof value === "number") return `type number (${String(value)})`; - return `type ${typeof value} (${JSON.stringify(value)})`; -} - function buildSensitiveNames(headers, sensitives) { const map = {}; if (sensitives) { @@ -6860,9 +6826,8 @@ function performServerHandshake(socket, options = {}) { options = initializeOptions(options); return new ServerHttp2Session(socket, options, undefined); } -function getDefaultSettings() { - // return default settings - return getUnpackedSettings(); +function getDefaultSettings(): any { + return { ...kDefaultSettings }; } Object.defineProperty(connect, promisify.custom, { diff --git a/test/js/node/http2/node-http2.test.js b/test/js/node/http2/node-http2.test.js index 26f4f42a1597..0c3063909e28 100644 --- a/test/js/node/http2/node-http2.test.js +++ b/test/js/node/http2/node-http2.test.js @@ -1,4 +1,4 @@ -import { bunEnv, bunExe, isASAN, isCI, isDebug, nodeExe } from "harness"; +import { bunEnv, bunExe, isASAN, isCI, isDebug, nodeExe, tempDir } from "harness"; import { createTest } from "node-harness"; import { AsyncLocalStorage } from "node:async_hooks"; import dc from "node:diagnostics_channel"; @@ -4070,6 +4070,83 @@ it("http2 stream.respond accepts raw-headers arrays; respondWithFD/respondWithFi server.close(); } }); + +// Rejected values paired with how node v26.3.0's ERR_INVALID_ARG_TYPE describes each of them. +const invalidArgTypeCases = [ + [1n, "type bigint (1n)"], + ["a".repeat(40), "type string ('aaaaaaaaaaaaaaaaaaaaaaaaa...')"], + ["it's", `type string ("it's")`], + [Object.create(null), "[Object: null prototype] {}"], + [undefined, "undefined"], + [null, "null"], + [true, "type boolean (true)"], + [{}, "an instance of Object"], + [new DataView(new ArrayBuffer(6)), "an instance of DataView"], +]; + +function collectInvalidArgTypeErrors(cases, invoke) { + return cases.map(([value]) => { + try { + invoke(value); + return "did not throw"; + } catch (err) { + return { name: err.constructor.name, code: err.code, message: err.message }; + } + }); +} + +it("http2 getUnpackedSettings() reports a bad buf argument like node", () => { + expect(collectInvalidArgTypeErrors(invalidArgTypeCases, value => http2.getUnpackedSettings(value))).toEqual( + invalidArgTypeCases.map(([, received]) => ({ + name: "TypeError", + code: "ERR_INVALID_ARG_TYPE", + message: `The "buf" argument must be an instance of Buffer or TypedArray. Received ${received}`, + })), + ); +}); + +it("http2 stream.respondWithFD() reports a bad fd argument like node and accepts a FileHandle", async () => { + using dir = tempDir("http2-respond-with-fd", { "body.txt": "served from a FileHandle" }); + const fileHandle = await fs.promises.open(path.join(String(dir), "body.txt"), "r"); + // Only a real FileHandle stands in for a number; node rejects other objects carrying an fd property. + const cases = [...invalidArgTypeCases, [{ fd: fileHandle.fd }, "an instance of Object"]]; + let errors; + const server = http2.createServer(); + server.on("stream", stream => { + errors = collectInvalidArgTypeErrors(cases, value => stream.respondWithFD(value)); + stream.respondWithFD(fileHandle, { "content-type": "text/plain" }); + }); + await new Promise(resolve => server.listen(0, resolve)); + const client = http2.connect(`http://localhost:${server.address().port}`); + + try { + const req = client.request({ ":path": "/" }); + const response = await new Promise((resolve, reject) => { + req.on("error", reject); + req.on("response", resolve); + req.end(); + }); + let body = ""; + req.setEncoding("utf8"); + req.on("data", chunk => (body += chunk)); + await new Promise(resolve => req.on("end", resolve)); + + expect(errors).toEqual( + cases.map(([, received]) => ({ + name: "TypeError", + code: "ERR_INVALID_ARG_TYPE", + message: `The "fd" argument must be of type number or an instance of FileHandle. Received ${received}`, + })), + ); + expect(response[":status"]).toBe(200); + expect(body).toBe("served from a FileHandle"); + } finally { + client.close(); + server.close(); + await fileHandle.close(); + } +}); + it("http2 client.request() on a destroyed or closed session uses the right error codes", async () => { // Node: destroyed session -> ERR_HTTP2_INVALID_SESSION, // closed (GOAWAY-pending) session -> ERR_HTTP2_GOAWAY_SESSION. From 86dcf726655f35c2b468397c1018be0ae99e1e17 Mon Sep 17 00:00:00 2001 From: robobun <117481402+robobun@users.noreply.github.com> Date: Fri, 14 Aug 2026 19:18:26 +0000 Subject: [PATCH 2/2] test: reject the respondWithFD request promise on session/stream/listen errors --- test/js/node/http2/node-http2.test.js | 25 ++++++++++++++++--------- 1 file changed, 16 insertions(+), 9 deletions(-) diff --git a/test/js/node/http2/node-http2.test.js b/test/js/node/http2/node-http2.test.js index 0c3063909e28..a9393d9fdf04 100644 --- a/test/js/node/http2/node-http2.test.js +++ b/test/js/node/http2/node-http2.test.js @@ -4116,20 +4116,27 @@ it("http2 stream.respondWithFD() reports a bad fd argument like node and accepts errors = collectInvalidArgTypeErrors(cases, value => stream.respondWithFD(value)); stream.respondWithFD(fileHandle, { "content-type": "text/plain" }); }); - await new Promise(resolve => server.listen(0, resolve)); - const client = http2.connect(`http://localhost:${server.address().port}`); + let client; try { - const req = client.request({ ":path": "/" }); - const response = await new Promise((resolve, reject) => { - req.on("error", reject); - req.on("response", resolve); - req.end(); + await new Promise((resolve, reject) => { + server.once("error", reject); + server.listen(0, resolve); }); + client = http2.connect(`http://localhost:${server.address().port}`); + + const { promise: finished, resolve, reject } = Promise.withResolvers(); + client.on("error", reject); + const req = client.request({ ":path": "/" }); + req.on("error", reject); + let response; + req.on("response", headers => (response = headers)); let body = ""; req.setEncoding("utf8"); req.on("data", chunk => (body += chunk)); - await new Promise(resolve => req.on("end", resolve)); + req.on("end", resolve); + req.end(); + await finished; expect(errors).toEqual( cases.map(([, received]) => ({ @@ -4141,7 +4148,7 @@ it("http2 stream.respondWithFD() reports a bad fd argument like node and accepts expect(response[":status"]).toBe(200); expect(body).toBe("served from a FileHandle"); } finally { - client.close(); + client?.close(); server.close(); await fileHandle.close(); }