refactor: detect external CSS references with the CSS Syntax tokenizer

Replace the regex/escape-normalizer with @csstools/css-tokenizer (already
present transitively). Tokenizing resolves comments, hex escapes, and line
continuations into the real value before scanning, so obfuscated forms (a
scheme split by a line continuation or hex escape) cannot slip past. Scan
url-tokens and string-tokens to cover url(), quoted @import, and string-form
image functions. Add regression tests for the bypasses.
This commit is contained in:
Buco7854 committed 2026-06-23 19:25:18 +00:00
1 parent 3685e0c476
commit 96021b7479
4 files changed
+26 -18

No files matched your search

+7 -16
View File
@@ -1,23 +1,14 @@
// Normalize the CSS the way a browser does before matching, so obfuscated forms
// (inline comments, CSS escapes like "\75 rl(") can't hide an external reference.
const decodeForScan = (css: string): string =>
css.replace(/\/\*[\s\S]*?\*\//g, "").replace(/\\([0-9a-fA-F]{1,6})\s?|\\([\s\S])/g, (_match, hex: string, char: string) => {
if (!hex) {
return char;
}
const codePoint = parseInt(hex, 16);
return codePoint > 0 && codePoint <= 0x10ffff ? String.fromCodePoint(codePoint) : "�";
});
import { isTokenString, isTokenURL, tokenize } from "@csstools/css-tokenizer";
// An external reference is @import, or a resource function (url, image-set,
// image, cross-fade) whose target starts with an http(s) scheme or is
// protocol-relative. Anchoring on the start of the target keeps data: and
// relative URLs allowed, including data: SVG that embeds the SVG namespace URL.
const EXTERNAL_REFERENCE = /(?:@import\b|(?:url|image-set|-webkit-image-set|image|cross-fade|-webkit-cross-fade)\s*\(\s*['"]?\s*(?:https?:|\/\/))/i;
// Absolute http(s) or protocol-relative target; data: and relative URLs stay allowed.
const EXTERNAL_TARGET = /^\s*(?:https?:|\/\/)/i;
// Tokenizing resolves comments, escapes, and line continuations so obfuscated
// targets can't hide. url-tokens cover url(); string-tokens cover @import and image-set().
export const cssReferencesExternalResource = (css?: string | null): boolean => {
if (typeof css !== "string" || css === "") {
return false;
}
return EXTERNAL_REFERENCE.test(decodeForScan(css));
return tokenize({ css }).some((token) => (isTokenURL(token) || isTokenString(token)) && EXTERNAL_TARGET.test(token[4].value));
};