Skip to content

fix(claude-accounts): refresh OAuth tokens through Node fetch, not Electron net - #18732

Closed
Tauri-EPO wants to merge 2 commits into
stablyai:mainfrom
Tauri-EPO:Tauri-EPO/claude-oauth-refresh-node-fetch
Closed

Tauri-EPO wants to merge 2 commits into
stablyai:mainfrom
Tauri-EPO:Tauri-EPO/claude-oauth-refresh-node-fetch

Conversation

@Tauri-EPO

@Tauri-EPO Tauri-EPO commented Sep 4, 2026 •

Copy link
Copy Markdown
Contributor

ELI5

Orca renews Claude login tokens by asking Anthropic's token server for a new one. It was asking through Chromium's networking, and that server now answers "rate limited" to Chromium. Nobody noticed because the failure was silent and the claude CLI quietly renewed the active account on its own. Accounts that are saved but not active had nobody to renew them, so their usage bars stayed empty. This PR sends that one request through Node's networking instead, which the server accepts.

What Changed

  • src/main/claude-accounts/oauth-refresh.ts: the refresh_token POST goes through undici's fetch instead of Electron's net.fetch. The module no longer imports electron.
  • Proxy support is kept: the dispatcher is resolved the same way child processes get their proxy env (buildConfiguredProxyEnv), so Orca's configured proxy wins over the shell's and its bypass list replaces NO_PROXY. EnvHttpProxyAgent handles the bypass matching. A SOCKS proxy (which undici cannot tunnel through) logs a warning and connects directly instead of failing the refresh.
  • refreshClaudeOauthCredentials(credentialsJson, now) became refreshClaudeOauthCredentials(credentialsJson, { now?, env?, networkProxySettings? }). The inactive-account usage fetch passes its networkProxySettings; the launch-time refresh keeps env-only proxy resolution, which is what it effectively had before.
  • Non-OK responses drain the body (orca#8695); transport failures log error.cause since undici reports them all as fetch failed.
  • undici added to dependencies (already in the lockfile via @electron/get).
  • Tests: oauth-refresh.test.ts mocks undici and asserts electron.net.fetch is never touched, plus proxy-resolution cases (shell proxy, Orca proxy overriding it, SOCKS fallback, dispatcher closed on both paths). claude-fetcher-managed-account-usage.test.ts routes its token-endpoint mock through undici.

Why

Measured on 1.4.197 (Windows 11, Electron 43), same account, same process, seconds apart:

stack result
globalThis.fetch (Node) in Electron main 200, token rotated
net.fetch (Chromium) 429, server: cloudflare, {"type":"rate_limit_error"}
net.fetch + --disable-http2 --disable-quic 429
net.fetch + User-Agent: claude-code/2.1.0 429

Order does not matter and no proxy is configured, so it is the network stack, not throttling. Using Node's stack makes Orca's refresh behave like the claude CLI's own refresh, which is the environment each account was logged in from. Details and the field evidence (inactive credentials never rewritten for days, 401 on every stored token, rows appearing as soon as tokens were refreshed out of process) are in #18716.

Linked Issue

Fixes #18716

Mechanism behind the blank inactive rows in #14833 (that issue's visibility/persistence points stay open).

Visual Proof

N/A — no UI change. Behavior proof is the live run below.

Testing

Platforms: Windows 11 (local). Not run on macOS/Linux/SSH; the change is main-process only and platform-neutral.

  • Live: bundled the branch's real refreshClaudeOauthCredentials (esbuild, no Electron) and ran it against a managed account whose refresh had been failing in-app for days:

    before: expiresAt=2026-09-05T05:31:59.827Z expiring=false
    refresh OK in 499ms: rotated=true newExpiresAt=2026-09-05T06:44:37.361Z persisted
    

    The same account through net.fetch, seconds earlier: 429.

  • pnpm vitest run src/main/claude-accounts src/main/rate-limits/claude-fetcher-*.test.ts src/main/rate-limits/service-live-claude-usage.test.ts: 28 files, 242 tests passed.

  • pnpm tc:node: clean. oxlint and oxfmt --check on changed files: clean. check:runtime-electron-ratchet and check:max-lines-ratchet: unchanged.

  • pnpm build:desktop: exit 0 (includes the full typecheck).

  • Pre-existing on Windows, unrelated to this diff (fails identically on clean main @ d607a63): service-inactive-account-previews.test.ts › allows usage-panel Fable supplements expects allowUsagePanelSupplement: true, which is darwin/linux-only.

  • I manually tested these changes locally

  • Automated tests added/updated, or explained why not below

AI Disclosure

Diagnosis, implementation, and tests by Claude (Fable 5.1) via Claude Code, driven and verified by me. The live refresh runs above were executed by me on my machine.

Review

Agent code-review summary:

  • Cross-platform: no platform branches added; undici is pure JS and ships in dependencies like the other externalized main-process deps. Windows verified live; macOS keychain path unchanged (only the credentials JSON flows through).
  • SSH / remote: refresh runs on the host that owns the credentials, same as before. Node hosts without Chromium already used Node's stack for other traffic.
  • Agents / integrations: only the Claude OAuth refresh changes. The usage GET (api.anthropic.com) still uses net.fetch, which that endpoint accepts. Codex/Gemini/others untouched.
  • Proxy behavior change: net.fetch followed whatever proxy the default session had applied (settings or env). The new path resolves settings-over-env explicitly per call. Differences: SOCKS proxies fall back to direct (warned), and TLS trust is Node's bundled CA list rather than the OS store, so a TLS-intercepting corporate proxy without NODE_EXTRA_CA_CERTS would fail the refresh. That is the same constraint the claude CLI already has for the same request. Worth a maintainer call whether to add --use-system-ca handling; not done here to keep the PR to one subject.
  • Performance: one EnvHttpProxyAgent per refresh when a proxy is configured, closed in finally. Refresh is rare (token expiry, ~8 h).
  • UI: none.
  • Security: token never logged (status/cause only). Refresh token rotation and atomic persistence unchanged. No new network destinations.

Agent skill upstream boundary

  • Not applicable, or this change follows docs/reference/agent-skill-sharing-upstream-boundary.md and copies or mechanically translates no upstream skill-installer source, tests, fixtures, registry entries, path tables, comments, or documentation.

Notes

Review follow-ups (97bc62f): the refresh honors the caller's AbortSignal, and a configured SOCKS proxy skips the refresh instead of connecting directly around it.

pnpm lint in full and pnpm test in full were not run locally (check:code-quality:changed fails on this machine with ENAMETOOLONG on its own spawn; verify:skill-bundle-manifest is known-stale on a clean tree). CI will cover them.

Checklist

  • This PR is small and focused
  • I explained what changed and why (including ELI5)
  • Before/after screenshots or videos attached for UI changes, or N/A with reason
  • Self-reviewed for correctness, security, and performance
  • Cross-platform, SSH/remote, and path/shortcut impact considered (or N/A)
  • pnpm lint, pnpm typecheck, pnpm test, and pnpm build pass (or CI will cover; local preferred)

Author

X: @EnricoPin

…ectron net

The token endpoint answers 429 to Chromium's network stack while the same
refresh_token grant from Node succeeds, so every Orca-owned refresh failed
silently: inactive managed accounts never got a new token and their usage
rows stayed blank, and the launch-time refresh only worked because the
claude CLI refreshed on its own afterwards.

Route the POST through undici's fetch. Proxy resolution mirrors what child
processes get: Orca's configured proxy wins over the shell's and its bypass
list replaces NO_PROXY; SOCKS proxies fall back to a direct connection with a
warning since undici only tunnels through HTTP proxies. The usage fetch keeps
using net.fetch, which the usage endpoint accepts.

Fixes stablyai#18716
@coderabbitai

coderabbitai Bot commented Sep 4, 2026 •

Copy link
Copy Markdown
Contributor

Review Change Stack

No actionable comments were generated in the recent review. 🎉

ℹ️ Recent review info
⚙️ Run configuration

Configuration used: Repository UI

Review profile: CHILL

Plan: Team

Run ID: 6fdff67c-87bc-46fa-a4ee-447dd9fa0f11

📥 Commits

Reviewing files that changed from the base of the PR and between ffe8737 and 97bc62f.

📒 Files selected for processing (3)
  • src/main/claude-accounts/oauth-refresh.test.ts
  • src/main/claude-accounts/oauth-refresh.ts
  • src/main/rate-limits/claude-managed-account-usage.ts
🚧 Files skipped from review as they are similar to previous changes (1)
  • src/main/rate-limits/claude-managed-account-usage.ts

Included review availability: Your plan provides up to 10 included reviews per hour; 9 remain after this review.


📝 Walkthrough

Walkthrough

OAuth credential refreshes now use Node’s undici fetch instead of Electron’s net.fetch. Proxy settings merge with environment values and support HTTP and HTTPS proxies. Unsupported SOCKS proxies cause the refresh to return null with a warning. Caller cancellation propagates to the refresh request. Non-success responses cancel their bodies, and dispatchers close on completion or failure. Tests cover routing, proxy precedence, cancellation, cleanup, and error handling.

Merge Risk: 🔵 Low · up to 97bc6

OAuth refreshes now use Node networking with proxy and cancellation support, but failed token responses may still be unavailable in the required trace diagnostics, limiting supportability when refreshes fail.

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 60.00% which is insufficient. The required threshold is 80.00%. Docstring coverage is scoped to functions touched by this diff. Analyzed 5 functions across 4 files. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (4 passed)
Check name Status Explanation
Linked Issues check ✅ Passed The changes satisfy issue #18716 by using undici for OAuth refreshes, preserving proxy resolution, handling unsupported SOCKS routes safely, logging failures, supporting cancellation, draining non-OK …
Out of Scope Changes check ✅ Passed The changes remain within the linked issue scope. They update OAuth refresh networking, proxy handling, cancellation, error handling, dependency configuration, and related tests without introducing un…
Title check ✅ Passed The title clearly and concisely describes the primary change: moving Claude OAuth token refreshes from Electron's network stack to Node fetch.
Description check ✅ Passed The description follows the required template, explains the change and rationale, links issue #18716, documents testing and limitations, and completes the relevant checklists. It also correctly marks …
  • Fix all pre-merge checks with AI

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Actionable comments posted: 2


ℹ️ Review info
⚙️ Run configuration

Configuration used: Repository UI

Review profile: CHILL

Plan: Team

Run ID: 4e44ede3-87cb-497b-a1a2-0c7e7c74f8eb

📥 Commits

Reviewing files that changed from the base of the PR and between 264c9ed and ffe8737.

⛔ Files ignored due to path filters (1)
  • pnpm-lock.yaml is excluded by !**/pnpm-lock.yaml
📒 Files selected for processing (5)
  • package.json
  • src/main/claude-accounts/oauth-refresh.test.ts
  • src/main/claude-accounts/oauth-refresh.ts
  • src/main/rate-limits/claude-fetcher-managed-account-usage.test.ts
  • src/main/rate-limits/claude-managed-account-usage.ts

Included review availability: Your plan provides up to 10 included reviews per hour; 9 remain after this review.

@pullfrog pullfrog Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Important

The core change is correct and well-tested, but the two refresh entry points now resolve proxies differently in a way that isn't reflected in the PR description — worth resolving before merge — plus one TLS-trust decision to confirm.

Reviewed changes

  • oauth-refresh.ts — swaps Electron net.fetch for undici's fetch (the claude CLI's stack, which the token endpoint accepts), resolves a per-call EnvHttpProxyAgent that prefers Orca's configured proxy over the shell env, and drains non-OK bodies / logs error.cause.
  • claude-managed-account-usage.ts — threads networkProxySettings into the inactive-account refresh.
  • Dependency — adds undici to dependencies (already transitively present).
  • Tests — oauth-refresh.test.ts asserts Node fetch is used (Electron net.fetch throws if touched) and covers proxy resolution, SOCKS fallback, body drain, and dispatcher close; claude-fetcher-managed-account-usage.test.ts routes its token mock through undici.

