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 = {
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 会把 <script> 作为可见文本泄漏给读者
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);
}