Skip to content

Privacy-first password manager with built-in email aliasing. Fully encrypted and self-hostable.

Add UnlockCoordinator.kt implementation (#1340)

Leendert de Borst4b59776b86ed
diff --git a/apps/mobile-app/android/app/src/main/java/net/aliasvault/app/credentialprovider/PasskeyAuthenticationActivity.kt b/apps/mobile-app/android/app/src/main/java/net/aliasvault/app/credentialprovider/PasskeyAuthenticationActivity.kt
index c638c3f61..b4a214477 100644
--- a/apps/mobile-app/android/app/src/main/java/net/aliasvault/app/credentialprovider/PasskeyAuthenticationActivity.kt
+++ b/apps/mobile-app/android/app/src/main/java/net/aliasvault/app/credentialprovider/PasskeyAuthenticationActivity.kt
@@ -12,7 +12,6 @@ import net.aliasvault.app.R
import net.aliasvault.app.utils.Helpers
import net.aliasvault.app.vaultstore.VaultStore
import net.aliasvault.app.vaultstore.keystoreprovider.AndroidKeystoreProvider
-import net.aliasvault.app.vaultstore.keystoreprovider.KeystoreOperationCallback
import net.aliasvault.app.vaultstore.passkey.PasskeyAuthenticator
import net.aliasvault.app.vaultstore.passkey.PasskeyHelper
import net.aliasvault.app.vaultstore.storageprovider.AndroidStorageProvider
@@ -44,6 +43,7 @@ class PasskeyAuthenticationActivity : FragmentActivity() {
}
private lateinit var vaultStore: VaultStore
+ private lateinit var unlockCoordinator: UnlockCoordinator
private var providerRequest: ProviderGetCredentialRequest? = null
override fun onCreate(savedInstanceState: Bundle?) {
@@ -66,47 +66,30 @@ class PasskeyAuthenticationActivity : FragmentActivity() {
VaultStore.getInstance(keystoreProvider, storageProvider)
}
- // Show loading screen while biometric prompt is displayed
+ // Show loading screen while unlock is in progress
setContentView(R.layout.activity_loading)
- // Check if biometric authentication is available before attempting unlock
- if (!vaultStore.isBiometricAuthEnabled()) {
- Log.e(TAG, "Biometric authentication is not enabled or not available")
- showError(getString(R.string.error_biometric_required))
- return
- }
-
- // Show biometric prompt to unlock vault (same pattern as registration)
- val keystoreProvider = AndroidKeystoreProvider(applicationContext) { this }
- keystoreProvider.retrieveKeyExternal(
- this,
- object : KeystoreOperationCallback {
- override fun onSuccess(result: String) {
- try {
- // Biometric authentication successful, unlock vault
- vaultStore.initEncryptionKey(result)
- vaultStore.unlockVault()
-
- // Now process the authentication request
- runOnUiThread {
- processAuthenticationRequest()
- }
- } catch (e: Exception) {
- Log.e(TAG, "Failed to unlock vault after biometric auth", e)
- runOnUiThread {
- showUnlockError(e)
- }
- }
- }
-
- override fun onError(e: Exception) {
- Log.e(TAG, "Failed to retrieve encryption key", e)
- runOnUiThread {
- showKeychainError(e)
- }
- }
+ // Initialize unlock coordinator
+ unlockCoordinator = UnlockCoordinator(
+ activity = this,
+ vaultStore = vaultStore,
+ onUnlocked = {
+ // Vault unlocked successfully - process authentication request
+ processAuthenticationRequest()
+ },
+ onCancelled = {
+ // User cancelled unlock
+ setResult(RESULT_CANCELED)
+ finish()
+ },
+ onError = { errorMessage ->
+ // Error during unlock
+ showError(errorMessage)
},
)
+
+ // Start the unlock flow
+ unlockCoordinator.startUnlockFlow()
} catch (e: Exception) {
Log.e(TAG, "Error in onCreate", e)
// Make sure we have the layout set before showing error
@@ -117,9 +100,18 @@ class PasskeyAuthenticationActivity : FragmentActivity() {
}
}
+ override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
+ super.onActivityResult(requestCode, resultCode, data)
+
+ // Delegate PIN unlock result to coordinator
+ if (requestCode == UnlockCoordinator.REQUEST_CODE_PIN_UNLOCK) {
+ unlockCoordinator.handlePinUnlockResult(resultCode, data)
+ }
+ }
+
/**
* Process the passkey authentication request and generate assertion.
- * Called after biometric authentication succeeds and vault is unlocked.
+ * Called after authentication (biometric or PIN) succeeds and vault is unlocked.
*/
private fun processAuthenticationRequest() {
val providerRequest = this.providerRequest ?: run {
@@ -337,33 +329,6 @@ class PasskeyAuthenticationActivity : FragmentActivity() {
)
}
- /**
- * Show error message when unlocking vault fails.
- */
- private fun showUnlockError(e: Exception) {
- val errorMessage = when {
- e.message?.contains("No encryption key found", ignoreCase = true) == true ->
- getString(R.string.error_unlock_vault_first)
- e.message?.contains("Database setup error", ignoreCase = true) == true ->
- getString(R.string.error_vault_decrypt_failed)
- else -> getString(R.string.error_vault_unlock_failed)
- }
- showError(errorMessage)
- }
-
- /**
- * Show error message when retrieving key from keychain fails.
- */
- private fun showKeychainError(e: Exception) {
- val errorMessage = when {
- e.message?.contains("user canceled", ignoreCase = true) == true ||
- e.message?.contains("authentication failed", ignoreCase = true) == true ->
- getString(R.string.error_biometric_cancelled)
- else -> getString(R.string.error_encryption_key_failed)
- }
- showError(errorMessage)
- }
-
/**
* Show error message in the loading view and display a close button.
* Hides the loading indicator and shows the error state.
diff --git a/apps/mobile-app/android/app/src/main/java/net/aliasvault/app/credentialprovider/PasskeyRegistrationActivity.kt b/apps/mobile-app/android/app/src/main/java/net/aliasvault/app/credentialprovider/PasskeyRegistrationActivity.kt
index 9c470d334..b9927b917 100644
--- a/apps/mobile-app/android/app/src/main/java/net/aliasvault/app/credentialprovider/PasskeyRegistrationActivity.kt
+++ b/apps/mobile-app/android/app/src/main/java/net/aliasvault/app/credentialprovider/PasskeyRegistrationActivity.kt
@@ -1,5 +1,6 @@
package net.aliasvault.app.credentialprovider
+import android.content.Intent
import android.os.Bundle
import android.util.Log
import android.view.View
@@ -13,7 +14,6 @@ import net.aliasvault.app.credentialprovider.models.PasskeyRegistrationViewModel
import net.aliasvault.app.utils.Helpers
import net.aliasvault.app.vaultstore.VaultStore
import net.aliasvault.app.vaultstore.keystoreprovider.AndroidKeystoreProvider
-import net.aliasvault.app.vaultstore.keystoreprovider.KeystoreOperationCallback
import net.aliasvault.app.vaultstore.storageprovider.AndroidStorageProvider
import org.json.JSONObject
@@ -36,6 +36,7 @@ class PasskeyRegistrationActivity : FragmentActivity() {
private val viewModel: PasskeyRegistrationViewModel by viewModels()
private lateinit var vaultStore: VaultStore
+ private lateinit var unlockCoordinator: UnlockCoordinator
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
@@ -101,57 +102,46 @@ class PasskeyRegistrationActivity : FragmentActivity() {
null
}
- // Show loading screen first
+ // Show loading screen while unlock is in progress
setContentView(R.layout.activity_loading)
- // Check if biometric authentication is available before attempting unlock
- if (!vaultStore.isBiometricAuthEnabled()) {
- Log.e(TAG, "Biometric authentication is not enabled or not available")
- showError(getString(R.string.error_biometric_required))
- return
- }
-
- // Add biometric prompt here to get decryption key and act as user verification as well
- // If biometric prompt is successful, we can proceed with the passkey registration
- // Create new keystore provider instance to avoid using the existing one
- val keystoreProvider = AndroidKeystoreProvider(applicationContext) { this }
- keystoreProvider.retrieveKeyExternal(
- this,
- object : KeystoreOperationCallback {
- override fun onSuccess(result: String) {
- try {
- Log.d(TAG, "Got decrypt key: ${result.length} bytes")
- // Biometric authentication successful, now proceed with passkey registration
- // (Re)unlock the vault now that the decryption key is available
- vaultStore.initEncryptionKey(result)
- vaultStore.unlockVault()
- runOnUiThread {
- proceedWithPasskeyRegistration(savedInstanceState)
- }
- } catch (e: Exception) {
- Log.e(TAG, "Failed to unlock vault after biometric auth", e)
- runOnUiThread {
- showUnlockError(e)
- }
- }
- }
-
- override fun onError(e: Exception) {
- Log.e(TAG, "Failed to retrieve encryption key", e)
- runOnUiThread {
- showKeychainError(e)
- }
- }
+ // Initialize unlock coordinator
+ unlockCoordinator = UnlockCoordinator(
+ activity = this,
+ vaultStore = vaultStore,
+ onUnlocked = {
+ // Vault unlocked successfully - proceed with passkey registration
+ proceedWithPasskeyRegistration(savedInstanceState)
+ },
+ onCancelled = {
+ // User cancelled unlock
+ finish()
+ },
+ onError = { errorMessage ->
+ // Error during unlock
+ showError(errorMessage)
},
)
+
+ // Start the unlock flow
+ unlockCoordinator.startUnlockFlow()
} catch (e: Exception) {
Log.e(TAG, "Error in onCreate", e)
finish()
}
}
+ override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
+ super.onActivityResult(requestCode, resultCode, data)
+
+ // Delegate PIN unlock result to coordinator
+ if (requestCode == UnlockCoordinator.REQUEST_CODE_PIN_UNLOCK) {
+ unlockCoordinator.handlePinUnlockResult(resultCode, data)
+ }
+ }
+
/**
- * Proceed with passkey registration after biometric authentication.
+ * Proceed with passkey registration after authentication (biometric or PIN).
*/
private fun proceedWithPasskeyRegistration(savedInstanceState: Bundle?) {
try {
@@ -206,33 +196,6 @@ class PasskeyRegistrationActivity : FragmentActivity() {
.commit()
}
- /**
- * Show error message when unlocking vault fails.
- */
- private fun showUnlockError(e: Exception) {
- val errorMessage = when {
- e.message?.contains("No encryption key found", ignoreCase = true) == true ->
- getString(R.string.error_unlock_vault_first)
- e.message?.contains("Database setup error", ignoreCase = true) == true ->
- getString(R.string.error_vault_decrypt_failed)
- else -> getString(R.string.error_vault_unlock_failed)
- }
- showError(errorMessage)
- }
-
- /**
- * Show error message when retrieving key from keychain fails.
- */
- private fun showKeychainError(e: Exception) {
- val errorMessage = when {
- e.message?.contains("user canceled", ignoreCase = true) == true ||
- e.message?.contains("authentication failed", ignoreCase = true) == true ->
- getString(R.string.error_biometric_cancelled)
- else -> getString(R.string.error_encryption_key_failed)
- }
- showError(errorMessage)
- }
-
/**
* Show error message in the loading view and display a close button.
* Hides the loading indicator and shows the error state.
diff --git a/apps/mobile-app/android/app/src/main/java/net/aliasvault/app/credentialprovider/UnlockCoordinator.kt b/apps/mobile-app/android/app/src/main/java/net/aliasvault/app/credentialprovider/UnlockCoordinator.kt
new file mode 100644
index 000000000..45954abeb
--- /dev/null
+++ b/apps/mobile-app/android/app/src/main/java/net/aliasvault/app/credentialprovider/UnlockCoordinator.kt
@@ -0,0 +1,198 @@
+package net.aliasvault.app.credentialprovider
+
+import android.content.Intent
+import android.util.Log
+import androidx.fragment.app.FragmentActivity
+import net.aliasvault.app.R
+import net.aliasvault.app.pinunlock.PinUnlockActivity
+import net.aliasvault.app.vaultstore.VaultStore
+import net.aliasvault.app.vaultstore.keystoreprovider.AndroidKeystoreProvider
+import net.aliasvault.app.vaultstore.keystoreprovider.KeystoreOperationCallback
+
+/**
+ * UnlockCoordinator
+ *
+ * Centralized coordinator for handling vault unlock flow in credential provider activities.
+ * This coordinator manages the unlock sequence, deciding whether to use PIN or biometric
+ * authentication based on what's enabled.
+ *
+ * Similar to iOS UnlockCoordinator.swift - provides a clean separation of unlock logic
+ * from the main activity flows.
+ */
+class UnlockCoordinator(
+ private val activity: FragmentActivity,
+ private val vaultStore: VaultStore,
+ private val onUnlocked: () -> Unit,
+ private val onCancelled: () -> Unit,
+ private val onError: (String) -> Unit,
+) {
+ companion object {
+ private const val TAG = "UnlockCoordinator"
+
+ /**
+ * Request code for PIN unlock activity result.
+ * Activities using UnlockCoordinator should use this constant
+ * when handling onActivityResult for PIN unlock.
+ */
+ const val REQUEST_CODE_PIN_UNLOCK = 1001
+ }
+
+ /**
+ * Start the unlock flow by checking which auth method is enabled.
+ * Priority: PIN -> Biometric -> Error
+ */
+ fun startUnlockFlow() {
+ val pinEnabled = vaultStore.isPinEnabled()
+ val biometricEnabled = vaultStore.isBiometricAuthEnabled()
+
+ when {
+ pinEnabled -> {
+ // PIN is enabled - launch PIN unlock activity
+ Log.d(TAG, "PIN unlock is enabled, launching PIN unlock activity")
+ launchPinUnlock()
+ }
+ biometricEnabled -> {
+ // Only biometric is enabled - attempt biometric unlock
+ Log.d(TAG, "Biometric unlock is enabled, attempting biometric unlock")
+ attemptBiometricUnlock()
+ }
+ else -> {
+ // Neither PIN nor biometric is enabled
+ Log.e(TAG, "No unlock method is enabled or available")
+ onError(activity.getString(R.string.error_unlock_method_required))
+ }
+ }
+ }
+
+ /**
+ * Launch PIN unlock activity.
+ */
+ private fun launchPinUnlock() {
+ val intent = Intent(activity, PinUnlockActivity::class.java)
+ activity.startActivityForResult(intent, REQUEST_CODE_PIN_UNLOCK)
+ }
+
+ /**
+ * Attempt biometric unlock using the keystore provider.
+ */
+ private fun attemptBiometricUnlock() {
+ val keystoreProvider = AndroidKeystoreProvider(activity.applicationContext) { activity }
+ keystoreProvider.retrieveKeyExternal(
+ activity,
+ object : KeystoreOperationCallback {
+ override fun onSuccess(result: String) {
+ try {
+ // Biometric authentication successful, unlock vault
+ vaultStore.initEncryptionKey(result)
+ vaultStore.unlockVault()
+
+ // Notify success
+ activity.runOnUiThread {
+ onUnlocked()
+ }
+ } catch (e: Exception) {
+ Log.e(TAG, "Failed to unlock vault after biometric auth", e)
+ activity.runOnUiThread {
+ handleBiometricUnlockError(e)
+ }
+ }
+ }
+
+ override fun onError(e: Exception) {
+ Log.e(TAG, "Failed to retrieve encryption key", e)
+ activity.runOnUiThread {
+ handleBiometricKeystoreError(e)
+ }
+ }
+ },
+ )
+ }
+
+ /**
+ * Handle result from PIN unlock activity.
+ * Call this from the activity's onActivityResult method.
+ */
+ fun handlePinUnlockResult(resultCode: Int, data: Intent?) {
+ when (resultCode) {
+ PinUnlockActivity.RESULT_SUCCESS -> {
+ // PIN unlock successful - get encryption key and unlock vault
+ val encryptionKey = data?.getStringExtra(PinUnlockActivity.EXTRA_ENCRYPTION_KEY)
+ if (encryptionKey != null) {
+ try {
+ vaultStore.initEncryptionKey(encryptionKey)
+ vaultStore.unlockVault()
+ onUnlocked()
+ } catch (e: Exception) {
+ Log.e(TAG, "Failed to unlock vault after PIN unlock", e)
+ onError(getUnlockErrorMessage(e))
+ }
+ } else {
+ Log.e(TAG, "No encryption key returned from PIN unlock")
+ onError("Failed to unlock vault")
+ }
+ }
+ PinUnlockActivity.RESULT_CANCELLED -> {
+ // User cancelled PIN unlock
+ Log.d(TAG, "PIN unlock cancelled by user")
+ onCancelled()
+ }
+ PinUnlockActivity.RESULT_PIN_DISABLED -> {
+ // PIN was disabled due to max attempts - fall back to biometric if available
+ Log.w(TAG, "PIN was disabled, attempting biometric unlock fallback")
+ if (vaultStore.isBiometricAuthEnabled()) {
+ attemptBiometricUnlock()
+ } else {
+ onError(activity.getString(R.string.error_unlock_method_required))
+ }
+ }
+ }
+ }
+
+ /**
+ * Handle errors during biometric unlock (after successful keystore retrieval).
+ */
+ private fun handleBiometricUnlockError(e: Exception) {
+ val errorMessage = when {
+ e.message?.contains("No encryption key found", ignoreCase = true) == true ->
+ "Please unlock vault in the app first"
+ e.message?.contains("Database setup error", ignoreCase = true) == true ->
+ "Failed to decrypt vault"
+ else -> "Failed to unlock vault"
+ }
+ onError(errorMessage)
+ }
+
+ /**
+ * Handle errors during biometric keystore retrieval.
+ */
+ private fun handleBiometricKeystoreError(e: Exception) {
+ val errorMessage = when {
+ e.message?.contains("user canceled", ignoreCase = true) == true ||
+ e.message?.contains("authentication failed", ignoreCase = true) == true -> {
+ // User cancelled or biometric failed - check if PIN is available as fallback
+ if (vaultStore.isPinEnabled()) {
+ Log.d(TAG, "Biometric cancelled/failed, falling back to PIN")
+ launchPinUnlock()
+ return // Don't call onError, we're falling back to PIN
+ } else {
+ "Authentication cancelled"
+ }
+ }
+ else -> "Failed to retrieve encryption key"
+ }
+ onError(errorMessage)
+ }
+
+ /**
+ * Get user-friendly error message for unlock errors.
+ */
+ private fun getUnlockErrorMessage(e: Exception): String {
+ return when {
+ e.message?.contains("No encryption key found", ignoreCase = true) == true ->
+ "Please unlock vault in the app first"
+ e.message?.contains("Database setup error", ignoreCase = true) == true ->
+ "Failed to decrypt vault"
+ else -> "Failed to unlock vault"
+ }
+ }
+}
diff --git a/apps/mobile-app/android/app/src/main/res/values/strings.xml b/apps/mobile-app/android/app/src/main/res/values/strings.xml
index be9b42ba6..06c497ec1 100644
--- a/apps/mobile-app/android/app/src/main/res/values/strings.xml
+++ b/apps/mobile-app/android/app/src/main/res/values/strings.xml
@@ -65,7 +65,7 @@
<string name="server_version_not_supported_message">The server version is outdated. Please contact your administrator to update the server.</string>
<!-- Passkey authentication and unlock error messages -->
- <string name="error_biometric_required">Please enable biometric authentication in the main AliasVault app in order to use passkeys</string>
+ <string name="error_unlock_method_required">Please enable biometric or PIN authentication in the main AliasVault app in order to continue</string>
<string name="error_unlock_vault_first">Please unlock vault in AliasVault app first</string>
<string name="error_vault_decrypt_failed">Failed to decrypt vault</string>
<string name="error_vault_unlock_failed">Failed to unlock vault</string>