XSS 防护
xssProtection 中间件自动为响应添加 XSS 防护相关的安全头(X-XSS-Protection、X-Content-Type-Options、Content-Security-Policy、X-Frame-Options)。同时提供 escapeHTML 和 detectXSS 工具函数用于手动防护。
import { xssProtection } from "@ventostack/core";
// 默认配置app.use(xssProtection());
// 自定义 CSPapp.use( xssProtection({ contentSecurityPolicy: "default-src 'self'; script-src 'self'", frameOptions: "SAMEORIGIN", }),);import { escapeHTML, detectXSS } from "@ventostack/core";
// HTML 实体转义escapeHTML('<script>alert("xss")</script>');// => "<script>alert("xss")</script>"
// XSS 载荷检测detectXSS('<script>alert(1)</script>'); // truedetectXSS('Hello World'); // false| 选项 | 类型 | 默认值 | 说明 |
|---|---|---|---|
xssProtection | boolean | true | 是否设置 X-XSS-Protection: 1; mode=block |
noSniff | boolean | true | 是否设置 X-Content-Type-Options: nosniff |
contentSecurityPolicy | string | 不设置 | CSP 策略值 |
frameOptions | "DENY" | "SAMEORIGIN" | "DENY" | X-Frame-Options 值 |
完整类型定义:
interface XSSOptions { xssProtection?: boolean; noSniff?: boolean; contentSecurityPolicy?: string; frameOptions?: "DENY" | "SAMEORIGIN";}
function xssProtection(options?: XSSOptions): Middleware;function escapeHTML(input: string): string;function detectXSS(input: string): boolean;escapeHTML优先使用Bun.escapeHTML(),不可用时回退到手动替换detectXSS通过正则匹配常见 XSS 模式(<script>、javascript:、事件处理器等)- 中间件仅添加安全头,不拦截请求;配合
escapeHTML做输出转义效果更佳