Skip to content

Open source website builder and Webflow alternative. Webstudio is an advanced visual builder that connects to any headless CMS, supports all CSS properties, and can be hosted anywhere, including with us.

fix: Validate malformed CSS variable values (#5787)

Oleg Isonen95dc7f0a75cd
diff --git a/apps/builder/app/builder/features/style-panel/shared/css-value-input/parse-intermediate-or-invalid-value.test.ts b/apps/builder/app/builder/features/style-panel/shared/css-value-input/parse-intermediate-or-invalid-value.test.ts
index a30fa5c064..dd92d141d5 100644
--- a/apps/builder/app/builder/features/style-panel/shared/css-value-input/parse-intermediate-or-invalid-value.test.ts
+++ b/apps/builder/app/builder/features/style-panel/shared/css-value-input/parse-intermediate-or-invalid-value.test.ts
@@ -847,6 +847,18 @@ test("parse css variables as unparsed", () => {
});
});
+test("does not coerce invalid css variable values", () => {
+ expect(
+ parseIntermediateOrInvalidValue("--size", {
+ type: "intermediate",
+ value: "#sd'",
+ })
+ ).toEqual({
+ type: "invalid",
+ value: "#sd'",
+ });
+});
+
test("parse z-index", () => {
expect(
parseIntermediateOrInvalidValue("z-index", {
diff --git a/apps/builder/app/builder/features/style-panel/shared/css-value-input/parse-intermediate-or-invalid-value.ts b/apps/builder/app/builder/features/style-panel/shared/css-value-input/parse-intermediate-or-invalid-value.ts
index 6c4247bfed..e0f1817562 100644
--- a/apps/builder/app/builder/features/style-panel/shared/css-value-input/parse-intermediate-or-invalid-value.ts
+++ b/apps/builder/app/builder/features/style-panel/shared/css-value-input/parse-intermediate-or-invalid-value.ts
@@ -104,6 +104,13 @@ export const parseIntermediateOrInvalidValue = (
return styleInput;
}
+ if (property.startsWith("--")) {
+ return {
+ type: "invalid",
+ value: originalValue ?? value,
+ };
+ }
+
if ("unit" in styleValue && styleValue.unit === "number") {
// when unit is number some properties supports only integer
// for example z-index
diff --git a/apps/builder/app/builder/shared/css-editor/parse-style-input.test.ts b/apps/builder/app/builder/shared/css-editor/parse-style-input.test.ts
index bec943d527..076019d446 100644
--- a/apps/builder/app/builder/shared/css-editor/parse-style-input.test.ts
+++ b/apps/builder/app/builder/shared/css-editor/parse-style-input.test.ts
@@ -169,6 +169,11 @@ describe("parseStyleInput", () => {
);
});
+ test("does not parse malformed custom property values", () => {
+ const { styleMap: result } = parseStyleInput("--test: #sd'", new Map());
+ expect(result).toEqual(new Map());
+ });
+
test("handles malformed style block", () => {
const { styleMap: result } = parseStyleInput(
"color: red; invalid;",
diff --git a/packages/css-data/src/parse-css-value.test.ts b/packages/css-data/src/parse-css-value.test.ts
index 3b875822b1..3470214b14 100644
--- a/packages/css-data/src/parse-css-value.test.ts
+++ b/packages/css-data/src/parse-css-value.test.ts
@@ -1527,10 +1527,34 @@ test("parse perspective-origin", () => {
});
describe("isValidDeclaration", () => {
- test("custom properties always accept any value", () => {
+ test("custom properties accept valid token streams", () => {
expect(isValidDeclaration("--my-color", "anything")).toBe(true);
expect(isValidDeclaration("--x", "rgb(0 0 0)")).toBe(true);
expect(isValidDeclaration("--x", "not-valid-garbage")).toBe(true);
+ expect(
+ isValidDeclaration("--x", "url(https://example.com/image.png)")
+ ).toBe(true);
+ expect(isValidDeclaration("--x", "calc(100% - 1rem)")).toBe(true);
+ });
+
+ test("custom properties reject malformed token streams", () => {
+ for (const value of [
+ "#sd'",
+ '#sd"',
+ "abc(",
+ "abc[",
+ "abc{",
+ "abc/*",
+ "abc\\",
+ "url(foo",
+ "var(--x",
+ ]) {
+ expect(isValidDeclaration("--x", value), value).toBe(false);
+ expect(parseCssValue("--x", value)).toEqual({
+ type: "invalid",
+ value,
+ });
+ }
});
test("var() is valid on any property, detected via AST", () => {
diff --git a/packages/css-data/src/parse-css-value.ts b/packages/css-data/src/parse-css-value.ts
index 86ffa80058..43af4468b0 100644
--- a/packages/css-data/src/parse-css-value.ts
+++ b/packages/css-data/src/parse-css-value.ts
@@ -6,6 +6,8 @@ import {
lexer,
List,
parse,
+ tokenize,
+ tokenTypes,
walk,
} from "css-tree";
import warnOnce from "warn-once";
@@ -140,15 +142,119 @@ const getSyntaxMatchErrorSyntax = (error: Error | null | undefined) => {
}
};
+const matchingOpenToken = new Map([
+ [tokenTypes.RightSquareBracket, tokenTypes.LeftSquareBracket],
+ [tokenTypes.RightCurlyBracket, tokenTypes.LeftCurlyBracket],
+]);
+
+const endsWithUnescaped = (value: string, char: string) => {
+ if (value.endsWith(char) === false) {
+ return false;
+ }
+ let backslashes = 0;
+ for (let index = value.length - 2; index >= 0; index -= 1) {
+ if (value[index] !== "\\") {
+ break;
+ }
+ backslashes += 1;
+ }
+ return backslashes % 2 === 0;
+};
+
+export const isValidCustomPropertyValue = (value: string): boolean => {
+ if (endsWithUnescaped(value, "\\")) {
+ return false;
+ }
+
+ const blockStack: number[] = [];
+ const tokenizeValue = tokenize as unknown as (
+ source: string,
+ onToken: (type: number, start: number, end: number) => void
+ ) => void;
+
+ tokenizeValue(value, (type, start, end) => {
+ const tokenValue = value.slice(start, end);
+
+ if (type === tokenTypes.BadString || type === tokenTypes.BadUrl) {
+ blockStack.push(Number.NaN);
+ return;
+ }
+
+ if (type === tokenTypes.String) {
+ const quote = tokenValue[0];
+ if (
+ quote !== undefined &&
+ (quote === `"` || quote === `'`) &&
+ (tokenValue.length < 2 ||
+ endsWithUnescaped(tokenValue, quote) === false)
+ ) {
+ blockStack.push(Number.NaN);
+ }
+ return;
+ }
+
+ if (type === tokenTypes.Url) {
+ if (endsWithUnescaped(tokenValue, ")") === false) {
+ blockStack.push(Number.NaN);
+ }
+ return;
+ }
+
+ if (type === tokenTypes.Comment) {
+ if (tokenValue.endsWith("*/") === false) {
+ blockStack.push(Number.NaN);
+ }
+ return;
+ }
+
+ if (
+ type === tokenTypes.Function ||
+ type === tokenTypes.LeftParenthesis ||
+ type === tokenTypes.LeftSquareBracket ||
+ type === tokenTypes.LeftCurlyBracket
+ ) {
+ blockStack.push(type);
+ return;
+ }
+
+ if (type === tokenTypes.RightParenthesis) {
+ const open = blockStack.at(-1);
+ if (open !== tokenTypes.LeftParenthesis && open !== tokenTypes.Function) {
+ blockStack.push(Number.NaN);
+ return;
+ }
+ blockStack.pop();
+ return;
+ }
+
+ const expectedOpen = matchingOpenToken.get(type);
+ if (expectedOpen !== undefined) {
+ if (blockStack.at(-1) !== expectedOpen) {
+ blockStack.push(Number.NaN);
+ return;
+ }
+ blockStack.pop();
+ return;
+ }
+
+ if (type === tokenTypes.Semicolon && blockStack.length === 0) {
+ blockStack.push(Number.NaN);
+ }
+ });
+
+ return blockStack.length === 0;
+};
+
// Because csstree parser has bugs we use CSSStyleValue to validate css properties if available
// and fall back to csstree.
export const isValidDeclaration = (
property: CssProperty,
value: string
): boolean => {
- // Custom properties accept any value.
+ // Custom properties accept any valid declaration value token stream, but
+ // malformed strings, URLs, comments, or blocks can invalidate the whole rule.
if (property.startsWith("--")) {
- return true;
+ return isValidCustomPropertyValue(value);
}
// Parse once upfront for structural inspection. cssTryParseValue may return
diff --git a/packages/css-data/src/parse-css.test.ts b/packages/css-data/src/parse-css.test.ts
index c5b3dcae1d..09229c5caf 100644
--- a/packages/css-data/src/parse-css.test.ts
+++ b/packages/css-data/src/parse-css.test.ts
@@ -486,6 +486,22 @@ describe("Parse CSS", () => {
]);
});
+ test("drops malformed custom property values", () => {
+ const result = parseCss(
+ `
+ a {
+ --my-property: #sd';
+ color: red;
+ }
+ `,
+ new Map()
+ );
+ expect(result.styles).toEqual([]);
+ expect(result.errors).toEqual([
+ `"--my-property" was not applied because its value is invalid`,
+ ]);
+ });
+
test("parse empty custom property", () => {
expect(parseCss(`a { --my-property: ; }`, new Map()).styles).toEqual([
{
diff --git a/packages/css-data/src/parse-css.ts b/packages/css-data/src/parse-css.ts
index dffa5345dc..410f10e944 100644
--- a/packages/css-data/src/parse-css.ts
+++ b/packages/css-data/src/parse-css.ts
@@ -8,6 +8,7 @@ import type {
import {
parseCssValue as parseCssValueLonghand,
parseCssVar,
+ isValidCustomPropertyValue,
} from "./parse-css-value";
import { expandShorthands } from "./shorthands";
import { shorthandProperties } from "./__generated__/shorthand-properties";
@@ -85,6 +86,9 @@ export const camelCaseProperty = (
};
const parseCssValue = (property: CssProperty, value: string) => {
+ if (property.startsWith("--")) {
+ return new Map([[property, parseCssValueLonghand(property, value)]]);
+ }
const expanded = new Map(expandShorthands([[property, value]]));
const final = new Map<CssProperty, StyleValue>();
for (const [property, value] of expanded) {
@@ -628,13 +632,35 @@ const substituteVarsInShorthand = (
const cssTreeTryParse = (input: string) => {
try {
- const ast = csstree.parse(input);
+ const ast = csstree.parse(input, { positions: true });
return ast;
} catch {
return;
}
};
+const getRawDeclarationValue = (
+ css: string,
+ declaration: csstree.Declaration
+) => {
+ const loc = declaration.value.loc;
+ if (loc === null) {
+ return;
+ }
+ return css.slice(loc.start.offset, loc.end.offset).trim();
+};
+
+const normalizeCustomPropertyValue = (value: string) => {
+ if (value === "") {
+ return value;
+ }
+ try {
+ return csstree.generate(csstree.parse(value, { context: "value" }));
+ } catch {
+ return value;
+ }
+};
+
type Selector = {
name: string;
state?: string;
@@ -665,7 +691,10 @@ export const extractCssCustomProperties = (
const decl = node as csstree.Declaration;
const prop = normalizeProperty(decl.property);
if (prop.startsWith("--")) {
- map.set(prop, csstree.generate(decl.value));
+ const value = getRawDeclarationValue(css, decl);
+ if (value !== undefined && isValidCustomPropertyValue(value)) {
+ map.set(prop, normalizeCustomPropertyValue(value));
+ }
}
},
});
@@ -701,7 +730,10 @@ export const parseCss = (
const decl = node as csstree.Declaration;
const prop = normalizeProperty(decl.property);
if (prop.startsWith("--")) {
- customProperties.set(prop, csstree.generate(decl.value));
+ const value = getRawDeclarationValue(css, decl);
+ if (value !== undefined && isValidCustomPropertyValue(value)) {
+ customProperties.set(prop, normalizeCustomPropertyValue(value));
+ }
}
},
});
@@ -862,8 +894,14 @@ export const parseCss = (
}
}
- const stringValue = csstree.generate(node.value);
const property = normalizeProperty(node.property);
+ const rawValue = getRawDeclarationValue(css, node);
+ const stringValue =
+ property.startsWith("--") && rawValue !== undefined
+ ? isValidCustomPropertyValue(rawValue)
+ ? normalizeCustomPropertyValue(rawValue)
+ : rawValue
+ : csstree.generate(node.value).trim();
let parsedCss: Map<CssProperty, StyleValue>;
if (shorthandSet.has(property)) {
@@ -887,6 +925,16 @@ export const parseCss = (
parsedCss = parseCssValue(property, stringValue);
}
+ if (
+ property.startsWith("--") &&
+ [...parsedCss.values()].some((value) => value.type === "invalid")
+ ) {
+ errors.push(
+ `"${property}" was not applied because its value is invalid`
+ );
+ return;
+ }
+
for (const { name: selector, state } of selectors) {
for (const [prop, value] of parsedCss) {
const normalizedProperty = normalizeProperty(prop);