前端错误报告与崩溃分析安全治理(Source Map/采样/脱敏)最佳实践概述前端错误上报需兼顾敏感信息保护与可定位性。采用采样、脱敏与受控的Source Map解析可在降低隐私风险的同时提供有效诊断。采样与节流class Sampler {

rate: number

windowMs: number

hits: number[] = []

constructor(rate: number, windowMs: number) { this.rate = rate; this.windowMs = windowMs }

allow(): boolean {

const now = Date.now()

this.hits = this.hits.filter(t => now - t < this.windowMs)

if (this.hits.length >= this.rate) return false

this.hits.push(now)

return true

}

}

字段脱敏function redactErrorPayload(payload: Record<string, any>): Record<string, any> {

const sensitive = ['email', 'token', 'authorization', 'cookie']

const out: Record<string, any> = {}

for (const k of Object.keys(payload)) {

out[k] = sensitive.includes(k.toLowerCase()) ? '***' : payload[k]

}

return out

}

受控Source Map解析import { SourceMapConsumer } from 'source-map'

async function resolveStack(stack: string, mapContent: string): Promise<string[]> {

const consumer = await new SourceMapConsumer(mapContent)

const lines = stack.split('\n')

const result: string[] = []

for (const line of lines) {

const m = line.match(/(.*)\((.*):(\d+):(\d+)\)/)

if (m) {

const pos = consumer.originalPositionFor({ line: Number(m[3]), column: Number(m[4]) })

result.push(`${pos.source}:${pos.line}:${pos.column}`)

} else {

result.push(line)

}

}

consumer.destroy()

return result

}

统一错误模型type ErrorEventPayload = { name: string; message: string; stack?: string; url: string; ua: string; traceId: string }

function buildErrorEvent(e: Error, url: string, ua: string, traceId: string): ErrorEventPayload {

return {

name: e.name,

message: e.message,

stack: e.stack?.split('\n').slice(0, 15).join('\n'),

url,

ua,

traceId

}

}

运维要点启用采样与窗口节流,避免报告风暴上报前进行字段脱敏与堆栈截断Source Map仅在受控环境解析,避免将源码暴露给客户端通过采样、脱敏与受控解析,可实现安全可控的前端错误报告体系。

点赞(0) 打赏

评论列表 共有 0 条评论

暂无评论
立即
投稿

微信公众账号

微信扫一扫加关注

发表
评论
返回
顶部