error-sanitizer.ts 6.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176
  1. const MAX_ERROR_MESSAGE_CHARS = 2_048;
  2. const MAX_ERROR_CHAIN_DEPTH = 8;
  3. const claimedErrorObjects = new WeakSet<object>();
  4. export interface SanitizedTelemetryError {
  5. cause?: {
  6. code?: string;
  7. message?: string;
  8. type: string;
  9. };
  10. code?: string;
  11. message?: string;
  12. type: string;
  13. }
  14. export function sanitizeTelemetryError(error: unknown): SanitizedTelemetryError {
  15. const record = objectRecord(error);
  16. const type =
  17. sanitizeErrorIdentifier(
  18. stringValue(record.type) ??
  19. stringValue(record.name) ??
  20. (error instanceof Error ? error.name : undefined),
  21. ) ?? "UnknownError";
  22. const code = sanitizeErrorCode(stringValue(record.code));
  23. const message = sanitizeErrorMessage(
  24. error instanceof Error ? error.message : stringValue(record.message),
  25. );
  26. const chain = errorObjectChain(error);
  27. // 修复原因:链包含输入本身;没有独立嵌套对象时不能把同一个错误重复登记为 cause。
  28. const cause = chain.length > 1 ? sanitizeCause(chain[chain.length - 1]!) : undefined;
  29. return {
  30. ...(cause ? { cause } : {}),
  31. ...(code ? { code } : {}),
  32. ...(message ? { message } : {}),
  33. type,
  34. };
  35. }
  36. /**
  37. * 同一个源异常会沿 Attempt -> Call -> Step -> Turn 冒泡。错误正文只应记录在最靠近
  38. * 来源、最先认领它的 Span;父层继续记录 outcome/failure_stage,但不复制同一份正文。
  39. *
  40. * 包装错误的 cause 链也参与认领:AdapterError(cause=ProviderError) 不会在上层重新覆盖
  41. * Provider Attempt 已记录的原始错误。WeakSet 不延长异常对象生命周期。
  42. */
  43. export function claimSanitizedTelemetryError(error: unknown): SanitizedTelemetryError | undefined {
  44. const objects = errorObjectChain(error);
  45. if (objects.length === 0) return sanitizeTelemetryError(error);
  46. const alreadyClaimed = objects.some((candidate) => claimedErrorObjects.has(candidate));
  47. for (const candidate of objects) claimedErrorObjects.add(candidate);
  48. return alreadyClaimed ? undefined : sanitizeTelemetryError(error);
  49. }
  50. export function sanitizeErrorMessage(value: string | undefined): string | undefined {
  51. if (!value) return undefined;
  52. // 错误可能携带整段响应正文;先做有界截断再正则清洗,避免 Telemetry 为恶意或异常
  53. // Provider 消息承担无界 CPU/内存成本。
  54. const sanitized = value
  55. .slice(0, 4_096)
  56. .replace(/\bhttps?:\/\/[^\s"'<>]+/giu, sanitizeUrl)
  57. .replace(
  58. /(\bauthorization\b["']?\s*[:=])\s*(?:(?:Bearer|Basic)\s+)?[^\s,"'};]+/giu,
  59. "$1 {redacted}",
  60. )
  61. .replace(
  62. /([?&](?:api[_-]?key|token|access[_-]?token|authorization|password|passwd|secret|cookie|session|x-arms-license-key)=)[^&\s]+/giu,
  63. "$1{redacted}",
  64. )
  65. .replace(
  66. /(["']?(?:api[_-]?key|token|access[_-]?token|password|passwd|secret|client[_-]?secret|cookie|set-cookie|session|x-arms-license-key)["']?\s*[:=]\s*["']?)(?!\{redacted\})[^\s,"'};]+/giu,
  67. "$1{redacted}",
  68. )
  69. .replace(/\b(Bearer|Basic)\s+[A-Za-z0-9._~+/=-]+/giu, "$1 {redacted}")
  70. .replace(/\b(?:sk|rk|pk)-[A-Za-z0-9_-]{12,}\b/giu, "{secret}")
  71. .replace(/\bgh[pousr]_[A-Za-z0-9]{20,}\b/gu, "{secret}")
  72. .replace(/\bAKIA[A-Z0-9]{16}\b/gu, "{secret}")
  73. .replace(/\bAIza[0-9A-Za-z_-]{30,}\b/gu, "{secret}")
  74. .replace(/\b[A-Za-z0-9]{4,32}@[0-9a-f]{12,}\b/giu, "{secret}")
  75. .replace(/\b[^/@\s]+@[^/@\s]+\.[^/@\s]+\b/gu, "{email}")
  76. .replace(
  77. /\/(?:Users|home|root|workspace|workspaces|Volumes)\/[^/\s]+(?:\/[^\s:;,)\]}]+)*/gu,
  78. "/{path}",
  79. )
  80. .replace(/\/(?:private\/)?(?:var\/folders|tmp)\/[^\s:;,)\]}]+/gu, "/{path}")
  81. .replace(/\b[A-Za-z]:\\[^\\\s]+(?:\\[^\s:;,)\]}]+)*/gu, "{path}")
  82. .replace(/\p{Cc}+/gu, " ")
  83. .replace(/\s+/gu, " ")
  84. .trim();
  85. return sanitized.slice(0, MAX_ERROR_MESSAGE_CHARS) || undefined;
  86. }
  87. function objectRecord(value: unknown): Record<string, unknown> {
  88. return value && typeof value === "object" && !Array.isArray(value)
  89. ? (value as Record<string, unknown>)
  90. : {};
  91. }
  92. function errorObjectChain(error: unknown): object[] {
  93. const result: object[] = [];
  94. const seen = new Set<object>();
  95. let current = error;
  96. for (
  97. let depth = 0;
  98. depth < MAX_ERROR_CHAIN_DEPTH && current && typeof current === "object";
  99. depth += 1
  100. ) {
  101. if (seen.has(current)) break;
  102. seen.add(current);
  103. result.push(current);
  104. const record = current as Record<string, unknown>;
  105. // 部分流包装器使用 adapterError/error;沿单条优先链复用同一认领机制,避免父 Span 重复记录。
  106. current = [record.cause, record.adapterError, record.error].find(
  107. (nested) => nested && typeof nested === "object",
  108. );
  109. }
  110. return result;
  111. }
  112. function sanitizeCause(record: object): SanitizedTelemetryError["cause"] | undefined {
  113. const value = record as Record<string, unknown>;
  114. const type = sanitizeErrorIdentifier(stringValue(value.type) ?? stringValue(value.name));
  115. const code = sanitizeErrorCode(stringValue(value.code));
  116. const message = sanitizeErrorMessage(stringValue(value.message));
  117. if (!type && !code && !message) return undefined;
  118. return {
  119. ...(code ? { code } : {}),
  120. ...(message ? { message } : {}),
  121. type: type ?? "UnknownError",
  122. };
  123. }
  124. function stringValue(value: unknown): string | undefined {
  125. return typeof value === "string" && value.trim() ? value.trim() : undefined;
  126. }
  127. function sanitizeErrorIdentifier(value: string | undefined): string | undefined {
  128. if (!value) return undefined;
  129. const sanitized = value.trim().slice(0, 128);
  130. return /^[A-Za-z0-9_.:-]+$/u.test(sanitized) ? sanitized : undefined;
  131. }
  132. function sanitizeErrorCode(value: string | undefined): string | undefined {
  133. if (!value) return undefined;
  134. const sanitized = value
  135. .replace(/\p{Cc}+/gu, " ")
  136. .replace(/\s+/gu, " ")
  137. .trim()
  138. .slice(0, 128);
  139. return sanitized || undefined;
  140. }
  141. function sanitizeUrl(value: string): string {
  142. try {
  143. const parsed = new URL(value);
  144. const route = parsed.pathname
  145. .split("/")
  146. .map((segment) => sanitizeRouteSegment(segment))
  147. .join("/");
  148. return `${parsed.protocol}//${parsed.host}${route}`;
  149. } catch {
  150. return "{url}";
  151. }
  152. }
  153. function sanitizeRouteSegment(segment: string): string {
  154. if (!segment) return segment;
  155. if (
  156. /@/u.test(segment) ||
  157. /^\d{7,}$/u.test(segment) ||
  158. /^[0-9a-f]{16,}$/iu.test(segment) ||
  159. /^[0-9a-f]{8}-[0-9a-f-]{27,}$/iu.test(segment)
  160. ) {
  161. return "{segment}";
  162. }
  163. return segment.slice(0, 128);
  164. }