Skip to content

Commit 37ff937

Browse files
committed
fix: create CSS styles using the CSSOM
Currently, we're creating CSS styles using strings, which isn't ideal, since it can lead to CSS injections other other CSS bugs. However, we can instead use Constructable Stylesheets and the CSSOM to better construct a CSS stylesheet. This new API scrubs invalid syntax from the CSS stylesheet and does some normalization (e.g. removing unnecessary spaces). [1]: https://developer.mozilla.org/en-US/docs/Web/API/CSSStyleSheet/replaceSync See: https://web.dev/articles/constructable-stylesheets
1 parent e4148ff commit 37ff937

11 files changed

Lines changed: 115 additions & 44 deletions

File tree

‎.changeset/cold-numbers-taste.md‎

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,7 @@
1+
---
2+
'mermaid': patch
3+
---
4+
5+
fix: create CSS styles using the CSSOM
6+
7+
This removes some invalid CSS and normalizes some CSS formatting.

‎cypress/integration/other/ghsa.spec.js‎

Lines changed: 11 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
1-
import { urlSnapshotTest, openURLAndVerifyRendering } from '../../helpers/util.ts';
1+
import { urlSnapshotTest, openURLAndVerifyRendering, imgSnapshotTest } from '../../helpers/util.ts';
22

33
describe('CSS injections', () => {
44
it('should not allow CSS injections outside of the diagram', () => {
@@ -31,4 +31,14 @@ describe('CSS injections', () => {
3131
'url("https://example.test/3.png")'
3232
);
3333
});
34+
it('should prevent HTML injection via class definitions', () => {
35+
imgSnapshotTest(
36+
`stateDiagram-v2
37+
classDef xss fill:red</style></svg><style>*{x:x;y:y;overflow:visible!important;contain:none!important;transform:none!important;filter:none!important;clip-path:none!important}</style><div id="pwned" style="x:x;y:y;color:red;font:5em/1 monospace;display:grid;place-items:center;z-index:2147483647;width:100vw;height:100vh;position:fixed;top:0;left:0;background:black">HACKED</div><svg><style>a:b
38+
[*] --> A:::xss
39+
`,
40+
{ logLevel: 1 }
41+
);
42+
cy.get('body > div #pwned').should('not.exist');
43+
});
3444
});

‎cypress/integration/rendering/theme.spec.js‎

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -23,6 +23,16 @@ describe('themeCSS balancing, it', () => {
2323
});
2424
});
2525

