Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We鈥檒l occasionally send you account related emails.

Already on GitHub? Sign in to your account

fix: Dompurify Hooks #5236

Merged
merged 2 commits into from
Jan 27, 2024
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
33 changes: 24 additions & 9 deletions packages/mermaid/src/diagrams/common/common.ts
Original file line number Diff line number Diff line change
Expand Up @@ -18,13 +18,18 @@ export const getRows = (s?: string): string[] => {
return str.split('#br#');
};

/**
* Removes script tags from a text
*
* @param txt - The text to sanitize
* @returns The safer text
*/
export const removeScript = (txt: string): string => {
const setupDompurifyHooksIfNotSetup = (() => {
let setup = false;

return () => {
if (!setup) {
setupDompurifyHooks();
setup = true;
}
};
})();

function setupDompurifyHooks() {
const TEMPORARY_ATTRIBUTE = 'data-temp-href-target';

DOMPurify.addHook('beforeSanitizeAttributes', (node: Element) => {
Expand All @@ -33,8 +38,6 @@ export const removeScript = (txt: string): string => {
}
});

const sanitizedText = DOMPurify.sanitize(txt);

DOMPurify.addHook('afterSanitizeAttributes', (node: Element) => {
if (node.tagName === 'A' && node.hasAttribute(TEMPORARY_ATTRIBUTE)) {
node.setAttribute('target', node.getAttribute(TEMPORARY_ATTRIBUTE) || '');
Expand All @@ -44,6 +47,18 @@ export const removeScript = (txt: string): string => {
}
}
});
}

/**
* Removes script tags from a text
*
* @param txt - The text to sanitize
* @returns The safer text
*/
export const removeScript = (txt: string): string => {
setupDompurifyHooksIfNotSetup();

const sanitizedText = DOMPurify.sanitize(txt);

return sanitizedText;
};
Expand Down