Skip to content

fix(orca-cloud): report the real cause when cloud sign-in cannot reach the network - #10789

Open
OrcaWin wants to merge 3 commits into
mainfrom
OrcaWin/bug-windows-google-oauth-callback-succeeds-but-c
Open

OrcaWin wants to merge 3 commits into
mainfrom
OrcaWin/bug-windows-google-oauth-callback-succeeds-but-c

Conversation

@OrcaWin

@OrcaWin OrcaWin commented Jul 26, 2026 •

Copy link
Copy Markdown
Collaborator

Fixes #10758

Summary

Signing in to Orca Cloud on Windows completed in the browser, returned to the loopback callback, and then failed with a bare fetch failed. The profile stayed local and nothing in main.trace.ndjson explained why.

The desktop session exchange (POST /v1/desktop/auth/session) ran through bare global fetch. Every transport-level failure — DNS, TLS interception, a refused redirect, a reset socket — surfaces from undici as the identical string TypeError: fetch failed, with the real diagnosis buried in error.cause. connectCurrentOrcaProfile reduces the error to error.message (profile-cloud-service.ts:91) and the renderer prints that verbatim as the toast description, so cause was discarded before it reached the user or the trace file.

This PR:

  1. Routes both cloud clients through Electron net.fetch behind ensureElectronProxyFromEnvironment, via a new orcaCloudFetch in profile-cloud-transport.ts. This matches the existing precedent in jira/client.ts, claude-accounts/oauth-refresh.ts, and rate-limits/claude-fetcher.ts. Chromium's stack honors the OS certificate store and proxy configuration and keeps its own socket pool, so Windows TLS interception and undici's stale keep-alive sockets stop being silent failure modes.
  2. Classifies transport failures into a bounded category — dns, tls, proxy, offline, timeout, redirect, connection-lost, unknown — and surfaces it with the errno / net:: detail. The original error chain is retained as cause and recorded on the span (orcaCloud.operation, transportFailure, transportErrorName, transportErrorDetail), so main.trace.ndjson finally has something actionable.

This addresses suggestions 1–3 from the issue. Suggestion 4 (backend returning a structured error instead of closing the connection) is server-side.

ELI5

Orca asks the sign-in server "here's my one-time code, give me a session." That question was being asked by a phone line that only knows how to say one thing when anything goes wrong: "it didn't work."

Not why. The address book couldn't find the server, the security certificate looked wrong, a corporate proxy hung up, the server tried to forward us somewhere we refuse to follow — all of it came out as the same three words. The detail did exist, tucked inside the error, but the code threw it away before showing anything to the user.

