diff --git a/src/js/node/_http2_upgrade.ts b/src/js/node/_http2_upgrade.ts deleted file mode 100644 index bd2a0c79724c..000000000000 --- a/src/js/node/_http2_upgrade.ts +++ /dev/null @@ -1,405 +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; - handedOver: 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.handedOver = false; -} - -// --------------------------------------------------------------------------- -// 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); - ctx.server.emit("tlsClientError", err, tlsSocket); - 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; - ctx.server.emit("tlsClientError", verifyError, tlsSocket); - 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(); -} - -// --------------------------------------------------------------------------- -// 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). -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]); -} - -// --------------------------------------------------------------------------- -// 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]); - - // 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 118faf531820..a436c6cca6db 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 @@ -185,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", () => { @@ -278,6 +323,53 @@ 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)); + + const transportError = new Error("transport failed"); + rawSocket!.destroy(transportError); + + await sessionClosed; + const { err, session } = await sessionErrored.promise; + assert.strictEqual(err, transportError); + assert.deepStrictEqual( + { sameSession: session === h2Session, destroyed: h2Session.destroyed }, + { sameSession: true, destroyed: true }, + ); + + client.close(); + netServer.close(); + }); }); describe("HTTP/2 upgrade — ALPN negotiation", () => { @@ -357,7 +449,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(); @@ -600,11 +691,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"); @@ -621,7 +707,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) => { @@ -656,7 +742,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); @@ -725,6 +811,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", () => {