// Redact credentials that providers can echo in upstream error bodies. const PATTERNS: Array<{ re: RegExp; replacement: string }> = [ // Provider-specific key shapes, longest/most specific first. { re: /sk-ant-(?:api\d+-)?[A-Za-z0-9_\-]{20,}/g, replacement: 'sk-ant-REDACTED' }, { re: /sk-proj-[A-Za-z0-9_\-]{20,}/g, replacement: 'sk-proj-REDACTED' }, { re: /sk-[A-Za-z0-9]{20,}/g, replacement: 'sk-REDACTED' }, { re: /AIza[0-9A-Za-z_\-]{20,}/g, replacement: 'AIza-REDACTED' }, { re: /xai-[A-Za-z0-9]{20,}/g, replacement: 'xai-REDACTED' }, { re: /gsk_[A-Za-z0-9]{20,}/g, replacement: 'gsk-REDACTED' }, { re: /r8_[A-Za-z0-9]{20,}/g, replacement: 'r8-REDACTED' }, // Generic bearer headers embedded in echoed bodies. { re: /(authorization["':\s]*bearer\s+)[A-Za-z0-9._\-]{16,}/gi, replacement: '$1REDACTED' }, { re: /(x-api-key["':\s]*)[A-Za-z0-9._\-]{16,}/gi, replacement: '$1REDACTED' }, ]; // Redact known credential shapes from arbitrary text. Safe on non-string input // (returns empty string) so callers don't need a null-check. export function redactSecrets(input: string | undefined | null): string { if (!input) return ''; let out = String(input); for (const { re, replacement } of PATTERNS) { out = out.replace(re, replacement); } return out; } // Redact AND truncate to a safe length for surfacing to API clients or logs. // We always redact *before* truncating so a partial match at the boundary // can't re-expose characters after the cut. export function sanitizeUpstreamError(input: string | undefined | null, maxLen = 200): string { const redacted = redactSecrets(input); return redacted.length > maxLen ? redacted.slice(0, maxLen) + '…' : redacted; }