Skip to content

fix(oauth): do not persist needsReauth across process restarts - #221

Closed
Wibias wants to merge 29 commits into
lidge-jun:devfrom
Wibias:codex/fix-oauth-needsreauth-not-persisted
Closed

Wibias wants to merge 29 commits into
lidge-jun:devfrom
Wibias:codex/fix-oauth-needsreauth-not-persisted

Conversation

@Wibias

@Wibias Wibias commented Jul 21, 2026

Copy link
Copy Markdown
Contributor

Problem

On Windows (and potentially other platforms), the Anthropic OAuth account was permanently marked needsReauth: true after every reboot, hiding all models until the user manually removed and re-added the account.

Root cause: needsReauth was persisted to auth.json via mutateStore and restored on every load through normalizeAccount. A transient failure during the first refresh attempt after boot — most commonly Windows not yet having network connectivity when ocx start runs — would hit isTerminalRefreshError, call markAccountNeedsReauth(..., true), and write that permanently to disk. The account was then skipped by the token guardian, excluded from /api/models, and the only recovery was removing and re-adding the account (which writes fresh credentials and clears the flag).

Fix

Introduce an in-memory-only Set<string> (inMemoryNeedsReauth) keyed by provider\x00accountId:

  • normalizeAccount no longer copies needsReauth from the JSON file on disk.
  • getAccountSet overlays the in-memory markers when returning account lists, so the guardian sweep, catalog fetches, and CLI all see correct state within a session.
  • markAccountNeedsReauth / markAccountNeedsReauthIfGeneration write to the Set.
  • saveCredential, saveAccountCredential, mergeAccountCredential, removeAccount, removeCredential clear the relevant key from the Set on success.

On each fresh process start the Set is empty, so every OAuth account gets one real refresh attempt regardless of what the previous session recorded. A genuinely revoked token still fails terminally and re-marks itself within the session; a transient boot-time error does not survive a restart.

Behaviour

  • Within a session: needsReauth works exactly as before — terminal failures mark the account and the guardian skips it.
  • Across restarts: the mark is gone. The first refresh attempt after startup either succeeds (valid token) or fails terminally (truly revoked) — no permanent state from a boot-time network hiccup.

Tests

tests/oauth-store-multi.test.ts updated: verifies in-memory visibility, clears on fresh credential save, and confirms needsReauth is absent from the raw JSON on disk.

Closes #209

Accounts marked needsReauth were written back to disk via mutateStore and
restored on every load through normalizeAccount. A transient failure at
boot time — most commonly Windows not having network connectivity yet when
ocx start runs — would trigger a terminal-looking OAuth error, permanently
lock the Anthropic (or any OAuth) account, and drop all models from the
listing until the user manually removed and re-added the account.

The fix introduces an in-memory-only Set<string> (inMemoryNeedsReauth) keyed
by provider+accountId. normalizeAccount no longer copies the flag from disk;
getAccountSet overlays the in-memory markers when returning account lists so
the guardian sweep, catalog fetches, and CLI all see the correct state within
a session. markAccountNeedsReauth/IfGeneration write to the in-memory Set;
saveCredential, saveAccountCredential, mergeAccountCredential, removeAccount,
and removeCredential clear it on success.

On each fresh process start the Set is empty, so every account gets one real
refresh attempt. A genuinely revoked token still fails with the same terminal
error and re-marks itself within the session; a transient boot error does not.

Tests updated: oauth-store-multi covers in-memory visibility, cross-session
clearance, and the absence of needsReauth from the raw JSON on disk.
Three issues found in double-review:

1. Hot-path allocation: getAccountSet previously called set.accounts.map(...)
   on every invocation, even when inMemoryNeedsReauth was empty. Every OAuth
   token resolution and model-listing call goes through getAccountSet, so this
   was unnecessary GC pressure on a hot path. Fixed with an early-exit when
   the Set is empty, and a second short-circuit when no account in the provider
   set is actually marked.

2. markAccountNeedsReauth declared async but had a synchronous body after the
   mutateStore call was removed. The async keyword was a lie — callers that
   awaited it scheduled an unnecessary microtask on every terminal failure.
   Changed to a plain synchronous function. Callers that await it still work
   correctly (await of a non-Promise is a no-op microtask), and TypeScript
   is happy since the return type is now void not Promise<void>.

3. markAccountNeedsReauthIfGeneration was still wrapped in mutateStore to
   perform a generation check before setting the in-memory flag. mutateStore
   acquires the auth.json file lock and rewrites the file — a full disk I/O
   cycle — even though nothing in the store object was being mutated anymore.
   Replaced with a direct getAccountCredential read (no lock, no disk write)
   for the generation comparison. The generation-check semantics are preserved:
   if a concurrent refresh already rotated the credential, credentialGeneration
   will differ and the mark is correctly skipped.

