Skip to content

Commit 772236a

Browse files
committed
[fix] Abort the handshake if the server is closing or closed
Prevent WebSocket connections from being established after `WebSocketServer.prototype.close()` is called.
1 parent 5a58730 commit 772236a

File tree

2 files changed

+24
-0
lines changed

2 files changed

+24
-0
lines changed

lib/websocket-server.js

+2
Original file line numberDiff line numberDiff line change
@@ -297,6 +297,8 @@ class WebSocketServer extends EventEmitter {
297297
);
298298
}
299299

300+
if (this._state > RUNNING) return abortHandshake(socket, 503);
301+
300302
const digest = createHash('sha1')
301303
.update(key + GUID)
302304
.digest('base64');

test/websocket-server.test.js

+22
Original file line numberDiff line numberDiff line change
@@ -613,6 +613,28 @@ describe('WebSocketServer', () => {
613613
});
614614
});
615615

616+
it('fails if the WebSocket server is closing or closed', (done) => {
617+
const server = http.createServer();
618+
const wss = new WebSocket.Server({ noServer: true });
619+
620+
server.on('upgrade', (req, socket, head) => {
621+
wss.close();
622+
wss.handleUpgrade(req, socket, head, () => {
623+
done(new Error('Unexpected callback invocation'));
624+
});
625+
});
626+
627+
server.listen(0, () => {
628+
const ws = new WebSocket(`ws://localhost:${server.address().port}`);
629+
630+
ws.on('unexpected-response', (req, res) => {
631+
assert.strictEqual(res.statusCode, 503);
632+
res.resume();
633+
server.close(done);
634+
});
635+
});
636+
});
637+
616638
it('handles unsupported extensions', (done) => {
617639
const wss = new WebSocket.Server(
618640
{

0 commit comments

Comments
 (0)