Skip to content
Merged
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
9 changes: 9 additions & 0 deletions .changeset/expo-android-restore-credentials.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
---
'@clerk/expo-native-components': minor
---

Add an `enableRestoreCredentials` prop to `AuthView` that turns on [Restore Credentials](https://developer.android.com/identity/sign-in/restore-credentials) on Android, so users stay signed in when they move to a new device. It is off by default and ignored on iOS. When it is on, on the first launch after the app is installed or restored onto a device, a signed-out `AuthView` in `signIn` or `signInOrUp` mode silently signs the user in with the restore credential transferred from their old device. Later launches don't try again. After a sign-in or sign-up, it creates a restore credential for the signed-in user in the background, replacing the one this device created for that user before; a device holds one restore credential, for the user who most recently signed in. Passkeys must be enabled as a first factor for your Clerk instance. On Android, whether or not the prop is set, the device's restore credential is deleted on a best-effort basis when a signed-in user signs out (including from JavaScript), is revoked, or times out from inactivity. A session that reaches its maximum lifetime keeps the credential.

```tsx
<AuthView enableRestoreCredentials />
```
Original file line number Diff line number Diff line change
Expand Up @@ -52,6 +52,7 @@ class ClerkAuthNativeView(context: Context, appContext: AppContext) : ClerkCompo
val logoView: View?
get() = logoViewState
var hostBackButton: Boolean by mutableStateOf(false)
var enableRestoreCredentials: Boolean by mutableStateOf(false)

private var logoWidth by mutableIntStateOf(0)
private var logoHeight by mutableIntStateOf(0)
Expand Down Expand Up @@ -128,6 +129,7 @@ class ClerkAuthNativeView(context: Context, appContext: AppContext) : ClerkCompo
mode = authMode(mode),
preferredEmailStrategy = emailStrategy(preferredEmailStrategy),
isDismissible = isDismissible,
enableRestoreCredentials = enableRestoreCredentials,
Comment thread
swolfand marked this conversation as resolved.
Resolved
onDismiss = ::sendDismissEvent,
onAuthComplete = {
sendDismissEvent()
Expand Down Expand Up @@ -247,6 +249,10 @@ class ClerkAuthViewModule : Module() {
view.hostBackButton = hostBackButton
}

Prop("enableRestoreCredentials") { view: ClerkAuthNativeView, enableRestoreCredentials: Boolean? ->
view.enableRestoreCredentials = enableRestoreCredentials ?: false
}

OnViewDidUpdateProps { view: ClerkAuthNativeView ->
view.setupView()
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,7 @@ import expo.modules.kotlin.Promise
import expo.modules.kotlin.modules.Module
import expo.modules.kotlin.modules.ModuleDefinition
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.CoroutineStart
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.Job
import kotlinx.coroutines.flow.combine
Expand Down Expand Up @@ -48,6 +49,7 @@ class ClerkExpoModule : Module() {
private var configuredPublishableKey: String? = null
private val mainHandler = Handler(Looper.getMainLooper())
private var clientInvalidationObserverJob: Job? = null
private var restoreCredentialSignOutObserverJob: Job? = null
private val clientInvalidationTracker = ClerkClientInvalidationTracker(
schedule = { flush -> mainHandler.post(flush) },
emit = { sendEvent(NATIVE_CLIENT_INVALIDATED_EVENT, emptyMap<String, Any?>()) }
Expand Down Expand Up @@ -76,6 +78,8 @@ class ClerkExpoModule : Module() {
authFlowStateObserverJob = null
clientInvalidationObserverJob?.cancel()
clientInvalidationObserverJob = null
restoreCredentialSignOutObserverJob?.cancel()
restoreCredentialSignOutObserverJob = null
mainHandler.removeCallbacksAndMessages(null)
}

Expand Down Expand Up @@ -187,6 +191,7 @@ class ClerkExpoModule : Module() {

val didAdoptSeed = adoptSeedDeviceTokenIfNeeded(seedDeviceToken)
startClientInvalidationObserver()
startRestoreCredentialSignOutObserver()
if (didAdoptSeed) {
// An initialization refresh started before the seed was stored is fenced off by the token change.
launch {
Expand Down Expand Up @@ -224,6 +229,23 @@ class ClerkExpoModule : Module() {
}
}

private fun startRestoreCredentialSignOutObserver() {
if (restoreCredentialSignOutObserverJob != null) {
return
}

// Collect on IO so RestoreCredentials.clear()'s synchronous file write and fsync never run
// on the main thread, while UNDISPATCHED enters clear() before the next client emission.
restoreCredentialSignOutObserverJob = coroutineScope.launch(Dispatchers.IO) {
val signOutDetector = ClerkSignOutDetector()
Clerk.clientFlow.collect { client ->
if (signOutDetector.signedOut(client, System.currentTimeMillis())) {
launch(start = CoroutineStart.UNDISPATCHED) { clearRestoreCredential() }
}
}
}
}

private fun clientFingerprint(client: Client? = Clerk.clientFlow.value): ClerkClientFingerprint {
return ClerkClientFingerprint.from(client, currentDeviceToken())
}
Expand Down Expand Up @@ -297,6 +319,14 @@ class ClerkExpoModule : Module() {
}
}

private suspend fun clearRestoreCredential() {
val result = Clerk.restoreCredentials.clear()
if (result is ClerkResult.Failure) {
val detail = result.error?.firstMessage() ?: result.throwable?.message ?: result.error
debugLog(TAG, "Restore credential cleanup after a sign-out did not complete: $detail")
}
}

// MARK: - Theme Loading

private fun loadThemeFromAssets(context: Context) {
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@
package expo.modules.clerk

import com.clerk.api.network.model.client.Client
import com.clerk.api.session.Session

internal class ClerkSignOutDetector {
private var lastKnownClient: Client? = null

fun signedOut(client: Client?, nowMillis: Long): Boolean {
if (client?.id == null) return false
val previous = lastKnownClient
lastKnownClient = client
val remaining = client.signedInSessions()
val remainingSessionIds = remaining.mapTo(mutableSetOf()) { it.id }
val remainingUsers = remaining.mapTo(mutableSetOf()) { it.userKey() }
val expiredSessionIds = client.sessions
.filter { it.status == Session.SessionStatus.EXPIRED }
.mapTo(mutableSetOf()) { it.id }
return previous?.signedInSessions().orEmpty().any {
it.id !in remainingSessionIds &&
it.userKey() !in remainingUsers &&
it.id !in expiredSessionIds &&
!it.hasExpiredBy(nowMillis)
}
}
}

private fun Client.signedInSessions(): List<Session> =
sessions.filter { it.status == Session.SessionStatus.ACTIVE || it.status == Session.SessionStatus.PENDING }

private fun Session.userKey(): String = user?.id ?: publicUserData?.userId ?: id
Comment thread
coderabbitai[bot] marked this conversation as resolved.
Resolved

private fun Session.hasExpiredBy(nowMillis: Long): Boolean = expireAt in 1..nowMillis
Original file line number Diff line number Diff line change
@@ -0,0 +1,93 @@
package expo.modules.clerk

import com.clerk.api.network.model.client.Client
import com.clerk.api.network.model.userdata.PublicUserData
import com.clerk.api.session.Session
import org.junit.Assert.assertEquals
import org.junit.Test

class ClerkSignOutDetectorTest {
private val now = 1_000_000L
private val signedOut = Client(id = "client_1")
private val alice = client(session("sess_1", "user_alice"))
private val aliceAndBob = client(session("sess_1", "user_alice"), session("sess_2", "user_bob"))

@Test
fun `a signed-in user leaving the client is a sign-out`() {
assertEquals(listOf(false, true), detect(alice, signedOut))
assertEquals(listOf(false, true), detect(aliceAndBob, alice))
assertEquals(listOf(false, true), detect(alice, client(session("sess_1", "user_alice", Session.SessionStatus.ENDED))))
assertEquals(listOf(false, true), detect(client(session("sess_1", "user_alice", Session.SessionStatus.PENDING)), signedOut))
assertEquals(listOf(false, true), detect(client(session("sess_1", user = null)), signedOut))
}

@Test
fun `keeping or adding users is not a sign-out`() {
assertEquals(listOf(false, false), detect(alice, alice))
assertEquals(listOf(false, false), detect(alice, aliceAndBob))
assertEquals(listOf(false, false), detect(signedOut, alice))
assertEquals(listOf(false, false), detect(client(session("sess_1", "user_alice", Session.SessionStatus.PENDING)), alice))
assertEquals(listOf(false, false), detect(client(session("sess_1", user = null)), alice))
}

@Test
fun `a sign-in right after a sign-out clears once`() {
val bob = client(session("sess_2", "user_bob"))
assertEquals(listOf(false, true, false), detect(alice, signedOut, bob))
assertEquals(listOf(false, true, false), detect(alice, signedOut, alice))
}

@Test
fun `another user replacing the signed-in user in one update is a sign-out`() {
assertEquals(listOf(false, true), detect(alice, client(session("sess_2", "user_bob"))))
}

@Test
fun `the same user on a new client after a device token swap is not a sign-out`() {
val aliceOnNewClient = Client(id = "client_2", sessions = listOf(session("sess_9", "user_alice")))
assertEquals(listOf(false, false, false), detect(alice, Client(), aliceOnNewClient))
}

@Test
fun `a client that is not known yet is skipped until one is`() {
assertEquals(listOf(false, false, true), detect(alice, null, signedOut))
assertEquals(listOf(false, false, true), detect(alice, Client(), signedOut))
assertEquals(listOf(false, false), detect(null, signedOut))
}

@Test
fun `a session that has passed its expiry is not a sign-out`() {
assertEquals(listOf(false, false), detect(client(session("sess_1", "user_alice", expireAt = now)), signedOut))
assertEquals(listOf(false, true), detect(client(session("sess_1", "user_alice", expireAt = now + 1)), signedOut))
assertEquals(
listOf(false, false, false),
detect(
client(session("sess_1", "user_alice", expireAt = now + 1)),
client(session("sess_1", "user_alice", Session.SessionStatus.EXPIRED, expireAt = now + 1)),
signedOut,
),
)
}

private fun detect(vararg clients: Client?): List<Boolean> {
val detector = ClerkSignOutDetector()
return clients.map { detector.signedOut(it, now) }
}

private fun client(vararg sessions: Session) = Client(id = "client_1", sessions = sessions.toList())

private fun session(
id: String,
user: String?,
status: Session.SessionStatus = Session.SessionStatus.ACTIVE,
expireAt: Long = 0,
) = Session(
id = id,
status = status,
expireAt = expireAt,
lastActiveAt = 0,
createdAt = 0,
updatedAt = 0,
publicUserData = user?.let { PublicUserData(hasImage = false, identifier = it, userId = it) },
)
}
4 changes: 3 additions & 1 deletion packages/expo-native-components/src/AuthView.tsx
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import { useCallback } from 'react';
import type { NativeSyntheticEvent } from 'react-native';
import { Text, View } from 'react-native';
import { Platform, Text, View } from 'react-native';

import type { AuthViewProps } from './AuthView.types';
import NativeClerkAuthView from './specs/NativeClerkAuthView';
Expand Down Expand Up @@ -46,6 +46,7 @@ export function AuthView({
isDismissible = true,
preferredEmailStrategy,
logoMaxHeight,
enableRestoreCredentials = false,
onDismiss,
onHostBack,
}: AuthViewProps) {
Expand Down Expand Up @@ -77,6 +78,7 @@ export function AuthView({
isDismissible={isDismissible}
preferredEmailStrategy={preferredEmailStrategy}
logoMaxHeight={logoMaxHeight}
enableRestoreCredentials={Platform.OS === 'android' ? enableRestoreCredentials : undefined}
hostBackButton={!!onHostBack}
onAuthEvent={handleAuthEvent}
onHostBack={onHostBack ? () => onHostBack() : undefined}
Expand Down
28 changes: 28 additions & 0 deletions packages/expo-native-components/src/AuthView.types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -79,6 +79,34 @@ export interface AuthViewProps extends EmbeddedNavigationProps {
*/
logoMaxHeight?: number;

/**
* Turns on [Restore Credentials](https://developer.android.com/identity/sign-in/restore-credentials)
* so users stay signed in when they move to a new Android device. Android only and opt-in;
* ignored on iOS.
*
* When `true`, on the first launch after the app is installed or restored onto a device, a
* signed-out `AuthView` in `signIn` or `signInOrUp` mode tries to sign in silently with the restore
* credential that Android device setup transferred from the user's old device, and falls back to
* the usual sign-in UI if there is none. Later launches don't try again, so a user whose session
* ended is not signed back in silently.
*
* After a sign-in or sign-up, `AuthView` creates a restore credential for the signed-in user in
* the background, replacing the one this device created for that user before. A device holds one
* restore credential, which belongs to the user who most recently signed in. Restore credentials
* are passkeys named "Android restore key".
*
* On Android, whether or not this prop is set, the device's restore credential is deleted when a
* signed-in user leaves the device: they sign out from JavaScript or native code, their session is
* revoked, or it times out from inactivity. A session that reaches its maximum lifetime keeps the
* credential, so the user can still be restored on a new device. Deletion is best effort: if
* Android fails to delete the credential, the failure is logged and not retried.
*
* Requires passkeys to be enabled as a first factor for your Clerk instance.
*
* @default false
*/
enableRestoreCredentials?: boolean;

/**
* Called when the native authentication view requests dismissal.
*
Expand Down
25 changes: 24 additions & 1 deletion packages/expo-native-components/src/__tests__/AuthView.test.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,8 @@ import { AuthView } from '../AuthView';

const mocks = vi.hoisted(() => {
return {
NativeClerkAuthView: vi.fn(() => null),
NativeClerkAuthView: vi.fn((_props: Record<string, unknown>) => null),
platform: { OS: 'android' },
};
});

Expand All @@ -24,6 +25,7 @@ vi.mock('../utils/native-module', () => {

vi.mock('react-native', () => {
return {
Platform: mocks.platform,
Text: ({ children }: { children?: React.ReactNode }) => React.createElement('span', null, children),
View: ({ children }: { children?: React.ReactNode }) => React.createElement('div', null, children),
};
Expand All @@ -32,6 +34,7 @@ vi.mock('react-native', () => {
describe('AuthView', () => {
beforeEach(() => {
mocks.NativeClerkAuthView.mockClear();
mocks.platform.OS = 'android';
});

test('passes logoMaxHeight to the native auth view', () => {
Expand All @@ -46,6 +49,26 @@ describe('AuthView', () => {
expect(mocks.NativeClerkAuthView.mock.calls[0]?.[0]).toMatchObject({ preferredEmailStrategy: 'email_code' });
});

test('turns off restore credentials by default on Android', () => {
render(<AuthView />);

expect(mocks.NativeClerkAuthView.mock.calls[0]?.[0]).toMatchObject({ enableRestoreCredentials: false });
});

test('passes enableRestoreCredentials to the native auth view on Android', () => {
render(<AuthView enableRestoreCredentials />);

expect(mocks.NativeClerkAuthView.mock.calls[0]?.[0]).toMatchObject({ enableRestoreCredentials: true });
});

test('does not pass enableRestoreCredentials to the native auth view on iOS', () => {
mocks.platform.OS = 'ios';

render(<AuthView enableRestoreCredentials />);

expect(mocks.NativeClerkAuthView.mock.calls[0]?.[0].enableRestoreCredentials).toBeUndefined();
});

test('calls onDismiss when the native auth view emits dismissed', () => {
const onDismiss = vi.fn();

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@ interface NativeProps extends ViewProps {
isDismissible?: boolean;
preferredEmailStrategy?: string;
logoMaxHeight?: number;
enableRestoreCredentials?: boolean;
hostBackButton?: boolean;
onAuthEvent?: (event: NativeSyntheticEvent<AuthEvent>) => void;
onHostBack?: (event: NativeSyntheticEvent<object>) => void;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@ interface NativeProps extends ViewProps {
isDismissible?: boolean;
preferredEmailStrategy?: string;
logoMaxHeight?: number;
enableRestoreCredentials?: boolean;
hostBackButton?: boolean;
onAuthEvent?: (event: NativeSyntheticEvent<AuthEvent>) => void;
onHostBack?: (event: NativeSyntheticEvent<object>) => void;
Expand Down
Loading