Sanitizer API 安全HTML清洗与防XSS:策略配置、DOM插入与验证指标技术背景Sanitizer API 提供浏览器原生的 HTML 清洗能力,可在将不可信内容插入 DOM 前进行过滤,优于手写正则与第三方库的易错性与维护成本。结合 CSP/Trusted Types 可形成更强的防线。核心内容策略配置与清洗// 配置允许的标签与属性 const sanitizer = new (window as any).Sanitizer({ allowedElements: ['a', 'p', 'span', 'strong', 'em', 'ul', 'li', 'code', 'pre'], allowedAttributes: { 'a': ['href', 'rel', 'target'], 'code': ['class'] }, allowCustomElements: false, allowComments: false }); // 清洗为安全字符串(部分浏览器实现) function sanitizeToString(html: string) { const div = document.createElement('div'); // 一些实现支持 setHTML 第二参数传入 sanitizer (div as any).setHTML?.(html, { sanitizer }); // 兜底:直接赋值后再读取 textContent(简化示意) if (!(div as any).setHTML) { div.innerHTML = html; } return div.innerHTML; } 安全 DOM 插入function safeInsert(container: HTMLElement, html: string) { // 使用 setHTML + sanitizer(支持的浏览器) if ((container as any).setHTML) { (container as any).setHTML(html, { sanitizer }); return; } // 兜底策略:转义或使用 textContent(保守) const safe = sanitizeToString(html); container.innerHTML = safe; } // 示例:将用户生成内容插入卡片 const card = document.getElementById('card')!; safeInsert(card, userProvidedHTML); 技术验证参数在 Chrome 128/Edge 130(启用 Sanitizer 实现)下:危险标签/属性阻断率:≈ 100%插入开销:P95 < 2ms/次(中等片段)与 CSP/TT 协同命中率:≥ 95%应用场景富文本评论与用户内容展示第三方内容嵌入与安全隔离最佳实践明确允许列表并最小化范围,避免过宽放行与 CSP/Trusted Types 联合使用,覆盖不同注入路径为不支持的浏览器提供保守兜底(转义/仅文本)

发表评论 取消回复