JonathanWilbur / asn1-ts

ASN.1 TypeScript library, including codecs for Basic Encoding Rules (BER) and Distinguished Encoding Rules (DER).
MIT License
32 stars 6 forks source link

Error decoding string types in NodeJS version 11.0 and higher #5

Closed JonathanWilbur closed 5 years ago

JonathanWilbur commented 5 years ago

To my knowledge, these types fail to decode correctly in NodeJS version 11.0 and higher:

The problem starts with this piece of recurring code:

if (typeof TextEncoder !== "undefined") { // Browser JavaScript
    dateString = (new TextDecoder("utf-8")).decode(<ArrayBuffer>this.value.subarray(0).buffer);
} else if (typeof Buffer !== "undefined") { // NodeJS
    dateString = (new Buffer(this.value)).toString("utf-8");
}

Before NodeJS version 11.0, TextEncoder and TextDecoder were in the util part of the standard library. I did not know about this. I thought they were undefined in NodeJS altogether, so I wrote the above code to accommodate both browser and NodeJS versions. In version 11.0 of NodeJS, both TextEncoder and TextDecoder were made global, which made the first block execute instead of the second. This works fine in a web browser, but in NodeJS, it seems that this.value tends to be a slice of the underlying ArrayBuffer rather than a brand new Uint8Array, so when this.value.subarray(0) is called in NodeJS, it returns the entire underlying ArrayBuffer instead of the slice, which we are expecting to be a copy of this.value.