Use recursive stylesheet sanitation

This commit is contained in:
Cohee 2024-05-27 14:26:59 +03:00
parent 99e09f0b91
commit 62a1919402

View File

@ -465,18 +465,7 @@ export function decodeStyleTags(text) {
const styleDecodeRegex = /<custom-style>(.+?)<\/custom-style>/gms; const styleDecodeRegex = /<custom-style>(.+?)<\/custom-style>/gms;
const mediaAllowed = isExternalMediaAllowed(); const mediaAllowed = isExternalMediaAllowed();
return text.replaceAll(styleDecodeRegex, (_, style) => { function sanitizeRule(rule) {
try {
let styleCleaned = unescape(style).replaceAll(/<br\/>/g, '');
const ast = css.parse(styleCleaned);
const rules = ast?.stylesheet?.rules;
if (rules) {
for (const rule of rules) {
if (rule.type === 'import') {
rules.splice(rules.indexOf(rule), 1);
}
if (rule.type === 'rule') {
if (rule.selectors) { if (rule.selectors) {
for (let i = 0; i < rule.selectors.length; i++) { for (let i = 0; i < rule.selectors.length; i++) {
let selector = rule.selectors[i]; let selector = rule.selectors[i];
@ -500,7 +489,28 @@ export function decodeStyleTags(text) {
} }
} }
} }
function sanitizeRuleSet(ruleSet) {
if (ruleSet.type === 'rule') {
sanitizeRule(ruleSet);
} }
if (Array.isArray(ruleSet.rules)) {
ruleSet.rules = ruleSet.rules.filter(rule => rule.type !== 'import');
for (const mediaRule of ruleSet.rules) {
sanitizeRuleSet(mediaRule);
}
}
}
return text.replaceAll(styleDecodeRegex, (_, style) => {
try {
let styleCleaned = unescape(style).replaceAll(/<br\/>/g, '');
const ast = css.parse(styleCleaned);
const sheet = ast?.stylesheet;
if (sheet) {
sanitizeRuleSet(ast.stylesheet);
} }
return `<style>${css.stringify(ast)}</style>`; return `<style>${css.stringify(ast)}</style>`;
} catch (error) { } catch (error) {