diff --git a/src/__tests__/use.ts b/src/__tests__/use.ts index 9ec50566..9d5e6cfe 100644 --- a/src/__tests__/use.ts +++ b/src/__tests__/use.ts @@ -361,6 +361,28 @@ for (const { tServer, startTServer } of tServers) { // }, ); + it('should limit the internal server error message size', async () => { + const { url } = await startTServer({ + onConnect: () => { + throw new Error( + 'i am exactly 124 characters long i am exactly 124 characters long i am exactly 124 characters long i am exactly 124 characte', + ); + }, + }); + + const client = await createTClient(url); + client.ws.send( + stringifyMessage({ + type: MessageType.ConnectionInit, + }), + ); + + await client.waitForClose((event) => { + expect(event.code).toBe(CloseCode.InternalServerError); + expect(event.reason).toBe('Internal server error'); + }); + }); + describe('Keep-Alive', () => { it('should dispatch pings after the timeout has passed', async (done) => { const { url } = await startTServer(undefined, 50); diff --git a/src/use/fastify-websocket.ts b/src/use/fastify-websocket.ts index 508bf1a8..f22903e9 100644 --- a/src/use/fastify-websocket.ts +++ b/src/use/fastify-websocket.ts @@ -93,7 +93,10 @@ export function makeHandler< } catch (err) { socket.close( CloseCode.InternalServerError, - isProd ? 'Internal server error' : err.message, + // close reason should fit in one frame https://datatracker.ietf.org/doc/html/rfc6455#section-5.2 + isProd || err.message.length > 123 + ? 'Internal server error' + : err.message, ); } }), diff --git a/src/use/uWebSockets.ts b/src/use/uWebSockets.ts index b5f08b70..08b658be 100644 --- a/src/use/uWebSockets.ts +++ b/src/use/uWebSockets.ts @@ -191,7 +191,10 @@ export function makeBehavior< } catch (err) { socket.end( CloseCode.InternalServerError, - isProd ? 'Internal server error' : err.message, + // close reason should fit in one frame https://datatracker.ietf.org/doc/html/rfc6455#section-5.2 + isProd || err.message.length > 123 + ? 'Internal server error' + : err.message, ); } }, diff --git a/src/use/ws.ts b/src/use/ws.ts index fbe77f42..a663bba9 100644 --- a/src/use/ws.ts +++ b/src/use/ws.ts @@ -111,7 +111,10 @@ export function useServer< } catch (err) { socket.close( CloseCode.InternalServerError, - isProd ? 'Internal server error' : err.message, + // close reason should fit in one frame https://datatracker.ietf.org/doc/html/rfc6455#section-5.2 + isProd || err.message.length > 123 + ? 'Internal server error' + : err.message, ); } }),