From c327acbc3c3c2d0b2b439136cbcb56c81db173d6 Mon Sep 17 00:00:00 2001 From: Damien Arrachequesne Date: Tue, 22 Sep 2020 22:55:16 +0200 Subject: [PATCH] fix: throw upon invalid payload format An invalid packet was previously parsed as an ERROR packet, which was then ignored because it didn't contain any 'nsp' (namespace) field. This behavior was wrong because: - it means the other side is sending invalid payloads, so the connection must be closed right away - ERROR packets are meant for namespace authentication failures Parsing an invalid payload will now throw an error, which must be caught by the caller. Closes https://github.com/socketio/socket.io-parser/issues/86 --- lib/index.ts | 13 +++---------- test/parser.js | 10 +++------- 2 files changed, 6 insertions(+), 17 deletions(-) diff --git a/lib/index.ts b/lib/index.ts index ee87d03..2795e73 100644 --- a/lib/index.ts +++ b/lib/index.ts @@ -257,7 +257,7 @@ export class Decoder extends Emitter { * @param {String} str * @return {Object} packet */ - private decodeString(str) { + private decodeString(str): Packet { let i = 0; // look up type const p: any = { @@ -265,7 +265,7 @@ export class Decoder extends Emitter { }; if (null == exports.types[p.type]) { - return error("unknown packet type " + p.type); + throw new Error("unknown packet type " + p.type); } // look up attachments if type binary @@ -316,7 +316,7 @@ export class Decoder extends Emitter { if (isPayloadValid) { p.data = payload; } else { - return error("invalid payload"); + throw new Error("invalid payload"); } } @@ -386,10 +386,3 @@ class BinaryReconstructor { this.buffers = []; } } - -function error(msg) { - return { - type: exports.ERROR, - data: "parser error: " + msg, - }; -} diff --git a/test/parser.js b/test/parser.js index 281f188..22483be 100644 --- a/test/parser.js +++ b/test/parser.js @@ -86,12 +86,8 @@ describe('parser', function(){ } }); - it('returns an error packet on parsing error', function(done){ - var decoder = new parser.Decoder(); - decoder.on('decoded', function(packet) { - expect(packet).to.eql({ type: 4, data: 'parser error: invalid payload' }); - done(); - }); - decoder.add('442["some","data"'); + it('throw an error upon parsing error', () => { + expect(() => new parser.Decoder().add('442["some","data"')).to.throwException(/^invalid payload$/); + expect(() => new parser.Decoder().add('999')).to.throwException(/^unknown packet type 9$/); }); });