跳转到内容

XSS 防护

xssProtection 中间件自动为响应添加 XSS 防护相关的安全头(X-XSS-ProtectionX-Content-Type-OptionsContent-Security-PolicyX-Frame-Options)。同时提供 escapeHTMLdetectXSS 工具函数用于手动防护。

import { xssProtection } from "@ventostack/core";
// 默认配置
app.use(xssProtection());
// 自定义 CSP
app.use(
xssProtection({
contentSecurityPolicy: "default-src 'self'; script-src 'self'",
frameOptions: "SAMEORIGIN",
}),
);
import { escapeHTML, detectXSS } from "@ventostack/core";
// HTML 实体转义
escapeHTML('<script>alert("xss")</script>');
// => "&lt;script&gt;alert(&quot;xss&quot;)&lt;/script&gt;"
// XSS 载荷检测
detectXSS('<script>alert(1)</script>'); // true
detectXSS('Hello World'); // false
选项类型默认值说明
xssProtectionbooleantrue是否设置 X-XSS-Protection: 1; mode=block
noSniffbooleantrue是否设置 X-Content-Type-Options: nosniff
contentSecurityPolicystring不设置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 做输出转义效果更佳