Repository navigation
fix(browser): present Firefox UA on Google auth hosts to end ~1h sign-in staleness - #12884
Conversation
Google binds a signed-in session to the browser identity that created it, so cookies sent under an Electron/Chrome-shaped UA that doesn't match a real first-party browser get flagged by anti-fraud on accounts.google.com and expire within ~1h. Present a Firefox identity scoped to the Google/YouTube sign-in hosts so the user signs in inside the embedded browser and Google issues self-refreshing bound cookies, instead of relying on a UA/cookie shape that goes stale. Applied at both layers that Google probes: the onBeforeSendHeaders request UA (+ stripping sec-ch-ua* client hints, which real Firefox omits) and the per-WebContents UA read by auth-page JS via navigator.userAgent. Scope is the auth hosts only; post-auth app surfaces keep the profile's real Chrome identity. Native-UA profiles opt out of the whole clean-UA path unchanged.
|
Note Reviews pausedIt looks like this branch is under active development. To avoid overwhelming you with review comments due to an influx of new commits, CodeRabbit has automatically paused this review. You can configure this behavior by changing the Use the following commands to manage reviews:
Use the checkboxes below for quick actions:
📝 WalkthroughWalkthroughAdded utilities to identify Google authentication hosts, generate a platform-specific Firefox 140 user agent, remove Chromium client hints, and update user-agent headers. Updated request interception to apply Firefox identity on authentication requests and preserve Chrome hints elsewhere. Added shared viewport user-agent construction for desktop and mobile presets. Updated navigation to switch authentication identity, restore the session identity, and reapply active viewport overrides. Added tests for these behaviors. 🚥 Pre-merge checks | ✅ 5✅ Passed checks (5 passed)
✨ Finishing Touches📝 Generate docstrings
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. Comment |
There was a problem hiding this comment.
🧹 Nitpick comments (1)
src/main/browser/browser-google-auth-ua.ts (1)
1-12: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick winCondense the new explanatory comments.
Keep only the non-obvious invariant in one concise line per site.
src/main/browser/browser-google-auth-ua.ts#L1-L12: replace the module narrative with the auth-host scoping invariant.src/main/browser/browser-session-ua.ts#L30-L32: reduce the comment to why the interceptor must install without Chrome hints.src/main/browser/browser-session-ua.ts#L39-L41: reduce the comment to the Firefox identity and client-hint invariant.src/main/browser/browser-manager.ts#L918-L922: reduce the comment to thenavigator.userAgentsynchronization invariant.As per coding guidelines, comments must be concise, limited to non-obvious information, and preferably one line.
Source: Coding guidelines
ℹ️ Review info
⚙️ Run configuration
Configuration used: Repository UI
Review profile: CHILL
Plan: Pro Plus
Run ID: 56c0dd07-b97f-413a-acfb-2cc3f1edf442
📒 Files selected for processing (5)
src/main/browser/browser-google-auth-ua.test.tssrc/main/browser/browser-google-auth-ua.tssrc/main/browser/browser-manager.tssrc/main/browser/browser-session-registry.test.tssrc/main/browser/browser-session-ua.ts
End-to-end verification in the real Orca appRan the built change in a dev Orca instance (production browser session path, Result — Google served the genuine sign-in form (not the "browser may not be secure" rejection):
Both production layers engaged: the
ScreenshotsGenuine The |
did-start-navigation now reads the guest UA on every main-frame nav; the load-failure replay guest mocks had no WebContents UA surface, so the handler threw. Only touch the session UA when actually leaving an auth host (a Firefox override is in place), give the affected mocks a faithful UA surface, and add direct coverage for the auth-host switch, off-host restore, and native opt-out.
…t identity The CDP Emulation.setUserAgentOverride a viewport preset installs outranks WebContents.setUserAgent for navigator.userAgent and stands across every later navigation, so a preset applied before reaching accounts.google.com pinned navigator.userAgent to the Chrome-shaped preset UA while the request header said Firefox — reintroducing the mismatch this scope removes.
There was a problem hiding this comment.
Actionable comments posted: 1
ℹ️ Review info
⚙️ Run configuration
Configuration used: Repository UI
Review profile: CHILL
Plan: Pro Plus
Run ID: 47372559-ba5e-4922-bea5-7c6b475169bf
📒 Files selected for processing (4)
src/main/browser/browser-manager.test.tssrc/main/browser/browser-manager.tssrc/main/browser/browser-viewport-user-agent.test.tssrc/main/browser/browser-viewport-user-agent.ts
…n URL setViewportOverride and the navigation path both wrote Emulation.setUserAgentOverride for the same tab with no shared ordering, and resolved the tab's host from different sources. Verified against real Electron 43.1.0: did-start-navigation fires while an awaited sendCommand is pending, and getURL() keeps reporting the outgoing page until commit — so a preset resuming mid-navigation resolved the wrong host. Route both writers through viewportOpsByTabId and resolve the host from the in-flight navigation target, held until commit or failure.
There was a problem hiding this comment.
🧹 Nitpick comments (1)
src/main/browser/browser-manager.test.ts (1)
2905-2911: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low valueAlign the comment with the fixed-iteration implementation.
The comment states the helper loops "until the chain is empty rather than guessing a tick count". The body awaits a fixed 20 microtask hops, which is a guessed tick count. Either reword the comment, or drain the actual chain so the guarantee is real.
♻️ Minimal comment fix
- // Why: viewport UA writes are queued on the per-tab chain, so draining it takes more than one - // microtask hop; loop until the chain is empty rather than guessing a tick count. + // Why: viewport UA writes are queued on the per-tab chain, so draining it takes several + // microtask hops; 20 is a generous upper bound for the deepest chain these tests build. async function flushViewportOps(): Promise<void> {
ℹ️ Review info
⚙️ Run configuration
Configuration used: Repository UI
Review profile: CHILL
Plan: Pro Plus
Run ID: 75922bcd-a748-4ab6-8288-af6832a56477
📒 Files selected for processing (2)
src/main/browser/browser-manager.test.tssrc/main/browser/browser-manager.ts
…cking Three corrections to the auth-host UA work: - Popup child windows get attachGuestPolicies but are never in tabIdByWebContentsId, so the native-UA opt-out missed them. A native profile's popup was handed the Firefox UA while its session skips setupClientHintsOverride entirely, sending the raw Electron UA on the wire. Resolve the mode through the popup's owner tab. - setViewportOverride mutated its tracking map before the CDP writes landed. A failed clear stranded a still-standing override with no map entry, so navigation could never correct it. Mutate only after the writes succeed. - Drop the viewport op queue added for a cross-writer race that does not exist: debugger.sendCommand dispatches in call order, so the later write always wins. The real defect was post-await staleness in the resolved URL, which the shared navigation target already fixes.
…port (STA-3514) Delete the import-time UA synthesis entirely instead of patching its version detection. The session now always keeps the engine-derived UA the registry sets at startup (clean or native), for imported and non-imported profiles alike. Why deletion is the fix: - The synthesis read CFBundleShortVersionString, which on forks is a marketing version — Arc imports presented Chrome/1.x and sites rejected the browser as ancient (STA-3514). - Its stated purpose (keep Google-bound cookies valid) is handled by isGoogleSourceBoundCookie excluding those cookies since #736, and #12884 measured that Google rejects re-transplants regardless of UA identity. - #12608 measured the synthesized Chrome-shaped UA reaching /v3/signin/rejected while the engine UA reached account lookup. Persisted userAgent/userAgentByPartition meta is no longer read; legacy keys drop off on the next meta write. The #12811 gate existed only to catch bad synthesized values, so it leaves with the synthesis.
…port (STA-3514) (#12849) * fix(browser): stop impersonating the source browser's UA on cookie import (STA-3514) Delete the import-time UA synthesis entirely instead of patching its version detection. The session now always keeps the engine-derived UA the registry sets at startup (clean or native), for imported and non-imported profiles alike. Why deletion is the fix: - The synthesis read CFBundleShortVersionString, which on forks is a marketing version — Arc imports presented Chrome/1.x and sites rejected the browser as ancient (STA-3514). - Its stated purpose (keep Google-bound cookies valid) is handled by isGoogleSourceBoundCookie excluding those cookies since #736, and #12884 measured that Google rejects re-transplants regardless of UA identity. - #12608 measured the synthesized Chrome-shaped UA reaching /v3/signin/rejected while the engine UA reached account lookup. Persisted userAgent/userAgentByPartition meta is no longer read; legacy keys drop off on the next meta write. The #12811 gate existed only to catch bad synthesized values, so it leaves with the synthesis. * test(browser): catch source UA impersonation regression
…-in staleness (stablyai#12884) Google binds a signed-in session to the browser identity that created it, and rejected Orca's Electron/Chrome-shaped UA on accounts.google.com — so sessions died at ~1h and re-copying cookies only reset the same losing clock. Present a Firefox identity scoped to the Google/YouTube sign-in hosts at every layer Google probes: the request headers (with sec-ch-ua* stripped, since real Firefox sends none), the per-WebContents UA that auth JS reads, and the CDP emulation override a viewport preset installs. All three must agree — a disagreement between them is a sharper bot signal than any single wrong UA. Native-UA profiles opt out at every layer, including popup child windows and after a browser-native cookie import. Validated live against a real account: freshness cookies issued and rotating on a ~10-min cadence, session still signed in and self-renewing past 10 hours, against a pre-fix baseline of death at ~1h. Closes stablyai#11518.
…port (STA-3514) (stablyai#12849) * fix(browser): stop impersonating the source browser's UA on cookie import (STA-3514) Delete the import-time UA synthesis entirely instead of patching its version detection. The session now always keeps the engine-derived UA the registry sets at startup (clean or native), for imported and non-imported profiles alike. Why deletion is the fix: - The synthesis read CFBundleShortVersionString, which on forks is a marketing version — Arc imports presented Chrome/1.x and sites rejected the browser as ancient (STA-3514). - Its stated purpose (keep Google-bound cookies valid) is handled by isGoogleSourceBoundCookie excluding those cookies since stablyai#736, and stablyai#12884 measured that Google rejects re-transplants regardless of UA identity. - stablyai#12608 measured the synthesized Chrome-shaped UA reaching /v3/signin/rejected while the engine UA reached account lookup. Persisted userAgent/userAgentByPartition meta is no longer read; legacy keys drop off on the next meta write. The stablyai#12811 gate existed only to catch bad synthesized values, so it leaves with the synthesis. * test(browser): catch source UA impersonation regression


Summary
Fixes Google sign-in sessions going stale after ~1 hour in the embedded browser (#11518).
Google binds a signed-in session to the browser identity that created it. Cookies sent under Orca's Electron/Chrome-shaped UA — which doesn't match a real first-party browser — get flagged by anti-fraud on
accounts.google.comand expire within ~1h, and re-copying cookies from the desktop browser only resets the same losing clock. This PR stops relying on a UA/cookie shape Google rejects: it presents a Firefox identity scoped to the Google/YouTube sign-in hosts (accounts.google.com,accounts.youtube.com) so the user signs in inside the embedded browser and Google issues cookies bound to this browser that self-refresh.The switch is applied at every layer Google probes:
onBeforeSendHeaders): sets the Firefox UA and stripssec-ch-ua*client hints (real Firefox sends none; Chromium hints under a Firefox UA are a sharper tell than either alone).WebContentsUA (did-start-navigation): thenavigator.userAgentthat Google's auth JS reads reflects the WebContents UA, not the request header — so both layers must agree or the mismatch is itself a bot signal.Emulation.setUserAgentOverride): the responsive-viewport presets install a third UA layer that outranks the other two. See Third UA layer below.Scope is the auth hosts only. Post-auth app surfaces (Gmail,
myaccount.google.com, Drive, etc.) keep the profile's real Chrome-shaped identity, so nothing else about the session shifts. Native-UA profiles (theuserAgentMode: 'native'escape hatch introduced in #12608) opt out of the whole clean-UA path and are unchanged.Third UA layer: the viewport-preset CDP override
Reviewing this branch surfaced a real defect in the interaction between the auth-host switch and the responsive-viewport presets, now fixed in this PR.
setViewportOverridesendsEmulation.setUserAgentOverridewith a Chrome-shaped UA. Measured against real Electron 43.1.0 / Chromium 150 (standalone harness: local echo server,webContents.setUserAgent+webRequest.onBeforeSendHeaders+ CDP, all three layers observed directly):WebContents.setUserAgentfor bothnavigator.userAgentand the outgoing request header.webContents.getUserAgent()still reports the WebContents value, so the disagreement is invisible from the Electron API.userAgent: '') or the debugger detaches. It is not re-applied per navigation.onBeforeSendHeadersstill wins for the outgoing header, so the wire-level Firefox switch was never at risk.That combination produced a genuine mismatch: apply a desktop/mobile preset first, then navigate to
accounts.google.com, and the request header says Firefox whilenavigator.userAgent— read by Google's auth JS — stays pinned to the Chrome-shaped preset UA. Exactly the two-layer disagreement this PR exists to remove.The reverse order was benign, as suspected, and this was verified rather than assumed:
cleanElectronUserAgent()finds noElectron/token and noChrome/token in a Firefox UA, so it passes it through unchanged (asserted in tests). But it left a stale Firefox override standing on every later non-auth navigation.Fix: the override payload moved to
buildViewportUserAgentOverride()(browser-viewport-user-agent.ts), which reusesisGoogleAuthUrland returns the Firefox UA — with nouserAgentMetadata, since real Firefox emits no client hints — whenever the target URL is an auth host.did-start-navigationre-issues the standing override against the URL being navigated to, so all three layers move together. Native-UA profiles remain untouched. The async re-issue is safe: page JS readsnavigator.userAgentafter commit, and the header layer already forces Firefox on the wire independently.Host resolution across the navigation boundary
A follow-up review flagged the two CDP user-agent writers as an ordering race. That framing turned
out to be wrong and is worth recording so it is not re-raised:
debugger.sendCommanddispatches incall order over a single channel, so the later-issued write always wins and the two could not land
out of order.
The real defect was post-await staleness. Measured against real Electron 43.1.0,
did-start-navigationfires while an awaitedsendCommandis still pending, andwebContents.getURL()keeps reporting the page being left until the navigation commits. SosetViewportOverride, resuming after its firstawait, resolved the wrong host — and then wonwith the wrong value. Both predicted symptoms were reachable that way: the Firefox UA stranded after
leaving an auth host, and a Chrome-shaped UA standing on one (mobile presets only — the desktop
branch is masked, because
cleanElectronUserAgentpasses the already-switched Firefox UA throughunchanged).
Fixed by giving both writers one source of truth for the host: a per-tab pending-navigation target,
set at
did-start-navigationand cleared on commit or failure, resolved in preference togetURL(). No queue required.Two further defects were found and fixed while re-examining this code:
attachGuestPoliciesbut arenever entered into
tabIdByWebContentsId, so the mode read asundefinedand the guard missed.That was worse than doing nothing: native profiles skip
setupClientHintsOverrideentirely, sosuch a popup would have sent the raw Electron UA on the wire while
navigator.userAgentclaimedFirefox 140 — the sharpest form of the mismatch this PR removes. Now resolved through the popup's
owner tab.
still-standing override that the navigation path could never correct. Both branches now mutate
tracking only after the writes land.
Known follow-up: device emulation is not URL-aware
The UA stack is URL-aware; the device-emulation stack is not.
setDeviceMetricsOverride(mobile: true)and
setTouchEmulationEnabled(maxTouchPoints: 5)are issued only fromsetViewportOverrideand arenever revisited on navigation, so a mobile viewport preset on an auth host produces desktop Firefox
with
navigator.maxTouchPoints === 5, where real desktop Firefox reports 0. Same class of internalcontradiction, different signal pair. Making device metrics URL-aware is a scope increase and is
deliberately left out of this PR.
Note the tempting alternative is wrong: emitting a mobile-Firefox UA on auth hosts would reintroduce
the bug this PR fixes, because
setupClientHintsOverrideis session-scoped and preset-blind and canonly ever emit the desktop
googleAuthUserAgent(). The CDP layer would then disagree with the headerlayer again. Desktop Firefox on auth hosts regardless of the preset is the only choice that keeps the
two UA layers in agreement.
Live E2E validation — real account, 8h+ and still self-refreshing (2026-08-07)
Ran the patched build in the real Orca app (dev build of this branch, isolated browser profile) and signed into a real Google account inside the embedded browser. All cookie reads below are metadata only (name / host / timestamps), read-only — no cookie values.
UA scoping (live in-app):
navigator.userAgentand WebContents UAaccounts.google.com/v3/signin/identifier…rv:140.0 … Firefox/140.0✅ Firefox override appliedexample.com(off-host)…Chrome/150 … Safari/537.36✅ reverts to base identityGoogle served the genuine sign-in form (no bounce to
/v3/signin/rejected), login succeeded, andmyaccount.google.comrendered signed-in.Durability — the exact #11518 failure mode. Pre-fix behavior was death at ~1h; this session is past 8 hours and still rotating.
Auth cookies issued at 2026-08-06 22:20:02 UTC. Cookie DB re-read at 2026-08-07 06:34:58 UTC — 8h 15m post-login:
__Secure-1PSIDTS.google.com__Secure-3PSIDTS.google.com__Secure-1PSIDCC.google.com__Secure-3PSIDCC.google.comSIDCC.google.comThe rotating freshness cookies are not merely alive at 8h — they were refreshed minutes before the measurement, i.e. the session is still actively self-renewing, not coasting on a long expiry. Earlier in the same session
__Secure-1PSIDTSrotated on a clean ~10-min cadence (22:20 → 22:30 → … → 23:20UTC) and forced revalidation (hard reload ofmyaccount.google.com) at 1h4m returned the signed-in account page rather than a bounce to sign-in. Against a pre-fix baseline of ~1h, this is roughly 8x and still climbing.For contrast, the pre-fix signature captured as the live repro was a week-old release-app session in which
__Secure-1PSIDTS/__Secure-3PSIDTSwere absent entirely and every auth cookie was frozen at creation time.One asymmetry, stated plainly: the
.youtube.comcopies of__Secure-1PSIDTS/__Secure-3PSIDTSare still frozen at the 22:20:02 login time and have never rotated. This is not a partial failure — it is explained by traffic, and the cookie DB confirms it rather than leaving it to inference. Grouping every cookie by host and taking the newestlast_access_utc:.google.commyaccount.google.comogs.google.comaccounts.google.com.youtube.comNo
youtube.comhost was contacted at any point after login. All 11.youtube.comcookies were written by the cross-domain propagation during sign-in itself and have alast_access_utcstill pinned to that instant — meaning they were never once attached to an outgoing request in the following 8 hours. No requests means no refresh responses, so there is nothing that could have rotated them. (Chromium'slast_access_utcupdate is throttled to roughly hourly, which only strengthens this: 8 hours of no movement cannot be a throttling artifact.)The Electron bump is exonerated
A reviewer's first instinct here is to blame the Electron 43 upgrade, so this was tested directly and ruled out.
A dual-engine A/B ran the two engine versions in parallel — Electron 42.3.3 / Chromium 148 vs Electron 43.1.0 / Chromium 150 — against the same real cookies and the same laundered UA. Both arms went stale identically. The staleness is a property of the cookie/identity binding, not of the Chromium version, and the Electron 43 upgrade is not the cause of #11518.
Methodology caveat: transplanted sessions cannot be A/B'd on one account
Worth recording, because it constrains how any future work in this area can be validated.
A transplanted Google session cannot be A/B tested against a single account. The first transplant of an account's cookies into a fresh partition works; every subsequent transplant of that same account is rejected, regardless of UA identity. The rejection tracks the re-import, not the browser fingerprint, so a second arm can never be a clean control — a valid transplant A/B would need separate Google accounts per arm.
Two consequences:
Screenshots
End-to-end Electron QA in the real Orca app — the embedded browser reaching Google's genuine sign-in form under the scoped Firefox identity — is posted in this comment, with the
navigator.userAgentproof and screenshots. (The post-login account page is intentionally not attached — it contains account PII; the sign-in-form capture demonstrates the UA mechanics without it.)Testing
pnpm lintpnpm typecheck(all three projects clean)pnpm test(src/main/browser/suite: 33 files, 586/586 passing — newbrowser-google-auth-uaandbrowser-viewport-user-agentsuites, updatedsetupClientHintsOverridesuite,browser-managersuite 67/67)pnpm buildsetupClientHintsOverridebehavior on/off the auth hosts, per-WebContentsUA apply-on-auth-host / restore-off-host / native-profile-untouched.AI Review Report
Codex (gpt-5.6-sol, high) ran the review-until-clean gate in its own worktree at the PR head, using four internal same-model adversarial passes. It found and fixed three defects, all introduced by this PR rather than pre-existing, and its final pass came back clean (
2363c3a04).All three are the same underlying class: a UA writer that resolves the tab's identity from state the auth-host switch does not reach.
did-start-navigation. Google's sign-in flow is redirect-heavy, so a redirect into an auth host mid-chain never triggered the switch, and a navigation that failed after being superseded could leave the auth identity standing on the document that remained. Now keyed per guest with an explicit superseded-URL set, applied onwill-redirect, and restored ondid-fail-loadonly when the failed navigation was the current one.browser-session-registryskipssetupClientHintsOverrideentirely foruserAgentMode: 'native', butbrowser-cookie-importre-installed it unconditionally after a browser-native import. Because this PR moved the Google-auth switch inside that function, a native profile that imported cookies silently acquired the Firefox header switch it had opted out of — while itsnavigator.userAgentstayed native, producing exactly the two-layer disagreement this PR exists to remove. Session-scoped mode state now gates it.Earlier rounds in this PR also closed a viewport-preset CDP override that outranked the WebContents UA, a tracking-order bug where the override map was cleared before the CDP write was known to have landed, and a degenerate-root guard. One reported finding was rejected after investigation: an automated reviewer claimed the navigation reapply and the viewport chain could interleave out of order. Tracing showed
debugger.sendCommanddispatches in call order, so the later write always wins; the speculative serialization queue added for it was removed rather than kept.Reference comparison against embedded-browser implementations in comparable tools found no architectural objection. The closest equivalent independently arrived at the same design — the same two auth hosts, the same Firefox template, the same two layers — and does not strip
sec-ch-ua*, so it ships Chromium client hints under a Firefox UA. This PR'sstripClientHintsis ahead of it. Two items were recorded as out of scope: device emulation is not URL-aware (already noted above as a known follow-up), andnavigator.userAgentData.brandsstill reports Chromium under the Firefox UA — measured, tolerated by Google, and documented in the E2E comment.Browser suite at the reviewed head: 33 files, 592 tests, all passing. New coverage was mutation-checked rather than assumed — removing the redirect-time UA apply fails its specific test.
Security Audit
No new input-handling, command-execution, path, or IPC surface. The change only rewrites outgoing request headers, the per-WebContents UA, and the CDP UA override for two exact-matched hostnames; hostname matching is exact (
URL.hostnameequality, lowercased) so lookalikes likeaccounts.google.com.evil.testdo not match. No cookie transplant, no secret handling, no new dependencies. All cookie inspection during validation was read-only and metadata-only (name / host / timestamps); no cookie values were read or logged.Notes
process.platform(macOS/Windows/Linux); no platform-specific shell/path/shortcut behavior touched.