From a45ac598646eb29c6f08c83d06e700af140a3940 Mon Sep 17 00:00:00 2001 From: robobun <117481402+robobun@users.noreply.github.com> Date: Thu, 13 Aug 2026 08:36:18 +0000 Subject: [PATCH 1/8] node:http2: report an injected socket's error on the session instead of leaving it uncaught --- src/js/node/_http2_upgrade.ts | 19 ++++++++ .../js/node/http2/node-http2-upgrade.test.mts | 45 +++++++++++++++++++ 2 files changed, 64 insertions(+) diff --git a/src/js/node/_http2_upgrade.ts b/src/js/node/_http2_upgrade.ts index 354267a9f34d..47ef4ab4b37e 100644 --- a/src/js/node/_http2_upgrade.ts +++ b/src/js/node/_http2_upgrade.ts @@ -246,6 +246,23 @@ function socketHandshake( tlsSocket.resume(); } +// --------------------------------------------------------------------------- +// Raw socket listeners bound to tlsSocket +// --------------------------------------------------------------------------- + +// error: the transport under the TLS layer failed (reset, EPIPE, destroy(err)). +// Node's TLSSocket re-emits the wrapped socket's errors on itself, so they +// reach the session's socket error handling and the socket handed in never +// emits an unhandled 'error': +// https://github.com/nodejs/node/blob/v26.3.0/lib/internal/tls/wrap.js#L977 +// Stays attached for the raw socket's lifetime (it is still flushing after the +// session is gone), hence the destroyed check. +function onRawSocketError(this: TLSProxySocket, err: Error) { + if (!this.destroyed) { + this.destroy(err); + } +} + // --------------------------------------------------------------------------- // Close-cleanup handler // --------------------------------------------------------------------------- @@ -253,6 +270,7 @@ function socketHandshake( // onTlsClose: when the TLS socket closes (e.g. H2 session destroyed), clean up // the raw socket listeners to prevent memory leaks and stale callback references. // EventEmitter calls 'close' handlers with `this` = emitter (tlsSocket). +// The 'error' listener is deliberately left in place (see onRawSocketError). function onTlsClose(this: TLSProxySocket) { const ctx = this._ctx; const raw = ctx.rawSocket; @@ -386,6 +404,7 @@ function upgradeRawSocketToH2( rawSocket.on("end", events[1]); rawSocket.on("drain", events[2]); rawSocket.on("close", events[3]); + rawSocket.on("error", onRawSocketError.bind(tlsSocket)); // When the TLS socket closes (e.g. H2 session destroyed), clean up the raw socket // listeners to prevent memory leaks and stale callback references. diff --git a/test/js/node/http2/node-http2-upgrade.test.mts b/test/js/node/http2/node-http2-upgrade.test.mts index 57a8b73d93bc..35a70d959307 100644 --- a/test/js/node/http2/node-http2-upgrade.test.mts +++ b/test/js/node/http2/node-http2-upgrade.test.mts @@ -277,6 +277,51 @@ describe("HTTP/2 upgrade — socket close ordering", () => { client.close(); netServer.close(); }); + + test("an error on rawSocket is the session's error, not an uncaught exception", async () => { + // Nothing but the upgrade listens on rawSocket once it has been handed + // over, so its error (a reset, EPIPE, a destroy(err) by its owner) has to + // be reported the way a TLSSocket reports its wrapped socket's errors: the + // session is destroyed with it and the server sees 'sessionError'. + let rawSocket: net.Socket | undefined; + const sessionReady = Promise.withResolvers(); + const sessionErrored = Promise.withResolvers<{ err: Error; session: http2.Http2Session }>(); + + const h2Server = http2.createSecureServer(TLS, (_req, res) => { + res.writeHead(200); + res.end("done"); + }); + h2Server.on("error", () => {}); + h2Server.on("session", s => sessionReady.resolve(s)); + h2Server.on("sessionError", (err: Error, session: http2.Http2Session) => sessionErrored.resolve({ err, session })); + + const netServer = net.createServer(socket => { + rawSocket = socket; + h2Server.emit("connection", socket); + }); + + const port = await new Promise(resolve => { + netServer.listen(0, "127.0.0.1", () => resolve((netServer.address() as net.AddressInfo).port)); + }); + + const client = connectClient(port); + await request(client, "GET", "/"); + const h2Session = await sessionReady.promise; + // Not events.once(): the session emits 'error' on its way to 'close'. + const sessionClosed = new Promise(resolve => h2Session.once("close", resolve)); + + rawSocket!.destroy(new Error("transport failed")); + + await sessionClosed; + const { err, session } = await sessionErrored.promise; + assert.deepStrictEqual( + { message: err.message, sameSession: session === h2Session, destroyed: h2Session.destroyed }, + { message: "transport failed", sameSession: true, destroyed: true }, + ); + + client.close(); + netServer.close(); + }); }); describe("HTTP/2 upgrade — ALPN negotiation", () => { From 1ad82ac451889fdc8df60c6541376a799883f5cf Mon Sep 17 00:00:00 2001 From: robobun <117481402+robobun@users.noreply.github.com> Date: Thu, 13 Aug 2026 09:35:48 +0000 Subject: [PATCH 2/8] node:http2: report a failed injected-connection upgrade on the server, not on the socket --- src/js/node/_http2_upgrade.ts | 10 ++++- .../js/node/http2/node-http2-upgrade.test.mts | 41 +++++++++++++++++++ 2 files changed, 49 insertions(+), 2 deletions(-) diff --git a/src/js/node/_http2_upgrade.ts b/src/js/node/_http2_upgrade.ts index 47ef4ab4b37e..aecef5bb7937 100644 --- a/src/js/node/_http2_upgrade.ts +++ b/src/js/node/_http2_upgrade.ts @@ -386,8 +386,14 @@ function upgradeRawSocketToH2( data: {}, }); } catch (e) { - rawSocket.destroy(e as Error); - tlsSocket.destroy(e as Error); + // The credentials are built on first use, so a bad key/cert is detected + // here, on the first injected connection. Report it the way tls.Server's + // own connection listener does, on the server's 'error' event; nothing + // listens on rawSocket yet, so an error handed to its destroy() would be + // an uncaught exception. + rawSocket.destroy(); + tlsSocket.destroy(); + server.emit("error", e); return true; } diff --git a/test/js/node/http2/node-http2-upgrade.test.mts b/test/js/node/http2/node-http2-upgrade.test.mts index 35a70d959307..4259d865d436 100644 --- a/test/js/node/http2/node-http2-upgrade.test.mts +++ b/test/js/node/http2/node-http2-upgrade.test.mts @@ -504,6 +504,47 @@ describe("HTTP/2 upgrade — server TLS options", () => { netServer.close(); } }); + + test("unusable credentials are the server's error, and the injected connection is closed", async () => { + // Node rejects the key inside createSecureServer(). Bun builds the + // credentials on first use, which for a server that never listens is the + // first injected connection, and then reports the failure the way + // tls.Server does for server.emit('connection'): on the server's 'error' + // event, with the connection closed quietly. In neither runtime is the + // injected socket, which nothing listens to, where the error surfaces. + let h2Server: http2.Http2SecureServer; + try { + h2Server = http2.createSecureServer({ key: "not a key", cert: "not a cert" }); + } catch (err) { + assert.strictEqual((err as NodeJS.ErrnoException).code, "ERR_OSSL_PEM_NO_START_LINE"); + return; + } + const surfaced = Promise.withResolvers(); + h2Server.on("error", surfaced.resolve); + + let rawSocket: net.Socket | undefined; + let emitReturned: boolean | undefined; + const netServer = net.createServer(socket => { + rawSocket = socket; + emitReturned = h2Server.emit("connection", socket); + }); + const port = await new Promise(resolve => { + netServer.listen(0, "127.0.0.1", () => resolve((netServer.address() as net.AddressInfo).port)); + }); + + const client = net.connect(port, "127.0.0.1"); + client.on("error", () => {}); + try { + const err = await surfaced.promise; + assert.deepStrictEqual( + { code: err.code, emitReturned, rawDestroyed: rawSocket!.destroyed }, + { code: "ERR_OSSL_PEM_NO_START_LINE", emitReturned: true, rawDestroyed: true }, + ); + } finally { + client.destroy(); + netServer.close(); + } + }); }); if (typeof Bun !== "undefined") { From 28a41aedf5d87653df895166f691e02b8bc5b265 Mon Sep 17 00:00:00 2001 From: robobun <117481402+robobun@users.noreply.github.com> Date: Thu, 13 Aug 2026 09:51:51 +0000 Subject: [PATCH 3/8] node:http2: shorten the upgrade error comments --- src/js/node/_http2_upgrade.ts | 26 ++++++-------------------- 1 file changed, 6 insertions(+), 20 deletions(-) diff --git a/src/js/node/_http2_upgrade.ts b/src/js/node/_http2_upgrade.ts index aecef5bb7937..c2d02a71165c 100644 --- a/src/js/node/_http2_upgrade.ts +++ b/src/js/node/_http2_upgrade.ts @@ -247,30 +247,19 @@ function socketHandshake( } // --------------------------------------------------------------------------- -// Raw socket listeners bound to tlsSocket +// Raw socket error forwarding and close cleanup // --------------------------------------------------------------------------- -// error: the transport under the TLS layer failed (reset, EPIPE, destroy(err)). -// Node's TLSSocket re-emits the wrapped socket's errors on itself, so they -// reach the session's socket error handling and the socket handed in never -// emits an unhandled 'error': +// A wrapped socket's errors belong to the TLS socket over it, as in node: // https://github.com/nodejs/node/blob/v26.3.0/lib/internal/tls/wrap.js#L977 -// Stays attached for the raw socket's lifetime (it is still flushing after the -// session is gone), hence the destroyed check. +// rawSocket outlives the session (onTlsClose keeps this listener), hence the guard. function onRawSocketError(this: TLSProxySocket, err: Error) { - if (!this.destroyed) { - this.destroy(err); - } + if (!this.destroyed) this.destroy(err); } -// --------------------------------------------------------------------------- -// Close-cleanup handler -// --------------------------------------------------------------------------- - // onTlsClose: when the TLS socket closes (e.g. H2 session destroyed), clean up // the raw socket listeners to prevent memory leaks and stale callback references. // EventEmitter calls 'close' handlers with `this` = emitter (tlsSocket). -// The 'error' listener is deliberately left in place (see onRawSocketError). function onTlsClose(this: TLSProxySocket) { const ctx = this._ctx; const raw = ctx.rawSocket; @@ -386,11 +375,8 @@ function upgradeRawSocketToH2( data: {}, }); } catch (e) { - // The credentials are built on first use, so a bad key/cert is detected - // here, on the first injected connection. Report it the way tls.Server's - // own connection listener does, on the server's 'error' event; nothing - // listens on rawSocket yet, so an error handed to its destroy() would be - // an uncaught exception. + // Credentials are built on first use and can fail here; same surface as + // tls.Server's own 'connection' listener (nothing listens on rawSocket). rawSocket.destroy(); tlsSocket.destroy(); server.emit("error", e); From 24c2e185afaba59010520f37266f719c85c4d302 Mon Sep 17 00:00:00 2001 From: robobun <117481402+robobun@users.noreply.github.com> Date: Thu, 13 Aug 2026 09:58:33 +0000 Subject: [PATCH 4/8] node:http2: one-line comments in the upgrade error paths --- src/js/node/_http2_upgrade.ts | 7 ++----- 1 file changed, 2 insertions(+), 5 deletions(-) diff --git a/src/js/node/_http2_upgrade.ts b/src/js/node/_http2_upgrade.ts index c2d02a71165c..3bf73dc565e0 100644 --- a/src/js/node/_http2_upgrade.ts +++ b/src/js/node/_http2_upgrade.ts @@ -250,9 +250,7 @@ function socketHandshake( // Raw socket error forwarding and close cleanup // --------------------------------------------------------------------------- -// A wrapped socket's errors belong to the TLS socket over it, as in node: -// https://github.com/nodejs/node/blob/v26.3.0/lib/internal/tls/wrap.js#L977 -// rawSocket outlives the session (onTlsClose keeps this listener), hence the guard. +// Node reports a wrapped socket's errors on the TLS socket over it: https://github.com/nodejs/node/blob/v26.3.0/lib/internal/tls/wrap.js#L977 function onRawSocketError(this: TLSProxySocket, err: Error) { if (!this.destroyed) this.destroy(err); } @@ -375,8 +373,7 @@ function upgradeRawSocketToH2( data: {}, }); } catch (e) { - // Credentials are built on first use and can fail here; same surface as - // tls.Server's own 'connection' listener (nothing listens on rawSocket). + // Same surface as tls.Server's own 'connection' listener when the credentials fail to build. rawSocket.destroy(); tlsSocket.destroy(); server.emit("error", e); From 0321e261d7bf4593e061f8dbbc2f43ff65357889 Mon Sep 17 00:00:00 2001 From: robobun <117481402+robobun@users.noreply.github.com> Date: Thu, 13 Aug 2026 10:04:01 +0000 Subject: [PATCH 5/8] node:http2: assert the forwarded error is the same object --- test/js/node/http2/node-http2-upgrade.test.mts | 8 +++++--- 1 file changed, 5 insertions(+), 3 deletions(-) diff --git a/test/js/node/http2/node-http2-upgrade.test.mts b/test/js/node/http2/node-http2-upgrade.test.mts index 4259d865d436..65fbda50c1f9 100644 --- a/test/js/node/http2/node-http2-upgrade.test.mts +++ b/test/js/node/http2/node-http2-upgrade.test.mts @@ -310,13 +310,15 @@ describe("HTTP/2 upgrade — socket close ordering", () => { // Not events.once(): the session emits 'error' on its way to 'close'. const sessionClosed = new Promise(resolve => h2Session.once("close", resolve)); - rawSocket!.destroy(new Error("transport failed")); + const transportError = new Error("transport failed"); + rawSocket!.destroy(transportError); await sessionClosed; const { err, session } = await sessionErrored.promise; + assert.strictEqual(err, transportError); assert.deepStrictEqual( - { message: err.message, sameSession: session === h2Session, destroyed: h2Session.destroyed }, - { message: "transport failed", sameSession: true, destroyed: true }, + { sameSession: session === h2Session, destroyed: h2Session.destroyed }, + { sameSession: true, destroyed: true }, ); client.close(); From 8c593be1b4693dbe737136e3a33002b634f75eb5 Mon Sep 17 00:00:00 2001 From: robobun Date: Mon, 19 Oct 2026 13:55:09 +0000 Subject: [PATCH 6/8] node:http2: report an injected socket's error before the handover as tlsClientError, once A raw socket error before the handover is the server's tlsClientError, as in tls.Server. The close that follows aborts the handshake, which must not be reported again, so the emission is guarded like node's kErrorEmitted. onTlsClose swaps the bound raw socket error listener for the module noop, so a finished session is not kept alive by a raw socket that stays open. The catch block goes back to what it was. Credentials are built in the tls.Server constructor now, so the upgrade cannot fail on them, and the test that was written for that path never reached it. --- src/js/node/_http2_upgrade.ts | 34 +++++-- .../js/node/http2/node-http2-upgrade.test.mts | 94 +++++++++++-------- 2 files changed, 79 insertions(+), 49 deletions(-) diff --git a/src/js/node/_http2_upgrade.ts b/src/js/node/_http2_upgrade.ts index d31bd3c7614f..f3604b44d78b 100644 --- a/src/js/node/_http2_upgrade.ts +++ b/src/js/node/_http2_upgrade.ts @@ -18,7 +18,9 @@ interface UpgradeContextType { rawSocket: import("node:net").Socket; nativeHandle: NativeHandle | null; events: UpgradeEvents | null; + onRawSocketError: ((err: Error) => void) | null; handedOver: boolean; + errorEmitted: boolean; } interface Http2SecureServer { @@ -65,7 +67,19 @@ function UpgradeContext( this.rawSocket = rawSocket; this.nativeHandle = null; this.events = null; + this.onRawSocketError = null; this.handedOver = false; + this.errorEmitted = false; +} + +// Until the handover the connection is the server's, so its error is the +// server's 'tlsClientError', once: a close that follows an error reports the +// aborted handshake too. Same guard as tls.Server's kerrorEmitted (net.ts). +function emitTlsClientError(tlsSocket: TLSProxySocket, err: Error) { + const ctx = tlsSocket._ctx; + if (ctx.handedOver || ctx.errorEmitted) return; + ctx.errorEmitted = true; + ctx.server.emit("tlsClientError", err, tlsSocket); } // --------------------------------------------------------------------------- @@ -210,7 +224,7 @@ function socketHandshake( if (!success) { const err = require("internal/tls").tlsHandshakeError(verifyError); - ctx.server.emit("tlsClientError", err, tlsSocket); + emitTlsClientError(tlsSocket, err); tlsSocket.destroy(err); return; } @@ -231,7 +245,7 @@ function socketHandshake( if (verifyError) { tlsSocket.authorized = false; tlsSocket.authorizationError = verifyError.code || verifyError.message; - ctx.server.emit("tlsClientError", verifyError, tlsSocket); + emitTlsClientError(tlsSocket, verifyError); if (rejectUnauthorized ?? tlsSocket._rejectUnauthorized) { tlsSocket.emit("secure", tlsSocket); tlsSocket.destroy(verifyError); @@ -260,7 +274,9 @@ function socketHandshake( // Node reports a wrapped socket's errors on the TLS socket over it: https://github.com/nodejs/node/blob/v26.3.0/lib/internal/tls/wrap.js#L977 function onRawSocketError(this: TLSProxySocket, err: Error) { - if (!this.destroyed) this.destroy(err); + if (this.destroyed) return; + emitTlsClientError(this, err); + this.destroy(err); } // onTlsClose: when the TLS socket closes (e.g. H2 session destroyed), clean up @@ -275,6 +291,10 @@ function onTlsClose(this: TLSProxySocket) { raw.removeListener("end", ev[1]); raw.removeListener("drain", ev[2]); raw.removeListener("close", ev[3]); + // The raw socket is still sending close_notify. A failure there has no session to go to, and must not be uncaught. + raw.removeListener("error", ctx.onRawSocketError!); + ctx.onRawSocketError = null; + raw.on("error", noop); } // --------------------------------------------------------------------------- @@ -381,10 +401,8 @@ function upgradeRawSocketToH2( data: {}, }); } catch (e) { - // Same surface as tls.Server's own 'connection' listener when the credentials fail to build. - rawSocket.destroy(); - tlsSocket.destroy(); - server.emit("error", e); + rawSocket.destroy(e as Error); + tlsSocket.destroy(e as Error); return true; } @@ -401,7 +419,7 @@ function upgradeRawSocketToH2( rawSocket.on("end", events[1]); rawSocket.on("drain", events[2]); rawSocket.on("close", events[3]); - rawSocket.on("error", onRawSocketError.bind(tlsSocket)); + rawSocket.on("error", (tlsSocket._ctx.onRawSocketError = onRawSocketError.bind(tlsSocket))); // When the TLS socket closes (e.g. H2 session destroyed), clean up the raw socket // listeners to prevent memory leaks and stale callback references. diff --git a/test/js/node/http2/node-http2-upgrade.test.mts b/test/js/node/http2/node-http2-upgrade.test.mts index ea363e16967a..297cfb1bf8cf 100644 --- a/test/js/node/http2/node-http2-upgrade.test.mts +++ b/test/js/node/http2/node-http2-upgrade.test.mts @@ -585,47 +585,6 @@ describe("HTTP/2 upgrade — server TLS options", () => { netServer.close(); } }); - - test("unusable credentials are the server's error, and the injected connection is closed", async () => { - // Node rejects the key inside createSecureServer(). Bun builds the - // credentials on first use, which for a server that never listens is the - // first injected connection, and then reports the failure the way - // tls.Server does for server.emit('connection'): on the server's 'error' - // event, with the connection closed quietly. In neither runtime is the - // injected socket, which nothing listens to, where the error surfaces. - let h2Server: http2.Http2SecureServer; - try { - h2Server = http2.createSecureServer({ key: "not a key", cert: "not a cert" }); - } catch (err) { - assert.strictEqual((err as NodeJS.ErrnoException).code, "ERR_OSSL_PEM_NO_START_LINE"); - return; - } - const surfaced = Promise.withResolvers(); - h2Server.on("error", surfaced.resolve); - - let rawSocket: net.Socket | undefined; - let emitReturned: boolean | undefined; - const netServer = net.createServer(socket => { - rawSocket = socket; - emitReturned = h2Server.emit("connection", socket); - }); - const port = await new Promise(resolve => { - netServer.listen(0, "127.0.0.1", () => resolve((netServer.address() as net.AddressInfo).port)); - }); - - const client = net.connect(port, "127.0.0.1"); - client.on("error", () => {}); - try { - const err = await surfaced.promise; - assert.deepStrictEqual( - { code: err.code, emitReturned, rawDestroyed: rawSocket!.destroyed }, - { code: "ERR_OSSL_PEM_NO_START_LINE", emitReturned: true, rawDestroyed: true }, - ); - } finally { - client.destroy(); - netServer.close(); - } - }); }); // The peer keeps its end of the TCP connection open in every case. @@ -813,6 +772,59 @@ describe("HTTP/2 upgrade — failed handshake", () => { : "ERR_SSL_UNEXPECTED_MESSAGE"; assert.deepStrictEqual({ event, code }, { event: "tlsClientError", code: expected }); }); + + test("an error on rawSocket during the handshake is the server's tlsClientError, reported once", async () => { + // Until the handover the connection is the server's, so the error goes + // where tls.Server puts a wrapped socket's error: 'tlsClientError', with + // that error. The close that follows aborts the handshake, which must not + // be reported as a second 'tlsClientError'. + const transportError = new Error("transport failed"); + const reported: Error[] = []; + const first = Promise.withResolvers(); + const h2Server = http2.createSecureServer(TLS); + h2Server.on("error", () => {}); + h2Server.on("tlsClientError", (err: Error, socket: Duplex) => { + reported.push(err); + first.resolve(socket); + }); + h2Server.on("secureConnection", () => first.reject(new Error("the handshake completed"))); + let rawSocket: net.Socket | undefined; + const netServer = net.createServer(socket => { + rawSocket = socket; + h2Server.emit("connection", socket); + }); + // A plain proxy in front of the net.Server. It forwards the client's bytes + // only, so the server's answer to the ClientHello is the signal that its + // handshake is pending, and stays so. + let toServer: net.Socket | undefined; + const proxy = net.createServer(c => { + toServer = net.connect((netServer.address() as net.AddressInfo).port, "127.0.0.1"); + c.pipe(toServer); + c.on("error", () => {}); + toServer.on("error", () => {}); + toServer.once("data", () => rawSocket!.destroy(transportError)); + }); + let client: tls.TLSSocket | undefined; + try { + await once(netServer.listen(0, "127.0.0.1"), "listening"); + await once(proxy.listen(0, "127.0.0.1"), "listening"); + client = tls.connect({ + port: (proxy.address() as net.AddressInfo).port, + host: "127.0.0.1", + rejectUnauthorized: false, + ALPNProtocols: ["h2"], + }); + client.on("error", () => {}); + const tlsSocket = await first.promise; + if (!tlsSocket.closed) await once(tlsSocket, "close"); + assert.deepStrictEqual(reported, [transportError]); + } finally { + client?.destroy(); + toServer?.destroy(); + proxy.close(); + netServer.close(); + } + }); }); describe("HTTP/2 upgrade — fatal TLS error after the handshake", () => { From 47073a0639d414d530e66b535caa416a96f6d54f Mon Sep 17 00:00:00 2001 From: robobun Date: Mon, 19 Oct 2026 19:07:42 +0000 Subject: [PATCH 7/8] node:http2: let tls.Server wrap a socket injected into an Http2SecureServer Http2SecureServer.prototype.emit intercepted 'connection' and routed a plain socket into _http2_upgrade.ts, a TLS-over-Duplex path with its own handshake, error and close handling. That path listened to the raw socket's data, end, drain and close, but not to its error, so a transport error after the upgrade was an uncaught exception. tls.Server's own 'connection' listener wraps any injected plain socket in a server-side TLSSocket, with the wrapped socket's errors forwarded and the pre-handshake ones reported once as tlsClientError. The h2 connection listener is already on 'secureConnection' through the super call. So the override and the module go, and the injected connection takes the same path as in node. The two tests that waited for the accepted socket to be released are no longer todo: the wrapped socket is destroyed with the TLSSocket. --- src/js/node/_http2_upgrade.ts | 431 ------------------ src/js/node/http2.ts | 12 - .../js/node/http2/node-http2-upgrade.test.mts | 15 +- 3 files changed, 5 insertions(+), 453 deletions(-) delete mode 100644 src/js/node/_http2_upgrade.ts diff --git a/src/js/node/_http2_upgrade.ts b/src/js/node/_http2_upgrade.ts deleted file mode 100644 index f3604b44d78b..000000000000 --- a/src/js/node/_http2_upgrade.ts +++ /dev/null @@ -1,431 +0,0 @@ -const { Duplex } = require("node:stream"); -const upgradeDuplexToTLS = $newRustFunction("runtime/socket/socket.rs", "jsUpgradeDuplexToTLS", 2); - -interface NativeHandle { - resume(): void; - close(): void; - end(): void; - $write(chunk: Buffer, encoding: string): boolean; - alpnProtocol?: string; -} - -type UpgradeEventListener = (...args: any[]) => void; -type UpgradeEvents = [UpgradeEventListener, UpgradeEventListener, UpgradeEventListener, UpgradeEventListener]; - -interface UpgradeContextType { - connectionListener: (...args: any[]) => any; - server: Http2SecureServer; - rawSocket: import("node:net").Socket; - nativeHandle: NativeHandle | null; - events: UpgradeEvents | null; - onRawSocketError: ((err: Error) => void) | null; - handedOver: boolean; - errorEmitted: boolean; -} - -interface Http2SecureServer { - key?: Buffer; - cert?: Buffer; - ca?: Buffer; - passphrase?: string; - ALPNProtocols?: Buffer; - _requestCert?: boolean; - _rejectUnauthorized?: boolean; - emit(event: string, ...args: any[]): boolean; - _sharedCreds: { context: unknown }; -} - -type DuplexStream = import("node:stream").Duplex; - -interface TLSProxySocket extends DuplexStream { - _ctx: UpgradeContextType; - _writeCallback: ((err?: Error | null) => void) | null; - alpnProtocol: string | null; - authorized: boolean; - encrypted: boolean; - server: Http2SecureServer; - _requestCert: boolean; - _rejectUnauthorized: boolean | undefined; - _securePending: boolean; - secureConnecting: boolean; - _secureEstablished: boolean; - authorizationError?: string; -} - -/** - * Context object holding upgrade-time state for the TLS proxy socket. - * Attached as `tlsSocket._ctx` so named functions can reach it via `this._ctx` - * (Duplex methods) or via a bound `this` (socket callbacks). - */ -function UpgradeContext( - connectionListener: (...args: any[]) => any, - server: Http2SecureServer, - rawSocket: import("node:net").Socket, -) { - this.connectionListener = connectionListener; - this.server = server; - this.rawSocket = rawSocket; - this.nativeHandle = null; - this.events = null; - this.onRawSocketError = null; - this.handedOver = false; - this.errorEmitted = false; -} - -// Until the handover the connection is the server's, so its error is the -// server's 'tlsClientError', once: a close that follows an error reports the -// aborted handshake too. Same guard as tls.Server's kerrorEmitted (net.ts). -function emitTlsClientError(tlsSocket: TLSProxySocket, err: Error) { - const ctx = tlsSocket._ctx; - if (ctx.handedOver || ctx.errorEmitted) return; - ctx.errorEmitted = true; - ctx.server.emit("tlsClientError", err, tlsSocket); -} - -// --------------------------------------------------------------------------- -// Duplex stream methods — called with `this` = tlsSocket (standard stream API) -// --------------------------------------------------------------------------- - -// _read: called by stream machinery when the H2 session wants data. -// Resume the native TLS handle so it feeds decrypted data via the data callback. -// Mirrors net.ts Socket.prototype._read which calls socket.resume(). -function tlsSocketRead(this: TLSProxySocket) { - const h = this._ctx.nativeHandle; - if (h) { - h.resume(); - } - this._ctx.rawSocket.resume(); -} - -// _write: called when the H2 session writes outbound frames. -// Forward to the native TLS handle for encryption, then back to rawSocket. -// Mirrors net.ts Socket.prototype._write which calls socket.$write(). -function tlsSocketWrite(this: TLSProxySocket, chunk: Buffer, encoding: string, callback: (err?: Error | null) => void) { - const h = this._ctx.nativeHandle; - if (!h) { - callback(new Error("Socket is closed")); - return; - } - // $write returns true if fully flushed, false if buffered - if (h.$write(chunk, encoding)) { - callback(); - } else { - // Store callback so drain event can invoke it (backpressure) - this._writeCallback = callback; - } -} - -// _destroy: called when the stream is destroyed (e.g. tlsSocket.destroy(err)). -// Cleans up the native TLS handle. -// Mirrors net.ts Socket.prototype._destroy. -function tlsSocketDestroy(this: TLSProxySocket, err: Error | null, callback: (err?: Error | null) => void) { - const ctx = this._ctx; - const h = ctx.nativeHandle; - if (h) { - h.close(); - ctx.nativeHandle = null; - } - // Nothing of the application's is on its way on a socket it never got. Else the raw socket closes when it has sent what it took. - if (!ctx.handedOver) ctx.rawSocket.destroy(); - // Must invoke pending write callback with error per Writable stream contract - const writeCb = this._writeCallback; - if (writeCb) { - this._writeCallback = null; - writeCb(err ?? new Error("Socket destroyed")); - } - callback(err); -} - -// _final: called when the writable side is ending (all data flushed). -// Shuts down the TLS write side gracefully. -// Mirrors net.ts Socket.prototype._final. -function tlsSocketFinal(this: TLSProxySocket, callback: () => void) { - const h = this._ctx.nativeHandle; - if (!h) return callback(); - // Signal end-of-stream to the TLS layer - h.end(); - callback(); -} - -// --------------------------------------------------------------------------- -// Socket callbacks — called natively with `this` = native handle (not useful). -// All are bound to tlsSocket so `this` inside each = tlsSocket. -// --------------------------------------------------------------------------- - -// open: called when the TLS layer is initialized (before handshake). -// No action needed; we wait for the handshake callback. -function socketOpen() {} - -// data: called with decrypted plaintext after the TLS layer decrypts incoming data. -// Push into tlsSocket so the H2 session's _read() receives these frames. -function socketData(this: TLSProxySocket, _socket: NativeHandle, chunk: Buffer) { - if (!this.push(chunk)) { - this._ctx.rawSocket.pause(); - } -} - -// end: TLS peer signaled end-of-stream; signal EOF to the H2 session. -function socketEnd(this: TLSProxySocket) { - this.push(null); -} - -// drain: raw socket is writable again after being full; propagate backpressure signal. -// If _write stored a callback waiting for drain, invoke it now. -function socketDrain(this: TLSProxySocket) { - const cb = this._writeCallback; - if (cb) { - this._writeCallback = null; - cb(); - } -} - -// close: TLS connection closed; tear down the tlsSocket Duplex. -function socketClose(this: TLSProxySocket) { - if (!this.destroyed) { - this.destroy(); - } -} - -// error: TLS-level error (e.g. certificate verification failure). -// In server mode without _requestCert, the server doesn't request a client cert, -// so issuer verification errors on the server's own cert are non-fatal. -function socketError(this: TLSProxySocket, _socket: NativeHandle, err: NodeJS.ErrnoException) { - const ctx = this._ctx; - if (!ctx.server._requestCert && err?.code === "UNABLE_TO_GET_ISSUER_CERT") { - return; - } - if (this._secureEstablished && err?.code === "EPROTO" && err.syscall === undefined) { - err = require("internal/tls").tlsHandshakeError(err); - } - this.destroy(err); -} - -// timeout: socket idle timeout; forward to the Duplex so H2 session can handle it. -function socketTimeout(this: TLSProxySocket) { - this.emit("timeout"); -} - -// handshake: TLS handshake completed. This is the critical callback that triggers -// H2 session creation. -// -// Mirrors the handshake logic in net.ts ServerHandlers.handshake: -// - Set secure-connection state flags on tlsSocket -// - Read alpnProtocol from the native handle (set by ALPN negotiation) -// - Handle _requestCert / _rejectUnauthorized for mutual TLS -// - Call connectionListener to create the ServerHttp2Session -function socketHandshake( - this: TLSProxySocket, - nativeHandle: NativeHandle, - success: boolean, - verifyError: NodeJS.ErrnoException | null, -) { - const tlsSocket = this; // bound - const ctx = tlsSocket._ctx; - - if (!success) { - const err = require("internal/tls").tlsHandshakeError(verifyError); - emitTlsClientError(tlsSocket, err); - tlsSocket.destroy(err); - return; - } - - // Mark TLS handshake as complete on the proxy socket - tlsSocket._securePending = false; - tlsSocket.secureConnecting = false; - tlsSocket._secureEstablished = true; - - // Copy the negotiated ALPN protocol (e.g. "h2") from the native TLS handle. - // The H2 session checks this to confirm HTTP/2 was negotiated. - tlsSocket.alpnProtocol = nativeHandle?.alpnProtocol ?? null; - - // Handle mutual TLS: if the server requested a client cert, check for errors - const requestCert = tlsSocket._requestCert; - let rejectUnauthorized; - if (requestCert || (rejectUnauthorized = tlsSocket._rejectUnauthorized)) { - if (verifyError) { - tlsSocket.authorized = false; - tlsSocket.authorizationError = verifyError.code || verifyError.message; - emitTlsClientError(tlsSocket, verifyError); - if (rejectUnauthorized ?? tlsSocket._rejectUnauthorized) { - tlsSocket.emit("secure", tlsSocket); - tlsSocket.destroy(verifyError); - return; - } - } else if (requestCert) { - tlsSocket.authorized = true; - } - } - - // Invoke the H2 connectionListener which creates a ServerHttp2Session. - // This is the same function passed to Http2SecureServer's constructor - // and is what normally fires on the 'secureConnection' event. - ctx.handedOver = true; - ctx.connectionListener.$call(ctx.server, tlsSocket); - - // Resume the Duplex so the H2 session can read frames from it. The accept - // path in net.ts ServerHandlers.handshake only read(0)s (node's manualStart - // server socket); the H2 session is the consumer here, so it flows. - tlsSocket.resume(); -} - -// --------------------------------------------------------------------------- -// Raw socket error forwarding and close cleanup -// --------------------------------------------------------------------------- - -// Node reports a wrapped socket's errors on the TLS socket over it: https://github.com/nodejs/node/blob/v26.3.0/lib/internal/tls/wrap.js#L977 -function onRawSocketError(this: TLSProxySocket, err: Error) { - if (this.destroyed) return; - emitTlsClientError(this, err); - this.destroy(err); -} - -// onTlsClose: when the TLS socket closes (e.g. H2 session destroyed), clean up -// the raw socket listeners to prevent memory leaks and stale callback references. -// EventEmitter calls 'close' handlers with `this` = emitter (tlsSocket). -function onTlsClose(this: TLSProxySocket) { - const ctx = this._ctx; - const raw = ctx.rawSocket; - const ev = ctx.events; - if (!ev) return; - raw.removeListener("data", ev[0]); - raw.removeListener("end", ev[1]); - raw.removeListener("drain", ev[2]); - raw.removeListener("close", ev[3]); - // The raw socket is still sending close_notify. A failure there has no session to go to, and must not be uncaught. - raw.removeListener("error", ctx.onRawSocketError!); - ctx.onRawSocketError = null; - raw.on("error", noop); -} - -// --------------------------------------------------------------------------- -// Module-scope noop (replaces anonymous () => {} for the error suppression) -// --------------------------------------------------------------------------- - -// no-op handler used to suppress unhandled error events until -// the H2 session attaches its own error handler. -function noop() {} - -// --------------------------------------------------------------------------- -// Main upgrade function -// --------------------------------------------------------------------------- - -// Upgrades a raw TCP socket to TLS and initiates an H2 session on it. -// -// When a net.Server forwards an accepted TCP connection to an Http2SecureServer -// via `h2Server.emit('connection', socket)`, the socket has not been TLS-upgraded. -// Node.js Http2SecureServer expects to receive this and perform the upgrade itself. -// -// This mirrors the TLS server handshake pattern from net.ts ServerHandlers, but -// targets the H2 connectionListener instead of a generic secureConnection event. -// -// Data flow after upgrade: -// rawSocket (TCP) → upgradeDuplexToTLS (native TLS layer) → socket callbacks -// → tlsSocket.push() → H2 session reads -// H2 session writes → tlsSocket._write() → handle.$write() → native TLS layer → rawSocket -// -// CRITICAL: We do NOT set tlsSocket._handle to the native TLS handle. -// If we did, the H2FrameParser constructor would detect it as a JSTLSSocket -// and call attachNativeCallback(), which intercepts all decrypted data at the -// native level, completely bypassing our JS data callback and Duplex.push() path. -// Instead, we store the handle in _ctx.nativeHandle so _read/_write/_destroy -// can use it, while the H2 session sees _handle as null and uses the JS-level -// socket.on("data") → Duplex → parser.read() path for incoming frames. -function upgradeRawSocketToH2( - connectionListener: (...args: any[]) => any, - server: Http2SecureServer, - rawSocket: import("node:net").Socket, -): boolean { - // Create a Duplex stream that acts as the TLS "socket" from the H2 session's perspective. - const tlsSocket = new Duplex() as TLSProxySocket; - tlsSocket._ctx = new UpgradeContext(connectionListener, server, rawSocket); - - // Duplex stream methods — `this` is tlsSocket, no bind needed - tlsSocket._read = tlsSocketRead; - tlsSocket._write = tlsSocketWrite; - tlsSocket._destroy = tlsSocketDestroy; - tlsSocket._final = tlsSocketFinal; - - // Suppress unhandled error events until the H2 session attaches its own error handler - tlsSocket.on("error", noop); - - // Set TLS-like properties that connectionListener and the H2 session expect. - // These are set on the Duplex because we cannot use a real TLSSocket here — - // its internal state machine would conflict with upgradeDuplexToTLS. - tlsSocket.alpnProtocol = null; - tlsSocket.authorized = false; - tlsSocket.encrypted = true; - tlsSocket.server = server; - - // Only enforce client cert verification if the server explicitly requests it. - // tls.Server defaults _rejectUnauthorized to true, but without _requestCert - // the server doesn't actually ask for a client cert, so verification errors - // (e.g. UNABLE_TO_GET_ISSUER_CERT for the server's own self-signed cert) are - // spurious and must be ignored. - tlsSocket._requestCert = server._requestCert || false; - tlsSocket._rejectUnauthorized = server._requestCert ? server._rejectUnauthorized : false; - - // socket: callbacks — bind to tlsSocket since they are invoked with the native handle as `this` - let handle: NativeHandle, events: UpgradeEvents; - try { - // upgradeDuplexToTLS wraps rawSocket with a TLS layer in server mode (isServer: true). - // The native side will: - // 1. Read encrypted data from rawSocket via events[0..3] - // 2. Decrypt it through the TLS engine (with ALPN negotiation for "h2") - // 3. Call our socket callbacks below with the decrypted plaintext - // - // ALPNProtocols: server.ALPNProtocols is a Buffer in wire format (e.g. - // for ["h2"]). The native SSLConfig expects an ArrayBuffer, so we slice the underlying buffer. - [handle, events] = upgradeDuplexToTLS(rawSocket, { - isServer: true, - tls: { - secureContext: server._sharedCreds.context, - requestCert: server._requestCert, - rejectUnauthorized: server._rejectUnauthorized, - ALPNProtocols: server.ALPNProtocols - ? server.ALPNProtocols.buffer.slice( - server.ALPNProtocols.byteOffset, - server.ALPNProtocols.byteOffset + server.ALPNProtocols.byteLength, - ) - : null, - }, - socket: { - open: socketOpen, - data: socketData.bind(tlsSocket), - end: socketEnd.bind(tlsSocket), - drain: socketDrain.bind(tlsSocket), - close: socketClose.bind(tlsSocket), - error: socketError.bind(tlsSocket), - timeout: socketTimeout.bind(tlsSocket), - handshake: socketHandshake.bind(tlsSocket), - }, - data: {}, - }); - } catch (e) { - rawSocket.destroy(e as Error); - tlsSocket.destroy(e as Error); - return true; - } - - // Store handle in _ctx (NOT on tlsSocket._handle). - // This prevents H2FrameParser from attaching as native callback which would - // intercept data at the native level and bypass our Duplex push path. - tlsSocket._ctx.nativeHandle = handle; - tlsSocket._ctx.events = events; - - // Wire up the raw TCP socket to feed encrypted data into the TLS layer. - // events[0..3] are native event handlers returned by upgradeDuplexToTLS that - // the native TLS engine expects to receive data/end/drain/close through. - rawSocket.on("data", events[0]); - rawSocket.on("end", events[1]); - rawSocket.on("drain", events[2]); - rawSocket.on("close", events[3]); - rawSocket.on("error", (tlsSocket._ctx.onRawSocketError = onRawSocketError.bind(tlsSocket))); - - // When the TLS socket closes (e.g. H2 session destroyed), clean up the raw socket - // listeners to prevent memory leaks and stale callback references. - // EventEmitter calls 'close' handlers with `this` = emitter (tlsSocket). - tlsSocket.once("close", onTlsClose); - return true; -} - -export default { upgradeRawSocketToH2 }; diff --git a/src/js/node/http2.ts b/src/js/node/http2.ts index f41ce68605fc..ca0c7d0d0bf0 100644 --- a/src/js/node/http2.ts +++ b/src/js/node/http2.ts @@ -94,8 +94,6 @@ const StringPrototypeStartsWith = String.prototype.startsWith; const ObjectPrototypeHasOwnProperty = Object.prototype.hasOwnProperty; const H2FrameParser = $rust("h2_frame_parser.rs", "H2FrameParserConstructor"); -const { upgradeRawSocketToH2 } = require("node:_http2_upgrade"); -type UpgradableSecureServer = Parameters[1]; const kSettingIds: Record = { 0x1: "headerTableSize", @@ -6639,7 +6637,6 @@ function onErrorSecureServerSession(err, socket) { function emitFrameErrorEventNT(stream, frameType, errorCode) { stream.emit("frameError", frameType, errorCode); } -interface Http2SecureServer extends UpgradableSecureServer {} class Http2SecureServer extends (tls.Server as unknown as Http2SecureServerBase) { declare keepAliveTimeout: number | undefined; declare headersTimeout: number | undefined; @@ -6685,15 +6682,6 @@ class Http2SecureServer extends (tls.Server as unknown as Http2SecureServerBase) } this.on("tlsClientError", onErrorSecureServerSession); } - emit(event: string, ...args: any[]) { - if (event === "connection") { - const socket = args[0]; - if (socket && !(socket instanceof TLSSocket)) { - return upgradeRawSocketToH2(connectionListener, this, socket); - } - } - return super.emit(event, ...args); - } setTimeout(ms, callback) { if (callback !== undefined && typeof callback !== "function") { throw $ERR_INVALID_ARG_TYPE("callback", "function", callback); diff --git a/test/js/node/http2/node-http2-upgrade.test.mts b/test/js/node/http2/node-http2-upgrade.test.mts index 297cfb1bf8cf..478a57484f94 100644 --- a/test/js/node/http2/node-http2-upgrade.test.mts +++ b/test/js/node/http2/node-http2-upgrade.test.mts @@ -1,6 +1,7 @@ /** - * Tests for the net.Server → Http2SecureServer upgrade path - * (upgradeRawSocketToH2 in _http2_upgrade.ts). + * Tests for the net.Server → Http2SecureServer upgrade path: tls.Server's + * 'connection' listener wraps the injected socket in a server-side TLSSocket, + * and the secure connection reaches the h2 connection listener. * * This pattern is used by http2-wrapper, crawlee, and other libraries that * accept raw TCP connections and upgrade them to HTTP/2 via @@ -404,7 +405,6 @@ describe("HTTP/2 upgrade — the client closes its side first", () => { await writing.promise; // A turn later only what the kernel did not take is left. await new Promise(resolve => setImmediate(resolve)); - if (process.versions.bun !== undefined) assert.notStrictEqual(raw?.writableLength, 0); let received = 0; const ended = once(client, "end"); client.end(); @@ -647,11 +647,6 @@ describe("HTTP/2 upgrade — the accepted socket is released when the server sid if (netServer.listening) netServer.close(); } - // Once the application has the socket, what it wrote may still be on its way when the session goes down: in Bun a write - // over a stream completes before the stream has sent it. So the accepted socket is ended, not destroyed, and a client - // that never closes its side holds it. Releasing it needs a write that completes as in Node (#43877). - const heldByTheClient = process.versions.bun !== undefined && "the accepted socket waits for the client's FIN"; - test("after a failed handshake", async () => { const h2Server = http2.createSecureServer(TLS); const tlsClientError = once(h2Server, "tlsClientError"); @@ -668,7 +663,7 @@ describe("HTTP/2 upgrade — the accepted socket is released when the server sid } }); - test("after the session is destroyed", { todo: heldByTheClient }, async () => { + test("after the session is destroyed", async () => { const h2Server = http2.createSecureServer(TLS); const sessionClosed = new Promise(resolve => { h2Server.once("session", (session: http2.ServerHttp2Session) => { @@ -703,7 +698,7 @@ describe("HTTP/2 upgrade — the accepted socket is released when the server sid } }); - test("after a client that negotiated no protocol is turned away", { todo: heldByTheClient }, async () => { + test("after a client that negotiated no protocol is turned away", async () => { const h2Server = http2.createSecureServer({ ...TLS, unknownProtocolTimeout: 0 }); h2Server.on("session", () => assert.fail("a client without ALPN must not get a session")); const { netServer, port, accepted } = await acceptInto(h2Server); From 71233975a6f0fba838fdce7f426fbeccbc4211b8 Mon Sep 17 00:00:00 2001 From: robobun Date: Wed, 21 Oct 2026 06:48:17 +0000 Subject: [PATCH 8/8] test: the socket injected into an Http2SecureServer reaches the session as a TLSSocket --- .../js/node/http2/node-http2-upgrade.test.mts | 44 +++++++++++++++++++ 1 file changed, 44 insertions(+) diff --git a/test/js/node/http2/node-http2-upgrade.test.mts b/test/js/node/http2/node-http2-upgrade.test.mts index 478a57484f94..a436c6cca6db 100644 --- a/test/js/node/http2/node-http2-upgrade.test.mts +++ b/test/js/node/http2/node-http2-upgrade.test.mts @@ -186,6 +186,50 @@ describe("HTTP/2 upgrade — session event", () => { client.close(); srv.netServer.close(); }); + + test("the injected socket reaches the session as the server's TLSSocket", async () => { + // tls.Server wraps the injected socket like any other plain one: its own + // 'connection' listeners see it, and the session gets a TLSSocket over it. + const seen = Promise.withResolvers<{ remotePort: number; shape: Record }>(); + let userConnection = 0; + const h2Server = http2.createSecureServer(TLS, (req, res) => { + const socket = req.socket as tls.TLSSocket; + seen.resolve({ + remotePort: socket.remotePort!, + shape: { + userConnection, + isTLSSocket: socket instanceof tls.TLSSocket, + encrypted: socket.encrypted, + alpnProtocol: socket.alpnProtocol, + remoteAddress: socket.remoteAddress, + // The peer's origin: its address and port. + originSet: req.stream.session!.originSet, + }, + }); + res.end("ok"); + }); + h2Server.on("error", () => {}); + h2Server.on("connection", () => userConnection++); + const netServer = net.createServer(socket => h2Server.emit("connection", socket)); + await once(netServer.listen(0, "127.0.0.1"), "listening"); + const port = (netServer.address() as net.AddressInfo).port; + const client = connectClient(port); + try { + await request(client, "GET", "/"); + const { remotePort, shape } = await seen.promise; + assert.deepStrictEqual(shape, { + userConnection: 1, + isTLSSocket: true, + encrypted: true, + alpnProtocol: "h2", + remoteAddress: "127.0.0.1", + originSet: [`https://127.0.0.1:${remotePort}`], + }); + } finally { + client.close(); + netServer.close(); + } + }); }); describe("HTTP/2 upgrade — concurrent clients", () => {