-
Notifications
You must be signed in to change notification settings - Fork 320
🔒 使用 DOMPurify 清理公告通知 HTML 内容 #1274
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’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Changes from all commits
File filter
Filter by extension
Conversations
Jump to
Diff view
Diff view
There are no files selected for viewing
Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,24 @@ | ||
| import DOMPurify from "dompurify"; | ||
|
|
||
| // 允许的安全 CSS 属性白名单 | ||
| const ALLOWED_CSS_PROPERTIES = ["color", "font-size", "font-weight", "font-style"]; | ||
|
|
||
| // 过滤不安全的 CSS 属性,只保留白名单中的属性 | ||
| DOMPurify.addHook("afterSanitizeAttributes", (node) => { | ||
| if (node instanceof HTMLElement && node.hasAttribute("style")) { | ||
| const { style } = node; | ||
| for (let i = style.length - 1; i >= 0; i--) { | ||
| if (!ALLOWED_CSS_PROPERTIES.includes(style[i])) { | ||
| style.removeProperty(style[i]); | ||
| } | ||
| } | ||
| } | ||
| }); | ||
|
|
||
| // 对 HTML 进行清理,只保留安全的标签和属性 | ||
| export function sanitizeHTML(html: string): string { | ||
| return DOMPurify.sanitize(html, { | ||
| ALLOWED_TAGS: ["b", "i", "a", "br", "p", "strong", "em", "span"], | ||
| ALLOWED_ATTR: ["href", "target", "style"], | ||
| }); | ||
|
Comment on lines
+20
to
+23
|
||
| } | ||
|
Comment on lines
+18
to
+24
|
||
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
这里在模块顶层调用
DOMPurify.addHook会产生全局副作用:任何后续对 DOMPurify 的使用都会被这个 style 白名单逻辑影响,并且在热重载/多实例场景可能重复注册 hook。更稳妥的做法是创建专用的 DOMPurify 实例(例如基于当前 window 创建实例)并只在该实例上注册 hook,或至少加一次性初始化保护。