From 4cb7abf9ab9eb5a952f02196afbde23d8e429d41 Mon Sep 17 00:00:00 2001 From: wobsoriano Date: Sat, 5 Dec 2026 15:10:19 +0800 Subject: [PATCH 01/17] test(expo): cover a slow native configure leaving JS on another client --- .../nativeClientSyncBehavior/fakeServer.ts | 5 ++- .../nativeClientSyncBehavior/harness.ts | 5 +++ .../nativeClientSync.behavior.test.tsx | 26 ++++++++++++++ .../newEngineAdapter.tsx | 34 +++++++++++++------ 4 files changed, 58 insertions(+), 12 deletions(-) diff --git a/packages/expo/src/provider/__tests__/nativeClientSyncBehavior/fakeServer.ts b/packages/expo/src/provider/__tests__/nativeClientSyncBehavior/fakeServer.ts index b576a531425..6efef18a7a8 100644 --- a/packages/expo/src/provider/__tests__/nativeClientSyncBehavior/fakeServer.ts +++ b/packages/expo/src/provider/__tests__/nativeClientSyncBehavior/fakeServer.ts @@ -98,8 +98,11 @@ export class FakeClerkServer { return { client, token: this.#mintToken(client.id) }; } + /** Set to answer GET /client without a device token like FAPI does: with a brand new client. */ + createClientForMissingToken = false; + #authenticate(token: string | null): { client: FakeServerClientJSON | null; token: string | null } { - if (token && this.#retiredTokens.has(token)) { + if ((token && this.#retiredTokens.has(token)) || (!token && this.createClientForMissingToken)) { return this.#createClient(); } return { client: this.#clientFor(token), token }; diff --git a/packages/expo/src/provider/__tests__/nativeClientSyncBehavior/harness.ts b/packages/expo/src/provider/__tests__/nativeClientSyncBehavior/harness.ts index 05a95bbaf16..d605c0c30c5 100644 --- a/packages/expo/src/provider/__tests__/nativeClientSyncBehavior/harness.ts +++ b/packages/expo/src/provider/__tests__/nativeClientSyncBehavior/harness.ts @@ -16,6 +16,10 @@ export type NativeSyncScenario = { /** The native SDK fails to configure, e.g. a native build that cannot initialize Clerk. */ failNativeConfigure?: boolean; delayNativeStartup?: boolean; + /** Native `configure` does not resolve until `releaseNativeConfigure`. */ + delayNativeConfigure?: boolean; + /** The test drives fake timers itself, so the harness neither waits for load nor settles on real timers. */ + manualClock?: boolean; strictMode?: boolean; }; @@ -33,6 +37,7 @@ export type NativeSyncHarness = { run: (action: () => T | Promise) => Promise; settle: () => Promise; releaseNativeStartup: () => void; + releaseNativeConfigure: () => void; unmount: () => void; }; 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 a40fa727bda..3895f92662f 100644 --- a/packages/expo/src/provider/__tests__/nativeClientSyncBehavior/nativeClientSync.behavior.test.tsx +++ b/packages/expo/src/provider/__tests__/nativeClientSyncBehavior/nativeClientSync.behavior.test.tsx @@ -717,6 +717,32 @@ 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 () => { + vi.useFakeTimers(); + const { server, token, clientId, sessionIds } = seedDevice(['user_1']); + server.singleSessionMode = true; + server.createClientForMissingToken = true; + const h = await start({ + server, + nativeDeviceToken: token, + persistentTokenCache: true, + delayNativeConfigure: true, + manualClock: true, + }); + // Native restores its signed-in client from the keychain before JS can see it. + h.native.client = server.inspectClient(token); + + // Configure outlives the startup timeout, so the boot request reads the empty app token cache. + await h.run(() => vi.advanceTimersByTimeAsync(3_500)); + expect(h.js.client?.id).not.toBe(clientId); + await h.run(() => h.releaseNativeConfigure()); + await skipRetryBackoff(h); + + expect(h.js.client?.id).toBe(clientId); + expect(h.js.session?.id).toBe(sessionIds.user_1); + expect(await h.run(() => h.jsDeviceToken())).toBe(h.native.token); + }); + it('delivers a JS sign-in that happens while native is still starting up', async () => { const h = await start({ delayNativeStartup: true }); diff --git a/packages/expo/src/provider/__tests__/nativeClientSyncBehavior/newEngineAdapter.tsx b/packages/expo/src/provider/__tests__/nativeClientSyncBehavior/newEngineAdapter.tsx index 8a40e35ba0c..666bcd50d8c 100644 --- a/packages/expo/src/provider/__tests__/nativeClientSyncBehavior/newEngineAdapter.tsx +++ b/packages/expo/src/provider/__tests__/nativeClientSyncBehavior/newEngineAdapter.tsx @@ -21,7 +21,7 @@ const nativeClientInvalidatedEvent = 'clerkNativeClientInvalidated'; function createNativeModule( native: FakeNativeClerk, calls: string[], - { failConfigure }: { failConfigure: boolean }, + { failConfigure, configureGate }: { failConfigure: boolean; configureGate: Promise | null }, ): ClerkExpoNativeModule { const listeners = new Set<() => void>(); native.onChange(() => { @@ -54,14 +54,14 @@ function createNativeModule( listeners.add(invalidated); return { remove: () => listeners.delete(invalidated) }; }, - configure: (_publishableKey, seedDeviceToken) => { + configure: async (_publishableKey, seedDeviceToken) => { calls.push('configure'); + await configureGate; if (failConfigure) { - return Promise.reject(new Error('native configure failed')); + throw new Error('native configure failed'); } native.token ??= seedDeviceToken; native.isConfigured = true; - return Promise.resolve(); }, getDeviceToken: () => { calls.push('getDeviceToken'); @@ -101,6 +101,12 @@ export const renderWithNativeSync: RenderWithNativeSync = async (scenario = {}) : null; const releaseNativeStartup = scenario.delayNativeStartup ? native.delayStartup() : () => undefined; const nativeModuleCalls: string[] = []; + let releaseNativeConfigure = () => undefined as void; + const configureGate = scenario.delayNativeConfigure + ? new Promise(resolve => { + releaseNativeConfigure = resolve; + }) + : null; // Fresh engine modules per scenario: the native module is resolved at import time and the native // configuration, active engine and Clerk instance are module singletons. @@ -113,7 +119,10 @@ export const renderWithNativeSync: RenderWithNativeSync = async (scenario = {}) nativeModule: scenario.nativeModule === 'absent' ? null - : createNativeModule(native, nativeModuleCalls, { failConfigure: !!scenario.failNativeConfigure }), + : createNativeModule(native, nativeModuleCalls, { + failConfigure: !!scenario.failNativeConfigure, + configureGate, + }), }); const { ClerkProvider } = await import('../../ClerkProvider'); @@ -133,12 +142,14 @@ export const renderWithNativeSync: RenderWithNativeSync = async (scenario = {}) } }; - await waitFor(() => { - if (!js.loaded) { - throw new Error('Clerk has not loaded yet'); - } - }); - await settle(); + if (!scenario.manualClock) { + await waitFor(() => { + if (!js.loaded) { + throw new Error('Clerk has not loaded yet'); + } + }); + await settle(); + } const harness: NativeSyncHarness = { server, @@ -156,6 +167,7 @@ export const renderWithNativeSync: RenderWithNativeSync = async (scenario = {}) }, settle, releaseNativeStartup, + releaseNativeConfigure: () => releaseNativeConfigure(), unmount: () => view.unmount(), }; return harness; From f3ed4fcea816ab6165479f81c17348620c4fc54b Mon Sep 17 00:00:00 2001 From: wobsoriano Date: Sat, 5 Dec 2026 15:13:08 +0800 Subject: [PATCH 02/17] fix(expo): converge on the native client after a slow native configure --- .../expo-converge-native-client-slow-start.md | 5 ++ .../nativeClientSync.behavior.test.tsx | 31 +++++++++++++ .../expo/src/provider/nativeClientSync.ts | 46 +++++++++++++++++-- 3 files changed, 77 insertions(+), 5 deletions(-) create mode 100644 .changeset/expo-converge-native-client-slow-start.md diff --git a/.changeset/expo-converge-native-client-slow-start.md b/.changeset/expo-converge-native-client-slow-start.md new file mode 100644 index 00000000000..2bf849565f2 --- /dev/null +++ b/.changeset/expo-converge-native-client-slow-start.md @@ -0,0 +1,5 @@ +--- +'@clerk/expo': patch +--- + +Fix the JS SDK staying signed out while native components are signed in after a slow app start. When the native SDK takes longer than usual to start, the JS SDK now switches to the native SDK's client and session once it is ready, so native sign-in no longer fails with `session_exists`. 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 3895f92662f..c88bc7ddf08 100644 --- a/packages/expo/src/provider/__tests__/nativeClientSyncBehavior/nativeClientSync.behavior.test.tsx +++ b/packages/expo/src/provider/__tests__/nativeClientSyncBehavior/nativeClientSync.behavior.test.tsx @@ -743,6 +743,37 @@ 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 () => { + vi.useFakeTimers(); + const { server, token } = seedDevice(['user_1']); + server.singleSessionMode = true; + const cached = server.seedClient({ users: ['user_2'] }); + const h = await start({ + server, + nativeDeviceToken: token, + jsDeviceToken: cached.token, + delayNativeConfigure: true, + manualClock: true, + }); + h.native.client = server.inspectClient(token); + + // Configure outlives the startup timeout, so JS boots on the client in the app token cache. + await h.run(() => vi.advanceTimersByTimeAsync(3_500)); + expect(h.js.session?.id).toBe(cached.sessionIds.user_2); + // Each request still waits out the configure timeout before it reads the app token cache. + await h.run(async () => { + const signingOut = h.js.signOut(); + await vi.advanceTimersByTimeAsync(3_500); + await signingOut; + }); + expect(h.js.session).toBeNull(); + await h.run(() => h.releaseNativeConfigure()); + await skipRetryBackoff(h); + + expect(h.js.client?.id).toBe(cached.clientId); + expect(h.js.session).toBeNull(); + }); + it('delivers a JS sign-in that happens while native is still starting up', async () => { const h = await start({ delayNativeStartup: true }); diff --git a/packages/expo/src/provider/nativeClientSync.ts b/packages/expo/src/provider/nativeClientSync.ts index 22609c4de9c..7c70d23f89a 100644 --- a/packages/expo/src/provider/nativeClientSync.ts +++ b/packages/expo/src/provider/nativeClientSync.ts @@ -198,6 +198,10 @@ export function createNativeClientSync( const fallback = () => getUserTokenCache() ?? MemoryTokenCache; const ready = () => configureOnce(native, publishableKey, proxyUrl, fallback(), getNativeUpdateRequiredViewEnabled()); let mirroredToken: string | null = null; + // Set when the client JWT was read or written before native finished configuring, so JS may be on another client. + let startedOnFallback = false; + // A JS sign-out is deliberate, so JS never converges back onto native's signed-in client after one. + let signedOutInJs = false; const discardedClientIds = new Set(); let lastFingerprint: string | undefined; @@ -237,7 +241,11 @@ export function createNativeClientSync( const tokenCache: ClientTokenCache = { getToken: async key => { - if (key !== CLERK_CLIENT_JWT_KEY || !(await ready())) { + if (key !== CLERK_CLIENT_JWT_KEY) { + return fallback().getToken(key); + } + if (!(await ready())) { + startedOnFallback = true; return fallback().getToken(key); } return native.getDeviceToken().catch(error => { @@ -246,7 +254,11 @@ export function createNativeClientSync( }); }, saveToken: async (key, token) => { - if (key !== CLERK_CLIENT_JWT_KEY || !(await ready())) { + if (key !== CLERK_CLIENT_JWT_KEY) { + return fallback().saveToken(key, token); + } + if (!(await ready())) { + startedOnFallback = true; return fallback().saveToken(key, token); } await tokenCache.saveClientToken(token, await native.getDeviceToken().catch(() => null)); @@ -262,6 +274,7 @@ export function createNativeClientSync( return; } if (!isReady) { + startedOnFallback = true; return fallback().saveToken(CLERK_CLIENT_JWT_KEY, token); } if (token === requestToken && token === mirroredToken) { @@ -378,6 +391,24 @@ export function createNativeClientSync( const pullInBackground = () => void fromNative.run().catch(error => warn('Failed to refresh the client from native.', error)); + // After a startup that fell back to the app token cache, JS may have loaded another client than native's. + const convergeOnNative = async () => { + const jsClientId = clerk.client?.id; + if (!startedOnFallback || !attached || !jsClientId || !(await ready())) { + return; + } + const nativeClientId = clientIdOf(await native.getDeviceToken().catch(() => null)); + // Checked after the awaits so a sign-out that lands during them still wins. + if (!nativeClientId || discardedClientIds.has(nativeClientId) || signedOutInJs) { + return; + } + if (nativeClientId === clerk.client?.id) { + startedOnFallback = false; + return; + } + pullInBackground(); + }; + const toNative = singleFlight(async () => { // Let an in-flight native pull settle first so one refresh covers what it applied. await fromNative.current()?.catch(noop); @@ -453,6 +484,7 @@ export function createNativeClientSync( const options = args.find(arg => !!arg && typeof arg === 'object') as { sessionId?: string } | undefined; const client = clerk.client; const signsOutEverySession = !options?.sessionId || (client?.signedInSessions.length ?? 0) <= 1; + signedOutInJs = true; let failure: { error: unknown } | null = null; try { await originalSignOut(...args); @@ -477,9 +509,13 @@ export function createNativeClientSync( if (signOut) { clerk.signOut = signOut; } - const removeClerkListener = clerk.addListener( - () => void toNative.run().catch(error => warn('Failed to refresh the native client.', error)), - ); + 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) { From 620f758cc09aaec5ad8b2adeee5efb5cd15dae50 Mon Sep 17 00:00:00 2001 From: wobsoriano Date: Sat, 5 Dec 2026 15:33:59 +0800 Subject: [PATCH 03/17] refactor(expo): name the slow-configure helpers instead of commenting them --- .../fakeNativeClerk.ts | 4 +++ .../nativeClientSyncBehavior/fakeServer.ts | 1 - .../nativeClientSyncBehavior/harness.ts | 4 +-- .../nativeClientSync.behavior.test.tsx | 23 +++++++-------- .../newEngineAdapter.tsx | 4 +-- .../expo/src/provider/nativeClientSync.ts | 28 +++++++++---------- 6 files changed, 33 insertions(+), 31 deletions(-) diff --git a/packages/expo/src/provider/__tests__/nativeClientSyncBehavior/fakeNativeClerk.ts b/packages/expo/src/provider/__tests__/nativeClientSyncBehavior/fakeNativeClerk.ts index 8afede7a344..c11ec876e09 100644 --- a/packages/expo/src/provider/__tests__/nativeClientSyncBehavior/fakeNativeClerk.ts +++ b/packages/expo/src/provider/__tests__/nativeClientSyncBehavior/fakeNativeClerk.ts @@ -142,6 +142,10 @@ export class FakeNativeClerk { await this.#observe(() => this.server.getClient('native', this.token)); } + restoreClientFromKeychain(client: FakeServerClientJSON | null): void { + this.client = client; + } + /** Native ends up on a brand new client with no sessions, e.g. after losing its keychain entry. */ async switchToForeignSessionlessClient(): Promise { await this.#observe(() => this.server.createSessionlessClient('native')); diff --git a/packages/expo/src/provider/__tests__/nativeClientSyncBehavior/fakeServer.ts b/packages/expo/src/provider/__tests__/nativeClientSyncBehavior/fakeServer.ts index 6efef18a7a8..a214c5b410a 100644 --- a/packages/expo/src/provider/__tests__/nativeClientSyncBehavior/fakeServer.ts +++ b/packages/expo/src/provider/__tests__/nativeClientSyncBehavior/fakeServer.ts @@ -98,7 +98,6 @@ export class FakeClerkServer { return { client, token: this.#mintToken(client.id) }; } - /** Set to answer GET /client without a device token like FAPI does: with a brand new client. */ createClientForMissingToken = false; #authenticate(token: string | null): { client: FakeServerClientJSON | null; token: string | null } { diff --git a/packages/expo/src/provider/__tests__/nativeClientSyncBehavior/harness.ts b/packages/expo/src/provider/__tests__/nativeClientSyncBehavior/harness.ts index d605c0c30c5..eb1e47ab72d 100644 --- a/packages/expo/src/provider/__tests__/nativeClientSyncBehavior/harness.ts +++ b/packages/expo/src/provider/__tests__/nativeClientSyncBehavior/harness.ts @@ -16,10 +16,8 @@ export type NativeSyncScenario = { /** The native SDK fails to configure, e.g. a native build that cannot initialize Clerk. */ failNativeConfigure?: boolean; delayNativeStartup?: boolean; - /** Native `configure` does not resolve until `releaseNativeConfigure`. */ delayNativeConfigure?: boolean; - /** The test drives fake timers itself, so the harness neither waits for load nor settles on real timers. */ - manualClock?: boolean; + skipInitialLoad?: boolean; strictMode?: boolean; }; 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 c88bc7ddf08..06eaf0818df 100644 --- a/packages/expo/src/provider/__tests__/nativeClientSyncBehavior/nativeClientSync.behavior.test.tsx +++ b/packages/expo/src/provider/__tests__/nativeClientSyncBehavior/nativeClientSync.behavior.test.tsx @@ -2,6 +2,7 @@ import { waitFor } from '@testing-library/react'; import { afterEach, describe, expect, it, vi } from 'vitest'; import { CLERK_CLIENT_JWT_KEY } from '../../../constants'; +import { CONFIGURE_TIMEOUT_MS } from '../../nativeClientSync'; import { FakeClerkServer, type NativeSyncHarness, renderWithNativeSync } from './index'; vi.mock('../../../polyfills', () => ({})); @@ -87,6 +88,10 @@ afterEach(() => { vi.useRealTimers(); }); +async function outlastConfigureTimeout(h: NativeSyncHarness): Promise { + await h.run(() => vi.advanceTimersByTimeAsync(CONFIGURE_TIMEOUT_MS + 500)); +} + async function skipRetryBackoff(h: NativeSyncHarness): Promise { await h.run(() => vi.advanceTimersByTimeAsync(10_000)); } @@ -727,13 +732,11 @@ describe('native client sync behavior', () => { nativeDeviceToken: token, persistentTokenCache: true, delayNativeConfigure: true, - manualClock: true, + skipInitialLoad: true, }); - // Native restores its signed-in client from the keychain before JS can see it. - h.native.client = server.inspectClient(token); + h.native.restoreClientFromKeychain(server.inspectClient(token)); - // Configure outlives the startup timeout, so the boot request reads the empty app token cache. - await h.run(() => vi.advanceTimersByTimeAsync(3_500)); + await outlastConfigureTimeout(h); expect(h.js.client?.id).not.toBe(clientId); await h.run(() => h.releaseNativeConfigure()); await skipRetryBackoff(h); @@ -753,17 +756,15 @@ describe('native client sync behavior', () => { nativeDeviceToken: token, jsDeviceToken: cached.token, delayNativeConfigure: true, - manualClock: true, + skipInitialLoad: true, }); - h.native.client = server.inspectClient(token); + h.native.restoreClientFromKeychain(server.inspectClient(token)); - // Configure outlives the startup timeout, so JS boots on the client in the app token cache. - await h.run(() => vi.advanceTimersByTimeAsync(3_500)); + await outlastConfigureTimeout(h); expect(h.js.session?.id).toBe(cached.sessionIds.user_2); - // Each request still waits out the configure timeout before it reads the app token cache. await h.run(async () => { const signingOut = h.js.signOut(); - await vi.advanceTimersByTimeAsync(3_500); + await vi.advanceTimersByTimeAsync(CONFIGURE_TIMEOUT_MS + 500); await signingOut; }); expect(h.js.session).toBeNull(); diff --git a/packages/expo/src/provider/__tests__/nativeClientSyncBehavior/newEngineAdapter.tsx b/packages/expo/src/provider/__tests__/nativeClientSyncBehavior/newEngineAdapter.tsx index 666bcd50d8c..f9cf64f47f6 100644 --- a/packages/expo/src/provider/__tests__/nativeClientSyncBehavior/newEngineAdapter.tsx +++ b/packages/expo/src/provider/__tests__/nativeClientSyncBehavior/newEngineAdapter.tsx @@ -101,7 +101,7 @@ export const renderWithNativeSync: RenderWithNativeSync = async (scenario = {}) : null; const releaseNativeStartup = scenario.delayNativeStartup ? native.delayStartup() : () => undefined; const nativeModuleCalls: string[] = []; - let releaseNativeConfigure = () => undefined as void; + let releaseNativeConfigure: () => void = () => {}; const configureGate = scenario.delayNativeConfigure ? new Promise(resolve => { releaseNativeConfigure = resolve; @@ -142,7 +142,7 @@ export const renderWithNativeSync: RenderWithNativeSync = async (scenario = {}) } }; - if (!scenario.manualClock) { + if (!scenario.skipInitialLoad) { await waitFor(() => { if (!js.loaded) { throw new Error('Clerk has not loaded yet'); diff --git a/packages/expo/src/provider/nativeClientSync.ts b/packages/expo/src/provider/nativeClientSync.ts index 7c70d23f89a..838fbe5c054 100644 --- a/packages/expo/src/provider/nativeClientSync.ts +++ b/packages/expo/src/provider/nativeClientSync.ts @@ -10,7 +10,7 @@ import { CLERK_CLIENT_JWT_KEY } from '../constants'; import type { ClerkExpoNativeModule } from '../utils/native-module'; import { waitUntilAppIsActive } from '../utils/runtime'; -const CONFIGURE_TIMEOUT_MS = 3_000; +export const CONFIGURE_TIMEOUT_MS = 3_000; const INVALIDATED_EVENT = 'clerkNativeClientInvalidated'; type FetchableClient = ClientResource & { fetch?: (options?: { fetchMaxTries?: number }) => Promise }; @@ -198,9 +198,7 @@ export function createNativeClientSync( const fallback = () => getUserTokenCache() ?? MemoryTokenCache; const ready = () => configureOnce(native, publishableKey, proxyUrl, fallback(), getNativeUpdateRequiredViewEnabled()); let mirroredToken: string | null = null; - // Set when the client JWT was read or written before native finished configuring, so JS may be on another client. - let startedOnFallback = false; - // A JS sign-out is deliberate, so JS never converges back onto native's signed-in client after one. + let usedFallbackTokenCache = false; let signedOutInJs = false; const discardedClientIds = new Set(); let lastFingerprint: string | undefined; @@ -245,7 +243,7 @@ export function createNativeClientSync( return fallback().getToken(key); } if (!(await ready())) { - startedOnFallback = true; + usedFallbackTokenCache = true; return fallback().getToken(key); } return native.getDeviceToken().catch(error => { @@ -258,7 +256,7 @@ export function createNativeClientSync( return fallback().saveToken(key, token); } if (!(await ready())) { - startedOnFallback = true; + usedFallbackTokenCache = true; return fallback().saveToken(key, token); } await tokenCache.saveClientToken(token, await native.getDeviceToken().catch(() => null)); @@ -274,7 +272,7 @@ export function createNativeClientSync( return; } if (!isReady) { - startedOnFallback = true; + usedFallbackTokenCache = true; return fallback().saveToken(CLERK_CLIENT_JWT_KEY, token); } if (token === requestToken && token === mirroredToken) { @@ -391,19 +389,21 @@ export function createNativeClientSync( const pullInBackground = () => void fromNative.run().catch(error => warn('Failed to refresh the client from native.', error)); - // After a startup that fell back to the app token cache, JS may have loaded another client than native's. + const nativeClientToAdopt = async () => { + const nativeClientId = clientIdOf(await native.getDeviceToken().catch(() => null)); + return nativeClientId && !signedOutInJs && !discardedClientIds.has(nativeClientId) ? nativeClientId : null; + }; + const convergeOnNative = async () => { - const jsClientId = clerk.client?.id; - if (!startedOnFallback || !attached || !jsClientId || !(await ready())) { + if (!usedFallbackTokenCache || !attached || !clerk.client?.id || !(await ready())) { return; } - const nativeClientId = clientIdOf(await native.getDeviceToken().catch(() => null)); - // Checked after the awaits so a sign-out that lands during them still wins. - if (!nativeClientId || discardedClientIds.has(nativeClientId) || signedOutInJs) { + const nativeClientId = await nativeClientToAdopt(); + if (!nativeClientId) { return; } if (nativeClientId === clerk.client?.id) { - startedOnFallback = false; + usedFallbackTokenCache = false; return; } pullInBackground(); From 500512ccd87314ca85cae1ad3a5b0a0a0d84f1ab Mon Sep 17 00:00:00 2001 From: wobsoriano Date: Sat, 5 Dec 2026 15:39:28 +0800 Subject: [PATCH 04/17] fix(expo): refetch the JS client once per native client while converging --- .../fakeNativeClerk.ts | 1 + .../nativeClientSync.behavior.test.tsx | 30 +++++++++++++++++++ .../newEngineAdapter.tsx | 2 +- .../expo/src/provider/nativeClientSync.ts | 6 ++++ 4 files changed, 38 insertions(+), 1 deletion(-) diff --git a/packages/expo/src/provider/__tests__/nativeClientSyncBehavior/fakeNativeClerk.ts b/packages/expo/src/provider/__tests__/nativeClientSyncBehavior/fakeNativeClerk.ts index c11ec876e09..63cd49dcb54 100644 --- a/packages/expo/src/provider/__tests__/nativeClientSyncBehavior/fakeNativeClerk.ts +++ b/packages/expo/src/provider/__tests__/nativeClientSyncBehavior/fakeNativeClerk.ts @@ -24,6 +24,7 @@ export class FakeNativeClerk { client: FakeServerClientJSON | null = null; isConfigured = false; clientRefreshCount = 0; + deviceTokenWritesFail = false; #listeners = new Set(); #heldChanges: Array<[NativeClientChange, NativeChangeOrigin]> | null = null; #startupGate: Promise | null = null; 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 06eaf0818df..8908d16aae5 100644 --- a/packages/expo/src/provider/__tests__/nativeClientSyncBehavior/nativeClientSync.behavior.test.tsx +++ b/packages/expo/src/provider/__tests__/nativeClientSyncBehavior/nativeClientSync.behavior.test.tsx @@ -775,6 +775,36 @@ describe('native client sync behavior', () => { expect(h.js.session).toBeNull(); }); + it('refetches the JS client a bounded number of times when native holds a retired token it cannot replace', async () => { + const { server, token, clientId } = seedDevice(['user_1']); + server.createClientForMissingToken = true; + server.rotateTokenOnNextResponse(token); + await server.getClient('native', token); + vi.useFakeTimers(); + const h = await start({ + server, + nativeDeviceToken: token, + persistentTokenCache: true, + delayNativeConfigure: true, + delayNativeStartup: true, + skipInitialLoad: true, + }); + 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++) { + await vi.advanceTimersToNextTimerAsync(); + } + }); + + 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('delivers a JS sign-in that happens while native is still starting up', async () => { const h = await start({ delayNativeStartup: true }); diff --git a/packages/expo/src/provider/__tests__/nativeClientSyncBehavior/newEngineAdapter.tsx b/packages/expo/src/provider/__tests__/nativeClientSyncBehavior/newEngineAdapter.tsx index f9cf64f47f6..69b7b213186 100644 --- a/packages/expo/src/provider/__tests__/nativeClientSyncBehavior/newEngineAdapter.tsx +++ b/packages/expo/src/provider/__tests__/nativeClientSyncBehavior/newEngineAdapter.tsx @@ -69,7 +69,7 @@ function createNativeModule( }, setDeviceToken: async (token, expected) => { calls.push('setDeviceToken'); - if (native.token !== expected) { + if (native.deviceTokenWritesFail || native.token !== expected) { return false; } await notifyIfChanged(() => { diff --git a/packages/expo/src/provider/nativeClientSync.ts b/packages/expo/src/provider/nativeClientSync.ts index 838fbe5c054..322c699c15a 100644 --- a/packages/expo/src/provider/nativeClientSync.ts +++ b/packages/expo/src/provider/nativeClientSync.ts @@ -394,6 +394,7 @@ export function createNativeClientSync( return nativeClientId && !signedOutInJs && !discardedClientIds.has(nativeClientId) ? nativeClientId : null; }; + let convergingOn: string | null = null; const convergeOnNative = async () => { if (!usedFallbackTokenCache || !attached || !clerk.client?.id || !(await ready())) { return; @@ -404,8 +405,13 @@ export function createNativeClientSync( } if (nativeClientId === clerk.client?.id) { usedFallbackTokenCache = false; + convergingOn = null; return; } + if (nativeClientId === convergingOn) { + return; + } + convergingOn = nativeClientId; pullInBackground(); }; From c8e3feefa86cd69e523dd6802f7fff6ae638317d Mon Sep 17 00:00:00 2001 From: wobsoriano Date: Sat, 5 Dec 2026 15:41:38 +0800 Subject: [PATCH 05/17] fix(expo): stop applying a native client pull that started before a JS sign-out --- .../nativeClientSync.behavior.test.tsx | 97 +++++++++++++++++++ .../expo/src/provider/nativeClientSync.ts | 21 ++-- 2 files changed, 111 insertions(+), 7 deletions(-) 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 8908d16aae5..a31973f5c2c 100644 --- a/packages/expo/src/provider/__tests__/nativeClientSyncBehavior/nativeClientSync.behavior.test.tsx +++ b/packages/expo/src/provider/__tests__/nativeClientSyncBehavior/nativeClientSync.behavior.test.tsx @@ -92,6 +92,33 @@ async function outlastConfigureTimeout(h: NativeSyncHarness): Promise { await h.run(() => vi.advanceTimersByTimeAsync(CONFIGURE_TIMEOUT_MS + 500)); } +async function bootOnCachedClientWhileNativeConfigures(cachedUsers: string[]) { + const { server, token } = seedDevice(['user_1']); + const cached = server.seedClient({ users: cachedUsers }); + const h = await start({ + server, + nativeDeviceToken: token, + jsDeviceToken: cached.token, + delayNativeConfigure: true, + skipInitialLoad: true, + }); + h.native.restoreClientFromKeychain(server.inspectClient(token)); + await outlastConfigureTimeout(h); + return { h, cached }; +} + +async function whileTimersRun(h: NativeSyncHarness, action: () => T | Promise): Promise { + return h.run(async () => { + const running = Promise.resolve(action()); + await vi.advanceTimersByTimeAsync(50); + return running; + }); +} + +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)); } @@ -805,6 +832,76 @@ describe('native client sync behavior', () => { 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(['user_2']); + 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, cached } = await bootOnCachedClientWhileNativeConfigures(['user_2']); + h.server.failNextRequests('js', 'GET /client', 3); + await whileTimersRun(h, () => h.releaseNativeConfigure()); + await skipRetryBackoff(h); + expect(h.js.session?.id).toBe(cached.sessionIds.user_2); + + 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('keeps JS signed out of its last session when the pull onto the native client lands after the sign-out', async () => { + vi.useFakeTimers(); + const { h, cached } = await bootOnCachedClientWhileNativeConfigures(['user_2', 'user_3']); + const held = h.server.holdNextResponse('js', 'GET /client'); + await whileTimersRun(h, () => h.releaseNativeConfigure()); + await held.handled; + + await whileTimersRun(h, () => h.js.signOut({ sessionId: cached.sessionIds.user_2 })); + expect(h.js.session).toBeNull(); + const emissionIndex = h.js.emissions.length; + held.release(); + 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(['user_2']); + 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('delivers a JS sign-in that happens while native is still starting up', async () => { const h = await start({ delayNativeStartup: true }); diff --git a/packages/expo/src/provider/nativeClientSync.ts b/packages/expo/src/provider/nativeClientSync.ts index 322c699c15a..8a4695abfff 100644 --- a/packages/expo/src/provider/nativeClientSync.ts +++ b/packages/expo/src/provider/nativeClientSync.ts @@ -331,7 +331,7 @@ export function createNativeClientSync( let reconciling: Promise | null = null; // Refetches the JS client with the shared device token. - const refetchClient = async () => { + const refetchClient = async (isCurrent: () => boolean = () => true) => { const client = clerk.client as FetchableClient | null | undefined; if (typeof client?.fetch === 'function') { let fetched = await client.fetch({ fetchMaxTries: 1 }); @@ -339,7 +339,9 @@ export function createNativeClientSync( if (sharedClientId && fetched.id && fetched.id !== sharedClientId) { fetched = await client.fetch({ fetchMaxTries: 1 }); } - clerk.updateClient(fetched); + if (isCurrent()) { + clerk.updateClient(fetched); + } } else { await clerk.__internal_reloadInitialResources?.(); } @@ -359,28 +361,31 @@ export function createNativeClientSync( let attached = true; let needsRepair = false; + let jsSignOuts = 0; const fromNative = singleFlight(async () => { + const signOutsAtStart = jsSignOuts; + const isCurrent = () => attached && jsSignOuts === signOutsAtStart; if (await ready()) { try { await retry( async () => { - if (attached) { - await refetchClient(); + if (isCurrent()) { + await refetchClient(isCurrent); } }, { initialDelay: 300, maxDelayBetweenRetries: 2_000, - shouldRetry: (error, iterations) => attached && iterations <= 2 && !is4xxError(error), + shouldRetry: (error, iterations) => isCurrent() && iterations <= 2 && !is4xxError(error), }, ); - if (!attached) { + if (!isCurrent()) { return; } await activateDefaultSession(); needsRepair = false; } catch (error) { - needsRepair = true; + needsRepair = isCurrent(); throw error; } await reconciling; @@ -491,6 +496,8 @@ export function createNativeClientSync( const client = clerk.client; const signsOutEverySession = !options?.sessionId || (client?.signedInSessions.length ?? 0) <= 1; signedOutInJs = true; + jsSignOuts += 1; + needsRepair = false; let failure: { error: unknown } | null = null; try { await originalSignOut(...args); From 0b4a39ba0f913d7440051494692977657d1171d8 Mon Sep 17 00:00:00 2001 From: wobsoriano Date: Sat, 5 Dec 2026 15:43:15 +0800 Subject: [PATCH 06/17] fix(expo): converge on the native client after a failed native device token read --- .../fakeNativeClerk.ts | 1 + .../nativeClientSync.behavior.test.tsx | 20 +++++++++++++++++++ .../newEngineAdapter.tsx | 4 ++++ .../expo/src/provider/nativeClientSync.ts | 1 + 4 files changed, 26 insertions(+) diff --git a/packages/expo/src/provider/__tests__/nativeClientSyncBehavior/fakeNativeClerk.ts b/packages/expo/src/provider/__tests__/nativeClientSyncBehavior/fakeNativeClerk.ts index 63cd49dcb54..1dd25210dbe 100644 --- a/packages/expo/src/provider/__tests__/nativeClientSyncBehavior/fakeNativeClerk.ts +++ b/packages/expo/src/provider/__tests__/nativeClientSyncBehavior/fakeNativeClerk.ts @@ -25,6 +25,7 @@ export class FakeNativeClerk { isConfigured = false; clientRefreshCount = 0; deviceTokenWritesFail = false; + deviceTokenReadFailures = 0; #listeners = new Set(); #heldChanges: Array<[NativeClientChange, NativeChangeOrigin]> | null = null; #startupGate: Promise | null = null; 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 a31973f5c2c..f19b29a0d29 100644 --- a/packages/expo/src/provider/__tests__/nativeClientSyncBehavior/nativeClientSync.behavior.test.tsx +++ b/packages/expo/src/provider/__tests__/nativeClientSyncBehavior/nativeClientSync.behavior.test.tsx @@ -802,6 +802,26 @@ describe('native client sync behavior', () => { expect(h.js.session).toBeNull(); }); + it('signs JS in on the native client when JS booted on the app token cache because reading the native device token failed', async () => { + const { server, token, clientId, sessionIds } = seedDevice(['user_1']); + const foreign = server.seedClient(); + const h = await start({ + server, + nativeDeviceToken: token, + jsDeviceToken: foreign.token, + delayNativeConfigure: true, + skipInitialLoad: true, + }); + h.native.restoreClientFromKeychain(server.inspectClient(token)); + h.native.deviceTokenReadFailures = 1; + + await h.run(() => h.releaseNativeConfigure()); + await h.settle(); + + expect(h.js.client?.id).toBe(clientId); + expect(h.js.session?.id).toBe(sessionIds.user_1); + }); + it('refetches the JS client a bounded number of times when native holds a retired token it cannot replace', async () => { const { server, token, clientId } = seedDevice(['user_1']); server.createClientForMissingToken = true; diff --git a/packages/expo/src/provider/__tests__/nativeClientSyncBehavior/newEngineAdapter.tsx b/packages/expo/src/provider/__tests__/nativeClientSyncBehavior/newEngineAdapter.tsx index 69b7b213186..ee1f67060b5 100644 --- a/packages/expo/src/provider/__tests__/nativeClientSyncBehavior/newEngineAdapter.tsx +++ b/packages/expo/src/provider/__tests__/nativeClientSyncBehavior/newEngineAdapter.tsx @@ -65,6 +65,10 @@ function createNativeModule( }, getDeviceToken: () => { calls.push('getDeviceToken'); + if (native.deviceTokenReadFailures > 0) { + native.deviceTokenReadFailures -= 1; + return Promise.reject(new Error('native device token read failed')); + } return Promise.resolve(native.token); }, setDeviceToken: async (token, expected) => { diff --git a/packages/expo/src/provider/nativeClientSync.ts b/packages/expo/src/provider/nativeClientSync.ts index 8a4695abfff..d1f571b756e 100644 --- a/packages/expo/src/provider/nativeClientSync.ts +++ b/packages/expo/src/provider/nativeClientSync.ts @@ -248,6 +248,7 @@ export function createNativeClientSync( } return native.getDeviceToken().catch(error => { warn('Failed to read the native device token.', error); + usedFallbackTokenCache = true; return fallback().getToken(key); }); }, From 3fc4ac46324852eac145e2791f527cb2e1d0ff8b Mon Sep 17 00:00:00 2001 From: wobsoriano Date: Sat, 5 Dec 2026 15:45:42 +0800 Subject: [PATCH 07/17] fix(expo): keep the app token cache on the native device token --- .../nativeClientSyncBehavior/fakeServer.ts | 11 +++++++- .../nativeClientSync.behavior.test.tsx | 26 +++++++++++++++++++ .../expo/src/provider/nativeClientSync.ts | 16 ++++++++---- 3 files changed, 47 insertions(+), 6 deletions(-) diff --git a/packages/expo/src/provider/__tests__/nativeClientSyncBehavior/fakeServer.ts b/packages/expo/src/provider/__tests__/nativeClientSyncBehavior/fakeServer.ts index a214c5b410a..12aa8e0cb36 100644 --- a/packages/expo/src/provider/__tests__/nativeClientSyncBehavior/fakeServer.ts +++ b/packages/expo/src/provider/__tests__/nativeClientSyncBehavior/fakeServer.ts @@ -99,6 +99,7 @@ export class FakeClerkServer { } createClientForMissingToken = false; + omitUnrotatedTokenOnReadAndTouch = false; #authenticate(token: string | null): { client: FakeServerClientJSON | null; token: string | null } { if ((token && this.#retiredTokens.has(token)) || (!token && this.createClientForMissingToken)) { @@ -125,6 +126,14 @@ export class FakeClerkServer { return { status, client: client ? cloneClient(client) : null, token: responseToken }; } + #withoutUnrotatedToken(operation: string, token: string | null, response: T): T { + const omitsToken = + this.omitUnrotatedTokenOnReadAndTouch && + (operation === 'GET /client' || operation === 'POST /client/sessions/:id/touch') && + response.token === token; + return omitsToken ? { ...response, token: null } : response; + } + async #send( caller: FapiCaller, operation: string, @@ -143,7 +152,7 @@ export class FakeClerkServer { } throw new TypeError('Network request failed'); } - const response = handle(); + const response = this.#withoutUnrotatedToken(operation, token, handle()); const holdIndex = this.#responseHolds.findIndex(hold => hold.caller === caller && hold.operation === operation); if (holdIndex >= 0) { const [hold] = this.#responseHolds.splice(holdIndex, 1); 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 f19b29a0d29..d579a76cc28 100644 --- a/packages/expo/src/provider/__tests__/nativeClientSyncBehavior/nativeClientSync.behavior.test.tsx +++ b/packages/expo/src/provider/__tests__/nativeClientSyncBehavior/nativeClientSync.behavior.test.tsx @@ -802,6 +802,32 @@ describe('native client sync behavior', () => { expect(h.js.session).toBeNull(); }); + it('boots JS on the native client during a slow native configure after JS followed a native sign-in on the previous launch', async () => { + const server = new FakeClerkServer(); + server.omitUnrotatedTokenOnReadAndTouch = true; + 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(); + const nativeToken = previousLaunch.native.token; + const cachedToken = previousLaunch.persistentTokenCache?.read(CLERK_CLIENT_JWT_KEY) ?? null; + previousLaunch.unmount(); + + vi.useFakeTimers(); + server.createClientForMissingToken = true; + const h = await start({ + server, + nativeDeviceToken: nativeToken, + jsDeviceToken: cachedToken, + delayNativeConfigure: true, + skipInitialLoad: true, + }); + await outlastConfigureTimeout(h); + + expect(h.js.client?.id).toBe(server.clientIdForToken(nativeToken)); + expect(h.js.session?.id).toBe(sessionId); + }); + it('signs JS in on the native client when JS booted on the app token cache because reading the native device token failed', async () => { const { server, token, clientId, sessionIds } = seedDevice(['user_1']); const foreign = server.seedClient(); diff --git a/packages/expo/src/provider/nativeClientSync.ts b/packages/expo/src/provider/nativeClientSync.ts index d1f571b756e..334ac879edb 100644 --- a/packages/expo/src/provider/nativeClientSync.ts +++ b/packages/expo/src/provider/nativeClientSync.ts @@ -246,11 +246,17 @@ export function createNativeClientSync( usedFallbackTokenCache = true; return fallback().getToken(key); } - return native.getDeviceToken().catch(error => { - warn('Failed to read the native device token.', error); - usedFallbackTokenCache = true; - return fallback().getToken(key); - }); + return native.getDeviceToken().then( + token => { + mirror(token); + return token; + }, + error => { + warn('Failed to read the native device token.', error); + usedFallbackTokenCache = true; + return fallback().getToken(key); + }, + ); }, saveToken: async (key, token) => { if (key !== CLERK_CLIENT_JWT_KEY) { From 7d5a860ff1a0a1248cdf90829d53dc93c633d92a Mon Sep 17 00:00:00 2001 From: wobsoriano Date: Sat, 5 Dec 2026 16:07:32 +0800 Subject: [PATCH 08/17] test(expo): cover a native sign-in restored after a slow native configure --- .../verify-clerk-expo/features/README.md | 2 +- .../features/native-js-sync.md | 4 ++ .../slow-native-configure.e2e.ts | 26 +++++++++ integration/templates/expo-native/App.tsx | 3 +- .../templates/expo-native/screens/Home.tsx | 28 +++++++++ .../templates/expo-native/verify/faults.ts | 57 +++++++++++++++++++ 6 files changed, 118 insertions(+), 2 deletions(-) create mode 100644 integration/expo-native/specs/features/native-js-sync/slow-native-configure.e2e.ts diff --git a/.claude/skills/verify-clerk-expo/features/README.md b/.claude/skills/verify-clerk-expo/features/README.md index 981f3bf5147..7161745ab54 100644 --- a/.claude/skills/verify-clerk-expo/features/README.md +++ b/.claude/skills/verify-clerk-expo/features/README.md @@ -56,7 +56,7 @@ Each feature file starts with an H1 title and one paragraph describing the user- - [Custom sign-in flow](./custom-flow-sign-in.md) covers an email code sign-in built on `useSignIn`. - [Custom sign-up flow](./custom-flow-sign-up.md) covers an email and password sign-up built on `useSignUp`. - [Token cache persistence](./token-cache-persistence.md) covers restoring the same session after a relaunch. -- [Native and JS session sync](./native-js-sync.md) covers a native sign-out and a native password sign-in reaching `useAuth`, `useUser`, and `useSession`, that sign-in surviving a relaunch, a second native sign-in in one process, a native sign-in whose first client fetch fails, a ticket sign-in reaching the native profile, a JS sign-out clearing the hooks, and a JS sign-out whose request fails letting another user sign in, and it lists the active organization's sync and the foreground repair as states no spec reaches. +- [Native and JS session sync](./native-js-sync.md) covers a native sign-out and a native password sign-in reaching `useAuth`, `useUser`, and `useSession`, that sign-in surviving a relaunch and a relaunch whose native configure is slow, a second native sign-in in one process, a native sign-in whose first client fetch fails, a ticket sign-in reaching the native profile, a JS sign-out clearing the hooks, and a JS sign-out whose request fails letting another user sign in, and it lists the active organization's sync and the foreground repair as states no spec reaches. - [Native modules](./native-modules.md) covers `useSignInWithGoogle` opening the native Google sign-in, a cancel of it on iOS, and on Android when Google's page closes, by back or by itself, and `useBiometricCredentials` reporting what its native module found on the device. - [Update required](./update-required.md) covers the update screen for a signed-in and a signed-out user on a build below the minimum, the same session returning once the minimum is lowered, and a build at the minimum, on both platforms, and it lists the states no spec reaches. - [Native to Web SSO](./native-to-web-sso.md) covers the test app's own screen that loads the Account Portal in a WebView with `useAuthenticatedWebView`, signed in as the native user, and a transfer refused with `feature_not_enabled` when session transfers are off, on both platforms, and it lists the states no spec reaches. diff --git a/.claude/skills/verify-clerk-expo/features/native-js-sync.md b/.claude/skills/verify-clerk-expo/features/native-js-sync.md index 4ed03391f07..1d8eff9f342 100644 --- a/.claude/skills/verify-clerk-expo/features/native-js-sync.md +++ b/.claude/skills/verify-clerk-expo/features/native-js-sync.md @@ -10,6 +10,7 @@ A session change in the native UI reaches the `@clerk/expo` JS hooks, and a sess - `client-fetch-failure` signs in natively while the JS client fetch that follows fails. One failed fetch still reaches the hooks, because the SDK retries it. - `js-sign-in` signs in with a ticket through `useSignIn`, and the native profile shows the same user. `user-button-and-profile/profile` proves it. - `js-sign-out` signs out through `useAuth().signOut()`, and the home shows no user and no session. The second test of `user-button-and-profile/profile` proves it. +- `slow-native-configure` signs in natively, then relaunches while the native SDK takes 5 seconds to configure, longer than the SDK waits for it. The hooks report the same user and the same session. - `offline-sign-out` signs out through `useAuth().signOut()` while the sign-out request fails, and the home shows `Signed out`. Another user then signs in natively on a single-session instance. ## How to get to it (user POV) @@ -28,6 +29,7 @@ Preconditions: - **Client fetch failure.** Run `integration/expo-native/bin/control-clerk-expo run native-js-sync/client-fetch-failure --platform ios`, and again with `--platform android`. The signed-out home of a verify launch has a `Drop the next client fetch` button (`verify.fault.dropClientFetch`). Each tap makes the next `GET /v1/client` of clerk-js fail with `Network request failed`, and `verify.fault.dropped` shows how many requests were dropped. The test taps it once, signs in with `signInWithPassword`, expects the home to show the user, and expects the count to read `1`, so the pass cannot come from a fetch that was never dropped. Screenshot `signed-in-after-one-failed-fetch`. - **JS sign-in and sign-out.** `user-button-and-profile/profile` proves both. Run `integration/expo-native/bin/control-clerk-expo run user-button-and-profile/profile --platform ios`, and again with `--platform android`. The first test signs in with a ticket through `useSignIn` and expects the native profile's Manage account screen to show the user's email. The second test signs out with the home's `Sign out` button, which calls `useAuth().signOut()`, and `host.expectSignedOut` waits until the home shows no user and no session. Screenshots `user-button-profile`, `profile`, and `signed-out`. - **Sign-out that never reaches Clerk.** Run `integration/expo-native/bin/control-clerk-expo run native-js-sync/offline-sign-out --platform ios`, and again with `--platform android`. The spec turns off multi-session mode, launches signed in through a ticket, taps `Drop the next sign-out request` (`verify.fault.dropSignOut`), and taps `Sign out`. The app's `fetch` then fails the `DELETE /v1/client/sessions` request as it fails offline, and `verify.fault.droppedSignOuts` counts it. The spec expects the home to show `Signed out`, then signs in as a second user with `signInWithPassword` and expects the home to show that user. Screenshot `signed-in-as-second-user`. +- **Slow native configure.** Run `integration/expo-native/bin/control-clerk-expo run native-js-sync/slow-native-configure --platform ios`, and again with `--platform android`. The signed-in home of a verify launch has a `Slow the next native configure` button (`verify.fault.slowConfigure`). A tap saves a flag in the token cache, and the home then shows `verify.fault.slowConfigureArmed`. On the next launch the test app delays the native module's `configure` by 5 seconds, longer than the 3 seconds `nativeClientSync.ts` waits, and `verify.fault.slowedConfigures` counts the delayed calls. The spec signs in with `signInWithPassword`, arms the delay, relaunches with `keepStorage`, expects the count to read `1`, and expects the same user and the same session ID. Screenshot `signed-in-after-slow-configure`. - **Proof.** `screenshots/signed-out-from-native.png` shows the home with `Signed out` and the `Sign in` button. The native profile closes by itself when the native user goes away. On iOS the native UserButton closes the profile it presented. On Android the UserProfileView dismisses itself, and the UserButton then hides it. ## States a spec cannot reach @@ -41,6 +43,8 @@ Preconditions: - The drop hook is in `integration/templates/expo-native/verify/faults.ts` and runs only in a verify launch. It matches a GET whose path ends in `/v1/client` and nothing else, so tokens, touches, and the foreground app-version check (`GET /v1/`) pass. Arm it only where no other `GET /v1/client` can run before the sign-in, as on the signed-out home right after `host.launch`. +- The slow configure hook wraps `configure` on the `ClerkExpo` native module object in `faults.ts`, which `@clerk/expo` loads too. It reads and clears its flag at startup, so only the launch after the tap is slow. Without the fix, that launch shows `Signed out` while the native SDK is still signed in, and a native sign-in then fails with `session_exists`. + - The `Sign out` row is at the bottom of the profile. On a small simulator it can be below the fold. The devices the CLI leases show it without scrolling. - A seeded password user is created with `bypass_client_trust`, so the password is the only step of the sign-in. - AuthView remembers the last identifier. When it opens a second time in one process the email field is already filled, on iOS and Android, and on iOS `clerk.auth.start.identifier` then matches two nodes. `reachPasswordScreen` in `specs/native.ts` types the email only when the field does not show it. diff --git a/integration/expo-native/specs/features/native-js-sync/slow-native-configure.e2e.ts b/integration/expo-native/specs/features/native-js-sync/slow-native-configure.e2e.ts new file mode 100644 index 00000000000..c379aa7f108 --- /dev/null +++ b/integration/expo-native/specs/features/native-js-sync/slow-native-configure.e2e.ts @@ -0,0 +1,26 @@ +import { test, expect } from '../../fixtures.ts'; +import { signInWithPassword } from '../../native.ts'; + +test('a native sign-in reaches the JS hooks after a relaunch whose native configure is slow', async ({ + host, + screen, + platform, +}) => { + const user = await host.seedUser({ password: true }); + await host.launch(); + await host.tap(host.app.signIn); + await signInWithPassword(host, screen, platform, user); + await host.expectSignedInAs(user, 45_000); + const session = (await host.app.sessionId.textContent()) ?? ''; + await host.tap(screen.getByTestId('verify.fault.slowConfigure')); + await expect(screen.getByTestId('verify.fault.slowConfigureArmed')).toBeVisible(); + + await host.evidence('relaunch while the native SDK takes 5 seconds to configure', async () => { + const slowed = screen.getByTestId('verify.fault.slowedConfigures'); + await host.launch({ keepStorage: true, landsOn: slowed }); + await expect(slowed).toHaveText('1'); + await host.expectSignedInAs(user, 30_000); + await expect(host.app.sessionId).toHaveText(session); + }); + await host.screenshot('signed-in-after-slow-configure'); +}); diff --git a/integration/templates/expo-native/App.tsx b/integration/templates/expo-native/App.tsx index 4f558723e68..a57106acbe9 100644 --- a/integration/templates/expo-native/App.tsx +++ b/integration/templates/expo-native/App.tsx @@ -1,7 +1,7 @@ import { type ReactElement } from 'react'; import { LogBox } from 'react-native'; -import { installFetchFaults } from './verify/faults'; +import { installFetchFaults, installNativeConfigureFault } from './verify/faults'; import { readVerifyLaunch } from './verify/launch'; import { logRequests, VerifyHost } from './verify/VerifyHost'; @@ -10,6 +10,7 @@ const verifyLaunch = readVerifyLaunch(); if (verifyLaunch.runId !== null) { LogBox.ignoreAllLogs(); installFetchFaults(); + installNativeConfigureFault(); } if (verifyLaunch.debugLogging) { logRequests(); diff --git a/integration/templates/expo-native/screens/Home.tsx b/integration/templates/expo-native/screens/Home.tsx index e038194b450..34122849c5f 100644 --- a/integration/templates/expo-native/screens/Home.tsx +++ b/integration/templates/expo-native/screens/Home.tsx @@ -6,9 +6,12 @@ import { Button, Modal, StyleSheet, Text, View } from 'react-native'; import { armClientFetchDrop, armSignOutDrop, + armSlowNativeConfigure, fetchFaultsInstalled, useDroppedClientFetches, useDroppedSignOuts, + useSlowConfigureArmed, + useSlowedNativeConfigures, } from '../verify/faults'; import { AuthLogo } from './AuthLogo'; import { type Destination, homeLinksFor } from './destinations'; @@ -21,6 +24,8 @@ export function Home({ authMode, onOpen }: HomeProps): ReactElement { const { session } = useSession(); const dropped = useDroppedClientFetches(); const droppedSignOuts = useDroppedSignOuts(); + const slowedConfigures = useSlowedNativeConfigures(); + const slowConfigureArmed = useSlowConfigureArmed(); const [authSheet, setAuthSheet] = useState<'closed' | 'plain' | 'withLogo'>('closed'); const closeAuth = (): void => setAuthSheet('closed'); @@ -80,6 +85,21 @@ export function Home({ authMode, onOpen }: HomeProps): ReactElement { onPress={armSignOutDrop} /> )} + {fetchFaultsInstalled() && ( +