Skip to content

Commit b6f33a2

Browse files
committed
Decode invalid UTF-8 in short strings like TextDecoder
utf8DecodeJs read continuation bytes without checking them or the string's end, so a truncated sequence took bytes from the next value and overlong sequences decoded to real characters (C0 80 -> NUL). Follow the WHATWG decoder: one U+FFFD per maximal subpart, and never read past byteLength. Fixes #305
1 parent 6d4b666 commit b6f33a2

2 files changed

Lines changed: 135 additions & 20 deletions

File tree

‎src/utils/utf8.ts‎

Lines changed: 54 additions & 20 deletions
Original file line numberDiff line numberDiff line change
@@ -108,6 +108,9 @@ export function utf8Encode(str: string, output: Uint8Array, outputOffset: number
108108

109109
const CHUNK_SIZE = 0x1_000;
110110

111+
// Decodes UTF-8 like TextDecoder (WHATWG Encoding Standard): an ill-formed
112+
// sequence becomes one U+FFFD per maximal subpart, and a sequence is never
113+
// read past `inputOffset + byteLength`.
111114
export function utf8DecodeJs(bytes: Uint8Array, inputOffset: number, byteLength: number): string {
112115
let offset = inputOffset;
113116
const end = offset + byteLength;
@@ -119,29 +122,60 @@ export function utf8DecodeJs(bytes: Uint8Array, inputOffset: number, byteLength:
119122
if ((byte1 & 0x80) === 0) {
120123
// 1 byte
121124
units.push(byte1);
122-
} else if ((byte1 & 0xe0) === 0xc0) {
125+
} else if (byte1 >= 0xc2 && byte1 <= 0xdf) {
123126
// 2 bytes
124-
const byte2 = bytes[offset++]! & 0x3f;
125-
units.push(((byte1 & 0x1f) << 6) | byte2);
126-
} else if ((byte1 & 0xf0) === 0xe0) {
127-
// 3 bytes
128-
const byte2 = bytes[offset++]! & 0x3f;
129-
const byte3 = bytes[offset++]! & 0x3f;
130-
units.push(((byte1 & 0x1f) << 12) | (byte2 << 6) | byte3);
131-
} else if ((byte1 & 0xf8) === 0xf0) {
132-
// 4 bytes
133-
const byte2 = bytes[offset++]! & 0x3f;
134-
const byte3 = bytes[offset++]! & 0x3f;
135-
const byte4 = bytes[offset++]! & 0x3f;
136-
let unit = ((byte1 & 0x07) << 0x12) | (byte2 << 0x0c) | (byte3 << 0x06) | byte4;
137-
if (unit > 0xffff) {
138-
unit -= 0x10000;
139-
units.push(((unit >>> 10) & 0x3ff) | 0xd800);
140-
unit = 0xdc00 | (unit & 0x3ff);
127+
const byte2 = offset < end ? bytes[offset]! : 0;
128+
if ((byte2 & 0xc0) === 0x80) {
129+
offset++;
130+
units.push(((byte1 & 0x1f) << 6) | (byte2 & 0x3f));
131+
} else {
132+
units.push(0xfffd);
133+
}
134+
} else if (byte1 >= 0xe0 && byte1 <= 0xef) {
135+
// 3 bytes; E0 and ED narrow the second byte to reject overlongs and surrogates
136+
const byte2 = offset < end ? bytes[offset]! : 0;
137+
const lower = byte1 === 0xe0 ? 0xa0 : 0x80;
138+
const upper = byte1 === 0xed ? 0x9f : 0xbf;
139+
if (byte2 >= lower && byte2 <= upper) {
140+
offset++;
141+
const byte3 = offset < end ? bytes[offset]! : 0;
142+
if ((byte3 & 0xc0) === 0x80) {
143+
offset++;
144+
units.push(((byte1 & 0x0f) << 12) | ((byte2 & 0x3f) << 6) | (byte3 & 0x3f));
145+
} else {
146+
units.push(0xfffd);
147+
}
148+
} else {
149+
units.push(0xfffd);
150+
}
151+
} else if (byte1 >= 0xf0 && byte1 <= 0xf4) {
152+
// 4 bytes; F0 and F4 narrow the second byte to reject overlongs and values above U+10FFFF
153+
const byte2 = offset < end ? bytes[offset]! : 0;
154+
const lower = byte1 === 0xf0 ? 0x90 : 0x80;
155+
const upper = byte1 === 0xf4 ? 0x8f : 0xbf;
156+
if (byte2 >= lower && byte2 <= upper) {
157+
offset++;
158+
const byte3 = offset < end ? bytes[offset]! : 0;
159+
if ((byte3 & 0xc0) === 0x80) {
160+
offset++;
161+
const byte4 = offset < end ? bytes[offset]! : 0;
162+
if ((byte4 & 0xc0) === 0x80) {
163+
offset++;
164+
const unit =
165+
(((byte1 & 0x07) << 18) | ((byte2 & 0x3f) << 12) | ((byte3 & 0x3f) << 6) | (byte4 & 0x3f)) - 0x10000;
166+
units.push(((unit >>> 10) & 0x3ff) | 0xd800, 0xdc00 | (unit & 0x3ff));
167+
} else {
168+
units.push(0xfffd);
169+
}
170+
} else {
171+
units.push(0xfffd);
172+
}
173+
} else {
174+
units.push(0xfffd);
141175
}
142-
units.push(unit);
143176
} else {
144-
units.push(byte1);
177+
// continuation byte without a lead byte, C0, C1 or F5..FF
178+
units.push(0xfffd);
145179
}
146180

147181
if (units.length >= CHUNK_SIZE) {

‎test/decode-invalid-utf8.test.ts‎

Lines changed: 81 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,81 @@
1+
import assert from "assert";
2+
import { decode } from "../src/index.ts";
3+
import { utf8DecodeJs, utf8DecodeTD } from "../src/utils/utf8.ts";
4+
5+
function str8(bytes: Array<number>): Array<number> {
6+
return [0xd9, bytes.length, ...bytes];
7+
}
8+
9+
describe("decode invalid UTF-8 strings", () => {
10+
it("does not read a truncated sequence past the end of the string", () => {
11+
// ["\xe2\x82", "A"]: the first string must not take the header of the second one
12+
const actual = decode(Uint8Array.from([0x92, ...str8([0xe2, 0x82]), ...str8([0x41])]));
13+
assert.deepStrictEqual(actual, ["\ufffd", "A"]);
14+
});
15+
16+
it("does not read a truncated sequence past the end of a map key", () => {
17+
const actual = decode(Uint8Array.from([0x81, 0xa2, 0xe2, 0x82, 0xa1, 0x41]));
18+
assert.deepStrictEqual(actual, Object.fromEntries([["\ufffd", "A"]]));
19+
});
20+
21+
it("decodes overlong sequences to U+FFFD, not to NUL", () => {
22+
assert.deepStrictEqual(decode(Uint8Array.from(str8([0xc0, 0x80]))), "\ufffd\ufffd");
23+
assert.deepStrictEqual(decode(Uint8Array.from(str8([0xe0, 0x80, 0x80]))), "\ufffd\ufffd\ufffd");
24+
assert.deepStrictEqual(decode(Uint8Array.from(str8([0xf0, 0x80, 0x80, 0x80]))), "\ufffd\ufffd\ufffd\ufffd");
25+
});
26+
27+
it("decodes short strings the same as long strings", () => {
28+
const samples = [
29+
[0x80],
30+
[0xff],
31+
[0xc2],
32+
[0xc1, 0xbf],
33+
[0xe2, 0x82],
34+
[0xe0, 0x9f, 0xbf],
35+
[0xed, 0xa0, 0x80],
36+
[0xf0, 0x9f, 0x98],
37+
[0xf4, 0x90, 0x80, 0x80],
38+
[0xe2, 0x82, 0xac, 0xf0, 0x9f, 0x98, 0x80],
39+
];
40+
for (const sample of samples) {
41+
const bytes = Uint8Array.from(sample);
42+
assert.strictEqual(utf8DecodeJs(bytes, 0, bytes.length), utf8DecodeTD(bytes, 0, bytes.length), String(sample));
43+
}
44+
});
45+
46+
it("matches TextDecoder on random byte sequences", () => {
47+
const pieces = [
48+
[0x41],
49+
[0x7f],
50+
[0xc2, 0xa9],
51+
[0xe2, 0x82, 0xac],
52+
[0xf0, 0x9f, 0x98, 0x80],
53+
[0xf4, 0x8f, 0xbf, 0xbf],
54+
[0xef, 0xbb, 0xbf],
55+
[0xc0, 0x80],
56+
[0xe0, 0x80, 0x80],
57+
[0xed, 0xa0, 0x80],
58+
[0xf4, 0x90, 0x80, 0x80],
59+
[0xf5],
60+
[0x80],
61+
[0xc2],
62+
[0xe2, 0x82],
63+
[0xf0, 0x9f, 0x98],
64+
];
65+
const decoder = new TextDecoder("utf-8", { ignoreBOM: true });
66+
let seed = 1;
67+
const random = (n: number) => {
68+
seed = (seed * 1103515245 + 12345) & 0x7fffffff;
69+
return seed % n;
70+
};
71+
for (let i = 0; i < 5000; i++) {
72+
const sample: Array<number> = [];
73+
const count = 1 + random(6);
74+
for (let j = 0; j < count; j++) {
75+
sample.push(...pieces[random(pieces.length)]!);
76+
}
77+
const bytes = Uint8Array.from([0x20, ...sample, 0x20]);
78+
assert.strictEqual(utf8DecodeJs(bytes, 1, sample.length), decoder.decode(bytes.subarray(1, 1 + sample.length)));
79+
}
80+
});
81+
});

0 commit comments

Comments
 (0)