@@ -13,11 +13,14 @@ exports.ERROR = 4;
13
13
exports . BINARY_EVENT = 5 ;
14
14
exports . BINARY_ACK = 6 ;
15
15
16
- var errorPacket = {
17
- type : exports . ERROR ,
18
- data : 'parser error'
16
+ var isInteger = Number . isInteger || function ( value ) {
17
+ return typeof value === 'number' &&
18
+ isFinite ( value ) &&
19
+ Math . floor ( value ) === value ;
19
20
} ;
20
21
22
+ var isString = function ( value ) { return typeof value === 'string' ; } ;
23
+
21
24
function Encoder ( ) { }
22
25
23
26
Encoder . prototype . encode = function ( packet , callback ) {
@@ -28,13 +31,40 @@ function Decoder () {}
28
31
29
32
Emitter ( Decoder . prototype ) ;
30
33
34
+ function isDataValid ( decoded ) {
35
+ switch ( decoded . type ) {
36
+ case exports . CONNECT :
37
+ case exports . DISCONNECT :
38
+ return decoded . data === undefined ;
39
+ case exports . ERROR :
40
+ return isString ( decoded . data ) ;
41
+ default :
42
+ return Array . isArray ( decoded . data ) ;
43
+ }
44
+ }
45
+
31
46
Decoder . prototype . add = function ( obj ) {
32
- try {
33
- var decoded = JSON . parse ( obj ) ;
34
- this . emit ( 'decoded' , decoded ) ;
35
- } catch ( e ) {
36
- this . emit ( 'decoded' , errorPacket ) ;
47
+ var decoded = JSON . parse ( obj ) ;
48
+
49
+ var isTypeValid = isInteger ( decoded . type ) && decoded . type >= exports . CONNECT && decoded . type <= exports . BINARY_ACK ;
50
+ if ( ! isTypeValid ) {
51
+ throw new Error ( 'invalid packet type' ) ;
52
+ }
53
+
54
+ if ( ! isString ( decoded . nsp ) ) {
55
+ throw new Error ( 'invalid namespace' ) ;
37
56
}
57
+
58
+ if ( ! isDataValid ( decoded ) ) {
59
+ throw new Error ( 'invalid payload' ) ;
60
+ }
61
+
62
+ var isAckValid = decoded . id === undefined || isInteger ( decoded . id ) ;
63
+ if ( ! isAckValid ) {
64
+ throw new Error ( 'invalid packet id' ) ;
65
+ }
66
+
67
+ this . emit ( 'decoded' , decoded ) ;
38
68
} ;
39
69
40
70
Decoder . prototype . destroy = function ( ) { } ;
0 commit comments