package com.cottondb.android.platformimport androidx.biometric.BiometricManagerimport androidx.biometric.BiometricPromptimport androidx.fragment.app.FragmentActivityimport android.os.Buildimport java.util.concurrent.atomic.AtomicBooleanimport java.util.concurrent.atomic.AtomicReferenceimport kotlinx.coroutines.CoroutineScopeimport kotlinx.coroutines.Dispatchersimport kotlinx.coroutines.Jobimport kotlinx.coroutines.launchimport kotlinx.coroutines.suspendCancellableCoroutineimport kotlinx.coroutines.withContext/** * The only Android seam that turns a user-presence prompt into a vault private key. * * The caller receives the base64url scalar only long enough to pass it as `vault.unlock`'s * call parameter. Cancelling the caller cancels the system prompt; a cancelled or failed * prompt never calls [VaultKeyring.unlock] and never falls back to an unprotected read. */classVaultUnlock(privateval keyring: VaultKeyring) {suspendfun unlock(activity: FragmentActivity): String {val request = withContext(Dispatchers.IO) { keyring.prepareUnlock() }return withContext(Dispatchers.Main.immediate) { authenticate(activity, request) } }privatesuspendfun authenticate(activity: FragmentActivity, request: VaultUnlockRequest): String = suspendCancellableCoroutine { continuation ->val availability = BiometricManager.from(activity).canAuthenticate(allowedAuthenticators())if (availability != BiometricManager.BIOMETRIC_SUCCESS) { continuation.resumeWith(Result.failure(VaultUnlockUnavailableException(availabilityMessage(availability))))return@suspendCancellableCoroutine }val completion = AtomicReference<Job?>(null)val terminal = AtomicBoolean(false)fun finish(result: Result<String>) {// Prompt callbacks arrive on main while the IO completion and a caller's// cancellation may arrive elsewhere. This single admission owns resumption.if (terminal.compareAndSet(false, true)) continuation.resumeWith(result) }val prompt = BiometricPrompt(activity, activity.mainExecutor, object : BiometricPrompt.AuthenticationCallback() {overridefun onAuthenticationSucceeded(result: BiometricPrompt.AuthenticationResult) {if (terminal.get()) returnval cipher = result.cryptoObject?.cipherif (cipher == null) { finish(Result.failure(VaultUnlockAuthenticationException("The vault prompt did not return its cipher.")))return }// BiometricPrompt returns the cipher that was authenticated. Do not accept a// different one, and do the KeyStore finish/file write away from the UI thread.if (cipher !== request.cipher) { finish(Result.failure(VaultUnlockAuthenticationException("The vault prompt returned the wrong cipher.")))return }// Keep the file/decrypt work a child of the caller's Job. Activity-backed// callers cancel it as they leave the screen; this is not a detached secret// read that can outlive the prompt's owner.val job =CoroutineScope(continuation.context + Dispatchers.IO) .launchUnlock(request, ::finish) completion.set(job)if (terminal.get()) job.cancel() }overridefun onAuthenticationError(errorCode: Int, errString: CharSequence) {val failure = if (errorCode in CANCELLED_ERRORS) {VaultUnlockCancelledException() } else {VaultUnlockAuthenticationException(errString.toString()) } finish(Result.failure(failure)) }// A failed scan is not terminal. BiometricPrompt keeps the same protected// CryptoObject and lets the person try again or cancel explicitly.overridefun onAuthenticationFailed() = Unit }) continuation.invokeOnCancellation {if (terminal.compareAndSet(false, true)) { completion.get()?.cancel()// A coroutine may be cancelled from IO or a lifecycle callback. The// Fragment-backed prompt is manipulated only on its activity's UI thread. activity.runOnUiThread { prompt.cancelAuthentication() } } } prompt.authenticate(promptInfo(), BiometricPrompt.CryptoObject(request.cipher)) }privatefunCoroutineScope.launchUnlock( request: VaultUnlockRequest, finish: (Result<String>) -> Unit, ): Job = launch {try {val privateKey = keyring.unlock(request) finish(Result.success(privateKey)) } catch (failure: Throwable) { finish(Result.failure(failure)) } }privatecompanionobject {fun allowedAuthenticators(): Int =if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R) {BiometricManager.Authenticators.BIOMETRIC_STRONG orBiometricManager.Authenticators.DEVICE_CREDENTIAL } else {// Android 10 and lower cannot use a CryptoObject together// with device-credential fallback. Do not present a fallback// that cannot authorize this exact private-key operation.BiometricManager.Authenticators.BIOMETRIC_STRONG }fun promptInfo(): BiometricPrompt.PromptInfo {val builder = BiometricPrompt.PromptInfo.Builder() .setTitle("Unlock your passwords") .setAllowedAuthenticators(allowedAuthenticators())if (Build.VERSION.SDK_INT < Build.VERSION_CODES.R) { builder.setNegativeButtonText("Cancel") }return builder.build() }val CANCELLED_ERRORS = setOf(BiometricPrompt.ERROR_CANCELED,BiometricPrompt.ERROR_NEGATIVE_BUTTON,BiometricPrompt.ERROR_USER_CANCELED, )fun availabilityMessage(code: Int): String = when (code) {BiometricManager.BIOMETRIC_ERROR_NONE_ENROLLED ->if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R) {"This phone needs a screen lock or a strong biometric set up to unlock passwords." } else {"Android 10 and earlier need a fingerprint or another biometric set up to unlock passwords; passcode fallback starts on Android 11." }BiometricManager.BIOMETRIC_ERROR_NO_HARDWARE ->"This phone has no biometric hardware for unlocking passwords."BiometricManager.BIOMETRIC_ERROR_HW_UNAVAILABLE ->"This phone's biometric hardware is unavailable right now."else -> "This phone cannot ask to unlock passwords right now." } }}/** A person cancelled the biometric sheet; callers treat this as a decision, never a retry. */classVaultUnlockCancelledException : IllegalStateException("Vault unlock was cancelled.")/** Biometric availability or an authenticated-prompt failure that must remain visible. */classVaultUnlockUnavailableException(message: String) : IllegalStateException(message)classVaultUnlockAuthenticationException(message: String) : IllegalStateException(message)