Skip to content

Commit

Permalink
fix: throw upon invalid payload format
Browse files Browse the repository at this point in the history
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 #86
  • Loading branch information
darrachequesne committed Sep 22, 2020
1 parent b23576a commit c327acb
Show file tree
Hide file tree
Showing 2 changed files with 6 additions and 17 deletions.
13 changes: 3 additions & 10 deletions lib/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -257,15 +257,15 @@ 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 = {
type: Number(str.charAt(0)),
};

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
Expand Down Expand Up @@ -316,7 +316,7 @@ export class Decoder extends Emitter {
if (isPayloadValid) {
p.data = payload;
} else {
return error("invalid payload");
throw new Error("invalid payload");
}
}

Expand Down Expand Up @@ -386,10 +386,3 @@ class BinaryReconstructor {
this.buffers = [];
}
}

function error(msg) {
return {
type: exports.ERROR,
data: "parser error: " + msg,
};
}
10 changes: 3 additions & 7 deletions test/parser.js
Original file line number Diff line number Diff line change
Expand Up @@ -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$/);
});
});

0 comments on commit c327acb

Please sign in to comment.