diff --git a/lib/sender.js b/lib/sender.js index f23042453..75c78fb35 100644 --- a/lib/sender.js +++ b/lib/sender.js @@ -110,7 +110,13 @@ class Sender { buf = Buffer.allocUnsafe(2); buf.writeUInt16BE(code, 0); } else { - buf = Buffer.allocUnsafe(2 + Buffer.byteLength(data)); + const length = Buffer.byteLength(data); + + if (length > 123) { + throw new RangeError('The message must not be greater than 123 bytes'); + } + + buf = Buffer.allocUnsafe(2 + length); buf.writeUInt16BE(code, 0); buf.write(data, 2); } @@ -154,6 +160,10 @@ class Sender { ping(data, mask, cb) { const buf = toBuffer(data); + if (buf.length > 125) { + throw new RangeError('The data size must not be greater than 125 bytes'); + } + if (this._deflating) { this.enqueue([this.doPing, buf, mask, toBuffer.readOnly, cb]); } else { @@ -194,6 +204,10 @@ class Sender { pong(data, mask, cb) { const buf = toBuffer(data); + if (buf.length > 125) { + throw new RangeError('The data size must not be greater than 125 bytes'); + } + if (this._deflating) { this.enqueue([this.doPong, buf, mask, toBuffer.readOnly, cb]); } else { diff --git a/test/websocket.test.js b/test/websocket.test.js index b9275035d..87115eeb4 100644 --- a/test/websocket.test.js +++ b/test/websocket.test.js @@ -878,6 +878,21 @@ describe('WebSocket', () => { }); }); }); + + it('throws an error if the data size is greater than 125 bytes', (done) => { + const wss = new WebSocket.Server({ port: 0 }, () => { + const ws = new WebSocket(`ws://localhost:${wss.address().port}`); + + ws.on('open', () => { + assert.throws( + () => ws.ping(Buffer.alloc(126)), + /^RangeError: The data size must not be greater than 125 bytes$/ + ); + + wss.close(done); + }); + }); + }); }); describe('#pong', () => { @@ -1019,6 +1034,21 @@ describe('WebSocket', () => { }); }); }); + + it('throws an error if the data size is greater than 125 bytes', (done) => { + const wss = new WebSocket.Server({ port: 0 }, () => { + const ws = new WebSocket(`ws://localhost:${wss.address().port}`); + + ws.on('open', () => { + assert.throws( + () => ws.pong(Buffer.alloc(126)), + /^RangeError: The data size must not be greater than 125 bytes$/ + ); + + wss.close(done); + }); + }); + }); }); describe('#send', () => { @@ -1429,6 +1459,21 @@ describe('WebSocket', () => { }); }); + it('throws an error if the message is greater than 123 bytes', (done) => { + const wss = new WebSocket.Server({ port: 0 }, () => { + const ws = new WebSocket(`ws://localhost:${wss.address().port}`); + + ws.on('open', () => { + assert.throws( + () => ws.close(1000, 'a'.repeat(124)), + /^RangeError: The message must not be greater than 123 bytes$/ + ); + + wss.close(done); + }); + }); + }); + it('sends the close status code only when necessary', (done) => { let sent; const wss = new WebSocket.Server({ port: 0 }, () => {