diff --git a/lib/websocket.js b/lib/websocket.js index 7175b2ec0..9760e1ec9 100644 --- a/lib/websocket.js +++ b/lib/websocket.js @@ -1191,9 +1191,20 @@ function receiverOnConclude(code, reason) { const websocket = this[kWebSocket]; websocket._closeFrameReceived = true; - websocket._closeMessage = reason; websocket._closeCode = code; + // + // The reason is a view into the buffer the socket delivered. Copy it so that + // the `WebSocket` does not keep that buffer alive. The copy is not pooled + // because a pooled one would keep the pool alive in the same way. + // + if (reason.length === 0) { + websocket._closeMessage = EMPTY_BUFFER; + } else { + websocket._closeMessage = Buffer.allocUnsafeSlow(reason.length); + websocket._closeMessage.set(reason); + } + if (websocket._socket[kWebSocket] === undefined) return; websocket._socket.removeListener('data', socketOnData); diff --git a/test/websocket.test.js b/test/websocket.test.js index f169292f6..99f973fa2 100644 --- a/test/websocket.test.js +++ b/test/websocket.test.js @@ -5206,5 +5206,22 @@ describe('WebSocket', () => { ws._socket.push(Buffer.concat(list)); }); }); + + it('does not retain the read buffer via the close reason', (done) => { + const wss = new WebSocket.Server({ port: 0 }, () => { + const ws = new WebSocket(`ws://localhost:${wss.address().port}`); + + ws.on('close', (code, reason) => { + assert.strictEqual(code, 1000); + assert.deepStrictEqual(reason, Buffer.from('bye')); + assert.strictEqual(reason.buffer.byteLength, reason.length); + wss.close(done); + }); + }); + + wss.on('connection', (ws) => { + ws.close(1000, 'bye'); + }); + }); }); });