Skip to content

Commit dac76d1

Browse files
committed
fix(expo): recover native sync after background reads and honor request aborts
Native client sync now waits until the app is active and rereads the token cache when a read fails, so bootstrap and native client events reconcile instead of failing permanently. Request hooks stop waiting for activation when the request is aborted.
1 parent b302647 commit dac76d1

6 files changed

Lines changed: 276 additions & 24 deletions

File tree

‎packages/expo/src/provider/__tests__/ClerkProvider.nativeClientSync.test.tsx‎

Lines changed: 118 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -11,7 +11,16 @@ import {
1111
} from '../nativeClientSyncCoordinator';
1212

1313
const mocks = vi.hoisted(() => {
14+
const appStateListeners = new Set<(state: string) => void>();
1415
return {
16+
appState: {
17+
currentState: 'active' as string,
18+
addEventListener: (_type: 'change', listener: (state: string) => void) => {
19+
appStateListeners.add(listener);
20+
return { remove: () => appStateListeners.delete(listener) };
21+
},
22+
},
23+
appStateListeners,
1524
configure: vi.fn(),
1625
getClientToken: vi.fn(),
1726
nativeClientEvent: null as unknown,
@@ -62,6 +71,7 @@ vi.mock('@clerk/react/internal', () => {
6271

6372
vi.mock('react-native', () => {
6473
return {
74+
AppState: mocks.appState,
6575
NativeModules: {
6676
BlobModule: {},
6777
},
@@ -106,8 +116,10 @@ vi.mock('../../specs/NativeClerkModule', () => {
106116
};
107117
});
108118

109-
vi.mock('../../utils/runtime', () => {
119+
vi.mock('../../utils/runtime', async () => {
120+
const runtime = await vi.importActual<typeof import('../../utils/runtime')>('../../utils/runtime');
110121
return {
122+
...runtime,
111123
isNative: () => true,
112124
isWeb: () => false,
113125
};
@@ -122,6 +134,18 @@ vi.mock('../singleton', () => {
122134
};
123135
});
124136

137+
const setAppState = (state: string) => {
138+
mocks.appState.currentState = state;
139+
for (const listener of [...mocks.appStateListeners]) {
140+
listener(state);
141+
}
142+
};
143+
144+
const rejectUnlessAppIsActive = (token: string) => () =>
145+
mocks.appState.currentState === 'active'
146+
? Promise.resolve(token)
147+
: Promise.reject(new Error('User interaction is not allowed.'));
148+
125149
function deferred(): { promise: Promise<void>; resolve: () => void } {
126150
let resolve!: () => void;
127151
const promise = new Promise<void>(innerResolve => {
@@ -142,6 +166,8 @@ describe('ClerkProvider native client sync', () => {
142166
beforeEach(() => {
143167
__internal_resetNativeClientSyncCoordinator();
144168
vi.clearAllMocks();
169+
mocks.appState.currentState = 'active';
170+
mocks.appStateListeners.clear();
145171
mocks.nativeClientEvent = null;
146172
mocks.configure.mockResolvedValue(undefined);
147173
mocks.getClientToken.mockResolvedValue(null);
@@ -531,6 +557,97 @@ describe('ClerkProvider native client sync', () => {
531557
consoleError.mockRestore();
532558
});
533559

560+
test('finishes bootstrap with the cached token once the app is active when the token cache cannot be read in the background', async () => {
561+
const consoleError = vi.spyOn(console, 'error').mockImplementation(() => undefined);
562+
setAppState('background');
563+
mocks.tokenCache.getToken.mockImplementation(rejectUnlessAppIsActive('client-token'));
564+
mocks.getClientToken.mockResolvedValue('client-token');
565+
566+
const { rerender } = render(
567+
<ClerkProvider
568+
publishableKey='pk_test_123'
569+
tokenCache={mocks.tokenCache}
570+
/>,
571+
);
572+
573+
await act(async () => {
574+
await new Promise(resolve => setTimeout(resolve, 300));
575+
});
576+
expect(mocks.configure).not.toHaveBeenCalled();
577+
578+
act(() => {
579+
setAppState('active');
580+
});
581+
582+
await waitFor(() => expect(mocks.configure).toHaveBeenCalledWith('pk_test_123', 'client-token'));
583+
expect(mocks.configure).toHaveBeenCalledTimes(1);
584+
expect(mocks.syncClientStateFromJs).not.toHaveBeenCalled();
585+
expect(mocks.tokenCache.clearToken).not.toHaveBeenCalled();
586+
587+
mocks.nativeClientEvent = {
588+
issuedAt: 1,
589+
changed: { client: true, deviceToken: true },
590+
deviceToken: 'native-client-token',
591+
};
592+
rerender(
593+
<ClerkProvider
594+
publishableKey='pk_test_123'
595+
tokenCache={mocks.tokenCache}
596+
/>,
597+
);
598+
599+
await waitFor(() =>
600+
expect(mocks.tokenCache.saveToken).toHaveBeenCalledWith(CLERK_CLIENT_JWT_KEY, 'native-client-token'),
601+
);
602+
consoleError.mockRestore();
603+
});
604+
605+
test('applies a native client change once the app is active when the token cache cannot be read in the background', async () => {
606+
const consoleError = vi.spyOn(console, 'error').mockImplementation(() => undefined);
607+
mocks.tokenCache.getToken.mockImplementation(rejectUnlessAppIsActive('client-token'));
608+
mocks.getClientToken.mockResolvedValue('client-token');
609+
610+
const { rerender } = render(
611+
<ClerkProvider
612+
publishableKey='pk_test_123'
613+
tokenCache={mocks.tokenCache}
614+
/>,
615+
);
616+
617+
await waitFor(() => expect(mocks.configure).toHaveBeenCalledWith('pk_test_123', 'client-token'));
618+
await act(async () => {
619+
await Promise.resolve();
620+
});
621+
622+
setAppState('background');
623+
mocks.nativeClientEvent = {
624+
issuedAt: 1,
625+
changed: { client: true, deviceToken: true },
626+
deviceToken: 'native-client-token',
627+
};
628+
rerender(
629+
<ClerkProvider
630+
publishableKey='pk_test_123'
631+
tokenCache={mocks.tokenCache}
632+
/>,
633+
);
634+
635+
await act(async () => {
636+
await new Promise(resolve => setTimeout(resolve, 50));
637+
});
638+
expect(mocks.tokenCache.saveToken).not.toHaveBeenCalled();
639+
640+
act(() => {
641+
setAppState('active');
642+
});
643+
644+
await waitFor(() =>
645+
expect(mocks.tokenCache.saveToken).toHaveBeenCalledWith(CLERK_CLIENT_JWT_KEY, 'native-client-token'),
646+
);
647+
expect(mocks.clerkInstance.__internal_reloadInitialResources).toHaveBeenCalled();
648+
consoleError.mockRestore();
649+
});
650+
534651
test('disables synchronization when switching publishable keys fails to configure native', async () => {
535652
const consoleError = vi.spyOn(console, 'error').mockImplementation(() => undefined);
536653
const configureError = new Error('native key switch failed');

‎packages/expo/src/provider/nativeClientSync.tsx‎

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -7,6 +7,7 @@ import type { TokenCache } from '../cache/types';
77
import { CLERK_CLIENT_JWT_KEY } from '../constants';
88
import { type NativeClientEvent, useNativeClientEvents } from '../hooks/useNativeClientEvents';
99
import { ClerkExpoModule as NativeClerkModule } from '../utils/native-module';
10+
import { waitUntilAppIsActive } from '../utils/runtime';
1011
import {
1112
registerNativeToJsSyncHandler,
1213
synchronizeNativeClientToJs,
@@ -502,6 +503,15 @@ async function getCachedDeviceToken(tokenCache: TokenCache | undefined): Promise
502503
return null;
503504
}
504505

506+
try {
507+
return await readCachedDeviceToken(tokenCache);
508+
} catch {
509+
await waitUntilAppIsActive();
510+
}
511+
return readCachedDeviceToken(tokenCache);
512+
}
513+
514+
async function readCachedDeviceToken(tokenCache: TokenCache): Promise<string | null | undefined> {
505515
let timeoutId: ReturnType<typeof setTimeout> | undefined;
506516
try {
507517
const result = await Promise.race([

‎packages/expo/src/provider/singleton/__tests__/createClerkInstance.test.ts‎

Lines changed: 109 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -477,6 +477,115 @@ describe('createClerkInstance', () => {
477477
expect(requestInit.headers.has('authorization')).toBe(false);
478478
});
479479

480+
test('stops waiting for the app to become active when the request is aborted', async () => {
481+
setAppState('background');
482+
const getToken = vi.fn<TokenCache['getToken']>(() => Promise.reject(new Error('User interaction is not allowed.')));
483+
const tokenCache: TokenCache = {
484+
getToken,
485+
saveToken: vi.fn(() => Promise.resolve()),
486+
};
487+
488+
const createClerkInstance = await loadCreateClerkInstance();
489+
const getClerkInstance = createClerkInstance(MockClerk as unknown as typeof Clerk);
490+
const clerk = getClerkInstance({
491+
publishableKey: 'pk_test_123',
492+
tokenCache,
493+
}) as unknown as MockClerk;
494+
495+
const beforeRequest = clerk.__internal_onBeforeRequest.mock.calls[0][0];
496+
const controller = new AbortController();
497+
const abortReason = new Error('client fetch timed out');
498+
const requestInit = {
499+
headers: new Headers(),
500+
signal: controller.signal,
501+
url: new URL('https://clerk.example.com/v1/client'),
502+
};
503+
504+
const pending = beforeRequest(requestInit).catch((err: unknown) => err);
505+
await vi.waitFor(() => expect(mocks.appStateListeners.size).toBe(1));
506+
507+
controller.abort(abortReason);
508+
509+
await expect(pending).resolves.toBe(abortReason);
510+
expect(mocks.appStateListeners.size).toBe(0);
511+
512+
setAppState('active');
513+
await Promise.resolve();
514+
expect(getToken).toHaveBeenCalledTimes(1);
515+
});
516+
517+
test('does not wait for the app to become active when the request was already aborted', async () => {
518+
setAppState('background');
519+
const getToken = vi.fn<TokenCache['getToken']>(() => Promise.reject(new Error('User interaction is not allowed.')));
520+
const tokenCache: TokenCache = {
521+
getToken,
522+
saveToken: vi.fn(() => Promise.resolve()),
523+
};
524+
525+
const createClerkInstance = await loadCreateClerkInstance();
526+
const getClerkInstance = createClerkInstance(MockClerk as unknown as typeof Clerk);
527+
const clerk = getClerkInstance({
528+
publishableKey: 'pk_test_123',
529+
tokenCache,
530+
}) as unknown as MockClerk;
531+
532+
const beforeRequest = clerk.__internal_onBeforeRequest.mock.calls[0][0];
533+
const controller = new AbortController();
534+
const abortReason = new Error('client fetch timed out');
535+
controller.abort(abortReason);
536+
const requestInit = {
537+
headers: new Headers(),
538+
signal: controller.signal,
539+
url: new URL('https://clerk.example.com/v1/client'),
540+
};
541+
542+
await expect(beforeRequest(requestInit)).rejects.toBe(abortReason);
543+
expect(mocks.appStateListeners.size).toBe(0);
544+
expect(getToken).toHaveBeenCalledTimes(1);
545+
});
546+
547+
test('rejects with an AbortError when the aborted signal has no reason', async () => {
548+
setAppState('background');
549+
const tokenCache: TokenCache = {
550+
getToken: vi.fn(() => Promise.reject(new Error('User interaction is not allowed.'))),
551+
saveToken: vi.fn(() => Promise.resolve()),
552+
};
553+
554+
const createClerkInstance = await loadCreateClerkInstance();
555+
const getClerkInstance = createClerkInstance(MockClerk as unknown as typeof Clerk);
556+
const clerk = getClerkInstance({
557+
publishableKey: 'pk_test_123',
558+
tokenCache,
559+
}) as unknown as MockClerk;
560+
561+
const beforeRequest = clerk.__internal_onBeforeRequest.mock.calls[0][0];
562+
const abortListeners = new Set<() => void>();
563+
const polyfilledSignal = {
564+
aborted: false,
565+
reason: undefined,
566+
addEventListener: (_type: 'abort', listener: () => void) => abortListeners.add(listener),
567+
removeEventListener: (_type: 'abort', listener: () => void) => abortListeners.delete(listener),
568+
};
569+
const requestInit = {
570+
headers: new Headers(),
571+
signal: polyfilledSignal,
572+
url: new URL('https://clerk.example.com/v1/client'),
573+
};
574+
575+
const pending = beforeRequest(requestInit).catch((err: unknown) => err);
576+
await vi.waitFor(() => expect(abortListeners.size).toBe(1));
577+
578+
polyfilledSignal.aborted = true;
579+
for (const listener of [...abortListeners]) {
580+
listener();
581+
}
582+
583+
const error = await pending;
584+
expect(error).toBeInstanceOf(Error);
585+
expect((error as Error).name).toBe('AbortError');
586+
expect(mocks.appStateListeners.size).toBe(0);
587+
});
588+
480589
test('does not wait for the app to become active inside an app extension', async () => {
481590
setAppState('extension');
482591
const readError = new Error('Unable to decode the provided data.');

‎packages/expo/src/provider/singleton/createClerkInstance.ts‎

Lines changed: 5 additions & 19 deletions
Original file line numberDiff line numberDiff line change
@@ -7,7 +7,7 @@ import type {
77
PublicKeyCredentialCreationOptionsWithoutExtensions,
88
PublicKeyCredentialRequestOptionsWithoutExtensions,
99
} from '@clerk/shared/types';
10-
import { AppState, Platform } from 'react-native';
10+
import { Platform } from 'react-native';
1111

1212
import packageJson from '../../../package.json';
1313
import {
@@ -24,7 +24,7 @@ import type { TokenCache } from '../../cache/types';
2424
import { CLERK_CLIENT_JWT_KEY } from '../../constants';
2525
import { errorThrower } from '../../errorThrower';
2626
import { assertValidProxyUrl } from '../../utils/errors';
27-
import { isAppInBackgroundOrInactive, isNative } from '../../utils/runtime';
27+
import { isNative, waitUntilAppIsActive } from '../../utils/runtime';
2828
import type { BuildClerkOptions } from './types';
2929

3030
/**
@@ -49,20 +49,6 @@ type ResolvedClerkRuntimeOptions = Omit<ClerkRuntimeOptions, 'publishableKey'> &
4949
const RESOURCE_RETRY_MAX_DELAY_MS = 30_000;
5050
const RESOURCE_RETRY_MAX_EXPONENT = 4;
5151

52-
function waitUntilAppIsActive(): Promise<void> {
53-
if (!isAppInBackgroundOrInactive()) {
54-
return Promise.resolve();
55-
}
56-
return new Promise(resolve => {
57-
const subscription = AppState.addEventListener('change', state => {
58-
if (state === 'active') {
59-
subscription.remove();
60-
resolve();
61-
}
62-
});
63-
});
64-
}
65-
6652
function hasOwnOption<Key extends keyof BuildClerkOptions>(
6753
options: BuildClerkOptions | undefined,
6854
key: Key,
@@ -76,11 +62,11 @@ let __internal_cancelResourceRetries: (() => void) | undefined;
7662
// Token IO can change without recreating the native singleton.
7763
let __internal_tokenCache: TokenCache = MemoryTokenCache;
7864

79-
async function readClientJwt() {
65+
async function readClientJwt(signal?: AbortSignal): Promise<string | null | undefined> {
8066
try {
8167
return await __internal_tokenCache.getToken(CLERK_CLIENT_JWT_KEY);
8268
} catch {
83-
await waitUntilAppIsActive();
69+
await waitUntilAppIsActive(signal);
8470
}
8571
return __internal_tokenCache.getToken(CLERK_CLIENT_JWT_KEY);
8672
}
@@ -312,7 +298,7 @@ export function createClerkInstance(ClerkClass: typeof Clerk) {
312298
// Instructs the backend to parse the api token from the Authorization header.
313299
requestInit.url?.searchParams.append('_is_native', '1');
314300

315-
const jwt = await readClientJwt();
301+
const jwt = await readClientJwt(requestInit.signal ?? undefined);
316302
(requestInit.headers as Headers).set('authorization', jwt || '');
317303

318304
// Instructs the backend that the request is from a mobile device.

‎packages/expo/src/token-cache/__tests__/tokenCache.test.ts‎

Lines changed: 1 addition & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -17,11 +17,9 @@ vi.mock('react-native', () => {
1717
};
1818
});
1919

20-
vi.mock('../../utils', async () => {
21-
const runtime = await vi.importActual<typeof import('../../utils/runtime')>('../../utils/runtime');
20+
vi.mock('../../utils', () => {
2221
return {
2322
isNative: () => true,
24-
isAppInBackgroundOrInactive: runtime.isAppInBackgroundOrInactive,
2523
};
2624
});
2725

0 commit comments

Comments
 (0)