diff --git a/dist/core/rules/spec-char-escape.js b/dist/core/rules/spec-char-escape.js index 9bb2fedcb..6ec5ea676 100644 --- a/dist/core/rules/spec-char-escape.js +++ b/dist/core/rules/spec-char-escape.js @@ -1,18 +1,75 @@ "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); +function parseEntityNames(table) { + return table.replace(/#.*$/gm, '').trim().split(/\s+/); +} +const legacyNames = parseEntityNames(` +AElig AMP Aacute Acirc Agrave Aring Atilde Auml COPY Ccedil ETH Eacute +Ecirc Egrave Euml GT Iacute Icirc Igrave Iuml LT Ntilde Oacute Ocirc +Ograve Oslash Otilde Ouml QUOT REG THORN Uacute Ucirc Ugrave Uuml Yacute +aacute acirc acute aelig agrave amp aring atilde auml brvbar ccedil cedil +cent copy curren deg divide eacute ecirc egrave eth euml frac12 frac14 # codespell:ignore curren +frac34 gt iacute icirc iexcl igrave iquest iuml laquo lt macr micro middot +nbsp not ntilde oacute ocirc ograve ordf ordm oslash otilde ouml para +plusmn pound quot raquo reg sect shy sup1 sup2 sup3 szlig thorn times +uacute ucirc ugrave uml uuml yacute yen yuml +`); +const longerNames = parseEntityNames(` +centerdot copysr divideontimes gtcc gtcir gtdot gtlPar gtquest gtrapprox +gtrarr gtrdot gtreqless gtreqqless gtrless gtrsim ltcc ltcir ltdot lthree +ltimes ltlarr ltquest ltrPar ltri ltrie ltrif notin notinE notindot # codespell:ignore notin +notinva notinvb notinvc notni notniva notnivb notnivc parallel timesb +timesbar timesd +`); +const legacyPrefix = new RegExp(`^(?:${legacyNames.join('|')})`); +const completeNames = new Set([...legacyNames, ...longerNames]); +const rawTextElement = /^(?:iframe|noembed|noframes|plaintext|script|style|xmp)$/i; +function isUnterminatedReference(reference) { + const terminated = reference.endsWith(';'); + if (reference.startsWith('&#')) { + return !terminated; + } + const name = reference.slice(1, terminated ? -1 : undefined); + return legacyPrefix.test(name) && !(terminated && completeNames.has(name)); +} exports.default = { id: 'spec-char-escape', description: 'Special characters must be escaped.', init(parser, reporter) { + let rawTextTag = ''; + parser.addListener('tagstart', ({ tagName, attrs }) => { + var _a; + if (rawTextTag || !rawTextElement.test(tagName)) { + return; + } + const name = tagName.toLowerCase(); + const type = (_a = attrs.find((attr) => attr.name === 'type')) === null || _a === void 0 ? void 0 : _a.value; + if (name === 'script' && (type === null || type === void 0 ? void 0 : type.includes('text/ng-template'))) { + return; + } + rawTextTag = name; + }); + parser.addListener('tagend', ({ tagName }) => { + if (rawTextTag !== 'plaintext' && rawTextTag === tagName.toLowerCase()) { + rawTextTag = ''; + } + }); parser.addListener('text', (event) => { const raw = event.raw; - const reSpecChar = /([<>])/g; + const reSpecChar = /[<>]|&(?:#[xX][\dA-Fa-f]+|#\d+|[A-Za-z][A-Za-z0-9]*);?/g; let match; while ((match = reSpecChar.exec(raw))) { + let message = `Special characters must be escaped : [ ${match[0]} ].`; + if (match[0].startsWith('&')) { + if (rawTextTag || !isUnterminatedReference(match[0])) { + continue; + } + message = 'Character references must end with a semicolon.'; + } const fixedPos = parser.fixPos(event, match.index); - reporter.error(`Special characters must be escaped : [ ${match[0]} ].`, fixedPos.line, fixedPos.col, this, event.raw); + reporter.error(message, fixedPos.line, fixedPos.col, this, raw); } }); }, }; -//# sourceMappingURL=data:application/json;base64,eyJ2ZXJzaW9uIjozLCJmaWxlIjoic3BlYy1jaGFyLWVzY2FwZS5qcyIsInNvdXJjZVJvb3QiOiIiLCJzb3VyY2VzIjpbIi4uLy4uLy4uL3NyYy9jb3JlL3J1bGVzL3NwZWMtY2hhci1lc2NhcGUudHMiXSwibmFtZXMiOltdLCJtYXBwaW5ncyI6Ijs7QUFFQSxrQkFBZTtJQUNiLEVBQUUsRUFBRSxrQkFBa0I7SUFDdEIsV0FBVyxFQUFFLHFDQUFxQztJQUNsRCxJQUFJLENBQUMsTUFBTSxFQUFFLFFBQVE7UUFDbkIsTUFBTSxDQUFDLFdBQVcsQ0FBQyxNQUFNLEVBQUUsQ0FBQyxLQUFLLEVBQUUsRUFBRTtZQUNuQyxNQU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yxHQUFHLENBQUE7WUFDckIsTUFBTSxVQUFVLEdBQ2QseURBQXlELENBQUE7WUFDM0QsSUFBSSxLQUFLLENBQUE7WUFFVCxPQUFPLENBQUMsS0FBSyxHQUFHLFVBQVUsQ0FBQyxJQUFJLENBQUMsR0FBRyxDQUFDLENBQUMsRUFBRSxDQUFDO2dCQUN0QyxJQUFJLE9BQU8sR0FBRywwQ0FBMEMsS0FBSyxDQUFDLENBQUMsQ0FBQyxLQUFLLENBQUE7Z0JBQ3JFLElBQUksS0FBSyxDQUFDLENBQUMsQ0FBQyxDQUFDLFVBQVUsQ0FBQyxHQUFHLENBQUMsRUFBRSxDQUFDO29CQUM3QixJQUFJLFVBQVUsSUFBSSxDQUFDLHVCQUF1QixDQUFDLEtBQUssQ0FBQyxDQUFDLENBQUMsQ0FBQyxFQUFFLENBQUM7d0JBQ3JELFNBQVE7b0JBQ1YsQ0FBQztvQkFDRCxPQUFPLEdBQUcsaURBQWlELENBQUE7Z0JBQzdELENBQUM7Z0JBQ0QsTUFBTSxRQUFRLEdBQUcsTUFBTSxDQUFDLE1BQU0sQ0FBQyxLQUFLLEVBQUUsS0FBSyxDQUFDLEtBQUssQ0FBQyxDQUFBO2dCQUNsRCxRQUFRLENBQUMsS0FBSyxDQUFDLE9BQU8sRUFBRSxRQUFRLENBQUMsSUFBSSxFQUFFLFFBQVEsQ0FBQyxHQUFHLEVBQUUsSUFBSSxFQUFFLEdBQUcsQ0FBQyxDQUFBO1lBQ2pFLENBQUM7UUFDSCxDQUFDLENBQUMsQ0FBQTtJQUNKLENBQUM7Q0FDTSxDQUFBIn0= \ No newline at end of file diff --git a/src/core/rules/spec-char-escape.ts b/src/core/rules/spec-char-escape.ts index c436af9f8..a1d7537cc 100644 --- a/src/core/rules/spec-char-escape.ts +++ b/src/core/rules/spec-char-escape.ts @@ -1,23 +1,93 @@ import { Rule } from '../types' +function parseEntityNames(table: string): string[] { + // The tables can annotate exact spellings after #. + return table.replace(/#.*$/gm, '').trim().split(/\s+/) +} + +// Name subsets adapted from the WHATWG HTML Standard (CC BY 4.0). +// https://html.spec.whatwg.org/multipage/named-characters.html +// Only these names can be decoded without a semicolon. +// cspell:disable +const legacyNames = parseEntityNames(` +AElig AMP Aacute Acirc Agrave Aring Atilde Auml COPY Ccedil ETH Eacute +Ecirc Egrave Euml GT Iacute Icirc Igrave Iuml LT Ntilde Oacute Ocirc +Ograve Oslash Otilde Ouml QUOT REG THORN Uacute Ucirc Ugrave Uuml Yacute +aacute acirc acute aelig agrave amp aring atilde auml brvbar ccedil cedil +cent copy curren deg divide eacute ecirc egrave eth euml frac12 frac14 # codespell:ignore curren +frac34 gt iacute icirc iexcl igrave iquest iuml laquo lt macr micro middot +nbsp not ntilde oacute ocirc ograve ordf ordm oslash otilde ouml para +plusmn pound quot raquo reg sect shy sup1 sup2 sup3 szlig thorn times +uacute ucirc ugrave uml uuml yacute yen yuml +`) + +// Only complete names that start with a legacy name can override its match. +const longerNames = parseEntityNames(` +centerdot copysr divideontimes gtcc gtcir gtdot gtlPar gtquest gtrapprox +gtrarr gtrdot gtreqless gtreqqless gtrless gtrsim ltcc ltcir ltdot lthree +ltimes ltlarr ltquest ltrPar ltri ltrie ltrif notin notinE notindot # codespell:ignore notin +notinva notinvb notinvc notni notniva notnivb notnivc parallel timesb +timesbar timesd +`) +// cspell:enable + +const legacyPrefix = new RegExp(`^(?:${legacyNames.join('|')})`) +const completeNames = new Set([...legacyNames, ...longerNames]) +const rawTextElement = + /^(?:iframe|noembed|noframes|plaintext|script|style|xmp)$/i + +function isUnterminatedReference(reference: string): boolean { + const terminated = reference.endsWith(';') + if (reference.startsWith('&#')) { + return !terminated + } + + // A complete longer name takes precedence over its legacy prefix. + const name = reference.slice(1, terminated ? -1 : undefined) + return legacyPrefix.test(name) && !(terminated && completeNames.has(name)) +} + export default { id: 'spec-char-escape', description: 'Special characters must be escaped.', init(parser, reporter) { + let rawTextTag = '' + parser.addListener('tagstart', ({ tagName, attrs }) => { + if (rawTextTag || !rawTextElement.test(tagName)) { + return + } + + const name = tagName.toLowerCase() + const type = attrs.find((attr) => attr.name === 'type')?.value + // HTMLHint parses AngularJS script templates as HTML. + if (name === 'script' && type?.includes('text/ng-template')) { + return + } + + rawTextTag = name + }) + parser.addListener('tagend', ({ tagName }) => { + if (rawTextTag !== 'plaintext' && rawTextTag === tagName.toLowerCase()) { + rawTextTag = '' + } + }) + parser.addListener('text', (event) => { const raw = event.raw - const reSpecChar = /([<>])/g + const reSpecChar = + /[<>]|&(?:#[xX][\dA-Fa-f]+|#\d+|[A-Za-z][A-Za-z0-9]*);?/g let match while ((match = reSpecChar.exec(raw))) { + let message = `Special characters must be escaped : [ ${match[0]} ].` + if (match[0].startsWith('&')) { + if (rawTextTag || !isUnterminatedReference(match[0])) { + continue + } + message = 'Character references must end with a semicolon.' + } const fixedPos = parser.fixPos(event, match.index) - reporter.error( - `Special characters must be escaped : [ ${match[0]} ].`, - fixedPos.line, - fixedPos.col, - this, - event.raw - ) + reporter.error(message, fixedPos.line, fixedPos.col, this, raw) } }) }, diff --git a/test/cli/formatters/sarif.sarif b/test/cli/formatters/sarif.sarif index 754b90123..78293bff9 100644 --- a/test/cli/formatters/sarif.sarif +++ b/test/cli/formatters/sarif.sarif @@ -48,7 +48,7 @@ "helpUri": "https://htmlhint.com/rules/spec-char-escape", "help": { "text": "Special characters must be escaped.", - "markdown": "\nSpecial characters must be escaped.\n\nLevel: Error\n\n## Config value\n\n- `true`: enable rule\n- `false`: disable rule\n\n### The following patterns are **not** considered violations\n\n```html\n``aaa>bbb<ccc``\n``Steinway & Sons, Q&A``\n``Steinway & Sons, Q&A``\n```\n\n### The following pattern is considered a rule violation:\n\n```html\n``aaa>bbb``\n```\n\n## Why this rule is important\n\nSpecial HTML characters like `<`, `>`, and `&` must be escaped to prevent them from being interpreted as HTML tags or entities. This avoids rendering issues and potential cross-site scripting (XSS) vulnerabilities." + "markdown": "\nSpecial characters must be escaped.\n\nLevel: Error\n\n## Config value\n\n- `true`: enable rule\n- `false`: disable rule\n\n### The following patterns are **not** considered violations\n\n```html\n``aaa>bbb<ccc``\n``Steinway & Sons, Q&A``\n``Steinway & Sons, Q&A``\n``© 2026``\n```\n\n### The following patterns are considered violations\n\n```html\n``aaa>bbb``\n``© 2026``\n```\n\n## Why this rule is important\n\nAngle brackets in plain text can be read as HTML markup. Browsers can also decode some [character references](https://html.spec.whatwg.org/multipage/parsing.html#character-reference-state) without a semicolon. Write `©` for © or `&copy` to display the literal text `©`." } } ], diff --git a/test/rules/spec-char-escape.spec.js b/test/rules/spec-char-escape.spec.js index cd8c5f674..87da4d2c9 100644 --- a/test/rules/spec-char-escape.spec.js +++ b/test/rules/spec-char-escape.spec.js @@ -1,5 +1,6 @@ const HTMLHint = require('../../dist/htmlhint.js').HTMLHint +// cspell:ignore copyx notit notin const ruleId = 'spec-char-escape' const ruleOptions = {} @@ -38,4 +39,48 @@ describe(`Rules: ${ruleId}`, () => { const messages = HTMLHint.verify(code, ruleOptions) expect(messages.length).toBe(0) }) + + it.each(['©', '©x', '¬it;', '©', '©'])( + 'Reports the missing semicolon in %s', + (reference) => { + const messages = HTMLHint.verify(`

