Skip to content

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

Use RustItemMatcher for finding mergeable passkey items (#1473)

Leendert de Borst18164fa8681d
diff --git a/apps/mobile-app/android/app/src/main/java/net/aliasvault/app/autofill/utils/RustItemMatcher.kt b/apps/mobile-app/android/app/src/main/java/net/aliasvault/app/autofill/utils/RustItemMatcher.kt
index 0b12c8884..2020c9a65 100644
--- a/apps/mobile-app/android/app/src/main/java/net/aliasvault/app/autofill/utils/RustItemMatcher.kt
+++ b/apps/mobile-app/android/app/src/main/java/net/aliasvault/app/autofill/utils/RustItemMatcher.kt
@@ -3,6 +3,7 @@ package net.aliasvault.app.autofill.utils
import android.util.Log
import net.aliasvault.app.rustcore.JnaInitializer
import net.aliasvault.app.vaultstore.models.Item
+import net.aliasvault.app.vaultstore.repositories.ItemWithCredentialInfo
import org.json.JSONArray
import org.json.JSONObject
@@ -12,6 +13,22 @@ import org.json.JSONObject
object RustItemMatcher {
private const val TAG = "RustItemMatcher"
+ /**
+ * Matching mode for credential filtering.
+ *
+ * @property value The string value used in the Rust API.
+ */
+ enum class MatchingMode(val value: String) {
+ /** Default matching mode - uses subdomain matching. */
+ DEFAULT("default"),
+
+ /** Exact URL matching only - no subdomain matching. */
+ URL_EXACT("url_exact"),
+
+ /** Subdomain matching - matches subdomains and root domains. */
+ URL_SUBDOMAIN("url_subdomain"),
+ }
+
init {
// Ensure JNA is initialized before any UniFFI calls
JnaInitializer.ensureInitialized()
@@ -86,4 +103,83 @@ object RustItemMatcher {
return items
}
}
+
+ /**
+ * Filter ItemWithCredentialInfo items based on rpId using the Rust core credential matcher.
+ * Used during passkey registration to find existing credentials that can have a passkey merged into them.
+ *
+ * @param items List of items to filter (without passkeys).
+ * @param rpId The relying party identifier (domain) to match against.
+ * @param rpName The relying party name (used for title matching fallback).
+ * @param matchingMode The matching mode to use (default: URL_SUBDOMAIN).
+ * @return List of items that match the rpId, in priority order.
+ */
+ fun filterItemsForPasskeyMerge(
+ items: List<ItemWithCredentialInfo>,
+ rpId: String,
+ rpName: String? = null,
+ matchingMode: MatchingMode = MatchingMode.URL_SUBDOMAIN,
+ ): List<ItemWithCredentialInfo> {
+ // Early return for empty rpId or items
+ if (rpId.isEmpty() || items.isEmpty()) {
+ return emptyList()
+ }
+
+ try {
+ // Convert items to JSON format expected by Rust
+ val rustCredentials = JSONArray()
+ val itemMap = mutableMapOf<String, ItemWithCredentialInfo>()
+
+ for (item in items) {
+ val idString = item.itemId.toString()
+ val urlsArray = JSONArray()
+ item.urls.forEach { urlsArray.put(it) }
+
+ val credJson = JSONObject().apply {
+ put("Id", idString)
+ put("ItemName", item.serviceName ?: JSONObject.NULL)
+ put("ItemUrls", urlsArray)
+ put("Username", item.username ?: JSONObject.NULL)
+ }
+ rustCredentials.put(credJson)
+ itemMap[idString] = item
+ }
+
+ // Prepare input JSON for Rust
+ // Use https:// prefix for the rpId to match URL format
+ val input = JSONObject().apply {
+ put("credentials", rustCredentials)
+ put("current_url", "https://$rpId")
+ put("page_title", rpName ?: "")
+ put("matching_mode", matchingMode.value)
+ }
+
+ // Call Rust via UniFFI
+ val outputJson = uniffi.aliasvault_core.filterCredentialsJson(input.toString())
+
+ // Parse output
+ val output = JSONObject(outputJson)
+ val matchedIds = output.getJSONArray("matched_ids")
+
+ // If no matches found, return empty list
+ if (matchedIds.length() == 0) {
+ return emptyList()
+ }
+
+ // Convert matched IDs back to items, maintaining Rust's priority order
+ val result = mutableListOf<ItemWithCredentialInfo>()
+ for (i in 0 until matchedIds.length()) {
+ val id = matchedIds.getString(i)
+ itemMap[id]?.let {
+ result.add(it)
+ }
+ }
+
+ return result
+ } catch (e: Exception) {
+ Log.e(TAG, "Error filtering items for passkey merge: ${e.message}", e)
+ // Return empty list on error
+ return emptyList()
+ }
+ }
}
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 4f2356567..f6d85c812 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
@@ -221,9 +221,11 @@ class PasskeyRegistrationActivity : FragmentActivity() {
)
// Get existing Items without passkeys (can have passkey merged into them)
+ // Note: Don't filter by userName here - we want to show all matching items
+ // regardless of username so user can choose which item to merge into
viewModel.existingItemsWithoutPasskey = vaultStore.getItemsWithoutPasskeyForRpId(
rpId = viewModel.rpId,
- userName = viewModel.userName,
+ rpName = viewModel.rpName,
)
}
diff --git a/apps/mobile-app/android/app/src/main/java/net/aliasvault/app/vaultstore/VaultPasskey.kt b/apps/mobile-app/android/app/src/main/java/net/aliasvault/app/vaultstore/VaultPasskey.kt
index 91d45f922..084e928c6 100644
--- a/apps/mobile-app/android/app/src/main/java/net/aliasvault/app/vaultstore/VaultPasskey.kt
+++ b/apps/mobile-app/android/app/src/main/java/net/aliasvault/app/vaultstore/VaultPasskey.kt
@@ -60,14 +60,16 @@ class VaultPasskey(
* Used for finding existing credentials that could have a passkey added to them.
*
* @param rpId The relying party identifier to match against the login URL.
+ * @param rpName The relying party name (used for title matching fallback).
* @param userName Optional username to filter by.
* @return List of ItemWithCredentialInfo objects representing Items without passkeys.
*/
fun getItemsWithoutPasskeyForRpId(
rpId: String,
+ rpName: String? = null,
userName: String? = null,
): List<ItemWithCredentialInfo> {
- return passkeyRepository.getItemsWithoutPasskeyForRpId(rpId, userName)
+ return passkeyRepository.getItemsWithoutPasskeyForRpId(rpId, rpName, userName)
}
/**
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 64c01e1b9..921835a5c 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
@@ -747,9 +747,10 @@ class VaultStore(
*/
fun getItemsWithoutPasskeyForRpId(
rpId: String,
+ rpName: String? = null,
userName: String? = null,
): List<net.aliasvault.app.vaultstore.repositories.ItemWithCredentialInfo> {
- return passkey.getItemsWithoutPasskeyForRpId(rpId, userName)
+ return passkey.getItemsWithoutPasskeyForRpId(rpId, rpName, userName)
}
/**
diff --git a/apps/mobile-app/android/app/src/main/java/net/aliasvault/app/vaultstore/repositories/PasskeyRepository.kt b/apps/mobile-app/android/app/src/main/java/net/aliasvault/app/vaultstore/repositories/PasskeyRepository.kt
index 1b95fdd29..c0e136800 100644
--- a/apps/mobile-app/android/app/src/main/java/net/aliasvault/app/vaultstore/repositories/PasskeyRepository.kt
+++ b/apps/mobile-app/android/app/src/main/java/net/aliasvault/app/vaultstore/repositories/PasskeyRepository.kt
@@ -2,6 +2,7 @@ package net.aliasvault.app.vaultstore.repositories
import android.database.Cursor
import android.util.Log
+import net.aliasvault.app.autofill.utils.RustItemMatcher
import net.aliasvault.app.utils.DateHelpers
import net.aliasvault.app.vaultstore.VaultDatabase
import net.aliasvault.app.vaultstore.models.FieldKey
@@ -490,26 +491,21 @@ class PasskeyRepository(database: VaultDatabase) : BaseRepository(database) {
}
/**
- * Get Items that match an rpId but don't have a passkey yet.
- * Used for finding existing credentials that could have a passkey added to them.
+ * Get ALL Login items that don't have a passkey yet (no URL filtering).
+ * Used with RustCredentialMatcher for intelligent, cross-platform consistent filtering.
*
- * @param rpId The relying party identifier to match against the login URL.
- * @param userName Optional username to filter by.
- * @return List of ItemWithCredentialInfo objects representing Items without passkeys.
+ * @return List of ItemWithCredentialInfo objects with all URLs.
*/
- fun getItemsWithoutPasskeyForRpId(
- rpId: String,
- userName: String? = null,
- ): List<ItemWithCredentialInfo> {
+ fun getAllItemsWithoutPasskey(): List<ItemWithCredentialInfo> {
val db = database.dbConnection ?: return emptyList()
val query = """
SELECT i.Id, i.Name, i.CreatedAt, i.UpdatedAt,
- fv_url.Value as Url,
+ GROUP_CONCAT(DISTINCT fv_url.Value) as Urls,
fv_username.Value as Username,
fv_password.Value as Password
FROM Items i
- INNER JOIN FieldValues fv_url ON fv_url.ItemId = i.Id
+ LEFT JOIN FieldValues fv_url ON fv_url.ItemId = i.Id
AND fv_url.FieldKey = ?
AND fv_url.IsDeleted = 0
LEFT JOIN FieldValues fv_username ON fv_username.ItemId = i.Id
@@ -521,18 +517,14 @@ class PasskeyRepository(database: VaultDatabase) : BaseRepository(database) {
WHERE i.IsDeleted = 0
AND i.DeletedAt IS NULL
AND i.ItemType = 'Login'
- AND (LOWER(fv_url.Value) LIKE ? OR LOWER(fv_url.Value) LIKE ?)
AND NOT EXISTS (
SELECT 1 FROM Passkeys p
WHERE p.ItemId = i.Id AND p.IsDeleted = 0
)
+ GROUP BY i.Id
ORDER BY i.UpdatedAt DESC
""".trimIndent()
- val rpIdLower = rpId.lowercase()
- val urlPattern1 = "%$rpIdLower%"
- val urlPattern2 = "%${rpIdLower.replace("www.", "")}%"
-
val results = mutableListOf<ItemWithCredentialInfo>()
val cursor = db.query(
query,
@@ -540,8 +532,6 @@ class PasskeyRepository(database: VaultDatabase) : BaseRepository(database) {
FieldKey.LOGIN_URL,
FieldKey.LOGIN_USERNAME,
FieldKey.LOGIN_PASSWORD,
- urlPattern1,
- urlPattern2,
),
)
@@ -551,25 +541,22 @@ class PasskeyRepository(database: VaultDatabase) : BaseRepository(database) {
val itemName = if (!it.isNull(1)) it.getString(1) else null
val itemCreatedAt = if (!it.isNull(2)) it.getString(2) else null
val itemUpdatedAt = if (!it.isNull(3)) it.getString(3) else null
- val url = if (!it.isNull(4)) it.getString(4) else null
+ val urlsString = if (!it.isNull(4)) it.getString(4) else null
val itemUsername = if (!it.isNull(5)) it.getString(5) else null
val hasPassword = !it.isNull(6) && it.getString(6).isNotEmpty()
- // Filter by username if provided
- if (userName != null && itemUsername != userName) {
- continue
- }
-
try {
val itemId = UUID.fromString(itemIdString)
val createdAt = DateHelpers.parseDateString(itemCreatedAt ?: "") ?: MIN_DATE
val updatedAt = DateHelpers.parseDateString(itemUpdatedAt ?: "") ?: MIN_DATE
+ val urls = urlsString?.split(",")?.filter { it.isNotEmpty() } ?: emptyList()
results.add(
ItemWithCredentialInfo(
itemId = itemId,
serviceName = itemName,
- url = url,
+ url = urls.firstOrNull(),
+ urls = urls,
username = itemUsername,
hasPassword = hasPassword,
createdAt = createdAt,
@@ -585,6 +572,34 @@ class PasskeyRepository(database: VaultDatabase) : BaseRepository(database) {
return results
}
+ /**
+ * Get Items that match an rpId but don't have a passkey yet.
+ * Uses the Rust credential matcher for consistent cross-platform matching logic.
+ *
+ * @param rpId The relying party identifier to match against.
+ * @param rpName The relying party name (used for title matching fallback).
+ * @param userName Optional username to filter by.
+ * @return List of ItemWithCredentialInfo objects representing Items without passkeys.
+ */
+ fun getItemsWithoutPasskeyForRpId(
+ rpId: String,
+ rpName: String? = null,
+ userName: String? = null,
+ ): List<ItemWithCredentialInfo> {
+ // Get all items without passkeys
+ val allItems = getAllItemsWithoutPasskey()
+
+ // Use Rust item matcher for intelligent filtering
+ var matchedItems = RustItemMatcher.filterItemsForPasskeyMerge(allItems, rpId, rpName)
+
+ // Apply optional username filter
+ if (userName != null) {
+ matchedItems = matchedItems.filter { it.username == userName }
+ }
+
+ return matchedItems
+ }
+
/**
* Get all passkeys with their associated items in a single query.
* This is much more efficient than calling getForItem() for each item.
@@ -835,7 +850,8 @@ data class PasskeyWithItem(
*
* @property itemId The UUID of the item.
* @property serviceName The service name (Item.Name).
- * @property url The login URL.
+ * @property url The login URL (first URL for backwards compatibility).
+ * @property urls All login URLs associated with this item.
* @property username The username from field values.
* @property hasPassword Whether the item has a password.
* @property createdAt When the item was created.
@@ -845,6 +861,7 @@ data class ItemWithCredentialInfo(
val itemId: UUID,
val serviceName: String?,
val url: String?,
+ val urls: List<String> = url?.let { listOf(it) } ?: emptyList(),
val username: String?,
val hasPassword: Boolean,
val createdAt: Date,
diff --git a/apps/mobile-app/ios/Autofill/CredentialProviderViewController+Passkey.swift b/apps/mobile-app/ios/Autofill/CredentialProviderViewController+Passkey.swift
index 505721049..4fdf92f62 100644
--- a/apps/mobile-app/ios/Autofill/CredentialProviderViewController+Passkey.swift
+++ b/apps/mobile-app/ios/Autofill/CredentialProviderViewController+Passkey.swift
@@ -242,9 +242,11 @@ extension CredentialProviderViewController: PasskeyProviderDelegate {
}
// Query for existing Items without passkeys that match this rpId
+ // Note: Don't filter by userName here - we want to show all matching items
+ // regardless of username so user can choose which item to merge into
var existingItemsWithoutPasskey: [ItemWithCredentialInfo] = []
do {
- let results = try vaultStore.getItemsWithoutPasskey(forRpId: rpId, userName: userName)
+ let results = try vaultStore.getItemsWithoutPasskey(forRpId: rpId)
existingItemsWithoutPasskey = results.map { item in
ItemWithCredentialInfo(
itemId: item.itemId,
diff --git a/apps/mobile-app/ios/VaultStoreKit/Database/Queries/PasskeyQueries.swift b/apps/mobile-app/ios/VaultStoreKit/Database/Queries/PasskeyQueries.swift
index 0a9135b03..367f5abb7 100644
--- a/apps/mobile-app/ios/VaultStoreKit/Database/Queries/PasskeyQueries.swift
+++ b/apps/mobile-app/ios/VaultStoreKit/Database/Queries/PasskeyQueries.swift
@@ -88,6 +88,8 @@ public struct PasskeyQueries {
/// Get Items that match an rpId but don't have a passkey yet.
/// Used for finding existing credentials that could have a passkey added to them.
+ /// Note: The public API now uses getAllItemsWithoutPasskey + Rust credential matcher for consistent cross-platform matching.
+ /// This query is kept for potential fallback scenarios.
public static let getItemsWithoutPasskeyForRpId = """
SELECT i.Id, i.Name, i.CreatedAt, i.UpdatedAt,
fv_url.Value as Url,
@@ -113,6 +115,35 @@ public struct PasskeyQueries {
)
ORDER BY i.UpdatedAt DESC
"""
+
+ /// Get ALL Login items that don't have a passkey yet (no URL filtering).
+ /// Used with Rust credential matcher for intelligent filtering.
+ /// Returns items with their URLs aggregated using GROUP_CONCAT for multi-URL support.
+ public static let getAllItemsWithoutPasskey = """
+ SELECT i.Id, i.Name, i.CreatedAt, i.UpdatedAt,
+ GROUP_CONCAT(DISTINCT fv_url.Value) as Urls,
+ fv_username.Value as Username,
+ fv_password.Value as Password
+ FROM Items i
+ LEFT JOIN FieldValues fv_url ON fv_url.ItemId = i.Id
+ AND fv_url.FieldKey = 'login.url'
+ AND fv_url.IsDeleted = 0
+ LEFT JOIN FieldValues fv_username ON fv_username.ItemId = i.Id
+ AND fv_username.FieldKey = 'login.username'
+ AND fv_username.IsDeleted = 0
+ LEFT JOIN FieldValues fv_password ON fv_password.ItemId = i.Id
+ AND fv_password.FieldKey = 'login.password'
+ AND fv_password.IsDeleted = 0
+ WHERE i.IsDeleted = 0
+ AND i.DeletedAt IS NULL
+ AND i.ItemType = 'Login'
+ AND NOT EXISTS (
+ SELECT 1 FROM Passkeys p
+ WHERE p.ItemId = i.Id AND p.IsDeleted = 0
+ )
+ GROUP BY i.Id
+ ORDER BY i.UpdatedAt DESC
+ """
}
/// SQL query constants for Logo operations used during passkey/item creation.
diff --git a/apps/mobile-app/ios/VaultStoreKit/Database/Repositories/PasskeyRepository.swift b/apps/mobile-app/ios/VaultStoreKit/Database/Repositories/PasskeyRepository.swift
index 354ae7010..dc437ab23 100644
--- a/apps/mobile-app/ios/VaultStoreKit/Database/Repositories/PasskeyRepository.swift
+++ b/apps/mobile-app/ios/VaultStoreKit/Database/Repositories/PasskeyRepository.swift
@@ -59,13 +59,14 @@ public class PasskeyRepository: BaseRepository {
return mappedResults
}
- /// Get Items that match an rpId but don't have a passkey yet.
- /// Used for finding existing credentials that could have a passkey added to them.
+ /// Get Items that match an rpId but don't have a passkey yet using legacy SQL LIKE matching.
+ /// Note: The public API now uses getAllItemsWithoutPasskey + Rust credential matcher for consistent cross-platform matching.
+ /// This method is kept for potential fallback scenarios.
/// - Parameters:
/// - rpId: The relying party identifier (domain)
/// - userName: Optional username to filter by
/// - Returns: Array of ItemWithCredentialInfoData objects
- public func getItemsWithoutPasskey(forRpId rpId: String, userName: String? = nil) throws -> [ItemWithCredentialInfoData] {
+ func getItemsWithoutPasskeyLegacy(forRpId rpId: String, userName: String? = nil) throws -> [ItemWithCredentialInfoData] {
let rpIdLower = rpId.lowercased()
let urlPattern1 = "%\(rpIdLower)%"
let urlPattern2 = "%\(rpIdLower.replacingOccurrences(of: "www.", with: ""))%"
@@ -108,6 +109,44 @@ public class PasskeyRepository: BaseRepository {
return items
}
+ /// Get ALL Login items that don't have a passkey yet (no URL filtering).
+ /// Used with RustItemMatcher for intelligent, cross-platform consistent filtering.
+ /// - Returns: Array of ItemWithCredentialInfoData objects with all URLs
+ public func getAllItemsWithoutPasskey() throws -> [ItemWithCredentialInfoData] {
+ let results = try client.executeQuery(PasskeyQueries.getAllItemsWithoutPasskey, params: [])
+
+ var items: [ItemWithCredentialInfoData] = []
+
+ for row in results {
+ guard let idString = row["Id"] as? String,
+ let itemId = UUID(uuidString: idString) else {
+ continue
+ }
+
+ let serviceName = row["Name"] as? String
+ let urlsString = row["Urls"] as? String
+ let urls = urlsString?.components(separatedBy: ",").filter { !$0.isEmpty } ?? []
+ let itemUsername = row["Username"] as? String
+ let password = row["Password"] as? String
+ let hasPassword = password != nil && !password!.isEmpty
+
+ let createdAt = DateHelpers.parseDateString(row["CreatedAt"] as? String ?? "") ?? Date.distantPast
+ let updatedAt = DateHelpers.parseDateString(row["UpdatedAt"] as? String ?? "") ?? Date.distantPast
+
+ items.append(ItemWithCredentialInfoData(
+ itemId: itemId,
+ serviceName: serviceName,
+ urls: urls,
+ username: itemUsername,
+ hasPassword: hasPassword,
+ createdAt: createdAt,
+ updatedAt: updatedAt
+ ))
+ }
+
+ return items
+ }
+
// MARK: - Write Operations
/// Create a new passkey.
@@ -462,6 +501,8 @@ public struct ItemWithCredentialInfoData {
public let itemId: UUID
public let serviceName: String?
public let url: String?
+ /// All URLs associated with this item (supports multi-value URL fields)
+ public let urls: [String]
public let username: String?
public let hasPassword: Bool
public let createdAt: Date
@@ -471,6 +512,18 @@ public struct ItemWithCredentialInfoData {
self.itemId = itemId
self.serviceName = serviceName
self.url = url
+ self.urls = url.map { [$0] } ?? []
+ self.username = username
+ self.hasPassword = hasPassword
+ self.createdAt = createdAt
+ self.updatedAt = updatedAt
+ }
+
+ public init(itemId: UUID, serviceName: String?, urls: [String], username: String?, hasPassword: Bool, createdAt: Date, updatedAt: Date) {
+ self.itemId = itemId
+ self.serviceName = serviceName
+ self.url = urls.first
+ self.urls = urls
self.username = username
self.hasPassword = hasPassword
self.createdAt = createdAt
diff --git a/apps/mobile-app/ios/VaultStoreKit/Utils/RustItemMatcher.swift b/apps/mobile-app/ios/VaultStoreKit/Utils/RustItemMatcher.swift
new file mode 100644
index 000000000..7d7abca0d
--- /dev/null
+++ b/apps/mobile-app/ios/VaultStoreKit/Utils/RustItemMatcher.swift
@@ -0,0 +1,105 @@
+import Foundation
+import RustCoreFramework
+
+/// Wrapper for the Rust item matcher using UniFFI bindings.
+/// Used in VaultStoreKit for passkey registration to find mergeable items.
+public enum RustItemMatcher {
+
+ /// Matching mode for item filtering.
+ public enum MatchingMode: String {
+ case `default` = "default"
+ case urlExact = "url_exact"
+ case urlSubdomain = "url_subdomain"
+ }
+
+ /// Filter items based on rpId using the Rust core item matcher.
+ /// Used during passkey registration to find existing items that can have a passkey merged into them.
+ ///
+ /// - Parameters:
+ /// - items: List of items to filter (without passkeys)
+ /// - rpId: The relying party identifier (domain) to match against
+ /// - matchingMode: The matching mode to use (default: urlSubdomain)
+ /// - Returns: List of item IDs that match the rpId
+ public static func filterItems(
+ _ items: [ItemWithCredentialInfoData],
+ rpId: String,
+ matchingMode: MatchingMode = .urlSubdomain
+ ) -> [UUID] {
+ // Early return for empty rpId or items
+ if rpId.isEmpty || items.isEmpty {
+ return []
+ }
+
+ do {
+ // Convert items to the format expected by Rust
+ let rustCredentials = items.map { item -> [String: Any?] in
+ return [
+ "Id": item.itemId.uuidString,
+ "ItemName": item.serviceName as Any?,
+ "ItemUrls": item.urls,
+ "Username": item.username as Any?
+ ]
+ }
+
+ // Prepare input JSON for Rust
+ // Use https:// prefix for the rpId to match URL format
+ let input: [String: Any] = [
+ "credentials": rustCredentials,
+ "current_url": "https://\(rpId)",
+ "page_title": "",
+ "matching_mode": matchingMode.rawValue
+ ]
+
+ let inputData = try JSONSerialization.data(withJSONObject: input, options: [])
+ guard let inputJson = String(data: inputData, encoding: .utf8) else {
+ print("[RustItemMatcher] Failed to create input JSON")
+ return []
+ }
+
+ // Call Rust via UniFFI
+ let outputJson = try filterCredentialsJson(inputJson: inputJson)
+
+ // Parse output
+ guard let outputData = outputJson.data(using: .utf8),
+ let output = try JSONSerialization.jsonObject(with: outputData) as? [String: Any],
+ let matchedIds = output["matched_ids"] as? [String] else {
+ print("[RustItemMatcher] Failed to parse output JSON")
+ return []
+ }
+
+ // If no matches found, return empty array
+ if matchedIds.isEmpty {
+ return []
+ }
+
+ // Convert matched IDs back to UUIDs, maintaining order
+ return matchedIds.compactMap { UUID(uuidString: $0) }
+
+ } catch {
+ print("[RustItemMatcher] Error filtering items: \(error)")
+ // Return empty array on error
+ return []
+ }
+ }
+
+ /// Filter items and return the full ItemWithCredentialInfoData objects.
+ /// Convenience method that returns filtered items instead of just IDs.
+ ///
+ /// - Parameters:
+ /// - items: List of items to filter (without passkeys)
+ /// - rpId: The relying party identifier (domain) to match against
+ /// - matchingMode: The matching mode to use (default: urlSubdomain)
+ /// - Returns: List of items that match the rpId, in priority order
+ public static func filterItemsWithData(
+ _ items: [ItemWithCredentialInfoData],
+ rpId: String,
+ matchingMode: MatchingMode = .urlSubdomain
+ ) -> [ItemWithCredentialInfoData] {
+ let matchedIds = filterItems(items, rpId: rpId, matchingMode: matchingMode)
+
+ // Map matched IDs back to items, maintaining Rust's priority order
+ return matchedIds.compactMap { matchedId in
+ items.first { $0.itemId == matchedId }
+ }
+ }
+}
diff --git a/apps/mobile-app/ios/VaultStoreKit/VaultStore+Passkey.swift b/apps/mobile-app/ios/VaultStoreKit/VaultStore+Passkey.swift
index 82c9eb4a3..5b2d9b642 100644
--- a/apps/mobile-app/ios/VaultStoreKit/VaultStore+Passkey.swift
+++ b/apps/mobile-app/ios/VaultStoreKit/VaultStore+Passkey.swift
@@ -57,9 +57,21 @@ extension VaultStore {
/**
* Get Items that match an rpId but don't have a passkey yet.
* Used for finding existing credentials that could have a passkey added to them.
+ * Uses the Rust credential matcher for consistent cross-platform matching logic.
*/
public func getItemsWithoutPasskey(forRpId rpId: String, userName: String? = nil) throws -> [ItemWithCredentialInfoData] {
- return try passkeyRepository.getItemsWithoutPasskey(forRpId: rpId, userName: userName)
+ // Get all items without passkeys
+ let allItems = try passkeyRepository.getAllItemsWithoutPasskey()
+
+ // Use Rust item matcher for intelligent filtering
+ var matchedItems = RustItemMatcher.filterItemsWithData(allItems, rpId: rpId)
+
+ // Apply optional username filter
+ if let userName = userName {
+ matchedItems = matchedItems.filter { $0.username == userName }
+ }
+
+ return matchedItems
}
// MARK: - Passkey Storage (Public API)
diff --git a/apps/mobile-app/ios/VaultUI/Selection/CredentialProviderView.swift b/apps/mobile-app/ios/VaultUI/Selection/CredentialProviderView.swift
index c33df92e0..894b2153e 100644
--- a/apps/mobile-app/ios/VaultUI/Selection/CredentialProviderView.swift
+++ b/apps/mobile-app/ios/VaultUI/Selection/CredentialProviderView.swift
@@ -257,7 +257,7 @@ public class CredentialProviderViewModel: ObservableObject {
}
func filterCredentials() {
- filteredCredentials = RustCredentialMatcher.filterCredentials(credentials, searchText: searchText)
+ filteredCredentials = RustItemMatcher.filterCredentials(credentials, searchText: searchText)
}
func handleSelection(username: String, password: String) {
diff --git a/apps/mobile-app/ios/VaultUI/Selection/Utils/RustCredentialMatcher.swift b/apps/mobile-app/ios/VaultUI/Selection/Utils/RustItemMatcher.swift
similarity index 87%
rename from apps/mobile-app/ios/VaultUI/Selection/Utils/RustCredentialMatcher.swift
rename to apps/mobile-app/ios/VaultUI/Selection/Utils/RustItemMatcher.swift
index 6a040d48e..80cabfe29 100644
--- a/apps/mobile-app/ios/VaultUI/Selection/Utils/RustCredentialMatcher.swift
+++ b/apps/mobile-app/ios/VaultUI/Selection/Utils/RustItemMatcher.swift
@@ -2,10 +2,10 @@ import Foundation
import VaultModels
import RustCoreFramework
-/// Wrapper for the Rust credential matcher using UniFFI bindings.
-public class RustCredentialMatcher {
+/// Wrapper for the Rust item matcher using UniFFI bindings.
+public class RustItemMatcher {
- /// Filter credentials based on search text using the Rust core credential matcher.
+ /// Filter credentials based on search text using the Rust core item matcher.
///
/// - Parameters:
/// - credentials: List of credentials to filter
@@ -38,7 +38,7 @@ public class RustCredentialMatcher {
let inputData = try JSONSerialization.data(withJSONObject: input, options: [])
guard let inputJson = String(data: inputData, encoding: .utf8) else {
- print("[RustCredentialMatcher] Failed to create input JSON")
+ print("[RustItemMatcher] Failed to create input JSON")
return credentials
}
@@ -49,7 +49,7 @@ public class RustCredentialMatcher {
guard let outputData = outputJson.data(using: .utf8),
let output = try JSONSerialization.jsonObject(with: outputData) as? [String: Any],
let matchedIds = output["matched_ids"] as? [String] else {
- print("[RustCredentialMatcher] Failed to parse output JSON")
+ print("[RustItemMatcher] Failed to parse output JSON")
return credentials
}
@@ -69,7 +69,7 @@ public class RustCredentialMatcher {
return filtered
} catch {
- print("[RustCredentialMatcher] Error filtering credentials: \(error)")
+ print("[RustItemMatcher] Error filtering credentials: \(error)")
// Fallback to returning all credentials on error
return credentials
}