From 69f303279b3929e45355a974128edb50ba356c91 Mon Sep 17 00:00:00 2001 From: Khafra Date: Sun, 25 Feb 2024 17:37:52 -0500 Subject: [PATCH] fixup --- lib/web/websocket/connection.js | 5 +++++ test/websocket/issue-2844.js | 32 ++++++++++++++++++++++++++++++++ test/wpt/server/websocket.mjs | 2 +- 3 files changed, 38 insertions(+), 1 deletion(-) diff --git a/lib/web/websocket/connection.js b/lib/web/websocket/connection.js index 45f68e1de93..855706938a9 100644 --- a/lib/web/websocket/connection.js +++ b/lib/web/websocket/connection.js @@ -189,6 +189,11 @@ function establishWebSocketConnection (url, protocols, ws, onEstablish, options) failWebsocketConnection(ws, 'Protocol was not set in the opening handshake.') return } + } else if (request.headersList.contains('sec-websocket-protocol', true)) { + // If the server did not send a Sec-WebSocket-Protocol header but the client did, + // fail the connection. + failWebsocketConnection(ws, 'Client sent a Sec-WebSocket-Protocol header but did not receive one from the server.') + return } response.socket.on('data', onSocketData) diff --git a/test/websocket/issue-2844.js b/test/websocket/issue-2844.js index fc6cad76252..d103a1722ff 100644 --- a/test/websocket/issue-2844.js +++ b/test/websocket/issue-2844.js @@ -39,3 +39,35 @@ test('The server must reply with at least one subprotocol the client sends', asy await completed }) + +test('The connection fails when the client sends subprotocols that the server does not responc with', async (t) => { + const { completed, fail, ok } = tspl(t, { plan: 1 }) + + const wss = new WebSocketServer({ + handleProtocols: () => false, + port: 0 + }) + + wss.on('connection', (ws) => { + ws.on('error', fail) + ws.send('something') + }) + + await once(wss, 'listening') + + const ws = new WebSocket(`ws://localhost:${wss.address().port}`, { + protocols: ['json'] + }) + + ws.onerror = ok.bind(null, true) + // The server will try to send 'something', this ensures that the connection + // fails during the handshake and doesn't receive any messages. + ws.onmessage = fail + + t.after(() => { + wss.close() + ws.close() + }) + + await completed +}) diff --git a/test/wpt/server/websocket.mjs b/test/wpt/server/websocket.mjs index cc8ce78151b..9bb05d12612 100644 --- a/test/wpt/server/websocket.mjs +++ b/test/wpt/server/websocket.mjs @@ -8,7 +8,7 @@ import { server } from './server.mjs' const wss = new WebSocketServer({ server, - handleProtocols: (protocols) => [...protocols].join(', ') + handleProtocols: (protocols) => protocols.values().next().value }) wss.on('connection', (ws, request) => {