Skip to content
Open
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
63 changes: 60 additions & 3 deletions dist/core/rules/spec-char-escape.js

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

86 changes: 78 additions & 8 deletions src/core/rules/spec-char-escape.ts
Original file line number Diff line number Diff line change
@@ -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)
}
})
},
Expand Down
2 changes: 1 addition & 1 deletion test/cli/formatters/sarif.sarif
Original file line number Diff line number Diff line change
Expand Up @@ -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`<span>`aaa&gt;bbb&lt;ccc`</span>`\n`<span>`Steinway &amp; Sons, Q&amp;A`</span>`\n`<span>`Steinway & Sons, Q&A`</span>`\n```\n\n### The following pattern is considered a rule violation:\n\n```html\n`<span>`aaa>bbb`<ccc</span>`\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`<span>`aaa&gt;bbb&lt;ccc`</span>`\n`<span>`Steinway &amp; Sons, Q&amp;A`</span>`\n`<span>`Steinway & Sons, Q&A`</span>`\n`<span>`&copy; 2026`</span>`\n```\n\n### The following patterns are considered violations\n\n```html\n`<span>`aaa>bbb`<ccc</span>`\n`<span>`&copy 2026`</span>`\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 `&copy;` for © or `&amp;copy` to display the literal text `&copy`."
}
}
],
Expand Down
45 changes: 45 additions & 0 deletions test/rules/spec-char-escape.spec.js
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
const HTMLHint = require('../../dist/htmlhint.js').HTMLHint

// cspell:ignore copyx notit notin
const ruleId = 'spec-char-escape'
const ruleOptions = {}

Expand Down Expand Up @@ -38,4 +39,48 @@ describe(`Rules: ${ruleId}`, () => {
const messages = HTMLHint.verify(code, ruleOptions)
expect(messages.length).toBe(0)
})

it.each(['&copy', '&copyx', '&notit;', '&#169', '&#xA9'])(
'Reports the missing semicolon in %s',
(reference) => {
const messages = HTMLHint.verify(`<p>\n ${reference}</p>`, 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', '&copy;', '&notin;', '&#169;', '&#xA9;'])(
'Leaves %s alone when it has no missing semicolon',
(text) => {
expect(HTMLHint.verify(`<p>${text}</p>`, ruleOptions)).toHaveLength(0)
}
)

it('Ignores ampersands in script text and attributes', () => {
const code =
'<script>const name = "&copy"</script><p title="&copy">Text</p>'
expect(HTMLHint.verify(code, ruleOptions)).toHaveLength(0)
})

it('Checks HTML inside AngularJS script templates', () => {
const code = '<script type="text/ng-template"><p>&copy</p></script>'
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}>&copy</${tagName}>\n<p>&copy</p>`
const messages = HTMLHint.verify(code, ruleOptions)

expect(messages).toHaveLength(1)
expect(messages[0]).toMatchObject({ line: 2, col: 4 })
}
)
})
6 changes: 4 additions & 2 deletions website/src/content/docs/rules/spec-char-escape.mdx
Original file line number Diff line number Diff line change
Expand Up @@ -21,14 +21,16 @@ Level: <Badge text="Error" variant="danger" />
<span>aaa&gt;bbb&lt;ccc</span>
<span>Steinway &amp; Sons, Q&amp;A</span>
<span>Steinway & Sons, Q&A</span>
<span>&copy; 2026</span>
```

### The following pattern is considered a rule violation:
### The following patterns are considered violations

```html
<span>aaa>bbb<ccc</span>
<span>&copy 2026</span>
```

## 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 `&copy;` for © or `&amp;copy` to display the literal text `&copy`.