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/fakeClerk.ts b/packages/expo/src/provider/__tests__/nativeClientSyncBehavior/fakeClerk.ts index 4c3afba3f59..cfab520f98c 100644 --- a/packages/expo/src/provider/__tests__/nativeClientSyncBehavior/fakeClerk.ts +++ b/packages/expo/src/provider/__tests__/nativeClientSyncBehavior/fakeClerk.ts @@ -1,6 +1,6 @@ import type { FakeClerkServer, FakeServerClientJSON, FapiResponse } from './fakeServer'; -type FakeRequestInit = { url: URL; headers: Headers }; +type FakeRequestInit = { url: URL; headers: Headers; signal?: AbortSignal }; type BeforeRequestHook = (requestInit: FakeRequestInit) => unknown; type FakePayload = { client?: FakeServerClientJSON | null; response?: FakeServerClientJSON | null }; type AfterResponseHook = ( @@ -54,8 +54,12 @@ export class FakeClientResource { return this.sessions.filter(session => session.status === 'active'); } - fetch = async (_options?: { fetchMaxTries?: number }): Promise => { - const response = await this.clerk.fapi(token => this.clerk.server.getClient('js', token), 'response'); + fetch = async (options?: { fetchMaxTries?: number; abortSignal?: AbortSignal }): Promise => { + const response = await this.clerk.fapi( + token => this.clerk.server.getClient('js', token), + 'response', + options?.abortSignal, + ); return this.fromJSON(response.client); }; @@ -114,8 +118,9 @@ export class FakeClerk { async fapi( request: (token: string | null) => Promise, clientField: 'client' | 'response' = 'client', + signal?: AbortSignal, ): Promise { - const requestInit = await this.#prepareRequest(); + const requestInit = await this.#prepareRequest(signal); const response = await request(requestInit.headers.get('authorization') || null); const headers = new Headers(response.token ? { authorization: response.token } : {}); const payload: FakePayload = { [clientField]: response.client }; @@ -130,8 +135,8 @@ export class FakeClerk { return requestInit.headers.get('authorization') || null; } - async #prepareRequest(): Promise { - const requestInit = { url: new URL('https://fapi.clerk.test/v1/client'), headers: new Headers() }; + async #prepareRequest(signal?: AbortSignal): Promise { + const requestInit = { url: new URL('https://fapi.clerk.test/v1/client'), headers: new Headers(), signal }; for (const hook of this.#beforeRequestHooks) { await hook(requestInit); } diff --git a/packages/expo/src/provider/__tests__/nativeClientSyncBehavior/fakeNativeClerk.ts b/packages/expo/src/provider/__tests__/nativeClientSyncBehavior/fakeNativeClerk.ts index 8afede7a344..1dd25210dbe 100644 --- a/packages/expo/src/provider/__tests__/nativeClientSyncBehavior/fakeNativeClerk.ts +++ b/packages/expo/src/provider/__tests__/nativeClientSyncBehavior/fakeNativeClerk.ts @@ -24,6 +24,8 @@ export class FakeNativeClerk { client: FakeServerClientJSON | null = null; isConfigured = false; clientRefreshCount = 0; + deviceTokenWritesFail = false; + deviceTokenReadFailures = 0; #listeners = new Set(); #heldChanges: Array<[NativeClientChange, NativeChangeOrigin]> | null = null; #startupGate: Promise | null = null; @@ -142,6 +144,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 b576a531425..12aa8e0cb36 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) }; } + createClientForMissingToken = false; + omitUnrotatedTokenOnReadAndTouch = 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 }; @@ -123,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, @@ -141,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/harness.ts b/packages/expo/src/provider/__tests__/nativeClientSyncBehavior/harness.ts index 05a95bbaf16..a7d0f0f3fe9 100644 --- a/packages/expo/src/provider/__tests__/nativeClientSyncBehavior/harness.ts +++ b/packages/expo/src/provider/__tests__/nativeClientSyncBehavior/harness.ts @@ -16,6 +16,8 @@ export type NativeSyncScenario = { /** The native SDK fails to configure, e.g. a native build that cannot initialize Clerk. */ failNativeConfigure?: boolean; delayNativeStartup?: boolean; + delayNativeConfigure?: boolean; + skipInitialLoad?: boolean; strictMode?: boolean; }; @@ -33,6 +35,8 @@ export type NativeSyncHarness = { run: (action: () => T | Promise) => Promise; settle: () => Promise; releaseNativeStartup: () => void; + releaseNativeConfigure: () => void; + remount: () => 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..6fe8cd96cea 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,37 @@ afterEach(() => { vi.useRealTimers(); }); +async function outlastConfigureTimeout(h: NativeSyncHarness): Promise { + await h.run(() => vi.advanceTimersByTimeAsync(CONFIGURE_TIMEOUT_MS + 500)); +} + +async function bootOnCachedClientWhileNativeConfigures(cachedUsers: string[]) { + const { server, ...native } = seedDevice(['user_1']); + const cached = server.seedClient({ users: cachedUsers }); + const h = await start({ + server, + nativeDeviceToken: native.token, + jsDeviceToken: cached.token, + delayNativeConfigure: true, + skipInitialLoad: true, + }); + h.native.restoreClientFromKeychain(server.inspectClient(native.token)); + await outlastConfigureTimeout(h); + return { h, cached, native }; +} + +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)); } @@ -98,6 +130,46 @@ 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 }) }; @@ -193,6 +265,24 @@ describe('native client sync behavior', () => { expect(h.server.requestCount('js', 'POST /client/sessions/:id/touch')).toBe(0); }); + it('keeps the device token a native pull rotated when ClerkProvider unmounts before the pull lands', async () => { + const { server, token, clientId } = seedDevice(['user_1']); + const h = await start({ server, jsDeviceToken: token, nativeDeviceToken: token }); + vi.useFakeTimers(); + server.rotateTokenOnNextResponse(token); + const held = server.holdNextResponse('js', 'GET /client'); + await whileTimersRun(h, () => h.native.emitChange({ client: true, deviceToken: false }, { kind: 'native' })); + await whileTimersRun(h, () => held.handled); + + h.unmount(); + harness = undefined; + held.release(); + await vi.advanceTimersByTimeAsync(10_000); + + expect(h.native.token).not.toBe(token); + expect(server.clientIdForToken(h.native.token)).toBe(clientId); + }); + it('does not retry a JS refetch of a native sign-in that the server rejected', async () => { const h = await start(); vi.useFakeTimers({ shouldAdvanceTime: true }); @@ -292,6 +382,106 @@ describe('native client sync behavior', () => { await expectConverged(h); }); + it('does not reactivate the session JS signed out of when a native pull sent before the sign-out lands after it', async () => { + const { server, token, sessionIds } = seedDevice(['user_1', 'user_2'], 'user_1'); + const h = await start({ server, jsDeviceToken: token, nativeDeviceToken: token }); + vi.useFakeTimers(); + const held = server.holdNextResponse('js', 'GET /client'); + await whileTimersRun(h, () => h.native.emitChange({ client: true, deviceToken: false }, { kind: 'native' })); + await whileTimersRun(h, () => held.handled); + + await whileTimersRun(h, () => h.js.signOut({ sessionId: sessionIds.user_1 })); + expect(h.js.session).toBeNull(); + const emissionIndex = h.js.emissions.length; + held.release(); + await skipRetryBackoff(h); + + expect(h.js.emissions.slice(emissionIndex).filter(emission => emission.sessionId === sessionIds.user_1)).toEqual( + [], + ); + expect(h.js.session?.id).not.toBe(sessionIds.user_1); + }); + + it('signs JS in on the native session when the app returns to the foreground after failing to sign out an inactive session', async () => { + const { server, token, sessionIds } = seedDevice(['user_1', 'user_2'], 'user_1'); + const h = await start({ server, jsDeviceToken: token, nativeDeviceToken: token }); + vi.useFakeTimers(); + server.failNextRequests('js', 'GET /client', 3); + await whileTimersRun(h, () => h.native.setActiveSession(sessionIds.user_2)); + await skipRetryBackoff(h); + expect(h.js.session?.id).toBe(sessionIds.user_1); + + server.failNextRequests('js', 'POST /client/sessions/:id/remove'); + await whileTimersRun(h, () => h.js.signOut({ sessionId: sessionIds.user_2 }).catch(() => undefined)); + expect(h.js.session?.id).toBe(sessionIds.user_1); + await returnToForeground(h); + await skipRetryBackoff(h); + + expect(h.js.session?.id).toBe(sessionIds.user_2); + expect(h.native.activeSessionId).toBe(sessionIds.user_2); + }); + + it('signs JS out when ClerkProvider remounts while JS is fetching a native sign-out', async () => { + const { server, token, sessionIds } = seedDevice(['user_1']); + const h = await start({ server, jsDeviceToken: token, nativeDeviceToken: token }); + expect(h.js.session?.id).toBe(sessionIds.user_1); + vi.useFakeTimers(); + const held = server.holdNextResponse('js', 'GET /client'); + await whileTimersRun(h, () => h.native.signOut()); + await whileTimersRun(h, () => held.handled); + + await h.run(() => h.remount()); + held.release(); + await skipRetryBackoff(h); + + expect(h.js.session).toBeNull(); + expect(h.js.client?.signedInSessions).toEqual([]); + }); + + it('signs JS out on the next foreground when a pull from before a ClerkProvider remount lands after the new pull failed', async () => { + const { server, token, sessionIds } = seedDevice(['user_1', 'user_2'], 'user_1'); + const h = await start({ server, jsDeviceToken: token, nativeDeviceToken: token }); + vi.useFakeTimers(); + const held = server.holdNextResponse('js', 'POST /client/sessions/:id/touch'); + await whileTimersRun(h, () => h.native.setActiveSession(sessionIds.user_2)); + await whileTimersRun(h, () => held.handled); + + await h.run(() => h.remount()); + await skipRetryBackoff(h); + server.failNextRequests('js', 'GET /client', 3); + await whileTimersRun(h, () => h.native.signOut()); + await skipRetryBackoff(h); + held.release(); + await skipRetryBackoff(h); + await returnToForeground(h); + await skipRetryBackoff(h); + + expect(h.js.session).toBeNull(); + }); + + it('does not reactivate the session JS failed to sign out of when ClerkProvider remounts while JS was fetching a native change', async () => { + const { server, token, sessionIds } = seedDevice(['user_1', 'user_2'], 'user_1'); + const h = await start({ server, jsDeviceToken: token, nativeDeviceToken: token }); + vi.useFakeTimers(); + const held = server.holdNextResponse('js', 'GET /client'); + await whileTimersRun(h, () => h.native.emitChange({ client: true, deviceToken: false }, { kind: 'native' })); + await whileTimersRun(h, () => held.handled); + server.failNextRequests('js', 'POST /client/sessions/:id/remove'); + h.native.failNextClientRefresh(new Error('The network connection was lost.')); + await whileTimersRun(h, () => h.js.signOut({ sessionId: sessionIds.user_1 }).catch(() => undefined)); + expect(h.js.session).toBeNull(); + const emissionIndex = h.js.emissions.length; + + await h.run(() => h.remount()); + held.release(); + await skipRetryBackoff(h); + + expect(h.js.emissions.slice(emissionIndex).filter(emission => emission.sessionId === sessionIds.user_1)).toEqual( + [], + ); + expect(h.js.session).toBeNull(); + }); + it('signs JS out when native signs out of the only session', async () => { const { server, token } = seedDevice(['user_1']); const h = await start({ server, jsDeviceToken: token, nativeDeviceToken: token }); @@ -595,6 +785,25 @@ describe('native client sync behavior', () => { expect(h.native.token).toBeNull(); }); + 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()); + await skipRetryBackoff(h); + 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); + + h.server.failNextRequests('js', 'DELETE /client/sessions'); + await whileTimersRun(h, () => h.js.signOut().catch(() => undefined)); + expect(h.js.session).toBeNull(); + held.release(); + await skipRetryBackoff(h); + + expect(h.js.client?.id).toBe(cached.clientId); + expect(h.js.client?.signedInSessions.map(session => session.id)).not.toContain(native.sessionIds.user_1); + }); + it('keeps the next sign-in when a client fetch sent before the sign-out lands afterwards', async () => { const { server, token } = seedDevice(['user_1']); const h = await start({ server, jsDeviceToken: token, nativeDeviceToken: token }); @@ -717,6 +926,320 @@ 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, + skipInitialLoad: true, + }); + h.native.restoreClientFromKeychain(server.inspectClient(token)); + + await outlastConfigureTimeout(h); + 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('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, + skipInitialLoad: true, + }); + h.native.restoreClientFromKeychain(server.inspectClient(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(); + await h.run(() => h.releaseNativeConfigure()); + await skipRetryBackoff(h); + + expect(h.js.client?.id).toBe(cached.clientId); + 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(); + 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('keeps a JS sign-in made while native holds a signed-out client and is still configuring', 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()); + await skipRetryBackoff(h); + expect(h.js.session).toBeNull(); + + 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('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('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(); + }); + 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..6f458734288 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,22 +54,26 @@ 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'); + 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) => { calls.push('setDeviceToken'); - if (native.token !== expected) { + if (native.deviceTokenWritesFail || native.token !== expected) { return false; } await notifyIfChanged(() => { @@ -101,6 +105,12 @@ export const renderWithNativeSync: RenderWithNativeSync = async (scenario = {}) : null; const releaseNativeStartup = scenario.delayNativeStartup ? native.delayStartup() : () => undefined; const nativeModuleCalls: string[] = []; + let releaseNativeConfigure: () => 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 +123,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'); @@ -123,7 +136,8 @@ export const renderWithNativeSync: RenderWithNativeSync = async (scenario = {}) tokenCache={persistentTokenCache ?? undefined} /> ); - const view = render(scenario.strictMode ? {provider} : provider); + const element = scenario.strictMode ? {provider} : provider; + let view = render(element); const settle = async () => { for (let round = 0; round < 8; round++) { @@ -133,12 +147,14 @@ export const renderWithNativeSync: RenderWithNativeSync = async (scenario = {}) } }; - await waitFor(() => { - if (!js.loaded) { - throw new Error('Clerk has not loaded yet'); - } - }); - await settle(); + if (!scenario.skipInitialLoad) { + await waitFor(() => { + if (!js.loaded) { + throw new Error('Clerk has not loaded yet'); + } + }); + await settle(); + } const harness: NativeSyncHarness = { server, @@ -156,6 +172,11 @@ export const renderWithNativeSync: RenderWithNativeSync = async (scenario = {}) }, settle, releaseNativeStartup, + releaseNativeConfigure: () => releaseNativeConfigure(), + remount: () => { + view.unmount(); + view = render(element); + }, unmount: () => view.unmount(), }; return harness; diff --git a/packages/expo/src/provider/nativeClientSync.ts b/packages/expo/src/provider/nativeClientSync.ts index 22609c4de9c..86053201d79 100644 --- a/packages/expo/src/provider/nativeClientSync.ts +++ b/packages/expo/src/provider/nativeClientSync.ts @@ -10,10 +10,12 @@ 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 }; +type FetchableClient = ClientResource & { + fetch?: (options?: { fetchMaxTries?: number; abortSignal?: AbortSignal }) => Promise; +}; export type SyncableClerk = { addListener: (listener: () => void) => () => void; @@ -31,6 +33,7 @@ export type SyncableClerk = { export type ClientTokenCache = TokenCache & { saveClientToken: (token: string, requestToken: string | null) => Promise; isDiscardedClient: (clientId: string) => boolean; + isStaleRequest: (signal: AbortSignal) => boolean; }; type SingleFlight = { run: () => Promise; current: () => Promise | null }; @@ -44,6 +47,9 @@ let configuration: { settled: () => Promise; } | null = null; +const pullRequests = new WeakMap boolean>(); +let needsRepair = false; + function warn(message: string, error?: unknown): void { if (__DEV__) { console.warn(`Clerk: ${message}`, error); @@ -141,6 +147,7 @@ function configureOnce( updateRequiredViewEnabled: boolean, ) { if (configuration?.publishableKey !== publishableKey || configuration.proxyUrl !== proxyUrl) { + needsRepair = false; let configured = false; let timedOut = false; const configuring = (async () => { @@ -198,6 +205,8 @@ export function createNativeClientSync( const fallback = () => getUserTokenCache() ?? MemoryTokenCache; const ready = () => configureOnce(native, publishableKey, proxyUrl, fallback(), getNativeUpdateRequiredViewEnabled()); let mirroredToken: string | null = null; + let usedFallbackTokenCache = false; + let signedOutInJs = false; const discardedClientIds = new Set(); let lastFingerprint: string | undefined; @@ -237,22 +246,38 @@ 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); } - return native.getDeviceToken().catch(error => { - warn('Failed to read the native device token.', error); + if (!(await ready())) { + 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 || !(await ready())) { + if (key !== CLERK_CLIENT_JWT_KEY) { + return fallback().saveToken(key, token); + } + if (!(await ready())) { + usedFallbackTokenCache = true; return fallback().saveToken(key, token); } await tokenCache.saveClientToken(token, await native.getDeviceToken().catch(() => null)); }, clearToken: key => fallback().clearToken?.(key), isDiscardedClient: clientId => discardedClientIds.has(clientId), + isStaleRequest: signal => pullRequests.get(signal)?.() === false, saveClientToken: async (token, requestToken) => { if (isDiscarded(token)) { return; @@ -262,6 +287,7 @@ export function createNativeClientSync( return; } if (!isReady) { + usedFallbackTokenCache = true; return fallback().saveToken(CLERK_CLIENT_JWT_KEY, token); } if (token === requestToken && token === mirroredToken) { @@ -320,15 +346,19 @@ 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 }); + const abortSignal = new AbortController().signal; + pullRequests.set(abortSignal, isCurrent); + let fetched = await client.fetch({ fetchMaxTries: 1, abortSignal }); const sharedClientId = clientIdOf(await native.getDeviceToken().catch(() => null)); if (sharedClientId && fetched.id && fetched.id !== sharedClientId) { - fetched = await client.fetch({ fetchMaxTries: 1 }); + fetched = await client.fetch({ fetchMaxTries: 1, abortSignal }); + } + if (isCurrent()) { + clerk.updateClient(fetched); } - clerk.updateClient(fetched); } else { await clerk.__internal_reloadInitialResources?.(); } @@ -347,28 +377,36 @@ export function createNativeClientSync( }; let attached = true; - let needsRepair = false; + let jsSignOuts = 0; + let signOutsAtPull = 0; + const isCurrent = () => attached && jsSignOuts === signOutsAtPull; const fromNative = singleFlight(async () => { + signOutsAtPull = jsSignOuts; 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; + if (isCurrent()) { + needsRepair = false; + } } catch (error) { + if (!isCurrent()) { + return; + } needsRepair = true; throw error; } @@ -378,6 +416,38 @@ 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); @@ -453,6 +523,11 @@ 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; + if (signsOutEverySession || options?.sessionId === clerk.session?.id) { + signedOutInJs = true; + jsSignOuts += 1; + needsRepair = false; + } let failure: { error: unknown } | null = null; try { await originalSignOut(...args); @@ -477,17 +552,27 @@ 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) { pullInBackground(); } }); + if (needsRepair) { + pullInBackground(); + } return () => { + if (fromNative.current() && isCurrent()) { + needsRepair = true; + } attached = false; removeClerkListener(); subscription?.remove(); diff --git a/packages/expo/src/provider/singleton/createClerkInstance.ts b/packages/expo/src/provider/singleton/createClerkInstance.ts index b82430dfbb3..e5b1719fc70 100644 --- a/packages/expo/src/provider/singleton/createClerkInstance.ts +++ b/packages/expo/src/provider/singleton/createClerkInstance.ts @@ -162,6 +162,12 @@ export function createClerkInstance(ClerkClass: typeof Clerk) { throw new Error('Clerk: Ignored a response for a client that was signed out.'); } }; + const dropStaleResponse = (requestInit: FapiRequestInit) => { + const tokenCache = __internal_tokenCache as TokenCache & Partial; + if (requestInit.signal && tokenCache.isStaleRequest?.(requestInit.signal)) { + throw new Error('Clerk: Ignored a stale client response.'); + } + }; const requestTokens = new WeakMap(); const appVersionRequestHooks = isNative() ? createAppVersionRequestHooks() : null; @@ -368,6 +374,7 @@ export function createClerkInstance(ClerkClass: typeof Clerk) { ); nativeApiErrorShown = true; } + dropStaleResponse(requestInit); }); }