Two changes. First, Orca now uses the same phone line the rest of the app uses (Electron's network stack) — the one that knows about Windows' certificate store, corporate proxies, and doesn't reuse stale connections. Second, when a call fails, Orca now reads the detail before throwing it away and tells you which of the seven things went wrong.

So fetch failed becomes Could not reach Orca Cloud: the TLS handshake failed — a proxy or security tool may be intercepting HTTPS (net::ERR_CERT_AUTHORITY_INVALID).

The bug wasn't that sign-in broke. Sign-in was always going to break on that machine for some environmental reason. The bug is that Orca made it impossible to find out which one.

Screenshots

No visual change. The failure toast already renders result.error as its description, so it now carries the categorized message instead of fetch failed — no renderer changes were needed.

Proof of fix

1. Reproduction of the reported symptom. Driving the shipped options (redirect: 'error', 30s AbortSignal.timeout, bare global fetch) against real local servers that fail three structurally different ways:

connection reset mid-exchange -> {"uiMessage":"fetch failed","name":"TypeError","cause":"SocketError: other side closed","causeCode":"UND_ERR_SOCKET"}
redirect on the session endpoint -> {"uiMessage":"fetch failed","name":"TypeError","cause":"Error: unexpected redirect"}
DNS failure -> {"uiMessage":"fetch failed","name":"TypeError","cause":"Error: getaddrinfo ENOTFOUND ...","causeCode":"ENOTFOUND"}

Three different root causes, one indistinguishable user-facing string — exactly the report. Note the redirect case is deterministic, which fits "reproduces across a full app restart" better than a stale-socket theory does.

2. Same three scenarios, before vs. after, through the production code path:

### connection reset mid-exchange
BEFORE: fetch failed
AFTER  [connection-lost]: Could not reach Orca Cloud: the connection closed before a response arrived (UND_ERR_SOCKET: other side closed)

### redirect on the session endpoint
BEFORE: fetch failed
AFTER  [redirect]: Could not reach Orca Cloud: Orca Cloud redirected the request, and Orca never follows redirects on token endpoints (unexpected redirect)

### DNS failure
BEFORE: fetch failed
AFTER  [dns]: Could not reach Orca Cloud: the Orca Cloud hostname could not be resolved (ENOTFOUND: getaddrinfo ENOTFOUND login.invalid-host-10758.test)

3. The new regression test fails on the shipped code. Reverting only profile-cloud-client.ts to its pre-PR state and re-running:

FAIL  profile-cloud-transport.test.ts > reports a bounded category and never echoes the authorization code
AssertionError: expected TypeError: fetch failed to be an instance of OrcaCloudTransportError
 Tests  1 failed | 13 passed (14)

With the fix restored, all 14 pass. That test drives the real exchangeOrcaCloudAuthCode against a live socket that dies mid-request, so it asserts against a genuine undici error chain rather than a hand-built stand-in.

4. The fix is present in the built bundle — out/main/index.js contains Could not reach Orca Cloud and orcaCloud.transportFailure after pnpm build:electron-vite.

Proof of no regression

The suite has substantial pre-existing failures on this Windows machine, so every number below is a before/after comparison against the same tree, not an absolute count.

Scope Pre-fix baseline With this PR Delta
src/main (1115 files) 31 files / 96 tests failed 31 files / 96 tests failed — identical file list, passing 15111 → 15119 0
11 failing files outside src/main 11 files / 29 tests failed 11 files / 29 tests failed 0
Directly affected (orca-profiles, profile IPC, relay, fetch audit) — 21 files / 115 tests passed —

Full suite: Test Files 44 failed | 3387 passed | 25 skipped, Tests 126 failed | 36325 passed | 446 skipped. Every failing file was enumerated and re-run against the pre-fix parent commit; all fail identically. They are environment-dependent (symlinks, /bin/sh spawn, filesystem watchers, PTY, host-boundary renderer tests) and none live in orca-profiles. The two suite-level "Errors" originate in src/main/ipc/ephemeral-vm.test.ts and src/relay/pty-handler.test.ts, both already in the baselined set.

Other gates:

  • pnpm typecheck (node + cli + web) — exit 0
  • pnpm build:electron-vite — exit 0 (main, preload, renderer)
  • oxlint — exit 0, zero errors
  • lint:switch-exhaustiveness, check:reliability-gates (49 gates), check:max-lines-ratchet, verify:bundled-skill-guides — all pass
  • pnpm lint overall fails at verify:skill-bundle-manifest (stale generated resources/skills/*.json). Verified pre-existing — the same check fails identically on a stashed clean tree, and this PR touches nothing under resources/.

Testing

  • pnpm lint — passes except the pre-existing stale-skill-manifest step documented above
  • pnpm typecheck
  • pnpm test — 126 failures, all verified pre-existing against the parent commit
  • [~] pnpm build — ran build:electron-vite and typecheck; did not run build:native / build:relay / build:cli / build:web, none of which this main-process-only change touches
  • Added or updated high-quality tests

New profile-cloud-transport.test.ts: 12 classification cases spanning both error shapes (undici errno chains and Chromium net::ERR_*), a guard that cloud requests never reach global fetch, and the live-socket repro test. Both existing client test files were migrated from stubGlobal('fetch') to mocking net.fetch.

AI Review Report

Five review rounds over the diff. Each finding below was verified against the code, not eyeballed; all are fixed in follow-up commits on this branch.

Correctness found and fixed

  • TLS failures were misclassified as unknown. Node reports certificate problems as bare CERT_HAS_EXPIRED / CERT_REVOKED / CERT_UNTRUSTED with no err_ prefix, and the pattern required one. Probing the regex directly confirmed four such codes fell through. This is the clock-skew case, a documented adjacent report ([Bug]: Mobile Relay host-proof silently rejects every handshake when the local clock is a few seconds off (no skew tolerance) #10401) — precisely the failure most worth naming. Matching on cert now; DNS is still evaluated first so a hostname containing "cert" cannot be mistaken for a certificate error.
  • net::ERR_ABORTED classified as unknown. That is how Chromium surfaces our own 30s timeout signal. Also gave ERR_ADDRESS_UNREACHABLE and ERR_SOCKET_NOT_CONNECTED a home.
  • Detail could pair an outer error's code with an inner error's message. Now built per chain level.

Simplification

  • The operation label was threaded through five functions and eleven call sites, and OrcaCloudTransportError.operation was never read anywhere. Removed — the span derives the same information from the URL's origin and path. Both cloud clients are back to a one-line change each (3 +- per file, down from 26 +- and 9 +-). Also dropped a codes array the classifier no longer consulted.

Verified rather than assumed

Every test mocks net.fetch, so its real contract was unverified. Ran the actual init against real Electron:

[happy-path] RESOLVED status=200          <- accepts credentials/cache/redirect/signal
[redirect]   THREW  "Attempted to redirect, but redirect policy was 'error'"
[reset]      THREW  net::ERR_EMPTY_RESPONSE
[timeout]    THREW  TimeoutError

Two fixtures were wrong as a result and were corrected to what Electron actually throws: the redirect refusal is an Error, not a TypeError, and a dead socket reports ERR_EMPTY_RESPONSE, not ERR_CONNECTION_RESET.

Cross-platform — net.fetch is Electron-wide, not Windows-specific, and is already the norm here. Classification matches both undici errno chains and Chromium net::ERR_*, so no platform depends on a single error dialect. No path handling, shell invocation, or shortcut label is touched. Not SSH- or workspace-shaped: identical for git worktrees and folder workspaces. Verified every cloud entry point is reached through an IPC handler, hence after app.whenReady(), so session.defaultSession is always safe to touch.

Auth state machine unchanged — reconnect/refresh keys strictly on OrcaCloudRequestError and its status code (isOrcaCloudAuthFailure, runOrgMemberCall, the post-refresh 401 branch). A transport failure was a TypeError before and is an OrcaCloudTransportError now; both are non-OrcaCloudRequestError, so every branch takes the identical path.

Deliberately not done — no retry on transport failures. Retrying would burn the one-time authorization code and replace a truthful "connection reset" with a misleading invalid_code. The undici connection-pool behavior that motivated that suggestion is exactly what moving to net.fetch removes.

Security Audit

One real issue found during review, fixed and now tested.

Electron's net.fetch attaches default-session cookies by default. Undici never did for these cross-origin requests. Switching stacks would therefore have started sending the app's session cookies to first-party token endpoints — a regression introduced by the fix itself. Confirmed against real Electron:

DEFAULT (no credentials option):   cookie header seen: "orca_session=SENSITIVE"
WITH credentials:'omit':           cookie header seen: null

credentials: 'omit' is therefore load-bearing, not cosmetic, and a test now asserts it so it cannot be dropped silently.

Hardening that followed from it. Both invariants that keep a code verifier or refresh token from reaching another origin were call-site conventions — init spread last, so any caller could weaken them with redirect: 'follow' or credentials: 'include'. They are now applied after the spread, so the transport guarantees them instead of trusting eleven call sites to agree. No behavior change today (every call site already passed redirect: 'error'), but the guarantee is structural, with a test that a caller attempting to opt out is overridden. Callers keep control of cache, method, headers, body, and signal.

Reviewed and clear:

  • Secret handling — the failure detail derives solely from transport-layer error text (errno, net:: code, hostname), never from the request body or headers, and is length-capped since it reaches a toast and the trace file. A test asserts the authorization code, verifier, nonce, and state never appear in the message. The span records origin + path with the query string dropped — the only part of a URL that could carry a secret; these endpoints put codes and tokens in the body or Bearer header.
  • Certificate validation — nothing disables verification: no rejectUnauthorized: false, no setCertificateVerifyProc. Trust moves from Node's bundled CA list to the OS store, which is the platform trust model every other first-party integration here already uses.
  • SSRF — request URLs come from OrcaCloudAuthConfig, built from ORCA_CLOUD_* environment variables. No user-controlled input reaches the host or protocol.
  • No new IPC surface, no command execution, no path handling, no deserialization, no new dependencies. The error message crosses the existing IPC result field as a plain string.
  • Follow-up: the relay token exchange in runtime/relay/relay-http-client.ts still uses global fetch and deserves the same treatment, but it runs post-sign-in and belongs to [Bug]: Mobile Relay stays unavailable after a transient desktop broker failure #10273.

Notes

…h the network

The desktop session exchange went through bare global fetch, so every
transport failure — DNS, TLS interception, a refused redirect, a reset
socket — arrived as `TypeError: fetch failed`. connectCurrentOrcaProfile
reduces the error to `error.message`, discarding `error.cause`, which is
where the entire diagnosis lived. Windows users saw "fetch failed" with
nothing in main.trace.ndjson to narrow it down (#10758).

Route both cloud clients through a new orcaCloudFetch that uses Electron
net.fetch behind ensureElectronProxyFromEnvironment, matching the existing
jira/claude-fetcher/oauth-refresh precedent: Chromium's stack honors the OS
certificate store and proxy configuration and keeps its own socket pool.
Transport failures now raise OrcaCloudTransportError carrying a bounded
category (dns, tls, proxy, offline, timeout, redirect, connection-lost) plus
the errno/net:: detail, with the original chain retained as `cause` and
recorded on the span.

redirect: 'error' stays as-is — it keeps code verifiers and refresh tokens
from reaching another origin; the failure is now self-explaining instead of
silent. No retry on transport errors: retrying would burn the one-time
authorization code and replace a truthful "connection reset" with a
misleading invalid_code.

credentials: 'omit' and cache: 'no-store' are pinned so Chromium does not
attach default-session cookies or serve a cached response, neither of which
the previous undici path did.
@coderabbitai

coderabbitai Bot commented Jul 26, 2026 •

Copy link
Copy Markdown
Contributor

Review Change Stack

📝 Walkthrough

Walkthrough

Adds a traced Orca Cloud transport layer using Electron’s network stack, proxy initialization, explicit request defaults, and categorized transport errors. Profile and organization-member clients now route requests through this helper. Tests cover transport failure classification, Electron network routing, socket failures, proxy mocking, and updated global-fetch audit expectations.

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 66.67% which is insufficient. The required threshold is 80.00%. 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 PR addresses #10758 by routing cloud requests through Electron fetch, classifying transport failures, preserving secret redaction, and adding diagnostics/tests.
Out of Scope Changes check ✅ Passed The changes stay focused on Orca Cloud transport, diagnostics, and related tests; no clear unrelated code additions stand out.
Title check ✅ Passed The title clearly matches the main change: improving Orca Cloud sign-in failure reporting and network transport handling.
Description check ✅ Passed The description covers all required template sections and includes detailed summary, testing, review, security, and notes.
✨ Finishing Touches
📝 Generate docstrings
  • Create stacked PR
  • Commit on current branch

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: 1

🧹 Nitpick comments (1)
src/main/orca-profiles/profile-cloud-transport.ts (1)

161-165: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low value

Defaults can be silently overridden by future callers.

credentials: 'omit' and cache: 'no-store' are spread before ...init, so a future caller passing either key would silently defeat the safety guarantees this function's comment promises. Not exploitable today (no caller does this), but worth guarding against regressions.


ℹ️ Review info
⚙️ Run configuration

Configuration used: Repository UI

Review profile: CHILL

Plan: Pro Plus

Run ID: fb620852-4db3-430f-943a-5fae569decf3

📥 Commits

Reviewing files that changed from the base of the PR and between af708d3 and ddf5727.

📒 Files selected for processing (7)
  • src/main/global-fetch-call-site-audit.test.ts
  • src/main/orca-profiles/profile-cloud-client.test.ts
  • src/main/orca-profiles/profile-cloud-client.ts
  • src/main/orca-profiles/profile-cloud-org-members-client.test.ts
  • src/main/orca-profiles/profile-cloud-org-members-client.ts
  • src/main/orca-profiles/profile-cloud-transport.test.ts
  • src/main/orca-profiles/profile-cloud-transport.ts
💤 Files with no reviewable changes (1)
  • src/main/global-fetch-call-site-audit.test.ts

Comment on lines +138 to +174
export async function orcaCloudFetch(
operation: string,
url: string,
init: RequestInit
): Promise<Response> {
return withSpan(
'orcaCloud.request',
async (span) => {
span.setAttribute('orcaCloud.operation', operation)
span.setAttribute('orcaCloud.origin', new URL(url).origin)
await ensureElectronProxyFromEnvironment({
proxySession: session.defaultSession,
probeUrl: url
}).catch((error: unknown) => {
span.addEvent('orcaCloud.proxySetupFailed', {
errorMessage: error instanceof Error ? error.message : String(error)
})
})
try {
// Why the explicit defaults: Chromium would otherwise attach default-
// session cookies and consult the HTTP cache, neither of which the
// previous undici path did. Token endpoints authenticate from the body
// or the Bearer header, so ambient session state stays out of it.
const response = await net.fetch(url, {
credentials: 'omit',
cache: 'no-store',
...init
})
span.setAttribute('orcaCloud.status', response.status)
return response
} catch (error) {
throw recordTransportFailure(span, operation, error)
}
},
{ kind: 'client' }
)
}

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.

🩺 Stability & Availability | 🔴 Critical | ⚡ Quick win

🧩 Analysis chain

🌐 Web query:

Does Electron's session.resolveProxy have a timeout or can it hang on slow PAC script evaluation?

💡 Result:

Electron's session.resolveProxy API does not expose a configurable timeout, and it is theoretically susceptible to delays if the Proxy Auto-Configuration (PAC) script is slow to execute or fetch [1][2]. The resolveProxy method is a wrapper around Chromium's underlying proxy resolution service [1][2]. When called, it requests that the network stack determine the appropriate proxy settings for a given URL [1]. If a PAC script is configured, this process involves fetching the script (if not already cached) and executing the JavaScript contained within it [3][1]. Key considerations regarding this behavior include: 1. Absence of Direct Timeout Control: The official Electron API does not provide a parameter to set a timeout for the resolveProxy operation itself [4][5]. The promise returned by the method will remain pending until the underlying Chromium network stack completes the resolution process or encounters an error [1][2]. 2. Potential for Delays: Because PAC script evaluation can involve network requests (e.g., fetching the PAC file) or complex JavaScript execution, a "slow" or unresponsive PAC server can cause the resolveProxy promise to hang or take a significant amount of time to settle [6][1]. 3. Underlying Mechanism: The resolution is handled by Chromium's net layer, which maintains its own internal logic and timeouts for proxy detection [1][7]. If the environment is misconfigured or the PAC script is invalid, the operation may eventually fail with specific network errors (such as ERR_MANDATORY_PROXY_CONFIGURATION_FAILED), but this is determined by the Chromium engine rather than a user-defined timeout in Electron [3][7]. If you are experiencing hangs with resolveProxy, it is typically recommended to investigate the responsiveness of the PAC script server and the performance of the script itself, as Electron simply reflects the result of this external resolution process [6][1].

Citations:


🏁 Script executed:

#!/bin/bash
set -euo pipefail

# Locate and inspect the referenced function and call sites, without running repo code.
printf 'Tracked files matching profile-cloud-transport.ts and related symbols:\n'
fd -a 'profile-cloud-transport\.ts$|profile-cloud-client\.ts$' . | sed 's#^\./##' | sort

printf '\nReferences:\n'
rg -n "orcaCloudFetch|ensureElectronProxyFromEnvironment|AbortSignal\.timeout|session\.resolveProxy|resolveProxy|must not hang|orc[aA]+Cloud|cloud" src/main src -S || true

printf '\nFile outline/profile-cloud-transport.ts:\n'
ast-grep outline src/main/orca-profiles/profile-cloud-transport.ts || true

printf '\nRelevant source slice:\n'
sed -n '1,230p' src/main/orca-profiles/profile-cloud-transport.ts

Repository: stablyai/orca

Length of output: 50370


🏁 Script executed:

#!/bin/bash
set -euo pipefail

printf 'package Electrons:\n'
rg -n '"electron"|"`@electron/remote`"|electron:' package.json package-lock.json pnpm-lock.yaml yarn.lock 2>/dev/null || true

printf '\nproxy-settings outline:\n'
ast-grep outline src/main/network/proxy-settings.ts || true

printf '\nproxy-settings relevant:\n'
sed -n '1,260p' src/main/network/proxy-settings.ts

printf '\nprofile-cloud-client call-site:\n'
sed -n '150,190p' src/main/orca-profiles/profile-cloud-client.ts

printf '\norca-cloud-service IPC boundary comment/context:\n'
rg -n "ora.*cloud.*IPC|ipcMain|ipcRenderer|stalled server|must not hang|render.*waiting|await.*ipc|timeout|timeoutMs|30s" src/main/orca-profiles src/main/ipc -S

Repository: stablyai/orca

Length of output: 50370


🏁 Script executed:

#!/bin/bash
set -euo pipefail

printf 'Relevant orca-profiles IPC handlers:\n'
sed -n '1,120p' src/main/ipc/orca-profiles.ts
sed -n '180,235p' src/main/ipc/orca-profiles.ts
sed -n '235,290p' src/main/ipc/orca-profiles.ts

printf '\nFocused orcaCloudFetch source:\n'
sed -n '1,190p' src/main/orca-profiles/profile-cloud-transport.ts

printf '\nEnsure timeout races the awaited await point before setting signal on net.fetch:\n'
python3 - <<'PY'
from pathlib import Path
import re
p = Path("src/main/orca-profiles/profile-cloud-transport.ts")
s = p.read_text()
checks = {
    "proxy await exists": "await ensureElectronProxyFromEnvironment" in s,
    "proxy await before net.fetch": s.index("await ensureElectronProxyFromEnvironment") < s.index("net.fetch"),
    "fetch uses init": "await net.fetch(url, {", s.index("fetch(url,") > s.index("net.fetch"),
    "net fetch signal uses init": "signal: init?.signal" in s or "signal: init.signal" in s,
}
for k,v in checks.items():
    print(f"{k}: {v}")
print("contains Proxy.race / race proxy setup:", bool(re.search(r"Promise\.race|Promise\.race\s*\(", s)))
PY

Repository: stablyai/orca

Length of output: 15500


Bound the proxy setup wait or it can bypass the 30s cloud-request timeout.

ensureElectronProxyFromEnvironment can call session.resolveProxy, and callers use AbortSignal.timeout(30_000) only on net.fetch. A stalled PAC/WPAD resolution for https://api.anthropic.com/ can keep the first cloud auth request waiting before the fetch timeout signal is applied. Race the proxy setup against a bounded timeout before returning to postJson.

OrcaWin added 2 commits July 27, 2026 12:45
…peration label

Review follow-ups on the cloud transport wrapper:

- Bare CERT_* codes (CERT_HAS_EXPIRED, CERT_REVOKED, CERT_UNTRUSTED) are how
  Node reports certificate problems, and none of them carry an err_ prefix, so
  they fell through to 'unknown' — including the expiry case a skewed clock
  produces. Match on `cert` instead. DNS is still checked first so a hostname
  containing "cert" cannot be mistaken for a certificate failure.
- net::ERR_ABORTED is how Chromium surfaces the 30s timeout signal, and
  ERR_ADDRESS_UNREACHABLE / ERR_SOCKET_NOT_CONNECTED had no home either.
- Drop the `operation` parameter. It was threaded through five functions and
  eleven call sites, and OrcaCloudTransportError.operation was never read; the
  span now derives the label from the URL's origin and path, which is the same
  information. Both clients are back to a one-line change each.
- Report the deepest chain level's own `code: message` rather than pairing an
  outer code with an inner message, and cap the detail length since it reaches
  a toast and the trace file.

Verified the net.fetch contract against real Electron rather than assuming it:
redirect:'error' refuses with "Attempted to redirect, but redirect policy was
'error'", a dead socket reports net::ERR_EMPTY_RESPONSE, AbortSignal.timeout
raises TimeoutError, and — importantly — net.fetch attaches default-session
cookies unless credentials is 'omit'. That option is load-bearing: without it
this switch would have started sending app cookies to token endpoints, which
undici never did cross-origin. Added a test so it cannot be dropped silently,
and corrected two fixtures to the strings Electron actually throws.
…transport

Both invariants that keep a code verifier or refresh token from reaching
another origin were call-site conventions: `init` spread last, so any caller
could weaken them by passing redirect:'follow' or credentials:'include'.
Now that every cloud request funnels through one wrapper, set them after the
spread so the transport guarantees them instead of trusting eleven call sites
to agree. Callers keep control of cache, method, headers, body, and signal.

No behavior change today — every existing call site already passed
redirect:'error' — but the guarantee is now structural, with a test that a
caller attempting to opt out is overridden.

@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: 1


ℹ️ Review info
⚙️ Run configuration

Configuration used: Repository UI

Review profile: CHILL

Plan: Pro Plus

Run ID: 7c295a33-6713-4c44-aa25-952786a6b330

📥 Commits

Reviewing files that changed from the base of the PR and between ddf5727 and 17a06c8.

📒 Files selected for processing (4)
  • src/main/orca-profiles/profile-cloud-client.ts
  • src/main/orca-profiles/profile-cloud-org-members-client.ts
  • src/main/orca-profiles/profile-cloud-transport.test.ts
  • src/main/orca-profiles/profile-cloud-transport.ts

Comment on lines +165 to +176
// cache:'no-store' keeps Chromium from serving a stale roster on the
// one GET route; a caller may override it.
cache: 'no-store',
...init,
// Set after the spread so no call site can weaken them. Following a
// redirect would re-send a code verifier or refresh token to another
// origin, and net.fetch attaches default-session cookies unless told
// otherwise (verified against Electron) — which undici never did
// cross-origin. These endpoints authenticate from the body or the
// Bearer header, so ambient session state has no business on them.
redirect: 'error',
credentials: 'omit'

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.

🔒 Security & Privacy | 🟠 Major | ⚡ Quick win

Prevent callers from disabling no-store.

...init overwrites cache: 'no-store', so { cache: 'force-cache' } weakens the transport invariant. Spread first, then enforce cache; extend the invariant test with cache: 'force-cache'. Also reduce the surrounding explanation to one concise rationale.

Proposed fix
-          // cache:'no-store' keeps Chromium from serving a stale roster on the
-          // one GET route; a caller may override it.
-          cache: 'no-store',
           ...init,
-          // Set after the spread so no call site can weaken them. Following a
-          // redirect would re-send a code verifier or refresh token to another
-          // origin, and net.fetch attaches default-session cookies unless told
-          // otherwise (verified against Electron) — which undici never did
-          // cross-origin. These endpoints authenticate from the body or the
-          // Bearer header, so ambient session state has no business on them.
+          // Enforce no caching, redirects, or ambient credentials.
+          cache: 'no-store',
           redirect: 'error',
           credentials: 'omit'
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
// cache:'no-store' keeps Chromium from serving a stale roster on the
// one GET route; a caller may override it.
cache: 'no-store',
...init,
// Set after the spread so no call site can weaken them. Following a
// redirect would re-send a code verifier or refresh token to another
// origin, and net.fetch attaches default-session cookies unless told
// otherwise (verified against Electron) — which undici never did
// cross-origin. These endpoints authenticate from the body or the
// Bearer header, so ambient session state has no business on them.
redirect: 'error',
credentials: 'omit'
...init,
// Enforce no caching, redirects, or ambient credentials.
cache: 'no-store',
redirect: 'error',
credentials: 'omit'

Source: Coding guidelines

@1Morganmore

Copy link
Copy Markdown

Operating system

Windows

Orca version

1.4.183

Details

Summary

On Windows 11 x64, Orca repeatedly fails to connect a local profile to Orca Cloud.

The external browser login succeeds and reaches Orca's local callback page:

Signed in to Orca

However, Orca then shows:

Failed to connect profile

fetch failed

The local profile remains unlinked and Orca Relay is unavailable.

Environment

  • OS: Windows 11 x64
  • Orca version: 1.4.183
  • Installation method: Official Orca Updater
  • Terminal daemon version after reboot: 1.4.183
  • Network during reproduction: smartphone hotspot only
  • Wired Ethernet adapter: disabled
  • Tailscale: fully stopped
  • WinHTTP proxy: direct connection
  • HTTP(S)_PROXY environment variables: not configured

The same general Relay flow works on another Windows desktop. The exact Orca version and environment of
that desktop may differ.

Steps to reproduce

  1. Start Orca with a local profile.
  2. Open Settings → Orca Account.
  3. Click Sign in to Orca.
  4. Complete the browser-based sign-in.
  5. Allow the browser to redirect to Orca's local callback:
    http://127.0.0.1:<dynamic-port>/auth/callback
  6. The browser displays Signed in to Orca.
  7. Return to Orca.

Expected behavior

The OAuth code is exchanged for an Orca Cloud session, the local profile is linked, and Orca Relay
becomes available.

Actual behavior

Orca displays:

Failed to connect profile
fetch failed

The profile remains local-only. No Cloud session is saved, and Orca Relay remains unavailable.

This reproduces repeatedly.

Additional diagnostics

The following checks were performed from the same smartphone-hotspot network:

This indicates that DNS, TCP/TLS connectivity, and basic endpoint reachability are working. The failure
appears to occur during the actual post-callback session exchange.

The browser callback succeeds, but:

  • The local profile remains local.
  • No encrypted Cloud session artifact is created.
  • No profile linkage is persisted.
  • main.trace.ndjson does not contain a useful auth, fetch, TLS, DNS, or session-exchange error for the
    failed attempt.

Technical suspicion

The v1.4.183 Cloud client appears to use Node's global fetch for:

POST https://login.onorca.dev/v1/desktop/auth/session

The request uses redirect: 'error' and a 30-second timeout. A transport error, socket reset, TLS/proxy
failure, or refused redirect is surfaced to the UI only as:

TypeError: fetch failed

The underlying error.cause is not exposed or recorded, so the exact transport failure cannot be
identified.

This appears related to:

Requested fix

Please consider:

  1. Routing Cloud authentication requests through Electron's net.fetch or another transport that uses the
    OS proxy and certificate configuration.
  2. Preserving and reporting the nested transport error cause, including:
  • DNS error code
  • TCP/TLS error code
  • proxy source
  • socket error
  • redirect status
  • timeout
  1. Adding a regression test for:
  • successful browser callback followed by session exchange
  • valid-code connection close
  • refused redirect
  • TLS/DNS/socket transport failures

@Minidoracat

Copy link
Copy Markdown
Contributor

Your transport half is now superseded: #15208 routes the same two Cloud clients through Electron's network stack and covers the Relay control/data sockets, artifact requests and the region catalog. After it went dirty, I rebased it onto current main as #16399.

Your cause-reporting half is not superseded, and it is the part that keeps costing people time. profile-cloud-service.ts on main still collapses failures to error.message in three places. So once #16399 lands, the next transport failure of any kind still surfaces as a bare fetch failed with cause discarded — for example the usage requests in main/rate-limits/codex-fetcher.ts, which global-fetch-call-site-audit.test.ts still lists as bare-fetch sites and which fail identically on an intercepted host (measured: UNABLE_TO_VERIFY_LEAF_SIGNATURE, reported to the user as nothing at all).

This branch needs a rebase regardless — its base is ~1840 commits behind main and its last commit is 2026-07-27. If it is rebased down to just the transport-error classification and the cause propagation, it should land without touching anything #16399 changes.

Worth recording here too, since this PR is where the redirect: 'error' / lost-cause analysis started: the reason the cause is worth surfacing is that recovering it by hand is what identified this bug class twice, and both times the string was already in the process. On the host I measured, the discarded cause was UNABLE_TO_VERIFY_LEAF_SIGNATURE — one line that would have replaced weeks of triage across #10758, #13735 and #14865.

This branch has not been deployed

No deployments
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]: Windows Google OAuth callback succeeds but cloud session exchange fails with TypeError: fetch failed

3 participants