Skip to content

Commit c327acb

Browse files
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 #86
1 parent b23576a commit c327acb

File tree

2 files changed

+6
-17
lines changed

2 files changed

+6
-17
lines changed

lib/index.ts

Lines changed: 3 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -257,15 +257,15 @@ export class Decoder extends Emitter {
257257
* @param {String} str
258258
* @return {Object} packet
259259
*/
260-
private decodeString(str) {
260+
private decodeString(str): Packet {
261261
let i = 0;
262262
// look up type
263263
const p: any = {
264264
type: Number(str.charAt(0)),
265265
};
266266

267267
if (null == exports.types[p.type]) {
268-
return error("unknown packet type " + p.type);
268+
throw new Error("unknown packet type " + p.type);
269269
}
270270

271271
// look up attachments if type binary
@@ -316,7 +316,7 @@ export class Decoder extends Emitter {
316316
if (isPayloadValid) {
317317
p.data = payload;
318318
} else {
319-
return error("invalid payload");
319+
throw new Error("invalid payload");
320320
}
321321
}
322322

@@ -386,10 +386,3 @@ class BinaryReconstructor {
386386
this.buffers = [];
387387
}
388388
}
389-
390-
function error(msg) {
391-
return {
392-
type: exports.ERROR,
393-
data: "parser error: " + msg,
394-
};
395-
}

test/parser.js

Lines changed: 3 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -86,12 +86,8 @@ describe('parser', function(){
8686
}
8787
});
8888

89-
it('returns an error packet on parsing error', function(done){
90-
var decoder = new parser.Decoder();
91-
decoder.on('decoded', function(packet) {
92-
expect(packet).to.eql({ type: 4, data: 'parser error: invalid payload' });
93-
done();
94-
});
95-
decoder.add('442["some","data"');
89+
it('throw an error upon parsing error', () => {
90+
expect(() => new parser.Decoder().add('442["some","data"')).to.throwException(/^invalid payload$/);
91+
expect(() => new parser.Decoder().add('999')).to.throwException(/^unknown packet type 9$/);
9692
});
9793
});

0 commit comments

Comments
 (0)