Skip to content

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

Add iOS passkey scaffolding (#520)

Leendert de Borst4661e36ef449
diff --git a/apps/mobile-app/ios/Autofill/CredentialProviderViewController+Passkey.swift b/apps/mobile-app/ios/Autofill/CredentialProviderViewController+Passkey.swift
new file mode 100644
index 000000000..df0374977
--- /dev/null
+++ b/apps/mobile-app/ios/Autofill/CredentialProviderViewController+Passkey.swift
@@ -0,0 +1,438 @@
+import AuthenticationServices
+import SwiftUI
+import VaultStoreKit
+import VaultUI
+import VaultModels
+
+/**
+ * Passkey-related functionality for CredentialProviderViewController
+ * This extension handles all passkey registration and authentication operations
+ */
+extension CredentialProviderViewController {
+
+ // MARK: - Passkey Registration
+
+ /**
+ * Handle passkey registration request from the system
+ */
+ func handlePasskeyRegistration(_ registrationRequest: ASCredentialRequest) {
+ // Set flag to prevent normal credential view from loading
+ self.isPasskeyRegistrationMode = true
+
+ guard let passkeyRequest = registrationRequest as? ASPasskeyCredentialRequest else {
+ extensionContext.cancelRequest(withError: NSError(
+ domain: ASExtensionErrorDomain,
+ code: ASExtensionError.failed.rawValue
+ ))
+ return
+ }
+
+ // Generate a unique request ID
+ let requestId = UUID().uuidString
+
+ // Extract registration request data
+ let credentialIdentity = passkeyRequest.credentialIdentity as? ASPasskeyCredentialIdentity
+ let rpId = credentialIdentity?.relyingPartyIdentifier ?? ""
+ let userId = credentialIdentity?.userHandle
+ let userName = credentialIdentity?.userName
+ let clientDataHash = passkeyRequest.clientDataHash
+
+ // Build request data dictionary
+ var requestData: [String: Any] = [
+ "requestId": requestId,
+ "origin": "https://\(rpId)",
+ "rpId": rpId,
+ "challenge": clientDataHash.base64EncodedString(),
+ "enablePrf": false // TODO: Extract from extensions if available
+ ]
+
+ if let userId = userId {
+ requestData["userId"] = userId.base64EncodedString()
+ }
+
+ if let userName = userName {
+ requestData["userName"] = userName
+ }
+
+ do {
+ // Convert to JSON string
+ let jsonData = try JSONSerialization.data(withJSONObject: requestData)
+ let jsonString = String(data: jsonData, encoding: .utf8) ?? ""
+
+ // Store request in shared storage
+ let vaultStore = VaultStore()
+ try vaultStore.storePasskeyRegistrationRequest(requestId: requestId, requestData: jsonString)
+
+ // Show passkey registration UI
+ showPasskeyRegistrationView(
+ requestId: requestId,
+ rpId: rpId,
+ userName: userName,
+ vaultStore: vaultStore
+ )
+
+ } catch {
+ print("PasskeyRegistration error: \(error)")
+ extensionContext.cancelRequest(withError: NSError(
+ domain: ASExtensionErrorDomain,
+ code: ASExtensionError.failed.rawValue,
+ userInfo: [NSLocalizedDescriptionKey: error.localizedDescription]
+ ))
+ }
+ }
+
+ /**
+ * Show the passkey registration view
+ */
+ private func showPasskeyRegistrationView(
+ requestId: String,
+ rpId: String,
+ userName: String?,
+ vaultStore: VaultStore
+ ) {
+ // Create view model with handlers
+ let viewModel = PasskeyRegistrationViewModel(
+ requestId: requestId,
+ rpId: rpId,
+ origin: "https://\(rpId)",
+ userName: userName,
+ userDisplayName: userName,
+ completionHandler: { [weak self] success in
+ guard let self = self else { return }
+
+ if success {
+ print("PasskeyRegistration: App opened successfully, starting to poll for result")
+ // The app was opened successfully
+ // Now we need to poll for the result or cancellation
+ self.pollForPasskeyRegistrationResult(requestId: requestId, vaultStore: vaultStore)
+ } else {
+ print("PasskeyRegistration: Failed to open app")
+ self.extensionContext.cancelRequest(withError: NSError(
+ domain: ASExtensionErrorDomain,
+ code: ASExtensionError.failed.rawValue,
+ userInfo: [NSLocalizedDescriptionKey: "Failed to open main app"]
+ ))
+ }
+ },
+ cancelHandler: { [weak self] in
+ self?.cancelPasskeyRegistration(requestId: requestId, vaultStore: vaultStore)
+ }
+ )
+
+ // Create and present the view
+ let passkeyView = PasskeyRegistrationView(viewModel: viewModel)
+ let hostingController = UIHostingController(rootView: passkeyView)
+
+ // Remove existing passkey hosting controller if present
+ if let existingController = self.passkeyHostingController {
+ existingController.willMove(toParent: nil)
+ existingController.view.removeFromSuperview()
+ existingController.removeFromParent()
+ }
+
+ // Add new hosting controller
+ addChild(hostingController)
+ view.addSubview(hostingController.view)
+
+ hostingController.view.translatesAutoresizingMaskIntoConstraints = false
+ NSLayoutConstraint.activate([
+ hostingController.view.topAnchor.constraint(equalTo: view.topAnchor),
+ hostingController.view.leadingAnchor.constraint(equalTo: view.leadingAnchor),
+ hostingController.view.trailingAnchor.constraint(equalTo: view.trailingAnchor),
+ hostingController.view.bottomAnchor.constraint(equalTo: view.bottomAnchor)
+ ])
+
+ hostingController.didMove(toParent: self)
+ self.passkeyHostingController = hostingController
+ }
+
+ /**
+ * Cancel passkey registration
+ */
+ private func cancelPasskeyRegistration(requestId: String, vaultStore: VaultStore) {
+ print("PasskeyRegistration: User cancelled registration")
+ vaultStore.cleanupPasskeyRegistrationRequest(requestId)
+ extensionContext.cancelRequest(withError: NSError(
+ domain: ASExtensionErrorDomain,
+ code: ASExtensionError.userCanceled.rawValue
+ ))
+ }
+
+ /**
+ * Poll for passkey registration result from the React Native app
+ */
+ func pollForPasskeyRegistrationResult(requestId: String, vaultStore: VaultStore, pollCount: Int = 0) {
+ // Check if cancelled
+ if vaultStore.isPasskeyRegistrationCancelled(requestId) {
+ vaultStore.cleanupPasskeyRegistrationRequest(requestId)
+ extensionContext.cancelRequest(withError: NSError(
+ domain: ASExtensionErrorDomain,
+ code: ASExtensionError.userCanceled.rawValue
+ ))
+ return
+ }
+
+ // Check if result is available
+ if let resultJson = try? vaultStore.getPasskeyRegistrationResult(requestId),
+ let resultData = resultJson.data(using: .utf8),
+ let result = try? JSONSerialization.jsonObject(with: resultData) as? [String: Any] {
+
+ // Parse result
+ guard let credentialIdString = result["credentialId"] as? String,
+ let attestationObjectB64 = result["attestationObject"] as? String,
+ let attestationObject = Data(base64Encoded: attestationObjectB64) else {
+ vaultStore.cleanupPasskeyRegistrationRequest(requestId)
+ extensionContext.cancelRequest(withError: NSError(
+ domain: ASExtensionErrorDomain,
+ code: ASExtensionError.failed.rawValue,
+ userInfo: [NSLocalizedDescriptionKey: "Invalid result data"]
+ ))
+ return
+ }
+
+ do {
+ let credentialId = try PasskeyHelper.guidToBytes(credentialIdString)
+
+ // Get client data hash and RP ID from original request
+ guard let passkeyRequest = self.extensionContext as? ASPasskeyCredentialRequest,
+ let credentialIdentity = passkeyRequest.credentialIdentity as? ASPasskeyCredentialIdentity else {
+ vaultStore.cleanupPasskeyRegistrationRequest(requestId)
+ extensionContext.cancelRequest(withError: NSError(
+ domain: ASExtensionErrorDomain,
+ code: ASExtensionError.failed.rawValue
+ ))
+ return
+ }
+
+ let clientDataHash = passkeyRequest.clientDataHash
+ let rpId = credentialIdentity.relyingPartyIdentifier
+
+ // Create passkey registration credential
+ let credential = ASPasskeyRegistrationCredential(
+ relyingParty: rpId,
+ clientDataHash: clientDataHash,
+ credentialID: credentialId,
+ attestationObject: attestationObject
+ )
+
+ // Clean up stored data
+ vaultStore.cleanupPasskeyRegistrationRequest(requestId)
+
+ // Complete the request
+ extensionContext.completeRegistrationRequest(using: credential)
+ return
+ } catch {
+ vaultStore.cleanupPasskeyRegistrationRequest(requestId)
+ extensionContext.cancelRequest(withError: NSError(
+ domain: ASExtensionErrorDomain,
+ code: ASExtensionError.failed.rawValue,
+ userInfo: [NSLocalizedDescriptionKey: "Failed to parse credential ID: \(error.localizedDescription)"]
+ ))
+ return
+ }
+ }
+
+ // Timeout after 60 seconds (120 polls * 0.5 seconds)
+ if pollCount >= 120 {
+ vaultStore.cleanupPasskeyRegistrationRequest(requestId)
+ extensionContext.cancelRequest(withError: NSError(
+ domain: ASExtensionErrorDomain,
+ code: ASExtensionError.userCanceled.rawValue,
+ userInfo: [NSLocalizedDescriptionKey: "Registration timed out"]
+ ))
+ return
+ }
+
+ // Poll again after 0.5 seconds
+ DispatchQueue.main.asyncAfter(deadline: .now() + 0.5) { [weak self] in
+ self?.pollForPasskeyRegistrationResult(requestId: requestId, vaultStore: vaultStore, pollCount: pollCount + 1)
+ }
+ }
+
+ // MARK: - Passkey Authentication
+
+ /**
+ * Handle passkey authentication request
+ */
+ func handlePasskeyAuthentication(_ request: ASPasskeyCredentialRequest) {
+ // Set flag to indicate passkey authentication mode
+ self.isPasskeyRegistrationMode = false
+
+ do {
+ let vaultStore = VaultStore()
+
+ // Check sanity before proceeding
+ guard sanityChecks(vaultStore: vaultStore) else {
+ return
+ }
+
+ // Unlock the vault
+ try vaultStore.unlockVault()
+
+ let clientDataHash = request.clientDataHash
+ let credentialIdentity = request.credentialIdentity as? ASPasskeyCredentialIdentity
+ let rpId = credentialIdentity?.relyingPartyIdentifier ?? ""
+
+ // Check if we have a specific credential ID provided by the system
+ if let credentialID = credentialIdentity?.credentialID, !credentialID.isEmpty {
+ // Direct credential ID lookup - authenticate immediately
+ guard let passkey = try vaultStore.getPasskey(byCredentialId: credentialID) else {
+ extensionContext.cancelRequest(withError: NSError(
+ domain: ASExtensionErrorDomain,
+ code: ASExtensionError.credentialIdentityNotFound.rawValue
+ ))
+ return
+ }
+
+ try authenticateWithPasskey(passkey, clientDataHash: clientDataHash, rpId: rpId)
+ } else {
+ // No specific credential - show picker for user to select
+ showPasskeyPickerView(rpId: rpId, clientDataHash: clientDataHash, vaultStore: vaultStore)
+ }
+
+ } catch {
+ print("PasskeyAuthentication error: \(error)")
+ extensionContext.cancelRequest(withError: NSError(
+ domain: ASExtensionErrorDomain,
+ code: ASExtensionError.failed.rawValue,
+ userInfo: [NSLocalizedDescriptionKey: error.localizedDescription]
+ ))
+ }
+ }
+
+ /**
+ * Authenticate with a specific passkey
+ */
+ private func authenticateWithPasskey(_ passkey: Passkey, clientDataHash: Data, rpId: String) throws {
+ // Generate assertion using PasskeyAuthenticator
+ let assertion = try PasskeyAuthenticator.getAssertion(
+ credentialId: passkey.credentialId,
+ clientDataHash: clientDataHash,
+ rpId: rpId,
+ privateKeyJWK: passkey.privateKey,
+ userId: passkey.userId,
+ uvPerformed: true,
+ prfInputs: nil,
+ prfSecret: passkey.prfKey
+ )
+
+ // Complete the request with passkey assertion credential
+ let credential = ASPasskeyAssertionCredential(
+ userHandle: assertion.userHandle ?? Data(),
+ relyingParty: rpId,
+ signature: assertion.signature,
+ clientDataHash: clientDataHash,
+ authenticatorData: assertion.authenticatorData,
+ credentialID: assertion.credentialId
+ )
+
+ extensionContext.completeAssertionRequest(using: credential)
+ }
+
+ /**
+ * Show passkey picker view for user selection
+ */
+ private func showPasskeyPickerView(rpId: String, clientDataHash: Data, vaultStore: VaultStore) {
+ let viewModel = PasskeyProviderViewModel(
+ loader: {
+ return try await self.loadPasskeyCredentials(vaultStore: vaultStore, rpId: rpId)
+ },
+ selectionHandler: { [weak self, clientDataHash, rpId] credential in
+ guard let self = self else { return }
+ self.handlePasskeyCredentialSelection(credential: credential, clientDataHash: clientDataHash, rpId: rpId)
+ },
+ cancelHandler: { [weak self] in
+ guard let self = self else { return }
+ self.handleCancel()
+ },
+ rpId: rpId
+ )
+
+ let passkeyView = PasskeyProviderView(viewModel: viewModel)
+ let hostingController = UIHostingController(rootView: passkeyView)
+
+ // Remove existing passkey hosting controller if present
+ if let existingController = self.passkeyHostingController {
+ existingController.willMove(toParent: nil)
+ existingController.view.removeFromSuperview()
+ existingController.removeFromParent()
+ }
+
+ // Add new hosting controller
+ addChild(hostingController)
+ view.addSubview(hostingController.view)
+
+ hostingController.view.translatesAutoresizingMaskIntoConstraints = false
+ NSLayoutConstraint.activate([
+ hostingController.view.topAnchor.constraint(equalTo: view.topAnchor),
+ hostingController.view.leadingAnchor.constraint(equalTo: view.leadingAnchor),
+ hostingController.view.trailingAnchor.constraint(equalTo: view.trailingAnchor),
+ hostingController.view.bottomAnchor.constraint(equalTo: view.bottomAnchor)
+ ])
+
+ hostingController.didMove(toParent: self)
+ self.passkeyHostingController = hostingController
+ }
+
+ /**
+ * Load credentials with passkeys for the specified RP ID
+ */
+ private func loadPasskeyCredentials(vaultStore: VaultStore, rpId: String) async throws -> [Credential] {
+ let credentials = try vaultStore.getAllCredentialsWithPasskeys()
+
+ // Filter by RP ID if specified
+ if !rpId.isEmpty {
+ let lowercasedRpId = rpId.lowercased()
+ return credentials.filter { credential in
+ guard let passkeys = credential.passkeys else { return false }
+ // Match exact RP ID or check if RP ID is a suffix of the credential's service domain
+ return passkeys.contains { passkey in
+ let passkeyRpId = passkey.rpId.lowercased()
+ // Exact match
+ if passkeyRpId == lowercasedRpId {
+ return true
+ }
+ // Check if they are related domains (e.g., rpId="example.com", passkey.rpId="www.example.com")
+ if passkeyRpId.hasSuffix(lowercasedRpId) || lowercasedRpId.hasSuffix(passkeyRpId) {
+ return true
+ }
+ // Check against service URL domain as well
+ if let serviceUrl = credential.service.url?.lowercased(),
+ let url = URL(string: serviceUrl),
+ let host = url.host?.lowercased() {
+ return host == lowercasedRpId || host.hasSuffix(".\(lowercasedRpId)") || lowercasedRpId.hasSuffix(".\(host)")
+ }
+ return false
+ }
+ }
+ }
+
+ return credentials
+ }
+
+ /**
+ * Handle passkey credential selection from picker
+ */
+ private func handlePasskeyCredentialSelection(credential: Credential, clientDataHash: Data, rpId: String) {
+ do {
+ // Get the first matching passkey for the RP ID
+ guard let passkeys = credential.passkeys,
+ let passkey = passkeys.first(where: { $0.rpId.lowercased() == rpId.lowercased() }) else {
+ extensionContext.cancelRequest(withError: NSError(
+ domain: ASExtensionErrorDomain,
+ code: ASExtensionError.credentialIdentityNotFound.rawValue
+ ))
+ return
+ }
+
+ try authenticateWithPasskey(passkey, clientDataHash: clientDataHash, rpId: rpId)
+ } catch {
+ print("PasskeyAuthentication error: \(error)")
+ extensionContext.cancelRequest(withError: NSError(
+ domain: ASExtensionErrorDomain,
+ code: ASExtensionError.failed.rawValue,
+ userInfo: [NSLocalizedDescriptionKey: error.localizedDescription]
+ ))
+ }
+ }
+}
diff --git a/apps/mobile-app/ios/Autofill/CredentialProviderViewController.swift b/apps/mobile-app/ios/Autofill/CredentialProviderViewController.swift
index 933637879..a3ff2bdf5 100644
--- a/apps/mobile-app/ios/Autofill/CredentialProviderViewController.swift
+++ b/apps/mobile-app/ios/Autofill/CredentialProviderViewController.swift
@@ -14,7 +14,9 @@ import VaultModels
* logins in the keyboard).
*/
public class CredentialProviderViewController: ASCredentialProviderViewController {
- private var hostingController: UIHostingController<CredentialProviderView>?
+ internal var hostingController: UIHostingController<CredentialProviderView>?
+ internal var passkeyHostingController: UIViewController?
+ internal var isPasskeyRegistrationMode = false
private var viewModel: CredentialProviderViewModel?
private var isChoosingTextToInsert = false
private var initialServiceUrl: String?
@@ -22,6 +24,12 @@ public class CredentialProviderViewController: ASCredentialProviderViewControlle
override public func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
+ // Don't set up credential view if we're in passkey registration mode
+ // TODO: make this more clear by design which action is taken for which mode in the viewWillAppear for autofill vs passkey
+ if isPasskeyRegistrationMode {
+ return
+ }
+
// Check if there is a stored vault. If not, it means the user has not logged in yet and we
// should redirect to the main app login screen automatically.
let vaultStore = VaultStore()
@@ -129,6 +137,15 @@ public class CredentialProviderViewController: ASCredentialProviderViewControlle
override public func provideCredentialWithoutUserInteraction(for credentialIdentity: ASPasswordCredentialIdentity) {
do {
let vaultStore = VaultStore()
+
+ // Check vault state
+ guard sanityChecks(vaultStore: vaultStore) else {
+ return
+ }
+
+ // Unlock vault
+ try vaultStore.unlockVault()
+
let credentials = try vaultStore.getAllCredentials()
if let matchingCredential = credentials.first(where: { credential in
@@ -150,6 +167,7 @@ public class CredentialProviderViewController: ASCredentialProviderViewControlle
)
}
} catch {
+ print("provideCredentialWithoutUserInteraction error: \(error)")
self.extensionContext.cancelRequest(
withError: NSError(
domain: ASExtensionErrorDomain,
@@ -163,20 +181,7 @@ public class CredentialProviderViewController: ASCredentialProviderViewControlle
// MARK: - Passkey Support
override public func prepareInterface(forPasskeyRegistration registrationRequest: ASCredentialRequest) {
- guard let passkeyRequest = registrationRequest as? ASPasskeyCredentialRequest else {
- extensionContext.cancelRequest(withError: NSError(
- domain: ASExtensionErrorDomain,
- code: ASExtensionError.failed.rawValue
- ))
- return
- }
-
- // TODO: Implement passkey registration UI
- // For now, cancel the request
- extensionContext.cancelRequest(withError: NSError(
- domain: ASExtensionErrorDomain,
- code: ASExtensionError.userCanceled.rawValue
- ))
+ handlePasskeyRegistration(registrationRequest)
}
override public func prepareInterfaceToProvideCredential(for credentialRequest: ASCredentialRequest) {
@@ -190,24 +195,49 @@ public class CredentialProviderViewController: ASCredentialProviderViewControlle
// The existing prepareCredentialList method will be called by the system
}
- private func handlePasskeyAuthentication(_ request: ASPasskeyCredentialRequest) {
+ @available(iOS 17.0, *)
+ override public func provideCredentialWithoutUserInteraction(for credentialRequest: ASCredentialRequest) {
+ // Check if this is a passkey request
+ if let passkeyRequest = credentialRequest as? ASPasskeyCredentialRequest {
+ providePasskeyCredentialWithoutUserInteraction(for: passkeyRequest)
+ return
+ }
+
+ // For password credentials, call the legacy method
+ if let credentialIdentity = credentialRequest.credentialIdentity as? ASPasswordCredentialIdentity {
+ provideCredentialWithoutUserInteraction(for: credentialIdentity)
+ return
+ }
+
+ // Unknown credential type
+ self.extensionContext.cancelRequest(withError: NSError(
+ domain: ASExtensionErrorDomain,
+ code: ASExtensionError.userInteractionRequired.rawValue
+ ))
+ }
+
+ /**
+ * Provide passkey credential without user interaction
+ */
+ private func providePasskeyCredentialWithoutUserInteraction(for request: ASPasskeyCredentialRequest) {
do {
let vaultStore = VaultStore()
- // Check sanity before proceeding
+ // Check vault state
guard sanityChecks(vaultStore: vaultStore) else {
return
}
- // Unlock the vault
+ // Unlock vault
try vaultStore.unlockVault()
let clientDataHash = request.clientDataHash
let credentialIdentity = request.credentialIdentity as? ASPasskeyCredentialIdentity
let rpId = credentialIdentity?.relyingPartyIdentifier ?? ""
+ let credentialID = credentialIdentity?.credentialID ?? Data()
- // Load passkey from vault using the credential ID
- guard let passkey = try vaultStore.getPasskey(byCredentialId: credentialIdentity?.credentialID ?? Data()) else {
+ // Look up passkey by credential ID
+ guard let passkey = try vaultStore.getPasskey(byCredentialId: credentialID) else {
extensionContext.cancelRequest(withError: NSError(
domain: ASExtensionErrorDomain,
code: ASExtensionError.credentialIdentityNotFound.rawValue
@@ -215,19 +245,19 @@ public class CredentialProviderViewController: ASCredentialProviderViewControlle
return
}
- // Generate assertion using PasskeyAuthenticator
+ // Generate assertion
let assertion = try PasskeyAuthenticator.getAssertion(
credentialId: passkey.credentialId,
clientDataHash: clientDataHash,
rpId: rpId,
privateKeyJWK: passkey.privateKey,
userId: passkey.userId,
- uvPerformed: true, // We verified user with Face ID/Touch ID
- prfInputs: nil, // TODO: Extract PRF inputs from request if needed
+ uvPerformed: true,
+ prfInputs: nil,
prfSecret: passkey.prfKey
)
- // Complete the request with passkey assertion credential
+ // Complete the request
let credential = ASPasskeyAssertionCredential(
userHandle: assertion.userHandle ?? Data(),
relyingParty: rpId,
@@ -240,24 +270,15 @@ public class CredentialProviderViewController: ASCredentialProviderViewControlle
extensionContext.completeAssertionRequest(using: credential)
} catch {
- print("PasskeyAuthentication error: \(error)")
+ print("Passkey authentication without UI error: \(error)")
+ // Require user interaction if we can't authenticate silently
extensionContext.cancelRequest(withError: NSError(
domain: ASExtensionErrorDomain,
- code: ASExtensionError.failed.rawValue,
- userInfo: [NSLocalizedDescriptionKey: error.localizedDescription]
+ code: ASExtensionError.userInteractionRequired.rawValue
))
}
}
- public func providePasskeyCredentialWithoutUserInteraction(for credentialIdentity: ASPasskeyCredentialIdentity) {
- // TODO: Implement silent passkey authentication
- // For now, fall back to requiring user interaction
- extensionContext.cancelRequest(withError: NSError(
- domain: ASExtensionErrorDomain,
- code: ASExtensionError.userInteractionRequired.rawValue
- ))
- }
-
/// This registers all known AliasVault credentials into iOS native credential storage, which iOS can then use to
/// suggest autofill credentials when a user focuses an input field on a login form. These suggestions will then be s
/// hown above the iOS keyboard, which saves the user one step.
@@ -274,7 +295,7 @@ public class CredentialProviderViewController: ASCredentialProviderViewControlle
/// - Returns
/// true if sanity checks succeeded and view can open
/// false if sanity checks failed and a notice windows has been shown.
- private func sanityChecks(vaultStore: VaultStore) -> Bool {
+ func sanityChecks(vaultStore: VaultStore) -> Bool {
if !vaultStore.hasEncryptedDatabase {
let alert = UIAlertController(
title: NSLocalizedString("login_required", comment: ""),
@@ -379,7 +400,7 @@ public class CredentialProviderViewController: ASCredentialProviderViewControlle
}
/// Handle autofill view cancel action.
- private func handleCancel() {
+ internal func handleCancel() {
self.extensionContext.cancelRequest(withError: NSError(
domain: ASExtensionErrorDomain,
code: ASExtensionError.userCanceled.rawValue
diff --git a/apps/mobile-app/ios/Autofill/en.lproj/Localizable.strings b/apps/mobile-app/ios/Autofill/en.lproj/Localizable.strings
index f74ca934e..8fcb1de76 100644
Binary files a/apps/mobile-app/ios/Autofill/en.lproj/Localizable.strings and b/apps/mobile-app/ios/Autofill/en.lproj/Localizable.strings differ
diff --git a/apps/mobile-app/ios/VaultStoreKit/VaultStore+Passkey.swift b/apps/mobile-app/ios/VaultStoreKit/VaultStore+Passkey.swift
index 3d659d325..e55ba893a 100644
--- a/apps/mobile-app/ios/VaultStoreKit/VaultStore+Passkey.swift
+++ b/apps/mobile-app/ios/VaultStoreKit/VaultStore+Passkey.swift
@@ -5,48 +5,93 @@ import VaultModels
/**
* VaultStore+Passkey
* Extension to VaultStore for passkey operations
+ * TODO: review file
*/
extension VaultStore {
// MARK: - Passkey Queries
/**
- * Get all passkeys for a specific relying party ID
+ * Get a passkey by its credential ID (the WebAuthn credential ID, not the parent Credential UUID)
*/
- public func getPasskeys(byRpId rpId: String) throws -> [Passkey] {
+ public func getPasskey(byCredentialId credentialId: Data) throws -> Passkey? {
guard let dbConn = dbConnection else {
throw VaultStoreError.vaultNotUnlocked
}
- // TODO: Implement actual SQLite query
- // This is a placeholder implementation
- // The actual implementation will depend on your database schema
- return []
- }
+ let query = """
+ SELECT
+ Id,
+ CredentialId,
+ RpId,
+ UserId,
+ PublicKey,
+ PrivateKey,
+ PrfKey,
+ DisplayName,
+ AdditionalData,
+ CreatedAt,
+ UpdatedAt,
+ IsDeleted
+ FROM Passkeys
+ WHERE AdditionalData = ? AND IsDeleted = 0
+ LIMIT 1
+ """
- /**
- * Get a passkey by its credential ID
- */
- public func getPasskey(byCredentialId credentialId: Data) throws -> Passkey? {
- guard let dbConn = dbConnection else {
- throw VaultStoreError.vaultNotUnlocked
- }
+ let credentialIdBlob = Blob(bytes: [UInt8](credentialId))
- // TODO: Implement actual SQLite query
- // This is a placeholder implementation
- return nil
- }
+ for row in try dbConn.prepare(query, [credentialIdBlob]) {
+ guard let idString = row[0] as? String,
+ let credentialIdString = row[1] as? String,
+ let rpId = row[2] as? String,
+ let publicKeyString = row[4] as? String,
+ let privateKeyString = row[5] as? String,
+ let displayName = row[7] as? String,
+ let createdAtString = row[9] as? String,
+ let updatedAtString = row[10] as? String,
+ let isDeletedInt64 = row[11] as? Int64,
+ let id = UUID(uuidString: idString),
+ let parentCredentialId = UUID(uuidString: credentialIdString),
+ let publicKeyData = publicKeyString.data(using: .utf8),
+ let privateKeyData = privateKeyString.data(using: .utf8) else {
+ continue
+ }
- /**
- * Get a passkey by its UUID
- */
- public func getPasskey(byId id: UUID) throws -> Passkey? {
- guard let dbConn = dbConnection else {
- throw VaultStoreError.vaultNotUnlocked
+ guard let createdAt = parseDateString(createdAtString),
+ let updatedAt = parseDateString(updatedAtString) else {
+ continue
+ }
+
+ let userId = (row[3] as? String)?.data(using: .utf8)
+ let prfKey = (row[6] as? SQLite.Blob).map { Data($0.bytes) }
+ let isDeleted = isDeletedInt64 == 1
+
+ // Get the actual WebAuthn credential ID from AdditionalData column
+ let webauthnCredentialId: Data
+ if let additionalDataBlob = row[8] as? SQLite.Blob {
+ webauthnCredentialId = Data(additionalDataBlob.bytes)
+ } else {
+ // Fallback: use the passkey ID as a GUID and convert to bytes
+ webauthnCredentialId = (try? PasskeyHelper.guidToBytes(idString)) ?? Data()
+ }
+
+ return Passkey(
+ id: id,
+ credentialId: webauthnCredentialId,
+ credentialIdString: parentCredentialId.uuidString,
+ rpId: rpId,
+ userId: userId,
+ userName: nil,
+ publicKey: publicKeyData,
+ privateKey: privateKeyData,
+ prfKey: prfKey,
+ displayName: displayName,
+ createdAt: createdAt,
+ updatedAt: updatedAt,
+ isDeleted: isDeleted
+ )
}
- // TODO: Implement actual SQLite query
- // This is a placeholder implementation
return nil
}
@@ -58,96 +103,315 @@ extension VaultStore {
throw VaultStoreError.vaultNotUnlocked
}
- // TODO: Implement actual SQLite query
- // This is a placeholder implementation
- return []
- }
+ let query = """
+ SELECT
+ Id,
+ CredentialId,
+ RpId,
+ UserId,
+ PublicKey,
+ PrivateKey,
+ PrfKey,
+ DisplayName,
+ AdditionalData,
+ CreatedAt,
+ UpdatedAt,
+ IsDeleted
+ FROM Passkeys
+ WHERE CredentialId = ? AND IsDeleted = 0
+ ORDER BY CreatedAt DESC
+ """
- // MARK: - Passkey Mutations
+ var passkeys: [Passkey] = []
+ for row in try dbConn.prepare(query, [credentialId.uuidString]) {
+ guard let idString = row[0] as? String,
+ let credentialIdString = row[1] as? String,
+ let rpId = row[2] as? String,
+ let publicKeyString = row[4] as? String,
+ let privateKeyString = row[5] as? String,
+ let displayName = row[7] as? String,
+ let createdAtString = row[9] as? String,
+ let updatedAtString = row[10] as? String,
+ let isDeletedInt64 = row[11] as? Int64,
+ let id = UUID(uuidString: idString),
+ let parentCredentialId = UUID(uuidString: credentialIdString),
+ let publicKeyData = publicKeyString.data(using: .utf8),
+ let privateKeyData = privateKeyString.data(using: .utf8) else {
+ continue
+ }
- /**
- * Create a new passkey
- *
- * - Note: This method intentionally has more than 5 parameters as it stores all WebAuthn
- * credential data required by the specification. Parameters cannot be grouped without
- * losing type safety and clarity.
- */
- // swiftlint:disable:next function_parameter_count
- public func createPasskey(
- credentialId: Data,
- parentCredentialId: UUID,
- rpId: String,
- userId: Data?,
- userName: String?,
- publicKey: Data,
- privateKey: Data,
- prfKey: Data?,
- displayName: String
- ) throws -> Passkey {
- guard let dbConn = dbConnection else {
- throw VaultStoreError.vaultNotUnlocked
+ guard let createdAt = parseDateString(createdAtString),
+ let updatedAt = parseDateString(updatedAtString) else {
+ continue
+ }
+
+ let userId = (row[3] as? String)?.data(using: .utf8)
+ let prfKey = (row[6] as? SQLite.Blob).map { Data($0.bytes) }
+ let isDeleted = isDeletedInt64 == 1
+
+ // Get the actual WebAuthn credential ID from AdditionalData column
+ let webauthnCredentialId: Data
+ if let additionalDataBlob = row[8] as? SQLite.Blob {
+ webauthnCredentialId = Data(additionalDataBlob.bytes)
+ } else {
+ // Fallback: use the passkey ID as a GUID and convert to bytes
+ webauthnCredentialId = (try? PasskeyHelper.guidToBytes(idString)) ?? Data()
+ }
+
+ let passkey = Passkey(
+ id: id,
+ credentialId: webauthnCredentialId,
+ credentialIdString: parentCredentialId.uuidString,
+ rpId: rpId,
+ userId: userId,
+ userName: nil,
+ publicKey: publicKeyData,
+ privateKey: privateKeyData,
+ prfKey: prfKey,
+ displayName: displayName,
+ createdAt: createdAt,
+ updatedAt: updatedAt,
+ isDeleted: isDeleted
+ )
+
+ passkeys.append(passkey)
}
- let now = Date()
- let passkeyId = UUID()
-
- let passkey = Passkey(
- id: passkeyId,
- credentialId: credentialId,
- credentialIdString: parentCredentialId.uuidString,
- rpId: rpId,
- userId: userId,
- userName: userName,
- publicKey: publicKey,
- privateKey: privateKey,
- prfKey: prfKey,
- displayName: displayName,
- createdAt: now,
- updatedAt: now,
- isDeleted: false
- )
-
- // TODO: Implement actual SQLite insert
- // This is a placeholder implementation
- // INSERT INTO Passkeys (...) VALUES (...)
-
- return passkey
+ return passkeys
}
/**
- * Update an existing passkey
+ * Get all credentials that have passkeys attached
*/
- public func updatePasskey(_ passkey: Passkey) throws {
+ // swiftlint:disable:next function_body_length
+ public func getAllCredentialsWithPasskeys() throws -> [Credential] {
guard let dbConn = dbConnection else {
throw VaultStoreError.vaultNotUnlocked
}
- // TODO: Implement actual SQLite update
- // UPDATE Passkeys SET ... WHERE id = ?
- }
+ let query = """
+ WITH LatestPasswords AS (
+ SELECT
+ p.Id as password_id,
+ p.CredentialId,
+ p.Value,
+ p.CreatedAt,
+ p.UpdatedAt,
+ p.IsDeleted,
+ ROW_NUMBER() OVER (PARTITION BY p.CredentialId ORDER BY p.CreatedAt DESC) as rn
+ FROM Passwords p
+ WHERE p.IsDeleted = 0
+ )
+ SELECT
+ c.Id,
+ c.AliasId,
+ c.Username,
+ c.Notes,
+ c.CreatedAt,
+ c.UpdatedAt,
+ c.IsDeleted,
+ s.Id as service_id,
+ s.Name as service_name,
+ s.Url as service_url,
+ s.Logo as service_logo,
+ s.CreatedAt as service_created_at,
+ s.UpdatedAt as service_updated_at,
+ s.IsDeleted as service_is_deleted,
+ lp.password_id,
+ lp.Value as password_value,
+ lp.CreatedAt as password_created_at,
+ lp.UpdatedAt as password_updated_at,
+ lp.IsDeleted as password_is_deleted,
+ a.Id as alias_id,
+ a.Gender as alias_gender,
+ a.FirstName as alias_first_name,
+ a.LastName as alias_last_name,
+ a.NickName as alias_nick_name,
+ a.BirthDate as alias_birth_date,
+ a.Email as alias_email,
+ a.CreatedAt as alias_created_at,
+ a.UpdatedAt as alias_updated_at,
+ a.IsDeleted as alias_is_deleted
+ FROM Credentials c
+ INNER JOIN Passkeys pk ON pk.CredentialId = c.Id AND pk.IsDeleted = 0
+ LEFT JOIN Services s ON s.Id = c.ServiceId AND s.IsDeleted = 0
+ LEFT JOIN LatestPasswords lp ON lp.CredentialId = c.Id AND lp.rn = 1
+ LEFT JOIN Aliases a ON a.Id = c.AliasId AND a.IsDeleted = 0
+ WHERE c.IsDeleted = 0
+ GROUP BY c.Id
+ ORDER BY c.CreatedAt DESC
+ """
- /**
- * Delete a passkey (soft delete)
- */
- public func deletePasskey(byId id: UUID) throws {
- guard let dbConn = dbConnection else {
- throw VaultStoreError.vaultNotUnlocked
+ var credentials: [Credential] = []
+ for row in try dbConn.prepare(query) {
+ guard let idString = row[0] as? String else {
+ continue
+ }
+
+ let createdAtString = row[4] as? String
+ let updatedAtString = row[5] as? String
+
+ guard let createdAtString = createdAtString,
+ let updatedAtString = updatedAtString else {
+ continue
+ }
+
+ guard let createdAt = parseDateString(createdAtString),
+ let updatedAt = parseDateString(updatedAtString) else {
+ continue
+ }
+
+ guard let isDeletedInt64 = row[6] as? Int64 else { continue }
+ let isDeleted = isDeletedInt64 == 1
+
+ guard let serviceId = row[7] as? String,
+ let serviceCreatedAtString = row[11] as? String,
+ let serviceUpdatedAtString = row[12] as? String,
+ let serviceIsDeletedInt64 = row[13] as? Int64,
+ let serviceCreatedAt = parseDateString(serviceCreatedAtString),
+ let serviceUpdatedAt = parseDateString(serviceUpdatedAtString) else {
+ continue
+ }
+
+ let serviceIsDeleted = serviceIsDeletedInt64 == 1
+
+ let service = Service(
+ id: UUID(uuidString: serviceId)!,
+ name: row[8] as? String,
+ url: row[9] as? String,
+ logo: (row[10] as? SQLite.Blob).map { Data($0.bytes) },
+ createdAt: serviceCreatedAt,
+ updatedAt: serviceUpdatedAt,
+ isDeleted: serviceIsDeleted
+ )
+
+ var alias: Alias?
+ if let aliasIdString = row[19] as? String,
+ let aliasCreatedAtString = row[26] as? String,
+ let aliasUpdatedAtString = row[27] as? String,
+ let aliasIsDeletedInt64 = row[28] as? Int64,
+ let aliasCreatedAt = parseDateString(aliasCreatedAtString),
+ let aliasUpdatedAt = parseDateString(aliasUpdatedAtString) {
+
+ let aliasIsDeleted = aliasIsDeletedInt64 == 1
+
+ let aliasBirthDate: Date
+ if let aliasBirthDateString = row[24] as? String,
+ let parsedBirthDate = parseDateString(aliasBirthDateString) {
+ aliasBirthDate = parsedBirthDate
+ } else {
+ var dateComponents = DateComponents()
+ dateComponents.year = 1
+ dateComponents.month = 1
+ dateComponents.day = 1
+ aliasBirthDate = Calendar(identifier: .gregorian).date(from: dateComponents)!
+ }
+
+ alias = Alias(
+ id: UUID(uuidString: aliasIdString)!,
+ gender: row[20] as? String,
+ firstName: row[21] as? String,
+ lastName: row[22] as? String,
+ nickName: row[23] as? String,
+ birthDate: aliasBirthDate,
+ email: row[25] as? String,
+ createdAt: aliasCreatedAt,
+ updatedAt: aliasUpdatedAt,
+ isDeleted: aliasIsDeleted
+ )
+ }
+
+ var password: Password?
+ if let passwordIdString = row[14] as? String,
+ let passwordValue = row[15] as? String,
+ let passwordCreatedAtString = row[16] as? String,
+ let passwordUpdatedAtString = row[17] as? String,
+ let passwordIsDeletedInt64 = row[18] as? Int64,
+ let passwordCreatedAt = parseDateString(passwordCreatedAtString),
+ let passwordUpdatedAt = parseDateString(passwordUpdatedAtString) {
+
+ let passwordIsDeleted = passwordIsDeletedInt64 == 1
+
+ password = Password(
+ id: UUID(uuidString: passwordIdString)!,
+ credentialId: UUID(uuidString: idString)!,
+ value: passwordValue,
+ createdAt: passwordCreatedAt,
+ updatedAt: passwordUpdatedAt,
+ isDeleted: passwordIsDeleted
+ )
+ }
+
+ // Load passkeys for this credential
+ let passkeys = try getPasskeys(forCredentialId: UUID(uuidString: idString)!)
+
+ let credential = Credential(
+ id: UUID(uuidString: idString)!,
+ alias: alias,
+ service: service,
+ username: row[2] as? String,
+ notes: row[3] as? String,
+ password: password,
+ passkeys: passkeys,
+ createdAt: createdAt,
+ updatedAt: updatedAt,
+ isDeleted: isDeleted
+ )
+
+ credentials.append(credential)
}
- // TODO: Implement actual SQLite update (soft delete)
- // UPDATE Passkeys SET isDeleted = 1, updatedAt = ? WHERE id = ?
+ return credentials
}
+ // MARK: - Helper Methods
+
/**
- * Delete a passkey by credential ID (soft delete)
+ * Parse a date string to a Date object for use in queries.
*/
- public func deletePasskey(byCredentialId credentialId: Data) throws {
- guard let dbConn = dbConnection else {
- throw VaultStoreError.vaultNotUnlocked
+ private func parseDateString(_ dateString: String) -> Date? {
+ struct StaticFormatters {
+ static let formatterWithMillis: DateFormatter = {
+ let formatter = DateFormatter()
+ formatter.dateFormat = "yyyy-MM-dd HH:mm:ss.SSS"
+ formatter.locale = Locale(identifier: "en_US_POSIX")
+ formatter.timeZone = TimeZone(secondsFromGMT: 0)
+ return formatter
+ }()
+
+ static let formatterWithoutMillis: DateFormatter = {
+ let formatter = DateFormatter()
+ formatter.dateFormat = "yyyy-MM-dd HH:mm:ss"
+ formatter.locale = Locale(identifier: "en_US_POSIX")
+ formatter.timeZone = TimeZone(secondsFromGMT: 0)
+ return formatter
+ }()
+
+ static let isoFormatter: ISO8601DateFormatter = {
+ let formatter = ISO8601DateFormatter()
+ formatter.formatOptions = [.withInternetDateTime, .withFractionalSeconds]
+ formatter.timeZone = TimeZone(secondsFromGMT: 0)
+ return formatter
+ }()
}
- // TODO: Implement actual SQLite update (soft delete)
- // UPDATE Passkeys SET isDeleted = 1, updatedAt = ? WHERE credentialId = ?
+ let cleanedDateString = dateString.trimmingCharacters(in: .whitespacesAndNewlines)
+
+ if cleanedDateString.contains("Z") || cleanedDateString.contains("+") || cleanedDateString.contains("-") {
+ if let isoDate = StaticFormatters.isoFormatter.date(from: cleanedDateString) {
+ return isoDate
+ }
+ }
+
+ if let dateWithMillis = StaticFormatters.formatterWithMillis.date(from: cleanedDateString) {
+ return dateWithMillis
+ }
+
+ if let dateWithoutMillis = StaticFormatters.formatterWithoutMillis.date(from: cleanedDateString) {
+ return dateWithoutMillis
+ }
+
+ return nil
}
}
diff --git a/apps/mobile-app/ios/VaultStoreKit/VaultStore+PasskeyRegistration.swift b/apps/mobile-app/ios/VaultStoreKit/VaultStore+PasskeyRegistration.swift
new file mode 100644
index 000000000..c0775018a
--- /dev/null
+++ b/apps/mobile-app/ios/VaultStoreKit/VaultStore+PasskeyRegistration.swift
@@ -0,0 +1,78 @@
+import Foundation
+
+/**
+ * VaultStore extension for handling passkey registration requests
+ * from the iOS Autofill extension to the React Native app.
+ *
+ * This allows the extension to store registration request data that
+ * the React Native app can pick up via deep link, process the request,
+ * and store the result back for the extension to complete.
+ */
+extension VaultStore {
+ private enum PasskeyRegistrationKeys {
+ static let requestPrefix = "passkeyRegistrationRequest_"
+ static let resultPrefix = "passkeyRegistrationResult_"
+ static let cancelledPrefix = "passkeyRegistrationCancelled_"
+ }
+
+ /**
+ * Store a passkey registration request
+ */
+ public func storePasskeyRegistrationRequest(requestId: String, requestData: String) throws {
+ let key = PasskeyRegistrationKeys.requestPrefix + requestId
+ userDefaults.set(requestData, forKey: key)
+ userDefaults.synchronize()
+ }
+
+ /**
+ * Get a passkey registration request
+ */
+ public func getPasskeyRegistrationRequest(_ requestId: String) throws -> String? {
+ let key = PasskeyRegistrationKeys.requestPrefix + requestId
+ return userDefaults.string(forKey: key)
+ }
+
+ /**
+ * Store a passkey registration result
+ */
+ public func storePasskeyRegistrationResult(requestId: String, result: String) throws {
+ let key = PasskeyRegistrationKeys.resultPrefix + requestId
+ userDefaults.set(result, forKey: key)
+ userDefaults.synchronize()
+ }
+
+ /**
+ * Get a passkey registration result
+ */
+ public func getPasskeyRegistrationResult(_ requestId: String) throws -> String? {
+ let key = PasskeyRegistrationKeys.resultPrefix + requestId
+ return userDefaults.string(forKey: key)
+ }
+
+ /**
+ * Cancel a passkey registration
+ */
+ public func cancelPasskeyRegistration(_ requestId: String) throws {
+ let key = PasskeyRegistrationKeys.cancelledPrefix + requestId
+ userDefaults.set(true, forKey: key)
+ userDefaults.synchronize()
+ }
+
+ /**
+ * Check if a passkey registration was cancelled
+ */
+ public func isPasskeyRegistrationCancelled(_ requestId: String) -> Bool {
+ let key = PasskeyRegistrationKeys.cancelledPrefix + requestId
+ return userDefaults.bool(forKey: key)
+ }
+
+ /**
+ * Clean up passkey registration request data
+ */
+ public func cleanupPasskeyRegistrationRequest(_ requestId: String) {
+ userDefaults.removeObject(forKey: PasskeyRegistrationKeys.requestPrefix + requestId)
+ userDefaults.removeObject(forKey: PasskeyRegistrationKeys.resultPrefix + requestId)
+ userDefaults.removeObject(forKey: PasskeyRegistrationKeys.cancelledPrefix + requestId)
+ userDefaults.synchronize()
+ }
+}
diff --git a/apps/mobile-app/ios/VaultUI/Views/CredentialProviderView.swift b/apps/mobile-app/ios/VaultUI/Views/CredentialProviderView.swift
index 224816b0b..c1a0a76a6 100644
--- a/apps/mobile-app/ios/VaultUI/Views/CredentialProviderView.swift
+++ b/apps/mobile-app/ios/VaultUI/Views/CredentialProviderView.swift
@@ -260,18 +260,24 @@ public class CredentialProviderViewModel: ObservableObject {
return
}
- // If we only have one option, use it directly
+ // For normal autofill, determine the best identifier and fill immediately
let username = credential.username?.trimmingCharacters(in: .whitespacesAndNewlines)
let email = credential.alias?.email?.trimmingCharacters(in: .whitespacesAndNewlines)
-
- if (username?.isEmpty ?? true) || (email?.isEmpty ?? true) {
- let identifier = username?.isEmpty == false ? username! : (email ?? "")
- selectionHandler(identifier, credential.password?.value ?? "")
- return
+ let hasUsername = !(username?.isEmpty ?? true)
+ let hasEmail = !(email?.isEmpty ?? true)
+
+ // Prefer username over email if both exist, or use whichever is available
+ let identifier: String
+ if hasUsername {
+ identifier = username!
+ } else if hasEmail {
+ identifier = email!
+ } else {
+ identifier = ""
}
- // If we have both options, show selection sheet
- showSelectionOptions = true
+ // Fill both username and password immediately for normal autofill
+ selectionHandler(identifier, credential.password?.value ?? "")
}
func selectUsername() {
diff --git a/apps/mobile-app/ios/VaultUI/Views/PasskeyProviderView.swift b/apps/mobile-app/ios/VaultUI/Views/PasskeyProviderView.swift
new file mode 100644
index 000000000..327caafd0
--- /dev/null
+++ b/apps/mobile-app/ios/VaultUI/Views/PasskeyProviderView.swift
@@ -0,0 +1,269 @@
+import SwiftUI
+import AuthenticationServices
+import VaultModels
+
+/// Passkey provider view for selecting passkeys during authentication
+/// TODO: review file
+public struct PasskeyProviderView: View {
+ @ObservedObject public var viewModel: PasskeyProviderViewModel
+
+ @Environment(\.dismiss) private var dismiss
+ @Environment(\.colorScheme) private var colorScheme
+
+ public init(viewModel: PasskeyProviderViewModel) {
+ self._viewModel = ObservedObject(wrappedValue: viewModel)
+ }
+
+ public var body: some View {
+ NavigationView {
+ ZStack {
+ (colorScheme == .dark ? ColorConstants.Dark.background : ColorConstants.Light.background)
+ .ignoresSafeArea()
+
+ VStack(spacing: 0) {
+ SearchBarView(text: $viewModel.searchText)
+ .padding(.horizontal)
+ .padding(.vertical, 8)
+ .background(colorScheme == .dark ? ColorConstants.Dark.background : ColorConstants.Light.background)
+ .onChange(of: viewModel.searchText) { _ in
+ viewModel.filterCredentials()
+ }
+
+ if viewModel.isLoading {
+ Spacer()
+ ProgressView(NSLocalizedString("loading_passkeys", comment: ""))
+ .progressViewStyle(.circular)
+ .scaleEffect(1.5)
+ Spacer()
+ } else {
+ ScrollView {
+ if viewModel.filteredCredentials.isEmpty {
+ VStack(spacing: 20) {
+ Image(systemName: "key.fill")
+ .font(.system(size: 50))
+ .foregroundColor(colorScheme == .dark ? ColorConstants.Dark.text : ColorConstants.Light.text)
+
+ Text(NSLocalizedString("no_passkeys_found", comment: ""))
+ .font(.headline)
+ .foregroundColor(colorScheme == .dark ? ColorConstants.Dark.text : ColorConstants.Light.text)
+
+ Text(NSLocalizedString("no_passkeys_match", comment: ""))
+ .font(.subheadline)
+ .foregroundColor(colorScheme == .dark ? ColorConstants.Dark.text : ColorConstants.Light.text)
+ .multilineTextAlignment(.center)
+ }
+ .padding(.top, 60)
+ } else {
+ LazyVStack(spacing: 8) {
+ ForEach(viewModel.filteredCredentials, id: \.id) { credential in
+ PasskeyCredentialCard(
+ credential: credential,
+ rpId: viewModel.rpId,
+ action: {
+ viewModel.selectCredential(credential)
+ }
+ )
+ }
+ }
+ .padding(.horizontal)
+ .padding(.top, 8)
+ }
+ }
+ .refreshable {
+ await viewModel.loadCredentials()
+ }
+ }
+ }
+ }
+ .navigationTitle(NSLocalizedString("select_passkey", comment: ""))
+ .navigationBarTitleDisplayMode(.inline)
+ .toolbar {
+ ToolbarItem(placement: .navigationBarLeading) {
+ Button(NSLocalizedString("cancel", comment: "")) {
+ viewModel.cancel()
+ }
+ .foregroundColor(ColorConstants.Light.primary)
+ }
+ }
+ .alert(NSLocalizedString("error", comment: ""), isPresented: $viewModel.showError) {
+ Button(NSLocalizedString("ok", comment: "")) {
+ viewModel.dismissError()
+ }
+ } message: {
+ Text(viewModel.errorMessage)
+ }
+ .task {
+ try? await Task.sleep(nanoseconds: 100_000_000)
+ await viewModel.loadCredentials()
+ }
+ .onDisappear {
+ viewModel.cancel()
+ }
+ }
+ }
+}
+
+// MARK: - Passkey Credential Card
+
+struct PasskeyCredentialCard: View {
+ let credential: Credential
+ let rpId: String?
+ let action: () -> Void
+
+ @Environment(\.colorScheme) private var colorScheme
+
+ var body: some View {
+ Button(action: action) {
+ VStack(alignment: .leading, spacing: 12) {
+ HStack {
+ // Service logo or icon
+ if let logo = credential.service.logo, !logo.isEmpty,
+ let uiImage = UIImage(data: logo) {
+ Image(uiImage: uiImage)
+ .resizable()
+ .scaledToFit()
+ .frame(width: 40, height: 40)
+ .cornerRadius(8)
+ } else {
+ Image(systemName: "key.fill")
+ .font(.system(size: 24))
+ .foregroundColor(ColorConstants.Light.primary)
+ .frame(width: 40, height: 40)
+ }
+
+ VStack(alignment: .leading, spacing: 4) {
+ Text(credential.service.name ?? credential.service.url ?? "Unknown Service")
+ .font(.headline)
+ .foregroundColor(colorScheme == .dark ? ColorConstants.Dark.text : ColorConstants.Light.text)
+
+ if let username = credential.username, !username.isEmpty {
+ Text(username)
+ .font(.subheadline)
+ .foregroundColor(colorScheme == .dark ? ColorConstants.Dark.textMuted : ColorConstants.Light.textMuted)
+ } else if let email = credential.alias?.email {
+ Text(email)
+ .font(.subheadline)
+ .foregroundColor(colorScheme == .dark ? ColorConstants.Dark.textMuted : ColorConstants.Light.textMuted)
+ }
+
+ // Show passkey count
+ if let passkeys = credential.passkeys, !passkeys.isEmpty {
+ Text("\(passkeys.count) passkey\(passkeys.count > 1 ? "s" : "")")
+ .font(.caption)
+ .foregroundColor(ColorConstants.Light.primary)
+ }
+ }
+
+ Spacer()
+
+ Image(systemName: "chevron.right")
+ .foregroundColor(colorScheme == .dark ? ColorConstants.Dark.textMuted : ColorConstants.Light.textMuted)
+ }
+ }
+ .padding()
+ .background(colorScheme == .dark ? ColorConstants.Dark.accentBackground : ColorConstants.Light.accentBackground)
+ .cornerRadius(12)
+ }
+ .buttonStyle(PlainButtonStyle())
+ }
+}
+
+// MARK: - ViewModel
+
+public class PasskeyProviderViewModel: ObservableObject {
+ @Published var credentials: [Credential] = []
+ @Published var filteredCredentials: [Credential] = []
+ @Published var searchText = ""
+ @Published var isLoading = true
+ @Published var showError = false
+ @Published var errorMessage = ""
+ @Published public var rpId: String?
+
+ private let loader: () async throws -> [Credential]
+ private let selectionHandler: (Credential) -> Void
+ private let cancelHandler: () -> Void
+
+ public init(
+ loader: @escaping () async throws -> [Credential],
+ selectionHandler: @escaping (Credential) -> Void,
+ cancelHandler: @escaping () -> Void,
+ rpId: String? = nil
+ ) {
+ self.loader = loader
+ self.selectionHandler = selectionHandler
+ self.cancelHandler = cancelHandler
+ self.rpId = rpId
+ if let rpId = rpId {
+ self.searchText = rpId
+ }
+ }
+
+ @MainActor
+ public func setSearchFilter(_ text: String) {
+ self.searchText = text
+ self.filterCredentials()
+ }
+
+ @MainActor
+ func loadCredentials() async {
+ isLoading = true
+ do {
+ credentials = try await loader()
+ filterCredentials()
+ isLoading = false
+ } catch {
+ isLoading = false
+ errorMessage = NSLocalizedString("passkeys_load_error", comment: "")
+ showError = true
+ }
+ }
+
+ func filterCredentials() {
+ if searchText.isEmpty {
+ filteredCredentials = credentials
+ } else {
+ let lowercasedSearch = searchText.lowercased()
+ filteredCredentials = credentials.filter { credential in
+ // Filter by service name
+ if let serviceName = credential.service.name?.lowercased(),
+ serviceName.contains(lowercasedSearch) {
+ return true
+ }
+ // Filter by service URL
+ if let serviceUrl = credential.service.url?.lowercased(),
+ serviceUrl.contains(lowercasedSearch) {
+ return true
+ }
+ // Filter by username
+ if let username = credential.username?.lowercased(),
+ username.contains(lowercasedSearch) {
+ return true
+ }
+ // Filter by email
+ if let email = credential.alias?.email?.lowercased(),
+ email.contains(lowercasedSearch) {
+ return true
+ }
+ // Filter by passkey rpId
+ if let passkeys = credential.passkeys {
+ return passkeys.contains { passkey in
+ passkey.rpId.lowercased().contains(lowercasedSearch)
+ }
+ }
+ return false
+ }
+ }
+ }
+
+ func selectCredential(_ credential: Credential) {
+ selectionHandler(credential)
+ }
+
+ func cancel() {
+ cancelHandler()
+ }
+
+ func dismissError() {
+ showError = false
+ }
+}
diff --git a/apps/mobile-app/ios/VaultUI/Views/PasskeyRegistrationView.swift b/apps/mobile-app/ios/VaultUI/Views/PasskeyRegistrationView.swift
new file mode 100644
index 000000000..474407332
--- /dev/null
+++ b/apps/mobile-app/ios/VaultUI/Views/PasskeyRegistrationView.swift
@@ -0,0 +1,251 @@
+import SwiftUI
+import AuthenticationServices
+
+/// Passkey registration view for the autofill extension
+public struct PasskeyRegistrationView: View {
+ @ObservedObject public var viewModel: PasskeyRegistrationViewModel
+
+ @Environment(\.colorScheme) private var colorScheme
+
+ public init(viewModel: PasskeyRegistrationViewModel) {
+ self._viewModel = ObservedObject(wrappedValue: viewModel)
+ }
+
+ public var body: some View {
+ NavigationView {
+ ZStack {
+ (colorScheme == .dark ? ColorConstants.Dark.background : ColorConstants.Light.background)
+ .ignoresSafeArea()
+
+ ScrollView {
+ VStack(spacing: 24) {
+ // Header
+ VStack(spacing: 12) {
+ Image(systemName: "key.fill")
+ .font(.system(size: 60))
+ .foregroundColor(ColorConstants.Light.primary)
+ .padding(.top, 20)
+
+ Text(NSLocalizedString("passkey_registration", comment: ""))
+ .font(.title)
+ .fontWeight(.bold)
+ .foregroundColor(colorScheme == .dark ? ColorConstants.Dark.text : ColorConstants.Light.text)
+
+ Text(NSLocalizedString("passkey_registration_subtitle", comment: ""))
+ .font(.subheadline)
+ .foregroundColor(colorScheme == .dark ? ColorConstants.Dark.textMuted : ColorConstants.Light.textMuted)
+ .multilineTextAlignment(.center)
+ .padding(.horizontal)
+ }
+ .padding(.bottom, 20)
+
+ // Request details
+ VStack(spacing: 16) {
+ InfoRow(
+ label: "Website",
+ value: viewModel.rpId,
+ icon: "globe"
+ )
+
+ if let userName = viewModel.userName {
+ InfoRow(
+ label: "Username",
+ value: userName,
+ icon: "person.fill"
+ )
+ }
+ }
+ .padding(.horizontal)
+
+ // Info box
+ HStack(alignment: .top, spacing: 12) {
+ Image(systemName: "info.circle.fill")
+ .foregroundColor(ColorConstants.Light.primary)
+ .font(.system(size: 20))
+
+ Text(NSLocalizedString("passkey_registration_info", comment: ""))
+ .font(.footnote)
+ .foregroundColor(colorScheme == .dark ? ColorConstants.Dark.text : ColorConstants.Light.text)
+ .fixedSize(horizontal: false, vertical: true)
+ }
+ .padding()
+ .background(
+ (colorScheme == .dark ? ColorConstants.Dark.accentBackground : ColorConstants.Light.accentBackground)
+ .opacity(0.5)
+ )
+ .cornerRadius(12)
+ .padding(.horizontal)
+
+ Spacer()
+
+ // Action buttons
+ VStack(spacing: 12) {
+ Button(action: {
+ viewModel.openMainApp()
+ }, label: {
+ HStack {
+ Image(systemName: "arrow.right.circle.fill")
+ Text(NSLocalizedString("open_app_to_create", comment: ""))
+ }
+ .padding()
+ .frame(maxWidth: .infinity)
+ .background(ColorConstants.Light.primary)
+ .foregroundColor(.white)
+ .cornerRadius(8)
+ })
+
+ Button(action: {
+ viewModel.cancel()
+ }, label: {
+ Text(NSLocalizedString("cancel", comment: ""))
+ .padding()
+ .frame(maxWidth: .infinity)
+ .foregroundColor(ColorConstants.Light.primary)
+ })
+ }
+ .padding(.horizontal)
+ .padding(.bottom, 20)
+ }
+ }
+ }
+ .navigationBarHidden(true)
+ }
+ }
+}
+
+/// Info row component for displaying passkey registration details
+private struct InfoRow: View {
+ let label: String
+ let value: String
+ let icon: String
+
+ @Environment(\.colorScheme) private var colorScheme
+
+ var body: some View {
+ HStack(alignment: .top, spacing: 12) {
+ Image(systemName: icon)
+ .foregroundColor(ColorConstants.Light.primary)
+ .frame(width: 24)
+
+ VStack(alignment: .leading, spacing: 4) {
+ Text(label)
+ .font(.caption)
+ .foregroundColor(colorScheme == .dark ? ColorConstants.Dark.textMuted : ColorConstants.Light.textMuted)
+
+ Text(value)
+ .font(.body)
+ .foregroundColor(colorScheme == .dark ? ColorConstants.Dark.text : ColorConstants.Light.text)
+ }
+
+ Spacer()
+ }
+ .padding()
+ .background(
+ (colorScheme == .dark ? ColorConstants.Dark.accentBackground : ColorConstants.Light.accentBackground)
+ )
+ .cornerRadius(8)
+ }
+}
+
+/// View model for passkey registration
+public class PasskeyRegistrationViewModel: ObservableObject {
+ @Published public var requestId: String
+ @Published public var rpId: String
+ @Published public var origin: String
+ @Published public var userName: String?
+ @Published public var userDisplayName: String?
+
+ private let completionHandler: (Bool) -> Void
+ private let cancelHandler: () -> Void
+
+ public init(
+ requestId: String,
+ rpId: String,
+ origin: String,
+ userName: String? = nil,
+ userDisplayName: String? = nil,
+ completionHandler: @escaping (Bool) -> Void,
+ cancelHandler: @escaping () -> Void
+ ) {
+ self.requestId = requestId
+ self.rpId = rpId
+ self.origin = origin
+ self.userName = userName
+ self.userDisplayName = userDisplayName
+ self.completionHandler = completionHandler
+ self.cancelHandler = cancelHandler
+ }
+
+ public func openMainApp() {
+ // Build the deep link URL
+ var urlString = "net.aliasvault.app://credentials/passkey-create"
+ let encodedRequestId = requestId.addingPercentEncoding(withAllowedCharacters: .urlQueryAllowed) ?? ""
+ urlString += "?requestId=\(encodedRequestId)"
+
+ guard let url = URL(string: urlString) else {
+ print("PasskeyRegistration: Invalid URL string: \(urlString)")
+ completionHandler(false)
+ return
+ }
+
+ print("PasskeyRegistration: Opening main app with URL: \(url.absoluteString)")
+
+ // Use UIApplication.shared.open from the view model (works in button tap context)
+ UIApplication.shared.open(url, options: [:]) { [weak self] success in
+ print("PasskeyRegistration: UIApplication.shared.open completed with success=\(success)")
+
+ if success {
+ print("PasskeyRegistration: App opened successfully")
+ } else {
+ print("PasskeyRegistration: Failed to open app")
+ }
+
+ self?.completionHandler(success)
+ }
+ }
+
+ public func cancel() {
+ cancelHandler()
+ }
+}
+
+// MARK: - Previews
+#if DEBUG
+private struct PasskeyRegistrationView_Previews: PreviewProvider {
+ static var previews: some View {
+ PasskeyRegistrationView(
+ viewModel: PasskeyRegistrationViewModel(
+ requestId: "12345678-1234-1234-1234-123456789012",
+ rpId: "example.com",
+ origin: "https://example.com",
+ userName: "[email protected]",
+ userDisplayName: "John Doe",
+ completionHandler: { success in
+ print("Open app completed with success: \(success)")
+ },
+ cancelHandler: {
+ print("Cancel tapped")
+ }
+ )
+ )
+ .preferredColorScheme(.light)
+
+ PasskeyRegistrationView(
+ viewModel: PasskeyRegistrationViewModel(
+ requestId: "12345678-1234-1234-1234-123456789012",
+ rpId: "example.com",
+ origin: "https://example.com",
+ userName: nil,
+ userDisplayName: nil,
+ completionHandler: { success in
+ print("Open app completed with success: \(success)")
+ },
+ cancelHandler: {
+ print("Cancel tapped")
+ }
+ )
+ )
+ .preferredColorScheme(.dark)
+ }
+}
+#endif