diff --git a/src/compat/selectorSafety.ts b/src/compat/selectorSafety.ts index acc059f..28bb179 100644 --- a/src/compat/selectorSafety.ts +++ b/src/compat/selectorSafety.ts @@ -56,15 +56,22 @@ export function checkSelectorSafety(input: string): SelectorCheck { reason: 'Selector contains characters that are not allowed (for example \\ { } ; < @ /).', }; } + // A quoted attribute value is data: a ":" or bracket inside it is not part of + // the selector ([class*="md:hidden"] has no :hidden pseudo-class). Blank the + // values out before the bracket and pseudo-class checks. Backslashes are not + // allowed, so a quote cannot be escaped and any quote left over is unclosed. + const unquoted = selector.replace(/"[^"]*"|'[^']*'/g, 'q'); + if (/["']/.test(unquoted)) return { ok: false, reason: 'Selector has an unterminated quote.' }; + let balance = 0; - for (const ch of selector) { + for (const ch of unquoted) { if (ch === '(' || ch === '[') balance++; if (ch === ')' || ch === ']') balance--; if (balance < 0) return { ok: false, reason: 'Selector has unbalanced brackets.' }; } if (balance !== 0) return { ok: false, reason: 'Selector has unbalanced brackets.' }; - const pseudoMatches = selector.match(/::?[a-zA-Z-]+/g) ?? []; + const pseudoMatches = unquoted.match(/::?[a-zA-Z-]+/g) ?? []; for (const raw of pseudoMatches) { if (raw.startsWith('::')) return { ok: false, reason: 'Pseudo-elements are not allowed.' }; const name = raw.slice(1).toLowerCase(); diff --git a/tests/unit/selector.test.ts b/tests/unit/selector.test.ts index 769d287..5821081 100644 --- a/tests/unit/selector.test.ts +++ b/tests/unit/selector.test.ts @@ -59,6 +59,12 @@ describe('checkSelectorSafety', () => { '.a, .b', '.wall:not(.x)', '[data-x="a b"]', + // Quoted attribute values are data: a colon or bracket in them is not a + // pseudo-class or a bracket of the selector (Tailwind classes like md:hidden). + 'div[class*="md:hidden"]', + '[data-state="modal:open"]', + "[title='Disable adblock :(']", + '[data-x="a[b"]', ])('accepts %s', (sel) => expect(checkSelectorSafety(sel)).toEqual({ ok: true })); it.each([ ['', 'empty'], @@ -75,6 +81,9 @@ describe('checkSelectorSafety', () => { ['.a[', 'unbalanced'], ['x'.repeat(201), 'too long'], ['.a\\:b', 'backslash'], + ['[data-x="a:b"]:hover', 'pseudo-class after a quoted value'], + ['[data-x="a"]::before', 'pseudo-element after a quoted value'], + ['[data-x="a].b', 'unterminated quote'], ])('rejects %s (%s)', (sel) => { expect(checkSelectorSafety(sel).ok).toBe(false); });