⚠️ Launch-time refresh loses configured-proxy support that the old path had

The PR description says the launch-time refresh "keeps env-only proxy resolution, which is what it effectively had before." That isn't quite right. Before this PR, both callers ran ensureElectronProxyFromEnvironment({ proxySession: session.defaultSession }), and ensureElectronProxyFromEnvironment re-applies the default session's already-pinned proxy when state.appliedResult is set. applyElectronProxySettings(store.getSettings()) pins Orca's configured proxy on session.defaultSession at startup (main-process-ready-foundation.ts:148), so the old refresh honored Orca's configured proxy, not just the shell env.

Now runtime-auth-managed-credentials.ts:66 calls refreshClaudeOauthCredentials(credentialsJson) with no options, so resolveRefreshDispatcher falls back to process.env and ignores the configured proxy entirely. For a user whose proxy lives only in Orca settings (not the shell env), the launch-time refresh of an about-to-be-activated account now goes direct and may fail, while the usage-fetch path (which passes networkProxySettings) succeeds. Recommend threading networkProxySettings through the runtime-auth service to match, or explicitly accepting the gap in the description.

Technical details
# Launch-time refresh should resolve the configured proxy too

## Affected sites
- src/main/claude-accounts/runtime-auth/runtime-auth-managed-credentials.ts:66 — `refreshClaudeOauthCredentials(credentialsJson)` with no options → env-only.
- src/main/claude-accounts/oauth-refresh.ts:177-180 — `resolveRefreshDispatcher(options.networkProxySettings, options.env ?? process.env)`; `networkProxySettings` is undefined on this path.
- src/main/network/proxy-settings.ts:286-307 — old `ensureElectronProxyFromEnvironment` re-applied `state.appliedResult` (the default session's configured proxy).
- src/main/startup/main-process-ready-foundation.ts:148 — `applyElectronProxySettings(store.getSettings())` pins the configured proxy on the default session.

## Required outcome
- The launch-time refresh resolves the same proxy as the usage-fetch refresh (settings-over-env), or the divergence is an explicit, accepted decision.

## Suggested approach (optional)
- Give `runtime-auth` a `networkProxySettings` resolver (mirroring `RateLimitService.networkProxySettingsResolver`) and pass it into `refreshClaudeOauthCredentials`, or pass `networkProxySettings` down from the caller of `refreshManagedAccountTokenIfNeeded`.

## Open questions for the human (optional)
- Is the launch-time refresh intended to be best-effort/direct-tolerant, or should it be as complete as the usage-fetch path?

ℹ️ Token refresh now trusts Node's bundled CA list, not the OS trust store

Switching from net.fetch to undici changes which certificate authorities validate the TLS handshake: Chromium's net.fetch uses the OS trust store (which includes enterprise roots installed via MDM/keychain), while Node's fetch uses its bundled CA list and ignores the OS store unless NODE_EXTRA_CA_CERTS is set. A user behind a TLS-intercepting corporate proxy whose root is in the OS store but not NODE_EXTRA_CA_CERTS will get a certificate error, and since the refresh returns null on failure, this reproduces the silent-failure symptom this PR fixes.

This is already flagged in the PR body as a maintainer call, so I'm seconding it rather than requesting a change — but note the "same constraint as the claude CLI" framing may be optimistic: recent claude-code builds ship a Bun-based runtime, and Bun trusts the OS store on macOS/Windows, so Orca's refresh would be stricter than the CLI it is now mirroring. Worth verifying before relying on that justification.

Technical details
# Node fetch trusts bundled CAs, not the OS store

## Affected sites
- src/main/claude-accounts/oauth-refresh.ts:184 — `nodeFetch(OAUTH_TOKEN_URL, ...)` uses Node's TLS with the bundled CA list.

## Required outcome
- Decide whether enterprise users behind TLS-intercepting proxies (OS-store roots, no `NODE_EXTRA_CA_CERTS`) must keep working; if so, add system-CA support.

## Suggested approach (optional)
- Plumb `NODE_EXTRA_CA_CERTS` to the exported bundle CA path, or construct a `Dispatcher`/`Agent` that loads OS roots (e.g. via `connect` with `ca`, or a system-CA package) for this one request.

## Open questions for the human (optional)
- Does the `claude` CLI's runtime trust OS CAs on macOS/Windows (Bun does); if so, is matching the CLI actually achieved here?

Pullfrog  | Fix it ➔ | View workflow run | Using DeepSeek Pro (free via Pullfrog for OSS) | 𝕏

…a SOCKS proxy in the refresh

Review follow-ups on stablyai#18732: the refresh request now aborts with the
caller's signal instead of waiting out its own timeout, and a configured
SOCKS proxy (which undici cannot tunnel through) skips the refresh with a
warning instead of connecting directly around the configured egress route.
Tauri-EPO added a commit to Tauri-EPO/orca that referenced this pull request Sep 5, 2026
…stead of a blank row

The inactive-account usage path threw on any OAuth failure and the service
swallowed it without writing a row, so a 401, a 429, or a dead refresh token
all looked like "no data" in the account switcher. The active-account path
already classifies these failures; reuse that classification for inactive
accounts and give the switcher a label for each case.

- OAuth refresh reports why it failed (invalid_grant, rate-limited, rejected,
  network); a dead refresh token becomes a `reauth-required` row without
  spending a usage call.
- The usage GET failure becomes a classified error row (stale-token,
  rate-limited with retry-at, server, network) instead of a throw.
- The service still catches thrown failures, but writes an error row and
  keeps last-known windows through the existing stale policy.
- Inline usage bars say "Sign in to see usage" only for auth failures; a
  throttle reads "Usage temporarily unavailable" and anything else "Usage
  unavailable".

Part of stablyai#14833 (points 3 and 5). Stacked on stablyai#18732.

@pullfrog pullfrog Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

✅ No new issues found.

The two incremental changes — refusing to bypass a SOCKS proxy and wiring caller cancellation into the refresh — are both correct and well-tested. AbortSignal.any matches the established pattern already used in claude-oauth-usage-request.ts and grok-fetcher.ts, and Electron 43's bundled Node supports it.

Reviewed changes

  • SOCKS proxies now refuse to refresh — resolveRefreshRoute returns unsupported-proxy rather than silently going direct, so a configured SOCKS egress is never bypassed; the old token is kept and a warning logged.
  • Caller cancellation threaded through — refreshClaudeOauthCredentials accepts options.signal and combines it with the refresh timeout via AbortSignal.any; claude-managed-account-usage.ts passes its own signal.

ℹ️ Nitpicks

  • The PR description's "What Changed" bullet still says a SOCKS proxy "logs a warning and connects directly instead of failing the refresh", but this commit now refuses the refresh instead — worth updating the description to match.

Pullfrog  | View workflow run | Using DeepSeek Pro (free via Pullfrog for OSS) | 𝕏

@nwparker

Copy link
Copy Markdown
Contributor

Thanks for putting this together, and sorry for the slow turnaround. The area has since been reworked and this is now covered on main by #26801 (per-account CLAUDE_CONFIG_DIR and scoped Keychain items, replacing the old credential swap/OAuth refresh code), so we're closing this as superseded. If you still see the problem on the latest build, please open a fresh report or reopen with a current repro. Thank you for the contribution.

@nwparker nwparker closed this Oct 24, 2026
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.

[Bug]: Claude OAuth token refresh via net.fetch gets 429 from the token endpoint; the same request through Node fetch succeeds

2 participants