Tests added: markAccountNeedsReauthIfGeneration generation-guard coverage
and no-alloc fast-path verification for getAccountSet.

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: 82a4a52a2a

ℹ️ About Codex in GitHub

Codex has been enabled to automatically review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

When you sign up for Codex through ChatGPT, Codex can also answer questions or update the PR, like "@codex address that feedback".

Comment thread src/oauth/store.ts Outdated
});
// Update in-memory marker (survives until process exit or credential save).
const key = needsReauthKey(provider, accountId);
if (needsReauth) inMemoryNeedsReauth.add(key);

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Only mark accounts that still exist

If a terminal refresh finishes after the user has logged out or removed that account, this now unconditionally leaves an in-memory marker for an account that is no longer in auth.json; the old mutation first looked up the account and became a no-op. Because OAuth account ids are deterministic, a subsequent login of the same identity in the same server process can recreate the same id while the stale marker is still present, causing getAccountSet/listAccounts to overlay needsReauth: true on the freshly saved credential and keep it skipped/hidden until the process restarts.

Useful? React with 👍 / 👎.

Comment thread src/oauth/store.ts
if (!set) return null;
// Overlay in-memory needsReauth markers onto the loaded accounts.
const accounts = set.accounts.map(a =>
inMemoryNeedsReauth.has(needsReauthKey(provider, a.id))

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Drop stale markers after external re-login

When the running proxy has marked an account needsReauth, a user can fix it by running ocx login <provider> in a separate CLI process; that path writes fresh credentials to auth.json and only notifies the proxy about provider config, so this process-local set is never cleared. Because account ids are deterministic, getAccountSet reloads the new credential from disk but still overlays the old marker on the same id, leaving the GUI/API showing the freshly reauthenticated account as needsReauth until the proxy is restarted.

Useful? React with 👍 / 👎.

Comment thread src/oauth/store.ts
if (!account) return;
account.credential = safe;
delete account.needsReauth;
inMemoryNeedsReauth.delete(needsReauthKey(provider, accountId));

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Clear markers only after the credential write succeeds

If the auth.json write fails here (for example due to permissions, disk full, or an atomic-write failure), the process-local needsReauth marker has already been cleared even though the old credential remains on disk and the caller receives an error. In that state the current process will advertise/retry the terminal account as usable until another failure re-marks it; the marker should only be removed after mutateStore has persisted successfully, or be rolled back on write errors.

Useful? React with 👍 / 👎.

lidge-jun added 26 commits July 21, 2026 20:23
…/011/020/021/022/030/031 + 008 cursor-effort research
…njection, cursor effort metadata invariant, vertex discovery diagnostics (#202, #179)
…xistence + post-persist clear

- saveCredential new-identity-append path (set.accounts.push with fresh id) was
  missing inMemoryNeedsReauth.delete(); same deterministic id could carry a stale
  marker overlaid onto a freshly added account in the same process.

- markAccountNeedsReauth now guards the add() behind a store-existence check: if the
  account was removed and re-added under the same deterministic id, the mark from the
  old instance is silently dropped rather than surviving into the new account.

- mergeAccountCredential: moved inMemoryNeedsReauth.delete() outside the mutateStore
  callback so the marker is only cleared after persist() commits to disk. If the write
  fails the account stays marked (safe failure mode) instead of silently losing the
  reauth signal while the old credential still lives on disk.

Fixes two flaky test failures caused by module-level Set state leaking across test
runs when the !set saveCredential path was reached without a prior delete.
@lidge-jun

Copy link
Copy Markdown
Owner

v2.7.31의 a626a5b 및 0de138aa에서 #209를 해결해 main, dev, preview에 배포했습니다. 최종 구현은 generation-safe refresh와 durable refresh intent로 재부팅 및 stale-lock token replay를 함께 처리하는 경로를 택했습니다. 대체 구현으로 superseded되어 닫으며 PR의 분석과 커밋 기록은 유지합니다.

@lidge-jun lidge-jun closed this Jul 21, 2026
@Wibias

Wibias commented Jul 21, 2026 •

Copy link
Copy Markdown
Contributor Author

@lidge-jun Please change ur automatic answers to english again.. Do not always want to use the waterfox built in translator, lol.

@Wibias
Wibias deleted the codex/fix-oauth-needsreauth-not-persisted branch July 25, 2026 07:01
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants