Skip to content
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 5 additions & 0 deletions .changeset/expo-wait-for-native-configure.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
'@clerk/expo': minor
---

With native components installed, Clerk now waits for the native SDK to finish starting up before it sends any request, instead of falling back to the app's token cache after 3 seconds. A slow native startup no longer signs the user into a different client than the native views show, but Clerk takes as long to load as the native SDK takes to start. If the native SDK has not started after the app has been open for 10 seconds, Clerk logs an error and keeps waiting. Clerk still uses the app's token cache when the native SDK fails to start.
134 changes: 48 additions & 86 deletions packages/expo/src/provider/__tests__/nativeClientSync.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -180,95 +180,59 @@ describe('createNativeClientSync', () => {
expect(native.configure).toHaveBeenCalledTimes(2);
});

test('uses the app token cache while a slow configure is pending and the native token once it finishes', async () => {
test('waits for a slow configure and reads the native token once it finishes', async () => {
vi.useFakeTimers();
try {
const createNativeClientSync = await loadEngine();
const native = nativeModule();
let finishConfigure!: () => void;
vi.mocked(native.configure).mockReturnValue(new Promise<void>(resolve => (finishConfigure = resolve)));
const cache = userTokenCache(vi.fn().mockResolvedValue('seed-token'));
const getToken = vi.fn().mockResolvedValue('seed-token');
const cache = userTokenCache(getToken);

const sync = createNativeClientSync(native, 'pk_test_123', null, () => cache);
const duringStartup = sync.tokenCache.getToken(CLERK_CLIENT_JWT_KEY);
await vi.advanceTimersByTimeAsync(3_000);

await expect(duringStartup).resolves.toBe('seed-token');
expect(native.getDeviceToken).not.toHaveBeenCalled();
let read: string | null | undefined;
void sync.tokenCache.getToken(CLERK_CLIENT_JWT_KEY).then(token => (read = token));
await vi.advanceTimersByTimeAsync(60_000);

expect(read).toBeUndefined();
expect(getToken).toHaveBeenCalledTimes(1);
finishConfigure();
await vi.advanceTimersByTimeAsync(0);
await expect(sync.tokenCache.getToken(CLERK_CLIENT_JWT_KEY)).resolves.toBe('native-token');
expect(read).toBe('native-token');
expect(native.configure).toHaveBeenCalledTimes(1);
} finally {
vi.useRealTimers();
}
});

test('hands native a token rotated while a slow configure was pending', async () => {
vi.useFakeTimers();
try {
const createNativeClientSync = await loadEngine();
const native = nativeModule();
let nativeToken: string | null = null;
let finishConfigure!: () => void;
vi.mocked(native.configure).mockImplementation(
(_publishableKey, seed) =>
new Promise<void>(resolve => {
finishConfigure = () => {
nativeToken ??= seed;
resolve();
};
}),
);
vi.mocked(native.getDeviceToken).mockImplementation(() => Promise.resolve(nativeToken));
vi.mocked(native.setDeviceToken).mockImplementation((token, expected) => {
const didSet = nativeToken === expected;
if (didSet) {
nativeToken = token;
}
return Promise.resolve(didSet);
});
const cache = storedTokenCache('seed-token');

const sync = createNativeClientSync(native, 'pk_test_123', null, () => cache);
const duringStartup = sync.tokenCache.getToken(CLERK_CLIENT_JWT_KEY);
await vi.advanceTimersByTimeAsync(3_000);
await expect(duringStartup).resolves.toBe('seed-token');
await sync.tokenCache.saveClientToken('signed-in-token', 'seed-token');

finishConfigure();
await vi.advanceTimersByTimeAsync(0);

await expect(sync.tokenCache.getToken(CLERK_CLIENT_JWT_KEY)).resolves.toBe('signed-in-token');
expect(native.setDeviceToken).toHaveBeenCalledWith('signed-in-token', 'seed-token');
expect(native.refreshClient).toHaveBeenCalledTimes(1);
} finally {
vi.useRealTimers();
}
});

test('keeps the native token when native already had its own during a slow configure', async () => {
test('reports a configure that has not settled once the app has been active for the timeout', async () => {
vi.useFakeTimers();
const consoleError = vi.spyOn(console, 'error').mockImplementation(() => undefined);
try {
const createNativeClientSync = await loadEngine();
const { CONFIGURE_TIMEOUT_MS } = await import('../nativeClientSync');
const native = nativeModule();
let finishConfigure!: () => void;
vi.mocked(native.configure).mockReturnValue(new Promise<void>(resolve => (finishConfigure = resolve)));
vi.mocked(native.setDeviceToken).mockResolvedValue(false);
const cache = storedTokenCache('seed-token');
vi.mocked(native.configure).mockReturnValue(new Promise<void>(() => undefined));
mocks.appState.currentState = 'background';

const sync = createNativeClientSync(native, 'pk_test_123', null, () => cache);
const sync = createNativeClientSync(native, 'pk_test_123', null, () => storedTokenCache('seed-token'));
void sync.tokenCache.getToken(CLERK_CLIENT_JWT_KEY);
await vi.advanceTimersByTimeAsync(3_000);
await sync.tokenCache.saveClientToken('signed-in-token', 'seed-token');

finishConfigure();
await vi.advanceTimersByTimeAsync(0);

await expect(sync.tokenCache.getToken(CLERK_CLIENT_JWT_KEY)).resolves.toBe('native-token');
expect(native.refreshClient).not.toHaveBeenCalled();
await vi.advanceTimersByTimeAsync(10 * CONFIGURE_TIMEOUT_MS);
expect(consoleError).not.toHaveBeenCalled();

mocks.appState.currentState = 'active';
mocks.listeners.forEach(listener => listener('active'));
await vi.advanceTimersByTimeAsync(CONFIGURE_TIMEOUT_MS - 1);
expect(consoleError).not.toHaveBeenCalled();
await vi.advanceTimersByTimeAsync(1);

expect(consoleError).toHaveBeenCalledTimes(1);
expect(consoleError).toHaveBeenCalledWith(
expect.objectContaining({ message: expect.stringContaining('has not finished configuring') }),
);
} finally {
consoleError.mockRestore();
vi.useRealTimers();
}
});
Expand Down Expand Up @@ -451,10 +415,9 @@ describe('createNativeClientSync', () => {
createNativeClientSync(native, 'pk_test_123', null, () => clearableTokenCache(signedIn).cache).attach(clerk);

const signOut = expect(clerk.signOut?.()).rejects.toThrow('Network request failed');
await vi.advanceTimersByTimeAsync(3_000);
await signOut;
await vi.advanceTimersByTimeAsync(60_000);
finishConfigure();
await vi.advanceTimersByTimeAsync(0);
await signOut;

await expect(native.getDeviceToken()).resolves.toBeNull();
} finally {
Expand All @@ -463,26 +426,25 @@ describe('createNativeClientSync', () => {
});

test('keeps a save that waited on a failed configure out of the app token cache after a failed sign-out', async () => {
vi.useFakeTimers();
try {
const createNativeClientSync = await loadEngine();
const signedIn = clientToken('client_signed_in', 1);
const native = nativeModule();
vi.mocked(native.configure).mockReturnValue(new Promise<void>(() => undefined));
const { cache, stored } = clearableTokenCache(signedIn);
const clerk = clerkWithFailingSignOut('client_signed_in');
const sync = createNativeClientSync(native, 'pk_test_123', null, () => cache);
sync.attach(clerk);
const createNativeClientSync = await loadEngine();
const signedIn = clientToken('client_signed_in', 1);
const native = nativeModule();
let failConfigure!: () => void;
vi.mocked(native.configure).mockReturnValue(
new Promise<void>((_, reject) => (failConfigure = () => reject(new Error('native configure failed')))),
);
const { cache, stored } = clearableTokenCache(signedIn);
const clerk = clerkWithFailingSignOut('client_signed_in');
const sync = createNativeClientSync(native, 'pk_test_123', null, () => cache);
sync.attach(clerk);

const save = sync.tokenCache.saveClientToken(clientToken('client_signed_in', 2), signedIn);
const signOut = expect(clerk.signOut?.()).rejects.toThrow('Network request failed');
await vi.advanceTimersByTimeAsync(3_000);
await Promise.all([save, signOut]);
const save = sync.tokenCache.saveClientToken(clientToken('client_signed_in', 2), signedIn);
const signOut = expect(clerk.signOut?.()).rejects.toThrow('Network request failed');
await vi.waitFor(() => expect(stored.has(CLERK_CLIENT_JWT_KEY)).toBe(false));
failConfigure();
await Promise.all([save, signOut]);

expect(stored.get(CLERK_CLIENT_JWT_KEY)).toBeUndefined();
} finally {
vi.useRealTimers();
}
expect(stored.get(CLERK_CLIENT_JWT_KEY)).toBeUndefined();
});

test('keeps refusing an earlier signed-out client after a later failed sign-out of another client', async () => {
Expand Down
Loading
Loading