From b8c73ed84875abada1b290806afcd3d120181173 Mon Sep 17 00:00:00 2001 From: Clinton Bowen Date: Wed, 5 Aug 2026 19:15:30 -0700 Subject: [PATCH] fix(auth): complete Android OAuth sign-in when the redirect cold-starts the app --- .../state/oauth-redirect-recovery.test.ts | 152 ++++++++++++++++++ src/screens/Login/LoginForm.tsx | 8 +- src/state/session/oauth-client.ts | 51 ++++-- src/state/session/useNativeOAuthRedirect.ts | 62 +++++++ src/view/shell/index.tsx | 2 + 5 files changed, 263 insertions(+), 12 deletions(-) create mode 100644 __tests__/state/oauth-redirect-recovery.test.ts create mode 100644 src/state/session/useNativeOAuthRedirect.ts diff --git a/__tests__/state/oauth-redirect-recovery.test.ts b/__tests__/state/oauth-redirect-recovery.test.ts new file mode 100644 index 000000000..0ee091ba1 --- /dev/null +++ b/__tests__/state/oauth-redirect-recovery.test.ts @@ -0,0 +1,152 @@ +/* eslint-disable @typescript-eslint/no-explicit-any, @typescript-eslint/no-unsafe-member-access -- test doubles model the untyped Expo OAuth client */ +import { + claimOAuthRedirect, + completeOAuthRedirect, + isOAuthCallbackUrl, + signInNativeAndroid, +} from '#/state/session/oauth-client' + +// oauth-client.ts constructs `new ExpoOAuthClient(...)` at module load, which pulls +// the expo native-module chain unavailable under jest. +jest.mock('@atproto/oauth-client-expo', () => ({ExpoOAuthClient: class {}})) + +const mockOpenAuthSessionAsync = jest.fn().mockResolvedValue({type: 'dismiss'}) +jest.mock('expo-web-browser', () => ({ + openAuthSessionAsync: (...a: any[]) => mockOpenAuthSessionAsync(...a), +})) + +let mockUrlHandler: ((e: {url: string}) => void) | null = null +jest.mock('expo-linking', () => ({ + addEventListener: (_evt: string, cb: (e: {url: string}) => void) => { + mockUrlHandler = cb + return {remove: jest.fn()} + }, +})) + +function makeClient(overrides: Partial = {}) { + return { + authorize: jest + .fn() + .mockResolvedValue(new URL('https://auth.example/authorize?x=1')), + callback: jest + .fn() + .mockResolvedValue({session: {sub: 'did:plc:abc'}, state: null}), + ...overrides, + } as any +} + +beforeEach(() => { + mockUrlHandler = null + mockOpenAuthSessionAsync.mockClear() +}) + +// Each test needs a URL no earlier test has claimed — the claim registry is +// module state, mirroring the real single-use-per-process behavior. +let seq = 0 +const uniqueRedirect = () => + `community.blacksky:/oauth/callback?code=c${seq++}&state=st${seq}` + +describe('isOAuthCallbackUrl', () => { + test('matches both single- and double-slash redirect forms', () => { + expect( + isOAuthCallbackUrl('community.blacksky:/oauth/callback?code=a'), + ).toBe(true) + expect( + isOAuthCallbackUrl('community.blacksky://oauth/callback?code=a'), + ).toBe(true) + }) + + test('rejects other deep-links', () => { + expect( + isOAuthCallbackUrl('community.blacksky:/intent/compose?text=hi'), + ).toBe(false) + expect( + isOAuthCallbackUrl('https://blacksky.community/oauth/callback'), + ).toBe(false) + }) +}) + +describe('claimOAuthRedirect', () => { + test('only the first claimant of a URL may exchange it', () => { + const url = uniqueRedirect() + expect(claimOAuthRedirect(url)).toBe(true) + expect(claimOAuthRedirect(url)).toBe(false) + }) + + test('claims are per-URL', () => { + expect(claimOAuthRedirect(uniqueRedirect())).toBe(true) + expect(claimOAuthRedirect(uniqueRedirect())).toBe(true) + }) +}) + +describe('completeOAuthRedirect', () => { + test('extracts params without new URL() and exchanges them', async () => { + const client = makeClient() + const session = await completeOAuthRedirect( + client, + 'community.blacksky:/oauth/callback?code=xyz&state=st&iss=https%3A%2F%2Fblacksky.app', + ) + + expect(session).toEqual({sub: 'did:plc:abc'}) + const params = client.callback.mock.calls[0][0] as URLSearchParams + expect(params.get('code')).toBe('xyz') + expect(params.get('iss')).toBe('https://blacksky.app') + expect(client.callback.mock.calls[0][1]).toEqual({ + redirect_uri: 'community.blacksky:/oauth/callback', + }) + }) + + test('works on the double-slash form the launcher may deliver', async () => { + const client = makeClient() + await completeOAuthRedirect( + client, + 'community.blacksky://oauth/callback?code=ds&state=st', + ) + const params = client.callback.mock.calls[0][0] as URLSearchParams + expect(params.get('code')).toBe('ds') + }) + + test('propagates an exhausted authorization window', async () => { + const client = makeClient({ + callback: jest.fn().mockRejectedValue(new Error('Unknown state')), + }) + await expect( + completeOAuthRedirect(client, uniqueRedirect()), + ).rejects.toThrow('Unknown state') + }) +}) + +describe('signInNativeAndroid claim interaction', () => { + test('claims the redirect so cold-start recovery stands down', async () => { + const client = makeClient() + const url = uniqueRedirect() + const promise = signInNativeAndroid(client, 'alice.test') + await new Promise(r => setImmediate(r)) + + mockUrlHandler!({url}) + await expect(promise).resolves.toEqual({sub: 'did:plc:abc'}) + + // The recovery path checks this before exchanging; a second exchange would + // fail against the now-spent state. + expect(claimOAuthRedirect(url)).toBe(false) + expect(client.callback).toHaveBeenCalledTimes(1) + }) + + test('a redirect already claimed elsewhere does not settle the sign-in', async () => { + const client = makeClient() + const url = uniqueRedirect() + expect(claimOAuthRedirect(url)).toBe(true) // e.g. recovery got there first + + const promise = signInNativeAndroid(client, 'alice.test') + await new Promise(r => setImmediate(r)) + + mockUrlHandler!({url}) + await new Promise(r => setImmediate(r)) + expect(client.callback).not.toHaveBeenCalled() + + // Still live, and a fresh redirect completes it. + const next = uniqueRedirect() + mockUrlHandler!({url: next}) + await expect(promise).resolves.toEqual({sub: 'did:plc:abc'}) + }) +}) diff --git a/src/screens/Login/LoginForm.tsx b/src/screens/Login/LoginForm.tsx index 18a26767e..6bdc74062 100644 --- a/src/screens/Login/LoginForm.tsx +++ b/src/screens/Login/LoginForm.tsx @@ -291,7 +291,13 @@ export const LoginForm = ({ variant="solid" color="secondary" size="large" - onPress={onPressBack}> + onPress={() => { + // Leaving the screen must also drop any pending sign-in. Its + // redirect listener would otherwise stay armed and race the next + // attempt for the same single-use authorization state. + abortRef.current?.abort() + onPressBack() + }}> Back diff --git a/src/state/session/oauth-client.ts b/src/state/session/oauth-client.ts index e4ee5ed9d..4a90eb7de 100644 --- a/src/state/session/oauth-client.ts +++ b/src/state/session/oauth-client.ts @@ -16,6 +16,41 @@ export const NATIVE_REDIRECT_URI = 'community.blacksky:/oauth/callback' // both forms rather than relying on `startsWith(NATIVE_REDIRECT_URI)`. const OAUTH_CALLBACK_RE = /^community\.blacksky:\/\/?oauth\/callback\b/ +export function isOAuthCallbackUrl(url: string): boolean { + return OAUTH_CALLBACK_RE.test(url) +} + +// Exchanging a redirect consumes its one-time `state` entry from the OAuth +// client's store, so exactly one handler may act on a given URL. Two are armed +// whenever the app is alive: the in-flight `signInNativeAndroid` listener, and +// the cold-start recovery in `useNativeOAuthRedirect`. Both claim here first; +// the loser backs off instead of calling `callback()` on spent state. +const claimedRedirects = new Set() + +export function claimOAuthRedirect(url: string): boolean { + if (claimedRedirects.has(url)) return false + claimedRedirects.add(url) + return true +} + +/** + * Exchange an OAuth redirect deep-link for a session. + * + * Slash-count-agnostic param extraction — do NOT rely on `new URL()`, which is + * fragile on Hermes for the custom `community.blacksky:` scheme. + */ +/* eslint-disable-next-line @typescript-eslint/no-explicit-any -- Expo OAuth types do not resolve in Linux CI */ +export async function completeOAuthRedirect(client: any, url: string) { + const query = url.includes('?') ? url.slice(url.indexOf('?') + 1) : '' + const params = new URLSearchParams(query) + /* eslint-disable-next-line @typescript-eslint/no-unsafe-member-access, @typescript-eslint/no-unsafe-call -- ditto */ + const {session} = await client.callback(params, { + redirect_uri: NATIVE_REDIRECT_URI, + }) + + return session +} + // Debug fetch wrapper — logs all OAuth-related network requests to Metro console const debugFetch: typeof fetch = async (input, init) => { const url = @@ -142,20 +177,14 @@ export async function signInNativeAndroid( const sub = Linking.addEventListener('url', ({url: incoming}) => { if (settled) return - if (!OAUTH_CALLBACK_RE.test(incoming)) return // ignore other deep-links + if (!isOAuthCallbackUrl(incoming)) return // ignore other deep-links + // Claimed synchronously so the cold-start handler, which can only run a + // tick later off a React effect, stands down for this URL. + if (!claimOAuthRedirect(incoming)) return settled = true cleanup() ;(async () => { - // Slash-count-agnostic param extraction — do NOT rely on `new URL()`, - // which is fragile on Hermes for the custom `community.blacksky:` scheme. - const query = incoming.includes('?') - ? incoming.slice(incoming.indexOf('?') + 1) - : '' - const params = new URLSearchParams(query) - const {session} = await client.callback(params, { - redirect_uri: redirectUri, - }) - resolve(session) + resolve(await completeOAuthRedirect(client, incoming)) })().catch(reject) }) diff --git a/src/state/session/useNativeOAuthRedirect.ts b/src/state/session/useNativeOAuthRedirect.ts new file mode 100644 index 000000000..4ec632506 --- /dev/null +++ b/src/state/session/useNativeOAuthRedirect.ts @@ -0,0 +1,62 @@ +import {useEffect} from 'react' +import * as Linking from 'expo-linking' + +import {logger} from '#/logger' +import {useSessionApi} from '#/state/session' +import { + claimOAuthRedirect, + completeOAuthRedirect, + getOAuthClient, + isOAuthCallbackUrl, +} from '#/state/session/oauth-client' + +/** + * Completes a native OAuth sign-in whose redirect arrived without an in-flight + * `signInNativeAndroid` waiting for it. + * + * The sign-in helper listens for the redirect with `Linking.addEventListener`, + * which only ever sees URLs delivered to a *running* app. That is enough while + * the app stays alive, but the 2FA flow forces the user out to an email app to + * fetch a code, and Android is free to kill our backgrounded process while they + * are gone. The redirect then cold-starts the app, where the listener does not + * exist yet and the launch URL is only reachable via the initial-URL APIs — so + * the callback landed nowhere and the user was dropped on the logged-out screen + * with their sign-in silently abandoned. + * + * `useLinkingURL()` reports the launch URL as well as later ones, so mounting + * this recovers those sign-ins. The authorization state that `callback()` needs + * outlives the process: @atproto/oauth-client-expo keeps it in MMKV for ten + * minutes, which also bounds how long a detour can take before the user has to + * start over. + */ +export function useNativeOAuthRedirect() { + const incomingUrl = Linking.useLinkingURL() + const {login} = useSessionApi() + + useEffect(() => { + if (!incomingUrl || !isOAuthCallbackUrl(incomingUrl)) return + // A live signInNativeAndroid claims the URL first and completes it itself; + // the exchange is single-use, so only one of us may run it. + if (!claimOAuthRedirect(incomingUrl)) return + + logger.warn('oauth: completing native redirect outside of sign-in flow') + void (async () => { + try { + const session = await completeOAuthRedirect( + getOAuthClient(), + incomingUrl, + ) + await login( + {service: '', identifier: '', password: '', oauthSession: session}, + 'LoginForm', + ) + } catch (e) { + // Most likely the ten-minute authorization window elapsed while the + // user was away, which cannot be recovered without a fresh sign-in. + logger.error('oauth: native redirect recovery failed', { + error: String(e), + }) + } + })() + }, [incomingUrl, login]) +} diff --git a/src/view/shell/index.tsx b/src/view/shell/index.tsx index e240df080..90adf7f15 100644 --- a/src/view/shell/index.tsx +++ b/src/view/shell/index.tsx @@ -15,6 +15,7 @@ import {AppviewFallbackController} from '#/state/appview-fallback-controller' import {useDialogFullyExpandedCountContext} from '#/state/dialogs' import {useProfileEnrichment} from '#/state/queries/profile-enrichment' import {useSession} from '#/state/session' +import {useNativeOAuthRedirect} from '#/state/session/useNativeOAuthRedirect' import { useIsDrawerOpen, useIsDrawerSwipeDisabled, @@ -200,6 +201,7 @@ export function Shell() { const fullyExpandedCount = useDialogFullyExpandedCountContext() useIntentHandler() + useNativeOAuthRedirect() useEffect(() => { setSystemUITheme('theme', t) -- knotmirror 0.0.1