Skip to content

Commit

Permalink
[fix] Fix misleading error message
Browse files Browse the repository at this point in the history
Use the correct error message if the server sends an empty subprotocol
name.
  • Loading branch information
lpinca committed Aug 6, 2021
1 parent 6a72da3 commit c95e695
Show file tree
Hide file tree
Showing 2 changed files with 32 additions and 2 deletions.
2 changes: 1 addition & 1 deletion lib/websocket.js
Original file line number Diff line number Diff line change
Expand Up @@ -771,7 +771,7 @@ function initAsClient(websocket, address, protocols, options) {
const serverProt = res.headers['sec-websocket-protocol'];
let protError;

if (serverProt) {
if (serverProt !== undefined) {
if (!protocolSet.size) {
protError = 'Server sent a subprotocol but none was requested';
} else if (!protocolSet.has(serverProt)) {
Expand Down
32 changes: 31 additions & 1 deletion test/websocket.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -895,7 +895,7 @@ describe('WebSocket', () => {
});
});

it('fails if server sends an invalid subprotocol', (done) => {
it('fails if server sends an invalid subprotocol (1/2)', (done) => {
const wss = new WebSocket.Server({
handleProtocols: () => 'baz',
server
Expand All @@ -914,6 +914,36 @@ describe('WebSocket', () => {
});
});

it('fails if server sends an invalid subprotocol (2/2)', (done) => {
server.once('upgrade', (req, socket) => {
const key = crypto
.createHash('sha1')
.update(req.headers['sec-websocket-key'] + GUID)
.digest('base64');

socket.end(
'HTTP/1.1 101 Switching Protocols\r\n' +
'Upgrade: websocket\r\n' +
'Connection: Upgrade\r\n' +
`Sec-WebSocket-Accept: ${key}\r\n` +
'Sec-WebSocket-Protocol:\r\n' +
'\r\n'
);
});

const ws = new WebSocket(`ws://localhost:${server.address().port}`, [
'foo',
'bar'
]);

ws.on('open', () => done(new Error("Unexpected 'open' event")));
ws.on('error', (err) => {
assert.ok(err instanceof Error);
assert.strictEqual(err.message, 'Server sent an invalid subprotocol');
ws.on('close', () => done());
});
});

it('fails if server sends no subprotocol', (done) => {
const wss = new WebSocket.Server({
handleProtocols() {},
Expand Down

0 comments on commit c95e695

Please sign in to comment.