Skip to content

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

Add explicit biometric auth for passkey create and authenticate flows (#520)

Leendert de Borst6698771fc4ec
diff --git a/apps/mobile-app/android/app/src/main/java/net/aliasvault/app/credentialprovider/AliasVaultCredentialProviderService.kt b/apps/mobile-app/android/app/src/main/java/net/aliasvault/app/credentialprovider/AliasVaultCredentialProviderService.kt
index 978854bac..d9f12cc18 100644
--- a/apps/mobile-app/android/app/src/main/java/net/aliasvault/app/credentialprovider/AliasVaultCredentialProviderService.kt
+++ b/apps/mobile-app/android/app/src/main/java/net/aliasvault/app/credentialprovider/AliasVaultCredentialProviderService.kt
@@ -19,10 +19,9 @@ import androidx.credentials.provider.CreateEntry
import androidx.credentials.provider.CredentialProviderService
import androidx.credentials.provider.ProviderClearCredentialStateRequest
import androidx.credentials.provider.PublicKeyCredentialEntry
-import net.aliasvault.app.utils.Helpers
import net.aliasvault.app.vaultstore.VaultStore
-import net.aliasvault.app.vaultstore.getPasskeysForRpId
-import net.aliasvault.app.vaultstore.passkey.PasskeyHelper
+import net.aliasvault.app.vaultstore.keystoreprovider.AndroidKeystoreProvider
+import net.aliasvault.app.vaultstore.storageprovider.AndroidStorageProvider
import org.json.JSONObject
/**
@@ -50,6 +49,7 @@ class AliasVaultCredentialProviderService : CredentialProviderService() {
/**
* Called when the system needs to display available credentials for authentication.
+ * Uses cached credential identities to show passkeys without unlocking the vault.
*/
override fun onBeginGetCredentialRequest(
request: BeginGetCredentialRequest,
@@ -57,13 +57,8 @@ class AliasVaultCredentialProviderService : CredentialProviderService() {
callback: OutcomeReceiver<BeginGetCredentialResponse, GetCredentialException>,
) {
try {
- // Get vault store instance
- val vaultStore = VaultStore.getExistingInstance()
- if (vaultStore == null) {
- Log.w(TAG, "VaultStore not initialized")
- callback.onResult(BeginGetCredentialResponse())
- return
- }
+ // Get credential identity store
+ val identityStore = CredentialIdentityStore.getInstance(applicationContext)
val credentialEntries = mutableListOf<PublicKeyCredentialEntry>()
@@ -72,7 +67,7 @@ class AliasVaultCredentialProviderService : CredentialProviderService() {
when (option) {
is BeginGetPublicKeyCredentialOption -> {
// This is a passkey request
- val entries = processPasskeyOption(option, vaultStore)
+ val entries = processPasskeyOptionFromIdentities(option, identityStore)
credentialEntries.addAll(entries)
}
}
@@ -86,11 +81,12 @@ class AliasVaultCredentialProviderService : CredentialProviderService() {
}
/**
- * Process a passkey credential option and return matching credential entries.
+ * Process a passkey credential option using cached credential identities.
+ * This allows showing passkeys without unlocking the vault.
*/
- private fun processPasskeyOption(
+ private fun processPasskeyOptionFromIdentities(
option: BeginGetPublicKeyCredentialOption,
- vaultStore: VaultStore,
+ identityStore: CredentialIdentityStore,
): List<PublicKeyCredentialEntry> {
try {
// Parse the request JSON to extract RP ID and other parameters
@@ -103,27 +99,12 @@ class AliasVaultCredentialProviderService : CredentialProviderService() {
return emptyList()
}
- // Query vault for matching passkeys
- val db = try {
- val dbField = VaultStore::class.java.getDeclaredField("dbConnection")
- dbField.isAccessible = true
- dbField.get(vaultStore) as? android.database.sqlite.SQLiteDatabase
- } catch (e: Exception) {
- Log.w(TAG, "Cannot access database - vault might be locked", e)
- null
- }
-
- if (db == null) {
- Log.w(TAG, "Database not available - vault is locked")
- return emptyList()
- }
-
- // Get passkeys for this RP ID
- val passkeys = vaultStore.getPasskeysForRpId(rpId, db)
+ // Get cached passkey identities for this RP ID
+ val identities = identityStore.getPasskeyIdentitiesForRpId(rpId)
// Filter by allowCredentials if specified
val allowCredentials = requestObj.optJSONArray("allowCredentials")
- val filteredPasskeys = if (allowCredentials != null && allowCredentials.length() > 0) {
+ val filteredIdentities = if (allowCredentials != null && allowCredentials.length() > 0) {
val allowedIds = mutableSetOf<String>()
for (i in 0 until allowCredentials.length()) {
val cred = allowCredentials.getJSONObject(i)
@@ -133,51 +114,48 @@ class AliasVaultCredentialProviderService : CredentialProviderService() {
}
}
- passkeys.filter { passkey ->
- val passkeyIdBytes = PasskeyHelper.guidToBytes(passkey.id.toString())
- val passkeyIdB64 = Helpers.bytesToBase64url(passkeyIdBytes)
- allowedIds.contains(passkeyIdB64)
+ identities.filter { identity ->
+ allowedIds.contains(identity.credentialId)
}
} else {
- passkeys
+ identities
}
// Convert to CredentialEntry objects
- return filteredPasskeys.map { passkey ->
- createPasskeyEntry(passkey, option, requestJson)
+ return filteredIdentities.map { identity ->
+ createPasskeyEntryFromIdentity(identity, option, requestJson)
}
} catch (e: Exception) {
- Log.e(TAG, "Error processing passkey option", e)
+ Log.e(TAG, "Error processing passkey option from identities", e)
return emptyList()
}
}
/**
- * Create a PublicKeyCredentialEntry for a passkey.
+ * Create a PublicKeyCredentialEntry from a cached PasskeyIdentity.
*/
- private fun createPasskeyEntry(
- passkey: net.aliasvault.app.vaultstore.models.Passkey,
+ private fun createPasskeyEntryFromIdentity(
+ identity: CredentialIdentityStore.PasskeyIdentity,
option: BeginGetPublicKeyCredentialOption,
requestJson: String,
): PublicKeyCredentialEntry {
// Create intent for PasskeyAuthenticationActivity
val intent = Intent(this, PasskeyAuthenticationActivity::class.java).apply {
putExtra(EXTRA_REQUEST_JSON, requestJson)
- putExtra(EXTRA_PASSKEY_ID, passkey.id.toString())
- putExtra(EXTRA_RP_ID, passkey.rpId)
- passkey.userHandle?.let { putExtra("user_handle", it) }
+ putExtra(EXTRA_PASSKEY_ID, identity.passkeyId)
+ putExtra(EXTRA_RP_ID, identity.rpId)
}
val pendingIntent = PendingIntent.getActivity(
this,
- passkey.id.hashCode(),
+ identity.passkeyId.hashCode(),
intent,
PendingIntent.FLAG_MUTABLE or PendingIntent.FLAG_UPDATE_CURRENT,
)
- // Use displayName or username for the UI
- val displayName = passkey.displayName.ifEmpty {
- passkey.userName ?: passkey.rpId
+ // Use displayName for the UI
+ val displayName = identity.displayName.ifEmpty {
+ identity.userName ?: identity.rpId
}
return PublicKeyCredentialEntry.Builder(
@@ -210,10 +188,14 @@ class AliasVaultCredentialProviderService : CredentialProviderService() {
private fun processCreateCredentialRequest(
request: BeginCreateCredentialRequest,
): BeginCreateCredentialResponse? {
- val vaultStore = VaultStore.getExistingInstance()
- if (vaultStore == null) {
- Log.w(TAG, "VaultStore not initialized for passkey creation")
- return null
+ // Get or initialize VaultStore instance (needed for subsequent passkey registration)
+ VaultStore.getExistingInstance() ?: run {
+ Log.d(TAG, "VaultStore not initialized, initializing now...")
+ // Need a FragmentActivity reference for biometrics, but this is a service
+ // We'll create a minimal VaultStore instance here
+ val keystoreProvider = AndroidKeystoreProvider(applicationContext) { null }
+ val storageProvider = AndroidStorageProvider(applicationContext)
+ VaultStore.getInstance(keystoreProvider, storageProvider)
}
return when (request) {
diff --git a/apps/mobile-app/android/app/src/main/java/net/aliasvault/app/credentialprovider/CredentialIdentityStore.kt b/apps/mobile-app/android/app/src/main/java/net/aliasvault/app/credentialprovider/CredentialIdentityStore.kt
new file mode 100644
index 000000000..12b064bc7
--- /dev/null
+++ b/apps/mobile-app/android/app/src/main/java/net/aliasvault/app/credentialprovider/CredentialIdentityStore.kt
@@ -0,0 +1,206 @@
+package net.aliasvault.app.credentialprovider
+
+import android.content.Context
+import android.content.SharedPreferences
+import android.util.Log
+import net.aliasvault.app.utils.Helpers
+import net.aliasvault.app.vaultstore.getPasskeysForCredential
+import net.aliasvault.app.vaultstore.models.Credential
+import net.aliasvault.app.vaultstore.models.Passkey
+import net.aliasvault.app.vaultstore.passkey.PasskeyHelper
+import org.json.JSONArray
+import org.json.JSONObject
+
+/**
+ * Android implementation of CredentialIdentityStore.
+ *
+ * This class stores passkey metadata (rpId, userName, displayName, credentialId, userHandle)
+ * in SharedPreferences so that passkeys can be displayed without unlocking the vault.
+ *
+ * Similar to iOS ASCredentialIdentityStore, but using SharedPreferences as Android's
+ * Credential Manager API doesn't provide a system-level identity store.
+ */
+class CredentialIdentityStore private constructor(context: Context) {
+
+ companion object {
+ private const val TAG = "CredentialIdentityStore"
+ private const val PREFS_NAME = "credential_identities"
+ private const val KEY_PASSKEY_IDENTITIES = "passkey_identities"
+
+ @Volatile
+ private var instance: CredentialIdentityStore? = null
+
+ /**
+ * Get the singleton instance of CredentialIdentityStore.
+ * @param context The application context
+ * @return The singleton instance
+ */
+ fun getInstance(context: Context): CredentialIdentityStore {
+ return instance ?: synchronized(this) {
+ instance ?: CredentialIdentityStore(context.applicationContext).also { instance = it }
+ }
+ }
+ }
+
+ private val prefs: SharedPreferences = context.getSharedPreferences(PREFS_NAME, Context.MODE_PRIVATE)
+
+ /**
+ * Data class representing a passkey credential identity.
+ * @property passkeyId UUID of the passkey
+ * @property rpId Relying Party ID
+ * @property userName Username (optional)
+ * @property displayName Display name for UI
+ * @property credentialId Base64url-encoded credential ID (16-byte GUID)
+ * @property userHandle Base64url-encoded user handle (optional)
+ */
+ data class PasskeyIdentity(
+ val passkeyId: String,
+ val rpId: String,
+ val userName: String?,
+ val displayName: String,
+ val credentialId: String,
+ val userHandle: String?,
+ ) {
+ companion object {
+ /**
+ * Create PasskeyIdentity from JSON.
+ */
+ fun fromJson(json: JSONObject): PasskeyIdentity {
+ return PasskeyIdentity(
+ passkeyId = json.getString("passkeyId"),
+ rpId = json.getString("rpId"),
+ userName = if (json.isNull("userName")) null else json.getString("userName"),
+ displayName = json.getString("displayName"),
+ credentialId = json.getString("credentialId"),
+ userHandle = if (json.isNull("userHandle")) null else json.getString("userHandle"),
+ )
+ }
+ }
+ }
+
+ /**
+ * Save credential identities from a list of credentials.
+ * This extracts passkey metadata and stores it in SharedPreferences.
+ * @param credentials List of credentials with passkeys
+ * @param vaultStore VaultStore instance to query passkeys
+ * @param db Database connection
+ */
+ fun saveCredentialIdentities(
+ credentials: List<Credential>,
+ vaultStore: net.aliasvault.app.vaultstore.VaultStore,
+ db: android.database.sqlite.SQLiteDatabase,
+ ) {
+ try {
+ val passkeyIdentities = mutableListOf<PasskeyIdentity>()
+
+ // Extract passkey identities from credentials
+ credentials.forEach { credential ->
+ // Get passkeys for this credential
+ val passkeys = vaultStore.getPasskeysForCredential(credential.id, db)
+
+ passkeys.forEach { passkey ->
+ if (!passkey.isDeleted) {
+ passkeyIdentities.add(createPasskeyIdentity(passkey, credential))
+ }
+ }
+ }
+
+ // Serialize to JSON and save
+ val jsonArray = JSONArray()
+ passkeyIdentities.forEach { identity ->
+ jsonArray.put(identity.toJson())
+ }
+
+ prefs.edit()
+ .putString(KEY_PASSKEY_IDENTITIES, jsonArray.toString())
+ .apply()
+
+ Log.d(TAG, "Saved ${passkeyIdentities.size} passkey identities")
+ } catch (e: Exception) {
+ Log.e(TAG, "Error saving credential identities", e)
+ }
+ }
+
+ /**
+ * Get all stored passkey identities.
+ */
+ fun getAllPasskeyIdentities(): List<PasskeyIdentity> {
+ return try {
+ val jsonString = prefs.getString(KEY_PASSKEY_IDENTITIES, null) ?: return emptyList()
+ val jsonArray = JSONArray(jsonString)
+
+ val identities = mutableListOf<PasskeyIdentity>()
+ for (i in 0 until jsonArray.length()) {
+ val jsonObject = jsonArray.getJSONObject(i)
+ identities.add(PasskeyIdentity.fromJson(jsonObject))
+ }
+
+ identities
+ } catch (e: Exception) {
+ Log.e(TAG, "Error reading credential identities", e)
+ emptyList()
+ }
+ }
+
+ /**
+ * Get passkey identities for a specific RP ID.
+ */
+ fun getPasskeyIdentitiesForRpId(rpId: String): List<PasskeyIdentity> {
+ return getAllPasskeyIdentities().filter { it.rpId.equals(rpId, ignoreCase = true) }
+ }
+
+ /**
+ * Get a specific passkey identity by its ID.
+ */
+ fun getPasskeyIdentityById(passkeyId: String): PasskeyIdentity? {
+ return getAllPasskeyIdentities().find { it.passkeyId == passkeyId }
+ }
+
+ /**
+ * Remove all credential identities.
+ */
+ fun removeAllCredentialIdentities() {
+ prefs.edit()
+ .remove(KEY_PASSKEY_IDENTITIES)
+ .apply()
+ Log.d(TAG, "Removed all credential identities")
+ }
+
+ /**
+ * Create a PasskeyIdentity from a Passkey and its parent Credential.
+ */
+ private fun createPasskeyIdentity(passkey: Passkey, credential: Credential): PasskeyIdentity {
+ // Get userName - prefer passkey's userName, fallback to credential's username or email
+ val userName = passkey.userName ?: credential.username ?: credential.alias?.email
+
+ // Convert passkey ID to credential ID (base64url-encoded bytes)
+ val credentialIdBytes = PasskeyHelper.guidToBytes(passkey.id.toString())
+ val credentialId = Helpers.bytesToBase64url(credentialIdBytes)
+
+ // Convert user handle to base64url if present
+ val userHandle = passkey.userHandle?.let { Helpers.bytesToBase64url(it) }
+
+ return PasskeyIdentity(
+ passkeyId = passkey.id.toString(),
+ rpId = passkey.rpId,
+ userName = userName,
+ displayName = passkey.displayName,
+ credentialId = credentialId,
+ userHandle = userHandle,
+ )
+ }
+
+ /**
+ * Extension function to convert PasskeyIdentity to JSON.
+ */
+ private fun PasskeyIdentity.toJson(): JSONObject {
+ return JSONObject().apply {
+ put("passkeyId", passkeyId)
+ put("rpId", rpId)
+ put("userName", userName ?: JSONObject.NULL)
+ put("displayName", displayName)
+ put("credentialId", credentialId)
+ put("userHandle", userHandle ?: JSONObject.NULL)
+ }
+ }
+}
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 28fb6bd21..e138622da 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
@@ -1,16 +1,20 @@
package net.aliasvault.app.credentialprovider
-import android.app.Activity
import android.content.Intent
import android.os.Bundle
import android.util.Log
import androidx.credentials.provider.PendingIntentHandler
import androidx.credentials.provider.ProviderGetCredentialRequest
+import androidx.fragment.app.FragmentActivity
+import net.aliasvault.app.R
import net.aliasvault.app.utils.Helpers
import net.aliasvault.app.vaultstore.VaultStore
import net.aliasvault.app.vaultstore.getPasskeyById
+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
import org.json.JSONObject
import java.security.MessageDigest
import java.util.UUID
@@ -20,28 +24,33 @@ import java.util.UUID
*
* Handles passkey authentication (assertion generation) when user selects a passkey.
* This activity:
- * 1. Retrieves the passkey from the vault
- * 2. Extracts PRF extension inputs if present
- * 3. Generates the WebAuthn assertion using PasskeyAuthenticator
- * 4. Returns the assertion to the calling app
+ * 1. Shows biometric prompt to unlock vault (if needed)
+ * 2. Retrieves the passkey from the vault
+ * 3. Extracts PRF extension inputs if present
+ * 4. Generates the WebAuthn assertion using PasskeyAuthenticator
+ * 5. Returns the assertion to the calling app
*
* Flow:
* - User selects a passkey from Credential Manager UI
* - This activity is launched with passkey details
- * - We generate assertion and return it immediately (no UI needed)
- * - Or show biometric prompt if required
+ * - Show biometric prompt to unlock vault (similar to registration flow)
+ * - After unlock: generate assertion and return it
*/
-class PasskeyAuthenticationActivity : Activity() {
+class PasskeyAuthenticationActivity : FragmentActivity() {
companion object {
private const val TAG = "PasskeyAuthentication"
}
+ private lateinit var vaultStore: VaultStore
+ private var providerRequest: ProviderGetCredentialRequest? = null
+
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
try {
- val providerRequest = PendingIntentHandler.retrieveProviderGetCredentialRequest(intent)
+ // Retrieve provider request
+ providerRequest = PendingIntentHandler.retrieveProviderGetCredentialRequest(intent)
if (providerRequest == null) {
Log.e(TAG, "No provider request found in intent")
setResult(RESULT_CANCELED)
@@ -49,9 +58,46 @@ class PasskeyAuthenticationActivity : Activity() {
return
}
- processAuthenticationRequest(providerRequest)
+ // Get or initialize VaultStore instance
+ vaultStore = VaultStore.getExistingInstance() ?: run {
+ Log.d(TAG, "VaultStore not initialized, initializing now...")
+ val keystoreProvider = AndroidKeystoreProvider(applicationContext) { this }
+ val storageProvider = AndroidStorageProvider(applicationContext)
+ VaultStore.getInstance(keystoreProvider, storageProvider)
+ }
+
+ // Show loading screen while biometric prompt is displayed
+ setContentView(R.layout.activity_loading)
+
+ // 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) {
+ Log.d(TAG, "Got decrypt key: ${result.length} bytes")
+ // Biometric authentication successful, unlock vault
+ vaultStore.initEncryptionKey(result)
+ vaultStore.unlockVault()
+
+ // Now process the authentication request
+ runOnUiThread {
+ processAuthenticationRequest()
+ }
+ }
+
+ override fun onError(e: Exception) {
+ Log.e(TAG, "Failed to retrieve encryption key", e)
+ runOnUiThread {
+ setResult(RESULT_CANCELED)
+ finish()
+ }
+ }
+ },
+ )
+ Log.d(TAG, "Waiting for biometric authentication...")
} catch (e: Exception) {
- Log.e(TAG, "Error processing authentication request", e)
+ Log.e(TAG, "Error in onCreate", e)
setResult(RESULT_CANCELED)
finish()
}
@@ -59,8 +105,15 @@ class PasskeyAuthenticationActivity : Activity() {
/**
* Process the passkey authentication request and generate assertion.
+ * Called after biometric authentication succeeds and vault is unlocked.
*/
- private fun processAuthenticationRequest(providerRequest: ProviderGetCredentialRequest) {
+ private fun processAuthenticationRequest() {
+ val providerRequest = this.providerRequest ?: run {
+ Log.e(TAG, "Provider request is null")
+ setResult(RESULT_CANCELED)
+ finish()
+ return
+ }
try {
// Extract passkey ID from intent
val passkeyIdString = intent.getStringExtra(
@@ -75,25 +128,10 @@ class PasskeyAuthenticationActivity : Activity() {
val passkeyId = UUID.fromString(passkeyIdString.uppercase())
- val vaultStore = VaultStore.getExistingInstance()
- if (vaultStore == null) {
- Log.e(TAG, "VaultStore not initialized")
- setResult(RESULT_CANCELED)
- finish()
- return
- }
-
- val db = try {
- val dbField = VaultStore::class.java.getDeclaredField("dbConnection")
- dbField.isAccessible = true
- dbField.get(vaultStore) as? android.database.sqlite.SQLiteDatabase
- } catch (e: Exception) {
- Log.e(TAG, "Cannot access database", e)
- null
- }
-
+ // Get database connection from vault (should be unlocked at this point)
+ val db = vaultStore.database
if (db == null) {
- Log.e(TAG, "Database not available")
+ Log.e(TAG, "Database not available - vault may not be unlocked")
setResult(RESULT_CANCELED)
finish()
return
diff --git a/apps/mobile-app/android/app/src/main/java/net/aliasvault/app/credentialprovider/PasskeyFormFragment.kt b/apps/mobile-app/android/app/src/main/java/net/aliasvault/app/credentialprovider/PasskeyFormFragment.kt
index 88f2de42f..995f3522d 100644
--- a/apps/mobile-app/android/app/src/main/java/net/aliasvault/app/credentialprovider/PasskeyFormFragment.kt
+++ b/apps/mobile-app/android/app/src/main/java/net/aliasvault/app/credentialprovider/PasskeyFormFragment.kt
@@ -313,6 +313,9 @@ class PasskeyFormFragment : Fragment() {
}
}
+ // Step 5: Update credential identity cache
+ updateCredentialIdentityCache()
+
// Build response
val credentialIdB64 = Helpers.bytesToBase64url(credentialId)
val attestationObjectB64 = Helpers.bytesToBase64url(passkeyResult.attestationObject)
@@ -512,6 +515,9 @@ class PasskeyFormFragment : Fragment() {
}
}
+ // Step 5: Update credential identity cache
+ updateCredentialIdentityCache()
+
// Build response (same as create flow)
val credentialIdB64 = Helpers.bytesToBase64url(credentialId)
val attestationObjectB64 = Helpers.bytesToBase64url(passkeyResult.attestationObject)
@@ -623,6 +629,24 @@ class PasskeyFormFragment : Fragment() {
}
}
+ /**
+ * Update credential identity cache after passkey creation/replacement.
+ */
+ private fun updateCredentialIdentityCache() {
+ try {
+ val credentials = vaultStore.getAllCredentials()
+ val db = vaultStore.database
+ if (db != null) {
+ val identityStore = CredentialIdentityStore.getInstance(requireContext())
+ identityStore.saveCredentialIdentities(credentials, vaultStore, db)
+ Log.d(TAG, "Updated credential identity cache")
+ }
+ } catch (e: Exception) {
+ Log.w(TAG, "Failed to update credential identity cache", e)
+ // Non-critical error, don't throw
+ }
+ }
+
/**
* Build clientDataJSON for WebAuthn create request.
*/
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 4499ad027..665f08786 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
@@ -8,10 +8,12 @@ import androidx.credentials.provider.PendingIntentHandler
import androidx.fragment.app.FragmentActivity
import net.aliasvault.app.R
import net.aliasvault.app.credentialprovider.models.PasskeyRegistrationViewModel
-import net.aliasvault.app.exceptions.VaultOperationException
import net.aliasvault.app.utils.Helpers
import net.aliasvault.app.vaultstore.VaultStore
import net.aliasvault.app.vaultstore.getPasskeysWithCredentialInfo
+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
/**
@@ -38,9 +40,13 @@ class PasskeyRegistrationActivity : FragmentActivity() {
super.onCreate(savedInstanceState)
try {
- // Initialize VaultStore
- vaultStore = VaultStore.getExistingInstance()
- ?: throw VaultOperationException("VaultStore not initialized")
+ // Get or initialize VaultStore instance
+ vaultStore = VaultStore.getExistingInstance() ?: run {
+ Log.d(TAG, "VaultStore not initialized, initializing now...")
+ val keystoreProvider = AndroidKeystoreProvider(applicationContext) { this }
+ val storageProvider = AndroidStorageProvider(applicationContext)
+ VaultStore.getInstance(keystoreProvider, storageProvider)
+ }
// Retrieve provider request
val providerRequest = PendingIntentHandler.retrieveProviderCreateCredentialRequest(intent)
@@ -94,8 +100,51 @@ class PasskeyRegistrationActivity : FragmentActivity() {
null
}
+ // Show loading screen first
+ setContentView(R.layout.activity_loading)
+
+ // 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) {
+ 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)
+ }
+ }
+
+ override fun onError(e: Exception) {
+ Log.e(TAG, "Failed to retrieve encryption key", e)
+ runOnUiThread {
+ finish()
+ }
+ }
+ },
+ )
+ Log.d(TAG, "Waiting for biometric authentication...")
+ } catch (e: Exception) {
+ Log.e(TAG, "Error in onCreate", e)
+ finish()
+ }
+ }
+
+ /**
+ * Proceed with passkey registration after biometric authentication.
+ */
+ private fun proceedWithPasskeyRegistration(savedInstanceState: Bundle?) {
+ try {
// Check for existing passkeys
val db = vaultStore.database
+ Log.d(TAG, "Db is not null?: ${db != null}")
+
if (db != null) {
viewModel.existingPasskeys = vaultStore.getPasskeysWithCredentialInfo(
rpId = viewModel.rpId,
@@ -120,7 +169,7 @@ class PasskeyRegistrationActivity : FragmentActivity() {
}
}
} catch (e: Exception) {
- Log.e(TAG, "Error in onCreate", e)
+ Log.e(TAG, "Error proceeding with passkey registration", e)
finish()
}
}
diff --git a/apps/mobile-app/android/app/src/main/java/net/aliasvault/app/nativevaultmanager/NativeVaultManager.kt b/apps/mobile-app/android/app/src/main/java/net/aliasvault/app/nativevaultmanager/NativeVaultManager.kt
index 66cecc7cc..d9c530f7c 100644
--- a/apps/mobile-app/android/app/src/main/java/net/aliasvault/app/nativevaultmanager/NativeVaultManager.kt
+++ b/apps/mobile-app/android/app/src/main/java/net/aliasvault/app/nativevaultmanager/NativeVaultManager.kt
@@ -1014,13 +1014,34 @@ class NativeVaultManager(reactContext: ReactApplicationContext) :
/**
* Register credential identities in the Native Autofill API cache.
+ * This stores passkey metadata so they can be shown without unlocking the vault.
* @param promise The promise to resolve.
*/
@ReactMethod
override fun registerCredentialIdentities(promise: Promise) {
- // Not required for Android as Android autofill queries AliasVault for credentials in realtime
- // and does not implement caching (in comparison to iOS which does).
- promise.resolve(null)
+ try {
+ // Get all credentials from the vault
+ val credentials = vaultStore.getAllCredentials()
+
+ // Get database connection
+ val db = vaultStore.database
+ if (db == null) {
+ Log.w(TAG, "Database not available - vault may be locked")
+ promise.resolve(null)
+ return
+ }
+
+ // Save credential identities to the identity store
+ val identityStore = net.aliasvault.app.credentialprovider.CredentialIdentityStore.getInstance(
+ reactApplicationContext,
+ )
+ identityStore.saveCredentialIdentities(credentials, vaultStore, db)
+
+ promise.resolve(null)
+ } catch (e: Exception) {
+ Log.e(TAG, "Error registering credential identities", e)
+ promise.reject("ERR_REGISTER_IDENTITIES", "Failed to register credential identities: ${e.message}", e)
+ }
}
// MARK: - Username Management
diff --git a/apps/mobile-app/android/app/src/main/java/net/aliasvault/app/vaultstore/VaultStore.kt b/apps/mobile-app/android/app/src/main/java/net/aliasvault/app/vaultstore/VaultStore.kt
index 32e61ba34..7109b50c9 100644
--- a/apps/mobile-app/android/app/src/main/java/net/aliasvault/app/vaultstore/VaultStore.kt
+++ b/apps/mobile-app/android/app/src/main/java/net/aliasvault/app/vaultstore/VaultStore.kt
@@ -197,6 +197,14 @@ class VaultStore(
}
}
+ /**
+ * Initialize the encryption key.
+ * @param encryptionKey The encryption key as a ByteArray
+ */
+ fun initEncryptionKey(base64EncryptionKey: String) {
+ this.encryptionKey = Base64.decode(base64EncryptionKey, Base64.NO_WRAP)
+ }
+
/**
* Get the encryption key.
* @param callback The callback to call when the key is retrieved
diff --git a/apps/mobile-app/android/app/src/main/java/net/aliasvault/app/vaultstore/keystoreprovider/AndroidKeystoreProvider.kt b/apps/mobile-app/android/app/src/main/java/net/aliasvault/app/vaultstore/keystoreprovider/AndroidKeystoreProvider.kt
index 7af643473..ef73264b3 100644
--- a/apps/mobile-app/android/app/src/main/java/net/aliasvault/app/vaultstore/keystoreprovider/AndroidKeystoreProvider.kt
+++ b/apps/mobile-app/android/app/src/main/java/net/aliasvault/app/vaultstore/keystoreprovider/AndroidKeystoreProvider.kt
@@ -208,104 +208,7 @@ class AndroidKeystoreProvider(
return@post
}
- // Check if we have a stored key
- val keyFile = File(context.filesDir, ENCRYPTED_KEY_FILE)
- if (!keyFile.exists()) {
- callback.onError(Exception("No encryption key found"))
- return@post
- }
- val encryptedKeyB64 = keyFile.readText()
-
- // Set up KeyStore
- val keyStore = KeyStore.getInstance("AndroidKeyStore")
- keyStore.load(null)
-
- // Check if key exists
- if (!keyStore.containsAlias(KEYSTORE_ALIAS)) {
- Log.e(TAG, "Keystore key not found")
- callback.onError(Exception("Keystore key not found"))
- return@post
- }
-
- // Get the key
- val secretKey = keyStore.getKey(KEYSTORE_ALIAS, null) as SecretKey
-
- // Create BiometricPrompt
- val promptInfo = BiometricPrompt.PromptInfo.Builder()
- .setTitle(context.getString(R.string.biometric_unlock_vault_title))
- .setSubtitle(context.getString(R.string.biometric_unlock_vault_subtitle))
- .setAllowedAuthenticators(
- BiometricManager.Authenticators.BIOMETRIC_STRONG or
- BiometricManager.Authenticators.DEVICE_CREDENTIAL,
- )
- .build()
-
- val biometricPrompt = BiometricPrompt(
- currentActivity,
- _executor,
- object : BiometricPrompt.AuthenticationCallback() {
- override fun onAuthenticationSucceeded(
- result: BiometricPrompt.AuthenticationResult,
- ) {
- try {
- // Get the cipher from the result
- val cipher = result.cryptoObject?.cipher ?: error("Cipher is null")
-
- // Decode combined data
- val combined = Base64.decode(encryptedKeyB64, Base64.NO_WRAP)
-
- // Extract IV and encrypted data
- val byteBuffer = ByteBuffer.wrap(combined)
-
- // GCM typically uses 12 bytes for IV
- val iv = ByteArray(12)
- byteBuffer.get(iv)
-
- // Get remaining bytes as ciphertext
- val encryptedBytes = ByteArray(byteBuffer.remaining())
- byteBuffer.get(encryptedBytes)
-
- // Decrypt the key
- val decryptedKey = cipher.doFinal(encryptedBytes)
-
- Log.d(TAG, "Encryption key retrieved successfully")
- callback.onSuccess(String(decryptedKey))
- } catch (e: Exception) {
- Log.e(TAG, "Error retrieving encryption key", e)
- callback.onError(e)
- }
- }
-
- override fun onAuthenticationError(
- errorCode: Int,
- errString: CharSequence,
- ) {
- Log.e(TAG, "Authentication error: $errString")
- callback.onError(Exception("Authentication error: $errString"))
- }
-
- override fun onAuthenticationFailed() {
- Log.e(TAG, "Authentication failed")
- }
- },
- )
-
- // Initialize cipher for decryption with IV from stored encrypted key
- val combined = Base64.decode(encryptedKeyB64, Base64.NO_WRAP)
- val byteBuffer = ByteBuffer.wrap(combined)
- val iv = ByteArray(12)
- byteBuffer.get(iv)
-
- val cipher = Cipher.getInstance(
- "${KeyProperties.KEY_ALGORITHM_AES}/" +
- "${KeyProperties.BLOCK_MODE_GCM}/" +
- KeyProperties.ENCRYPTION_PADDING_NONE,
- )
- val spec = GCMParameterSpec(128, iv)
- cipher.init(Cipher.DECRYPT_MODE, secretKey, spec)
-
- // Show biometric prompt
- biometricPrompt.authenticate(promptInfo, BiometricPrompt.CryptoObject(cipher))
+ retrieveKeyInternalLogic(currentActivity, callback)
} catch (e: Exception) {
Log.e(TAG, "Error in biometric key retrieval", e)
callback.onError(e)
@@ -313,6 +216,17 @@ class AndroidKeystoreProvider(
}
}
+ override fun retrieveKeyExternal(activity: FragmentActivity, callback: KeystoreOperationCallback) {
+ _mainHandler.post {
+ try {
+ retrieveKeyInternalLogic(activity, callback)
+ } catch (e: Exception) {
+ Log.e(TAG, "Error in external biometric key retrieval", e)
+ callback.onError(e)
+ }
+ }
+ }
+
override fun clearKeys() {
try {
// Clear from private file storage
@@ -334,4 +248,113 @@ class AndroidKeystoreProvider(
Log.e(TAG, "Error clearing keys", e)
}
}
+
+ private fun retrieveKeyInternalLogic(
+ currentActivity: FragmentActivity,
+ callback: KeystoreOperationCallback,
+ ) {
+ // Check if we have a stored key
+ val keyFile = File(context.filesDir, ENCRYPTED_KEY_FILE)
+ if (!keyFile.exists()) {
+ Log.e(TAG, "No encryption key found")
+ callback.onError(Exception("No encryption key found"))
+ return
+ }
+ val encryptedKeyB64 = keyFile.readText()
+
+ // Set up KeyStore
+ val keyStore = KeyStore.getInstance("AndroidKeyStore")
+ keyStore.load(null)
+
+ // Check if key exists
+ if (!keyStore.containsAlias(KEYSTORE_ALIAS)) {
+ Log.e(TAG, "Keystore key not found")
+ callback.onError(Exception("Keystore key not found"))
+ return
+ }
+
+ // Get the key
+ val secretKey = keyStore.getKey(KEYSTORE_ALIAS, null) as SecretKey
+
+ // Initialize cipher for decryption with IV from stored encrypted key
+ val combined = Base64.decode(encryptedKeyB64, Base64.NO_WRAP)
+ val byteBuffer = ByteBuffer.wrap(combined)
+ val iv = ByteArray(12)
+ byteBuffer.get(iv)
+
+ val cipher = Cipher.getInstance(
+ "${KeyProperties.KEY_ALGORITHM_AES}/" +
+ "${KeyProperties.BLOCK_MODE_GCM}/" +
+ KeyProperties.ENCRYPTION_PADDING_NONE,
+ )
+ val spec = GCMParameterSpec(128, iv)
+ cipher.init(Cipher.DECRYPT_MODE, secretKey, spec)
+
+ // Create BiometricPrompt
+ val promptInfo = BiometricPrompt.PromptInfo.Builder()
+ .setTitle(context.getString(R.string.biometric_unlock_vault_title))
+ .setSubtitle(context.getString(R.string.biometric_unlock_vault_subtitle))
+ .setAllowedAuthenticators(
+ BiometricManager.Authenticators.BIOMETRIC_STRONG or
+ BiometricManager.Authenticators.DEVICE_CREDENTIAL,
+ )
+ .build()
+
+ val biometricPrompt = BiometricPrompt(
+ currentActivity,
+ _executor,
+ object : BiometricPrompt.AuthenticationCallback() {
+ override fun onAuthenticationSucceeded(
+ result: BiometricPrompt.AuthenticationResult,
+ ) {
+ try {
+ // Get the cipher from the result
+ val cipher = result.cryptoObject?.cipher ?: error("Cipher is null")
+
+ // Decode combined data
+ val combined = Base64.decode(encryptedKeyB64, Base64.NO_WRAP)
+
+ // Extract IV and encrypted data
+ val byteBuffer = ByteBuffer.wrap(combined)
+
+ // GCM typically uses 12 bytes for IV
+ val iv = ByteArray(12)
+ byteBuffer.get(iv)
+
+ // Get remaining bytes as ciphertext
+ val encryptedBytes = ByteArray(byteBuffer.remaining())
+ byteBuffer.get(encryptedBytes)
+
+ // Decrypt the key
+ val decryptedKey = cipher.doFinal(encryptedBytes)
+
+ Log.d(TAG, "Encryption key retrieved successfully")
+ callback.onSuccess(String(decryptedKey))
+ } catch (e: Exception) {
+ Log.e(TAG, "Error retrieving encryption key", e)
+ callback.onError(
+ Exception("Failed to retrieve encryption key: ${e.message}"),
+ )
+ }
+ }
+
+ override fun onAuthenticationError(
+ errorCode: Int,
+ errString: CharSequence,
+ ) {
+ Log.e(TAG, "Authentication error: $errorCode - $errString")
+ callback.onError(
+ Exception("Authentication error: $errString (code: $errorCode)"),
+ )
+ }
+
+ override fun onAuthenticationFailed() {
+ Log.e(TAG, "Authentication failed")
+ }
+ },
+ )
+
+ // Show biometric prompt
+ biometricPrompt.authenticate(promptInfo, BiometricPrompt.CryptoObject(cipher))
+ }
}
diff --git a/apps/mobile-app/android/app/src/main/java/net/aliasvault/app/vaultstore/keystoreprovider/KeystoreProvider.kt b/apps/mobile-app/android/app/src/main/java/net/aliasvault/app/vaultstore/keystoreprovider/KeystoreProvider.kt
index 2ec87126a..5f5d4e682 100644
--- a/apps/mobile-app/android/app/src/main/java/net/aliasvault/app/vaultstore/keystoreprovider/KeystoreProvider.kt
+++ b/apps/mobile-app/android/app/src/main/java/net/aliasvault/app/vaultstore/keystoreprovider/KeystoreProvider.kt
@@ -1,5 +1,7 @@
package net.aliasvault.app.vaultstore.keystoreprovider
+import androidx.fragment.app.FragmentActivity
+
/**
* Interface for keystore providers that handle secure storage of encryption keys with biometric protection.
* This allows for different implementations for real devices and testing.
@@ -26,6 +28,14 @@ interface KeystoreProvider {
*/
fun retrieveKey(callback: KeystoreOperationCallback)
+ /**
+ * Retrieve an encryption key using biometric authentication from outside of React Native context.
+ * This is used by the passkey flows.
+ * @param activity The activity to show the biometric prompt on
+ * @param callback The callback to handle the result asynchronously
+ */
+ fun retrieveKeyExternal(activity: FragmentActivity, callback: KeystoreOperationCallback)
+
/**
* Clear all stored keys.
*/
diff --git a/apps/mobile-app/android/app/src/main/java/net/aliasvault/app/vaultstore/keystoreprovider/TestKeystoreProvider.kt b/apps/mobile-app/android/app/src/main/java/net/aliasvault/app/vaultstore/keystoreprovider/TestKeystoreProvider.kt
index 599d53ecc..6829801a0 100644
--- a/apps/mobile-app/android/app/src/main/java/net/aliasvault/app/vaultstore/keystoreprovider/TestKeystoreProvider.kt
+++ b/apps/mobile-app/android/app/src/main/java/net/aliasvault/app/vaultstore/keystoreprovider/TestKeystoreProvider.kt
@@ -1,5 +1,7 @@
package net.aliasvault.app.vaultstore.keystoreprovider
+import androidx.fragment.app.FragmentActivity
+
/**
* Test implementation of the keystore provider that does nothing and always returns false for biometric availability.
* This is used for testing when biometrics are not available.
@@ -19,6 +21,10 @@ class TestKeystoreProvider : KeystoreProvider {
callback.onError(Exception("No key found (test)"))
}
+ override fun retrieveKeyExternal(activity: FragmentActivity, callback: KeystoreOperationCallback) {
+ callback.onError(Exception("No key found (test)"))
+ }
+
override fun clearKeys() {
// Do nothing in test implementation
}
diff --git a/apps/mobile-app/android/app/src/main/res/layout/activity_loading.xml b/apps/mobile-app/android/app/src/main/res/layout/activity_loading.xml
new file mode 100644
index 000000000..42a4d1577
--- /dev/null
+++ b/apps/mobile-app/android/app/src/main/res/layout/activity_loading.xml
@@ -0,0 +1,13 @@
+<?xml version="1.0" encoding="utf-8"?>
+<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
+ android:layout_width="match_parent"
+ android:layout_height="match_parent"
+ android:background="@color/av_background">
+
+ <include
+ layout="@layout/loading_indicator"
+ android:layout_width="wrap_content"
+ android:layout_height="wrap_content"
+ android:layout_centerInParent="true" />
+
+</RelativeLayout>