From 111d0b31a14ab8974836be6d2f9a9630456a5c7f Mon Sep 17 00:00:00 2001 From: wobsoriano Date: Sun, 6 Dec 2026 17:08:57 +0800 Subject: [PATCH] fix(expo): wait for native configure instead of falling back to the app token cache --- .changeset/expo-wait-for-native-configure.md | 5 + .../__tests__/nativeClientSync.test.ts | 134 +++----- .../nativeClientSync.behavior.test.tsx | 294 +++--------------- .../expo/src/provider/nativeClientSync.ts | 113 ++----- 4 files changed, 129 insertions(+), 417 deletions(-) create mode 100644 .changeset/expo-wait-for-native-configure.md diff --git a/.changeset/expo-wait-for-native-configure.md b/.changeset/expo-wait-for-native-configure.md new file mode 100644 index 00000000000..3419ad9ee46 --- /dev/null +++ b/.changeset/expo-wait-for-native-configure.md @@ -0,0 +1,5 @@ +--- +'@clerk/expo': minor +--- + +With native components installed, Clerk now waits for the native SDK to finish starting up before it sends any request, instead of falling back to the app's token cache after 3 seconds. A slow native startup no longer signs the user into a different client than the native views show, but Clerk takes as long to load as the native SDK takes to start. If the native SDK has not started after the app has been open for 10 seconds, Clerk logs an error and keeps waiting. Clerk still uses the app's token cache when the native SDK fails to start. diff --git a/packages/expo/src/provider/__tests__/nativeClientSync.test.ts b/packages/expo/src/provider/__tests__/nativeClientSync.test.ts index 038b4f51939..b0e2aa2ad16 100644 --- a/packages/expo/src/provider/__tests__/nativeClientSync.test.ts +++ b/packages/expo/src/provider/__tests__/nativeClientSync.test.ts @@ -180,95 +180,59 @@ describe('createNativeClientSync', () => { expect(native.configure).toHaveBeenCalledTimes(2); }); - test('uses the app token cache while a slow configure is pending and the native token once it finishes', async () => { + test('waits for a slow configure and reads the native token once it finishes', async () => { vi.useFakeTimers(); try { const createNativeClientSync = await loadEngine(); const native = nativeModule(); let finishConfigure!: () => void; vi.mocked(native.configure).mockReturnValue(new Promise(resolve => (finishConfigure = resolve))); - const cache = userTokenCache(vi.fn().mockResolvedValue('seed-token')); + const getToken = vi.fn().mockResolvedValue('seed-token'); + const cache = userTokenCache(getToken); const sync = createNativeClientSync(native, 'pk_test_123', null, () => cache); - const duringStartup = sync.tokenCache.getToken(CLERK_CLIENT_JWT_KEY); - await vi.advanceTimersByTimeAsync(3_000); - - await expect(duringStartup).resolves.toBe('seed-token'); - expect(native.getDeviceToken).not.toHaveBeenCalled(); + let read: string | null | undefined; + void sync.tokenCache.getToken(CLERK_CLIENT_JWT_KEY).then(token => (read = token)); + await vi.advanceTimersByTimeAsync(60_000); + expect(read).toBeUndefined(); + expect(getToken).toHaveBeenCalledTimes(1); finishConfigure(); await vi.advanceTimersByTimeAsync(0); - await expect(sync.tokenCache.getToken(CLERK_CLIENT_JWT_KEY)).resolves.toBe('native-token'); + expect(read).toBe('native-token'); expect(native.configure).toHaveBeenCalledTimes(1); } finally { vi.useRealTimers(); } }); - test('hands native a token rotated while a slow configure was pending', async () => { - vi.useFakeTimers(); - try { - const createNativeClientSync = await loadEngine(); - const native = nativeModule(); - let nativeToken: string | null = null; - let finishConfigure!: () => void; - vi.mocked(native.configure).mockImplementation( - (_publishableKey, seed) => - new Promise(resolve => { - finishConfigure = () => { - nativeToken ??= seed; - resolve(); - }; - }), - ); - vi.mocked(native.getDeviceToken).mockImplementation(() => Promise.resolve(nativeToken)); - vi.mocked(native.setDeviceToken).mockImplementation((token, expected) => { - const didSet = nativeToken === expected; - if (didSet) { - nativeToken = token; - } - return Promise.resolve(didSet); - }); - const cache = storedTokenCache('seed-token'); - - const sync = createNativeClientSync(native, 'pk_test_123', null, () => cache); - const duringStartup = sync.tokenCache.getToken(CLERK_CLIENT_JWT_KEY); - await vi.advanceTimersByTimeAsync(3_000); - await expect(duringStartup).resolves.toBe('seed-token'); - await sync.tokenCache.saveClientToken('signed-in-token', 'seed-token'); - - finishConfigure(); - await vi.advanceTimersByTimeAsync(0); - - await expect(sync.tokenCache.getToken(CLERK_CLIENT_JWT_KEY)).resolves.toBe('signed-in-token'); - expect(native.setDeviceToken).toHaveBeenCalledWith('signed-in-token', 'seed-token'); - expect(native.refreshClient).toHaveBeenCalledTimes(1); - } finally { - vi.useRealTimers(); - } - }); - - test('keeps the native token when native already had its own during a slow configure', async () => { + test('reports a configure that has not settled once the app has been active for the timeout', async () => { vi.useFakeTimers(); + const consoleError = vi.spyOn(console, 'error').mockImplementation(() => undefined); try { const createNativeClientSync = await loadEngine(); + const { CONFIGURE_TIMEOUT_MS } = await import('../nativeClientSync'); const native = nativeModule(); - let finishConfigure!: () => void; - vi.mocked(native.configure).mockReturnValue(new Promise(resolve => (finishConfigure = resolve))); - vi.mocked(native.setDeviceToken).mockResolvedValue(false); - const cache = storedTokenCache('seed-token'); + vi.mocked(native.configure).mockReturnValue(new Promise(() => undefined)); + mocks.appState.currentState = 'background'; - const sync = createNativeClientSync(native, 'pk_test_123', null, () => cache); + const sync = createNativeClientSync(native, 'pk_test_123', null, () => storedTokenCache('seed-token')); void sync.tokenCache.getToken(CLERK_CLIENT_JWT_KEY); - await vi.advanceTimersByTimeAsync(3_000); - await sync.tokenCache.saveClientToken('signed-in-token', 'seed-token'); - - finishConfigure(); - await vi.advanceTimersByTimeAsync(0); - - await expect(sync.tokenCache.getToken(CLERK_CLIENT_JWT_KEY)).resolves.toBe('native-token'); - expect(native.refreshClient).not.toHaveBeenCalled(); + await vi.advanceTimersByTimeAsync(10 * CONFIGURE_TIMEOUT_MS); + expect(consoleError).not.toHaveBeenCalled(); + + mocks.appState.currentState = 'active'; + mocks.listeners.forEach(listener => listener('active')); + await vi.advanceTimersByTimeAsync(CONFIGURE_TIMEOUT_MS - 1); + expect(consoleError).not.toHaveBeenCalled(); + await vi.advanceTimersByTimeAsync(1); + + expect(consoleError).toHaveBeenCalledTimes(1); + expect(consoleError).toHaveBeenCalledWith( + expect.objectContaining({ message: expect.stringContaining('has not finished configuring') }), + ); } finally { + consoleError.mockRestore(); vi.useRealTimers(); } }); @@ -451,10 +415,9 @@ describe('createNativeClientSync', () => { createNativeClientSync(native, 'pk_test_123', null, () => clearableTokenCache(signedIn).cache).attach(clerk); const signOut = expect(clerk.signOut?.()).rejects.toThrow('Network request failed'); - await vi.advanceTimersByTimeAsync(3_000); - await signOut; + await vi.advanceTimersByTimeAsync(60_000); finishConfigure(); - await vi.advanceTimersByTimeAsync(0); + await signOut; await expect(native.getDeviceToken()).resolves.toBeNull(); } finally { @@ -463,26 +426,25 @@ describe('createNativeClientSync', () => { }); test('keeps a save that waited on a failed configure out of the app token cache after a failed sign-out', async () => { - vi.useFakeTimers(); - try { - const createNativeClientSync = await loadEngine(); - const signedIn = clientToken('client_signed_in', 1); - const native = nativeModule(); - vi.mocked(native.configure).mockReturnValue(new Promise(() => undefined)); - const { cache, stored } = clearableTokenCache(signedIn); - const clerk = clerkWithFailingSignOut('client_signed_in'); - const sync = createNativeClientSync(native, 'pk_test_123', null, () => cache); - sync.attach(clerk); + const createNativeClientSync = await loadEngine(); + const signedIn = clientToken('client_signed_in', 1); + const native = nativeModule(); + let failConfigure!: () => void; + vi.mocked(native.configure).mockReturnValue( + new Promise((_, reject) => (failConfigure = () => reject(new Error('native configure failed')))), + ); + const { cache, stored } = clearableTokenCache(signedIn); + const clerk = clerkWithFailingSignOut('client_signed_in'); + const sync = createNativeClientSync(native, 'pk_test_123', null, () => cache); + sync.attach(clerk); - const save = sync.tokenCache.saveClientToken(clientToken('client_signed_in', 2), signedIn); - const signOut = expect(clerk.signOut?.()).rejects.toThrow('Network request failed'); - await vi.advanceTimersByTimeAsync(3_000); - await Promise.all([save, signOut]); + const save = sync.tokenCache.saveClientToken(clientToken('client_signed_in', 2), signedIn); + const signOut = expect(clerk.signOut?.()).rejects.toThrow('Network request failed'); + await vi.waitFor(() => expect(stored.has(CLERK_CLIENT_JWT_KEY)).toBe(false)); + failConfigure(); + await Promise.all([save, signOut]); - expect(stored.get(CLERK_CLIENT_JWT_KEY)).toBeUndefined(); - } finally { - vi.useRealTimers(); - } + expect(stored.get(CLERK_CLIENT_JWT_KEY)).toBeUndefined(); }); test('keeps refusing an earlier signed-out client after a later failed sign-out of another client', async () => { 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 0d7bfe5524b..39e6ff6a5ea 100644 --- a/packages/expo/src/provider/__tests__/nativeClientSyncBehavior/nativeClientSync.behavior.test.tsx +++ b/packages/expo/src/provider/__tests__/nativeClientSyncBehavior/nativeClientSync.behavior.test.tsx @@ -93,7 +93,7 @@ async function outlastConfigureTimeout(h: NativeSyncHarness): Promise { await h.run(() => vi.advanceTimersByTimeAsync(CONFIGURE_TIMEOUT_MS + 500)); } -async function bootOnCachedClientWhileNativeConfigures(cachedUsers: string[]) { +async function bootOnCachedClientWhileNativeReadsFail(cachedUsers: string[]) { const { server, ...native } = seedDevice(['user_1']); const cached = server.seedClient({ users: cachedUsers }); const h = await start({ @@ -104,7 +104,8 @@ async function bootOnCachedClientWhileNativeConfigures(cachedUsers: string[]) { skipInitialLoad: true, }); h.native.restoreClientFromKeychain(server.inspectClient(native.token)); - await outlastConfigureTimeout(h); + h.native.deviceTokenReadFailures = 2; + await whileTimersRun(h, () => h.releaseNativeConfigure()); return { h, cached, native }; } @@ -116,10 +117,6 @@ async function whileTimersRun(h: NativeSyncHarness, action: () => T | Promise }); } -function signedInEmissionsSince(h: NativeSyncHarness, emissionIndex: number) { - return h.js.emissions.slice(emissionIndex).filter(emission => emission.sessionId !== null); -} - async function skipRetryBackoff(h: NativeSyncHarness): Promise { await h.run(() => vi.advanceTimersByTimeAsync(10_000)); } @@ -131,46 +128,6 @@ function returnToForeground(h: NativeSyncHarness): Promise { }); } -function signOutAfterNextNativeDeviceTokenRead(h: NativeSyncHarness, microtasks: number) { - let token = h.native.token; - let markStarted!: (started: boolean) => void; - const started = new Promise(resolve => { - markStarted = resolve; - }); - let armed = true; - Object.defineProperty(h.native, 'token', { - configurable: true, - get() { - if (armed && h.nativeModuleCalls.at(-1) === 'getDeviceToken') { - armed = false; - let delay = Promise.resolve(); - for (let i = 0; i < microtasks; i++) { - delay = delay.then(); - } - void delay.then(() => h.js.signOut().catch(() => undefined)).then(() => markStarted(true)); - } - return token; - }, - set(value: string | null) { - token = value; - }, - }); - return { started }; -} - -/** Fails the native device token reads numbered in `failing`, counting from 1 at the next read. */ -function failNativeReads(h: NativeSyncHarness, failing: number[]) { - const readsBefore = h.nativeModuleCalls.filter(call => call === 'getDeviceToken').length; - Object.defineProperty(h.native, 'deviceTokenReadFailures', { - configurable: true, - get() { - const read = h.nativeModuleCalls.filter(call => call === 'getDeviceToken').length - readsBefore; - return failing.includes(read) ? 1 : 0; - }, - set() {}, - }); -} - function seedDevice(users: string[] = ['user_1'], activeUser?: string) { const server = new FakeClerkServer(); return { server, ...server.seedClient({ users, activeUser }) }; @@ -815,9 +772,9 @@ describe('native client sync behavior', () => { it('keeps a client fetched for a native change off the JS client when it lands after a sign-out of another client', async () => { vi.useFakeTimers(); - const { h, cached, native } = await bootOnCachedClientWhileNativeConfigures(['user_2']); - await whileTimersRun(h, () => h.releaseNativeConfigure()); + const { h, cached, native } = await bootOnCachedClientWhileNativeReadsFail(['user_2']); await skipRetryBackoff(h); + expect(h.js.client?.id).toBe(cached.clientId); const held = h.server.holdNextResponse('js', 'GET /client'); await whileTimersRun(h, () => h.native.emitChange({ client: true, deviceToken: false }, { kind: 'native' })); await whileTimersRun(h, () => held.handled); @@ -966,7 +923,7 @@ describe('native client sync behavior', () => { 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]); + h.native.deviceTokenReadFailures = 8; await h.settle(); expect(h.persistentTokenCache?.read(CLERK_CLIENT_JWT_KEY)).toBe(token); @@ -986,7 +943,7 @@ describe('native client sync behavior', () => { expect(h.native.token).not.toBe(signedIn.token); }); - it('signs JS in on the native client when native finishes configuring after JS booted without a device token', async () => { + it('waits for a slow native configure instead of creating a client when the app token cache is empty', async () => { vi.useFakeTimers(); const { server, token, clientId, sessionIds } = seedDevice(['user_1']); server.singleSessionMode = true; @@ -1001,7 +958,8 @@ describe('native client sync behavior', () => { h.native.restoreClientFromKeychain(server.inspectClient(token)); await outlastConfigureTimeout(h); - expect(h.js.client?.id).not.toBe(clientId); + expect(h.js.loaded).toBe(false); + expect(server.requests.filter(request => request.caller === 'js')).toEqual([]); await h.run(() => h.releaseNativeConfigure()); await skipRetryBackoff(h); @@ -1010,33 +968,55 @@ describe('native client sync behavior', () => { expect(await h.run(() => h.jsDeviceToken())).toBe(h.native.token); }); - it('keeps JS signed out after a sign-out made while native was still configuring', async () => { + it('waits for a slow native configure instead of booting on another client in the app token cache', async () => { vi.useFakeTimers(); - const { server, token } = seedDevice(['user_1']); - server.singleSessionMode = true; + const { server, ...native } = seedDevice(['user_1']); const cached = server.seedClient({ users: ['user_2'] }); const h = await start({ server, - nativeDeviceToken: token, + nativeDeviceToken: native.token, jsDeviceToken: cached.token, delayNativeConfigure: true, skipInitialLoad: true, }); - h.native.restoreClientFromKeychain(server.inspectClient(token)); + h.native.restoreClientFromKeychain(server.inspectClient(native.token)); await outlastConfigureTimeout(h); - expect(h.js.session?.id).toBe(cached.sessionIds.user_2); - await h.run(async () => { - const signingOut = h.js.signOut(); - await vi.advanceTimersByTimeAsync(CONFIGURE_TIMEOUT_MS + 500); - await signingOut; - }); - expect(h.js.session).toBeNull(); + expect(h.js.loaded).toBe(false); await h.run(() => h.releaseNativeConfigure()); await skipRetryBackoff(h); - expect(h.js.client?.id).toBe(cached.clientId); - expect(h.js.session).toBeNull(); + expect(server.requests.filter(request => request.caller === 'js' && request.token === cached.token)).toEqual([]); + expect(h.js.client?.id).toBe(native.clientId); + expect(h.js.session?.id).toBe(native.sessionIds.user_1); + }); + + it('reports an error and keeps Clerk loading when native configure never settles', async () => { + vi.useFakeTimers(); + const consoleError = vi.spyOn(console, 'error').mockImplementation(() => undefined); + try { + const { server, ...native } = seedDevice(['user_1']); + const cached = server.seedClient({ users: ['user_2'] }); + const h = await start({ + server, + nativeDeviceToken: native.token, + jsDeviceToken: cached.token, + delayNativeConfigure: true, + skipInitialLoad: true, + }); + + await h.run(() => vi.advanceTimersByTimeAsync(CONFIGURE_TIMEOUT_MS - 1)); + expect(consoleError).not.toHaveBeenCalled(); + await h.run(() => vi.advanceTimersByTimeAsync(60_000)); + + expect(consoleError).toHaveBeenCalledWith( + expect.objectContaining({ message: expect.stringContaining('has not finished configuring') }), + ); + expect(h.js.loaded).toBe(false); + expect(server.requests.filter(request => request.caller === 'js')).toEqual([]); + } finally { + consoleError.mockRestore(); + } }); it('boots JS on the native client during a slow native configure after JS followed a native sign-in on the previous launch', async () => { @@ -1060,6 +1040,8 @@ describe('native client sync behavior', () => { skipInitialLoad: true, }); await outlastConfigureTimeout(h); + await h.run(() => h.releaseNativeConfigure()); + await skipRetryBackoff(h); expect(h.js.client?.id).toBe(server.clientIdForToken(nativeToken)); expect(h.js.session?.id).toBe(sessionId); @@ -1085,78 +1067,9 @@ describe('native client sync behavior', () => { expect(h.js.session?.id).toBe(sessionIds.user_1); }); - it('keeps a JS sign-in made while native holds a signed-out client and is still configuring', async () => { + it('signs JS in on the native client on the next foreground after both reads of the native device token failed at launch', async () => { vi.useFakeTimers(); - const server = new FakeClerkServer(); - const nativeSignedOut = server.seedClient({ users: [] }); - const h = await start({ - server, - nativeDeviceToken: nativeSignedOut.token, - persistentTokenCache: true, - delayNativeConfigure: true, - skipInitialLoad: true, - }); - h.native.restoreClientFromKeychain(server.inspectClient(nativeSignedOut.token)); - await outlastConfigureTimeout(h); - - const sessionId = await whileTimersRun(h, () => h.js.signIn('user_2')); - const signedInClientId = h.js.client?.id; - expect(h.js.session?.id).toBe(sessionId); - await whileTimersRun(h, () => h.releaseNativeConfigure()); - await skipRetryBackoff(h); - - expect(h.js.client?.id).toBe(signedInClientId); - expect(h.js.session?.id).toBe(sessionId); - }); - - it('keeps the JS user signed in on the app token cache client when native finishes configuring on another user', async () => { - vi.useFakeTimers(); - const { h, cached } = await bootOnCachedClientWhileNativeConfigures(['user_2']); - - await whileTimersRun(h, () => h.releaseNativeConfigure()); - await skipRetryBackoff(h); - await returnToForeground(h); - await skipRetryBackoff(h); - - expect(h.js.client?.id).toBe(cached.clientId); - expect(h.js.session?.id).toBe(cached.sessionIds.user_2); - }); - - it('signs JS in on the native session when switching to it fails after a JS request found the cached session gone', async () => { - vi.useFakeTimers(); - const { h, native } = await bootOnCachedClientWhileNativeConfigures(['user_2']); - h.server.failNextRequests('js', 'POST /client/sessions/:id/touch'); - await whileTimersRun(h, () => h.releaseNativeConfigure()); - await skipRetryBackoff(h); - - await whileTimersRun(h, () => h.js.getSessionToken()); - await skipRetryBackoff(h); - await returnToForeground(h); - await skipRetryBackoff(h); - - expect(h.js.client?.id).toBe(native.clientId); - expect(h.js.session?.id).toBe(native.sessionIds.user_1); - }); - - it('signs JS in on the native client, at the latest after a foreground, when native reads fail during the pull onto it', async () => { - vi.useFakeTimers(); - const { h, native } = await bootOnCachedClientWhileNativeConfigures([]); - failNativeReads(h, [2, 4]); - await whileTimersRun(h, () => h.releaseNativeConfigure()); - await skipRetryBackoff(h); - - await returnToForeground(h); - await skipRetryBackoff(h); - - expect(h.js.client?.id).toBe(native.clientId); - expect(h.js.session?.id).toBe(native.sessionIds.user_1); - }); - - it('signs JS in on the native client when the app returns to the foreground after convergence failed to read the native device token', async () => { - vi.useFakeTimers(); - const { h, native } = await bootOnCachedClientWhileNativeConfigures([]); - h.native.deviceTokenReadFailures = 1; - await whileTimersRun(h, () => h.releaseNativeConfigure()); + const { h, native } = await bootOnCachedClientWhileNativeReadsFail([]); await skipRetryBackoff(h); expect(h.js.session).toBeNull(); @@ -1167,7 +1080,7 @@ describe('native client sync behavior', () => { expect(h.js.session?.id).toBe(native.sessionIds.user_1); }); - it('refetches the JS client a bounded number of times when native holds a retired token it cannot replace', async () => { + it('fetches the JS client once when native holds a retired token it cannot replace', async () => { const { server, token, clientId } = seedDevice(['user_1']); server.createClientForMissingToken = true; server.rotateTokenOnNextResponse(token); @@ -1183,8 +1096,6 @@ describe('native client sync behavior', () => { }); h.native.deviceTokenWritesFail = true; - await outlastConfigureTimeout(h); - const jsClientFetchesBefore = server.requestCount('js', 'GET /client'); await h.run(async () => { h.releaseNativeConfigure(); for (let timer = 0; timer < 200; timer++) { @@ -1194,110 +1105,7 @@ describe('native client sync behavior', () => { expect(h.server.clientIdForToken(h.native.token)).toBeNull(); expect(h.js.client?.id).not.toBe(clientId); - expect(server.requestCount('js', 'GET /client') - jsClientFetchesBefore).toBe(2); - }); - - it('keeps JS signed out when it signs out while the pull onto the native client waits to retry', async () => { - vi.useFakeTimers(); - const { h } = await bootOnCachedClientWhileNativeConfigures([]); - const jsClientFetchesBefore = h.server.requestCount('js', 'GET /client'); - h.server.failNextRequests('js', 'GET /client'); - await whileTimersRun(h, () => h.releaseNativeConfigure()); - expect(h.server.requestCount('js', 'GET /client') - jsClientFetchesBefore).toBe(1); - - h.server.failNextRequests('js', 'DELETE /client/sessions'); - await whileTimersRun(h, () => h.js.signOut().catch(() => undefined)); - expect(h.js.session).toBeNull(); - const emissionIndex = h.js.emissions.length; - await skipRetryBackoff(h); - - expect(signedInEmissionsSince(h, emissionIndex)).toEqual([]); - expect(h.js.session).toBeNull(); - }); - - it('keeps JS signed out when the app returns to the foreground after a sign-out that followed a failed pull onto the native client', async () => { - vi.useFakeTimers(); - const { h } = await bootOnCachedClientWhileNativeConfigures([]); - h.server.failNextRequests('js', 'GET /client', 3); - await whileTimersRun(h, () => h.releaseNativeConfigure()); - await skipRetryBackoff(h); - expect(h.js.session).toBeNull(); - - h.server.failNextRequests('js', 'DELETE /client/sessions'); - await whileTimersRun(h, () => h.js.signOut().catch(() => undefined)); - expect(h.js.session).toBeNull(); - const emissionIndex = h.js.emissions.length; - await returnToForeground(h); - await skipRetryBackoff(h); - - expect(signedInEmissionsSince(h, emissionIndex)).toEqual([]); - expect(h.js.session).toBeNull(); - }); - - it('follows a native sign-in made after JS signed out during the pull onto the native client', async () => { - vi.useFakeTimers(); - const { h } = await bootOnCachedClientWhileNativeConfigures([]); - h.server.failNextRequests('js', 'GET /client'); - await whileTimersRun(h, () => h.releaseNativeConfigure()); - h.server.failNextRequests('js', 'DELETE /client/sessions'); - await whileTimersRun(h, () => h.js.signOut().catch(() => undefined)); - await skipRetryBackoff(h); - expect(h.js.session).toBeNull(); - - const sessionId = await whileTimersRun(h, () => h.native.signIn('user_3')); - await skipRetryBackoff(h); - - expect(h.js.session?.id).toBe(sessionId); - }); - - it.each([0, 1, 2, 3, 4, 5, 6, 7])( - 'keeps JS signed out when it signs out %i microtasks after convergence reads the native device token', - async microtasks => { - vi.useFakeTimers(); - const { h } = await bootOnCachedClientWhileNativeConfigures([]); - h.server.failNextRequests('js', 'DELETE /client/sessions'); - const signingOut = signOutAfterNextNativeDeviceTokenRead(h, microtasks); - - await whileTimersRun(h, () => h.releaseNativeConfigure()); - expect(await whileTimersRun(h, () => signingOut.started)).toBe(true); - await skipRetryBackoff(h); - - expect(h.js.session).toBeNull(); - }, - ); - - it('keeps JS signed out when it signs out while activating the session of the native client it converged onto', async () => { - vi.useFakeTimers(); - const { h } = await bootOnCachedClientWhileNativeConfigures([]); - const held = h.server.holdNextResponse('js', 'POST /client/sessions/:id/touch'); - await whileTimersRun(h, () => h.releaseNativeConfigure()); - await whileTimersRun(h, () => held.handled); - - await whileTimersRun(h, () => h.js.signOut()); - expect(h.js.session).toBeNull(); - held.release(); - await skipRetryBackoff(h); - - expect(h.server.inspectClient(h.native.token)?.sessions).toEqual([]); - expect(h.js.session).toBeNull(); - }); - - it('keeps the JS client without sessions when the pull onto the native client lands after signing out of every session', async () => { - vi.useFakeTimers(); - const { h } = await bootOnCachedClientWhileNativeConfigures([]); - const held = h.server.holdNextResponse('js', 'GET /client'); - await whileTimersRun(h, () => h.releaseNativeConfigure()); - await whileTimersRun(h, () => held.handled); - await whileTimersRun(h, () => h.js.signOut()); - const emissionIndex = h.js.emissions.length; - - held.release(); - await h.run(() => vi.advanceTimersByTimeAsync(0)); - - expect(h.js.client?.signedInSessions).toEqual([]); - await skipRetryBackoff(h); - expect(signedInEmissionsSince(h, emissionIndex)).toEqual([]); - expect(h.js.session).toBeNull(); + expect(server.requestCount('js', 'GET /client')).toBe(1); }); it('delivers a JS sign-in that happens while native is still starting up', async () => { diff --git a/packages/expo/src/provider/nativeClientSync.ts b/packages/expo/src/provider/nativeClientSync.ts index 479ec1c9aa4..0d61dd5a9d1 100644 --- a/packages/expo/src/provider/nativeClientSync.ts +++ b/packages/expo/src/provider/nativeClientSync.ts @@ -10,8 +10,9 @@ import { CLERK_CLIENT_JWT_KEY } from '../constants'; import type { ClerkExpoNativeModule } from '../utils/native-module'; import { waitUntilAppIsActive } from '../utils/runtime'; -export const CONFIGURE_TIMEOUT_MS = 3_000; +export const CONFIGURE_TIMEOUT_MS = 10_000; const INVALIDATED_EVENT = 'clerkNativeClientInvalidated'; +const CONFIGURE_TIMEOUT_MESSAGE = `Clerk: The native Clerk SDK has not finished configuring after ${CONFIGURE_TIMEOUT_MS / 1000} seconds. Clerk sends no requests until it does, so that JS and native use the same client. Check the Xcode or Logcat output for an error from the native Clerk SDK.`; type FetchableClient = ClientResource & { fetch?: (options?: { fetchMaxTries?: number; abortSignal?: AbortSignal }) => Promise; @@ -43,8 +44,7 @@ const noop = () => undefined; let configuration: { publishableKey: string; proxyUrl: string | null; - ready: () => Promise; - settled: () => Promise; + ready: Promise; } | null = null; const pullRequests = new WeakMap boolean>(); @@ -130,13 +130,23 @@ function clientIdOf(token: string | null): string | null { } } -async function readSeedDeviceToken(tokenCache: TokenCache): Promise { +async function readOnceAppIsActive(read: () => Promise): Promise { try { - return (await tokenCache.getToken(CLERK_CLIENT_JWT_KEY)) ?? null; + return await read(); } catch { await waitUntilAppIsActive(); } - return (await tokenCache.getToken(CLERK_CLIENT_JWT_KEY)) ?? null; + return read(); +} + +async function reportConfigureStillPendingOnceAppIsActive(seeding: Promise, configuring: Promise) { + await seeding.catch(noop); + await waitUntilAppIsActive(); + await withTimeout(configuring, CONFIGURE_TIMEOUT_MS, () => new Error(CONFIGURE_TIMEOUT_MESSAGE)).catch(error => { + if (configuration?.ready === configuring) { + console.error(error); + } + }); } function configureOnce( @@ -148,50 +158,24 @@ function configureOnce( ) { if (configuration?.publishableKey !== publishableKey || configuration.proxyUrl !== proxyUrl) { needsRepair = false; - let configured = false; - let timedOut = false; - const seeding = readSeedDeviceToken(tokenCache); + const seeding = readOnceAppIsActive(() => tokenCache.getToken(CLERK_CLIENT_JWT_KEY)); const configuring = (async () => { - const seed = await seeding; + const seed = (await seeding) ?? null; await native .setUpdateRequiredViewEnabled?.(updateRequiredViewEnabled) .catch(error => warn('Failed to set whether the native SDK shows its update screen.', error)); await native .configure(publishableKey, seed, proxyUrl) .catch(() => native.configure(publishableKey, seed, proxyUrl)); - const latest = timedOut ? ((await tokenCache.getToken(CLERK_CLIENT_JWT_KEY)) ?? null) : seed; - const didHandOff = !!latest && latest !== seed && (await native.setDeviceToken(latest, seed)); - configured = true; - if (didHandOff) { - void native.refreshClient().catch(error => warn('Failed to refresh the native client.', error)); - } + return true; })().catch(error => { warn('Native client sync is disabled because the native Clerk SDK failed to configure.', error); + return false; }); - // 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, - ready: async () => { - await startup; - return configured; - }, - settled: async () => { - await configuring; - return configured; - }, - }; + void reportConfigureStillPendingOnceAppIsActive(seeding, configuring); + configuration = { publishableKey, proxyUrl, ready: configuring }; } - return configuration.ready(); + return configuration.ready; } /** @@ -208,8 +192,6 @@ export function createNativeClientSync( const fallback = () => getUserTokenCache() ?? MemoryTokenCache; const ready = () => configureOnce(native, publishableKey, proxyUrl, fallback(), getNativeUpdateRequiredViewEnabled()); let mirroredToken: string | null | undefined; - let usedFallbackTokenCache = false; - let signedOutInJs = false; const discardedClientIds = new Set(); let lastFingerprint: string | undefined; @@ -270,17 +252,16 @@ export function createNativeClientSync( return fallback().getToken(key); } if (!(await ready())) { - usedFallbackTokenCache = true; return fallback().getToken(key); } - return native.getDeviceToken().then( + return readOnceAppIsActive(() => native.getDeviceToken()).then( token => { mirror(token); return token; }, error => { warn('Failed to read the native device token.', error); - usedFallbackTokenCache = true; + needsRepair = true; return fallback().getToken(key); }, ); @@ -290,7 +271,6 @@ export function createNativeClientSync( return fallback().saveToken(key, token); } if (!(await ready())) { - usedFallbackTokenCache = true; return fallback().saveToken(key, token); } await tokenCache.saveClientToken(token, await native.getDeviceToken().catch(() => null)); @@ -307,7 +287,6 @@ export function createNativeClientSync( return; } if (!isReady) { - usedFallbackTokenCache = true; return fallback().saveToken(CLERK_CLIENT_JWT_KEY, token); } if (token === requestToken && token === mirroredToken) { @@ -351,12 +330,7 @@ export function createNativeClientSync( await writeCachedToken(null).catch(error => warn('Failed to clear the cached device token.', error)); if (await ready()) { await clearNativeDeviceToken(clientId); - return; } - const settled = configuration?.settled; - void settled?.() - .then(didConfigure => (didConfigure ? clearNativeDeviceToken(clientId) : undefined)) - .catch(error => warn('Failed to clear the native device token.', error)); }; const attach = (clerk: SyncableClerk): (() => void) => { @@ -433,38 +407,6 @@ export function createNativeClientSync( const pullInBackground = () => void fromNative.run().catch(error => warn('Failed to refresh the client from native.', error)); - const shouldConverge = () => - usedFallbackTokenCache && attached && !!clerk.client?.id && !clerk.session && !signedOutInJs; - - const convergeOnNative = async () => { - if (!shouldConverge() || !(await ready())) { - return; - } - const nativeToken = await native.getDeviceToken().catch(() => undefined); - if (!shouldConverge()) { - return; - } - if (nativeToken === undefined) { - needsRepair = true; - return; - } - const nativeClientId = clientIdOf(nativeToken); - if (!nativeClientId || discardedClientIds.has(nativeClientId)) { - return; - } - usedFallbackTokenCache = false; - if (nativeClientId !== clerk.client?.id) { - pullInBackground(); - return; - } - await activateDefaultSession().catch(error => { - if (!signedOutInJs) { - needsRepair = true; - } - warn('Failed to activate the native session.', error); - }); - }; - const toNative = singleFlight(async () => { // Let an in-flight native pull settle first so one refresh covers what it applied. await fromNative.current()?.catch(noop); @@ -541,7 +483,6 @@ export function createNativeClientSync( const client = clerk.client; const signsOutEverySession = !options?.sessionId || (client?.signedInSessions.length ?? 0) <= 1; if (signsOutEverySession || options?.sessionId === clerk.session?.id) { - signedOutInJs = true; jsSignOuts += 1; needsRepair = false; } @@ -571,11 +512,7 @@ export function createNativeClientSync( } const removeClerkListener = clerk.addListener(() => { void toNative.run().catch(error => warn('Failed to refresh the native client.', error)); - void convergeOnNative(); }); - void ready() - .then(() => configuration?.settled()) - .then(convergeOnNative); const subscription = native.addListener?.(INVALIDATED_EVENT, pullInBackground); const appStateSubscription = AppState.addEventListener('change', state => { if (state === 'active' && needsRepair) {