Skip to content

Never stop coding. Free MIT AI gateway: one endpoint, 375 providers (150+ free), 1,400+ models Kimi, Claude, GPT, Gemini, GLM, DeepSeek, MiniMax. Works with Claude Code, Codex, Cursor, OpenCode, Cline & Copilot. Quota-aware auto-fallback, RTK+Caveman compression saves 15-95% tokens, MCP/A2A, Desktop/PWA. Built by 900+ contributors

2.0 KB
Raw Blame
// Extracted from proxyFetch.ts (frozen file-size baseline — #14309) so the
// transport-error diagnostics built there can be redacted without growing
// the frozen file.
//
// #10032 keeps the underlying transport failure reason in the propagated
// error for diagnosability, but the raw message can embed a full proxy URL
// — including userinfo credentials — which must never bubble into response
// bodies (#9837, Hard Rule #12).

/**
 * Redact proxy URLs (and any bare `user:pass@host` credential tokens) from an
 * upstream transport-error message before it is surfaced.
 */
export function redactProxyDetailsInMessage(message: string): string {
  return message
    .replace(/\b(?:https?|socks[45][ah]?|socks):\/\/\S+/gi, "[redacted-proxy]")
    .replace(/\b[^\s:@/]+:[^\s@/]*@\S+/g, "[redacted-proxy]");
}

/**
 * Builds the `.proxyFetchDetail` diagnosis for proxyFetch.ts's direct-path
 * (pooled undici dispatcher + native fetch fallback) branches, redacted the
 * same way as the proxy-path message (see redactProxyDetailsInMessage above).
 */
export function describeFallbackFailure(dispatcherCause: string, nativeDetail: string): string {
  return redactProxyDetailsInMessage(`dispatcher=[${dispatcherCause}] native=[${nativeDetail}]`);
}

export const TRANSPORT_CODE_RE = /^[A-Z0-9_:-]{1,64}$/;

/**
 * Reads one level of `error.cause.code`, sanitized with the same allowlist as
 * the transport `code` (`^[A-Z0-9_:-]{1,64}$`). Returns undefined when the
 * cause is absent, not an object, or carries an unsafe code — so no URL,
 * credential token, or free-form message can leak into the propagated error.
 */
export function extractTransportCauseCode(error: unknown): string | undefined {
  const source = error && typeof error === "object" ? (error as Record<string, unknown>) : {};
  const cause = source.cause;
  const raw = cause && typeof cause === "object" ? (cause as { code?: unknown }).code : undefined;
  return typeof raw === "string" && TRANSPORT_CODE_RE.test(raw) ? raw : undefined;
}