Skip to content

The agent that grows with you

fix(desktop): one OAuth login flow per cookie jar

Austin Pickett09e67682ae2b
diff --git a/apps/desktop/electron/main.ts b/apps/desktop/electron/main.ts
index b56b73ac9d0..4c3473eb596 100644
--- a/apps/desktop/electron/main.ts
+++ b/apps/desktop/electron/main.ts
@@ -402,7 +402,7 @@ import { runNativeLogin } from './native-oauth-login'
import { loadNativeTokenSet, type NativeTokenStoreIo, persistNativeTokenSet } from './native-token-store'
import { execGit, killTimedGitChildren, setNoConsoleGitRoots } from './no-console-git'
import { registerNativeNotifications } from './notification-ipc'
-import { SilentLoginCoalescer } from './oauth-login-coalescer'
+import { type LoginAttempt, loginFlightKey, OauthLoginFlights } from './oauth-login-flights'
import { isExpectedOauthNavigationAbort } from './oauth-navigation'
import { serializeJsonBody, setJsonRequestHeaders } from './oauth-net-request'
import { LEGACY_OAUTH_PARTITION, resolveOauthPartition } from './oauth-partition'
@@ -7300,24 +7300,57 @@ async function clearOauthSession(baseUrl) {
}
}
-// One silent login per gateway origin. The opener is a closure so baseUrl and
-// options reach the window; passing the function itself calls it with none.
-const silentOauthLogins = new SilentLoginCoalescer()
-
-function openOauthLoginWindow(baseUrl, options = {}) {
- return silentOauthLogins.runFor(baseUrl, options, (url, loginOptions) =>
- openOauthLoginWindowUnshared(url, loginOptions)
+// Open a gateway login window in the OAuth session partition, resolving once
+// the access-token cookie appears (login done) or rejecting if the window is
+// closed first. The window navigates through the IDP and back to
+// /auth/callback, which sets the session cookies on the partition; we poll the
+// cookie jar rather than try to read the HttpOnly value.
+//
+// `silent` selects the URL the window loads:
+// - silent=false (default): ``/login``, the public provider chooser the
+// settings UI drives.
+// - silent=true: the PROTECTED root ``/``. With no session cookie the gate
+// runs ``_auto_sso_response``: single provider + a live portal session in
+// this partition → silent 302 through ``/auth/login`` → portal
+// ``/oauth/authorize`` → ``/auth/callback``, no prompt (decisions.md Q5).
+//
+// `background` (or a withoutInteractiveOauthLogin scope) means nobody asked
+// for this sign-in: the window stays hidden and gives up after 12s. Only a
+// user-driven caller may show a window. oauth-login-flights.ts keeps one flow
+// per cookie jar, so a burst of callers shares one window.
+const oauthLoginFlights = new OauthLoginFlights()
+
+function openOauthLoginWindow(baseUrl, options: OauthLoginWindowOptions = {}) {
+ const { connectionId = '', pendingAuthMode = '', pendingKind = '' } = options
+ const background = Boolean(options.background) || !canShowInteractiveOauthLogin()
+ const partition = resolveOauthPartitionForUrl(baseUrl, { connectionId, pendingAuthMode, pendingKind })
+ const key = loginFlightKey(partition, baseUrl)
+
+ return oauthLoginFlights.run(key, background ? 'background' : 'foreground', () =>
+ startOauthLoginWindow(baseUrl, { ...options, background })
)
}
-function openOauthLoginWindowUnshared(
- baseUrl,
- { silent = false, background = false, connectionId = '', pendingAuthMode = '', pendingKind = '' } = {}
-) {
- return new Promise((resolve, reject) => {
- // Background roster work may silently renew a Cloud session, but must
- // never turn an expired saved gateway into a visible login window.
- const hiddenRecovery = background || !canShowInteractiveOauthLogin()
+interface OauthLoginWindowOptions {
+ silent?: boolean
+ background?: boolean
+ connectionId?: string
+ pendingAuthMode?: string
+ pendingKind?: string
+}
+
+type OauthLoginOutcome = { baseUrl: string; ok: boolean }
+
+function startOauthLoginWindow(baseUrl, options: OauthLoginWindowOptions = {}): LoginAttempt<OauthLoginOutcome> {
+ const { silent = false, background = false, connectionId = '', pendingAuthMode = '', pendingKind = '' } = options
+
+ let reveal = (): void => {}
+
+ const result = new Promise<OauthLoginOutcome>((resolve, reject) => {
+ // Unattended recovery may silently renew a session, but must never turn
+ // an expired gateway into a visible login window (a user click promotes
+ // it through reveal() below).
+ let hiddenRecovery = background
if (!app.isReady()) {
reject(new Error('Desktop is not ready to start an OAuth login.'))
@@ -7446,7 +7479,30 @@ function openOauthLoginWindowUnshared(
}
if (hiddenRecovery) {
- deadlineTimer = setTimeout(() => finish(new Error('Cloud session recovery requires sign-in.')), 12_000)
+ deadlineTimer = setTimeout(() => finish(new Error('Silent sign-in did not complete; sign-in required.')), 12_000)
+ }
+
+ // A user's click joined this flow: show the window it already has (a
+ // second window would replace the gateway's PKCE state cookie) and drop
+ // the unattended deadline so they have time to finish.
+ reveal = () => {
+ if (settled || !win || win.isDestroyed()) {
+ return
+ }
+
+ hiddenRecovery = false
+
+ if (deadlineTimer) {
+ clearTimeout(deadlineTimer)
+ deadlineTimer = null
+ }
+
+ try {
+ win.show()
+ win.focus()
+ } catch {
+ // window torn down
+ }
}
win.on('closed', () => {
@@ -7479,6 +7535,8 @@ function openOauthLoginWindowUnshared(
finish(error instanceof Error ? error : new Error(String(error)))
})
})
+
+ return { result, reveal: () => reveal() }
}
// JSON request routed through the OAuth session partition so the HttpOnly
@@ -7600,8 +7658,14 @@ function fetchJsonViaOauthSession(url, options: any = {}) {
return attempt().catch(async error => {
const origin = new URL(url).origin
- return retryCookie401WithLogin(error, { ...options, loginKey: origin }, {
- clearCookies: () => remoteSessionCookies.clear(partition, url),
+ return retryCookie401WithLogin(error, options, {
+ // One burst shares one clear: a joiner must not wipe the mirror the
+ // running window is about to fill.
+ clearCookies: () => {
+ if (!oauthLoginFlights.isRunning(loginFlightKey(partition, origin))) {
+ remoteSessionCookies.clear(partition, url)
+ }
+ },
login: async () => {
try {
await openOauthLoginWindow(origin, { silent: true })
diff --git a/apps/desktop/electron/oauth-login-coalescer.test.ts b/apps/desktop/electron/oauth-login-coalescer.test.ts
deleted file mode 100644
index cdceafbe047..00000000000
--- a/apps/desktop/electron/oauth-login-coalescer.test.ts
+++ /dev/null
@@ -1,177 +0,0 @@
-import { expect, test } from 'vitest'
-
-import { loginKeyFor, SilentLoginCoalescer, SilentLoginSuppressedError } from './oauth-login-coalescer'
-
-function fakeClock(start = 1_000_000) {
- let now = start
-
- return {
- now: () => now,
- advance: (ms: number) => {
- now += ms
- }
- }
-}
-
-function deferred<T>() {
- let resolve!: (value: T) => void
- let reject!: (error: unknown) => void
-
- const promise = new Promise<T>((res, rej) => {
- resolve = res
- reject = rej
- })
-
- return { promise, resolve, reject }
-}
-
-const GATEWAY = 'https://gateway.example.test'
-const KEY = loginKeyFor(GATEWAY)
-
-test('concurrent silent logins for one gateway share a single attempt', async () => {
- const coalescer = new SilentLoginCoalescer()
- const first = deferred<string>()
- let calls = 0
-
- const login = () => {
- calls += 1
-
- return first.promise
- }
-
- const silent = { silent: true }
- const a = coalescer.run(KEY, login)
- const b = coalescer.run(KEY, login)
- const c = coalescer.runFor(`${GATEWAY}/api/status`, silent, () => login())
-
- expect(calls).toBe(1)
-
- first.resolve('ok')
-
- await expect(Promise.all([a, b, c])).resolves.toEqual(['ok', 'ok', 'ok'])
- expect(calls).toBe(1)
-})
-
-test('a silent login forwards the gateway url and options to a single opener', async () => {
- const coalescer = new SilentLoginCoalescer()
- const seen: Array<{ url: string; options: { silent?: boolean; background?: boolean } }> = []
-
- const open = (url: string, options: { silent?: boolean; background?: boolean }) => {
- seen.push({ url, options })
-
- return Promise.resolve('ok')
- }
-
- const options = { silent: true as const, background: true }
-
- await Promise.all([
- coalescer.runFor(`${GATEWAY}/api/status`, options, open),
- coalescer.runFor(GATEWAY, options, open)
- ])
-
- expect(seen).toEqual([{ url: `${GATEWAY}/api/status`, options }])
-})
-
-test('a failed silent login is not retried until its cooldown expires', async () => {
- const clock = fakeClock()
- const coalescer = new SilentLoginCoalescer({ now: clock.now, baseDelayMs: 5_000, maxDelayMs: 60_000 })
- let calls = 0
-
- const login = () => {
- calls += 1
-
- return Promise.reject(new Error('Login window closed before authentication completed.'))
- }
-
- await expect(coalescer.run(KEY, login)).rejects.toThrow(/Login window closed/)
- expect(calls).toBe(1)
-
- const suppressed = await coalescer.run(KEY, login).then(
- () => null,
- error => error
- )
-
- expect(suppressed).toBeInstanceOf(SilentLoginSuppressedError)
- expect((suppressed as SilentLoginSuppressedError).retryAfterMs).toBe(5_000)
- expect(calls).toBe(1)
-
- clock.advance(5_000)
- await expect(coalescer.run(KEY, login)).rejects.toThrow(/Login window closed/)
- expect(calls).toBe(2)
-})
-
-test('the backoff doubles per consecutive failure and stops at the ceiling', async () => {
- const clock = fakeClock()
- const coalescer = new SilentLoginCoalescer({ now: clock.now, baseDelayMs: 5_000, maxDelayMs: 20_000 })
- const delays: number[] = []
-
- const fail = () => Promise.reject(new Error('nope'))
-
- for (let attempt = 0; attempt < 5; attempt += 1) {
- await expect(coalescer.run(KEY, fail)).rejects.toThrow(/nope/)
- delays.push(coalescer.cooldownRemainingMs(KEY))
- clock.advance(coalescer.cooldownRemainingMs(KEY))
- }
-
- expect(delays).toEqual([5_000, 10_000, 20_000, 20_000, 20_000])
-})
-
-test('a successful login clears the backoff', async () => {
- const clock = fakeClock()
- const coalescer = new SilentLoginCoalescer({ now: clock.now, baseDelayMs: 5_000, maxDelayMs: 60_000 })
-
- await expect(coalescer.run(KEY, () => Promise.reject(new Error('nope')))).rejects.toThrow(/nope/)
- clock.advance(5_000)
- await expect(coalescer.run(KEY, () => Promise.resolve('ok'))).resolves.toBe('ok')
- expect(coalescer.cooldownRemainingMs(KEY)).toBe(0)
-
- await expect(coalescer.run(KEY, () => Promise.reject(new Error('nope')))).rejects.toThrow(/nope/)
- expect(coalescer.cooldownRemainingMs(KEY)).toBe(5_000)
-})
-
-test('separate gateways are coalesced independently', async () => {
- const coalescer = new SilentLoginCoalescer()
- let calls = 0
-
- const login = () => {
- calls += 1
-
- return Promise.resolve('ok')
- }
-
- await Promise.all([coalescer.run(KEY, login), coalescer.run(loginKeyFor('https://other.example.test'), login)])
- expect(calls).toBe(2)
-})
-
-test('an interactive sign-in is never coalesced and still receives the url', async () => {
- const clock = fakeClock()
- const coalescer = new SilentLoginCoalescer({ now: clock.now, baseDelayMs: 5_000, maxDelayMs: 60_000 })
- const seen: string[] = []
-
- const open = (url: string) => {
- seen.push(url)
-
- return Promise.resolve('ok')
- }
-
- const silentAttempt = deferred<string>()
- const silent = coalescer.runFor(GATEWAY, { silent: true }, () => silentAttempt.promise)
-
- await Promise.all([
- coalescer.runFor(GATEWAY, { silent: false }, open),
- coalescer.runFor(GATEWAY, { silent: false }, open)
- ])
- expect(seen).toEqual([GATEWAY, GATEWAY])
-
- silentAttempt.reject(new Error('nope'))
- await expect(silent).rejects.toThrow(/nope/)
- await expect(coalescer.runFor(GATEWAY, { silent: false }, open)).resolves.toBe('ok')
- expect(seen).toEqual([GATEWAY, GATEWAY, GATEWAY])
-})
-
-test('the coalescing key is the gateway origin', () => {
- expect(loginKeyFor('https://gateway.example.test')).toBe('https://gateway.example.test')
- expect(loginKeyFor('https://gateway.example.test/some/path')).toBe('https://gateway.example.test')
- expect(loginKeyFor('http://127.0.0.1:9119')).toBe('http://127.0.0.1:9119')
- expect(loginKeyFor('https://gateway.example.test')).not.toBe(loginKeyFor('https://other.example.test'))
-})
diff --git a/apps/desktop/electron/oauth-login-coalescer.ts b/apps/desktop/electron/oauth-login-coalescer.ts
deleted file mode 100644
index ab21df33f56..00000000000
--- a/apps/desktop/electron/oauth-login-coalescer.ts
+++ /dev/null
@@ -1,143 +0,0 @@
-/**
- * One silent OAuth login window per gateway origin.
- *
- * A gated remote gateway answers every cookie-less request with
- * `401 {reason: "no_cookie"}`, and each refused request answers that with one
- * silent re-login (`retryCookie401WithLogin` → `openOauthLoginWindow`). A burst
- * — boot, sidebar polls, a wake while the network is still down — therefore
- * opened one BrowserWindow per request.
- *
- * Silent callers share one attempt: the jar either gains a session cookie or it
- * does not. After a failure the next silent attempt waits, so a closed or
- * unreachable window is not replaced once per incoming request. An interactive
- * sign-in is the user's own click and always opens immediately.
- *
- * `silent` also selects the URL the window loads:
- * - silent=false: `/login`, the provider chooser.
- * - silent=true: the protected root `/`, so the gate can auto-SSO through
- * portal `/oauth/authorize` back to `/auth/callback` without a chooser.
- */
-
-export interface SilentLoginCoalescerOptions {
- now?: () => number
- baseDelayMs?: number
- maxDelayMs?: number
-}
-
-export class SilentLoginSuppressedError extends Error {
- readonly retryAfterMs: number
-
- constructor(retryAfterMs: number) {
- super(
- `A silent sign-in for this gateway failed recently; the next attempt is held for ${Math.ceil(retryAfterMs / 1000)}s.`
- )
- this.name = 'SilentLoginSuppressedError'
- this.retryAfterMs = retryAfterMs
- }
-}
-
-/** Session cookies belong to the origin, which is the scope one silent login serves. */
-export function loginKeyFor(baseUrl: string): string {
- try {
- return new URL(baseUrl).origin
- } catch {
- return baseUrl
- }
-}
-
-export class SilentLoginCoalescer {
- private readonly now: () => number
- private readonly baseDelayMs: number
- private readonly maxDelayMs: number
- private readonly inFlight = new Map<string, Promise<unknown>>()
- private readonly failures = new Map<string, { consecutive: number; blockedUntil: number }>()
-
- constructor(options: SilentLoginCoalescerOptions = {}) {
- this.now = options.now ?? Date.now
- this.baseDelayMs = options.baseDelayMs ?? 5_000
- this.maxDelayMs = options.maxDelayMs ?? 60_000
- }
-
- /**
- * Open one login for `baseUrl`. The opener is always called as
- * `open(baseUrl, options)` — a zero-arg callback drops the gateway URL and
- * no window can load.
- */
- runFor<T, O extends { silent?: boolean }>(
- baseUrl: string,
- options: O,
- open: (baseUrl: string, options: O) => Promise<T>
- ): Promise<T> {
- if (options?.silent !== true) {
- return open(baseUrl, options)
- }
-
- return this.run(loginKeyFor(baseUrl), () => open(baseUrl, options))
- }
-
- cooldownRemainingMs(key: string): number {
- const failure = this.failures.get(key)
-
- if (!failure) {
- return 0
- }
-
- return Math.max(0, failure.blockedUntil - this.now())
- }
-
- run<T>(key: string, login: () => Promise<T>): Promise<T> {
- const running = this.inFlight.get(key)
-
- if (running) {
- return running as Promise<T>
- }
-
- const remaining = this.cooldownRemainingMs(key)
-
- if (remaining > 0) {
- return Promise.reject(new SilentLoginSuppressedError(remaining))
- }
-
- let started: Promise<T>
-
- try {
- started = login()
- } catch (error) {
- this.recordFailure(key)
-
- return Promise.reject(error)
- }
-
- const attempt: Promise<T> = started.then(
- value => {
- this.failures.delete(key)
-
- return value
- },
- error => {
- this.recordFailure(key)
-
- throw error
- }
- )
-
- this.inFlight.set(key, attempt)
-
- const release = (): void => {
- if (this.inFlight.get(key) === attempt) {
- this.inFlight.delete(key)
- }
- }
-
- void attempt.then(release, release)
-
- return attempt
- }
-
- private recordFailure(key: string): void {
- const consecutive = (this.failures.get(key)?.consecutive ?? 0) + 1
- const delay = Math.min(this.baseDelayMs * 2 ** (consecutive - 1), this.maxDelayMs)
-
- this.failures.set(key, { consecutive, blockedUntil: this.now() + delay })
- }
-}
diff --git a/apps/desktop/electron/oauth-login-flights.test.ts b/apps/desktop/electron/oauth-login-flights.test.ts
new file mode 100644
index 00000000000..4d15ba4b875
--- /dev/null
+++ b/apps/desktop/electron/oauth-login-flights.test.ts
@@ -0,0 +1,186 @@
+import { afterEach, expect, test, vi } from 'vitest'
+
+import {
+ type LoginAttempt,
+ loginFlightKey,
+ LoginJoinTimeoutError,
+ OauthLoginFlights,
+ SilentLoginSuppressedError
+} from './oauth-login-flights'
+
+function fakeClock(start = 1_000_000) {
+ let now = start
+
+ return {
+ now: () => now,
+ advance: (ms: number) => {
+ now += ms
+ }
+ }
+}
+
+function deferred<T>() {
+ let resolve!: (value: T) => void
+ let reject!: (error: unknown) => void
+
+ const promise = new Promise<T>((res, rej) => {
+ resolve = res
+ reject = rej
+ })
+
+ return { promise, resolve, reject }
+}
+
+/** A stand-in login window: counts how many were opened and revealed. */
+function fakeWindows<T>(outcome: () => Promise<T>) {
+ const stats = { opened: 0, revealed: 0 }
+
+ const start = (): LoginAttempt<T> => {
+ stats.opened += 1
+
+ return {
+ result: outcome(),
+ reveal: () => {
+ stats.revealed += 1
+ }
+ }
+ }
+
+ return { stats, start }
+}
+
+const JAR = 'persist:hermes-remote-oauth'
+const GATEWAY = 'https://gateway.example.test'
+const KEY = loginFlightKey(JAR, GATEWAY)
+
+afterEach(() => {
+ vi.useRealTimers()
+})
+
+test('a burst of background 401s opens one window for the gateway', async () => {
+ const flights = new OauthLoginFlights()
+ const login = deferred<string>()
+ const windows = fakeWindows(() => login.promise)
+
+ const burst = Array.from({ length: 10 }, () => flights.run(KEY, 'background', windows.start))
+
+ expect(windows.stats.opened).toBe(1)
+ login.resolve('ok')
+ await expect(Promise.all(burst)).resolves.toEqual(Array(10).fill('ok'))
+ expect(windows.stats).toEqual({ opened: 1, revealed: 0 })
+})
+
+test('a failed background login is held until its cooldown expires', async () => {
+ const clock = fakeClock()
+ const flights = new OauthLoginFlights({ now: clock.now, baseDelayMs: 5_000, maxDelayMs: 60_000 })
+ const windows = fakeWindows(() => Promise.reject(new Error('Login window closed before authentication completed.')))
+
+ await expect(flights.run(KEY, 'background', windows.start)).rejects.toThrow(/Login window closed/)
+
+ const held = await flights.run(KEY, 'background', windows.start).catch(error => error)
+
+ expect(held).toBeInstanceOf(SilentLoginSuppressedError)
+ expect((held as SilentLoginSuppressedError).retryAfterMs).toBe(5_000)
+ expect(windows.stats.opened).toBe(1)
+
+ // After a wake the next attempt runs on its own once the hold lapses.
+ clock.advance(5_000)
+ await expect(flights.run(KEY, 'background', windows.start)).rejects.toThrow(/Login window closed/)
+ expect(windows.stats.opened).toBe(2)
+})
+
+test('the backoff doubles per consecutive failure, stops at the ceiling, and clears on success', async () => {
+ const clock = fakeClock()
+ const flights = new OauthLoginFlights({ now: clock.now, baseDelayMs: 5_000, maxDelayMs: 20_000 })
+ const fail = fakeWindows(() => Promise.reject(new Error('nope')))
+ const delays: number[] = []
+
+ for (let attempt = 0; attempt < 5; attempt += 1) {
+ await expect(flights.run(KEY, 'background', fail.start)).rejects.toThrow(/nope/)
+ delays.push(flights.cooldownRemainingMs(KEY))
+ clock.advance(flights.cooldownRemainingMs(KEY))
+ }
+
+ expect(delays).toEqual([5_000, 10_000, 20_000, 20_000, 20_000])
+
+ await expect(flights.run(KEY, 'background', fakeWindows(async () => 'ok').start)).resolves.toBe('ok')
+ expect(flights.cooldownRemainingMs(KEY)).toBe(0)
+})
+
+test('a click while a hidden attempt runs reveals that window instead of opening a second', async () => {
+ const flights = new OauthLoginFlights()
+ const login = deferred<string>()
+ const windows = fakeWindows(() => login.promise)
+
+ const background = flights.run(KEY, 'background', windows.start)
+ const click = flights.run(KEY, 'foreground', windows.start)
+ const repeatClick = flights.run(KEY, 'foreground', windows.start)
+
+ expect(windows.stats).toEqual({ opened: 1, revealed: 2 })
+
+ login.resolve('ok')
+ await expect(Promise.all([background, click, repeatClick])).resolves.toEqual(['ok', 'ok', 'ok'])
+})
+
+test('a click is never held by a background cooldown', async () => {
+ const clock = fakeClock()
+ const flights = new OauthLoginFlights({ now: clock.now })
+
+ await expect(
+ flights.run(KEY, 'background', fakeWindows(() => Promise.reject(new Error('nope'))).start)
+ ).rejects.toThrow(/nope/)
+ expect(flights.cooldownRemainingMs(KEY)).toBeGreaterThan(0)
+
+ const click = fakeWindows(async () => 'ok')
+
+ await expect(flights.run(KEY, 'foreground', click.start)).resolves.toBe('ok')
+ expect(click.stats.opened).toBe(1)
+ expect(flights.cooldownRemainingMs(KEY)).toBe(0)
+})
+
+test('background callers stop waiting on a window the user left open', async () => {
+ vi.useFakeTimers()
+
+ const flights = new OauthLoginFlights({ joinTimeoutMs: 15_000 })
+ const login = deferred<string>()
+ const windows = fakeWindows(() => login.promise)
+
+ const owner = flights.run(KEY, 'foreground', windows.start)
+ const joiner = flights.run(KEY, 'background', windows.start)
+ const joinerOutcome = joiner.catch(error => error)
+
+ await vi.advanceTimersByTimeAsync(15_000)
+ expect(await joinerOutcome).toBeInstanceOf(LoginJoinTimeoutError)
+
+ // The user's own window is untouched and still completes.
+ expect(flights.isRunning(KEY)).toBe(true)
+ login.resolve('ok')
+ await expect(owner).resolves.toBe('ok')
+ expect(windows.stats.opened).toBe(1)
+})
+
+test('the same origin on two cookie jars gets two independent flows', async () => {
+ const flights = new OauthLoginFlights()
+ const primary = deferred<string>()
+ const other = deferred<string>()
+ const a = fakeWindows(() => primary.promise)
+ const b = fakeWindows(() => other.promise)
+
+ const viaPrimary = flights.run(loginFlightKey(JAR, GATEWAY), 'background', a.start)
+ const viaOther = flights.run(loginFlightKey(`${JAR}-conn-work`, GATEWAY), 'background', b.start)
+
+ expect([a.stats.opened, b.stats.opened]).toEqual([1, 1])
+
+ // One jar failing must not put the other on hold.
+ primary.reject(new Error('nope'))
+ other.resolve('ok')
+ await expect(viaPrimary).rejects.toThrow(/nope/)
+ await expect(viaOther).resolves.toBe('ok')
+ expect(flights.cooldownRemainingMs(loginFlightKey(`${JAR}-conn-work`, GATEWAY))).toBe(0)
+})
+
+test('the flight key is the jar plus the gateway origin', () => {
+ expect(loginFlightKey(JAR, `${GATEWAY}/api/status`)).toBe(KEY)
+ expect(loginFlightKey(JAR, 'https://other.example.test')).not.toBe(KEY)
+ expect(loginFlightKey(`${JAR}-conn-x`, GATEWAY)).not.toBe(KEY)
+})
diff --git a/apps/desktop/electron/oauth-login-flights.ts b/apps/desktop/electron/oauth-login-flights.ts
new file mode 100644
index 00000000000..fab9cd04638
--- /dev/null
+++ b/apps/desktop/electron/oauth-login-flights.ts
@@ -0,0 +1,183 @@
+/**
+ * One OAuth login window per gateway cookie jar.
+ *
+ * A gated remote gateway answers every cookie-less request with
+ * `401 {reason: "no_cookie"}`, and each refused request used to answer that
+ * with its own login window (`retryCookie401WithLogin` → `openOauthLoginWindow`).
+ * After a session lapse (overnight sleep, a gateway restart, an IdP outage)
+ * every background poll opened one, and the user woke to a stack of them.
+ *
+ * Rules, per (partition, origin), the scope one cookie jar serves:
+ * - At most one login flow is in flight. A second start would also replace
+ * the gateway's single PKCE state cookie and fail the first callback with
+ * `state_mismatch`.
+ * - Background work (no user gesture) joins a running flow but waits at most
+ * `joinTimeoutMs`, so a window the user left open cannot wedge every
+ * request for that gateway.
+ * - A failed attempt holds the next background attempt back with
+ * exponential backoff. The hold is time-based, not "until the user
+ * clicks": the first attempt after a wake fails while Wi-Fi/VPN reconnect,
+ * and the next one recovers on its own.
+ * - A foreground caller (the user's click) is never held by a cooldown. If a
+ * hidden attempt is already running it is revealed instead of opening a
+ * competing window, and a repeat click focuses the open one.
+ */
+
+export type LoginIntent = 'background' | 'foreground'
+
+/** A started login: its outcome, plus a way to put its window in front of the user. */
+export interface LoginAttempt<T> {
+ result: Promise<T>
+ reveal: () => void
+}
+
+export interface OauthLoginFlightsOptions {
+ now?: () => number
+ baseDelayMs?: number
+ maxDelayMs?: number
+ joinTimeoutMs?: number
+}
+
+export class SilentLoginSuppressedError extends Error {
+ readonly retryAfterMs: number
+
+ constructor(retryAfterMs: number) {
+ super(
+ `A silent sign-in for this gateway failed recently; the next attempt is held for ${Math.ceil(retryAfterMs / 1000)}s.`
+ )
+ this.name = 'SilentLoginSuppressedError'
+ this.retryAfterMs = retryAfterMs
+ }
+}
+
+export class LoginJoinTimeoutError extends Error {
+ constructor(timeoutMs: number) {
+ super(`A sign-in for this gateway is still open; stopped waiting after ${Math.ceil(timeoutMs / 1000)}s.`)
+ this.name = 'LoginJoinTimeoutError'
+ }
+}
+
+/** Cookies live per jar and per origin, and so does a login flow. */
+export function loginFlightKey(partition: string, baseUrl: string): string {
+ let origin = baseUrl
+
+ try {
+ origin = new URL(baseUrl).origin
+ } catch {
+ // an unparsable URL still keys consistently
+ }
+
+ return `${partition} ${origin}`
+}
+
+interface Flight {
+ result: Promise<unknown>
+ reveal: () => void
+}
+
+export class OauthLoginFlights {
+ private readonly now: () => number
+ private readonly baseDelayMs: number
+ private readonly maxDelayMs: number
+ private readonly joinTimeoutMs: number
+ private readonly inFlight = new Map<string, Flight>()
+ private readonly failures = new Map<string, { consecutive: number; blockedUntil: number }>()
+
+ constructor(options: OauthLoginFlightsOptions = {}) {
+ this.now = options.now ?? Date.now
+ this.baseDelayMs = options.baseDelayMs ?? 5_000
+ this.maxDelayMs = options.maxDelayMs ?? 60_000
+ this.joinTimeoutMs = options.joinTimeoutMs ?? 15_000
+ }
+
+ isRunning(key: string): boolean {
+ return this.inFlight.has(key)
+ }
+
+ cooldownRemainingMs(key: string): number {
+ const failure = this.failures.get(key)
+
+ return failure ? Math.max(0, failure.blockedUntil - this.now()) : 0
+ }
+
+ /** `start` runs only when `key` has no flight; joiners never open a window. */
+ run<T>(key: string, intent: LoginIntent, start: () => LoginAttempt<T>): Promise<T> {
+ const running = this.inFlight.get(key)
+
+ if (running) {
+ if (intent === 'foreground') {
+ running.reveal()
+
+ return running.result as Promise<T>
+ }
+
+ return this.boundedJoin(running.result as Promise<T>)
+ }
+
+ const remaining = intent === 'background' ? this.cooldownRemainingMs(key) : 0
+
+ if (remaining > 0) {
+ return Promise.reject(new SilentLoginSuppressedError(remaining))
+ }
+
+ let attempt: LoginAttempt<T>
+
+ try {
+ attempt = start()
+ } catch (error) {
+ this.recordFailure(key)
+
+ return Promise.reject(error)
+ }
+
+ const result: Promise<T> = attempt.result.then(
+ value => {
+ this.failures.delete(key)
+
+ return value
+ },
+ error => {
+ this.recordFailure(key)
+
+ throw error
+ }
+ )
+
+ const flight: Flight = { result, reveal: attempt.reveal }
+ this.inFlight.set(key, flight)
+
+ const release = (): void => {
+ if (this.inFlight.get(key) === flight) {
+ this.inFlight.delete(key)
+ }
+ }
+
+ void result.then(release, release)
+
+ return result
+ }
+
+ private boundedJoin<T>(result: Promise<T>): Promise<T> {
+ return new Promise<T>((resolve, reject) => {
+ const timer = setTimeout(() => reject(new LoginJoinTimeoutError(this.joinTimeoutMs)), this.joinTimeoutMs)
+
+ result.then(
+ value => {
+ clearTimeout(timer)
+ resolve(value)
+ },
+ error => {
+ clearTimeout(timer)
+ reject(error)
+ }
+ )
+ })
+ }
+
+ private recordFailure(key: string): void {
+ const consecutive = (this.failures.get(key)?.consecutive ?? 0) + 1
+ const delay = Math.min(this.baseDelayMs * 2 ** (consecutive - 1), this.maxDelayMs)
+
+ this.failures.set(key, { consecutive, blockedUntil: this.now() + delay })
+ }
+}
diff --git a/apps/desktop/electron/oauth-rest-request.test.ts b/apps/desktop/electron/oauth-rest-request.test.ts
index 9fbfb5906e4..a1905fa5535 100644
--- a/apps/desktop/electron/oauth-rest-request.test.ts
+++ b/apps/desktop/electron/oauth-rest-request.test.ts
@@ -139,98 +139,6 @@ test('background auth intent stays isolated from a concurrent foreground request
expect(foregroundLogins).toBe(1)
})
-test('concurrent gate 401s for one gateway clear cookies and open login once', async () => {
- const refusal = GATE_401()
- let clears = 0
- let logins = 0
-
- let releaseLogin: () => void = () => {}
-
- const loginGate = new Promise<void>(resolve => {
- releaseLogin = resolve
- })
-
- const attempt = () =>
- retryCookie401WithLogin(
- refusal,
- { method: 'GET', loginKey: 'https://gw.test' },
- {
- clearCookies: () => {
- clears += 1
- },
- login: async () => {
- logins += 1
- await loginGate
- },
- retry: async () => 'ok'
- }
- )
-
- const first = attempt()
- const second = attempt()
-
- expect(clears).toBe(1)
- expect(logins).toBe(1)
-
- releaseLogin()
-
- await expect(Promise.all([first, second])).resolves.toEqual(['ok', 'ok'])
- expect(clears).toBe(1)
- expect(logins).toBe(1)
-})
-
-test('a joiner does not clear cookies when the shared re-login fails', async () => {
- const refusal = GATE_401()
- let joinerClears = 0
-
- const first = retryCookie401WithLogin(
- refusal,
- { loginKey: 'https://gw.test' },
- {
- clearCookies: () => {},
- login: async () => {
- throw new Error('Login window closed before authentication completed.')
- },
- retry: async () => 'unexpected'
- }
- )
-
- const second = retryCookie401WithLogin(
- refusal,
- { loginKey: 'https://gw.test' },
- {
- clearCookies: () => {
- joinerClears += 1
- },
- login: async () => {
- throw new Error('joiner opened a window')
- },
- retry: async () => 'unexpected'
- }
- )
-
- await expect(first).rejects.toBe(refusal)
- await expect(second).rejects.toBe(refusal)
- expect(joinerClears).toBe(0)
-
- let laterLogins = 0
-
- await expect(
- retryCookie401WithLogin(
- refusal,
- { loginKey: 'https://gw.test' },
- {
- clearCookies: () => {},
- login: async () => {
- laterLogins += 1
- },
- retry: async () => 'recovered'
- }
- )
- ).resolves.toBe('recovered')
- expect(laterLogins).toBe(1)
-})
-
test('failed foreground re-login returns the original gate refusal without retrying', async () => {
const refusal = GATE_401()
let retries = 0
diff --git a/apps/desktop/electron/oauth-rest-request.ts b/apps/desktop/electron/oauth-rest-request.ts
index b928ebaf033..60cba284832 100644
--- a/apps/desktop/electron/oauth-rest-request.ts
+++ b/apps/desktop/electron/oauth-rest-request.ts
@@ -71,57 +71,15 @@ export function canShowInteractiveOauthLogin(): boolean {
return interactiveLoginAllowed.getStore() !== false
}
-const cookieReloginFlights = new Map<string, Promise<void>>()
-
-async function shareCookieRelogin(
- key: string,
- actions: { clearCookies: () => void; login: () => Promise<unknown> }
-): Promise<void> {
- const running = cookieReloginFlights.get(key)
-
- if (running) {
- await running
-
- return
- }
-
- // One burst shares one cookie clear. A joiner that clears mid-flight wipes
- // the mirror the in-flight window is about to fill.
- actions.clearCookies()
-
- const flight = actions.login().then(() => undefined)
-
- const tracked = flight.finally(() => {
- if (cookieReloginFlights.get(key) === tracked) {
- cookieReloginFlights.delete(key)
- }
- })
-
- cookieReloginFlights.set(key, tracked)
- await tracked
-}
-
export async function retryCookie401WithLogin<T>(
error: unknown,
- options: { method?: unknown; replayOn401?: unknown; loginKey?: unknown },
+ options: { method?: unknown; replayOn401?: unknown },
actions: { clearCookies: () => void; login: () => Promise<unknown>; retry: () => Promise<T> }
): Promise<T> {
if (!canShowInteractiveOauthLogin() || !shouldReplayAfterCookie401(error, options)) {
throw error
}
- const loginKey = typeof options.loginKey === 'string' ? options.loginKey : ''
-
- if (loginKey) {
- try {
- await shareCookieRelogin(loginKey, actions)
- } catch {
- throw error
- }
-
- return actions.retry()
- }
-
actions.clearCookies()
try {