diff --git a/doc/ws.md b/doc/ws.md index a9c3a2fd5..f645001a3 100644 --- a/doc/ws.md +++ b/doc/ws.md @@ -328,6 +328,9 @@ This class represents a WebSocket. It extends the `EventEmitter`. depending on the `protocolVersion`. - `perMessageDeflate` {Boolean|Object} Enable/disable permessage-deflate. - `protocolVersion` {Number} Value of the `Sec-WebSocket-Version` header. + - `requireProtocolSelection` {Boolean} Specifies whether to treat a missing + `Sec-WebSocket-Protocol` header in the server response as an error when + subprotocols are requested. Defaults to `true`. - `skipUTF8Validation` {Boolean} Specifies whether or not to skip UTF-8 validation for text and close messages. Defaults to `false`. Set to `true` only if the server is trusted. diff --git a/lib/websocket.js b/lib/websocket.js index ca2e1ad80..fa27b1482 100644 --- a/lib/websocket.js +++ b/lib/websocket.js @@ -650,6 +650,9 @@ module.exports = WebSocket; * permessage-deflate * @param {Number} [options.protocolVersion=13] Value of the * `Sec-WebSocket-Version` header + * @param {Boolean} [options.requireProtocolSelection=false] Specifies whether + * to treat a missing `Sec-WebSocket-Protocol` header in the server response + * as an error when subprotocols are requested. * @param {Boolean} [options.skipUTF8Validation=false] Specifies whether or * not to skip UTF-8 validation for text and close messages * @private @@ -663,6 +666,7 @@ function initAsClient(websocket, address, protocols, options) { maxPayload: 100 * 1024 * 1024, skipUTF8Validation: false, perMessageDeflate: true, + requireProtocolSelection: true, followRedirects: false, maxRedirects: 10, ...options, @@ -959,7 +963,7 @@ function initAsClient(websocket, address, protocols, options) { } else if (!protocolSet.has(serverProt)) { protError = 'Server sent an invalid subprotocol'; } - } else if (protocolSet.size) { + } else if (protocolSet.size && opts.requireProtocolSelection) { protError = 'Server sent no subprotocol'; } diff --git a/test/websocket.test.js b/test/websocket.test.js index 012f7c0a6..48d2662a3 100644 --- a/test/websocket.test.js +++ b/test/websocket.test.js @@ -1402,6 +1402,29 @@ describe('WebSocket', () => { }); }); + it('honors the `requireProtocolSelection` option', (done) => { + const wss = new WebSocket.Server({ + handleProtocols() {}, + server + }); + + wss.on('connection', (ws) => { + assert.strictEqual(ws.protocol, ''); + ws.on('close', () => wss.close(done)); + }); + + const ws = new WebSocket( + `ws://localhost:${server.address().port}`, + 'foo', + { requireProtocolSelection: false } + ); + + ws.on('open', () => { + assert.strictEqual(ws.protocol, ''); + ws.close(); + }); + }); + it('honors the `createConnection` option', (done) => { const wss = new WebSocket.Server({ noServer: true, path: '/foo' });