feat: clean markdown content

This commit is contained in:
jialin
2025-06-25 14:35:00 +08:00
parent 830ee45161
commit a6825f7ee3
7 changed files with 70 additions and 44 deletions
+22 -3
View File
@@ -1,6 +1,7 @@
import { EyeOutlined } from '@ant-design/icons';
import { sanitizeUrl } from '@braintree/sanitize-url';
import { Checkbox, Image, Typography } from 'antd';
import DOMPurify from 'dompurify';
import { unescape } from 'lodash';
import { TokensList, marked } from 'marked';
import React, { Fragment, useCallback, useEffect } from 'react';
@@ -16,6 +17,15 @@ interface MarkdownViewerProps {
generateImgLink?: (src: string) => string;
}
const dompurifyOptions = {
FORBID_TAGS: ['meta', 'style', 'script', 'iframe'],
FORBID_ATTR: ['onerror', 'onclick', 'onload', 'style']
};
const cleanHtml = (html: string): string => {
return DOMPurify.sanitize(html, dompurifyOptions);
};
const MarkdownViewer: React.FC<MarkdownViewerProps> = ({
content,
generateImgLink,
@@ -68,11 +78,14 @@ const MarkdownViewer: React.FC<MarkdownViewerProps> = ({
const renderItem = useCallback(
(token: any, render: any) => {
if (token.type === 'script' || token.type === 'style') {
return null;
}
if (!reDefineTypes.includes(token.type)) {
return (
<span
dangerouslySetInnerHTML={{
__html: marked.parser([token], { renderer })
__html: cleanHtml(marked.parser([token], { renderer }))
}}
></span>
);
@@ -89,7 +102,13 @@ const MarkdownViewer: React.FC<MarkdownViewerProps> = ({
}
if (token.type === 'html') {
htmlstr = <div dangerouslySetInnerHTML={{ __html: token.text }} />;
htmlstr = (
<div
dangerouslySetInnerHTML={{
__html: cleanHtml(token.text)
}}
/>
);
}
if (token.type === 'list') {
htmlstr = token.order ? (
@@ -158,7 +177,7 @@ const MarkdownViewer: React.FC<MarkdownViewerProps> = ({
if (token.type === 'link') {
htmlstr = (
<Link
href={token.href}
href={sanitizeUrl(token.href || '')}
title={token.title || ''}
target="_blank"
rel="noopener noreferrer"