From e9b44ca5abe1dbfdc50a0254f52fe0f3b6dedc0f Mon Sep 17 00:00:00 2001 From: Clinton Bowen Date: Wed, 5 Aug 2026 19:27:13 -0700 Subject: [PATCH] fix(auth): key the OAuth redirect claim on state and abort on unmount --- .../state/oauth-client-native-signin.test.ts | 15 +++++-- .../state/oauth-redirect-recovery.test.ts | 44 ++++++++++++++++++- src/screens/Login/LoginForm.tsx | 17 +++---- src/state/session/oauth-client.ts | 36 ++++++++++----- src/state/session/useNativeOAuthRedirect.ts | 10 ++++- 5 files changed, 96 insertions(+), 26 deletions(-) diff --git a/__tests__/state/oauth-client-native-signin.test.ts b/__tests__/state/oauth-client-native-signin.test.ts index 9f411d5e5..d0a4a31d2 100644 --- a/__tests__/state/oauth-client-native-signin.test.ts +++ b/__tests__/state/oauth-client-native-signin.test.ts @@ -44,6 +44,11 @@ beforeEach(() => { const REDIRECT = 'community.blacksky:/oauth/callback' +// A real `state` is a fresh nonce per authorize(), and the redirect claim +// registry is keyed on it to stay single-use, so each test needs its own. +let stateSeq = 0 +const nextState = () => `st${++stateSeq}` + test('completes via redirect deep-link, ignoring the browser dismiss', async () => { const client = makeClient() const promise = signInNativeAndroid(client, 'alice.test') @@ -57,7 +62,7 @@ test('completes via redirect deep-link, ignoring the browser dismiss', async () }) expect(mockUrlHandler).toBeTruthy() - mockUrlHandler!({url: `${REDIRECT}?code=xyz&state=st`}) + mockUrlHandler!({url: `${REDIRECT}?code=xyz&state=${nextState()}`}) const session = await promise expect(session).toEqual({sub: 'did:plc:abc'}) @@ -75,7 +80,7 @@ test('ignores unrelated deep-links', async () => { mockUrlHandler!({url: 'community.blacksky:/intent/compose?text=hi'}) expect(client.callback).not.toHaveBeenCalled() - mockUrlHandler!({url: `${REDIRECT}?code=ok&state=st`}) + mockUrlHandler!({url: `${REDIRECT}?code=ok&state=${nextState()}`}) await expect(promise).resolves.toEqual({sub: 'did:plc:abc'}) }) @@ -100,7 +105,7 @@ test('surfaces an error redirect (Kind 2) via callback throwing', async () => { const promise = signInNativeAndroid(client, 'alice.test') await new Promise(r => setImmediate(r)) - mockUrlHandler!({url: `${REDIRECT}?error=access_denied&state=st`}) + mockUrlHandler!({url: `${REDIRECT}?error=access_denied&state=${nextState()}`}) await expect(promise).rejects.toThrow('access_denied') }) @@ -109,7 +114,9 @@ test('completes via a double-slash redirect deep-link', async () => { const promise = signInNativeAndroid(client, 'alice.test') await new Promise(r => setImmediate(r)) - mockUrlHandler!({url: 'community.blacksky://oauth/callback?code=ds&state=st'}) + mockUrlHandler!({ + url: `community.blacksky://oauth/callback?code=ds&state=${nextState()}`, + }) const session = await promise expect(session).toEqual({sub: 'did:plc:abc'}) diff --git a/__tests__/state/oauth-redirect-recovery.test.ts b/__tests__/state/oauth-redirect-recovery.test.ts index 0ee091ba1..33b3fd526 100644 --- a/__tests__/state/oauth-redirect-recovery.test.ts +++ b/__tests__/state/oauth-redirect-recovery.test.ts @@ -67,16 +67,56 @@ describe('isOAuthCallbackUrl', () => { }) describe('claimOAuthRedirect', () => { - test('only the first claimant of a URL may exchange it', () => { + test('only the first claimant of a redirect may exchange it', () => { const url = uniqueRedirect() expect(claimOAuthRedirect(url)).toBe(true) expect(claimOAuthRedirect(url)).toBe(false) }) - test('claims are per-URL', () => { + test('distinct authorizations are claimed independently', () => { expect(claimOAuthRedirect(uniqueRedirect())).toBe(true) expect(claimOAuthRedirect(uniqueRedirect())).toBe(true) }) + + // The two claimants read the URL from different native modules (RN's 'url' + // event vs Expo's getLinkingURL), so the strings can differ in shape for the + // same authorization. Keying on `state` is what makes the dedupe hold. + test('dedupes across slash forms of the same state', () => { + expect( + claimOAuthRedirect('community.blacksky:/oauth/callback?code=a&state=SS1'), + ).toBe(true) + expect( + claimOAuthRedirect( + 'community.blacksky://oauth/callback?code=a&state=SS1', + ), + ).toBe(false) + }) + + test('dedupes when param order or extra params differ', () => { + expect( + claimOAuthRedirect('community.blacksky:/oauth/callback?code=b&state=SS2'), + ).toBe(true) + expect( + claimOAuthRedirect( + 'community.blacksky:/oauth/callback?state=SS2&iss=https%3A%2F%2Fblacksky.app&code=b', + ), + ).toBe(false) + }) + + test('different states on the same path are not confused', () => { + expect( + claimOAuthRedirect('community.blacksky:/oauth/callback?code=c&state=SS3'), + ).toBe(true) + expect( + claimOAuthRedirect('community.blacksky:/oauth/callback?code=c&state=SS4'), + ).toBe(true) + }) + + test('a redirect with no state stays single-use', () => { + const url = 'community.blacksky:/oauth/callback?error=invalid_request' + expect(claimOAuthRedirect(url)).toBe(true) + expect(claimOAuthRedirect(url)).toBe(false) + }) }) describe('completeOAuthRedirect', () => { diff --git a/src/screens/Login/LoginForm.tsx b/src/screens/Login/LoginForm.tsx index 6bdc74062..629c574d8 100644 --- a/src/screens/Login/LoginForm.tsx +++ b/src/screens/Login/LoginForm.tsx @@ -1,4 +1,4 @@ -import {useRef, useState} from 'react' +import {useEffect, useRef, useState} from 'react' import {Keyboard, LayoutAnimation, Platform, View} from 'react-native' import {type ComAtprotoServerDescribeServer} from '@atproto/api' import {msg} from '@lingui/core/macro' @@ -54,6 +54,13 @@ export const LoginForm = ({ const {_} = useLingui() const {login} = useSessionApi() + // Drop any pending sign-in when the screen goes away. Hardware back and the + // header back button pop this form without routing through onPressBack, so + // anything hung off a press handler would leave the redirect listener armed — + // and a stale listener matches on URL shape alone, so it would swallow the + // *next* attempt's redirect and spend its authorization state. + useEffect(() => () => abortRef.current?.abort(), []) + const onPressNext = async () => { if (isProcessing || processingRef.current) return processingRef.current = true @@ -291,13 +298,7 @@ export const LoginForm = ({ variant="solid" color="secondary" size="large" - 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() - }}> + onPress={onPressBack}> Back diff --git a/src/state/session/oauth-client.ts b/src/state/session/oauth-client.ts index 4a90eb7de..4df48cd1b 100644 --- a/src/state/session/oauth-client.ts +++ b/src/state/session/oauth-client.ts @@ -20,16 +20,34 @@ export function isOAuthCallbackUrl(url: string): boolean { return OAUTH_CALLBACK_RE.test(url) } +function redirectQuery(url: string): URLSearchParams { + return new URLSearchParams( + url.includes('?') ? url.slice(url.indexOf('?') + 1) : '', + ) +} + // 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() +// client's store, so exactly one handler may act on a given redirect. 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. +// +// Keyed on `state` rather than the URL because `state` *is* the contested +// resource — it is what `callback()` deletes — and because the two claimants do +// not read the URL from the same place: `signInNativeAndroid` takes React +// Native's `'url'` event while the recovery hook takes Expo's separate +// `getLinkingURL()`. Nothing guarantees those strings match byte for byte, and +// this URI is already known to vary by a slash (see OAUTH_CALLBACK_RE above), +// which URL-keyed dedupe would miss — letting both exchange the same code. +const claimedStates = new Set() export function claimOAuthRedirect(url: string): boolean { - if (claimedRedirects.has(url)) return false - claimedRedirects.add(url) + // No `state` should be impossible; treating the URL as its own key keeps a + // malformed redirect single-use rather than un-claimable. + const key = redirectQuery(url).get('state') ?? url + if (claimedStates.has(key)) return false + claimedStates.add(key) return true } @@ -41,10 +59,8 @@ export function claimOAuthRedirect(url: string): boolean { */ /* 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, { + const {session} = await client.callback(redirectQuery(url), { redirect_uri: NATIVE_REDIRECT_URI, }) diff --git a/src/state/session/useNativeOAuthRedirect.ts b/src/state/session/useNativeOAuthRedirect.ts index 4ec632506..2032074db 100644 --- a/src/state/session/useNativeOAuthRedirect.ts +++ b/src/state/session/useNativeOAuthRedirect.ts @@ -26,8 +26,14 @@ import { * `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. + * minutes. + * + * That MMKV TTL is not the real deadline, though. The PDS expires the + * authorization request after AUTHORIZATION_INACTIVITY_TIMEOUT — five minutes — + * refreshed only by requests to the authorization server, which a browser tab + * parked on the 2FA form does not make. A detour longer than five minutes comes + * back as `error=access_denied` no matter what the client does, so recovery here + * cannot be complete on its own. */ export function useNativeOAuthRedirect() { const incomingUrl = Linking.useLinkingURL() -- knotmirror 0.0.1