@@ -29,7 +29,87 @@ import { join, dirname } from "path";
2929import { homedir , platform } from "os" ;
3030import { createHash , randomBytes } from "crypto" ;
3131import { 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";
58138const OPENAI_ISSUER = "https://auth.openai.com" ;
59139const OPENAI_TOKEN_ENDPOINT = `${ OPENAI_ISSUER } /oauth/token` ;
60140const 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 */
183263let 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 */
196378async 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 */
244429async 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 } ) ;
0 commit comments