fix bg image css processing (#1044)

This commit is contained in:
Mike Sawka 2024-10-16 09:57:27 -07:00 committed by GitHub
parent 0b3888d900
commit fe70efab8d
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194

View File

@ -159,29 +159,46 @@ function processBackgroundUrls(cssText: string): string {
if (cssText.endsWith(";")) { if (cssText.endsWith(";")) {
cssText = cssText.slice(0, -1); cssText = cssText.slice(0, -1);
} }
const attrRe = /^background(-image):\s*/; const attrRe = /^background(-image)?\s*:\s*/i;
cssText = cssText.replace(attrRe, ""); cssText = cssText.replace(attrRe, "");
const ast = csstree.parse("background: " + cssText, { const ast = csstree.parse("background: " + cssText, {
context: "declaration", context: "declaration",
}); });
let hasJSUrl = false; let hasUnsafeUrl = false;
csstree.walk(ast, { csstree.walk(ast, {
visit: "Url", visit: "Url",
enter(node) { enter(node) {
const originalUrl = node.value.trim(); const originalUrl = node.value.trim();
if (originalUrl.startsWith("javascript:")) { if (
hasJSUrl = true; originalUrl.startsWith("http:") ||
originalUrl.startsWith("https:") ||
originalUrl.startsWith("data:")
) {
return; return;
} }
if (originalUrl.startsWith("data:")) { // allow file:/// urls (if they are absolute)
if (originalUrl.startsWith("file://")) {
const path = originalUrl.slice(7);
if (!path.startsWith("/")) {
console.log(`Invalid background, contains a non-absolute file URL: ${originalUrl}`);
hasUnsafeUrl = true;
return;
}
const newUrl = encodeFileURL(path);
node.value = newUrl;
return; return;
} }
const newUrl = encodeFileURL(originalUrl); // allow absolute paths
node.value = newUrl; if (originalUrl.startsWith("/") || originalUrl.startsWith("~/")) {
const newUrl = encodeFileURL(originalUrl);
node.value = newUrl;
return;
}
hasUnsafeUrl = true;
console.log(`Invalid background, contains an unsafe URL scheme: ${originalUrl}`);
}, },
}); });
if (hasJSUrl) { if (hasUnsafeUrl) {
console.log("invalid background, contains a 'javascript' protocol url which is not allowed");
return null; return null;
} }
const rtnStyle = csstree.generate(ast); const rtnStyle = csstree.generate(ast);