Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 5 additions & 0 deletions .changeset/mermaid-export-escape.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
"mermaid-export": patch
---

Escape `theme` and `backgroundColor` before they go into the render page, reject unknown themes, and document that diagrams and options must be trusted.
8 changes: 8 additions & 0 deletions packages/mermaid-export/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -133,6 +133,14 @@ Generic export function that supports all formats.

Close the shared browser instance. Call this when done with all exports.

## Security

Only render diagrams you trust, and only pass trusted option values. The diagram runs in headless Chromium with Mermaid in `securityLevel: 'loose'`, which allows HTML labels and click handlers, and the page can reach the network. An untrusted diagram can make requests from your machine and put script into the SVG you get back. Do not embed that SVG in a page without sanitizing it.

`theme` must be one of `default`, `forest`, `dark`, `neutral`, `base`. Any other value throws. `backgroundColor` is escaped before it goes into the page's CSS.

Chromium is launched with `--no-sandbox`. That flag is needed when running as root in a container, but it turns off a layer of browser isolation, so do not run untrusted diagrams this way.

## Supported Diagram Types

All Mermaid diagram types are supported:
Expand Down
72 changes: 72 additions & 0 deletions packages/mermaid-export/src/html.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,72 @@
import { describe, it, expect } from 'vitest';
import { generateHtml, validateTheme, escapeCss, escapeJsString } from './html.js';

describe('validateTheme', () => {
it('accepts the supported themes', () => {
for (const t of ['default', 'forest', 'dark', 'neutral', 'base']) {
expect(() => validateTheme(t)).not.toThrow();
}
});

it('rejects an unknown theme', () => {
expect(() => validateTheme("x'});window.pwned=1;//")).toThrow(/Unknown theme/);
expect(() => validateTheme(undefined)).toThrow(/Unknown theme/);
});
});

describe('escapeJsString', () => {
it('keeps a quote breakout inside the string', () => {
const out = escapeJsString("x'});window.pwned=1;//");
expect(out).toBe(JSON.stringify("x'});window.pwned=1;//"));
expect(() => new Function(`return ${out}`)()).not.toThrow();
expect(new Function(`return ${out}`)()).toBe("x'});window.pwned=1;//");
});

it('does not let a value close the script tag', () => {
expect(escapeJsString('</script><script>alert(1)')).not.toContain('</script');
});
});

describe('escapeCss', () => {
it('leaves normal colors alone', () => {
expect(escapeCss('transparent')).toBe('transparent');
expect(escapeCss('#ff00aa')).toBe('#ff00aa');
expect(escapeCss('rgb(1, 2, 3)')).toBe('rgb(1, 2, 3)');
});

it('keeps the modern rgb syntax valid', () => {
expect(escapeCss('rgb(0 0 0 / 50%)')).toBe('rgb(0 0 0 / 50%)');
});

it('still escapes a comment opener', () => {
expect(escapeCss('red/*x')).toBe('red\\2f \\2a x');
});

it('escapes characters that end a declaration or the style tag', () => {
const out = escapeCss('red;} </style><script>alert(1)</script>');
expect(out).not.toMatch(/[;{}<>]/);
});
});

describe('generateHtml', () => {
it('does not put raw option text into the page', () => {
const html = generateHtml(
'graph TD; A-->B',
"x'});window.pwned=1;//",
'red;} </style><script>window.pwned=1</script>'
);
expect(html).not.toContain("theme: 'x'");
expect(html).toContain('theme: "x\'});window.pwned=1;//"');
expect(html).not.toContain('</style><script>window.pwned');
expect(html.match(/<\/script>/g)).toHaveLength(1);
});
});

describe('renderToSvg theme check', () => {
it('rejects an unknown theme before launching a browser', async () => {
const { renderToSvg } = await import('./renderer.js');
await expect(
renderToSvg('graph TD; A-->B', { theme: "x'});window.pwned=1;//" as never })
).rejects.toThrow(/Unknown theme/);
});
});
98 changes: 98 additions & 0 deletions packages/mermaid-export/src/html.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,98 @@
import type { ExportOptions } from './types.js';

/** Mermaid CDN URL for rendering */
const MERMAID_CDN = 'https://cdn.jsdelivr.net/npm/mermaid@11/dist/mermaid.esm.min.mjs';

type Theme = NonNullable<ExportOptions['theme']>;

const THEMES: readonly string[] = ['default', 'forest', 'dark', 'neutral', 'base'];

/** Throws if the theme is not one of the supported Mermaid themes. */
export function validateTheme(theme: unknown): asserts theme is Theme {
if (typeof theme !== 'string' || !THEMES.includes(theme)) {
throw new Error(
`Unknown theme ${JSON.stringify(String(theme))}. Use one of: ${THEMES.join(', ')}`
);
}
}

