msgpackr icon indicating copy to clipboard operation
msgpackr copied to clipboard

unpack(pack(s)) corrupts strings containing a lone surrogate, and differently depending on length

Open MildlyMeticulous opened this issue 4 months ago • 1 comments

unpack(pack(s)) does not round-trip when s contains a lone surrogate. The encoder writes WTF-8, the decoder rejects it as invalid UTF-8, and one character becomes three.

const { pack, unpack } = require('msgpackr');   // 2.0.4

const s = ('hi ' + '😀').slice(0, 4);            // "hi \ud83d", emoji cut in half
unpack(pack(s)) === s;                           // false
// in:  "hi \ud83d"              len 4
// out: "hi ���"  len 6

pack emits ed a0 bd for the lone surrogate. That is WTF-8, not UTF-8, and MessagePack str is UTF-8, so strict decoders reject it: new TextDecoder().decode() gives the same three replacement characters. TextEncoder writes ef bf bd, a single U+FFFD, for the same input.

The result also depends on string length, so the two decode paths disagree with each other:

UTF-8 body replacement chars produced
<= 65 bytes 3
>= 66 bytes 1

That is the readStringJS / TextDecoder split described in #177. The native addon was loaded for these measurements.

cbor-x 1.6.4 behaves identically, same 1-in-3-out for short strings and 1-in-1-out for long ones.

The realistic way to get a lone surrogate is truncating a string to N characters when position N falls inside an astral pair, as above. The value changes and its .length changes with it, so anything using the decoded string as a key or for equality diverges from the sender.

The fix is a choice. Encoding lone surrogates as U+FFFD, like TextEncoder does, makes pack lossy but keeps the wire format valid and consistent for decoders in other languages. Accepting WTF-8 in the decoder preserves the round trip but keeps emitting bytes that other implementations mangle; @msgpack/msgpack takes that route and round-trips this input.

Checked against the official msgpack-test-suite first, where both msgpackr and @msgpack/msgpack pass all 216 decode assertions, so this is not something that suite covers.

MildlyMeticulous avatar Jul 28 '26 09:07 MildlyMeticulous

Separate from the pack()-side design choice, there's an uncontroversial inconsistency in the current reject-and-replace behavior: readStringJS doesn't advance position past a rejected malformed sequence, so its continuation bytes get reprocessed as fresh lead bytes — producing 3 U+FFFD for a sequence that TextDecoder (the long-string path) replaces with exactly 1.

I'd like to send a PR that fixes readStringJS's position handling so both paths consistently emit 1 U+FFFD per malformed sequence, without touching the broader lossy-pack-vs-WTF8-decoder question. Would that be welcome, or would you rather resolve the design choice first?

rajanpanth avatar Aug 07 '26 07:08 rajanpanth