Skip to content

Commit

Permalink
fix: properly detect plain objects
Browse files Browse the repository at this point in the history
The typeof check was not sufficient, as it also matches arrays and
nulls.
  • Loading branch information
darrachequesne committed May 31, 2023
1 parent d9db473 commit b0e6400
Show file tree
Hide file tree
Showing 2 changed files with 8 additions and 2 deletions.
9 changes: 7 additions & 2 deletions lib/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -131,6 +131,11 @@ export class Encoder {
}
}

// see https://stackoverflow.com/questions/8511281/check-if-a-value-is-an-object-in-javascript
function isObject(value: any): boolean {
return Object.prototype.toString.call(value) === "[object Object]";
}

interface DecoderReservedEvents {
decoded: (packet: Packet) => void;
}
Expand Down Expand Up @@ -280,11 +285,11 @@ export class Decoder extends Emitter<{}, {}, DecoderReservedEvents> {
private static isPayloadValid(type: PacketType, payload: any): boolean {
switch (type) {
case PacketType.CONNECT:
return typeof payload === "object";
return isObject(payload);
case PacketType.DISCONNECT:
return payload === undefined;
case PacketType.CONNECT_ERROR:
return typeof payload === "string" || typeof payload === "object";
return typeof payload === "string" || isObject(payload);
case PacketType.EVENT:
case PacketType.BINARY_EVENT:
return (
Expand Down
1 change: 1 addition & 0 deletions test/parser.js
Original file line number Diff line number Diff line change
Expand Up @@ -115,6 +115,7 @@ describe("socket.io-parser", () => {

isInvalidPayload('442["some","data"');
isInvalidPayload('0/admin,"invalid"');
isInvalidPayload("0[]");
isInvalidPayload("1/admin,{}");
isInvalidPayload('2/admin,"invalid');
isInvalidPayload("2/admin,{}");
Expand Down

0 comments on commit b0e6400

Please # to comment.