内容安全策略(CSP)
定义 CSP 头,防止 XSS、数据注入和混合内容。
边缘高级
为什么
CSP 是防 XSS 最有效的手段 — 限制可加载和执行的资源。Cloudflare 边缘网络覆盖 330+ 城市,全球 p95 延迟低于 50ms。
边缘函数相比源服务器将 TTFB 降低 60-80%,Akamai 报告 2024 年 40% 的企业使用边缘计算。
何时使用
所有处理用户输入或显示第三方内容的生产站点。 需要数据库写入的有状态逻辑避免边缘函数 — 边缘运行时无持久连接池。需要长时间运行任务(>30s)或重 CPU 计算时跳过。
如何做
# Next.js CSP via 头s
async headers() {
return [{
source: '/(.*)',
headers: [{
key: 'Content-Security-Policy',
value: [
"default-src 'self'",
"script-src 'self' 'unsafe-inline' 'unsafe-eval' https://cdn.example.com",
"style-src 'self' 'unsafe-inline' https://fonts.googleapis.com",
"img-src 'self' data: https: blob:",
"font-src 'self' https://fonts.gstatic.com",
"connect-src 'self' https://api.example.com wss://ws.example.com",
"frame-ancestors 'none'",
"base-uri 'self'",
"form-action 'self'",
"upgrade-insecure-requests",
].join('; ')
}]
}];
}
4. 验证部署 — curl -I https://your-app.example.com
5. 监控日志 — 前 5 分钟检查错误
6. 需要时回滚 — 回退到上一版本
示例
# Nonce-based CSP (Next.js 14)
import { headers } from 'next/headers';
export default function Layout({ children }) {
const nonce = headers().get('x-nonce') || '';
const csp = [
"default-src 'self'",
`script-src 'self' 'nonce-${nonce}'`,
"style-src 'self' 'unsafe-inline'",
].join('; ');
return (
<html>
<head>
<meta httpEquiv="Content-Security-Policy" content={csp} />
</head>
<body>{children}</body>
</html>
);
}
常见问题
- ⚠内联脚本被阻止 — 用 nonce 或 hash
- ⚠第三方脚本失败 — 在 script-src 加具体域
- ⚠环境间配置漂移 — 使用基础设施即代码(Terraform/Pulumi)保持 dev/staging/prod 一致
最佳实践
- ✓先用 report-only — 强制前收集违规
- ✓内联脚本用 nonce — 比 unsafe-inline 更安全
- ✓设置健康检查和优雅关闭 — 处理 SIGTERM 以在退出前排空进行中的请求