/** A JS string literal that is safe inside an inline script block. */
export function escapeJsString(value: string): string {
return JSON.stringify(String(value))
.replace(/</g, '\\u003c')
.replace(/\u2028/g, '\\u2028')
.replace(/\u2029/g, '\\u2029');
}

/**
* A value for a CSS declaration. Anything outside letters, digits and
* the characters colors use (# ( ) , . % space - and / unless it opens a comment) is hex escaped, so it
* cannot end the declaration, open a block or close the style tag.
*/
export function escapeCss(value: string): string {
return String(value).replace(
/[^A-Za-z0-9#(),.% -]/gu,
(ch, offset, str) =>
ch === '/' && str[offset + 1] !== '*'
? ch
: `\\${ch.codePointAt(0)!.toString(16)} `
);
}

/**
* Generate HTML template for rendering Mermaid diagram
*/
export function generateHtml(diagram: string, theme: string, backgroundColor: string): string {
return `<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<style>
body {
margin: 0;
padding: 20px;
background-color: ${escapeCss(backgroundColor)};
display: flex;
justify-content: center;
align-items: flex-start;
}
#container {
display: inline-block;
}
</style>
</head>
<body>
<div id="container">
<pre class="mermaid">${escapeHtml(diagram)}</pre>
</div>
<script type="module">
import mermaid from ${escapeJsString(MERMAID_CDN)};
mermaid.initialize({
startOnLoad: true,
theme: ${escapeJsString(theme)},
securityLevel: 'loose'
});

// Signal when rendering is complete
mermaid.run().then(() => {
window.mermaidRendered = true;
}).catch(err => {
window.mermaidError = err.message;
});
</script>
</body>
</html>`;
}

/**
* Escape HTML special characters
*/
function escapeHtml(str: string): string {
return str
.replace(/&/g, '&amp;')
.replace(/</g, '&lt;')
.replace(/>/g, '&gt;')
.replace(/"/g, '&quot;')
.replace(/'/g, '&#039;');
}

63 changes: 3 additions & 60 deletions packages/mermaid-export/src/renderer.ts
Original file line number Diff line number Diff line change
@@ -1,8 +1,6 @@
import puppeteer, { type Browser } from 'puppeteer';
import type { RasterExportOptions, SvgExportOptions } from './types.js';

/** Mermaid CDN URL for rendering */
const MERMAID_CDN = 'https://cdn.jsdelivr.net/npm/mermaid@11/dist/mermaid.esm.min.mjs';
import { generateHtml, validateTheme } from './html.js';

/** Browser instance for reuse */
let browserInstance: Browser | null = null;
Expand Down Expand Up @@ -30,63 +28,6 @@ export async function closeBrowser(): Promise<void> {
}
}

/**
* Generate HTML template for rendering Mermaid diagram
*/
function generateHtml(diagram: string, theme: string, backgroundColor: string): string {
return `<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<style>
body {
margin: 0;
padding: 20px;
background-color: ${backgroundColor};
display: flex;
justify-content: center;
align-items: flex-start;
}
#container {
display: inline-block;
}
</style>
</head>
<body>
<div id="container">
<pre class="mermaid">${escapeHtml(diagram)}</pre>
</div>
<script type="module">
import mermaid from '${MERMAID_CDN}';
mermaid.initialize({
startOnLoad: true,
theme: '${theme}',
securityLevel: 'loose'
});

// Signal when rendering is complete
mermaid.run().then(() => {
window.mermaidRendered = true;
}).catch(err => {
window.mermaidError = err.message;
});
</script>
</body>
</html>`;
}

/**
* Escape HTML special characters
*/
function escapeHtml(str: string): string {
return str
.replace(/&/g, '&amp;')
.replace(/</g, '&lt;')
.replace(/>/g, '&gt;')
.replace(/"/g, '&quot;')
.replace(/'/g, '&#039;');
}

/**
* Render a Mermaid diagram and return SVG string
*/
Expand All @@ -95,6 +36,7 @@ export async function renderToSvg(
options: SvgExportOptions = {}
): Promise<string> {
const { backgroundColor = 'transparent', theme = 'default' } = options;
validateTheme(theme);

const browser = await getBrowser();
const page = await browser.newPage();
Expand Down Expand Up @@ -145,6 +87,7 @@ export async function renderToBuffer(
theme = 'default',
scale = 1,
} = options;
validateTheme(theme);

const browser = await getBrowser();
const page = await browser.newPage();
Expand Down
Loading