Skip to content

Commit c95e695

Browse files
committedAug 6, 2021
[fix] Fix misleading error message
Use the correct error message if the server sends an empty subprotocol name.
1 parent 6a72da3 commit c95e695

File tree

2 files changed

+32
-2
lines changed

2 files changed

+32
-2
lines changed
 

‎lib/websocket.js

+1-1
Original file line numberDiff line numberDiff line change
@@ -771,7 +771,7 @@ function initAsClient(websocket, address, protocols, options) {
771771
const serverProt = res.headers['sec-websocket-protocol'];
772772
let protError;
773773

774-
if (serverProt) {
774+
if (serverProt !== undefined) {
775775
if (!protocolSet.size) {
776776
protError = 'Server sent a subprotocol but none was requested';
777777
} else if (!protocolSet.has(serverProt)) {

‎test/websocket.test.js

+31-1
Original file line numberDiff line numberDiff line change
@@ -895,7 +895,7 @@ describe('WebSocket', () => {
895895
});
896896
});
897897

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

917+
it('fails if server sends an invalid subprotocol (2/2)', (done) => {
918+
server.once('upgrade', (req, socket) => {
919+
const key = crypto
920+
.createHash('sha1')
921+
.update(req.headers['sec-websocket-key'] + GUID)
922+
.digest('base64');
923+
924+
socket.end(
925+
'HTTP/1.1 101 Switching Protocols\r\n' +
926+
'Upgrade: websocket\r\n' +
927+
'Connection: Upgrade\r\n' +
928+
`Sec-WebSocket-Accept: ${key}\r\n` +
929+
'Sec-WebSocket-Protocol:\r\n' +
930+
'\r\n'
931+
);
932+
});
933+
934+
const ws = new WebSocket(`ws://localhost:${server.address().port}`, [
935+
'foo',
936+
'bar'
937+
]);
938+
939+
ws.on('open', () => done(new Error("Unexpected 'open' event")));
940+
ws.on('error', (err) => {
941+
assert.ok(err instanceof Error);
942+
assert.strictEqual(err.message, 'Server sent an invalid subprotocol');
943+
ws.on('close', () => done());
944+
});
945+
});
946+
917947
it('fails if server sends no subprotocol', (done) => {
918948
const wss = new WebSocket.Server({
919949
handleProtocols() {},

0 commit comments

Comments
 (0)
Please sign in to comment.