From 092afacdb956dcb1905facd292b7f8593178d405 Mon Sep 17 00:00:00 2001 From: Rishi Balakrishnan Date: Mon, 9 Nov 2026 15:58:35 -0500 Subject: [PATCH] fix(session): handle terminal OAuth deletion and keep sessions through transient restore failures (#185) * fix(session): handle terminal OAuth deletion * fix(session): keep the account when session restore fails transiently at launch A single failed getSession or restore at app open (5xx, DPoP proof or nonce rejection, network error, timeout) dropped the user to the signed-out screen even when the server session was valid, and telemetry only recorded "Expected an active session". Retry the resume once. On a transient failure, keep the stored account on the locally stored tokens. Sign out only on terminal OAuth errors (refresh token rejected, session revoked, deleted or invalid) or errors not known to be transient. Report the real error category, and add an oauth:sessionResumeDegraded event for kept sessions. * chore(lint): prune stale unread.tsx suppressions * fix(session): never block or sign out on a stuck launch restore Address review findings on the OAuth resume fallback: - On a transient launch failure, build the agent on a lazily restored session instead of awaiting restore(did, false), which joined the same stuck refresh and timed out into a sign-out. - Only treat known-temporary DPoP errors (nonce, stale proof, replayed jti) as transient; other invalid_dpop_proof errors fail fast. - Check the transient set before retrying so other errors fail fast. - Apply the keep-on-transient fallback only to the app-launch restore; refresh and account-switch callers still get the error. - withTimeout preserves the original rejection and clears its timer, and is used for the restore, getSession and getTokenInfo timeouts. - Web: oauth-client 0.5.x ignores onDelete/onUpdate options, so wire the hooks to the client's deleted/updated events and emit the lifecycle deleted event. - Drop the redundant deletion set, the buffered lifecycle queue and the per-DID restore map; the OAuth client's CachedGetter already dedupes restores per DID. --- eslint-suppressions.json | 5 +- src/App.native.tsx | 2 +- src/App.web.tsx | 2 +- src/analytics/metrics/types.ts | 11 + .../__tests__/notifications-test.ts | 49 +++ src/lib/notifications/notifications.ts | 10 +- src/state/queries/notifications/unread.tsx | 16 +- .../session/__tests__/oauth-lifecycle-test.ts | 25 ++ .../session/__tests__/oauth-resume-test.ts | 302 ++++++++++++++++++ src/state/session/__tests__/session-test.ts | 50 +++ src/state/session/index.tsx | 39 ++- src/state/session/oauth-agent.ts | 163 +++++++--- src/state/session/oauth-client.ts | 15 +- src/state/session/oauth-client.web.ts | 30 +- src/state/session/oauth-lifecycle.ts | 16 + src/state/session/oauth-telemetry.ts | 33 +- src/state/session/reducer.ts | 20 +- src/state/session/types.ts | 1 + 18 files changed, 719 insertions(+), 70 deletions(-) create mode 100644 src/lib/notifications/__tests__/notifications-test.ts create mode 100644 src/state/session/__tests__/oauth-lifecycle-test.ts create mode 100644 src/state/session/__tests__/oauth-resume-test.ts create mode 100644 src/state/session/oauth-lifecycle.ts diff --git a/eslint-suppressions.json b/eslint-suppressions.json index 50b016055..fe40e523e 100644 --- a/eslint-suppressions.json +++ b/eslint-suppressions.json @@ -1796,10 +1796,7 @@ }, "src/state/queries/notifications/unread.tsx": { "@typescript-eslint/no-floating-promises": { - "count": 4 - }, - "@typescript-eslint/no-misused-promises": { - "count": 1 + "count": 3 }, "@typescript-eslint/no-unsafe-member-access": { "count": 4 diff --git a/src/App.native.tsx b/src/App.native.tsx index e657b6439..98f9f29da 100644 --- a/src/App.native.tsx +++ b/src/App.native.tsx @@ -106,7 +106,7 @@ function InnerApp() { async function onLaunch(account?: SessionAccount) { try { if (account) { - await resumeSession(account) + await resumeSession(account, false, true) } else { await features.init } diff --git a/src/App.web.tsx b/src/App.web.tsx index 8b10aee11..b7fc80018 100644 --- a/src/App.web.tsx +++ b/src/App.web.tsx @@ -130,7 +130,7 @@ function InnerApp() { } if (account) { - await resumeSession(account) + await resumeSession(account, false, true) } else { await features.init } diff --git a/src/analytics/metrics/types.ts b/src/analytics/metrics/types.ts index e65a10d66..38331e661 100644 --- a/src/analytics/metrics/types.ts +++ b/src/analytics/metrics/types.ts @@ -93,6 +93,9 @@ export type Events = { | 'invalidGrant' | 'databaseClosed' | 'dpopSkew' + | 'dpopStale' + | 'dpopReplayed' + | 'dpopNonce' | 'dpopOther' | 'refreshExhausted' | 'subMismatch' @@ -115,14 +118,22 @@ export type Events = { | 'invalidGrant' | 'databaseClosed' | 'dpopSkew' + | 'dpopStale' + | 'dpopReplayed' + | 'dpopNonce' | 'dpopOther' | 'refreshExhausted' | 'subMismatch' | 'timeout' | 'network' + | 'serverError' | 'unknown' message?: string } + 'oauth:sessionResumeDegraded': { + errorCategory: Events['oauth:sessionResumeFailed']['errorCategory'] + message?: string + } 'notifications:openApp': { reason: NotificationReason causedBoot: boolean diff --git a/src/lib/notifications/__tests__/notifications-test.ts b/src/lib/notifications/__tests__/notifications-test.ts new file mode 100644 index 000000000..ecb106f83 --- /dev/null +++ b/src/lib/notifications/__tests__/notifications-test.ts @@ -0,0 +1,49 @@ +import * as Notifications from 'expo-notifications' +import {type AtpAgent} from '@atproto/api' + +import {PUBLIC_APPVIEW_DID} from '#/lib/constants' +import {unregisterPushToken} from '#/lib/notifications/notifications' + +jest.mock('expo-notifications', () => ({ + getPermissionsAsync: jest.fn(), + getDevicePushTokenAsync: jest.fn(), + getBadgeCountAsync: jest.fn(), + setBadgeCountAsync: jest.fn(), +})) +jest.mock('#/state/session', () => ({ + useAgent: jest.fn(), + useSession: jest.fn(), +})) +jest.mock('#/analytics', () => ({useAnalytics: jest.fn()})) +jest.mock('#/../modules/expo-background-notification-handler', () => ({ + __esModule: true, + default: {setBadgeCountAsync: jest.fn()}, +})) + +describe('unregisterPushToken', () => { + it('uses the account service when an OAuth agent has no serviceUrl', async () => { + const unregisterPush = jest.fn().mockResolvedValue(undefined) + const agent = { + app: {bsky: {notification: {unregisterPush}}}, + session: {handle: 'alice.test'}, + } as unknown as AtpAgent + + jest.mocked(Notifications.getPermissionsAsync).mockResolvedValue({ + granted: true, + } as Notifications.NotificationPermissionsStatus) + jest.mocked(Notifications.getDevicePushTokenAsync).mockResolvedValue({ + type: 'ios', + data: 'device-token', + }) + + await unregisterPushToken([agent], 'https://blacksky.app') + + expect(unregisterPush).toHaveBeenCalledWith( + expect.objectContaining({ + serviceDid: PUBLIC_APPVIEW_DID, + token: 'device-token', + }), + expect.any(Object), + ) + }) +}) diff --git a/src/lib/notifications/notifications.ts b/src/lib/notifications/notifications.ts index c10554a87..8bed7e1aa 100644 --- a/src/lib/notifications/notifications.ts +++ b/src/lib/notifications/notifications.ts @@ -291,16 +291,22 @@ export async function resetBadgeCount() { await setBadgeCountAsync(0) } -export async function unregisterPushToken(agents: AtpAgent[]) { +export async function unregisterPushToken( + agents: AtpAgent[], + fallbackService?: string, +) { if (!IS_NATIVE) return try { const token = await getPushToken() if (token) { for (const agent of agents) { + const serviceHostname = + agent.serviceUrl?.hostname ?? + (fallbackService ? new URL(fallbackService).hostname : '') await agent.app.bsky.notification.unregisterPush( { - serviceDid: agent.serviceUrl.hostname.includes('staging') + serviceDid: serviceHostname.includes('staging') ? PUBLIC_STAGING_APPVIEW_DID : PUBLIC_APPVIEW_DID, platform: Platform.OS, diff --git a/src/state/queries/notifications/unread.tsx b/src/state/queries/notifications/unread.tsx index ad5b28a60..036faec16 100644 --- a/src/state/queries/notifications/unread.tsx +++ b/src/state/queries/notifications/unread.tsx @@ -17,6 +17,7 @@ import {EventEmitter} from 'eventemitter3' import BroadcastChannel from '#/lib/broadcast' import {HOME_APPVIEW_PINNED_OPTS} from '#/lib/constants' import {resetBadgeCount} from '#/lib/notifications/notifications' +import {logger as notyLogger} from '#/lib/notifications/util' import {useModerationOpts} from '#/state/preferences/moderation-opts' import {truncateAndInvalidate} from '#/state/queries/util' import {useAgent, useSession} from '#/state/session' @@ -85,11 +86,10 @@ export function Provider({children}: React.PropsWithChildren<{}>) { if (!hasSession || !checkUnreadRef.current) { return } - checkUnreadRef.current() // fire on init - const interval = setInterval( - () => checkUnreadRef.current?.({isPoll: true}), - UPDATE_INTERVAL, - ) + void checkUnreadRef.current().catch(onUnreadCheckError) // fire on init + const interval = setInterval(() => { + void checkUnreadRef.current?.({isPoll: true}).catch(onUnreadCheckError) + }, UPDATE_INTERVAL) return () => clearInterval(interval) }, [hasSession]) @@ -233,6 +233,12 @@ export function Provider({children}: React.PropsWithChildren<{}>) { ) } +function onUnreadCheckError(error: unknown) { + notyLogger.warn('Unread notification check failed', { + message: error instanceof Error ? error.message : String(error), + }) +} + export function useUnreadNotifications() { return useContext(stateContext) } diff --git a/src/state/session/__tests__/oauth-lifecycle-test.ts b/src/state/session/__tests__/oauth-lifecycle-test.ts new file mode 100644 index 000000000..127046d56 --- /dev/null +++ b/src/state/session/__tests__/oauth-lifecycle-test.ts @@ -0,0 +1,25 @@ +import {afterEach, describe, expect, it, jest} from '@jest/globals' + +import { + emitOauthLifecycleEvent, + setOauthLifecycleSink, +} from '../oauth-lifecycle' + +afterEach(() => setOauthLifecycleSink(null)) + +describe('OAuth lifecycle events', () => { + it('delivers events to the registered sink', () => { + const sink = jest.fn() + setOauthLifecycleSink(sink) + + emitOauthLifecycleEvent({type: 'deleted', did: 'did:plc:alice'}) + + expect(sink).toHaveBeenCalledWith({type: 'deleted', did: 'did:plc:alice'}) + }) + + it('drops events when no sink is registered', () => { + expect(() => + emitOauthLifecycleEvent({type: 'deleted', did: 'did:plc:alice'}), + ).not.toThrow() + }) +}) diff --git a/src/state/session/__tests__/oauth-resume-test.ts b/src/state/session/__tests__/oauth-resume-test.ts new file mode 100644 index 000000000..a1feb4c68 --- /dev/null +++ b/src/state/session/__tests__/oauth-resume-test.ts @@ -0,0 +1,302 @@ +import {type OAuthSession, TokenRefreshError} from '@atproto/oauth-client' +import {afterEach, beforeEach, describe, expect, it, jest} from '@jest/globals' + +import {oauthResumeSessionWithRetry, withTimeout} from '../oauth-agent' +import {emitOauthTelemetry} from '../oauth-telemetry' +import {type SessionAccount} from '../types' + +const mockRestore = jest.fn<(did: string) => Promise>() + +jest.mock('@atproto/oauth-client-expo', () => { + return { + ...jest.requireActual('@atproto/oauth-client'), + ExpoOAuthClient: class { + restore(did: string) { + return mockRestore(did) + } + }, + } +}) + +jest.mock('@atproto/lexicon', () => ({ + ...jest.requireActual('@atproto/lexicon'), + jsonStringToLex: (str: string): unknown => JSON.parse(str), +})) + +jest.mock('../moderation', () => ({ + configureModerationForAccount: () => Promise.resolve(), +})) + +jest.mock('../oauth-telemetry', () => ({ + ...jest.requireActual('../oauth-telemetry'), + emitOauthTelemetry: jest.fn(), +})) + +const DID = 'did:plc:alice' + +const storedAccount: SessionAccount = { + service: 'https://pds.test', + did: DID, + handle: 'alice.stored', + email: 'alice@example.com', + emailConfirmed: true, + emailAuthFactor: false, + active: true, + pdsUrl: 'https://pds.test', + isSelfHosted: true, + isOauthSession: true, +} + +function jsonResponse(status: number, body: object) { + return new Response(JSON.stringify(body), { + status, + headers: {'content-type': 'application/json'}, + }) +} + +const okSession = () => + jsonResponse(200, { + did: DID, + handle: 'alice.fresh', + email: 'alice@example.com', + emailConfirmed: true, + active: true, + }) + +const dpopError = (error: string, message: string) => () => + Promise.resolve(jsonResponse(401, {error, message})) + +function fakeSession(fetchHandler: () => Promise) { + return { + did: DID, + serverMetadata: {issuer: 'https://pds.test'}, + server: {issuer: 'https://pds.test'}, + fetchHandler, + getTokenInfo: () => Promise.resolve({aud: 'https://pds.test'}), + } as unknown as OAuthSession +} + +const degradedEvents = () => + jest + .mocked(emitOauthTelemetry) + .mock.calls.map(([event]) => event) + .filter(event => event.type === 'oauth:sessionResumeDegraded') + +describe('oauthResumeSessionWithRetry', () => { + beforeEach(() => { + mockRestore.mockReset() + jest.mocked(emitOauthTelemetry).mockClear() + }) + + afterEach(() => { + jest.useRealTimers() + }) + + it('proceeds normally when the retry succeeds', async () => { + const fetchHandler = jest + .fn<() => Promise>() + .mockResolvedValueOnce(jsonResponse(502, {error: 'UpstreamFailure'})) + .mockResolvedValueOnce(okSession()) + mockRestore.mockResolvedValue(fakeSession(fetchHandler)) + + const {account} = await oauthResumeSessionWithRetry(storedAccount, true) + + expect(account.handle).toBe('alice.fresh') + expect(mockRestore).toHaveBeenCalledTimes(2) + expect(degradedEvents()).toEqual([]) + }) + + it('keeps the stored account at launch on a 5xx and restores on the next request', async () => { + const fetchHandler = jest + .fn<() => Promise>() + .mockResolvedValueOnce(jsonResponse(500, {error: 'InternalServerError'})) + .mockResolvedValueOnce(jsonResponse(500, {error: 'InternalServerError'})) + .mockResolvedValueOnce(okSession()) + mockRestore.mockResolvedValue(fakeSession(fetchHandler)) + + const {account, agent} = await oauthResumeSessionWithRetry( + storedAccount, + true, + ) + + expect(account).toEqual(storedAccount) + expect(mockRestore).toHaveBeenCalledTimes(2) + expect(degradedEvents()).toEqual([ + { + type: 'oauth:sessionResumeDegraded', + payload: expect.objectContaining({errorCategory: 'serverError'}), + }, + ]) + + const {data} = await agent.com.atproto.server.getSession() + expect(data.handle).toBe('alice.fresh') + expect(mockRestore).toHaveBeenCalledTimes(3) + }) + + it('keeps the stored account when a refresh hangs past the timeout', async () => { + jest.useFakeTimers() + mockRestore.mockReturnValue(new Promise(() => {})) + + const resumed = oauthResumeSessionWithRetry(storedAccount, true) + await jest.advanceTimersByTimeAsync(10_000) + const {account} = await resumed + + expect(account).toEqual(storedAccount) + expect(mockRestore).toHaveBeenCalledTimes(1) + expect(degradedEvents()[0]?.payload).toEqual( + expect.objectContaining({errorCategory: 'timeout'}), + ) + }) + + it.each([ + ['invalid_dpop_proof', 'DPoP proof "jti" replayed', 'dpopReplayed'], + ['invalid_dpop_proof', 'DPoP proof is too old', 'dpopStale'], + ['use_dpop_nonce', 'Authorization server requires nonce', 'dpopNonce'], + ])( + 'keeps the stored account on a temporary DPoP error (%s: %s)', + async (error, message, errorCategory) => { + mockRestore.mockResolvedValue(fakeSession(dpopError(error, message))) + + const {account} = await oauthResumeSessionWithRetry(storedAccount, true) + + expect(account).toEqual(storedAccount) + expect(mockRestore).toHaveBeenCalledTimes(2) + expect(degradedEvents()[0]?.payload).toEqual( + expect.objectContaining({errorCategory}), + ) + }, + ) + + it.each([ + 'DPoP "htu" mismatch', + 'DPoP proof "iat" is in the future', + 'Failed to verify DPoP proof', + ])('fails fast on a persistent DPoP error (%s)', async message => { + mockRestore.mockResolvedValue( + fakeSession(dpopError('invalid_dpop_proof', message)), + ) + + await expect( + oauthResumeSessionWithRetry(storedAccount, true), + ).rejects.toThrow(message) + expect(mockRestore).toHaveBeenCalledTimes(1) + expect(degradedEvents()).toEqual([]) + }) + + it('keeps the stored account when the token refresh request fails', async () => { + mockRestore.mockRejectedValue(new TypeError('Network request failed')) + + const {account} = await oauthResumeSessionWithRetry(storedAccount, true) + + expect(account).toEqual(storedAccount) + expect(mockRestore).toHaveBeenCalledTimes(2) + expect(degradedEvents()[0]?.payload).toEqual( + expect.objectContaining({errorCategory: 'network'}), + ) + }) + + it('returns the error outside app launch instead of keeping the account', async () => { + mockRestore.mockResolvedValue( + fakeSession(() => + Promise.resolve(jsonResponse(503, {error: 'NotEnoughResources'})), + ), + ) + + await expect(oauthResumeSessionWithRetry(storedAccount)).rejects.toThrow( + 'NotEnoughResources', + ) + expect(mockRestore).toHaveBeenCalledTimes(2) + expect(degradedEvents()).toEqual([]) + }) + + it('signs out without retrying when the refresh token is rejected', async () => { + mockRestore.mockRejectedValue( + new TokenRefreshError(DID, 'Refresh token replayed'), + ) + + await expect( + oauthResumeSessionWithRetry(storedAccount, true), + ).rejects.toThrow('Refresh token replayed') + expect(mockRestore).toHaveBeenCalledTimes(1) + expect(degradedEvents()).toEqual([]) + }) + + it('fails fast on a non-transient error', async () => { + mockRestore.mockResolvedValue( + fakeSession(() => + Promise.resolve( + jsonResponse(400, { + error: 'AccountTakedown', + message: 'Account has been taken down', + }), + ), + ), + ) + + await expect( + oauthResumeSessionWithRetry(storedAccount, true), + ).rejects.toThrow('Account has been taken down') + expect(mockRestore).toHaveBeenCalledTimes(1) + expect(degradedEvents()).toEqual([]) + }) + + it('signs out when deleting a rejected session also failed', async () => { + mockRestore.mockRejectedValue( + new AggregateError([ + new TokenRefreshError(DID, 'Refresh token replayed'), + new Error('store write failed'), + ]), + ) + + await expect( + oauthResumeSessionWithRetry(storedAccount, true), + ).rejects.toThrow() + expect(mockRestore).toHaveBeenCalledTimes(1) + expect(degradedEvents()).toEqual([]) + }) + + it('signs out when a terminal error surfaces through getSession', async () => { + mockRestore.mockResolvedValue( + fakeSession(() => + Promise.reject( + new TokenRefreshError( + DID, + 'The session was deleted by another process', + ), + ), + ), + ) + + await expect( + oauthResumeSessionWithRetry(storedAccount, true), + ).rejects.toThrow('The session was deleted by another process') + expect(mockRestore).toHaveBeenCalledTimes(1) + expect(degradedEvents()).toEqual([]) + }) +}) + +describe('withTimeout', () => { + afterEach(() => { + jest.useRealTimers() + }) + + it('preserves the original rejection and clears its timer', async () => { + jest.useFakeTimers() + const original = {status: 502, error: 'UpstreamFailure'} + + await expect( + // eslint-disable-next-line @typescript-eslint/prefer-promise-reject-errors -- XRPC-like rejections must pass through unwrapped + withTimeout(Promise.reject(original), 1_000, 'timed out'), + ).rejects.toBe(original) + expect(jest.getTimerCount()).toBe(0) + }) + + it('clears its timer after resolving', async () => { + jest.useFakeTimers() + + await expect( + withTimeout(Promise.resolve(1), 1_000, 'timed out'), + ).resolves.toBe(1) + expect(jest.getTimerCount()).toBe(0) + }) +}) diff --git a/src/state/session/__tests__/session-test.ts b/src/state/session/__tests__/session-test.ts index 2a906938c..0dd22550e 100644 --- a/src/state/session/__tests__/session-test.ts +++ b/src/state/session/__tests__/session-test.ts @@ -979,6 +979,56 @@ describe('session', () => { `) }) + it('ends an active OAuth session while keeping the remembered account', () => { + const account = { + service: 'https://alice.com', + did: 'did:plc:alice', + handle: 'alice.test', + isOauthSession: true, + } + const agent = new AtpAgent({service: account.service}) + let state = run(getInitialState([]), [ + {type: 'switched-to-account', newAgent: agent, newAccount: account}, + ]) + + state = run(state, [ + {type: 'oauth-session-terminated', accountDid: account.did}, + ]) + + expect(state.currentAgentState.did).toBeUndefined() + expect(state.accounts).toEqual([account]) + expect(state.needsPersist).toBe(true) + }) + + it('ignores OAuth termination for an inactive account', () => { + const alice = { + service: 'https://alice.com', + did: 'did:plc:alice', + handle: 'alice.test', + isOauthSession: true, + } + const bob = { + service: 'https://bob.com', + did: 'did:plc:bob', + handle: 'bob.test', + isOauthSession: true, + } + const aliceAgent = new AtpAgent({service: alice.service}) + const bobAgent = new AtpAgent({service: bob.service}) + const state = run(getInitialState([]), [ + {type: 'switched-to-account', newAgent: aliceAgent, newAccount: alice}, + {type: 'switched-to-account', newAgent: bobAgent, newAccount: bob}, + ]) + + const next = reducer(state, { + type: 'oauth-session-terminated', + accountDid: alice.did, + }) + + expect(next).toBe(state) + expect(next.currentAgentState.did).toBe(bob.did) + }) + it('bails out of update on identical objects', () => { let state = getInitialState([]) diff --git a/src/state/session/index.tsx b/src/state/session/index.tsx index 1c67b892a..465aa705f 100644 --- a/src/state/session/index.tsx +++ b/src/state/session/index.tsx @@ -27,7 +27,7 @@ import { import { type OauthBskyAppAgent, oauthCreateAgent, - oauthResumeSession, + oauthResumeSessionWithRetry, } from './oauth-agent' import {categorizeOauthError, setOauthTelemetrySink} from './oauth-telemetry' import {type Action, getInitialState, reducer, type State} from './reducer' @@ -35,12 +35,14 @@ export {isSignupQueued} from './util' import {addSessionDebugLog} from './logging' export type {SessionAccount} from '#/state/session/types' +import {unregisterPushToken} from '#/lib/notifications/notifications' import {clearPersistedQueryStorage} from '#/lib/persisted-query-storage' import { type SessionApiContext, type SessionStateContext, } from '#/state/session/types' import {useOnboardingDispatch} from '#/state/shell/onboarding' +import {setOauthLifecycleSink} from './oauth-lifecycle' const StateContext = createContext({ accounts: [], @@ -202,6 +204,7 @@ export function Provider({children}: React.PropsWithChildren<{}>) { addSessionDebugLog({type: 'method:start', method: 'logout'}) cancelPendingTask() const prevState = store.getState() + unregisterActiveOauthPushToken(prevState) store.dispatch({ type: 'logged-out-current-account', }) @@ -233,6 +236,7 @@ export function Provider({children}: React.PropsWithChildren<{}>) { addSessionDebugLog({type: 'method:start', method: 'logout'}) cancelPendingTask() const prevState = store.getState() + unregisterActiveOauthPushToken(prevState) store.dispatch({ type: 'logged-out-every-account', }) @@ -258,7 +262,7 @@ export function Provider({children}: React.PropsWithChildren<{}>) { ) const resumeSession = useCallback( - async (storedAccount, isSwitchingAccounts = false) => { + async (storedAccount, isSwitchingAccounts = false, isAppLaunch = false) => { addSessionDebugLog({ type: 'method:start', method: 'resumeSession', @@ -272,7 +276,10 @@ export function Provider({children}: React.PropsWithChildren<{}>) { } if (storedAccount.isOauthSession) { try { - agentAccount = await oauthResumeSession(storedAccount) + agentAccount = await oauthResumeSessionWithRetry( + storedAccount, + isAppLaunch, + ) } catch (e) { ax.metric('oauth:sessionResumeFailed', { logContext: isSwitchingAccounts ? 'SwitchAccount' : 'AppBoot', @@ -333,6 +340,9 @@ export function Provider({children}: React.PropsWithChildren<{}>) { account, }) cancelPendingTask() + if (store.getState().currentAgentState.did === account.did) { + unregisterActiveOauthPushToken(store.getState()) + } store.dispatch({ type: 'removed-account', accountDid: account.did, @@ -341,6 +351,19 @@ export function Provider({children}: React.PropsWithChildren<{}>) { }, [store, cancelPendingTask], ) + useEffect(() => { + setOauthLifecycleSink(event => { + if (store.getState().currentAgentState.did !== event.did) return + store.dispatch({ + type: 'oauth-session-terminated', + accountDid: event.did, + }) + emitSessionDropped() + void clearPersistedQueryStorage(event.did) + }) + return () => setOauthLifecycleSink(null) + }, [store]) + useEffect(() => { setOauthTelemetrySink(event => { ax.metric(event.type, event.payload) @@ -453,6 +476,16 @@ export function Provider({children}: React.PropsWithChildren<{}>) { ) } +function unregisterActiveOauthPushToken(state: State) { + const did = state.currentAgentState.did + const account = state.accounts.find(candidate => candidate.did === did) + if (!account?.isOauthSession) return + void unregisterPushToken( + [state.currentAgentState.agent as AtpAgent], + account.service, + ) +} + function useOneTaskAtATime() { const abortController = useRef(null) const cancelPendingTask = useCallback(() => { diff --git a/src/state/session/oauth-agent.ts b/src/state/session/oauth-agent.ts index 3b0ddeb6c..e9365fcc1 100644 --- a/src/state/session/oauth-agent.ts +++ b/src/state/session/oauth-agent.ts @@ -1,4 +1,4 @@ -/* eslint-disable @typescript-eslint/no-explicit-any, @typescript-eslint/no-unsafe-call, @typescript-eslint/no-unsafe-member-access -- Expo OAuth types do not resolve in Linux CI */ +/* eslint-disable @typescript-eslint/no-explicit-any -- Expo OAuth types do not resolve in Linux CI */ import { Agent, type AtpSessionData, @@ -14,7 +14,12 @@ import { stripAppviewProxyForPdsLocalMethods, } from './agent' import {configureModerationForAccount} from './moderation' -import {getOAuthClient} from './oauth-client' +import {getOAuthClient, TERMINAL_OAUTH_ERRORS} from './oauth-client' +import { + categorizeOauthError, + emitOauthTelemetry, + truncateOauthMessage, +} from './oauth-telemetry' import {type SessionAccount} from './types' export async function oauthCreateAgent(session: OAuthSession) { @@ -30,19 +35,23 @@ export async function oauthCreateAgent(session: OAuthSession) { const OAUTH_RESTORE_TIMEOUT_MS = 10_000 +type OAuthRestoreClient = { + restore(did: string): Promise +} + +function restoreOAuthSession(did: string) { + const client: OAuthRestoreClient = getOAuthClient() + return client.restore(did) +} + export async function oauthResumeSession(account: SessionAccount) { - const client = getOAuthClient() let session: OAuthSession try { - session = await Promise.race([ - client.restore(account.did), - new Promise((_, reject) => - setTimeout( - () => reject(new Error('OAuth session restore timed out')), - OAUTH_RESTORE_TIMEOUT_MS, - ), - ), - ]) + session = await withTimeout( + restoreOAuthSession(account.did), + OAUTH_RESTORE_TIMEOUT_MS, + 'OAuth session restore timed out', + ) } catch (e) { logger.error('oauthResumeSession: restore failed', { did: account.did, @@ -53,52 +62,124 @@ export async function oauthResumeSession(account: SessionAccount) { return await oauthCreateAgent(session) } -export async function oauthAgentAndSessionToSessionAccountOrThrow( - agent: Agent, - session: OAuthSession, -): Promise { - const account = await oauthAgentAndSessionToSessionAccount(agent, session) - if (!account) { - throw Error('Expected an active session') +const OAUTH_RESUME_RETRY_DELAY_MS = 500 + +const TRANSIENT_RESUME_ERRORS = new Set([ + 'network', + 'timeout', + 'serverError', + 'dpopNonce', + 'dpopStale', + 'dpopReplayed', +]) + +export function withTimeout( + promise: Promise, + timeoutMs: number, + message: string, +): Promise { + let timer: ReturnType | undefined + const timeout = new Promise((_, reject) => { + timer = setTimeout(() => reject(new Error(message)), timeoutMs) + }) + return Promise.race([promise, timeout]).finally(() => clearTimeout(timer)) +} + +function isTerminalOAuthError(e: unknown, depth = 0): boolean { + if (!e || typeof e !== 'object' || depth > 5) return false + if (TERMINAL_OAUTH_ERRORS.some(ErrorClass => e instanceof ErrorClass)) { + return true + } + if ('errors' in e && Array.isArray(e.errors)) { + return e.errors.some(err => isTerminalOAuthError(err, depth + 1)) } - return account + return 'cause' in e && isTerminalOAuthError(e.cause, depth + 1) } -export async function oauthAgentAndSessionToSessionAccount( +export async function oauthResumeSessionWithRetry( + account: SessionAccount, + keepOnTransientFailure = false, +) { + let error: unknown + let errorCategory: ReturnType = 'unknown' + for (let attempt = 0; attempt < 2; attempt++) { + try { + return await oauthResumeSession(account) + } catch (e) { + error = e + } + errorCategory = categorizeOauthError(error) + if (isTerminalOAuthError(error)) throw error + if (!TRANSIENT_RESUME_ERRORS.has(errorCategory)) throw error + // A timeout has already held the splash screen for the full budget. + if (errorCategory === 'timeout') break + if (attempt === 0) { + await new Promise(r => setTimeout(r, OAUTH_RESUME_RETRY_DELAY_MS)) + } + } + if (!keepOnTransientFailure) throw error + + // Restoring now could wait on the same stuck refresh, so defer it to the + // first request. + const session = lazyOAuthSession(account.did) + logger.warn('oauthResumeSession: keeping stored account after failure', { + did: account.did, + errorCategory, + }) + emitOauthTelemetry({ + type: 'oauth:sessionResumeDegraded', + payload: {errorCategory, message: truncateOauthMessage(error)}, + }) + const agent = new OauthBskyAppAgent(session) + const moderation = configureModerationForAccount(agent, account) + return agent.prepare(account, Promise.resolve(), moderation) +} + +type OAuthSessionHandle = Pick + +function lazyOAuthSession(did: string): OAuthSessionHandle { + let pending: Promise | undefined + return { + did: did as OAuthSession['did'], + fetchHandler(url, init) { + const restoring = (pending ??= restoreOAuthSession(did).catch( + (e: unknown) => { + pending = undefined + throw e + }, + )) + return restoring.then(session => session.fetchHandler(url, init)) + }, + } +} + +export async function oauthAgentAndSessionToSessionAccountOrThrow( agent: Agent, session: OAuthSession, -): Promise { +): Promise { let data: ComAtprotoServerGetSession.OutputSchema try { - const res = await Promise.race([ + const res = await withTimeout( agent.com.atproto.server.getSession(), - new Promise((_, reject) => - setTimeout( - () => reject(new Error('getSession timed out')), - OAUTH_RESTORE_TIMEOUT_MS, - ), - ), - ]) + OAUTH_RESTORE_TIMEOUT_MS, + 'getSession timed out', + ) data = res.data } catch (e: any) { logger.error('oauthAgentAndSessionToSessionAccount: getSession failed', e) - return undefined + throw e } let aud: string try { - const tokenInfo = await Promise.race([ + const tokenInfo = await withTimeout( session.getTokenInfo(false), - new Promise((_, reject) => - setTimeout( - () => reject(new Error('getTokenInfo timed out')), - OAUTH_RESTORE_TIMEOUT_MS, - ), - ), - ]) + OAUTH_RESTORE_TIMEOUT_MS, + 'getTokenInfo timed out', + ) aud = tokenInfo.aud } catch (e: any) { logger.error('oauthAgentAndSessionToSessionAccount: getTokenInfo failed', e) - return undefined + throw e } return { service: session.serverMetadata.issuer, @@ -119,7 +200,7 @@ export class OauthBskyAppAgent extends Agent { session?: AtpSessionData dispatchUrl?: string - constructor(session: OAuthSession) { + constructor(session: OAuthSessionHandle) { // Wrap the OAuth session's fetchHandler so the appview proxy header is // stripped from PDS-local methods. The header is added by the Agent's XRPC // wrapper before it calls the session manager, so stripping here removes it diff --git a/src/state/session/oauth-client.ts b/src/state/session/oauth-client.ts index 2317be2c1..361fba8f3 100644 --- a/src/state/session/oauth-client.ts +++ b/src/state/session/oauth-client.ts @@ -1,6 +1,11 @@ import * as Linking from 'expo-linking' import {openAuthSessionAsync} from 'expo-web-browser' -import {ExpoOAuthClient} from '@atproto/oauth-client-expo' +import { + ExpoOAuthClient, + TokenInvalidError, + TokenRefreshError, + TokenRevokedError, +} from '@atproto/oauth-client-expo' import {logger} from '#/logger' import { @@ -8,6 +13,7 @@ import { emitOauthTelemetry, } from '#/state/session/oauth-telemetry' import {OAUTH_BASE_URL, OAUTH_CLIENT_NAME, OAUTH_SCOPE} from './oauth-config' +import {emitOauthLifecycleEvent} from './oauth-lifecycle' const LOCAL_OAUTH_HANDLE_RESOLVER = process.env.EXPO_PUBLIC_OAUTH_HANDLE_RESOLVER @@ -71,6 +77,7 @@ const sessionHooks = { ? cause : undefined logger.warn('oauth: session deleted', {sub, cause: category, message}) + emitOauthLifecycleEvent({type: 'deleted', did: sub}) emitOauthTelemetry({ type: 'oauth:sessionDeleted', payload: {cause: category, message: message?.slice(0, 200)}, @@ -104,6 +111,12 @@ export function getOAuthClient() { return BSKY_OAUTH_CLIENT } +export const TERMINAL_OAUTH_ERRORS = [ + TokenRefreshError, + TokenRevokedError, + TokenInvalidError, +] + /** * Android-only OAuth sign-in. * diff --git a/src/state/session/oauth-client.web.ts b/src/state/session/oauth-client.web.ts index b512bcf2f..d866f893f 100644 --- a/src/state/session/oauth-client.web.ts +++ b/src/state/session/oauth-client.web.ts @@ -1,4 +1,9 @@ -import {BrowserOAuthClient} from '@atproto/oauth-client-browser' +import { + BrowserOAuthClient, + TokenInvalidError, + TokenRefreshError, + TokenRevokedError, +} from '@atproto/oauth-client-browser' import {logger} from '#/logger' import { @@ -8,6 +13,7 @@ import { } from '#/state/session/oauth-telemetry' import {type Metrics} from '#/analytics/metrics' import {OAUTH_SCOPE} from './oauth-config' +import {emitOauthLifecycleEvent} from './oauth-lifecycle' const LOCAL_OAUTH_HANDLE_RESOLVER = process.env.EXPO_PUBLIC_OAUTH_HANDLE_RESOLVER @@ -50,11 +56,8 @@ function isLoopback() { ) } -// Session hooks passed at construction. @atproto/oauth-client-browser ^0.3 -// removed the post-construction `addEventListener('deleted'|'updated', ...)` -// surface; the OAuthClient base class now exposes `onDelete`/`onUpdate` -// callbacks via SessionHooks instead. Functionally equivalent — we still -// observe the same lifecycle events, just wired up earlier. +// oauth-client-browser 0.3.40 (oauth-client 0.5.x) ignores `onDelete` / +// `onUpdate` constructor options, so these are wired to the client's events. const sessionHooks = { onDelete(sub: string, cause: unknown) { const category = categorizeOauthError(cause) @@ -65,6 +68,7 @@ const sessionHooks = { ? cause : undefined logger.warn('oauth: session deleted', {sub, cause: category, message}) + emitOauthLifecycleEvent({type: 'deleted', did: sub}) emitOauthTelemetry({ type: 'oauth:sessionDeleted', payload: {cause: category, message: message?.slice(0, 200)}, @@ -180,7 +184,6 @@ function createWebOAuthClient() { }, ...oauthResolutionOptions, fetch: oauthInstrumentedFetch, - ...sessionHooks, }) } @@ -202,12 +205,23 @@ function createWebOAuthClient() { }, ...oauthResolutionOptions, fetch: oauthInstrumentedFetch, - ...sessionHooks, }) } const BSKY_OAUTH_CLIENT = createWebOAuthClient() +BSKY_OAUTH_CLIENT.addEventListener('deleted', event => { + sessionHooks.onDelete(event.detail.sub, event.detail.cause) +}) +BSKY_OAUTH_CLIENT.addEventListener('updated', event => { + sessionHooks.onUpdate(event.detail.sub) +}) export function getOAuthClient() { return BSKY_OAUTH_CLIENT } + +export const TERMINAL_OAUTH_ERRORS = [ + TokenRefreshError, + TokenRevokedError, + TokenInvalidError, +] diff --git a/src/state/session/oauth-lifecycle.ts b/src/state/session/oauth-lifecycle.ts new file mode 100644 index 000000000..bcf8fc1d6 --- /dev/null +++ b/src/state/session/oauth-lifecycle.ts @@ -0,0 +1,16 @@ +export type OauthLifecycleEvent = { + type: 'deleted' + did: string +} + +export type OauthLifecycleSink = (event: OauthLifecycleEvent) => void + +let sink: OauthLifecycleSink | null = null + +export function setOauthLifecycleSink(next: OauthLifecycleSink | null) { + sink = next +} + +export function emitOauthLifecycleEvent(event: OauthLifecycleEvent) { + sink?.(event) +} diff --git a/src/state/session/oauth-telemetry.ts b/src/state/session/oauth-telemetry.ts index 730f2f007..311eeff18 100644 --- a/src/state/session/oauth-telemetry.ts +++ b/src/state/session/oauth-telemetry.ts @@ -8,6 +8,10 @@ type OauthTelemetryEvent = type: 'oauth:sessionResumeFailed' payload: Metrics['oauth:sessionResumeFailed'] } + | { + type: 'oauth:sessionResumeDegraded' + payload: Metrics['oauth:sessionResumeDegraded'] + } export type OauthTelemetrySink = (event: OauthTelemetryEvent) => void @@ -63,6 +67,9 @@ export function categorizeOauthError( } else { str = '' } + if (err && typeof err === 'object' && 'error' in err) { + str = `${String(err.error)} ${str}` + } if ( str.includes('session was deleted by another process') || str.includes('The session was revoked') @@ -85,7 +92,22 @@ export function categorizeOauthError( ) { return 'databaseClosed' } - if (str.includes('invalid_dpop_proof') && str.includes('iat claim')) { + if (str.includes('use_dpop_nonce')) { + return 'dpopNonce' + } + if ( + str.includes('invalid_dpop_proof') && + (str.includes('too old') || str.includes('too far in the past')) + ) { + return 'dpopStale' + } + if (str.includes('invalid_dpop_proof') && str.includes('replayed')) { + return 'dpopReplayed' + } + if ( + str.includes('invalid_dpop_proof') && + (str.includes('iat claim') || str.includes('in the future')) + ) { return 'dpopSkew' } if (str.includes('invalid_dpop_proof')) { @@ -116,5 +138,14 @@ export function categorizeOauthError( if (str.includes('invalid_grant')) { return 'invalidGrant' } + if ( + err && + typeof err === 'object' && + 'status' in err && + typeof err.status === 'number' && + err.status >= 500 + ) { + return 'serverError' + } return 'unknown' } diff --git a/src/state/session/reducer.ts b/src/state/session/reducer.ts index f02e3e486..600b0a85b 100644 --- a/src/state/session/reducer.ts +++ b/src/state/session/reducer.ts @@ -50,6 +50,10 @@ export type Action = | { type: 'logged-out-every-account' } + | { + type: 'oauth-session-terminated' + accountDid: string + } | { type: 'synced-accounts' syncedAccounts: SessionAccount[] @@ -146,7 +150,7 @@ let reducer = (state: State, action: Action): State => { // side effect const account = state.accounts.find(a => a.did === accountDid) - if (account) { + if (account && !account.isOauthSession) { createTemporaryAgentsAndResume([account]) .then(agents => unregisterPushToken(agents)) .then(() => @@ -174,7 +178,7 @@ let reducer = (state: State, action: Action): State => { const accountDid = currentAgentState.did // side effect const account = state.accounts.find(a => a.did === accountDid) - if (account && accountDid) { + if (account && accountDid && !account.isOauthSession) { createTemporaryAgentsAndResume([account]) .then(agents => unregisterPushToken(agents)) .then(() => @@ -203,7 +207,9 @@ let reducer = (state: State, action: Action): State => { } } case 'logged-out-every-account': { - createTemporaryAgentsAndResume(state.accounts) + createTemporaryAgentsAndResume( + state.accounts.filter(account => !account.isOauthSession), + ) .then(agents => unregisterPushToken(agents)) .then(() => logger.debug('Push token unregistered')) .catch(err => { @@ -223,6 +229,14 @@ let reducer = (state: State, action: Action): State => { needsPersist: true, } } + case 'oauth-session-terminated': { + if (state.currentAgentState.did !== action.accountDid) return state + return { + accounts: state.accounts, + currentAgentState: createPublicAgentState(), + needsPersist: true, + } + } case 'synced-accounts': { const {syncedAccounts, syncedCurrentDid} = action return { diff --git a/src/state/session/types.ts b/src/state/session/types.ts index ab12ae1b3..f48bdd939 100644 --- a/src/state/session/types.ts +++ b/src/state/session/types.ts @@ -46,6 +46,7 @@ export type SessionApiContext = { resumeSession: ( account: SessionAccount, isSwitchingAccounts?: boolean, + isAppLaunch?: boolean, ) => Promise removeAccount: (account: SessionAccount) => void /** -- knotmirror 0.0.1