\n ${reference}

`, ruleOptions) + + expect(messages).toHaveLength(1) + expect(messages[0]).toMatchObject({ + rule: { id: ruleId }, + line: 2, + col: 3, + message: 'Character references must end with a semicolon.', + }) + } + ) + + it.each(['&a', '©', '∉', '©', '©'])( + 'Leaves %s alone when it has no missing semicolon', + (text) => { + expect(HTMLHint.verify(`

${text}

`, ruleOptions)).toHaveLength(0) + } + ) + + it('Ignores ampersands in script text and attributes', () => { + const code = + '

Text

' + expect(HTMLHint.verify(code, ruleOptions)).toHaveLength(0) + }) + + it('Checks HTML inside AngularJS script templates', () => { + const code = '' + expect(HTMLHint.verify(code, ruleOptions)).toHaveLength(1) + }) + + it.each(['SCRIPT', 'Style', 'iframe', 'xmp'])( + 'Reports the next text reference after leaving %s', + (tagName) => { + const code = `<${tagName}>©\n

©

` + const messages = HTMLHint.verify(code, ruleOptions) + + expect(messages).toHaveLength(1) + expect(messages[0]).toMatchObject({ line: 2, col: 4 }) + } + ) }) diff --git a/website/src/content/docs/rules/spec-char-escape.mdx b/website/src/content/docs/rules/spec-char-escape.mdx index 4ff629240..72990e681 100644 --- a/website/src/content/docs/rules/spec-char-escape.mdx +++ b/website/src/content/docs/rules/spec-char-escape.mdx @@ -21,14 +21,16 @@ Level: aaa>bbb<ccc Steinway & Sons, Q&A Steinway & Sons, Q&A +© 2026 ``` -### The following pattern is considered a rule violation: +### The following patterns are considered violations ```html aaa>bbb +© 2026 ``` ## Why this rule is important -Special HTML characters like `<`, `>`, and `&` must be escaped to prevent them from being interpreted as HTML tags or entities. This avoids rendering issues and potential cross-site scripting (XSS) vulnerabilities. +Angle brackets in plain text can be read as HTML markup. Browsers can also decode some [character references](https://html.spec.whatwg.org/multipage/parsing.html#character-reference-state) without a semicolon. Write `©` for © or `&copy` to display the literal text `©`.