背景与价值
响应完整性可防止传输与缓存中的篡改。Content-Digest提供标准化哈希头用于校验。
统一规范
- 算法:统一 `sha-256`。
- 生成:服务端对响应体计算并下发头。
- 校验:客户端验证后入缓存或使用。
核心实现
生成与下发
```ts
type Res = { setHeader: (k: string, v: string) => void; end: (b?: any) => void }
function b64url(buf: ArrayBuffer): string { const u = new Uint8Array(buf); let s=''; for (let i=0;i {
const h = resp.headers.get('Content-Digest') || ''
const m = h.match(/sha-256=([^,\s]+)/)
if (!m) return false
const body = await resp.arrayBuffer()
const d = await crypto.subtle.digest('SHA-256', body)
const hash = b64url(d)
return hash === m[1]
}
```
落地建议
- 对敏感与缓存型响应统一计算并下发Content-Digest(sha-256),客户端验证后缓存。
- 与ETag/条件请求协同,提升一致性与完整性。
验证清单
- 是否下发Content-Digest;客户端是否校验一致并再使用或缓存。
发表评论 取消回复