feat(claude-code): spoof TLS fingerprint and stabilize headers for Anthropic
- Add claudeHeaderCache.js to intercept and cache live Claude Code client headers - Forward cached headers dynamically to api.anthropic.com via default.js - Strip first-party identity headers (x-app, claude-code-* beta) for non-Anthropic upstreams - Validate and sanitize tool call IDs to match Anthropic pattern (^[a-zA-Z0-9_-]+$) - Skip thinking blocks when applying cache_control; fix max_tokens buffer (+1024) - Strip cache_control from thinking blocks in openai-to-claude translator - Comment out thoughtSignature in Gemini translator (kept for reference) - Expand .gitignore to match all deploy*.sh variants Co-authored-by: kwanLeeFrmVi <quanle96@outlook.com> Closes #433 Made-with: Cursor
This commit is contained in:
@@ -2,6 +2,7 @@ import { BaseExecutor } from "./base.js";
|
||||
import { PROVIDERS } from "../config/providers.js";
|
||||
import { OAUTH_ENDPOINTS, buildKimiHeaders } from "../config/appConstants.js";
|
||||
import { buildClineHeaders } from "../../src/shared/utils/clineAuth.js";
|
||||
import { getCachedClaudeHeaders } from "../utils/claudeHeaderCache.js";
|
||||
|
||||
export class DefaultExecutor extends BaseExecutor {
|
||||
constructor(provider) {
|
||||
@@ -43,9 +44,41 @@ export class DefaultExecutor extends BaseExecutor {
|
||||
case "gemini":
|
||||
credentials.apiKey ? headers["x-goog-api-key"] = credentials.apiKey : headers["Authorization"] = `Bearer ${credentials.accessToken}`;
|
||||
break;
|
||||
case "claude":
|
||||
credentials.apiKey ? headers["x-api-key"] = credentials.apiKey : headers["Authorization"] = `Bearer ${credentials.accessToken}`;
|
||||
case "claude": {
|
||||
// Overlay live cached headers from real Claude Code client over static defaults.
|
||||
// Static headers (Title-Case) remain as cold-start fallback.
|
||||
const cached = getCachedClaudeHeaders();
|
||||
if (cached) {
|
||||
// Remove Title-Case static keys that conflict with incoming lowercase cached keys
|
||||
for (const lcKey of Object.keys(cached)) {
|
||||
// Build the Title-Case equivalent: "anthropic-version" → "Anthropic-Version"
|
||||
const titleKey = lcKey.replace(/(^|-)([a-z])/g, (_, sep, c) => sep + c.toUpperCase());
|
||||
|
||||
// Special handling for Anthropic-Beta to preserve required flags like OAuth
|
||||
if (lcKey === "anthropic-beta") {
|
||||
const staticBetaStr = headers[titleKey] || headers[lcKey] || "";
|
||||
const staticFlags = new Set(staticBetaStr.split(",").map(f => f.trim()).filter(Boolean));
|
||||
const cachedFlags = new Set(cached[lcKey].split(",").map(f => f.trim()).filter(Boolean));
|
||||
|
||||
// Merge all static flags (which contain oauth, thinking, etc) into the cached ones
|
||||
for (const flag of staticFlags) {
|
||||
cachedFlags.add(flag);
|
||||
}
|
||||
|
||||
cached[lcKey] = Array.from(cachedFlags).join(",");
|
||||
}
|
||||
|
||||
if (titleKey !== lcKey && headers[titleKey] !== undefined) {
|
||||
delete headers[titleKey];
|
||||
}
|
||||
}
|
||||
Object.assign(headers, cached);
|
||||
}
|
||||
credentials.apiKey
|
||||
? (headers["x-api-key"] = credentials.apiKey)
|
||||
: (headers["Authorization"] = `Bearer ${credentials.accessToken}`);
|
||||
break;
|
||||
}
|
||||
case "glm":
|
||||
case "kimi":
|
||||
case "minimax":
|
||||
@@ -83,6 +116,33 @@ export class DefaultExecutor extends BaseExecutor {
|
||||
}
|
||||
}
|
||||
|
||||
// Strip first-party Claude Code identity headers for non-Anthropic anthropic-compatible upstreams
|
||||
if (this.provider?.startsWith?.("anthropic-compatible-")) {
|
||||
const baseUrl = credentials?.providerSpecificData?.baseUrl || "";
|
||||
const isOfficialAnthropic = baseUrl === "" || baseUrl.includes("api.anthropic.com");
|
||||
if (!isOfficialAnthropic) {
|
||||
delete headers["anthropic-dangerous-direct-browser-access"];
|
||||
delete headers["Anthropic-Dangerous-Direct-Browser-Access"];
|
||||
delete headers["x-app"];
|
||||
delete headers["X-App"];
|
||||
// Strip claude-code-20250219 from Anthropic-Beta / anthropic-beta
|
||||
for (const betaKey of ["anthropic-beta", "Anthropic-Beta"]) {
|
||||
if (headers[betaKey]) {
|
||||
const filtered = headers[betaKey]
|
||||
.split(",")
|
||||
.map(s => s.trim())
|
||||
.filter(f => f && f !== "claude-code-20250219")
|
||||
.join(",");
|
||||
if (filtered) {
|
||||
headers[betaKey] = filtered;
|
||||
} else {
|
||||
delete headers[betaKey];
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if (stream) headers["Accept"] = "text/event-stream";
|
||||
return headers;
|
||||
}
|
||||
@@ -197,8 +257,8 @@ export class DefaultExecutor extends BaseExecutor {
|
||||
const kimiHeaders = buildKimiHeaders();
|
||||
const response = await fetch("https://auth.kimi.com/api/oauth/token", {
|
||||
method: "POST",
|
||||
headers: {
|
||||
"Content-Type": "application/x-www-form-urlencoded",
|
||||
headers: {
|
||||
"Content-Type": "application/x-www-form-urlencoded",
|
||||
"Accept": "application/json",
|
||||
...kimiHeaders
|
||||
},
|
||||
|
||||
@@ -21,7 +21,7 @@ export function hasValidContent(msg) {
|
||||
// 2. Merge consecutive same-role messages
|
||||
export function fixToolUseOrdering(messages) {
|
||||
if (messages.length <= 1) return messages;
|
||||
|
||||
|
||||
// Pass 1: Fix assistant messages with tool_use - remove text after tool_use
|
||||
for (const msg of messages) {
|
||||
if (msg.role === "assistant" && Array.isArray(msg.content)) {
|
||||
@@ -30,7 +30,7 @@ export function fixToolUseOrdering(messages) {
|
||||
// Keep only: thinking blocks + tool_use blocks (remove text blocks after tool_use)
|
||||
const newContent = [];
|
||||
let foundToolUse = false;
|
||||
|
||||
|
||||
for (const block of msg.content) {
|
||||
if (block.type === "tool_use") {
|
||||
foundToolUse = true;
|
||||
@@ -43,27 +43,27 @@ export function fixToolUseOrdering(messages) {
|
||||
}
|
||||
// Skip text blocks AFTER tool_use
|
||||
}
|
||||
|
||||
|
||||
msg.content = newContent;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
// Pass 2: Merge consecutive same-role messages
|
||||
const merged = [];
|
||||
|
||||
|
||||
for (const msg of messages) {
|
||||
const last = merged[merged.length - 1];
|
||||
|
||||
|
||||
if (last && last.role === msg.role) {
|
||||
// Merge content arrays
|
||||
const lastContent = Array.isArray(last.content) ? last.content : [{ type: "text", text: last.content }];
|
||||
const msgContent = Array.isArray(msg.content) ? msg.content : [{ type: "text", text: msg.content }];
|
||||
|
||||
|
||||
// Put tool_result first, then other content
|
||||
const toolResults = [...lastContent.filter(b => b.type === "tool_result"), ...msgContent.filter(b => b.type === "tool_result")];
|
||||
const otherContent = [...lastContent.filter(b => b.type !== "tool_result"), ...msgContent.filter(b => b.type !== "tool_result")];
|
||||
|
||||
|
||||
last.content = [...toolResults, ...otherContent];
|
||||
} else {
|
||||
// Ensure content is array
|
||||
@@ -71,7 +71,7 @@ export function fixToolUseOrdering(messages) {
|
||||
merged.push({ role: msg.role, content: [...content] });
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
return merged;
|
||||
}
|
||||
|
||||
@@ -101,7 +101,7 @@ export function prepareClaudeRequest(body, provider = null, apiKey = null) {
|
||||
// Pass 1: remove cache_control + filter empty messages
|
||||
for (let i = 0; i < len; i++) {
|
||||
const msg = body.messages[i];
|
||||
|
||||
|
||||
// Remove cache_control from content blocks
|
||||
if (Array.isArray(msg.content)) {
|
||||
for (const block of msg.content) {
|
||||
@@ -131,19 +131,26 @@ export function prepareClaudeRequest(body, provider = null, apiKey = null) {
|
||||
let lastAssistantProcessed = false;
|
||||
for (let i = filtered.length - 1; i >= 0; i--) {
|
||||
const msg = filtered[i];
|
||||
|
||||
|
||||
if (msg.role === "assistant" && Array.isArray(msg.content)) {
|
||||
// Add cache_control to last block of first (from end) assistant with content
|
||||
// Add cache_control to last non-thinking block of first (from end) assistant with content
|
||||
// thinking/redacted_thinking blocks do not support cache_control
|
||||
if (!lastAssistantProcessed && msg.content.length > 0) {
|
||||
msg.content[msg.content.length - 1].cache_control = { type: "ephemeral" };
|
||||
for (let j = msg.content.length - 1; j >= 0; j--) {
|
||||
const block = msg.content[j];
|
||||
if (block.type !== "thinking" && block.type !== "redacted_thinking") {
|
||||
block.cache_control = { type: "ephemeral" };
|
||||
break;
|
||||
}
|
||||
}
|
||||
lastAssistantProcessed = true;
|
||||
}
|
||||
|
||||
// Handle thinking blocks for Anthropic endpoint only
|
||||
if (provider === "claude") {
|
||||
if (provider === "claude" || provider?.startsWith("anthropic-compatible")) {
|
||||
let hasToolUse = false;
|
||||
let hasThinking = false;
|
||||
|
||||
|
||||
// Always replace signature for all thinking blocks
|
||||
for (const block of msg.content) {
|
||||
if (block.type === "thinking" || block.type === "redacted_thinking") {
|
||||
@@ -189,7 +196,7 @@ export function prepareClaudeRequest(body, provider = null, apiKey = null) {
|
||||
}
|
||||
|
||||
// Apply cloaking for OAuth tokens (billing header + fake user ID)
|
||||
if (provider === "claude" && apiKey) {
|
||||
if ((provider === "claude" || provider?.startsWith("anthropic-compatible")) && apiKey) {
|
||||
body = applyCloaking(body, apiKey);
|
||||
}
|
||||
|
||||
|
||||
@@ -7,19 +7,21 @@ import { DEFAULT_MAX_TOKENS, DEFAULT_MIN_TOKENS } from "../../config/runtimeConf
|
||||
*/
|
||||
export function adjustMaxTokens(body) {
|
||||
let maxTokens = body.max_tokens || DEFAULT_MAX_TOKENS;
|
||||
|
||||
|
||||
// Auto-increase for tool calling to prevent truncated arguments
|
||||
if (body.tools && Array.isArray(body.tools) && body.tools.length > 0) {
|
||||
if (maxTokens < DEFAULT_MIN_TOKENS) {
|
||||
maxTokens = DEFAULT_MIN_TOKENS;
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
// Ensure max_tokens > thinking.budget_tokens (Claude API requirement)
|
||||
// Claude API requires strictly greater, so add buffer instead of using DEFAULT_MAX_TOKENS
|
||||
// which could equal budget_tokens when budget_tokens >= 64000
|
||||
if (body.thinking?.budget_tokens && maxTokens <= body.thinking.budget_tokens) {
|
||||
maxTokens = DEFAULT_MAX_TOKENS;
|
||||
maxTokens = body.thinking.budget_tokens + 1024;
|
||||
}
|
||||
|
||||
|
||||
return maxTokens;
|
||||
}
|
||||
|
||||
|
||||
@@ -1,19 +1,31 @@
|
||||
// Tool call helper functions for translator
|
||||
|
||||
// Generate unique tool call ID
|
||||
// Anthropic tool_use.id must match: ^[a-zA-Z0-9_-]+$
|
||||
const TOOL_ID_PATTERN = /^[a-zA-Z0-9_-]+$/;
|
||||
|
||||
// Generate unique tool call ID (always valid for Anthropic)
|
||||
export function generateToolCallId() {
|
||||
return `call_${Date.now().toString(36)}_${Math.random().toString(36).slice(2, 9)}`;
|
||||
}
|
||||
|
||||
// Ensure all tool_calls have id field and arguments is string (some providers require it)
|
||||
// Sanitize ID to match Anthropic pattern: keep only alphanumeric, underscore, hyphen
|
||||
function sanitizeToolId(id) {
|
||||
if (!id || typeof id !== "string") return null;
|
||||
const sanitized = id.replace(/[^a-zA-Z0-9_-]/g, "");
|
||||
return sanitized.length > 0 ? sanitized : null;
|
||||
}
|
||||
|
||||
// Ensure all tool_calls have valid id field and arguments is string (some providers require it)
|
||||
export function ensureToolCallIds(body) {
|
||||
if (!body.messages || !Array.isArray(body.messages)) return body;
|
||||
|
||||
|
||||
for (const msg of body.messages) {
|
||||
if (msg.role === "assistant" && msg.tool_calls && Array.isArray(msg.tool_calls)) {
|
||||
for (const tc of msg.tool_calls) {
|
||||
if (!tc.id) {
|
||||
tc.id = generateToolCallId();
|
||||
// Validate or regenerate ID for Anthropic compatibility
|
||||
if (!tc.id || !TOOL_ID_PATTERN.test(tc.id)) {
|
||||
const sanitized = sanitizeToolId(tc.id);
|
||||
tc.id = sanitized || generateToolCallId();
|
||||
}
|
||||
if (!tc.type) {
|
||||
tc.type = "function";
|
||||
@@ -24,24 +36,45 @@ export function ensureToolCallIds(body) {
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Validate tool_call_id in tool messages (role: "tool")
|
||||
if (msg.role === "tool" && msg.tool_call_id && !TOOL_ID_PATTERN.test(msg.tool_call_id)) {
|
||||
const sanitized = sanitizeToolId(msg.tool_call_id);
|
||||
msg.tool_call_id = sanitized || generateToolCallId();
|
||||
}
|
||||
|
||||
// Also validate tool_use blocks in content (Claude format)
|
||||
if (Array.isArray(msg.content)) {
|
||||
for (const block of msg.content) {
|
||||
if (block.type === "tool_use" && block.id && !TOOL_ID_PATTERN.test(block.id)) {
|
||||
const sanitized = sanitizeToolId(block.id);
|
||||
block.id = sanitized || generateToolCallId();
|
||||
}
|
||||
// Validate tool_use_id in tool_result blocks
|
||||
if (block.type === "tool_result" && block.tool_use_id && !TOOL_ID_PATTERN.test(block.tool_use_id)) {
|
||||
const sanitized = sanitizeToolId(block.tool_use_id);
|
||||
block.tool_use_id = sanitized || generateToolCallId();
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
return body;
|
||||
}
|
||||
|
||||
// Get tool_call ids from assistant message (OpenAI format: tool_calls, Claude format: tool_use in content)
|
||||
export function getToolCallIds(msg) {
|
||||
if (msg.role !== "assistant") return [];
|
||||
|
||||
|
||||
const ids = [];
|
||||
|
||||
|
||||
// OpenAI format: tool_calls array
|
||||
if (msg.tool_calls && Array.isArray(msg.tool_calls)) {
|
||||
for (const tc of msg.tool_calls) {
|
||||
if (tc.id) ids.push(tc.id);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
// Claude format: tool_use blocks in content
|
||||
if (Array.isArray(msg.content)) {
|
||||
for (const block of msg.content) {
|
||||
@@ -50,19 +83,19 @@ export function getToolCallIds(msg) {
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
return ids;
|
||||
}
|
||||
|
||||
// Check if user message has tool_result for given ids (OpenAI format: role=tool, Claude format: tool_result in content)
|
||||
export function hasToolResults(msg, toolCallIds) {
|
||||
if (!msg || !toolCallIds.length) return false;
|
||||
|
||||
|
||||
// OpenAI format: role = "tool" with tool_call_id
|
||||
if (msg.role === "tool" && msg.tool_call_id) {
|
||||
return toolCallIds.includes(msg.tool_call_id);
|
||||
}
|
||||
|
||||
|
||||
// Claude format: tool_result blocks in user message content
|
||||
if (msg.role === "user" && Array.isArray(msg.content)) {
|
||||
for (const block of msg.content) {
|
||||
@@ -71,26 +104,26 @@ export function hasToolResults(msg, toolCallIds) {
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
// Fix missing tool responses - insert empty tool_result if assistant has tool_use but next message has no tool_result
|
||||
export function fixMissingToolResponses(body) {
|
||||
if (!body.messages || !Array.isArray(body.messages)) return body;
|
||||
|
||||
|
||||
const newMessages = [];
|
||||
|
||||
|
||||
for (let i = 0; i < body.messages.length; i++) {
|
||||
const msg = body.messages[i];
|
||||
const nextMsg = body.messages[i + 1];
|
||||
|
||||
|
||||
newMessages.push(msg);
|
||||
|
||||
|
||||
// Check if this is assistant with tool_calls/tool_use
|
||||
const toolCallIds = getToolCallIds(msg);
|
||||
if (toolCallIds.length === 0) continue;
|
||||
|
||||
|
||||
// Check if next message has tool_result
|
||||
if (nextMsg && !hasToolResults(nextMsg, toolCallIds)) {
|
||||
// Insert tool responses for each tool_call
|
||||
@@ -104,7 +137,7 @@ export function fixMissingToolResponses(body) {
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
body.messages = newMessages;
|
||||
return body;
|
||||
}
|
||||
|
||||
@@ -91,11 +91,16 @@ export function openaiToClaudeRequest(model, body, stream) {
|
||||
for (let i = result.messages.length - 1; i >= 0; i--) {
|
||||
const message = result.messages[i];
|
||||
if (message.role === "assistant" && Array.isArray(message.content) && message.content.length > 0) {
|
||||
const lastBlock = message.content[message.content.length - 1];
|
||||
if (lastBlock) {
|
||||
lastBlock.cache_control = { type: "ephemeral" };
|
||||
break;
|
||||
// Find the last block that can have cache_control (not thinking blocks)
|
||||
const validBlockTypes = ["text", "tool_use", "tool_result", "image"];
|
||||
for (let j = message.content.length - 1; j >= 0; j--) {
|
||||
const block = message.content[j];
|
||||
if (validBlockTypes.includes(block.type)) {
|
||||
block.cache_control = { type: "ephemeral" };
|
||||
break;
|
||||
}
|
||||
}
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -141,13 +146,13 @@ Respond ONLY with the JSON object, no other text.`);
|
||||
|
||||
const toolData = toolType === "function" && tool.function ? tool.function : tool;
|
||||
const originalName = toolData.name;
|
||||
|
||||
|
||||
// Claude OAuth requires prefixed tool names to avoid conflicts
|
||||
const toolName = CLAUDE_OAUTH_TOOL_PREFIX + originalName;
|
||||
|
||||
|
||||
// Store mapping for response translation (prefixed → original)
|
||||
toolNameMap.set(toolName, originalName);
|
||||
|
||||
|
||||
result.tools.push({
|
||||
name: toolName,
|
||||
description: toolData.description || "",
|
||||
@@ -235,6 +240,10 @@ function getContentBlocksFromMessage(msg, toolNameMap = new Map()) {
|
||||
} else if (part.type === "tool_use") {
|
||||
// Tool name already has prefix from tool declarations, keep as-is
|
||||
blocks.push({ type: "tool_use", id: part.id, name: part.name, input: part.input });
|
||||
} else if (part.type === "thinking") {
|
||||
// Include thinking block but strip cache_control (not allowed on thinking blocks)
|
||||
const { cache_control, ...thinkingBlock } = part;
|
||||
blocks.push(thinkingBlock);
|
||||
}
|
||||
}
|
||||
} else if (msg.content) {
|
||||
@@ -297,17 +306,17 @@ function tryParseJSON(str) {
|
||||
// OpenAI -> Claude format for Antigravity (without system prompt modifications)
|
||||
function openaiToClaudeRequestForAntigravity(model, body, stream) {
|
||||
const result = openaiToClaudeRequest(model, body, stream);
|
||||
|
||||
|
||||
// Remove Claude Code system prompt, keep only user's system messages
|
||||
if (result.system && Array.isArray(result.system)) {
|
||||
result.system = result.system.filter(block =>
|
||||
result.system = result.system.filter(block =>
|
||||
!block.text || !block.text.includes("You are Claude Code")
|
||||
);
|
||||
if (result.system.length === 0) {
|
||||
delete result.system;
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
// Strip prefix from tool names for Antigravity (doesn't use Claude OAuth)
|
||||
if (result.tools && Array.isArray(result.tools)) {
|
||||
result.tools = result.tools.map(tool => {
|
||||
@@ -320,14 +329,14 @@ function openaiToClaudeRequestForAntigravity(model, body, stream) {
|
||||
return tool;
|
||||
});
|
||||
}
|
||||
|
||||
|
||||
// Strip prefix from tool_use in messages
|
||||
if (result.messages && Array.isArray(result.messages)) {
|
||||
result.messages = result.messages.map(msg => {
|
||||
if (!msg.content || !Array.isArray(msg.content)) {
|
||||
return msg;
|
||||
}
|
||||
|
||||
|
||||
const updatedContent = msg.content.map(block => {
|
||||
if (block.type === "tool_use" && block.name && block.name.startsWith(CLAUDE_OAUTH_TOOL_PREFIX)) {
|
||||
return {
|
||||
@@ -337,11 +346,11 @@ function openaiToClaudeRequestForAntigravity(model, body, stream) {
|
||||
}
|
||||
return block;
|
||||
});
|
||||
|
||||
|
||||
return { ...msg, content: updatedContent };
|
||||
});
|
||||
}
|
||||
|
||||
|
||||
return result;
|
||||
}
|
||||
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
import { register } from "../index.js";
|
||||
import { FORMATS } from "../formats.js";
|
||||
import { DEFAULT_THINKING_GEMINI_SIGNATURE } from "../../config/defaultThinkingSignature.js";
|
||||
// import { DEFAULT_THINKING_GEMINI_SIGNATURE } from "../../config/defaultThinkingSignature.js";
|
||||
import { ANTIGRAVITY_DEFAULT_SYSTEM } from "../../config/appConstants.js";
|
||||
import { openaiToClaudeRequestForAntigravity } from "./openai-to-claude.js";
|
||||
|
||||
@@ -102,16 +102,16 @@ function openaiToGeminiBase(model, body, stream) {
|
||||
} else if (role === "assistant") {
|
||||
const parts = [];
|
||||
|
||||
// Thinking/reasoning → thought part with signature
|
||||
// Thinking/reasoning → thought part
|
||||
if (msg.reasoning_content) {
|
||||
parts.push({
|
||||
thought: true,
|
||||
text: msg.reasoning_content
|
||||
});
|
||||
parts.push({
|
||||
thoughtSignature: DEFAULT_THINKING_GEMINI_SIGNATURE,
|
||||
text: ""
|
||||
});
|
||||
// parts.push({
|
||||
// thoughtSignature: DEFAULT_THINKING_GEMINI_SIGNATURE,
|
||||
// text: ""
|
||||
// });
|
||||
}
|
||||
|
||||
if (content) {
|
||||
@@ -128,7 +128,7 @@ function openaiToGeminiBase(model, body, stream) {
|
||||
|
||||
const args = tryParseJSON(tc.function?.arguments || "{}");
|
||||
parts.push({
|
||||
thoughtSignature: DEFAULT_THINKING_GEMINI_SIGNATURE,
|
||||
// thoughtSignature: DEFAULT_THINKING_GEMINI_SIGNATURE,
|
||||
functionCall: {
|
||||
id: tc.id,
|
||||
name: sanitizeGeminiFunctionName(tc.function.name),
|
||||
|
||||
69
open-sse/utils/claudeHeaderCache.js
Normal file
69
open-sse/utils/claudeHeaderCache.js
Normal file
@@ -0,0 +1,69 @@
|
||||
/**
|
||||
* Singleton cache for real Claude Code client headers.
|
||||
* Captures headers from authentic Claude Code requests and makes them available
|
||||
* for forwarding to api.anthropic.com, replacing static hardcoded values.
|
||||
*/
|
||||
|
||||
const CLAUDE_IDENTITY_HEADERS = [
|
||||
"user-agent",
|
||||
"anthropic-beta",
|
||||
"anthropic-version",
|
||||
"anthropic-dangerous-direct-browser-access",
|
||||
"x-app",
|
||||
"x-stainless-helper-method",
|
||||
"x-stainless-retry-count",
|
||||
"x-stainless-runtime-version",
|
||||
"x-stainless-package-version",
|
||||
"x-stainless-runtime",
|
||||
"x-stainless-lang",
|
||||
"x-stainless-arch",
|
||||
"x-stainless-os",
|
||||
"x-stainless-timeout",
|
||||
"package-version",
|
||||
"runtime-version",
|
||||
"os",
|
||||
"arch",
|
||||
];
|
||||
|
||||
let cachedHeaders = null;
|
||||
|
||||
/**
|
||||
* Detect if request headers look like a real Claude Code client.
|
||||
* @param {object} headers - Lowercase header key/value object
|
||||
*/
|
||||
function isClaudeCodeClient(headers) {
|
||||
const ua = (headers["user-agent"] || "").toLowerCase();
|
||||
const xApp = (headers["x-app"] || "").toLowerCase();
|
||||
return ua.includes("claude-cli") || ua.includes("claude-code") || xApp === "cli";
|
||||
}
|
||||
|
||||
/**
|
||||
* Store Claude Code identity headers if this looks like a real client request.
|
||||
* Called at the entry point before any translation/forwarding.
|
||||
* @param {object} headers - Lowercase header key/value object (from request.headers.entries())
|
||||
*/
|
||||
export function cacheClaudeHeaders(headers) {
|
||||
if (!headers || typeof headers !== "object") return;
|
||||
if (!isClaudeCodeClient(headers)) return;
|
||||
|
||||
const captured = {};
|
||||
for (const key of CLAUDE_IDENTITY_HEADERS) {
|
||||
if (headers[key] !== undefined && headers[key] !== null) {
|
||||
captured[key] = headers[key];
|
||||
}
|
||||
}
|
||||
|
||||
if (Object.keys(captured).length > 0) {
|
||||
cachedHeaders = captured;
|
||||
console.log(`[ClaudeHeaders] Cached ${Object.keys(captured).length} identity headers from Claude Code client`);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Get the most recently cached Claude Code identity headers.
|
||||
* Returns null if no authentic client request has been seen yet (cold start).
|
||||
* @returns {object|null}
|
||||
*/
|
||||
export function getCachedClaudeHeaders() {
|
||||
return cachedHeaders;
|
||||
}
|
||||
@@ -85,11 +85,11 @@ function getEnvProxyUrl(targetUrl) {
|
||||
|
||||
if (protocol === "https:") {
|
||||
return process.env.HTTPS_PROXY || process.env.https_proxy ||
|
||||
process.env.ALL_PROXY || process.env.all_proxy;
|
||||
process.env.ALL_PROXY || process.env.all_proxy;
|
||||
}
|
||||
|
||||
return process.env.HTTP_PROXY || process.env.http_proxy ||
|
||||
process.env.ALL_PROXY || process.env.all_proxy;
|
||||
process.env.ALL_PROXY || process.env.all_proxy;
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -100,7 +100,7 @@ function normalizeProxyUrl(proxyUrl) {
|
||||
if (!normalizedInput) return null;
|
||||
|
||||
try {
|
||||
// eslint-disable-next-line no-new
|
||||
|
||||
new URL(normalizedInput);
|
||||
return normalizedInput;
|
||||
} catch {
|
||||
|
||||
Reference in New Issue
Block a user