Skip to content

Commit

Permalink
fix/ws-error-handler - Handle WebSocket errors to avoid Node.js crash…
Browse files Browse the repository at this point in the history
…es (#228)
  • Loading branch information
marcolanaro committed Nov 3, 2022
1 parent 6384aae commit c24adeb
Show file tree
Hide file tree
Showing 2 changed files with 26 additions and 0 deletions.
4 changes: 4 additions & 0 deletions index.js
Original file line number Diff line number Diff line change
Expand Up @@ -61,6 +61,10 @@ function fastifyWebsocket (fastify, opts, next) {
const connection = WebSocket.createWebSocketStream(socket, opts.connectionOptions)
connection.socket = socket

connection.on('error', (error) => {
fastify.log.error(error)
})

connection.socket.on('newListener', event => {
if (event === 'message') {
connection.resume()
Expand Down
22 changes: 22 additions & 0 deletions test/base.js
Original file line number Diff line number Diff line change
Expand Up @@ -564,3 +564,25 @@ test('Should preserve the prefix in non-websocket routes', (t) => {
t.error(err)
})
})

test('Should Handle WebSocket errors to avoid Node.js crashes', async t => {
t.plan(1)

const fastify = Fastify()
await fastify.register(fastifyWebsocket)

fastify.get('/', { websocket: true }, ({ socket }) => {
socket.on('error', err => {
t.equal(err.code, 'WS_ERR_UNEXPECTED_RSV_2_3')
})
})

await fastify.listen({ port: 0 })

const client = new WebSocket('ws://localhost:' + fastify.server.address().port)
await once(client, 'open')

client._socket.write(Buffer.from([0xa2, 0x00]))

await fastify.close()
})

0 comments on commit c24adeb

Please sign in to comment.