Skip to content
Open
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-background-launch-offline-native-signout.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
'@clerk/expo': patch
---

Fix two startup issues with native components. When the app launches in the background before the keychain can be read, the JS SDK now waits for the app to open instead of starting from a stale cached token. When the JS SDK sees a native sign-out that never reached Clerk, it now clears its cached token, so the next launch doesn't sign the user back in.
Original file line number Diff line number Diff line change
Expand Up @@ -50,7 +50,11 @@ export class FakePersistentTokenCache implements TokenCache {
return this.#values.get(key) ?? null;
}

getToken = (key: string): Promise<string | undefined | null> => Promise.resolve(this.#values.get(key) ?? null);
/** The keychain is unreadable, as during an iOS background launch before the first unlock. */
locked = false;

getToken = (key: string): Promise<string | undefined | null> =>
this.locked ? Promise.reject(new Error('The keychain is locked.')) : Promise.resolve(this.#values.get(key) ?? null);

saveToken = (key: string, token: string): Promise<void> => {
this.#values.set(key, token);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -133,6 +133,13 @@ export class FakeNativeClerk {
await this.#observe(() => this.server.removeAllSessions('native', this.token));
}

/** Native signs out on the device after the sign-out request failed, so the server session stays active. */
signOutOnDevice(): void {
this.token = null;
this.client = null;
this.emitChange({ client: true, deviceToken: true }, { kind: 'native' });
}

async refresh(): Promise<void> {
await this.#observe(() => this.server.getClient('native', this.token));
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,8 @@ export type NativeSyncScenario = {
*/
jsDeviceToken?: string | null;
persistentTokenCache?: boolean;
/** The app token cache cannot be read until the test unlocks it. */
lockedTokenCache?: boolean;
nativeDeviceToken?: string | null;
nativeModule?: 'present' | 'absent';
/** The native SDK fails to configure, e.g. a native build that cannot initialize Clerk. */
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -49,7 +49,8 @@ vi.mock('expo-secure-store', () => ({
setItemAsync: vi.fn(),
}));

vi.mock('../../../utils/runtime', () => ({
vi.mock('../../../utils/runtime', async importOriginal => ({
...(await importOriginal<typeof import('../../../utils/runtime')>()),
isExpoGo: () => false,
isNative: () => true,
isWeb: () => false,
Expand Down Expand Up @@ -699,6 +700,33 @@ describe('native client sync behavior', () => {
});

describe('sign-out that never reaches the server', () => {
it('keeps a native sign-out that never reached Clerk on the next launch', async () => {
const server = new FakeClerkServer();
const previousLaunch = await start({ server, persistentTokenCache: true });
const sessionId = await previousLaunch.run(() => previousLaunch.native.signIn('user_1'));
await waitFor(() => expect(previousLaunch.js.session?.id).toBe(sessionId));
await previousLaunch.settle();

vi.useFakeTimers();
server.failNextRequests('js', 'GET /client', 3);
await whileTimersRun(previousLaunch, () => previousLaunch.native.signOutOnDevice());
await skipRetryBackoff(previousLaunch);
const cachedToken = previousLaunch.persistentTokenCache?.read(CLERK_CLIENT_JWT_KEY) ?? null;
previousLaunch.unmount();
vi.useRealTimers();

const h = await start({
server,
nativeDeviceToken: null,
jsDeviceToken: cachedToken,
persistentTokenCache: true,
});
await h.settle();

expect(h.native.token).toBeNull();
expect(h.js.session).toBeNull();
});

it('lets another user sign in on a single-session instance', async () => {
const { server, token } = seedDevice(['user_1']);
server.singleSessionMode = true;
Expand Down Expand Up @@ -913,6 +941,38 @@ describe('native client sync behavior', () => {
expect(h.nativeModuleCalls.filter(call => call !== 'configure' && call !== 'addListener')).toEqual([]);
});

it('waits for the app to open before falling back to the app token cache after a background launch with a locked keychain', async () => {
const { server, token, sessionIds } = seedDevice(['user_1']);
const stale = server.seedClient();
appState.currentState = 'background';
vi.useFakeTimers();
const h = await start({
server,
nativeDeviceToken: token,
jsDeviceToken: stale.token,
lockedTokenCache: true,
skipInitialLoad: true,
});

h.persistentTokenCache!.locked = false;
await outlastConfigureTimeout(h);
await h.run(() => appState.moveTo('active'));
await skipRetryBackoff(h);

expect(server.requests.filter(request => request.caller === 'js' && request.token === stale.token)).toEqual([]);
expect(h.js.session?.id).toBe(sessionIds.user_1);
});

it('keeps JS on the shared client while reads of the native device token fail', async () => {
const { server, token, sessionIds } = seedDevice(['user_1']);
const h = await start({ server, jsDeviceToken: token, nativeDeviceToken: token, skipInitialLoad: true });
failNativeReads(h, [1, 2, 3, 4, 5, 6, 7, 8]);
await h.settle();

expect(h.persistentTokenCache?.read(CLERK_CLIENT_JWT_KEY)).toBe(token);
expect(h.js.session?.id).toBe(sessionIds.user_1);
});

it('mirrors the shared device token into the app token cache', async () => {
const server = new FakeClerkServer();
const stale = server.seedClient();
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -103,6 +103,9 @@ export const renderWithNativeSync: RenderWithNativeSync = async (scenario = {})
scenario.persistentTokenCache || scenario.jsDeviceToken !== undefined
? new FakePersistentTokenCache(scenario.jsDeviceToken ? { [CLERK_CLIENT_JWT_KEY]: scenario.jsDeviceToken } : {})
: null;
if (persistentTokenCache && scenario.lockedTokenCache) {
persistentTokenCache.locked = true;
}
const releaseNativeStartup = scenario.delayNativeStartup ? native.delayStartup() : () => undefined;
const nativeModuleCalls: string[] = [];
let releaseNativeConfigure: () => void = () => {};
Expand Down
61 changes: 39 additions & 22 deletions packages/expo/src/provider/nativeClientSync.ts
Original file line number Diff line number Diff line change
Expand Up @@ -150,8 +150,9 @@ function configureOnce(
needsRepair = false;
let configured = false;
let timedOut = false;
const seeding = readSeedDeviceToken(tokenCache);
const configuring = (async () => {
const seed = await readSeedDeviceToken(tokenCache);
const seed = await seeding;
await native
.setUpdateRequiredViewEnabled?.(updateRequiredViewEnabled)
.catch(error => warn('Failed to set whether the native SDK shows its update screen.', error));
Expand All @@ -167,14 +168,16 @@ function configureOnce(
})().catch(error => {
warn('Native client sync is disabled because the native Clerk SDK failed to configure.', error);
});
const startup = withTimeout(
configuring,
CONFIGURE_TIMEOUT_MS,
() => new Error('Timed out configuring the native Clerk SDK.'),
).catch(error => {
timedOut = true;
warn('Native client sync is waiting for the native Clerk SDK to configure.', error);
});
// A background launch can wait for the app to open before the keychain is readable.
const startup = seeding
.catch(noop)
.then(() =>
withTimeout(configuring, CONFIGURE_TIMEOUT_MS, () => new Error('Timed out configuring the native Clerk SDK.')),
)
.catch(error => {
timedOut = true;
warn('Native client sync is waiting for the native Clerk SDK to configure.', error);
});
configuration = {
publishableKey,
proxyUrl,
Expand Down Expand Up @@ -204,7 +207,7 @@ export function createNativeClientSync(
) {
const fallback = () => getUserTokenCache() ?? MemoryTokenCache;
const ready = () => configureOnce(native, publishableKey, proxyUrl, fallback(), getNativeUpdateRequiredViewEnabled());
let mirroredToken: string | null = null;
let mirroredToken: string | null | undefined;
let usedFallbackTokenCache = false;
let signedOutInJs = false;
const discardedClientIds = new Set<string>();
Expand All @@ -215,11 +218,28 @@ export function createNativeClientSync(
return !!clientId && discardedClientIds.has(clientId);
};

let cacheWrites: Promise<void> = Promise.resolve();
const writeCachedToken = (token: string | null) => {
const cache = fallback();
const write = cacheWrites.then(async () => {
if (token) {
await cache.saveToken(CLERK_CLIENT_JWT_KEY, token);
} else if (cache.clearToken) {
await cache.clearToken(CLERK_CLIENT_JWT_KEY);
} else {
await cache.saveToken(CLERK_CLIENT_JWT_KEY, '');
}
});
cacheWrites = write.catch(noop);
return write;
};

const mirror = (token: string | null) => {
if (token && token !== mirroredToken && !isDiscarded(token)) {
mirroredToken = token;
void Promise.resolve(fallback().saveToken(CLERK_CLIENT_JWT_KEY, token)).catch(noop);
if (token === mirroredToken || isDiscarded(token)) {
return;
}
mirroredToken = token;
void writeCachedToken(token).catch(noop);
};

const setDeviceToken = (token: string | null, expected: string | null) =>
Expand Down Expand Up @@ -297,9 +317,11 @@ export function createNativeClientSync(
mirror(token);
return;
}
const current = await native.getDeviceToken().catch(() => null);
const didReclaim = token !== requestToken && (await reclaimRotatedToken(token, requestToken, current));
mirror(didReclaim ? token : current);
const current = await native.getDeviceToken().catch(() => undefined);
const didReclaim = token !== requestToken && (await reclaimRotatedToken(token, requestToken, current ?? null));
if (didReclaim || current !== undefined) {
mirror(didReclaim ? token : (current ?? null));
}
if (didReclaim) {
void native.refreshClient().catch(error => warn('Failed to refresh the native client.', error));
}
Expand All @@ -326,12 +348,7 @@ export function createNativeClientSync(
discardedClientIds.add(clientId);
}
mirroredToken = null;
const cache = fallback();
await Promise.resolve()
.then(() =>
cache.clearToken ? cache.clearToken(CLERK_CLIENT_JWT_KEY) : cache.saveToken(CLERK_CLIENT_JWT_KEY, ''),
)
.catch(error => warn('Failed to clear the cached device token.', error));
await writeCachedToken(null).catch(error => warn('Failed to clear the cached device token.', error));
if (await ready()) {
await clearNativeDeviceToken(clientId);
return;
Expand Down
Loading