diff --git a/.changeset/expo-background-launch-offline-native-signout.md b/.changeset/expo-background-launch-offline-native-signout.md new file mode 100644 index 00000000000..13dc4139f8d --- /dev/null +++ b/.changeset/expo-background-launch-offline-native-signout.md @@ -0,0 +1,5 @@ +--- +'@clerk/expo': patch +--- + +Fix two startup issues with native components. When the app launches in the background before the keychain can be read, the JS SDK now waits for the app to open instead of starting from a stale cached token. When the JS SDK sees a native sign-out that never reached Clerk, it now clears its cached token, so the next launch doesn't sign the user back in. diff --git a/packages/expo/src/provider/__tests__/nativeClientSyncBehavior/environment.tsx b/packages/expo/src/provider/__tests__/nativeClientSyncBehavior/environment.tsx index daaf102a0fd..303195d335c 100644 --- a/packages/expo/src/provider/__tests__/nativeClientSyncBehavior/environment.tsx +++ b/packages/expo/src/provider/__tests__/nativeClientSyncBehavior/environment.tsx @@ -50,7 +50,11 @@ export class FakePersistentTokenCache implements TokenCache { return this.#values.get(key) ?? null; } - getToken = (key: string): Promise => Promise.resolve(this.#values.get(key) ?? null); + /** The keychain is unreadable, as during an iOS background launch before the first unlock. */ + locked = false; + + getToken = (key: string): Promise => + this.locked ? Promise.reject(new Error('The keychain is locked.')) : Promise.resolve(this.#values.get(key) ?? null); saveToken = (key: string, token: string): Promise => { this.#values.set(key, token); diff --git a/packages/expo/src/provider/__tests__/nativeClientSyncBehavior/fakeNativeClerk.ts b/packages/expo/src/provider/__tests__/nativeClientSyncBehavior/fakeNativeClerk.ts index 1dd25210dbe..a66e6106016 100644 --- a/packages/expo/src/provider/__tests__/nativeClientSyncBehavior/fakeNativeClerk.ts +++ b/packages/expo/src/provider/__tests__/nativeClientSyncBehavior/fakeNativeClerk.ts @@ -133,6 +133,13 @@ export class FakeNativeClerk { await this.#observe(() => this.server.removeAllSessions('native', this.token)); } + /** Native signs out on the device after the sign-out request failed, so the server session stays active. */ + signOutOnDevice(): void { + this.token = null; + this.client = null; + this.emitChange({ client: true, deviceToken: true }, { kind: 'native' }); + } + async refresh(): Promise { await this.#observe(() => this.server.getClient('native', this.token)); } diff --git a/packages/expo/src/provider/__tests__/nativeClientSyncBehavior/harness.ts b/packages/expo/src/provider/__tests__/nativeClientSyncBehavior/harness.ts index a7d0f0f3fe9..f24cdeb67e7 100644 --- a/packages/expo/src/provider/__tests__/nativeClientSyncBehavior/harness.ts +++ b/packages/expo/src/provider/__tests__/nativeClientSyncBehavior/harness.ts @@ -11,6 +11,8 @@ export type NativeSyncScenario = { */ jsDeviceToken?: string | null; persistentTokenCache?: boolean; + /** The app token cache cannot be read until the test unlocks it. */ + lockedTokenCache?: boolean; nativeDeviceToken?: string | null; nativeModule?: 'present' | 'absent'; /** The native SDK fails to configure, e.g. a native build that cannot initialize Clerk. */ diff --git a/packages/expo/src/provider/__tests__/nativeClientSyncBehavior/nativeClientSync.behavior.test.tsx b/packages/expo/src/provider/__tests__/nativeClientSyncBehavior/nativeClientSync.behavior.test.tsx index 6fe8cd96cea..0d7bfe5524b 100644 --- a/packages/expo/src/provider/__tests__/nativeClientSyncBehavior/nativeClientSync.behavior.test.tsx +++ b/packages/expo/src/provider/__tests__/nativeClientSyncBehavior/nativeClientSync.behavior.test.tsx @@ -49,7 +49,8 @@ vi.mock('expo-secure-store', () => ({ setItemAsync: vi.fn(), })); -vi.mock('../../../utils/runtime', () => ({ +vi.mock('../../../utils/runtime', async importOriginal => ({ + ...(await importOriginal()), isExpoGo: () => false, isNative: () => true, isWeb: () => false, @@ -699,6 +700,33 @@ describe('native client sync behavior', () => { }); describe('sign-out that never reaches the server', () => { + it('keeps a native sign-out that never reached Clerk on the next launch', async () => { + const server = new FakeClerkServer(); + const previousLaunch = await start({ server, persistentTokenCache: true }); + const sessionId = await previousLaunch.run(() => previousLaunch.native.signIn('user_1')); + await waitFor(() => expect(previousLaunch.js.session?.id).toBe(sessionId)); + await previousLaunch.settle(); + + vi.useFakeTimers(); + server.failNextRequests('js', 'GET /client', 3); + await whileTimersRun(previousLaunch, () => previousLaunch.native.signOutOnDevice()); + await skipRetryBackoff(previousLaunch); + const cachedToken = previousLaunch.persistentTokenCache?.read(CLERK_CLIENT_JWT_KEY) ?? null; + previousLaunch.unmount(); + vi.useRealTimers(); + + const h = await start({ + server, + nativeDeviceToken: null, + jsDeviceToken: cachedToken, + persistentTokenCache: true, + }); + await h.settle(); + + expect(h.native.token).toBeNull(); + expect(h.js.session).toBeNull(); + }); + it('lets another user sign in on a single-session instance', async () => { const { server, token } = seedDevice(['user_1']); server.singleSessionMode = true; @@ -913,6 +941,38 @@ describe('native client sync behavior', () => { expect(h.nativeModuleCalls.filter(call => call !== 'configure' && call !== 'addListener')).toEqual([]); }); + it('waits for the app to open before falling back to the app token cache after a background launch with a locked keychain', async () => { + const { server, token, sessionIds } = seedDevice(['user_1']); + const stale = server.seedClient(); + appState.currentState = 'background'; + vi.useFakeTimers(); + const h = await start({ + server, + nativeDeviceToken: token, + jsDeviceToken: stale.token, + lockedTokenCache: true, + skipInitialLoad: true, + }); + + h.persistentTokenCache!.locked = false; + await outlastConfigureTimeout(h); + await h.run(() => appState.moveTo('active')); + await skipRetryBackoff(h); + + expect(server.requests.filter(request => request.caller === 'js' && request.token === stale.token)).toEqual([]); + expect(h.js.session?.id).toBe(sessionIds.user_1); + }); + + it('keeps JS on the shared client while reads of the native device token fail', async () => { + const { server, token, sessionIds } = seedDevice(['user_1']); + const h = await start({ server, jsDeviceToken: token, nativeDeviceToken: token, skipInitialLoad: true }); + failNativeReads(h, [1, 2, 3, 4, 5, 6, 7, 8]); + await h.settle(); + + expect(h.persistentTokenCache?.read(CLERK_CLIENT_JWT_KEY)).toBe(token); + expect(h.js.session?.id).toBe(sessionIds.user_1); + }); + it('mirrors the shared device token into the app token cache', async () => { const server = new FakeClerkServer(); const stale = server.seedClient(); diff --git a/packages/expo/src/provider/__tests__/nativeClientSyncBehavior/newEngineAdapter.tsx b/packages/expo/src/provider/__tests__/nativeClientSyncBehavior/newEngineAdapter.tsx index 6f458734288..814751b47c3 100644 --- a/packages/expo/src/provider/__tests__/nativeClientSyncBehavior/newEngineAdapter.tsx +++ b/packages/expo/src/provider/__tests__/nativeClientSyncBehavior/newEngineAdapter.tsx @@ -103,6 +103,9 @@ export const renderWithNativeSync: RenderWithNativeSync = async (scenario = {}) scenario.persistentTokenCache || scenario.jsDeviceToken !== undefined ? new FakePersistentTokenCache(scenario.jsDeviceToken ? { [CLERK_CLIENT_JWT_KEY]: scenario.jsDeviceToken } : {}) : null; + if (persistentTokenCache && scenario.lockedTokenCache) { + persistentTokenCache.locked = true; + } const releaseNativeStartup = scenario.delayNativeStartup ? native.delayStartup() : () => undefined; const nativeModuleCalls: string[] = []; let releaseNativeConfigure: () => void = () => {}; diff --git a/packages/expo/src/provider/nativeClientSync.ts b/packages/expo/src/provider/nativeClientSync.ts index 86053201d79..479ec1c9aa4 100644 --- a/packages/expo/src/provider/nativeClientSync.ts +++ b/packages/expo/src/provider/nativeClientSync.ts @@ -150,8 +150,9 @@ function configureOnce( needsRepair = false; let configured = false; let timedOut = false; + const seeding = readSeedDeviceToken(tokenCache); const configuring = (async () => { - const seed = await readSeedDeviceToken(tokenCache); + const seed = await seeding; await native .setUpdateRequiredViewEnabled?.(updateRequiredViewEnabled) .catch(error => warn('Failed to set whether the native SDK shows its update screen.', error)); @@ -167,14 +168,16 @@ function configureOnce( })().catch(error => { warn('Native client sync is disabled because the native Clerk SDK failed to configure.', error); }); - const startup = withTimeout( - configuring, - CONFIGURE_TIMEOUT_MS, - () => new Error('Timed out configuring the native Clerk SDK.'), - ).catch(error => { - timedOut = true; - warn('Native client sync is waiting for the native Clerk SDK to configure.', error); - }); + // A background launch can wait for the app to open before the keychain is readable. + const startup = seeding + .catch(noop) + .then(() => + withTimeout(configuring, CONFIGURE_TIMEOUT_MS, () => new Error('Timed out configuring the native Clerk SDK.')), + ) + .catch(error => { + timedOut = true; + warn('Native client sync is waiting for the native Clerk SDK to configure.', error); + }); configuration = { publishableKey, proxyUrl, @@ -204,7 +207,7 @@ export function createNativeClientSync( ) { const fallback = () => getUserTokenCache() ?? MemoryTokenCache; const ready = () => configureOnce(native, publishableKey, proxyUrl, fallback(), getNativeUpdateRequiredViewEnabled()); - let mirroredToken: string | null = null; + let mirroredToken: string | null | undefined; let usedFallbackTokenCache = false; let signedOutInJs = false; const discardedClientIds = new Set(); @@ -215,11 +218,28 @@ export function createNativeClientSync( return !!clientId && discardedClientIds.has(clientId); }; + let cacheWrites: Promise = Promise.resolve(); + const writeCachedToken = (token: string | null) => { + const cache = fallback(); + const write = cacheWrites.then(async () => { + if (token) { + await cache.saveToken(CLERK_CLIENT_JWT_KEY, token); + } else if (cache.clearToken) { + await cache.clearToken(CLERK_CLIENT_JWT_KEY); + } else { + await cache.saveToken(CLERK_CLIENT_JWT_KEY, ''); + } + }); + cacheWrites = write.catch(noop); + return write; + }; + const mirror = (token: string | null) => { - if (token && token !== mirroredToken && !isDiscarded(token)) { - mirroredToken = token; - void Promise.resolve(fallback().saveToken(CLERK_CLIENT_JWT_KEY, token)).catch(noop); + if (token === mirroredToken || isDiscarded(token)) { + return; } + mirroredToken = token; + void writeCachedToken(token).catch(noop); }; const setDeviceToken = (token: string | null, expected: string | null) => @@ -297,9 +317,11 @@ export function createNativeClientSync( mirror(token); return; } - const current = await native.getDeviceToken().catch(() => null); - const didReclaim = token !== requestToken && (await reclaimRotatedToken(token, requestToken, current)); - mirror(didReclaim ? token : current); + const current = await native.getDeviceToken().catch(() => undefined); + const didReclaim = token !== requestToken && (await reclaimRotatedToken(token, requestToken, current ?? null)); + if (didReclaim || current !== undefined) { + mirror(didReclaim ? token : (current ?? null)); + } if (didReclaim) { void native.refreshClient().catch(error => warn('Failed to refresh the native client.', error)); } @@ -326,12 +348,7 @@ export function createNativeClientSync( discardedClientIds.add(clientId); } mirroredToken = null; - const cache = fallback(); - await Promise.resolve() - .then(() => - cache.clearToken ? cache.clearToken(CLERK_CLIENT_JWT_KEY) : cache.saveToken(CLERK_CLIENT_JWT_KEY, ''), - ) - .catch(error => warn('Failed to clear the cached device token.', error)); + await writeCachedToken(null).catch(error => warn('Failed to clear the cached device token.', error)); if (await ready()) { await clearNativeDeviceToken(clientId); return;