Correlation 与安全 Observability
Web/Admin 请求关联、allowlisted Auth/audit 日志、错误分类、异步传播和外部 reporter 门禁。
Web 与 Admin 在 TanStack Start 全局 request middleware 中使用同一个 Observability contract。它用于把一次请求的 HTTP 与 Auth 安全事件关联起来,不是 request dump、用户行为分析或完整 trace storage。
Correlation 生命周期
- 请求 header:
x-correlation-id - 只允许 RFC UUID 文本格式,与
crypto.randomUUID()的输出一致 - 合法 incoming ID 原样使用
- 缺失、非 UUID 或类似任意 token/PII 的字符串都替换为新 UUID
- 最终 ID 写回 HTML、API、server-function 和无细节内部失败 response
AsyncLocalStorage 在一次 Worker request 内携带 { id },因此 Better Auth 的安全分类事件与外层 HTTP observation 使用相同 ID。应用代码不读取 Cookie 或 Session 来建立 correlation。
Observation allowlist
| 事件 | 允许字段 |
|---|---|
http.request | application、correlationId、method class、route class |
http.response | 上述字段 + status |
http.error | 上述字段 + status/null + stable errorClass |
auth.internal | application、correlationId、level |
auth.delivery | application、correlationId、messageType、provider-neutral delivery outcome |
admin.audit | application=admin、correlationId、outcome=write-failed |
Route 只分类为 page、server-function、auth、admin、consent、assets 或 api。Logger 不读取 query value、request body、Cookie、Authorization、email、完整 Session、Error message 或 stack;sink 与 reporter 都只接收构造后的 union,不接收任意对象。
稳定错误分类
HTTP status 和显式 ObservationError 只映射到:
aborted、conflict、dependency、forbidden、internal、invalid-input、not-found、rate-limited、unauthenticated。
任意 Error message、Provider message 和 stack 都被丢弃。未转换的内部异常在边界成为无 body 的 500,并保留 correlation ID。Reporter 或 console sink 抛错不会改变主请求的 Response。
Queue 与 Webhook handoff
PRD 15 的未来 producer/consumer 只传播严格版本化对象:
{
"correlationId": "11111111-1111-4111-8111-111111111111",
"version": 1
}额外字段、非法 ID 或未知版本解析失败。当前提供 queue | webhook 类型化 adapter 和只记录 correlation metadata 的确定性内存实现;不发送消息、不创建 Queue,也不携带业务 payload。真实异步集成由 PRD 15 验收。
外部 reporter
默认 runtime 没有 reporter adapter,因此没有外部请求。下游项目只有同时提供 enabled: true 和注入 adapter 时,才会把已经净化的 http.error 交给外部 reporter;package 本身不包含网络客户端。Reporter 在主响应之外启动,失败或永久等待都不能阻塞/替代主响应,也不会自动重试。
验证
pnpm --filter @tanplate/observability test
pnpm --filter web test
pnpm --filter admin test
pnpm --filter web exec playwright test tests/consent-preferences.spec.ts
pnpm --filter admin test:e2e:worker-authCapture tests 使用实际 Web/Admin 全局 Start middleware 与 Auth/audit sink,并注入包含 password、token、secret、Cookie、Authorization、email、Session 和 Error message 的合成输入,验证它们未进入 observation。真实 Web/Admin Workers 覆盖 UUID correlation 传播和非法值替换;Admin E2E 还验证 mutation audit 与 response 使用同一 ID。