Skip to content

Commit

Permalink
fixup
Browse files Browse the repository at this point in the history
  • Loading branch information
KhafraDev committed Feb 25, 2024
1 parent c154a63 commit 69f3032
Show file tree
Hide file tree
Showing 3 changed files with 38 additions and 1 deletion.
5 changes: 5 additions & 0 deletions lib/web/websocket/connection.js
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand Down
32 changes: 32 additions & 0 deletions test/websocket/issue-2844.js
Original file line number Diff line number Diff line change
Expand Up @@ -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
})
2 changes: 1 addition & 1 deletion test/wpt/server/websocket.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -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) => {
Expand Down

0 comments on commit 69f3032

Please sign in to comment.