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 authored and mcollina committed Nov 4, 2022
1 parent 7becc2c commit 7e8c41a
Show file tree
Hide file tree
Showing 2 changed files with 27 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
23 changes: 23 additions & 0 deletions test/base.js
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ const test = require('tap').test
const Fastify = require('fastify')
const fastifyWebsocket = require('..')
const WebSocket = require('ws')
const { once } = require('events')

test('Should expose a websocket', (t) => {
t.plan(3)
Expand Down Expand Up @@ -594,3 +595,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 7e8c41a

Please sign in to comment.