fix: keep a decoded character reference from forming a new one (#4111)

Since numeric references are decoded into the text token, a decoded "&", or
a decoded character next to a literal "&", can spell a new reference that the
no-encode escaper leaves alone and the browser decodes again.
"&" rendered as "&" and displayed "&", and "©"
displayed "(c)". Escape "&" in text that contains a numeric reference, both
the decoded ones and the literal ones that do not already start a reference.
This commit is contained in:
KBS
2026-10-06 08:55:12 -06:00
committed by GitHub
parent 0db74cb019
commit 6bbac0cdb7
4 changed files with 19 additions and 4 deletions
+11 -3
View File
@@ -32,12 +32,20 @@ export function escapeHtmlEntities(html: string, encode?: boolean) {
* replacement character.
*/
export function decodeNumericCharacterReferences(text: string) {
return text.replace(other.numericCharacterReference, (_, dec: string, hex: string) => {
const code = dec === undefined ? Number.parseInt(hex, 16) : Number.parseInt(dec, 10);
if (!other.numericCharacterReference.test(text)) {
return text;
}
// A decoded character must not join its neighbours into a new reference,
// so every `&` that is not already one is escaped here.
return text.replace(other.numericCharacterReferenceOrAmpersand, (ref: string, dec?: string, hex?: string) => {
if (dec === undefined && hex === undefined) {
return '&';
}
const code = dec === undefined ? Number.parseInt(hex!, 16) : Number.parseInt(dec, 10);
if (code === 0 || code > 0x10ffff || (code >= 0xd800 && code <= 0xdfff)) {
return '�';
}
return String.fromCodePoint(code);
return code === 38 ? '&amp;' : String.fromCodePoint(code);
});
}
+2 -1
View File
@@ -79,7 +79,8 @@ export const other = {
endAngleBracket: />$/,
pedanticHrefTitle: /^([^'"]*[^\s])\s+(['"])(.*)\2/,
unicodeAlphaNumeric: /[\p{L}\p{N}]/u,
numericCharacterReference: /&#(?:(\d{1,7})|[Xx]([A-Fa-f0-9]{1,6}));/g,
numericCharacterReference: /&#(?:(\d{1,7})|[Xx]([A-Fa-f0-9]{1,6}));/,
numericCharacterReferenceOrAmpersand: /&#(?:(\d{1,7})|[Xx]([A-Fa-f0-9]{1,6}));|&(?!(#\d{1,7}|#[Xx][a-fA-F0-9]{1,6}|\w+);)/g,
escapeTest: /[&<>"']/,
escapeReplace: /[&<>"']/g,
escapeTestNoEncode: /[<>"']|&(?!(#\d{1,7}|#[Xx][a-fA-F0-9]{1,6}|\w+);)/,
@@ -3,3 +3,5 @@
<p>�</p>
<p>&amp;#abcdef0;</p>
<p><code>&amp;#35;</code></p>
<p>&amp;amp; &amp;lt;</p>
<p>&amp;#35; &amp;copy; &amp;amp;</p>
@@ -10,3 +10,7 @@ renderExact: true
&#abcdef0;
`&#35;`
&#38;amp; &#x26;lt;
&&#35;35; &co&#112;y; &amp&#59;