From 46a3fcc58c738850bae2bf40951b7ceb93bc4861 Mon Sep 17 00:00:00 2001 From: Rishi Balakrishnan Date: Thu, 30 Jul 2026 13:09:17 -0400 Subject: [PATCH] fix android oauth 2fa signin (#144) --- .../state/oauth-client-native-signin.test.ts | 129 ++++++++++++++++++ src/screens/Login/LoginForm.tsx | 97 +++++++++---- src/state/session/oauth-client.ts | 108 ++++++++++++++- 3 files changed, 303 insertions(+), 31 deletions(-) create mode 100644 __tests__/state/oauth-client-native-signin.test.ts diff --git a/__tests__/state/oauth-client-native-signin.test.ts b/__tests__/state/oauth-client-native-signin.test.ts new file mode 100644 index 000000000..9f411d5e5 --- /dev/null +++ b/__tests__/state/oauth-client-native-signin.test.ts @@ -0,0 +1,129 @@ +/* eslint-disable @typescript-eslint/no-explicit-any, @typescript-eslint/no-unsafe-member-access -- test doubles model the untyped Expo OAuth client */ +import {signInNativeAndroid} from '#/state/session/oauth-client' + +// --- mocks --- +// oauth-client.ts constructs `new ExpoOAuthClient(...)` at module load, which pulls +// the expo native-module chain unavailable under jest. signInNativeAndroid takes its +// client as a parameter, so stub the package to keep the import hermetic. +jest.mock('@atproto/oauth-client-expo', () => ({ExpoOAuthClient: class {}})) + +const mockOpenAuthSessionAsync = jest.fn().mockResolvedValue({type: 'dismiss'}) +// NB: intentionally do NOT mock dismissBrowser. On the real Android native module +// it is unimplemented (returns undefined), so the helper must never call it — this +// mock shape (no dismissBrowser export) mirrors that and guards the regression. +jest.mock('expo-web-browser', () => ({ + openAuthSessionAsync: (...a: any[]) => mockOpenAuthSessionAsync(...a), +})) + +let mockUrlHandler: ((e: {url: string}) => void) | null = null +const mockRemoveSub = jest.fn() +jest.mock('expo-linking', () => ({ + addEventListener: (_evt: string, cb: (e: {url: string}) => void) => { + mockUrlHandler = cb + return {remove: mockRemoveSub} + }, +})) + +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() + mockRemoveSub.mockClear() +}) + +const REDIRECT = 'community.blacksky:/oauth/callback' + +test('completes via redirect deep-link, ignoring the browser dismiss', async () => { + const client = makeClient() + const promise = signInNativeAndroid(client, 'alice.test') + + await new Promise(r => setImmediate(r)) + expect(mockOpenAuthSessionAsync).toHaveBeenCalledTimes(1) + // showInRecents:true keeps the Custom Tab alive + in recents so the user can + // leave to fetch a 2FA code and return to it (Android would otherwise destroy it). + expect(mockOpenAuthSessionAsync.mock.calls[0][2]).toEqual({ + showInRecents: true, + }) + expect(mockUrlHandler).toBeTruthy() + + mockUrlHandler!({url: `${REDIRECT}?code=xyz&state=st`}) + + const session = await promise + expect(session).toEqual({sub: 'did:plc:abc'}) + expect(client.callback).toHaveBeenCalledTimes(1) + const params = client.callback.mock.calls[0][0] as URLSearchParams + expect(params.get('code')).toBe('xyz') + expect(mockRemoveSub).toHaveBeenCalled() +}) + +test('ignores unrelated deep-links', async () => { + const client = makeClient() + const promise = signInNativeAndroid(client, 'alice.test') + await new Promise(r => setImmediate(r)) + + mockUrlHandler!({url: 'community.blacksky:/intent/compose?text=hi'}) + expect(client.callback).not.toHaveBeenCalled() + + mockUrlHandler!({url: `${REDIRECT}?code=ok&state=st`}) + await expect(promise).resolves.toEqual({sub: 'did:plc:abc'}) +}) + +test('rejects and removes the listener when aborted', async () => { + const client = makeClient() + const controller = new AbortController() + const promise = signInNativeAndroid(client, 'alice.test', { + signal: controller.signal, + }) + await new Promise(r => setImmediate(r)) + + controller.abort() + await expect(promise).rejects.toThrow('OAUTH_CANCELLED') + expect(mockRemoveSub).toHaveBeenCalled() + expect(client.callback).not.toHaveBeenCalled() +}) + +test('surfaces an error redirect (Kind 2) via callback throwing', async () => { + const client = makeClient({ + callback: jest.fn().mockRejectedValue(new Error('access_denied')), + }) + const promise = signInNativeAndroid(client, 'alice.test') + await new Promise(r => setImmediate(r)) + + mockUrlHandler!({url: `${REDIRECT}?error=access_denied&state=st`}) + await expect(promise).rejects.toThrow('access_denied') +}) + +test('completes via a double-slash redirect deep-link', async () => { + const client = makeClient() + const promise = signInNativeAndroid(client, 'alice.test') + await new Promise(r => setImmediate(r)) + + mockUrlHandler!({url: 'community.blacksky://oauth/callback?code=ds&state=st'}) + + const session = await promise + expect(session).toEqual({sub: 'did:plc:abc'}) + expect(client.callback).toHaveBeenCalledTimes(1) + const params = client.callback.mock.calls[0][0] as URLSearchParams + expect(params.get('code')).toBe('ds') +}) + +test('rejects (no hang) when the browser fails to launch', async () => { + mockOpenAuthSessionAsync.mockRejectedValueOnce(new Error('no browser')) + const client = makeClient() + const promise = signInNativeAndroid(client, 'alice.test') + + // No redirect is ever delivered; the flow must still settle via the launch error. + await expect(promise).rejects.toThrow('no browser') + expect(client.callback).not.toHaveBeenCalled() +}) diff --git a/src/screens/Login/LoginForm.tsx b/src/screens/Login/LoginForm.tsx index 77377229a..ceb52540b 100644 --- a/src/screens/Login/LoginForm.tsx +++ b/src/screens/Login/LoginForm.tsx @@ -7,17 +7,18 @@ import {Trans} from '@lingui/react/macro' import {cleanError, isNetworkError} from '#/lib/strings/errors' import {logger} from '#/logger' import {useSessionApi} from '#/state/session' -import {getOAuthClient} from '#/state/session/oauth-client' +import {getOAuthClient, signInNativeAndroid} from '#/state/session/oauth-client' import { isHandleResolutionError, resolveDeactivatedHandle, } from '#/state/session/resolveForLogin' -import {atoms as a} from '#/alf' +import {atoms as a, useTheme} from '#/alf' import {Button, ButtonIcon, ButtonText} from '#/components/Button' import {FormError} from '#/components/forms/FormError' import * as TextField from '#/components/forms/TextField' import {At_Stroke2_Corner0_Rounded as At} from '#/components/icons/At' import {Loader} from '#/components/Loader' +import {Text} from '#/components/Typography' import {FormContainer} from './FormContainer' export const LoginForm = ({ @@ -32,7 +33,10 @@ export const LoginForm = ({ onPressBack: () => void }) => { const [isProcessing, setIsProcessing] = useState(false) + const [awaitingRedirect, setAwaitingRedirect] = useState(false) + const abortRef = useRef(null) const identifierValueRef = useRef(initialHandle || '') + const t = useTheme() const {_} = useLingui() const {login} = useSessionApi() @@ -51,38 +55,45 @@ export const LoginForm = ({ setIsProcessing(true) + const client = getOAuthClient() + const controller = Platform.OS === 'android' ? new AbortController() : null + if (controller) { + abortRef.current = controller + setAwaitingRedirect(true) + } + /* eslint-disable @typescript-eslint/no-unsafe-call, @typescript-eslint/no-unsafe-member-access -- Expo OAuth types do not resolve in Linux CI */ + const doSignIn = (id: string) => + controller + ? signInNativeAndroid(client, id, {signal: controller.signal}) + : client.signIn(id) + try { - const client = getOAuthClient() let session - /* eslint-disable @typescript-eslint/no-unsafe-call, @typescript-eslint/no-unsafe-member-access -- Expo OAuth types do not resolve in Linux CI */ try { - session = await client.signIn(identifier) + session = await doSignIn(identifier) } catch (e) { if (!isHandleResolutionError(e)) throw e + if (controller?.signal.aborted) throw new Error('OAUTH_CANCELLED') const did = await resolveDeactivatedHandle(identifier) - session = await client.signIn(did) + if (controller?.signal.aborted) throw new Error('OAUTH_CANCELLED') + session = await doSignIn(did) } /* eslint-enable @typescript-eslint/no-unsafe-call, @typescript-eslint/no-unsafe-member-access */ + // On native, signInNativeAndroid/signIn returns the session directly. + // On web, the browser redirects away and App.web.tsx handles the callback. if (Platform.OS !== 'web' && session) { - // On native, signIn() returns the session directly after the - // in-app browser completes the OAuth flow. await login( - { - service: '', - identifier: '', - password: '', - oauthSession: session, - }, + {service: '', identifier: '', password: '', oauthSession: session}, 'LoginForm', ) } - // On web, the browser redirects away and App.web.tsx handles the callback. } catch (e) { const errMsg = String(e) LayoutAnimation.configureNext(LayoutAnimation.Presets.easeInEaseOut) - setIsProcessing(false) - if (isNetworkError(e)) { + if (errMsg.includes('OAUTH_CANCELLED')) { + // User-initiated cancel (Android): silent reset, no error banner. + } else if (isNetworkError(e)) { logger.warn('Failed to start OAuth sign-in due to network error', { error: errMsg, }) @@ -95,6 +106,10 @@ export const LoginForm = ({ logger.warn('Failed to start OAuth sign-in', {error: errMsg}) setError(cleanError(errMsg)) } + } finally { + setIsProcessing(false) + setAwaitingRedirect(false) + abortRef.current = null } } @@ -130,6 +145,13 @@ export const LoginForm = ({ + {awaitingRedirect && ( + + + Finishing sign-in… complete it in your browser, or cancel. + + + )} - + {awaitingRedirect ? ( + + ) : ( + + )} ) diff --git a/src/state/session/oauth-client.ts b/src/state/session/oauth-client.ts index 9d0061bf4..e4ee5ed9d 100644 --- a/src/state/session/oauth-client.ts +++ b/src/state/session/oauth-client.ts @@ -1,3 +1,5 @@ +import * as Linking from 'expo-linking' +import {openAuthSessionAsync} from 'expo-web-browser' import {ExpoOAuthClient} from '@atproto/oauth-client-expo' import {logger} from '#/logger' @@ -7,7 +9,12 @@ import { } from '#/state/session/oauth-telemetry' import {OAUTH_BASE_URL, OAUTH_CLIENT_NAME, OAUTH_SCOPE} from './oauth-config' -const NATIVE_REDIRECT_URI = 'community.blacksky:/oauth/callback' +export const NATIVE_REDIRECT_URI = 'community.blacksky:/oauth/callback' + +// The redirect deep-link can arrive with either a single (`:/oauth`) or double +// (`://oauth`) slash depending on the Android/Hermes deep-link path, so match +// both forms rather than relying on `startsWith(NATIVE_REDIRECT_URI)`. +const OAUTH_CALLBACK_RE = /^community\.blacksky:\/\/?oauth\/callback\b/ // Debug fetch wrapper — logs all OAuth-related network requests to Metro console const debugFetch: typeof fetch = async (input, init) => { @@ -80,3 +87,102 @@ const BSKY_OAUTH_CLIENT = new ExpoOAuthClient({ export function getOAuthClient() { return BSKY_OAUTH_CLIENT } + +/** + * Android-only OAuth sign-in. + * + * `client.signIn` relies on `openAuthSessionAsync`'s result, which on Android is + * a fragile AppState-based polyfill: returning to the app (e.g. after switching + * to an email app to fetch a 2FA code) makes it resolve `{type:'dismiss'}` even + * though the Custom Tab is still open. See docs/plans/2026-07-29-android-oauth-2fa-signin-design.md. + * + * Instead we drive the flow with the public `authorize()`/`callback()` methods and + * treat the redirect deep-link (delivered via `Linking`) as the only source of + * truth. The browser promise result — including the phantom `dismiss` — is ignored. + * + * Pass an `AbortSignal` to support user cancellation (a genuine cancel produces no + * redirect, so the UI must provide one). + */ +/* 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 */ +export async function signInNativeAndroid( + client: any, + identifier: string, + {signal}: {signal?: AbortSignal} = {}, +): Promise { + const redirectUri = NATIVE_REDIRECT_URI + + let url + try { + url = await client.authorize(identifier, {display: 'touch', signal}) + } catch (e) { + // An abort during authorize() rejects with a DOMException `AbortError`; + // normalize it so the UI's cancel branch recognizes it like every other path. + if (signal?.aborted) throw new Error('OAUTH_CANCELLED') + throw e + } + + return await new Promise((resolve, reject) => { + let settled = false + + const cleanup = () => { + sub.remove() + signal?.removeEventListener('abort', onAbort) + // NOTE: we deliberately do NOT call dismissBrowser() here. It is not + // implemented by the expo-web-browser Android native module (returns + // undefined), so calling it throws; and Custom Tabs cannot be dismissed + // programmatically on Android anyway. This helper is Android-only. + } + + const onAbort = () => { + if (settled) return + settled = true + cleanup() + reject(new Error('OAUTH_CANCELLED')) + } + + const sub = Linking.addEventListener('url', ({url: incoming}) => { + if (settled) return + if (!OAUTH_CALLBACK_RE.test(incoming)) return // ignore other deep-links + 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) + })().catch(reject) + }) + + if (signal) { + if (signal.aborted) return onAbort() + signal.addEventListener('abort', onAbort) + } + + // Fire the browser. Its RESULT (incl. Android's phantom `dismiss`) is + // intentionally ignored — the redirect listener above completes the flow. + // A genuine launch REJECTION, however, must surface, or the promise would + // hang forever with no redirect ever arriving. + // + // `showInRecents: true` is critical for the 2FA flow. By default Expo + // launches the Custom Tab with FLAG_ACTIVITY_NO_HISTORY + EXCLUDE_FROM_RECENTS, + // so leaving the tab (e.g. to fetch a 2FA code from an email app) DESTROYS it + // and it never reappears in the recents switcher — the user can never get back + // to enter the code. showInRecents keeps the tab alive and in recents so they + // can return to it. iOS ignores this option. + openAuthSessionAsync(url.toString(), redirectUri, { + showInRecents: true, + }).catch(err => { + if (settled) return + settled = true + cleanup() + reject(err instanceof Error ? err : new Error(String(err))) + }) + }) + /* eslint-enable @typescript-eslint/no-explicit-any, @typescript-eslint/no-unsafe-call, @typescript-eslint/no-unsafe-member-access */ +} -- knotmirror 0.0.1