Skip to content

Commit 12ef401

Browse files
feat(expo-passkeys): support preferImmediatelyAvailableCredentials for passkey sign-in (#10776)
Co-authored-by: ketanchexy <262376399+ketanchexy@users.noreply.github.com>
1 parent 57b4e0b commit 12ef401

15 files changed

Lines changed: 245 additions & 17 deletions

File tree

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,8 @@
1+
---
2+
'@clerk/expo-passkeys': minor
3+
'@clerk/expo': minor
4+
'@clerk/clerk-js': minor
5+
'@clerk/shared': minor
6+
---
7+
8+
Add a `preferImmediatelyAvailableCredentials` option to `signIn.authenticateWithPasskey()` and `signIn.passkey()`. With `@clerk/expo-passkeys` on iOS 16+ and Android, it limits sign-in to passkeys already on the device, and the request fails without showing the "use a passkey from another device" sheet when there are none. This lets an app prompt for a passkey automatically when its sign-in screen opens. Browsers ignore it.

‎packages/clerk-js/src/core/clerk.ts‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -361,6 +361,7 @@ export class Clerk implements ClerkInterface {
361361
publicKeyOptions,
362362
}: {
363363
publicKeyOptions: PublicKeyCredentialRequestOptionsWithoutExtensions;
364+
preferImmediatelyAvailableCredentials?: boolean;
364365
}) => Promise<CredentialReturn<PublicKeyCredentialWithAuthenticatorAssertionResponse>>)
365366
| undefined;
366367

‎packages/clerk-js/src/core/resources/SignIn.ts‎

