CSP报告与Report-To聚合与监控最佳实践概述通过配置CSP报告通道与服务端聚合,可及时发现前端策略违规与潜在威胁。响应头配置Reporting-Endpoints: csp="https://example.com/reports/csp"
Report-To: {"group":"csp","max_age":10800,"endpoints":[{"url":"https://example.com/reports/csp"}]}
Content-Security-Policy-Report-Only: default-src 'self'; report-to=csp; report-uri /csp-report
采集端点type CspReport = { "csp-report": Record<string, any> }
async function collectCspReport(reqBody: string): Promise<boolean> {
try {
const body = JSON.parse(reqBody) as CspReport
const item = body["csp-report"]
return !!item && typeof item["blocked-uri"] === "string"
} catch {
return false
}
}
聚合与告警class CspAggregator {
store: Map<string, number> = new Map()
add(uri: string): void {
const v = this.store.get(uri) || 0
this.store.set(uri, v + 1)
}
top(n: number): [string, number][] {
return Array.from(this.store.entries()).sort((a, b) => b[1] - a[1]).slice(0, n)
}
}
运维要点同时支持legacy `report-uri`与现代 `Reporting-Endpoints`聚合违规来源并在阈值触发告警将报告与安全日志统一入库并进行留存与分析通过统一采集与聚合,可持续提升前端安全策略的可观测与迭代质量。

发表评论 取消回复