From f1e3d07b2bfa7f5782b9634e95ba1a4d36ce349a Mon Sep 17 00:00:00 2001 From: achingbrain Date: Wed, 24 Jul 2024 15:33:44 +0200 Subject: [PATCH] fix: handle null server address The types for the `Server.address()` method in `@types/ws` are missing a return type of `null`. This can happen when a incoming connection is recieved after the ws `Server` has been closed but before the underlying HTTP server has finished closing down. https://github.com/DefinitelyTyped/DefinitelyTyped/pull/70132 will address the type problem, the change here is to handle the `null` return value. It also calls `.destroy` on the incoming message since we'd want to reclaim the resources immediately and not wait for the remote to time out. --- src/server.ts | 24 +++++++++++++++++------- 1 file changed, 17 insertions(+), 7 deletions(-) diff --git a/src/server.ts b/src/server.ts index 8f4fde3..32c4e32 100644 --- a/src/server.ts +++ b/src/server.ts @@ -61,15 +61,25 @@ class Server extends EventEmitter { } onWsServerConnection (socket: WebSocket, req: http.IncomingMessage): void { - const addr = this.wsServer.address() + let addr: string | AddressInfo - if (typeof addr === 'string') { - this.emit('error', new Error('Cannot listen on unix sockets')) - return - } + try { + if (req.socket.remoteAddress == null || req.socket.remotePort == null) { + throw new Error('Remote connection did not have address and/or port') + } + + addr = this.wsServer.address() + + if (typeof addr === 'string') { + throw new Error('Cannot listen on unix sockets') + } - if (req.socket.remoteAddress == null || req.socket.remotePort == null) { - this.emit('error', new Error('Remote connection did not have address and/or port')) + if (addr == null) { + throw new Error('Server was closing or not running') + } + } catch (err: any) { + req.destroy(err) + this.emit('error', err) return }