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
11 changes: 9 additions & 2 deletions src/compat/selectorSafety.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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();
Expand Down
9 changes: 9 additions & 0 deletions tests/unit/selector.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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'],
Expand All @@ -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);
});
Expand Down