Skip to content

Commit 67b318e

Browse files
authored
fix: dynamic OAuth User-Agent detection and curl-based token endpoints (#5371)
* fix: dynamic OAuth User-Agent detection and curl-based token endpoints - Replace hardcoded claude-cli/2.1.80 and opencode/1.2.27 User-Agent strings with runtime detection from installed CLIs (GH#18329) - Switch Anthropic and OpenAI token endpoint calls from fetch() to curl via execFileSync to prevent Bun from injecting Origin, Referer, and Sec-Fetch-* headers that cause 429 rate limiting - Add Claude Code CLI to tool-version-check.sh for auto-update so the detected version stays current - Export getAnthropicUserAgent() for provider-auth.mjs consumption Refs: anomalyco/opencode#18329, vinzabe/PERMANENT-opencode-anthropic-oauth-fix * fix: address review feedback — consistent return types and explicit User-Agent - Remove Anthropic fallback from curlTokenEndpoint — callers must always specify User-Agent explicitly (Gemini review) - Replace Response() with mock Response-like objects in cooldown gates for consistent return types across all code paths (CodeRabbit + Gemini) * fix: address CodeRabbit review — stdin body, header capture, execFileSync probes - Pass OAuth body via stdin (--data-binary @-) instead of argv to keep refresh_token/authorization_code off ps/proc command line - Capture response headers with curl -i and parse Retry-After for accurate cooldown timing instead of hardcoded defaults - Switch version detection to execFileSync with stdio config for cross-platform safety (Windows has no 2>/dev/null or ||) - Sanitize error logging to exclude request body content
1 parent 6faa8fa commit 67b318e

3 files changed

Lines changed: 214 additions & 24 deletions

File tree

‎.agents/plugins/opencode-aidevops/oauth-pool.mjs‎

Lines changed: 211 additions & 22 deletions
Original file line numberDiff line numberDiff line change
@@ -29,7 +29,87 @@ import { join, dirname } from "path";
2929
import { homedir, platform } from "os";
3030
import { createHash, randomBytes } from "crypto";
3131
import { createServer } from "http";
32-
import { execSync, spawn } from "child_process";
32+
import { execSync, execFileSync, spawn } from "child_process";
33+
34+
// ---------------------------------------------------------------------------
35+
// Dynamic CLI version detection (GH#18329 fix)
36+
//
37+
// Anthropic blanket-rejects token endpoint requests with unrecognised
38+
// User-Agent strings (429). Hardcoding the version means we silently break
39+
// when the CLI updates. Detect at module load time (~50ms), cache for the
40+
// process lifetime, fall back to a known-good version if the CLI isn't found.
41+
//
42+
// Bun's fetch() also injects Origin, Referer, and Sec-Fetch-* headers that
43+
// Anthropic rate-limits on. Token endpoint calls use execSync("curl ...")
44+
// instead of fetch() to send exactly the headers we specify — nothing more.
45+
// See: https://github.com/vinzabe/PERMANENT-opencode-anthropic-oauth-fix
46+
// ---------------------------------------------------------------------------
47+
48+
const FALLBACK_CLAUDE_VERSION = "2.1.80";
49+
const FALLBACK_OPENCODE_VERSION = "1.2.27";
50+
51+
/**
52+
* Detect the installed Claude CLI version.
53+
* Uses execFileSync (no shell) to avoid metacharacter issues on Windows
54+
* and maintain consistency with curlTokenEndpoint().
55+
* Returns just the version number (e.g. "2.1.80").
56+
* @returns {string}
57+
*/
58+
function detectClaudeCliVersion() {
59+
try {
60+
const raw = execFileSync("claude", ["--version"], {
61+
timeout: 3000,
62+
encoding: "utf-8",
63+
stdio: ["ignore", "pipe", "ignore"],
64+
}).trim();
65+
// Output is like "2.1.80 (Claude Code)" or just "2.1.80"
66+
const match = raw.match(/^(\d+\.\d+\.\d+)/);
67+
if (match) return match[1];
68+
} catch {
69+
// CLI not installed or timed out
70+
}
71+
return FALLBACK_CLAUDE_VERSION;
72+
}
73+
74+
/**
75+
* Detect the installed OpenCode CLI version.
76+
* Tries "opencode" first, then "oc" as fallback.
77+
* Uses execFileSync (no shell) for cross-platform safety.
78+
* Returns just the version number (e.g. "1.2.27").
79+
* @returns {string}
80+
*/
81+
function detectOpenCodeVersion() {
82+
for (const bin of ["opencode", "oc"]) {
83+
try {
84+
const raw = execFileSync(bin, ["--version"], {
85+
timeout: 3000,
86+
encoding: "utf-8",
87+
stdio: ["ignore", "pipe", "ignore"],
88+
}).trim();
89+
const match = raw.match(/^(\d+\.\d+\.\d+)/);
90+
if (match) return match[1];
91+
} catch {
92+
// Try next binary
93+
}
94+
}
95+
return FALLBACK_OPENCODE_VERSION;
96+
}
97+
98+
// Detect once at module load — cached for process lifetime
99+
const DETECTED_CLAUDE_VERSION = detectClaudeCliVersion();
100+
const DETECTED_OPENCODE_VERSION = detectOpenCodeVersion();
101+
const ANTHROPIC_USER_AGENT = `claude-cli/${DETECTED_CLAUDE_VERSION} (external, cli)`;
102+
103+
console.error(`[aidevops] OAuth pool: detected Claude CLI v${DETECTED_CLAUDE_VERSION}, OpenCode v${DETECTED_OPENCODE_VERSION}`);
104+
105+
/**
106+
* Get the dynamically-detected Anthropic User-Agent string.
107+
* Exported for use by provider-auth.mjs on API requests.
108+
* @returns {string}
109+
*/
110+
export function getAnthropicUserAgent() {
111+
return ANTHROPIC_USER_AGENT;
112+
}
33113

34114
// ---------------------------------------------------------------------------
35115
// Constants
@@ -58,7 +138,7 @@ const OPENAI_CLIENT_ID = "app_EMoamEEZ73f0CkXaXp7hrann";
58138
const OPENAI_ISSUER = "https://auth.openai.com";
59139
const OPENAI_TOKEN_ENDPOINT = `${OPENAI_ISSUER}/oauth/token`;
60140
const OPENAI_OAUTH_AUTHORIZE_URL = `${OPENAI_ISSUER}/oauth/authorize`;
61-
const OPENCODE_USER_AGENT = "opencode/1.2.27";
141+
const OPENCODE_USER_AGENT = `opencode/${DETECTED_OPENCODE_VERSION}`;
62142
/** OpenAI uses a local redirect server at port 1455 for its built-in flow.
63143
* For the pool's add-account flow we use the same redirect URI so the
64144
* authorization code can be pasted back into the terminal prompt. */
@@ -182,16 +262,118 @@ let openaiTokenEndpointCooldownUntil = 0;
182262
*/
183263
let cursorProxyCooldownUntil = 0;
184264

265+
/**
266+
* Execute a curl request to a token endpoint, returning a Response-like object.
267+
*
268+
* Uses curl instead of fetch() because Bun's fetch injects Origin, Referer,
269+
* and Sec-Fetch-* headers automatically. Anthropic's token endpoint
270+
* rate-limits/blocks requests with these extra browser-like headers (429).
271+
* curl only sends exactly the headers we specify.
272+
*
273+
* See: https://github.com/vinzabe/PERMANENT-opencode-anthropic-oauth-fix (Bug 3)
274+
*
275+
* @param {string} url - Token endpoint URL
276+
* @param {Object} options - { headers: Record<string,string>, body: string, contentType?: string }
277+
* @param {string} context - description for logging
278+
* @returns {{ ok: boolean, status: number, statusText: string, headers: { get(k: string): string|null }, json(): Promise<any>, text(): Promise<string> }}
279+
*/
280+
function curlTokenEndpoint(url, options, context) {
281+
const args = [
282+
"-sS", // silent but show errors
283+
"-i", // include response headers in output
284+
"-w", "\n%{http_code}", // append HTTP status on last line
285+
"-X", "POST",
286+
"-H", `Content-Type: ${options.contentType || "application/json"}`,
287+
"-H", `User-Agent: ${options.headers["User-Agent"]}`,
288+
"--data-binary", "@-", // read body from stdin (keeps secrets off argv/ps)
289+
"--max-time", "15", // hard timeout
290+
url,
291+
];
292+
293+
try {
294+
// Use execFileSync (no shell) to avoid metacharacter issues with
295+
// parentheses in User-Agent. Body is passed via stdin to keep
296+
// OAuth secrets (refresh_token, authorization_code) off the process
297+
// command line where they'd be visible via ps/proc.
298+
const raw = execFileSync("curl", args, {
299+
encoding: "utf-8",
300+
timeout: 20_000,
301+
input: options.body,
302+
});
303+
304+
// Output format with -i: headers\r\n\r\nbody\n<http_code>
305+
// Last line is the HTTP status code from -w
306+
const lines = raw.trimEnd().split("\n");
307+
const statusCode = parseInt(lines.pop(), 10) || 500;
308+
const fullOutput = lines.join("\n");
309+
310+
// Split headers from body at the blank line (\r\n\r\n)
311+
const headerBodySplit = fullOutput.indexOf("\r\n\r\n");
312+
let responseHeaders = {};
313+
let responseBody = fullOutput;
314+
315+
if (headerBodySplit !== -1) {
316+
const headerBlock = fullOutput.substring(0, headerBodySplit);
317+
responseBody = fullOutput.substring(headerBodySplit + 4);
318+
319+
// Parse response headers into a case-insensitive map
320+
for (const line of headerBlock.split("\r\n")) {
321+
const colonIdx = line.indexOf(":");
322+
if (colonIdx > 0) {
323+
const key = line.substring(0, colonIdx).trim().toLowerCase();
324+
const value = line.substring(colonIdx + 1).trim();
325+
responseHeaders[key] = value;
326+
}
327+
}
328+
}
329+
330+
const statusText = statusCode === 200 ? "OK"
331+
: statusCode === 429 ? "Too Many Requests"
332+
: statusCode === 401 ? "Unauthorized"
333+
: statusCode === 400 ? "Bad Request"
334+
: `HTTP ${statusCode}`;
335+
336+
return {
337+
ok: statusCode >= 200 && statusCode < 300,
338+
status: statusCode,
339+
statusText,
340+
headers: {
341+
get(key) {
342+
return responseHeaders[key.toLowerCase()] ?? null;
343+
},
344+
},
345+
async json() { return JSON.parse(responseBody); },
346+
async text() { return responseBody; },
347+
};
348+
} catch (err) {
349+
// Log only the error code/status — never err.message which may
350+
// contain the request body with OAuth secrets
351+
const reason = err?.code || `exit ${err?.status ?? "unknown"}`;
352+
console.error(`[aidevops] OAuth pool: ${context} curl failed (${reason})`);
353+
return {
354+
ok: false,
355+
status: 500,
356+
statusText: "curl failed",
357+
headers: { get() { return null; } },
358+
async json() { return { error: reason }; },
359+
async text() { return reason; },
360+
};
361+
}
362+
}
363+
185364
/**
186365
* Fetch from the Anthropic token endpoint. Single attempt with 429 cooldown gate.
187366
*
188367
* If a previous call got 429 within the cooldown window, this returns a
189368
* synthetic 429 response immediately — no network request made. This prevents
190369
* every session start from hitting the endpoint and extending the rate limit.
191370
*
371+
* Uses curl instead of fetch() to avoid Bun's automatic header injection
372+
* (Origin, Referer, Sec-Fetch-*) which Anthropic rate-limits on.
373+
*
192374
* @param {string} body - JSON string body
193375
* @param {string} context - description for logging
194-
* @returns {Promise<Response>}
376+
* @returns {Promise<{ ok: boolean, status: number, statusText: string, headers: { get(k: string): string|null }, json(): Promise<any>, text(): Promise<string> }>}
195377
*/
196378
async function fetchTokenEndpoint(body, context) {
197379
// Check cooldown gate — skip the request entirely if rate limited recently
@@ -203,20 +385,22 @@ async function fetchTokenEndpoint(body, context) {
203385
`[aidevops] OAuth pool: ${context} skipped — token endpoint rate limited, cooldown ${remainingMinutes}m remaining. ` +
204386
`Use /model-accounts-pool reset-cooldowns to clear manually.`,
205387
);
206-
return new Response(null, { status: 429, statusText: "Rate Limited (cooldown)" });
388+
return {
389+
ok: false,
390+
status: 429,
391+
statusText: "Rate Limited (cooldown)",
392+
headers: { get() { return null; } },
393+
async json() { return { error: "Rate limited (cooldown)" }; },
394+
async text() { return "Rate limited (cooldown)"; },
395+
};
207396
}
208397

209-
const response = await fetch(ANTHROPIC_TOKEN_ENDPOINT, {
210-
method: "POST",
211-
headers: {
212-
"Content-Type": "application/json",
213-
"User-Agent": "claude-cli/2.1.80 (external, cli)",
214-
},
398+
const response = curlTokenEndpoint(ANTHROPIC_TOKEN_ENDPOINT, {
399+
headers: { "User-Agent": ANTHROPIC_USER_AGENT },
215400
body,
216-
});
401+
}, context);
217402

218403
if (response.status === 429) {
219-
// Parse Retry-After header if present, otherwise use default cooldown
220404
const retryAfter = response.headers.get("retry-after");
221405
const cooldownMs = parseRetryAfterCooldown(retryAfter);
222406
tokenEndpointCooldownUntil = Date.now() + cooldownMs;
@@ -236,10 +420,11 @@ async function fetchTokenEndpoint(body, context) {
236420
/**
237421
* Fetch from the OpenAI token endpoint using form-encoded body (t1548).
238422
* OpenAI uses application/x-www-form-urlencoded, not JSON.
423+
* Uses curl to avoid Bun's automatic header injection.
239424
*
240425
* @param {URLSearchParams} params - Form parameters
241426
* @param {string} context - description for logging
242-
* @returns {Promise<Response>}
427+
* @returns {Promise<{ ok: boolean, status: number, statusText: string, headers: { get(k: string): string|null }, json(): Promise<any>, text(): Promise<string> }>}
243428
*/
244429
async function fetchOpenAITokenEndpoint(params, context) {
245430
const now = Date.now();
@@ -249,17 +434,21 @@ async function fetchOpenAITokenEndpoint(params, context) {
249434
`[aidevops] OAuth pool: ${context} skipped — OpenAI token endpoint rate limited, cooldown ${remainingMinutes}m remaining. ` +
250435
`Use /model-accounts-pool reset-cooldowns to clear manually.`,
251436
);
252-
return new Response(null, { status: 429, statusText: "Rate Limited (cooldown)" });
437+
return {
438+
ok: false,
439+
status: 429,
440+
statusText: "Rate Limited (cooldown)",
441+
headers: { get() { return null; } },
442+
async json() { return { error: "Rate limited (cooldown)" }; },
443+
async text() { return "Rate limited (cooldown)"; },
444+
};
253445
}
254446

255-
const response = await fetch(OPENAI_TOKEN_ENDPOINT, {
256-
method: "POST",
257-
headers: {
258-
"Content-Type": "application/x-www-form-urlencoded",
259-
"User-Agent": OPENCODE_USER_AGENT,
260-
},
447+
const response = curlTokenEndpoint(OPENAI_TOKEN_ENDPOINT, {
448+
headers: { "User-Agent": OPENCODE_USER_AGENT },
261449
body: params.toString(),
262-
});
450+
contentType: "application/x-www-form-urlencoded",
451+
}, context);
263452

264453
if (response.status === 429) {
265454
const retryAfter = response.headers.get("retry-after");
@@ -1545,7 +1734,7 @@ export function createPoolAuthHook(client) {
15451734
const profileResp = await fetch(endpoint, {
15461735
headers: {
15471736
"Authorization": `Bearer ${json.access_token}`,
1548-
"User-Agent": "claude-cli/2.1.80 (external, cli)",
1737+
"User-Agent": ANTHROPIC_USER_AGENT,
15491738
},
15501739
redirect: "follow",
15511740
});

‎.agents/plugins/opencode-aidevops/provider-auth.mjs‎

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -14,7 +14,7 @@
1414
* This module makes the built-in provider use them correctly.
1515
*/
1616

17-
import { ensureValidToken, getAccounts, patchAccount } from "./oauth-pool.mjs";
17+
import { ensureValidToken, getAccounts, patchAccount, getAnthropicUserAgent } from "./oauth-pool.mjs";
1818

1919
const TOKEN_ENDPOINT = "https://platform.claude.com/v1/oauth/token";
2020
const CLIENT_ID = "9d1c250a-e61b-44d9-88ed-5944d1962f5e";
@@ -179,7 +179,7 @@ export function createProviderAuthHook(client) {
179179

180180
requestHeaders.set("authorization", `Bearer ${accessToken}`);
181181
requestHeaders.set("anthropic-beta", mergedBetas);
182-
requestHeaders.set("user-agent", "claude-cli/2.1.80 (external, cli)");
182+
requestHeaders.set("user-agent", getAnthropicUserAgent());
183183
requestHeaders.delete("x-api-key");
184184

185185
// Transform request body

‎.agents/scripts/tool-version-check.sh‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -68,6 +68,7 @@ done
6868
# Format: category|display_name|cli_command|version_flag|package_name|update_command
6969

7070
NPM_TOOLS=(
71+
"npm|Claude Code CLI|claude|--version|@anthropic-ai/claude-code|npm install -g @anthropic-ai/claude-code@latest"
7172
"npm|Augment CLI|auggie|--version|@augmentcode/auggie@prerelease|npm install -g @augmentcode/auggie@prerelease"
7273
"npm|Repomix|repomix|--version|repomix|npm install -g repomix@latest"
7374
"npm|DSPyGround|dspyground|--version|dspyground|npm install -g dspyground@latest"

0 commit comments

Comments
 (0)