@@ -135,21 +135,40 @@ interface DecoderReservedEvents {
135135 decoded : ( packet : Packet ) => void ;
136136}
137137
138+ type JSONReviver = ( this : any , key : string , value : any ) => any ;
139+
140+ export interface DecoderOptions {
141+ /**
142+ * Custom reviver to pass down to JSON.stringify()
143+ */
144+ reviver ?: JSONReviver ;
145+ /**
146+ * Maximum number of attachments per packet.
147+ * @default 3
148+ */
149+ maxAttachments ?: number ;
150+ }
151+
138152/**
139153 * A socket.io Decoder instance
140154 *
141155 * @return {Object } decoder
142156 */
143157export class Decoder extends Emitter < { } , { } , DecoderReservedEvents > {
144158 private reconstructor : BinaryReconstructor ;
159+ private opts : Required < DecoderOptions > ;
145160
146161 /**
147162 * Decoder constructor
148163 *
149- * @param {function } reviver - custom reviver to pass down to JSON.stringify
164+ * @param {function|DecoderOptions } opts - custom reviver to pass down to JSON.stringify or an options object
150165 */
151- constructor ( private reviver ?: ( this : any , key : string , value : any ) => any ) {
166+ constructor ( opts ?: DecoderOptions | JSONReviver ) {
152167 super ( ) ;
168+ this . opts = Object . assign ( {
169+ reviver : undefined ,
170+ maxAttachments : 3
171+ } , typeof opts === "function" ? { reviver : opts } : opts ) ;
153172 }
154173
155174 /**
@@ -225,6 +244,9 @@ export class Decoder extends Emitter<{}, {}, DecoderReservedEvents> {
225244 throw new Error ( "Illegal attachments" ) ;
226245 }
227246 p . attachments = Number ( buf ) ;
247+ if ( p . attachments > this . opts . maxAttachments ) {
248+ throw new Error ( "too many attachments" ) ;
249+ }
228250 }
229251
230252 // look up namespace (if any)
@@ -271,7 +293,7 @@ export class Decoder extends Emitter<{}, {}, DecoderReservedEvents> {
271293
272294 private tryParse ( str ) {
273295 try {
274- return JSON . parse ( str , this . reviver ) ;
296+ return JSON . parse ( str , this . opts . reviver ) ;
275297 } catch ( e ) {
276298 return false ;
277299 }
0 commit comments