Skip to content

A Q&A platform software for teams at any scales. Whether it's a community forum, help center, or knowledge management platform, you can always count on Apache Answer.

feat(ui): filter unsafe tags in html to prevent xss

robin1813141f2c33
diff --git a/ui/src/components/Editor/Viewer.tsx b/ui/src/components/Editor/Viewer.tsx
index 93553887..217c0986 100644
--- a/ui/src/components/Editor/Viewer.tsx
+++ b/ui/src/components/Editor/Viewer.tsx
@@ -8,6 +8,7 @@ import {
} from 'react';
import { markdownToHtml } from '@/services';
+import { htmlToReact } from '@/utils';
import { htmlRender } from './utils';
@@ -38,6 +39,7 @@ const Index = ({ value }, ref) => {
}
previewRef.current?.scrollTo(0, scrollTop);
+
htmlRender(previewRef.current);
}, [html]);
useImperativeHandle(ref, () => {
@@ -49,9 +51,9 @@ const Index = ({ value }, ref) => {
return (
<div
ref={previewRef}
- className="preview-wrap position-relative p-3 bg-light rounded text-break text-wrap mt-2 fmt"
- dangerouslySetInnerHTML={{ __html: html }}
- />
+ className="preview-wrap position-relative p-3 bg-light rounded text-break text-wrap mt-2 fmt">
+ {htmlToReact(html)}
+ </div>
);
};
diff --git a/ui/src/utils/common.ts b/ui/src/utils/common.ts
index e3e53652..a7c6b12d 100644
--- a/ui/src/utils/common.ts
+++ b/ui/src/utils/common.ts
@@ -1,4 +1,6 @@
import i18next from 'i18next';
+import parse from 'html-react-parser';
+import * as DOMPurify from 'dompurify';
const Diff = require('diff');
@@ -214,6 +216,13 @@ function diffText(newText: string, oldText: string): string {
?.replace(/<input/gi, '&lt;input');
}
+function htmlToReact(html: string) {
+ const cleanedHtml = DOMPurify.sanitize(html, {
+ USE_PROFILES: { html: true },
+ });
+ return parse(cleanedHtml);
+}
+
export {
thousandthDivision,
formatCount,
@@ -228,4 +237,5 @@ export {
labelStyle,
handleFormError,
diffText,
+ htmlToReact,
};