diff --git a/src/proxy.ts b/src/proxy.ts index 955ca45..32b731c 100644 --- a/src/proxy.ts +++ b/src/proxy.ts @@ -16,15 +16,42 @@ function getBaseUrl(): string { return process.env.ANTHROPIC_BASE_URL || 'https://api.anthropic.com'; } -// 提取需要透传的 headers +// 提取需要透传的 headers,并处理认证头转换 function extractProxyHeaders(req: Request): Record { const headers: Record = {}; - for (const header of PROXY_HEADERS) { - const value = req.headers[header]; - if (value) { - headers[header] = Array.isArray(value) ? value[0] : value; + const baseUrl = getBaseUrl(); + + // 如果上游是智谱 AI 等,需要将 x-api-key 转换为 Authorization: Bearer + if (baseUrl.includes('bigmodel.cn') || baseUrl.includes('open.bigmodel')) { + // 优先使用 x-api-key,其次使用 Authorization + const rawHeaders = req.headers as Record; + const xApiKey = rawHeaders['x-api-key']; + const authHeader = rawHeaders['authorization']; + + const apiKey = (Array.isArray(xApiKey) ? xApiKey[0] : xApiKey) || + (Array.isArray(authHeader) ? authHeader[0] : authHeader)?.replace?.(/^Bearer\s+/i, ''); + + if (apiKey) { + headers['authorization'] = `Bearer ${apiKey}`; + } + // 复制其他 headers + for (const header of PROXY_HEADERS) { + if (header === 'x-api-key' || header === 'authorization') continue; + const value = req.headers[header]; + if (value) { + headers[header] = Array.isArray(value) ? value[0] : value; + } + } + } else { + // 标准 Claude API,直接透传 + for (const header of PROXY_HEADERS) { + const value = req.headers[header]; + if (value) { + headers[header] = Array.isArray(value) ? value[0] : value; + } } } + return headers; }