26+
it('themeCSS - should work', () => {
27+
const themeCSS = `.nodeLabel {
28+
font-variant-caps: petite-caps;
29+
}`;
30+
imgSnapshotTest("flowchart TD; A['Hello World']", {
31+
themeCSS,
32+
});
33+
cy.get('.nodeLabel').should('have.css', 'font-variant-caps', 'petite-caps');
34+
});
35+
2636
// TODO: Delete/Rename this describe, keeping the inner contents.
2737
describe('Pie Chart', () => {
2838
// beforeEach(()=>{

‎docs/config/setup/mermaid/interfaces/ExternalDiagramDefinition.md‎

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -10,28 +10,28 @@
1010

1111
# Interface: ExternalDiagramDefinition
1212

13-
Defined in: [packages/mermaid/src/diagram-api/types.ts:97](https://github.com/mermaid-js/mermaid/blob/master/packages/mermaid/src/diagram-api/types.ts#L97)
13+
Defined in: [packages/mermaid/src/diagram-api/types.ts:104](https://github.com/mermaid-js/mermaid/blob/master/packages/mermaid/src/diagram-api/types.ts#L104)
1414

1515
## Properties
1616

1717
### detector
1818

1919
> **detector**: `DiagramDetector`
2020
21-
Defined in: [packages/mermaid/src/diagram-api/types.ts:99](https://github.com/mermaid-js/mermaid/blob/master/packages/mermaid/src/diagram-api/types.ts#L99)
21+
Defined in: [packages/mermaid/src/diagram-api/types.ts:106](https://github.com/mermaid-js/mermaid/blob/master/packages/mermaid/src/diagram-api/types.ts#L106)
2222

2323
---
2424

2525
### id
2626

2727
> **id**: `string`
2828
29-
Defined in: [packages/mermaid/src/diagram-api/types.ts:98](https://github.com/mermaid-js/mermaid/blob/master/packages/mermaid/src/diagram-api/types.ts#L98)
29+
Defined in: [packages/mermaid/src/diagram-api/types.ts:105](https://github.com/mermaid-js/mermaid/blob/master/packages/mermaid/src/diagram-api/types.ts#L105)
3030

3131
---
3232

3333
### loader
3434

3535
> **loader**: `DiagramLoader`
3636
37-
Defined in: [packages/mermaid/src/diagram-api/types.ts:100](https://github.com/mermaid-js/mermaid/blob/master/packages/mermaid/src/diagram-api/types.ts#L100)
37+
Defined in: [packages/mermaid/src/diagram-api/types.ts:107](https://github.com/mermaid-js/mermaid/blob/master/packages/mermaid/src/diagram-api/types.ts#L107)

‎docs/config/setup/mermaid/interfaces/RenderResult.md‎

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -10,15 +10,15 @@
1010

1111
# Interface: RenderResult
1212

13-
Defined in: [packages/mermaid/src/types.ts:116](https://github.com/mermaid-js/mermaid/blob/master/packages/mermaid/src/types.ts#L116)
13+
Defined in: [packages/mermaid/src/types.ts:129](https://github.com/mermaid-js/mermaid/blob/master/packages/mermaid/src/types.ts#L129)
1414

1515
## Properties
1616

1717
### bindFunctions()?
1818

1919
> `optional` **bindFunctions**: (`element`) => `void`
2020
21-
Defined in: [packages/mermaid/src/types.ts:134](https://github.com/mermaid-js/mermaid/blob/master/packages/mermaid/src/types.ts#L134)
21+
Defined in: [packages/mermaid/src/types.ts:147](https://github.com/mermaid-js/mermaid/blob/master/packages/mermaid/src/types.ts#L147)
2222

2323
Bind function to be called after the svg has been inserted into the DOM.
2424
This is necessary for adding event listeners to the elements in the svg.
@@ -45,7 +45,7 @@ bindFunctions?.(div); // To call bindFunctions only if it's present.
4545
4646
> **diagramType**: `string`
4747
48-
Defined in: [packages/mermaid/src/types.ts:124](https://github.com/mermaid-js/mermaid/blob/master/packages/mermaid/src/types.ts#L124)
48+
Defined in: [packages/mermaid/src/types.ts:137](https://github.com/mermaid-js/mermaid/blob/master/packages/mermaid/src/types.ts#L137)
4949
5050
The diagram type, e.g. 'flowchart', 'sequence', etc.
5151
@@ -55,6 +55,6 @@ The diagram type, e.g. 'flowchart', 'sequence', etc.
5555
5656
> **svg**: `string`
5757
58-
Defined in: [packages/mermaid/src/types.ts:120](https://github.com/mermaid-js/mermaid/blob/master/packages/mermaid/src/types.ts#L120)
58+
Defined in: [packages/mermaid/src/types.ts:133](https://github.com/mermaid-js/mermaid/blob/master/packages/mermaid/src/types.ts#L133)
5959
6060
The svg code for the rendered graph.

‎docs/config/setup/mermaid/type-aliases/SVG.md‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -12,4 +12,4 @@
1212

1313
> **SVG** = `d3.Selection`<`SVGSVGElement`, `unknown`, `Element` | `null`, `unknown`>
1414
15-
Defined in: [packages/mermaid/src/diagram-api/types.ts:129](https://github.com/mermaid-js/mermaid/blob/master/packages/mermaid/src/diagram-api/types.ts#L129)
15+
Defined in: [packages/mermaid/src/diagram-api/types.ts:136](https://github.com/mermaid-js/mermaid/blob/master/packages/mermaid/src/diagram-api/types.ts#L136)

‎docs/config/setup/mermaid/type-aliases/SVGGroup.md‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -12,4 +12,4 @@
1212

1313
> **SVGGroup** = `d3.Selection`<`SVGGElement`, `unknown`, `Element` | `null`, `unknown`>
1414
15-
Defined in: [packages/mermaid/src/diagram-api/types.ts:131](https://github.com/mermaid-js/mermaid/blob/master/packages/mermaid/src/diagram-api/types.ts#L131)
15+
Defined in: [packages/mermaid/src/diagram-api/types.ts:138](https://github.com/mermaid-js/mermaid/blob/master/packages/mermaid/src/diagram-api/types.ts#L138)

‎packages/mermaid/src/diagram-api/types.ts‎

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -64,7 +64,14 @@ export type DiagramDBBase<T extends BaseDiagramConfig> = {
6464
// It makes it clear we're working with a style class definition, even though defining the type is currently difficult.
6565
export interface DiagramStyleClassDef {
6666
id: string;
67+
/**
68+
* The styles to apply to the class for HTML rendering.
69+
* These are expected to be CSS property declarations without a trailing semicolon, e.g. `color: red`.
70+
*/
6771
styles?: string[];
72+
/**
73+
* The styles to apply to `<tspan>` elements with the given class.
74+
*/
6875
textStyles?: string[];
6976
}
7077

‎packages/mermaid/src/mermaidAPI.spec.ts‎

Lines changed: 33 additions & 18 deletions
Original file line numberDiff line numberDiff line change
@@ -16,9 +16,11 @@ import * as configApi from './config.js';
1616
// --------------
1717
// Mocks
1818
// To mock a module, first define a mock for it, then (if used explicitly in the tests) import it. Be sure the path points to exactly the same file as is imported in mermaidAPI (the module being tested)
19-
vi.mock(import('./styles.js'), () => {
19+
vi.mock(import('./styles.js'), async (importOriginal) => {
20+
const original = await importOriginal();
2021
return {
2122
addStylesForDiagram: vi.fn(),
23+
cssStyleSheetToString: vi.fn().mockImplementation(original.cssStyleSheetToString),
2224
default: vi.fn().mockImplementation(
2325
(_type, userStyles, _options) => `
2426
& .edge-pattern-dashed{
@@ -241,29 +243,38 @@ describe('mermaidAPI', () => {
241243
const serif = 'serif';
242244
const sansSerif = 'sans-serif';
243245
const mocked_config_with_htmlLabels: MermaidConfig = {
244-
themeCSS: 'default',
246+
themeCSS: '.default {color: red;}',
245247
fontFamily: serif,
246248
altFontFamily: sansSerif,
247249
htmlLabels: true,
248250
};
249251

250252
it('gets the cssStyles from the theme', () => {
251253
const styles = createCssStyles(mocked_config_with_htmlLabels, null);
252-
expect(styles).toMatch(/^\ndefault(.*)/);
254+
expect(styles).toContain('.default {color: red;}');
253255
});
256+
254257
it('gets the fontFamily from the config', () => {
255258
const styles = createCssStyles(mocked_config_with_htmlLabels, new Map());
256-
expect(styles).toMatch(/(.*)\n:root { --mermaid-font-family: serif(.*)/);
259+
expect(styles).toMatch(/(.*)\n:root {--mermaid-font-family: serif(.*)/);
257260
});
261+
258262
it('gets the alt fontFamily from the config', () => {
259263
const styles = createCssStyles(mocked_config_with_htmlLabels, undefined);
260-
expect(styles).toMatch(/(.*)\n:root { --mermaid-alt-font-family: sans-serif(.*)/);
264+
expect(styles).toMatch(/(.*)\n:root {--mermaid-alt-font-family: sans-serif(.*)/);
261265
});
262266

263267
describe('there are some classDefs', () => {
264-
const classDef1 = { id: 'classDef1', styles: ['style1-1', 'style1-2'], textStyles: [] };
265-
const classDef2 = { id: 'classDef2', styles: [], textStyles: ['textStyle2-1'] };
266-
const classDef3 = { id: 'classDef3', textStyles: ['textStyle3-1', 'textStyle3-2'] };
268+
const classDef1 = {
269+
id: 'classDef1',
270+
styles: ['prop: style1-1', 'prop-2: style1-2'],
271+
textStyles: [],
272+
};
273+
const classDef2 = { id: 'classDef2', styles: [], textStyles: ['prop: textStyle2-1'] };
274+
const classDef3 = {
275+
id: 'classDef3',
276+
textStyles: ['prop: textStyle3-1', 'prop-2: textStyle3-2'],
277+
};
267278
const classDefs = { classDef1, classDef2, classDef3 };
268279

269280
describe('the graph supports classDefs', () => {
@@ -288,7 +299,7 @@ describe('mermaidAPI', () => {
288299
new RegExp(
289300
`\\.classDef1 ${escapeForRegexp(
290301
htmlElement
291-
)} \\{ style1-1 !important; style1-2 !important; }`
302+
)} \\{prop: style1-1 !important; prop-2: style1-2 !important;}`
292303
)
293304
);
294305
// no CSS styles are created if there are no styles for a classDef
@@ -304,14 +315,14 @@ describe('mermaidAPI', () => {
304315
function expect_textStyles_matchesHtmlElements(textStyles: string, htmlElement: string) {
305316
expect(textStyles).toMatch(
306317
new RegExp(
307-
`\\.classDef2 ${escapeForRegexp(htmlElement)} \\{ textStyle2-1 !important; }`
318+
`\\.classDef2 ${escapeForRegexp(htmlElement)} \\{prop: textStyle2-1 !important;}`
308319
)
309320
);
310321
expect(textStyles).toMatch(
311322
new RegExp(
312323
`\\.classDef3 ${escapeForRegexp(
313324
htmlElement
314-
)} \\{ textStyle3-1 !important; textStyle3-2 !important; }`
325+
)} \\{prop: textStyle3-1 !important; prop-2: textStyle3-2 !important;}`
315326
)
316327
);
317328

@@ -388,21 +399,23 @@ describe('mermaidAPI', () => {
388399

389400
describe('createUserStyles', () => {
390401
const mockConfig = {
391-
themeCSS: 'default',
402+
themeCSS: '.default {color: red;}',
392403
htmlLabels: true,
393404
themeVariables: { fontFamily: 'serif' },
394405
};
395406

396-
const classDef1 = { id: 'classDef1', styles: ['style1-1'], textStyles: [] };
407+
const classDef1 = { id: 'classDef1', styles: ['prop: style1-1'], textStyles: [] };
408+
409+
const divElement = document.body.appendChild(document.createElement('div'));
397410

398411
it('gets the css styles created', () => {
399412
// @todo TODO if a single function in the module can be mocked, do it for createCssStyles and mock the results.
400413

401414
createUserStyles(mockConfig, 'flowchart-v2', new Map([['classDef1', classDef1]]), '#someId');
402415
const expectedStyles =
403-
'\ndefault' +
404-
'\n.classDef1 > * { style1-1 !important; }' +
405-
'\n.classDef1 span { style1-1 !important; }';
416+
'.default {color: red;}' +
417+
'\n.classDef1 > * {prop: style1-1 !important;}' +
418+
'\n.classDef1 span {prop: style1-1 !important;}';
406419
expect(getStyles).toHaveBeenCalledWith(
407420
'flowchart-v2',
408421
expectedStyles,
@@ -422,7 +435,9 @@ describe('mermaidAPI', () => {
422435
const result = createUserStyles(mockConfig, 'someDiagram', new Map(), '#someId');
423436
expect(compile).toHaveBeenCalled();
424437
expect(serialize).toHaveBeenCalled();
425-
expect(result).toEqual('#someId .edge-pattern-dashed{stroke-dasharray:3;}');
438+
expect(result).toEqual(
439+
'#someId .edge-pattern-dashed{stroke-dasharray:3;}#someId .default{color:red;}'
440+
);
426441
});
427442

428443
it('should sanitize CSS to avoid unbalanced braces', () => {
@@ -443,7 +458,7 @@ describe('mermaidAPI', () => {
443458
'#someId'
444459
);
445460
expect(result).toEqual(
446-
'#someId .edge-pattern-dashed{stroke-dasharray:3;}#someId .classDef2>*{color:purple;}#someId .classDef2 span{color:purple;}'
461+
'#someId .edge-pattern-dashed{stroke-dasharray:3;}#someId .default{color:red;}#someId .classDef2>*{color:purple;}#someId .classDef2 span{color:purple;}'
447462
);
448463
});
449464
});

‎packages/mermaid/src/mermaidAPI.ts‎

Lines changed: 33 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -20,7 +20,7 @@ import errorRenderer from './diagrams/error/errorRenderer.js';
2020
import { attachFunctions } from './interactionDb.js';
2121
import { log, setLogLevel } from './logger.js';
2222
import { preprocessDiagram } from './preprocess.js';
23-
import getStyles from './styles.js';
23+
import getStyles, { cssStyleSheetToString } from './styles.js';
2424
import theme from './themes/index.js';
2525
import type {
2626
D3HtmlSelection,
@@ -104,7 +104,7 @@ export const cssImportantStyles = (
104104
cssClasses: string[] = []
105105
): string => {
106106
const declarationBlock = sanitizeCss(`{ ${cssClasses.join(' !important; ')} !important; }`);
107-
return `\n.${cssClass} ${element} ${declarationBlock}`;
107+
return `.${cssClass} ${element} ${declarationBlock}`;
108108
};
109109

110110
/**
@@ -118,20 +118,22 @@ export const createCssStyles = (
118118
config: MermaidConfig,
119119
classDefs: Map<string, DiagramStyleClassDef> | null | undefined = new Map()
120120
): string => {
121-
let cssStyles = '';
121+
const cssStyles = new CSSStyleSheet();
122122

123123
// user provided theme CSS info
124124
// If you add more configuration driven data into the user styles make sure that the value is
125125
// sanitized by the sanitize CSS function TODO where is this method? what should be used to replace it? refactor so that it's always sanitized
126-
if (config.themeCSS !== undefined) {
127-
cssStyles += `\n${config.themeCSS}`;
128-
}
129-
130126
if (config.fontFamily !== undefined) {
131-
cssStyles += `\n:root { --mermaid-font-family: ${config.fontFamily}}`;
127+
cssStyles.insertRule(
128+
`:root { --mermaid-font-family: ${config.fontFamily}}`,
129+
cssStyles.cssRules.length
130+
);
132131
}
133132
if (config.altFontFamily !== undefined) {
134-
cssStyles += `\n:root { --mermaid-alt-font-family: ${config.altFontFamily}}`;
133+
cssStyles.insertRule(
134+
`:root { --mermaid-alt-font-family: ${config.altFontFamily}}`,
135+
cssStyles.cssRules.length
136+
);
135137
}
136138

137139
// classDefs defined in the diagram text
@@ -148,20 +150,36 @@ export const createCssStyles = (
148150
// create the css styles for each cssElement and the styles (only if there are styles)
149151
if (!isEmpty(styleClassDef.styles)) {
150152
cssElements.forEach((cssElement) => {
151-
cssStyles += cssImportantStyles(styleClassDef.id, cssElement, styleClassDef.styles);
153+
cssStyles.insertRule(
154+
cssImportantStyles(styleClassDef.id, cssElement, styleClassDef.styles),
155+
cssStyles.cssRules.length
156+
);
152157
});
153158
}
154159
// create the css styles for the tspan element and the text styles (only if there are textStyles)
155160
if (!isEmpty(styleClassDef.textStyles)) {
156-
cssStyles += cssImportantStyles(
157-
styleClassDef.id,
158-
'tspan',
159-
(styleClassDef?.textStyles || []).map((s) => s.replace('color', 'fill'))
161+
cssStyles.insertRule(
162+
cssImportantStyles(
163+
styleClassDef.id,
164+
'tspan',
165+
(styleClassDef?.textStyles || []).map((s) => s.replace('color', 'fill'))
166+
),
167+
cssStyles.cssRules.length
160168
);
161169
}
162170
});
163171
}
164-
return cssStyles;
172+
173+
let cssString = '';
174+
if (config.themeCSS !== undefined) {
175+
/**
176+
* Ideally we'd do a `CSSStyleSheet.replaceSync`, but it's not supported
177+
* in some older browsers and in JSDOM.
178+
*/
179+
cssString += `${config.themeCSS}\n`;
180+
}
181+
182+
return cssString + cssStyleSheetToString(cssStyles);
165183
};
166184

167185
export const createUserStyles = (

0 commit comments

Comments
 (0)