From 772236a13ff2bd28291c911b7c25fbfe99580ed1 Mon Sep 17 00:00:00 2001 From: Luigi Pinca Date: Fri, 9 Jul 2021 12:34:22 +0200 Subject: [PATCH] [fix] Abort the handshake if the server is closing or closed Prevent WebSocket connections from being established after `WebSocketServer.prototype.close()` is called. --- lib/websocket-server.js | 2 ++ test/websocket-server.test.js | 22 ++++++++++++++++++++++ 2 files changed, 24 insertions(+) diff --git a/lib/websocket-server.js b/lib/websocket-server.js index e9ec2cbd7..fe7fdf501 100644 --- a/lib/websocket-server.js +++ b/lib/websocket-server.js @@ -297,6 +297,8 @@ class WebSocketServer extends EventEmitter { ); } + if (this._state > RUNNING) return abortHandshake(socket, 503); + const digest = createHash('sha1') .update(key + GUID) .digest('base64'); diff --git a/test/websocket-server.test.js b/test/websocket-server.test.js index 310c87c2e..90ceb5646 100644 --- a/test/websocket-server.test.js +++ b/test/websocket-server.test.js @@ -613,6 +613,28 @@ describe('WebSocketServer', () => { }); }); + it('fails if the WebSocket server is closing or closed', (done) => { + const server = http.createServer(); + const wss = new WebSocket.Server({ noServer: true }); + + server.on('upgrade', (req, socket, head) => { + wss.close(); + wss.handleUpgrade(req, socket, head, () => { + done(new Error('Unexpected callback invocation')); + }); + }); + + server.listen(0, () => { + const ws = new WebSocket(`ws://localhost:${server.address().port}`); + + ws.on('unexpected-response', (req, res) => { + assert.strictEqual(res.statusCode, 503); + res.resume(); + server.close(done); + }); + }); + }); + it('handles unsupported extensions', (done) => { const wss = new WebSocket.Server( {