From c24adeb3efd57a18b2f287c35d029e88b5a47194 Mon Sep 17 00:00:00 2001 From: Marco Lanaro Date: Thu, 3 Nov 2022 13:23:04 +0000 Subject: [PATCH] fix/ws-error-handler - Handle WebSocket errors to avoid Node.js crashes (#228) --- index.js | 4 ++++ test/base.js | 22 ++++++++++++++++++++++ 2 files changed, 26 insertions(+) diff --git a/index.js b/index.js index 638adfd..21ee508 100644 --- a/index.js +++ b/index.js @@ -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() diff --git a/test/base.js b/test/base.js index 34bd3d0..90d39b9 100644 --- a/test/base.js +++ b/test/base.js @@ -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() +})