Skip to content

Commit 7e8c41a

Browse files
marcolanaromcollina
authored andcommitted
fix/ws-error-handler - Handle WebSocket errors to avoid Node.js crashes (#228)
1 parent 7becc2c commit 7e8c41a

File tree

2 files changed

+27
-0
lines changed

2 files changed

+27
-0
lines changed

index.js

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -61,6 +61,10 @@ function fastifyWebsocket (fastify, opts, next) {
6161
const connection = WebSocket.createWebSocketStream(socket, opts.connectionOptions)
6262
connection.socket = socket
6363

64+
connection.on('error', (error) => {
65+
fastify.log.error(error)
66+
})
67+
6468
connection.socket.on('newListener', event => {
6569
if (event === 'message') {
6670
connection.resume()

test/base.js

Lines changed: 23 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -7,6 +7,7 @@ const test = require('tap').test
77
const Fastify = require('fastify')
88
const fastifyWebsocket = require('..')
99
const WebSocket = require('ws')
10+
const { once } = require('events')
1011

1112
test('Should expose a websocket', (t) => {
1213
t.plan(3)
@@ -594,3 +595,25 @@ test('Should preserve the prefix in non-websocket routes', (t) => {
594595
t.error(err)
595596
})
596597
})
598+
599+
test('Should Handle WebSocket errors to avoid Node.js crashes', async t => {
600+
t.plan(1)
601+
602+
const fastify = Fastify()
603+
await fastify.register(fastifyWebsocket)
604+
605+
fastify.get('/', { websocket: true }, ({ socket }) => {
606+
socket.on('error', err => {
607+
t.equal(err.code, 'WS_ERR_UNEXPECTED_RSV_2_3')
608+
})
609+
})
610+
611+
await fastify.listen({ port: 0 })
612+
613+
const client = new WebSocket('ws://localhost:' + fastify.server.address().port)
614+
await once(client, 'open')
615+
616+
client._socket.write(Buffer.from([0xa2, 0x00]))
617+
618+
await fastify.close()
619+
})

0 commit comments

Comments
 (0)