-
-
Notifications
You must be signed in to change notification settings - Fork 237
Expand file tree
/
Copy pathBiometricAuthenticator.kt
More file actions
190 lines (170 loc) · 7.37 KB
/
BiometricAuthenticator.kt
File metadata and controls
190 lines (170 loc) · 7.37 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
package com.sensitiveinfo.internal.auth
import android.os.Build
import androidx.biometric.BiometricManager
import androidx.biometric.BiometricPrompt
import androidx.core.content.ContextCompat
import androidx.fragment.app.FragmentActivity
import com.margelo.nitro.sensitiveinfo.AuthenticationPrompt
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.suspendCancellableCoroutine
import kotlinx.coroutines.withContext
import com.sensitiveinfo.internal.util.ReactContextHolder
import com.sensitiveinfo.internal.util.SensitiveInfoException
import javax.crypto.Cipher
import kotlin.coroutines.cancellation.CancellationException
import kotlin.coroutines.resume
import kotlin.coroutines.resumeWithException
/**
* Coroutine-friendly wrapper around `BiometricPrompt` used by the Keystore flows.
*
* The helper always executes prompts on the main dispatcher and returns the cipher configured for
* the successful authentication. Cancellation propagates back to the calling coroutine, matching
* the surface used by the Nitro Promise bridge.
*/
internal class BiometricAuthenticator {
private val applicationContext get() = ReactContextHolder.requireContext()
/**
* Prompts the user for biometric/device-credential authentication and returns the cipher once it
* can be used. The coroutine cooperatively cancels when the caller abandons the operation.
*/
suspend fun authenticate(
prompt: AuthenticationPrompt?,
allowedAuthenticators: Int,
cipher: Cipher?
): Cipher? {
val activity = currentFragmentActivity()
val effectivePrompt = prompt ?: AuthenticationPrompt(DEFAULT_TITLE, null, null, DEFAULT_CANCEL)
val allowDeviceCredential = allowedAuthenticators and BiometricManager.Authenticators.DEVICE_CREDENTIAL != 0
val supportsInlineDeviceCredential = allowDeviceCredential && Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q
val allowLegacyDeviceCredential = allowDeviceCredential && Build.VERSION.SDK_INT < Build.VERSION_CODES.Q
return withContext(Dispatchers.Main) {
if (cipher == null && allowLegacyDeviceCredential && !canUseBiometric()) {
DeviceCredentialPromptFragment.authenticate(activity, effectivePrompt)
cipher
} else {
try {
authenticateWithBiometricPrompt(
activity = activity,
prompt = effectivePrompt,
allowedAuthenticators = allowedAuthenticators,
supportsInlineDeviceCredential = supportsInlineDeviceCredential,
cipher = cipher
)
} catch (error: Throwable) {
if (error is CancellationException) throw error
if (allowLegacyDeviceCredential) {
DeviceCredentialPromptFragment.authenticate(activity, effectivePrompt)
return@withContext cipher
}
throw error
}
}
}
}
private suspend fun authenticateWithBiometricPrompt(
activity: FragmentActivity,
prompt: AuthenticationPrompt,
allowedAuthenticators: Int,
supportsInlineDeviceCredential: Boolean,
cipher: Cipher?
): Cipher? {
return suspendCancellableCoroutine { continuation ->
val executor = ContextCompat.getMainExecutor(activity)
val promptInfo = buildPromptInfo(prompt, allowedAuthenticators, supportsInlineDeviceCredential)
val biometricPrompt = BiometricPrompt(activity, executor, object : BiometricPrompt.AuthenticationCallback() {
override fun onAuthenticationSucceeded(result: BiometricPrompt.AuthenticationResult) {
val authCipher = result.cryptoObject?.cipher ?: cipher
continuation.resume(authCipher)
}
override fun onAuthenticationError(errorCode: Int, errString: CharSequence) {
if (
errorCode == BiometricPrompt.ERROR_CANCELED ||
errorCode == BiometricPrompt.ERROR_USER_CANCELED ||
errorCode == BiometricPrompt.ERROR_NEGATIVE_BUTTON
) {
continuation.resumeWithException(SensitiveInfoException.AuthenticationCanceled())
} else {
continuation.resumeWithException(IllegalStateException(errString.toString()))
}
}
override fun onAuthenticationFailed() {
// Keep waiting for another attempt.
}
})
continuation.invokeOnCancellation {
biometricPrompt.cancelAuthentication()
}
if (cipher != null) {
val cryptoObject = BiometricPrompt.CryptoObject(cipher)
biometricPrompt.authenticate(promptInfo, cryptoObject)
} else {
biometricPrompt.authenticate(promptInfo)
}
}
}
private fun buildPromptInfo(
prompt: AuthenticationPrompt,
allowedAuthenticators: Int,
supportsInlineDeviceCredential: Boolean
): BiometricPrompt.PromptInfo {
val builder = BiometricPrompt.PromptInfo.Builder()
.setTitle(prompt.title)
// Prefer disabling confirmation on supported devices to streamline UX while maintaining
// biometric security. Newer Biometric APIs support `setConfirmationRequired`.
try {
builder.setConfirmationRequired(false)
} catch (_: Throwable) {
// Ignore if the platform/library doesn't support this method.
}
prompt.subtitle?.let(builder::setSubtitle)
prompt.description?.let(builder::setDescription)
var promptAuthenticators = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R) {
// Newer biometric library versions (1.4.x+) prefer `setAllowedAuthenticators`.
allowedAuthenticators
} else {
// On older platforms fall back to the legacy flags.
allowedAuthenticators and (BiometricManager.Authenticators.BIOMETRIC_STRONG or BiometricManager.Authenticators.DEVICE_CREDENTIAL)
}
if (promptAuthenticators == 0) {
promptAuthenticators = BiometricManager.Authenticators.BIOMETRIC_STRONG
}
val allowsDeviceCredential = promptAuthenticators and BiometricManager.Authenticators.DEVICE_CREDENTIAL != 0
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R) {
builder.setAllowedAuthenticators(promptAuthenticators)
if (!allowsDeviceCredential) {
builder.setNegativeButtonText(prompt.cancel ?: DEFAULT_CANCEL)
}
} else {
if (allowsDeviceCredential && supportsInlineDeviceCredential && Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
@Suppress("DEPRECATION")
builder.setDeviceCredentialAllowed(true)
} else {
builder.setNegativeButtonText(prompt.cancel ?: DEFAULT_CANCEL)
}
}
return builder.build()
}
private fun canUseBiometric(): Boolean {
val biometricManager = BiometricManager.from(applicationContext)
return if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R) {
val strong = biometricManager.canAuthenticate(BiometricManager.Authenticators.BIOMETRIC_STRONG)
if (strong == BiometricManager.BIOMETRIC_SUCCESS) {
true
} else {
biometricManager.canAuthenticate(BiometricManager.Authenticators.BIOMETRIC_WEAK) == BiometricManager.BIOMETRIC_SUCCESS
}
} else {
@Suppress("DEPRECATION")
biometricManager.canAuthenticate() == BiometricManager.BIOMETRIC_SUCCESS
}
}
private fun currentFragmentActivity(): FragmentActivity {
val activity = ReactContextHolder.currentActivity()
?: throw IllegalStateException("Unable to show authentication prompt: no active React activity.")
return activity
}
companion object {
private const val DEFAULT_TITLE = "Authenticate"
private const val DEFAULT_CANCEL = "Cancel"
}
}