Lines changed: 5 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -665,7 +665,7 @@ export class SignIn extends BaseResource implements SignInResource {
665665
* @returns The updated `SignIn` resource.
666666
*/
667667
public authenticateWithPasskey = async (params?: AuthenticateWithPasskeyParams): Promise<SignInResource> => {
668-
const { flow } = params || {};
668+
const { flow, preferImmediatelyAvailableCredentials } = params || {};
669669

670670
/**
671671
* The UI should always prevent from this method being called if WebAuthn is not supported.
@@ -699,6 +699,7 @@ export class SignIn extends BaseResource implements SignInResource {
699699
const { publicKeyCredential, error } = await webAuthnGetCredential({
700700
publicKeyOptions: secondFactorPublicKeyOptions,
701701
conditionalUI: false,
702+
preferImmediatelyAvailableCredentials,
702703
});
703704
if (!publicKeyCredential) {
704705
throw error;
@@ -748,6 +749,7 @@ export class SignIn extends BaseResource implements SignInResource {
748749
const { publicKeyCredential, error } = await webAuthnGetCredential({
749750
publicKeyOptions,
750751
conditionalUI: canUseConditionalUI,
752+
preferImmediatelyAvailableCredentials,
751753
});
752754

753755
if (!publicKeyCredential) {
@@ -1578,7 +1580,7 @@ class SignInFuture implements SignInFutureResource {
15781580
}
15791581

15801582
async passkey(params?: SignInFuturePasskeyParams): Promise<{ error: ClerkError | null }> {
1581-
const { flow } = params || {};
1583+
const { flow, preferImmediatelyAvailableCredentials } = params || {};
15821584

15831585
/**
15841586
* The UI should always prevent from this method being called if WebAuthn is not supported.
@@ -1633,6 +1635,7 @@ class SignInFuture implements SignInFutureResource {
16331635
const { publicKeyCredential, error } = await webAuthnGetCredential({
16341636
publicKeyOptions,
16351637
conditionalUI: canUseConditionalUI,
1638+
preferImmediatelyAvailableCredentials,
16361639
});
16371640

16381641
if (!publicKeyCredential) {

‎packages/clerk-js/src/core/resources/__tests__/SignIn.test.ts‎

Lines changed: 139 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1020,6 +1020,93 @@ describe('SignIn', () => {
10201020
}),
10211021
);
10221022
});
1023+
1024+
it('forwards preferImmediatelyAvailableCredentials to the credential request in the discoverable flow', async () => {
1025+
const mockIsWebAuthnSupported = vi.fn().mockReturnValue(true);
1026+
const mockWebAuthnGetCredential = vi.fn().mockResolvedValue({
1027+
publicKeyCredential: mockPublicKeyCredential,
1028+
error: null,
1029+
});
1030+
1031+
SignIn.clerk = {
1032+
__internal_isWebAuthnSupported: mockIsWebAuthnSupported,
1033+
__internal_getPublicCredentials: mockWebAuthnGetCredential,
1034+
} as any;
1035+
1036+
const mockFetch = vi
1037+
.fn()
1038+
.mockResolvedValueOnce({
1039+
client: null,
1040+
response: {
1041+
id: 'signin_456',
1042+
status: 'needs_first_factor',
1043+
first_factor_verification: {
1044+
nonce: JSON.stringify({ challenge: 'Y2hhbGxlbmdl' }),
1045+
},
1046+
},
1047+
})
1048+
.mockResolvedValueOnce({
1049+
client: null,
1050+
response: { id: 'signin_456', status: 'complete' },
1051+
});
1052+
BaseResource._fetch = mockFetch;
1053+
1054+
const signIn = new SignIn({ id: 'signin_123' } as any);
1055+
await signIn.authenticateWithPasskey({ flow: 'discoverable', preferImmediatelyAvailableCredentials: true });
1056+
1057+
expect(mockWebAuthnGetCredential).toHaveBeenCalledWith(
1058+
expect.objectContaining({ preferImmediatelyAvailableCredentials: true }),
1059+
);
1060+
});
1061+
1062+
it('forwards preferImmediatelyAvailableCredentials to the credential request for a passkey second factor', async () => {
1063+
const mockIsWebAuthnSupported = vi.fn().mockReturnValue(true);
1064+
const mockWebAuthnGetCredential = vi.fn().mockResolvedValue({
1065+
publicKeyCredential: mockPublicKeyCredential,
1066+
error: null,
1067+
});
1068+
1069+
SignIn.clerk = {
1070+
__internal_isWebAuthnSupported: mockIsWebAuthnSupported,
1071+
__internal_getPublicCredentials: mockWebAuthnGetCredential,
1072+
} as any;
1073+
1074+
const mockFetch = vi
1075+
.fn()
1076+
.mockResolvedValueOnce({
1077+
client: null,
1078+
response: {
1079+
id: 'signin_123',
1080+
status: 'needs_second_factor',
1081+
supported_second_factors: [{ strategy: 'passkey' }],
1082+
second_factor_verification: {
1083+
nonce: JSON.stringify({ challenge: 'Y2hhbGxlbmdl' }),
1084+
},
1085+
},
1086+
})
1087+
.mockResolvedValueOnce({
1088+
client: null,
1089+
response: { id: 'signin_123', status: 'complete' },
1090+
});
1091+
BaseResource._fetch = mockFetch;
1092+
1093+
const signIn = new SignIn({
1094+
id: 'signin_123',
1095+
status: 'needs_second_factor',
1096+
supported_second_factors: [{ strategy: 'passkey' }, { strategy: 'totp' }],
1097+
} as any);
1098+
await signIn.authenticateWithPasskey({ preferImmediatelyAvailableCredentials: true });
1099+
1100+
expect(mockFetch).toHaveBeenNthCalledWith(
1101+
1,
1102+
expect.objectContaining({
1103+
path: '/client/sign_ins/signin_123/prepare_second_factor',
1104+
}),
1105+
);
1106+
expect(mockWebAuthnGetCredential).toHaveBeenCalledWith(
1107+
expect.objectContaining({ preferImmediatelyAvailableCredentials: true }),
1108+
);
1109+
});
10231110
});
10241111

10251112
describe('trusted_device strategy', () => {
@@ -2593,6 +2680,58 @@ describe('SignIn', () => {
25932680
expect(mockWebAuthnGetCredential).toHaveBeenCalled();
25942681
});
25952682

2683+
it('forwards preferImmediatelyAvailableCredentials to the credential request', async () => {
2684+
const mockIsWebAuthnSupported = vi.fn().mockReturnValue(true);
2685+
const mockWebAuthnGetCredential = vi.fn().mockResolvedValue({
2686+
publicKeyCredential: {
2687+
id: 'credential_123',
2688+
rawId: new ArrayBuffer(32),
2689+
response: {
2690+
authenticatorData: new ArrayBuffer(37),
2691+
clientDataJSON: new ArrayBuffer(121),
2692+
signature: new ArrayBuffer(64),
2693+
userHandle: null,
2694+
},
2695+
type: 'public-key',
2696+
},
2697+
error: null,
2698+
});
2699+
2700+
SignIn.clerk = {
2701+
__internal_isWebAuthnSupported: mockIsWebAuthnSupported,
2702+
__internal_getPublicCredentials: mockWebAuthnGetCredential,
2703+
__internal_environment: {
2704+
displayConfig: {
2705+
captchaOauthBypass: [],
2706+
},
2707+
},
2708+
} as any;
2709+
2710+
const mockFetch = vi
2711+
.fn()
2712+
.mockResolvedValueOnce({
2713+
client: null,
2714+
response: {
2715+
id: 'signin_123',
2716+
first_factor_verification: {
2717+
nonce: JSON.stringify({ challenge: 'Y2hhbGxlbmdl' }),
2718+
},
2719+
},
2720+
})
2721+
.mockResolvedValueOnce({
2722+
client: null,
2723+
response: { id: 'signin_123', status: 'complete' },
2724+
});
2725+
BaseResource._fetch = mockFetch;
2726+
2727+
const signIn = new SignIn();
2728+
await signIn.__internal_future.passkey({ flow: 'discoverable', preferImmediatelyAvailableCredentials: true });
2729+
2730+
expect(mockWebAuthnGetCredential).toHaveBeenCalledWith(
2731+
expect.objectContaining({ preferImmediatelyAvailableCredentials: true }),
2732+
);
2733+
});
2734+
25962735
it('throws error when WebAuthn is not supported', async () => {
25972736
const mockIsWebAuthnSupported = vi.fn().mockReturnValue(false);
25982737

‎packages/expo-passkeys/android/src/main/java/expo/modules/clerkexpopasskeys/ClerkExpoPasskeysModule.kt‎

Lines changed: 21 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -5,10 +5,16 @@ import androidx.credentials.exceptions.GetCredentialException
55
import expo.modules.kotlin.Promise
66
import expo.modules.kotlin.modules.Module
77
import expo.modules.kotlin.modules.ModuleDefinition
8+
import expo.modules.kotlin.records.Field
9+
import expo.modules.kotlin.records.Record
810
import kotlinx.coroutines.CoroutineScope
911
import kotlinx.coroutines.Dispatchers
1012
import kotlinx.coroutines.launch
1113

14+
class GetPasskeyOptionsArgument : Record {
15+
@Field var preferImmediatelyAvailableCredentials: Boolean = false
16+
}
17+
1218
class ClerkExpoPasskeysModule : Module() {
1319
private val mCoroutine = CoroutineScope(Dispatchers.Default)
1420

@@ -30,17 +36,24 @@ class ClerkExpoPasskeysModule : Module() {
3036
}
3137

3238
AsyncFunction("get") { request: String, promise: Promise ->
39+
launchGet(request, false, promise)
40+
}
3341

34-
mCoroutine.launch {
35-
try {
36-
val response = getPasskey(request, appContext)
37-
promise.resolve(response)
38-
} catch (e: GetCredentialException) {
39-
handleGetFailure(e, promise)
40-
}
41-
}
42+
AsyncFunction("getWithOptions") { request: String, options: GetPasskeyOptionsArgument, promise: Promise ->
43+
launchGet(request, options.preferImmediatelyAvailableCredentials, promise)
4244
}
4345

4446

4547
}
48+
49+
private fun launchGet(request: String, preferImmediatelyAvailableCredentials: Boolean, promise: Promise) {
50+
mCoroutine.launch {
51+
try {
52+
val response = getPasskey(request, preferImmediatelyAvailableCredentials, appContext)
53+
promise.resolve(response)
54+
} catch (e: GetCredentialException) {
55+
handleGetFailure(e, promise)
56+
}
57+
}
58+
}
4659
}

‎packages/expo-passkeys/android/src/main/java/expo/modules/clerkexpopasskeys/CredentialManager.kt‎

Lines changed: 5 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -22,12 +22,16 @@ suspend fun createPasskey(
2222

2323
suspend fun getPasskey(
2424
request: String,
25+
preferImmediatelyAvailableCredentials: Boolean,
2526
appContext: AppContext,
2627
): String? {
2728
val credentialManager =
2829
CredentialManager.create(appContext.reactContext?.applicationContext!!)
2930
val getCredentialRequest =
30-
GetCredentialRequest(listOf(GetPublicKeyCredentialOption(request)))
31+
GetCredentialRequest(
32+
credentialOptions = listOf(GetPublicKeyCredentialOption(request)),
33+
preferImmediatelyAvailableCredentials = preferImmediatelyAvailableCredentials,
34+
)
3135

3236
val result = appContext.activityProvider?.currentActivity?.let {
3337
credentialManager.getCredential(it, getCredentialRequest)

‎packages/expo-passkeys/ios/AccountManager.swift‎

Lines changed: 6 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -58,7 +58,7 @@ class AccountManager: NSObject, ASAuthorizationControllerPresentationContextProv
5858
}
5959

6060

61-
func getPasskey(challengeBase64URL: String, rpId: String, promise: Promise) {
61+
func getPasskey(challengeBase64URL: String, rpId: String, preferImmediatelyAvailableCredentials: Bool, promise: Promise) {
6262
let publicKeyCredentialProvider = ASAuthorizationPlatformPublicKeyCredentialProvider(relyingPartyIdentifier: rpId)
6363

6464
let challenge = dataFromBase64URL(base64urlString: challengeBase64URL)!
@@ -68,7 +68,11 @@ class AccountManager: NSObject, ASAuthorizationControllerPresentationContextProv
6868
let authController = ASAuthorizationController(authorizationRequests: [ assertionRequest ] )
6969
authController.delegate = self
7070
authController.presentationContextProvider = self
71-
authController.performRequests()
71+
if preferImmediatelyAvailableCredentials, #available(iOS 16.0, *) {
72+
authController.performRequests(options: .preferImmediatelyAvailableCredentials)
73+
} else {
74+
authController.performRequests()
75+
}
7276

7377
self.authCallback = { result,error in
7478
if (error != nil) {

‎packages/expo-passkeys/ios/ClerkExpoPasskeysModule.swift‎

Lines changed: 9 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,9 @@
11
import ExpoModulesCore
22

3+
struct GetPasskeyOptions: Record {
4+
@Field var preferImmediatelyAvailableCredentials: Bool = false
5+
}
6+
37
@available(iOS 15.0, *)
48
public class ClerkExpoPasskeysModule: Module {
59
let credentialManager = AccountManager()
@@ -12,7 +16,11 @@ public class ClerkExpoPasskeysModule: Module {
1216
}
1317

1418
AsyncFunction("get") { (challenge: String, rpId:String, promise: Promise) in
15-
self.credentialManager.getPasskey(challengeBase64URL: challenge, rpId: rpId, promise: promise)
19+
self.credentialManager.getPasskey(challengeBase64URL: challenge, rpId: rpId, preferImmediatelyAvailableCredentials: false, promise: promise)
20+
}
21+
22+
AsyncFunction("getWithOptions") { (challenge: String, rpId: String, options: GetPasskeyOptions, promise: Promise) in
23+
self.credentialManager.getPasskey(challengeBase64URL: challenge, rpId: rpId, preferImmediatelyAvailableCredentials: options.preferImmediatelyAvailableCredentials, promise: promise)
1624
}
1725

1826
AsyncFunction("autofill") { (challenge: String, rpId:String, promise: Promise) in

‎packages/expo-passkeys/src/index.ts‎

Lines changed: 9 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -115,8 +115,10 @@ const makeSerializedGetResponse = (
115115

116116
export async function get({
117117
publicKeyOptions,
118+
preferImmediatelyAvailableCredentials,
118119
}: {
119120
publicKeyOptions: PublicKeyCredentialRequestOptionsWithoutExtensions;
121+
preferImmediatelyAvailableCredentials?: boolean;
120122
}): Promise<CredentialReturn<PublicKeyCredentialWithAuthenticatorAssertionResponse>> {
121123
if (!publicKeyOptions) {
122124
throw new Error('publicKeyCredential has not been provided');
@@ -128,9 +130,14 @@ export async function get({
128130
challenge: arrayBufferToBase64Url(publicKeyOptions.challenge),
129131
};
130132

133+
const callGet = (...args: unknown[]) =>
134+
preferImmediatelyAvailableCredentials && ClerkExpoPasskeys.getWithOptions
135+
? ClerkExpoPasskeys.getWithOptions(...args, { preferImmediatelyAvailableCredentials: true })
136+
: ClerkExpoPasskeys.get(...args);
137+
131138
const getPasskeyModule = Platform.select({
132-
android: async () => ClerkExpoPasskeys.get(JSON.stringify(serializedPublicCredential)),
133-
ios: async () => ClerkExpoPasskeys.get(serializedPublicCredential.challenge, serializedPublicCredential.rpId),
139+
android: async () => callGet(JSON.stringify(serializedPublicCredential)),
140+
ios: async () => callGet(serializedPublicCredential.challenge, serializedPublicCredential.rpId),
134141
default: null,
135142
});
136143

‎packages/expo/src/provider/singleton/__tests__/createClerkInstance.test.ts‎

Lines changed: 28 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -223,6 +223,34 @@ describe('createClerkInstance', () => {
223223
expect(get).toHaveBeenNthCalledWith(2, { publicKeyOptions: sessionSecondFactorOptions });
224224
});
225225

226+
test('forwards preferImmediatelyAvailableCredentials to the native passkey adapter', async () => {
227+
const createClerkInstance = await loadCreateClerkInstance();
228+
const getClerkInstance = createClerkInstance(MockClerk as unknown as typeof Clerk);
229+
const get = vi.fn().mockResolvedValue({ publicKeyCredential: null, error: null });
230+
const clerk = getClerkInstance({
231+
publishableKey: 'pk_test_123',
232+
__experimental_passkeys: {
233+
get,
234+
create: vi.fn(),
235+
isSupported: vi.fn(() => true),
236+
isAutoFillSupported: vi.fn(() => Promise.resolve(false)),
237+
},
238+
}) as unknown as MockClerk & {
239+
__internal_getPublicCredentials: (params: {
240+
publicKeyOptions: PublicKeyCredentialRequestOptionsWithoutExtensions;
241+
preferImmediatelyAvailableCredentials?: boolean;
242+
}) => Promise<unknown>;
243+
};
244+
const publicKeyOptions = {
245+
challenge: new Uint8Array([1]).buffer,
246+
rpId: 'example.com',
247+
} as PublicKeyCredentialRequestOptionsWithoutExtensions;
248+
249+
await clerk.__internal_getPublicCredentials({ publicKeyOptions, preferImmediatelyAvailableCredentials: true });
250+
251+
expect(get).toHaveBeenCalledWith({ publicKeyOptions, preferImmediatelyAvailableCredentials: true });
252+
});
253+
226254
test('recreates the singleton when proxyUrl changes', async () => {
227255
const createClerkInstance = await loadCreateClerkInstance();
228256
const getClerkInstance = createClerkInstance(MockClerk as unknown as typeof Clerk);

0 commit comments

Comments
 (0)