Skip to content

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

Commit created passkey to vault (#520)

Leendert de Borst30d223aba6fc
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 354ed0c29..875e4a264 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
@@ -54,12 +54,16 @@ class PasskeyRegistrationActivity : Activity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
+ Log.d(TAG, "PasskeyRegistrationActivity onCreate called")
+
try {
// Initialize VaultStore and WebApiService
vaultStore = VaultStore.getExistingInstance()
?: throw Exception("VaultStore not initialized")
webApiService = WebApiService(this)
+ Log.d(TAG, "VaultStore and WebApiService initialized")
+
// Retrieve provider request
val providerRequest = PendingIntentHandler.retrieveProviderCreateCredentialRequest(intent)
if (providerRequest == null) {
@@ -69,6 +73,8 @@ class PasskeyRegistrationActivity : Activity() {
return
}
+ Log.d(TAG, "Provider request retrieved successfully")
+
// Extract parameters from intent
val requestJson = intent.getStringExtra(EXTRA_CREATE_REQUEST_JSON) ?: ""
val rpId = intent.getStringExtra(EXTRA_CREATE_RP_ID) ?: ""
@@ -76,8 +82,10 @@ class PasskeyRegistrationActivity : Activity() {
val userDisplayName = intent.getStringExtra(EXTRA_CREATE_USER_DISPLAY_NAME)
val userIdB64 = intent.getStringExtra(EXTRA_CREATE_USER_ID)
+ Log.d(TAG, "Parameters: rpId=$rpId, userName=$userName, userDisplayName=$userDisplayName")
+
if (rpId.isEmpty() || requestJson.isEmpty()) {
- Log.e(TAG, "Missing required parameters")
+ Log.e(TAG, "Missing required parameters: rpId=$rpId, requestJson length=${requestJson.length}")
setResult(RESULT_CANCELED)
finish()
return
@@ -95,6 +103,8 @@ class PasskeyRegistrationActivity : Activity() {
null
}
+ Log.d(TAG, "Starting passkey creation coroutine")
+
// Start passkey creation in coroutine
CoroutineScope(Dispatchers.Main).launch {
createPasskey(
@@ -144,9 +154,9 @@ class PasskeyRegistrationActivity : Activity() {
val requestObj = JSONObject(requestJson)
val challenge = requestObj.optString("challenge", "")
- // Construct origin from calling app package name
- val packageName = providerRequest.callingAppInfo.packageName
- val origin = "android:apk-key-hash:$packageName"
+ // Construct origin from calling app signing certificate
+ val origin = appInfoToOrigin(providerRequest.callingAppInfo)
+ Log.d(TAG, "Origin: $origin")
// Build clientDataJSON
val clientDataJson =
@@ -188,34 +198,16 @@ class PasskeyRegistrationActivity : Activity() {
isDeleted = false,
)
- // Store in database
- 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)
- throw Exception("Database not available")
- }
-
- if (db == null) {
- throw Exception("Database not available")
- }
-
- db.beginTransaction()
- try {
- vaultStore.createCredentialWithPasskey(
- rpId = rpId,
- userName = userName,
- displayName = displayName,
- passkey = passkey,
- logo = logo,
- db = db,
- )
- db.setTransactionSuccessful()
- } finally {
- db.endTransaction()
- }
+ // Store in database (transaction handled internally by VaultStore)
+ Log.d(TAG, "Saving passkey to vault...")
+ vaultStore.createCredentialWithPasskey(
+ rpId = rpId,
+ userName = userName,
+ displayName = displayName,
+ passkey = passkey,
+ logo = logo,
+ )
+ Log.d(TAG, "Passkey saved successfully")
// Upload vault changes to server
try {
@@ -270,13 +262,18 @@ class PasskeyRegistrationActivity : Activity() {
}
}
+ Log.d(TAG, "Response JSON: ${responseJson.toString(2)}")
+
val response = CreatePublicKeyCredentialResponse(responseJson.toString())
withContext(Dispatchers.Main) {
val resultIntent = Intent()
try {
+ Log.d(TAG, "Setting credential response...")
PendingIntentHandler.setCreateCredentialResponse(resultIntent, response)
+ Log.d(TAG, "Credential response set successfully")
setResult(RESULT_OK, resultIntent)
+ Log.d(TAG, "Result set to RESULT_OK")
} catch (e: Exception) {
Log.e(TAG, "Error setting credential response", e)
setResult(RESULT_CANCELED)
@@ -350,4 +347,15 @@ class PasskeyRegistrationActivity : Activity() {
return android.util.Base64.decode(base64, android.util.Base64.NO_WRAP)
}
+
+ /**
+ * Compute the origin from CallingAppInfo
+ * Format: android:apk-key-hash:<base64-encoded-sha256-of-signing-cert>
+ */
+ private fun appInfoToOrigin(info: androidx.credentials.provider.CallingAppInfo): String {
+ val cert = info.signingInfo.apkContentsSigners[0].toByteArray()
+ val md = MessageDigest.getInstance("SHA-256")
+ val certHash = md.digest(cert)
+ return "android:apk-key-hash:${base64urlEncode(certHash)}"
+ }
}
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 4c466602b..ec0c98835 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
@@ -106,6 +106,13 @@ class VaultStore(
*/
private var dbConnection: SQLiteDatabase? = null
+ /**
+ * Internal accessor for database connection
+ * Used by extension functions to access the database
+ */
+ internal val database: SQLiteDatabase?
+ get() = dbConnection
+
/**
* The auto-lock handler.
*/
@@ -995,26 +1002,46 @@ class VaultStore(
return null
}
+ // Normalize milliseconds to exactly 3 digits
+ // Handles: 2025-10-20 13:48:10.4 -> 2025-10-20 13:48:10.400
+ // 1992-10-21T23:49:44.336Z -> 1992-10-21T23:49:44.336Z (unchanged)
+ // 2025-10-20 13:48:10 -> 2025-10-20 13:48:10 (unchanged)
+ val normalizedDate = dateString.replace(
+ Regex("""(\d{2}:\d{2}:\d{2})\.(\d{1,2})(?=[TZ\s]|$)"""),
+ ) { matchResult ->
+ val base = matchResult.groupValues[1]
+ val millis = matchResult.groupValues[2].padEnd(3, '0')
+ "$base.$millis"
+ }
+
+ // Try all supported formats
val formats = listOf(
+ // ISO 8601 formats (most common from server)
SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'", Locale.US).apply {
timeZone = TimeZone.getTimeZone("UTC")
},
+ SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss'Z'", Locale.US).apply {
+ timeZone = TimeZone.getTimeZone("UTC")
+ },
+ // SQLite formats (local storage)
SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS", Locale.US).apply {
timeZone = TimeZone.getTimeZone("UTC")
},
+ SimpleDateFormat("yyyy-MM-dd HH:mm:ss", Locale.US).apply {
+ timeZone = TimeZone.getTimeZone("UTC")
+ },
)
for (format in formats) {
try {
- return format.parse(dateString)
+ return format.parse(normalizedDate)
} catch (e: Exception) {
- // Log the parsing error for this format
- Log.d(TAG, "Failed to parse date '$dateString' with format '${format.toPattern()}': ${e.message}")
+ // Try next format
continue
}
}
- Log.e(TAG, "Error parsing date: $dateString")
+ Log.e(TAG, "Error parsing date: $dateString (normalized: $normalizedDate)")
return null
}
diff --git a/apps/mobile-app/android/app/src/main/java/net/aliasvault/app/vaultstore/VaultStorePasskey.kt b/apps/mobile-app/android/app/src/main/java/net/aliasvault/app/vaultstore/VaultStorePasskey.kt
index 7891a3045..bdb4b79dc 100644
--- a/apps/mobile-app/android/app/src/main/java/net/aliasvault/app/vaultstore/VaultStorePasskey.kt
+++ b/apps/mobile-app/android/app/src/main/java/net/aliasvault/app/vaultstore/VaultStorePasskey.kt
@@ -218,8 +218,8 @@ fun VaultStore.insertPasskey(passkey: Passkey, db: SQLiteDatabase) {
}
/**
- * Create a credential with a passkey
- * This creates a minimal credential record and links the passkey to it
+ * Create a new credential with an associated passkey
+ * This method handles the database transaction internally
*/
fun VaultStore.createCredentialWithPasskey(
rpId: String,
@@ -227,114 +227,125 @@ fun VaultStore.createCredentialWithPasskey(
displayName: String,
passkey: Passkey,
logo: ByteArray? = null,
- db: SQLiteDatabase,
): Credential {
- val credentialId = passkey.parentCredentialId
- val now = Date()
- val timestamp = formatDateForDatabase(now)
+ val db = database ?: throw IllegalStateException("Vault not unlocked")
- // Create a minimal service for the RP
- val serviceId = UUID.randomUUID()
- val serviceInsert = """
- INSERT INTO Services (Id, Name, Url, Logo, CreatedAt, UpdatedAt, IsDeleted)
- VALUES (?, ?, ?, ?, ?, ?, ?)
- """.trimIndent()
-
- db.execSQL(
- serviceInsert,
- arrayOf(
- serviceId.toString().uppercase(),
- displayName,
- "https://$rpId",
- logo,
- timestamp,
- timestamp,
- 0,
- ),
- )
+ db.beginTransaction()
+ try {
+ val credentialId = passkey.parentCredentialId
+ val now = Date()
+ val timestamp = formatDateForDatabase(now)
+
+ // Create a minimal service for the RP
+ val serviceId = UUID.randomUUID()
+ val serviceInsert = """
+ INSERT INTO Services (Id, Name, Url, Logo, CreatedAt, UpdatedAt, IsDeleted)
+ VALUES (?, ?, ?, ?, ?, ?, ?)
+ """.trimIndent()
- // Create a minimal alias with empty fields and default birthdate
- val aliasId = UUID.randomUUID()
- val aliasInsert = """
- INSERT INTO Aliases (Id, FirstName, LastName, NickName, BirthDate, Gender, Email,
- CreatedAt, UpdatedAt, IsDeleted)
- VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
- """.trimIndent()
+ db.execSQL(
+ serviceInsert,
+ arrayOf(
+ serviceId.toString().uppercase(),
+ displayName,
+ "https://$rpId",
+ logo,
+ timestamp,
+ timestamp,
+ 0,
+ ),
+ )
- db.execSQL(
- aliasInsert,
- arrayOf(
- aliasId.toString().uppercase(),
- "",
- "",
- "",
- formatDateForDatabase(MIN_DATE),
- "",
- "",
- timestamp,
- timestamp,
- 0,
- ),
- )
+ // Create a minimal alias with empty fields and default birthdate
+ val aliasId = UUID.randomUUID()
+ val aliasInsert = """
+ INSERT INTO Aliases (Id, FirstName, LastName, NickName, BirthDate, Gender, Email,
+ CreatedAt, UpdatedAt, IsDeleted)
+ VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
+ """.trimIndent()
- // Create the credential with the alias
- val credentialInsert = """
- INSERT INTO Credentials (Id, ServiceId, AliasId, Username, Notes, CreatedAt, UpdatedAt, IsDeleted)
- VALUES (?, ?, ?, ?, ?, ?, ?, ?)
- """.trimIndent()
+ db.execSQL(
+ aliasInsert,
+ arrayOf(
+ aliasId.toString().uppercase(),
+ "",
+ "",
+ "",
+ formatDateForDatabase(MIN_DATE),
+ "",
+ "",
+ timestamp,
+ timestamp,
+ 0,
+ ),
+ )
- db.execSQL(
- credentialInsert,
- arrayOf(
- credentialId.toString().uppercase(),
- serviceId.toString().uppercase(),
- aliasId.toString().uppercase(),
- userName,
- null,
- timestamp,
- timestamp,
- 0,
- ),
- )
+ // Create the credential with the alias
+ val credentialInsert = """
+ INSERT INTO Credentials (Id, ServiceId, AliasId, Username, Notes, CreatedAt, UpdatedAt, IsDeleted)
+ VALUES (?, ?, ?, ?, ?, ?, ?, ?)
+ """.trimIndent()
- // Insert the passkey
- insertPasskey(passkey, db)
+ db.execSQL(
+ credentialInsert,
+ arrayOf(
+ credentialId.toString().uppercase(),
+ serviceId.toString().uppercase(),
+ aliasId.toString().uppercase(),
+ userName,
+ null,
+ timestamp,
+ timestamp,
+ 0,
+ ),
+ )
- // Return the credential
- val service = Service(
- id = serviceId,
- name = displayName,
- url = "https://$rpId",
- logo = logo,
- createdAt = now,
- updatedAt = now,
- isDeleted = false,
- )
+ // Insert the passkey
+ insertPasskey(passkey, db)
+
+ // Return the credential
+ val service = Service(
+ id = serviceId,
+ name = displayName,
+ url = "https://$rpId",
+ logo = logo,
+ createdAt = now,
+ updatedAt = now,
+ isDeleted = false,
+ )
- val alias = Alias(
- id = aliasId,
- gender = "",
- firstName = "",
- lastName = "",
- nickName = "",
- birthDate = MIN_DATE,
- email = "",
- createdAt = now,
- updatedAt = now,
- isDeleted = false,
- )
+ val alias = Alias(
+ id = aliasId,
+ gender = "",
+ firstName = "",
+ lastName = "",
+ nickName = "",
+ birthDate = MIN_DATE,
+ email = "",
+ createdAt = now,
+ updatedAt = now,
+ isDeleted = false,
+ )
- return Credential(
- id = credentialId,
- alias = alias,
- service = service,
- username = userName,
- notes = null,
- password = null,
- createdAt = now,
- updatedAt = now,
- isDeleted = false,
- )
+ // Commit transaction and persist to encrypted vault file
+ commitTransaction()
+
+ return Credential(
+ id = credentialId,
+ alias = alias,
+ service = service,
+ username = userName,
+ notes = null,
+ password = null,
+ createdAt = now,
+ updatedAt = now,
+ isDeleted = false,
+ )
+ } catch (e: Exception) {
+ // Rollback on error
+ db.endTransaction()
+ throw e
+ }
}
/**