Files
novalon-website/src/lib/sanitize.ts
T
zhangxiang a366bd1400 fix(qa): 第五轮系统性质量保障缺陷修复 + 单元/集成测试
安全/鉴权:登出清服务端 httpOnly 令牌、登录 IP 限流前置 bcrypt、停用账号
令牌在 6 个内联 role handler 失效、admin/items 存在性 oracle 认证前置、
同意偏好 sanitize fail-closed、api-crypto 按 HTTP 方法判体。

CMS:workflow 状态更新+审计收进交互式 $transaction(失败即回滚)、编辑器
richtext 走 textarea 防换行损毁、array/object 子字段按作用域读写防污染、
about/contact/erp-upgrade 补 ISR revalidate 与路由映射。

UI/a11y:AnimatedCounter 入视口前显起点、CLS 累计上报、MetricCard 动画入
effect 并卸载取消 rAF、后台状态四态映射/搜索防抖+序号守卫/媒体单 input/
吞错改横幅/表单 label-aria 关联。

新增对应判别性单测与 pagination/rate-limit/client-ip/sanitize/validate-content-data
等模块及 tests-integration 真库集成层。
2026-09-28 10:48:07 +08:00

52 lines
1.9 KiB
TypeScript
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
import sanitizeHtml from 'sanitize-html';
/**
* CMS 富文本渲染端净化(验收 A-3)。
* 白名单而非黑名单:新增的危险标签默认被丢弃,无需跟进上游漏洞库。
*/
const ALLOWED_TAGS = [
'a', 'abbr', 'b', 'blockquote', 'br', 'caption', 'cite', 'code', 'col', 'colgroup',
'dd', 'div', 'dl', 'dt', 'em', 'figcaption', 'figure', 'h1', 'h2', 'h3', 'h4', 'h5', 'h6',
'hr', 'i', 'img', 'li', 'mark', 'ol', 'p', 'pre', 's', 'small', 'span', 'strong',
'sub', 'sup', 'table', 'tbody', 'td', 'tfoot', 'th', 'thead', 'tr', 'u', 'ul',
];
const ALLOWED_ATTRIBUTES: Record<string, string[]> = {
a: ['href', 'title', 'target', 'rel'],
img: ['src', 'alt', 'title', 'width', 'height'],
col: ['span', 'width'],
td: ['colspan', 'rowspan'],
th: ['colspan', 'rowspan'],
ol: ['start', 'type'],
'*': ['class'],
};
// 无 javascript/data/vbscript:伪协议在属性层即被剔除(探针实测 href 整体消失)
const ALLOWED_SCHEMES = ['http', 'https', 'mailto', 'tel'];
const OPTIONS: sanitizeHtml.IOptions = {
allowedTags: ALLOWED_TAGS,
allowedAttributes: ALLOWED_ATTRIBUTES,
allowedSchemes: ALLOWED_SCHEMES,
// 协议相对 URL(//evil.example.com)等价于跟随页面协议外跳,一并拒绝
allowProtocolRelative: false,
// 危险标签连同其内容整体丢弃;recursiveEscape 会把 &lt;script&gt; 作为可见文本泄漏给读者
disallowedTagsMode: 'discard',
nonTextTags: ['script', 'style', 'textarea', 'title', 'noscript', 'iframe', 'object', 'embed', 'svg', 'math'],
nestingLimit: 50,
transformTags: {
a: (tagName, attribs) => ({
tagName,
attribs:
attribs.target === '_blank'
? { ...attribs, rel: 'noopener noreferrer' }
: attribs,
}),
},
};
export function sanitizeRichText(html: unknown): string {
if (typeof html !== 'string' || html.length === 0) return '';
return sanitizeHtml(html, OPTIONS);
}