Skip to content

Commit

Permalink
[fix] Abort the handshake if the server is closing or closed
Browse files Browse the repository at this point in the history
Prevent WebSocket connections from being established after
`WebSocketServer.prototype.close()` is called.
  • Loading branch information
lpinca committed Jul 9, 2021
1 parent 5a58730 commit 772236a
Show file tree
Hide file tree
Showing 2 changed files with 24 additions and 0 deletions.
2 changes: 2 additions & 0 deletions lib/websocket-server.js
Original file line number Diff line number Diff line change
Expand Up @@ -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');
Expand Down
22 changes: 22 additions & 0 deletions test/websocket-server.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -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(
{
Expand Down

0 comments on commit 772236a

Please sign in to comment.