Repository navigation
Description
Summary
An Anthropic OAuth refresh that fails before connecting to the token endpoint with getaddrinfo ENOTFOUND api.anthropic.com leaves a durable refresh intent. The next refresh attempt marks the account needsReauth: true and throws OAuthLoginRequiredError without calling the token endpoint again, even when the mocked network has recovered.
This turns a DNS outage into a persistent manual-relogin requirement. It is distinct from an ambiguous timeout after a request might have reached Anthropic: the existing replay guard should remain for those ambiguous outcomes.
Environment
- Client: OpenCodex dashboard / OAuth account resolver
- Area: Authentication and account pool
- Installed package:
@bitkyc08/opencodex2.76.0 - OS: macOS 27.0.1, arm64
- Reproduced with packaged Bun 1.4.0 and global Bun 1.4.2
- Provider: Anthropic,
authMode: "oauth", credentialsource: "oauth"; no model inference is needed
Observed live symptom and limits of attribution
The user reports recurrent Anthropic disconnections. Read-only inspection found:
GET /api/oauth/accounts?provider=anthropic -> HTTP 200
account count: 1
needsReauth: true
paused: false
credential source: oauth
refresh token present: true
access credential expired: true
pending auth.refresh.anthropic.<redacted>.lock.json: present
pending intent generation matches current credential generation: true
The service log also contains repeated TypeError: getaddrinfo ENOTFOUND api.anthropic.com errors from the quota endpoint (/api/oauth/usage) and timeout errors. The log does not record enough information to attribute the outstanding token refresh attempt conclusively to DNS failure rather than an ambiguous timeout or another interrupted attempt. No claim is made that the real saved refresh token is still accepted by Anthropic.
The deterministic reproduction below independently confirms the DNS failure handling defect. The live account and its replay guard were not deleted or modified, and its refresh token was not manually replayed.
Reproduction
Save the script below as anthropic-refresh-repro.mjs and run:
bun anthropic-refresh-repro.mjs /path/to/opencodexThe argument is the installed npm package directory or repository root containing src/. The script runs the real refreshAnthropicAccountWithLock and refreshAnthropicToken implementations against an isolated temporary auth store with fake credentials. Only the HTTP transport is stubbed; no account or external network is needed.
It tests three scenarios, each followed by a simulated recovered token endpoint:
| First failure | Fetch calls across two attempts | Second result | needsReauth | Intent remains |
|---|---|---|---|---|
| Explicit HTTP 503 | 2 | Success | false | false |
| DNS ENOTFOUND | 1 | OAuthLoginRequiredError | true | true |
| Ambiguous timeout (control) | 1 | OAuthLoginRequiredError | true | true |
The script exits 1 at BUG: DNS failure before connecting must not permanently require re-login. Repeated runs produced the same result in under a second.
Code path
In installed 2.76.0, src/oauth/index.ts, refreshAnthropicAccountWithLock:
- Writes the durable intent before calling
def.refresh. - Sets
refreshMayHaveReachedProvider = truebefore entering the adapter. - The adapter in
src/oauth/anthropic.tspropagates transport errors without structured evidence of whether the request could have reached the server. - An ENOTFOUND error is nonterminal, but fails
definitivelyAnswered(error), which accepts only anAnthropicTokenErrorwith HTTP status. The intent remains. - On the next call, the same-generation pending-intent branch marks the account as needing reauthentication before any network call.
- The token guardian subsequently skips accounts marked
needsReauth; the flag and intent also survive process restart.
The same broad dispatch classification and pending-intent branches are present in the inspected upstream source at 06841165 (package version 2.77.0). The runnable reproduction was executed on installed 2.76.0, not on a full checkout of 2.77.0.
Expected behavior / suggested fix scope
Preserve structured evidence of a definitive pre-connection failure in the Anthropic token transport. Clear the corresponding attempt intent through the existing generation-safe cleanup path and allow retry/backoff for that narrow class of failure.
Do not clear intents for every network error: a timeout, dropped connection after dispatch, unreadable successful response, or persistence failure can conceal an already-rotated refresh token. Those cases still need the replay guard. Proxy, redirects, and transport retries must be considered before asserting that no request reached the token endpoint.
Also consider recording a sanitized refresh failure category and distinguishing an unknown refresh outcome from an explicitly rejected grant in the account-health UI. Currently the live state cannot explain which of those caused the reconnect requirement.
Related issue
Issue #209 describes a similar user-visible symptom on an older release. This report concerns the durable-intent / pre-connection failure path in 2.76.0, with a runnable reproduction and an HTTP-503 control.
No secrets, actual account identifiers, email addresses, user paths, or original credential files are included.
Reproduction script
// Run with Bun; argument: installed opencodex package directory or repository root.
// Uses only fake credentials in a temporary directory. No external network calls.
import { mkdtempSync, writeFileSync, rmSync } from 'node:fs';
import { tmpdir } from 'node:os';
import { join, resolve } from 'node:path';
import { pathToFileURL } from 'node:url';
import assert from 'node:assert/strict';
const root = resolve(process.argv[2] ?? '.');
const scratch = mkdtempSync(join(tmpdir(), 'ocx-anthropic-repro-'));
process.env.OPENCODEX_HOME = scratch;
const scenarios = ['http503', 'dns-enotfound', 'ambiguous-timeout'];
const credential = {access:'fake-access',refresh:'fake-refresh',expires:Date.now()-60_000,source:'oauth'};
writeFileSync(join(scratch,'auth.json'),JSON.stringify({anthropic:{activeAccountId:scenarios[0],accounts:scenarios.map(id=>({id,credential}))}}),{mode:0o600});
const realFetch = globalThis.fetch;
try {
const {refreshAnthropicAccountWithLock} = await import(pathToFileURL(join(root,'src/oauth/index.ts')).href);
const {refreshAnthropicToken} = await import(pathToFileURL(join(root,'src/oauth/anthropic.ts')).href);
const {getAccountCredentialWithStatus,readOAuthRefreshIntent} = await import(pathToFileURL(join(root,'src/oauth/store.ts')).href);
const results=[];
for(const scenario of scenarios){
let calls=0;
globalThis.fetch=async url=>{
assert.equal(String(url),'https://api.anthropic.com/v1/oauth/token');
calls++;
if(calls===1){
if(scenario==='http503')return new Response('{"error":"temporarily_unavailable"}',{status:503});
if(scenario==='dns-enotfound')throw Object.assign(new TypeError('getaddrinfo ENOTFOUND api.anthropic.com'),{code:'ENOTFOUND',syscall:'getaddrinfo',hostname:'api.anthropic.com'});
throw new DOMException('The operation timed out.','TimeoutError');
}
return Response.json({access_token:'fake-new-access',refresh_token:'fake-new-refresh',expires_in:3600});
};
const errors=[];
for(let attempt=0;attempt<2;attempt++){
try{await refreshAnthropicAccountWithLock('anthropic',scenario,{refresh:refreshAnthropicToken},credential);errors.push(null);}
catch(e){errors.push(e.name);}
}
const row=getAccountCredentialWithStatus('anthropic',scenario);
results.push({scenario,fetchCalls:calls,errors,needsReauth:row.needsReauth,pendingIntent:!!readOAuthRefreshIntent('anthropic',scenario),recovered:row.credential.access==='fake-new-access'});
}
console.log(JSON.stringify(results,null,2));
assert.equal(results[0].recovered,true,'Control: explicit HTTP 503 should recover');
assert.equal(results[2].pendingIntent,true,'Ambiguous timeout must preserve replay guard');
assert.equal(results[1].recovered,true,'BUG: DNS failure before connecting must not permanently require re-login');
} finally {
globalThis.fetch=realFetch;
rmSync(scratch,{recursive:true,force:true});
}
Activity
Ingwannu commentedon Oct 4, 2026
Confirmed the reported state transition against current trusted
dev33185c2ccf7085f94357d9e56512803949b22cc5, not only installed 2.76.0. I used the actual refresh/store implementations in a detached checkout, fake credentials in private homes, and a fully stubbed token transport on Linux/Bun 1.4.0.The recovered-DNS assertion fails as reported (exit 1); both controls satisfy their assertions. In current
src/oauth/index.ts,definitivelyAnsweredat line 737 accepts only a structured HTTP response, dispatch is conservatively marked beforedef.refreshat line 1010, and known-failure intent cleanup at line 1041 excludes this raw transport error. The next same-generation intent branch refuses without another HTTP call.This independently validates the mocked DNS-handling path. It does not establish the cause of the saved live account state or prove that every ENOTFOUND emitted by a real proxy/redirect/retry transport is pre-dispatch. Please keep the fix narrow: transport-owned evidence of a definitively unsent attempt, generation-safe known-failure cleanup, and regressions preserving unknown-outcome, rotated-token/persistence and superseding-owner guards. Do not delete a live intent or blanket-retry network errors. A change to this refresh contract still needs the required independent boundary review; this reproduction supplies no waiver or approval.
The probe ran sequentially under CPU75%, MemoryHigh1280M/MemoryMax1536M, swap0, Tasks64, IOWeight20, nice10 and a 120s limit, with new private HOME/CODEX_HOME/OPENCODEX_HOME/TMPDIR and Claude config directories. Protected real-home snapshots are unchanged. No actual account/provider call, live repair, UI change or security/privacy scan was performed. The issue remains open; no fix or release is claimed.
atinseau commentedon Oct 4, 2026
Local fix proposal, tested against installed 2.76.0. Thanks for independently confirming the reproduction.
The original reproduction posted above fails before this patch and passes unchanged afterwards. The expanded check also passes through
getValidAccessTokenForAccountwith packaged Bun 1.4.0 (and the refresh-lock seam with Bun 1.4.2).The candidate patch:
requestNotSentevidence only for the structuredENOTFOUND+getaddrinfo+ exact token-endpoint hostname case, caught around the initialfetchonly.redirect: "error"andkeepalive: falsefor the token exchange to avoid classifying a redirect failure or a reused-connection retry as an initial DNS failure.pre-dispatchreason. It does not assign a fake HTTP status.invalid_grantdo not replay the token.A real fetch to a reserved
.invalidname using packaged Bun 1.4.0 produced the same structured error fields as the fixture; no credentials were sent. This verifies the error shape, not every possible proxy/retry transport path.Limits: this is a local candidate, not an independently reviewed upstream fix. Full repository typecheck/privacy suites were unavailable in the installed npm distribution. I have not replayed or deleted the existing live account's uncertain intent, and this patch cannot prove the historical live outage was DNS rather than timeout. Please retain the requested boundary review, particularly for Bun/proxy retry behavior and generation/ownership races.
Patch (relative to 2.76.0):
Local activation validation: after the user completed a fresh OAuth login (the old uncertain token was never replayed), a single real refresh through
refreshAnthropicAccountWithLockrotated credentials, persisted them withneedsReauth: false, left no pending intent, and the new access token received HTTP 200 from Anthropic’s usage endpoint. This validates a normal real refresh after login; it is not an induced real-network-outage test.Ingwannu commentedon Oct 4, 2026
The local candidate is useful additional evidence, but is not yet an upstream fix or independent approval. Please open a focused PR against current
dev33185c2ccf7085f94357d9e56512803949b22cc5, carrying the seven scenarios into permanent repository tests and updating the owning refresh documentation. Keep both test-layout registrations and the existing generation-safe cleanup/ownership regressions intact; the installed-2.76.0 patch is not a substitute for current-source integration.Current Bun fetch documentation describes
keepalive: falseas disabling connection reuse. That supports the intent of the option, but does not by itself prove that every supported-version direct/proxied transport path could not already have dispatched a request before emitting these error fields. Please make the pinned-runtime and proxy/redirect/retry assumptions explicit, and retain refusal for any outcome that cannot be proven unsent. No blanket network-error cleanup or fabricated HTTP status.Your normal real refresh after a fresh login is separate from outage/replay recovery. I have not independently executed this patched candidate, induced a real provider outage, inspected your live account or replayed/deleted its uncertain intent. Required independent refresh-boundary review remains before acceptance; this is correctness triage, not sponsorship, a security scan or permission to change a live account.
fix(oauth): keep the refresh intent on redirects and startup proxies
fix(oauth): release the unread redirect body before refusing
test(oauth): run the direct-DNS refresh case from a proxy-free startup
fix(oauth): release Anthropic refresh intent after a proven-unsent DN…
lidge-jun commentedon Oct 4, 2026
Fixed on
devby #6586 (989bb24), carrying your patch with credit: a refresh intent is released only when a DNS failure proves the request never left the machine; ambiguous outcomes keep the replay guard. Closing manually because PRs targetdev; it ships in the next release. Thank you for the detailed report and patch!atinseau commentedon Oct 5, 2026
Thank you to you for this incredible tool ;)
Update from upstream 2.80.0 while preserving fork integrations (#9)