diff --git a/README.md b/README.md index c2e1e0f..22c58b5 100644 --- a/README.md +++ b/README.md @@ -15,7 +15,7 @@ The passed bytes are given as a `Uint8Array`; the Node.js `Buffer` subclass of ` The returned value will be a canonical [encoding name](https://encoding.spec.whatwg.org/#names-and-labels) (not a label). You might then combine this with the [`@exodus/bytes`](https://github.com/ExodusOSS/bytes/) package to decode the result: ```js -const { TextDecoder } = require("@exodus/bytes"); +const { TextDecoder } = require("@exodus/bytes/encoding.js"); const htmlString = (new TextDecoder(sniffedEncoding)).decode(htmlBytes); ``` @@ -31,7 +31,7 @@ const sniffedEncoding = htmlEncodingSniffer(htmlBytes, { }); ``` -The `xml` option is a boolean, defaulting to `false`. If set to `true`, then we bypass the [HTML encoding sniffing algorithm](https://html.spec.whatwg.org/multipage/syntax.html#encoding-sniffing-algorithm) and compute the encoding based on the presence of a BOM, or the other options provided. (In the future, we may perform sniffing of the `` declaration, but for now that is not implemented.) +The `xml` option is a boolean, defaulting to `false`. If set to `true`, then we bypass the [HTML encoding sniffing algorithm](https://html.spec.whatwg.org/multipage/syntax.html#encoding-sniffing-algorithm) and compute the encoding based on the presence of a BOM, a UTF-16 byte signature, an XML encoding declaration, or the other options provided. HTML `` declarations are ignored. XML well-formedness validation is left to the caller's XML parser. The `transportLayerEncodingLabel` is an encoding label that is obtained from the "transport layer" (probably a HTTP `Content-Type` header), which overrides everything but a BOM. diff --git a/lib/html-encoding-sniffer.js b/lib/html-encoding-sniffer.js index b9e78ef..bba75bb 100644 --- a/lib/html-encoding-sniffer.js +++ b/lib/html-encoding-sniffer.js @@ -1,32 +1,88 @@ "use strict"; const { getBOMEncoding, labelToName } = require("@exodus/bytes/encoding-lite.js"); -// https://html.spec.whatwg.org/#encoding-sniffing-algorithm module.exports = (uint8Array, { xml = false, transportLayerEncodingLabel, defaultEncoding } = {}) => { - if (defaultEncoding === undefined) { - defaultEncoding = xml ? "UTF-8" : "windows-1252"; - } + let encoding; + + if (xml) { + // Follow WebKit's XML encoding sniffing until https://github.com/whatwg/html/issues/12968 is resolved. + if (defaultEncoding === undefined) { + defaultEncoding = "UTF-8"; + } + + // https://www.rfc-editor.org/rfc/rfc7303#section-3.2 gives BOMs precedence over transport-layer encodings. + encoding = labelToName(getBOMEncoding(uint8Array)); + + if (encoding === null && transportLayerEncodingLabel !== undefined) { + encoding = labelToName(transportLayerEncodingLabel); + } + + // WebKit waits for eight bytes before checking the six-byte UTF-16 `= 8) { + if (uint8Array[0] === 0x3C && uint8Array[1] === 0x00 && + uint8Array[2] === 0x3F && uint8Array[3] === 0x00 && + uint8Array[4] === 0x78 && uint8Array[5] === 0x00) { + encoding = "UTF-16LE"; + } else if (uint8Array[0] === 0x00 && uint8Array[1] === 0x3C && + uint8Array[2] === 0x00 && uint8Array[3] === 0x3F && + uint8Array[4] === 0x00 && uint8Array[5] === 0x78) { + encoding = "UTF-16BE"; + } else { + encoding = getXMLDeclarationEncoding(uint8Array); + } + } - let encoding = labelToName(getBOMEncoding(uint8Array)); + if (encoding === null) { + encoding = defaultEncoding; + } + } else { + // https://html.spec.whatwg.org/multipage/parsing.html#encoding-sniffing-algorithm + if (defaultEncoding === undefined) { + defaultEncoding = "windows-1252"; + } + + encoding = labelToName(getBOMEncoding(uint8Array)); - if (encoding === null && transportLayerEncodingLabel !== undefined) { - encoding = labelToName(transportLayerEncodingLabel); + if (encoding === null && transportLayerEncodingLabel !== undefined) { + encoding = labelToName(transportLayerEncodingLabel); + } + + if (encoding === null) { + encoding = prescanHTMLEncoding(uint8Array); + } + + if (encoding === null) { + encoding = defaultEncoding; + } } - if (encoding === null && !xml) { - encoding = prescanMetaCharset(uint8Array); + return encoding; +}; + +// https://html.spec.whatwg.org/multipage/parsing.html#prescan-a-byte-stream-to-determine-its-encoding +function prescanHTMLEncoding(uint8Array) { + // Six-byte UTF-16 `= l) { + return null; + } if (attrRes.attr && !attributeList.has(attrRes.attr.name)) { attributeList.add(attrRes.attr.name); if (attrRes.attr.name === "http-equiv") { @@ -127,6 +187,65 @@ function prescanMetaCharset(uint8Array) { return null; } +// https://html.spec.whatwg.org/multipage/parsing.html#concept-get-xml-encoding-when-sniffing +function getXMLDeclarationEncoding(uint8Array) { + // Case-sensitive `= end) { + return null; + } + i += 8; + + // Unlike HTML attribute whitespace, this includes every ASCII control byte. + while (i < end && uint8Array[i] <= 0x20) { + i++; + } + if (i >= end || uint8Array[i] !== 0x3D) { + return null; + } + i++; + while (i < end && uint8Array[i] <= 0x20) { + i++; + } + + const quote = uint8Array[i]; + if (i >= end || (quote !== 0x22 && quote !== 0x27)) { + return null; + } + + let label = ""; + for (i++; i < end; i++) { + const c = uint8Array[i]; + if (c === quote) { + const encoding = labelToName(label); + return encoding === "UTF-16LE" || encoding === "UTF-16BE" ? "UTF-8" : encoding; + } + if (c <= 0x20) { + return null; + } + label += String.fromCharCode(c); + } + return null; +} + // https://html.spec.whatwg.org/multipage/syntax.html#concept-get-attributes-when-sniffing function getAttribute(uint8Array, i, l) { for (; i < l; i++) { diff --git a/test/meta.mjs b/test/meta.mjs index 434589d..80fedf5 100644 --- a/test/meta.mjs +++ b/test/meta.mjs @@ -141,3 +141,69 @@ describe("HTML meta declarations", () => { }); } }); + +describe("HTML meta declaration boundaries", () => { + // Each row: test name, input, expected encoding, and expected encoding with `defaultEncoding: "ISO-8859-16"`. + for (const [name, source, expected, expectedWithDefault] of [ + [ + "charset without a closing > at EOF", + ' at EOF", + ' at EOF", + ' at byte offset 1023", + `${'`, + "windows-1253", + "windows-1253" + ], + [ + "charset with a closing > at byte offset 1024", + `${'`, + "windows-1252", + "ISO-8859-16" + ], + [ + "http-equiv with a closing > at byte offset 1023", + `${'`, + "windows-1253", + "windows-1253" + ], + [ + "http-equiv with a closing > at byte offset 1024", + `${'`, + "windows-1252", + "ISO-8859-16" + ], + [ + "charset followed by an attribute extending beyond the prescan limit", + ``, + "windows-1252", + "ISO-8859-16" + ] + ]) { + it(name, () => { + const input = Uint8Array.from(source, c => c.charCodeAt(0)); + assert.equal(htmlEncodingSniffer(input), expected); + assert.equal(htmlEncodingSniffer(input, { defaultEncoding: "ISO-8859-16" }), expectedWithDefault); + }); + } +}); diff --git a/test/xml-declarations.mjs b/test/xml-declarations.mjs new file mode 100644 index 0000000..a02aad7 --- /dev/null +++ b/test/xml-declarations.mjs @@ -0,0 +1,556 @@ +import { describe, it } from "node:test"; +import { TextDecoder } from "@exodus/bytes/encoding.js"; +import { TextEncoder } from "node:util"; +import assert from "node:assert/strict"; +import htmlEncodingSniffer from "../lib/html-encoding-sniffer.js"; + +// Inspired by https://github.com/web-platform-tests/wpt/tree/master/html/syntax/xmldecl. +// These test the byte prescan, independently of an HTML or XML parser. +// Each row: test name, input, expected HTML encoding, expected XML encoding, +// and expected encoding in either mode with `defaultEncoding: "KOI8-U"`. +const declarations = [ + [ + "ordinary declaration", + '', + "windows-1251", + "windows-1251", + "windows-1251" + ], + [ + "single quotes", + "", + "windows-1251", + "windows-1251", + "windows-1251" + ], + [ + "encoding alias", + '', + "windows-1251", + "windows-1251", + "windows-1251" + ], + [ + "case-insensitive label", + '', + "windows-1251", + "windows-1251", + "windows-1251" + ], + [ + "no version", + '', + "windows-1251", + "windows-1251", + "windows-1251" + ], + [ + "no space or question mark", + '', + "windows-1251", + "windows-1251", + "windows-1251" + ], + [ + "extra letter", + '', + "windows-1251", + "windows-1251", + "windows-1251" + ], + [ + "processing instruction without version", + '', + "windows-1251", + "windows-1251", + "windows-1251" + ], + [ + "processing instruction with version", + '', + "windows-1251", + "windows-1251", + "windows-1251" + ], + [ + "processing instruction without equals signs", + '', + "windows-1252", + "UTF-8", + "KOI8-U" + ], + [ + "processing instruction with encoding after >", + ' encoding="windows-1251"?>', + "windows-1252", + "UTF-8", + "KOI8-U" + ], + [ + "extra less-than sign", + '', + "windows-1251", + "windows-1251", + "windows-1251" + ], + [ + "uppercase version", + '', + "windows-1251", + "windows-1251", + "windows-1251" + ], + [ + "encoding inside another name", + '', + "windows-1251", + "windows-1251", + "windows-1251" + ], + [ + "encoding inside another value", + '', + "windows-1251", + "windows-1251", + "windows-1251" + ], + [ + "meta inside declaration", + '', + "windows-1251", + "windows-1251", + "windows-1251" + ], + [ + "first declaration wins", + '', + "windows-1251", + "windows-1251", + "windows-1251" + ], + [ + "first encoding wins", + '', + "windows-1251", + "windows-1251", + "windows-1251" + ], + [ + "user-defined is preserved", + '', + "x-user-defined", + "x-user-defined", + "x-user-defined" + ], + [ + "replacement is preserved", + '', + "replacement", + "replacement", + "replacement" + ], + [ + "uppercase XML", + '', + "windows-1252", + "UTF-8", + "KOI8-U" + ], + [ + "uppercase encoding", + '', + "windows-1252", + "UTF-8", + "KOI8-U" + ], + [ + "leading space", + ' ', + "windows-1252", + "UTF-8", + "KOI8-U" + ], + [ + "leading comment", + '', + "windows-1252", + "UTF-8", + "KOI8-U" + ], + [ + "missing greater-than sign", + 'encoding="windows-1251"?>', + "windows-1252", + "UTF-8", + "KOI8-U" + ], + [ + "quote after declaration", + '"', + "windows-1252", + "UTF-8", + "KOI8-U" + ], + [ + "empty label", + '', + "windows-1252", + "UTF-8", + "KOI8-U" + ], + [ + "unknown label", + '', + "windows-1252", + "UTF-8", + "KOI8-U" + ], + [ + "unsupported UTF-32", + '', + "windows-1252", + "UTF-8", + "KOI8-U" + ], + [ + "unsupported UTF-7", + '', + "windows-1252", + "UTF-8", + "KOI8-U" + ], + [ + "no quotes", + "", + "windows-1252", + "UTF-8", + "KOI8-U" + ], + [ + "unmatched quotes", + '', + "windows-1252", + "UTF-8", + "KOI8-U" + ], + [ + "no equals sign", + '', + "windows-1252", + "UTF-8", + "KOI8-U" + ], + [ + "repeated encoding substring", + '', + "windows-1252", + "UTF-8", + "KOI8-U" + ], + [ + "encoding instead of quote", + '', + "windows-1252", + "UTF-8", + "KOI8-U" + ], + [ + "invalid first encoding", + '', + "windows-1252", + "UTF-8", + "KOI8-U" + ], + [ + "malformed first encoding", + '', + "windows-1252", + "UTF-8", + "KOI8-U" + ] +]; + +function bytes(string) { + return Uint8Array.from(string, c => c.charCodeAt(0)); +} + +describe("XML declarations", () => { + for (const [name, source, expectedHTML, expectedXML, expectedWithDefault] of declarations) { + it(name, () => { + const input = bytes(source); + assert.equal(htmlEncodingSniffer(input, { xml: false }), expectedHTML); + assert.equal(htmlEncodingSniffer(input, { xml: true }), expectedXML); + assert.equal(htmlEncodingSniffer(input, { xml: false, defaultEncoding: "KOI8-U" }), expectedWithDefault); + assert.equal(htmlEncodingSniffer(input, { xml: true, defaultEncoding: "KOI8-U" }), expectedWithDefault); + }); + } +}); + +for (const xml of [false, true]) { + describe(`XML declarations with xml: ${xml}`, () => { + for (let c = 0; c <= 0x20; c++) { + const character = String.fromCharCode(c); + + it(`accepts byte ${c} around the equals sign`, () => { + const input = bytes(``); + assert.equal(htmlEncodingSniffer(input, { xml }), "windows-1251"); + }); + + it(`rejects byte ${c} anywhere in the label`, () => { + for (const label of [`${character}windows-1251`, `windows${character}-1251`, `windows-1251${character}`]) { + const input = bytes(``); + assert.equal(htmlEncodingSniffer(input, { xml, defaultEncoding: "KOI8-U" }), "KOI8-U"); + } + }); + } + + it("does not treat DEL or high bytes as whitespace around the equals sign", () => { + // WebKit uses unsigned bytes here; Blink's signed `char` can incorrectly skip bytes >= 0x80. + for (let c = 0x7F; c <= 0xFF; c++) { + const character = String.fromCharCode(c); + for (const input of [ + ``, + `` + ]) { + assert.equal( + htmlEncodingSniffer(bytes(input), { xml, defaultEncoding: "KOI8-U" }), + "KOI8-U", + `byte 0x${c.toString(16)} in ${JSON.stringify(input)}` + ); + } + } + }); + + it("rejects DEL and high bytes anywhere in the label", () => { + for (let c = 0x7F; c <= 0xFF; c++) { + const character = String.fromCharCode(c); + for (const label of [`${character}windows-1251`, `windows${character}-1251`, `windows-1251${character}`]) { + const input = bytes(``); + assert.equal( + htmlEncodingSniffer(input, { xml, defaultEncoding: "KOI8-U" }), + "KOI8-U", + `label ${JSON.stringify(label)}` + ); + } + } + }); + + it("respects the offset and length of a Uint8Array view", () => { + const declaration = ''; + const input = bytes(`junk${declaration}junk`); + assert.equal(htmlEncodingSniffer(input.subarray(4, -4), { xml }), "windows-1251"); + assert.equal(htmlEncodingSniffer(input.subarray(4, -5), { xml, defaultEncoding: "KOI8-U" }), "KOI8-U"); + }); + + it("falls back for every truncated prefix of a declaration", () => { + const input = bytes(''); + for (let length = 0; length < input.length; length++) { + assert.equal(htmlEncodingSniffer(input.subarray(0, length), { xml, defaultEncoding: "KOI8-U" }), "KOI8-U"); + } + }); + + it("uses the transport encoding before the declaration", () => { + const input = bytes(''); + assert.equal(htmlEncodingSniffer(input, { xml, transportLayerEncodingLabel: "csisolatingreek" }), "ISO-8859-7"); + }); + + it("ignores an unknown transport encoding", () => { + const input = bytes(''); + assert.equal(htmlEncodingSniffer(input, { xml, transportLayerEncodingLabel: "unknown" }), "windows-1251"); + }); + + it("uses a BOM before the transport encoding and declaration", () => { + const input = new Uint8Array([0xEF, 0xBB, 0xBF, ...bytes('')]); + assert.equal(htmlEncodingSniffer(input, { xml, transportLayerEncodingLabel: "windows-1253" }), "UTF-8"); + }); + + it("recognizes a BOM even when fewer than eight bytes are available", () => { + for (const [encoding, bom] of [ + ["UTF-8", [0xEF, 0xBB, 0xBF]], + ["UTF-16LE", [0xFF, 0xFE]], + ["UTF-16BE", [0xFE, 0xFF]] + ]) { + assert.equal(htmlEncodingSniffer(new Uint8Array(bom), { + xml, + transportLayerEncodingLabel: "windows-1251" + }), encoding); + } + }); + + it("only honors meta declarations in HTML", () => { + const input = bytes(''); + assert.equal(htmlEncodingSniffer(input, { xml }), xml ? "windows-1251" : "windows-1253"); + }); + + it("only honors http-equiv declarations in HTML", () => { + const input = bytes(` + `); + assert.equal(htmlEncodingSniffer(input, { xml }), xml ? "windows-1251" : "windows-1253"); + }); + + for (const [label, encoding] of [ + ["UTF-16", "UTF-16LE"], + ["UTF-16LE", "UTF-16LE"], + ["UTF-16BE", "UTF-16BE"], + ["unicode", "UTF-16LE"], + ["unicodefffe", "UTF-16BE"], + ["csUnicode", "UTF-16LE"] + ]) { + it(`decodes an ASCII declaration of ${label} as UTF-8`, () => { + const source = `

日本語

`; + const input = new TextEncoder().encode(source); + const sniffedEncoding = htmlEncodingSniffer(input, { xml }); + assert.equal(sniffedEncoding, "UTF-8"); + assert.equal(new TextDecoder(sniffedEncoding).decode(input), source); + }); + + it(`preserves ${label} from the transport layer`, () => { + for (const input of [new Uint8Array(), bytes('')]) { + assert.equal(htmlEncodingSniffer(input, { xml, transportLayerEncodingLabel: label }), encoding); + } + }); + } + + for (const [encoding, signature] of [ + ["UTF-16LE", [0x3C, 0, 0x3F, 0, 0x78, 0]], + ["UTF-16BE", [0, 0x3C, 0, 0x3F, 0, 0x78]] + ]) { + it(`detects the ${encoding} signature before meta declarations`, () => { + const input = new Uint8Array([...signature, ...bytes('>')]); + assert.equal(htmlEncodingSniffer(input, { xml }), encoding); + assert.equal(htmlEncodingSniffer(input, { xml, transportLayerEncodingLabel: "utf8" }), "UTF-8"); + }); + + it(`requires ${xml ? 8 : 6} bytes of input to recognize a ${encoding} signature`, () => { + const input = new Uint8Array([...signature, 0, 0]); + for (let length = 0; length <= input.length; length++) { + const expected = length >= (xml ? 8 : 6) ? encoding : "KOI8-U"; + assert.equal( + htmlEncodingSniffer(input.subarray(0, length), { xml, defaultEncoding: "KOI8-U" }), + expected, + `${length} bytes` + ); + } + }); + + it(`requires all six bytes of the ${encoding} signature to match`, () => { + for (let i = 0; i < signature.length; i++) { + const input = new Uint8Array([...signature, 0, 0]); + input[i] ^= 0x80; + assert.equal(htmlEncodingSniffer(input, { xml, defaultEncoding: "KOI8-U" }), "KOI8-U"); + } + }); + + it(`requires a lowercase x in the ${encoding} signature`, () => { + const input = new Uint8Array([...signature, ...bytes('>')]); + input[signature.indexOf(0x78)] = 0x58; + assert.equal(htmlEncodingSniffer(input, { xml, defaultEncoding: "KOI8-U" }), xml ? "KOI8-U" : "windows-1253"); + }); + + it(`does not recognize a ${encoding} signature containing only { + const input = new Uint8Array([...signature.slice(0, 4), ...bytes('>')]); + assert.equal(htmlEncodingSniffer(input, { xml, defaultEncoding: "KOI8-U" }), xml ? "KOI8-U" : "windows-1253"); + }); + + it(`uses a BOM before the ${encoding} signature`, () => { + const input = new Uint8Array([0xEF, 0xBB, 0xBF, ...signature, 0, 0]); + assert.equal(htmlEncodingSniffer(input, { xml, transportLayerEncodingLabel: "windows-1251" }), "UTF-8"); + }); + + it(`does not look for a ${encoding} signature beyond the start`, () => { + const input = new Uint8Array([0x20, ...signature]); + assert.equal(htmlEncodingSniffer(input, { xml, defaultEncoding: "KOI8-U" }), "KOI8-U"); + }); + + it(`decodes a complete ${encoding} document without a BOM`, () => { + const source = `

日本語

`; + const input = new Uint8Array(source.length * 2); + const view = new DataView(input.buffer); + for (let i = 0; i < source.length; i++) { + view.setUint16(i * 2, source.charCodeAt(i), encoding === "UTF-16LE"); + } + const sniffedEncoding = htmlEncodingSniffer(input, { xml }); + assert.equal(sniffedEncoding, encoding); + assert.equal(new TextDecoder(sniffedEncoding).decode(input), source); + }); + } + + it("decodes non-ASCII text using the declared legacy encoding", () => { + const input = bytes('

\u00C0

'); + const encoding = htmlEncodingSniffer(input, { xml }); + assert.equal(encoding, "windows-1251"); + assert.equal(new TextDecoder(encoding).decode(input), '

А

'); + }); + + for (const length of [1023, 1024, 1025, 4096]) { + for (const position of ["before", "after"]) { + for (const trailingLength of [0, 8192]) { + it(`${length} bytes, padding ${position} encoding, ${trailingLength} trailing bytes`, () => { + const padding = " ".repeat(length - ''.length); + const declaration = position === "before" ? + `` : + ``; + assert.equal(declaration.length, length); + const input = bytes(declaration + "\0".repeat(trailingLength)); + assert.equal(htmlEncodingSniffer(input, { xml, defaultEncoding: "KOI8-U" }), "windows-1251"); + }); + } + } + } + + it("still requires the closing > in a long declaration", () => { + const input = bytes(``); + assert.equal(htmlEncodingSniffer(input.subarray(0, -1), { xml, defaultEncoding: "KOI8-U" }), "KOI8-U"); + }); + + it("does not search beyond the first > in a long declaration", () => { + const input = bytes(`encoding="windows-1251"?>`); + assert.equal(htmlEncodingSniffer(input, { xml, defaultEncoding: "KOI8-U" }), "KOI8-U"); + }); + }); +} + +describe("HTML prescan falling back to an XML declaration", () => { + for (const suffix of [ + '', + '', + '