Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 2 additions & 2 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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);
```

Expand All @@ -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 `<?xml?>` 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 `<meta>` 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.

Expand Down
147 changes: 133 additions & 14 deletions lib/html-encoding-sniffer.js
Original file line number Diff line number Diff line change
@@ -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 `<?x` signatures or an XML declaration.
if (encoding === null && uint8Array.byteLength >= 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 `<?x` signatures.
if (uint8Array[0] === 0x3C && uint8Array[1] === 0x00 &&
uint8Array[2] === 0x3F && uint8Array[3] === 0x00 &&
uint8Array[4] === 0x78 && uint8Array[5] === 0x00) {
return "UTF-16LE";
}
if (uint8Array[0] === 0x00 && uint8Array[1] === 0x3C &&
uint8Array[2] === 0x00 && uint8Array[3] === 0x3F &&
uint8Array[4] === 0x00 && uint8Array[5] === 0x78) {
return "UTF-16BE";
}

let encoding = prescanMetaCharset(uint8Array.subarray(0, 1024));
if (encoding === null) {
encoding = defaultEncoding;
// The XML declaration scan is not subject to the meta prescan's 1024-byte limit.
encoding = getXMLDeclarationEncoding(uint8Array);
}

return encoding;
};
}

// https://html.spec.whatwg.org/multipage/syntax.html#prescan-a-byte-stream-to-determine-its-encoding
function prescanMetaCharset(uint8Array) {
const l = Math.min(uint8Array.byteLength, 1024);
const l = uint8Array.byteLength;
for (let i = 0; i < l; i++) {
let c = uint8Array[i];
if (c === 0x3C) {
Expand Down Expand Up @@ -63,6 +119,10 @@ function prescanMetaCharset(uint8Array) {
let attrRes;
do {
attrRes = getAttribute(uint8Array, i, l);
// Reaching the prescan limit aborts the entire prescan, including attribute processing.
if (attrRes.i >= l) {
return null;
}
if (attrRes.attr && !attributeList.has(attrRes.attr.name)) {
attributeList.add(attrRes.attr.name);
if (attrRes.attr.name === "http-equiv") {
Expand Down Expand Up @@ -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 `<?xml` at the start of the stream.
if (uint8Array[0] !== 0x3C || uint8Array[1] !== 0x3F || uint8Array[2] !== 0x78 ||
uint8Array[3] !== 0x6D || uint8Array[4] !== 0x6C) {
return null;
}

const end = uint8Array.indexOf(0x3E, 5);
if (end === -1) {
return null;
}

let i = 5;
for (; i + 7 < end; i++) {
// The first case-sensitive `encoding` substring, even within another name.
if (uint8Array[i] === 0x65 && uint8Array[i + 1] === 0x6E && uint8Array[i + 2] === 0x63 &&
uint8Array[i + 3] === 0x6F && uint8Array[i + 4] === 0x64 && uint8Array[i + 5] === 0x69 &&
uint8Array[i + 6] === 0x6E && uint8Array[i + 7] === 0x67) {
break;
}
}
if (i + 7 >= 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++) {
Expand Down
66 changes: 66 additions & 0 deletions test/meta.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -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",
'<meta charset="windows-1253"',
"windows-1252",
"ISO-8859-16"
],
[
"charset followed by an unfinished attribute at EOF",
'<meta charset="windows-1253" unfinished="',
"windows-1252",
"ISO-8859-16"
],
[
"http-equiv without a closing > at EOF",
'<meta http-equiv="content-type" content="text/html;charset=windows-1253"',
"windows-1252",
"ISO-8859-16"
],
[
"content before http-equiv without a closing > at EOF",
'<meta content="text/html;charset=windows-1253" http-equiv="content-type"',
"windows-1252",
"ISO-8859-16"
],
[
"charset with a closing > at byte offset 1023",
`${'<meta charset="windows-1253"'.padEnd(1023)}>`,
"windows-1253",
"windows-1253"
],
[
"charset with a closing > at byte offset 1024",
`${'<meta charset="windows-1253"'.padEnd(1024)}>`,
"windows-1252",
"ISO-8859-16"
],
[
"http-equiv with a closing > at byte offset 1023",
`${'<meta http-equiv="content-type" content="text/html;charset=windows-1253"'.padEnd(1023)}>`,
"windows-1253",
"windows-1253"
],
[
"http-equiv with a closing > at byte offset 1024",
`${'<meta http-equiv="content-type" content="text/html;charset=windows-1253"'.padEnd(1024)}>`,
"windows-1252",
"ISO-8859-16"
],
[
"charset followed by an attribute extending beyond the prescan limit",
`<meta charset="windows-1253" unfinished="${"x".repeat(1024)}">`,
"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);
});
}
});
Loading
Loading