Skip to content

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

Implement Swift passkey create persist flow (#520)

Leendert de Borst48acb81492f0
diff --git a/apps/mobile-app/hooks/useVaultSync.ts b/apps/mobile-app/hooks/useVaultSync.ts
index 536d44061..35d97792b 100644
--- a/apps/mobile-app/hooks/useVaultSync.ts
+++ b/apps/mobile-app/hooks/useVaultSync.ts
@@ -91,6 +91,8 @@ export const useVaultSync = () : {
onStatus?.(t('vault.syncingUpdatedVault'));
hasNewVault = await NativeVaultManager.syncVault();
+ console.log(`VaultSync: syncVault completed, hasNewVault=${hasNewVault}`);
+
// Add artificial delay for initial sync UX
if (enableDelay && hasNewVault) {
await new Promise(resolve => setTimeout(resolve, 1000));
@@ -129,63 +131,44 @@ export const useVaultSync = () : {
throw err;
}
- // If a new vault was downloaded, we need to unlock it
- if (hasNewVault) {
- try {
- // Vault was already stored by native layer, now unlock it
- await NativeVaultManager.unlockVault();
-
- // Check if the current vault version is known and up to date
- if (await NativeVaultManager.isVaultUnlocked() && await dbContext.hasPendingMigrations()) {
- onUpgradeRequired?.();
- return false;
- }
-
- onSuccess?.(true);
-
- // Register credential identities after successful vault sync
- try {
- await NativeVaultManager.registerCredentialIdentities();
- } catch (error) {
- // Don't fail the sync if credential registration fails
- }
+ try {
+ // We always re-unlock the vault to force reload of database connection
+ // This ensures React Native's SQLite connection sees changes made by native layer
+ console.log('VaultSync: Re-unlocking vault to refresh database connection');
+ await NativeVaultManager.unlockVault();
+
+ // Check if the vault needs migration
+ if (await dbContext.hasPendingMigrations()) {
+ onUpgradeRequired?.();
+ return false;
+ }
- return true;
- } catch (err) {
- if (err instanceof VaultVersionIncompatibleError) {
- await app.logout(t(err.message));
- return false;
- }
-
- // Vault could not be unlocked
- throw new Error(t('vault.errors.vaultDecryptFailed'));
+ // Add artificial delay for initial sync UX
+ if (enableDelay) {
+ await new Promise(resolve => setTimeout(resolve, hasNewVault ? 1000 : 300));
}
- }
- // Vault already up to date
- // Check if the vault needs migration
- if (await NativeVaultManager.isVaultUnlocked() && await dbContext.hasPendingMigrations()) {
- onUpgradeRequired?.();
- return false;
- }
+ onSuccess?.(hasNewVault);
- // Add artificial delay for initial sync UX
- if (enableDelay) {
- await new Promise(resolve => setTimeout(resolve, 300));
- }
+ // Register credential identities after sync
+ try {
+ await NativeVaultManager.registerCredentialIdentities();
+ console.log('Vault sync: Successfully registered credential identities');
+ } catch (error) {
+ console.warn('Vault sync: Failed to register credential identities:', error);
+ // Don't fail the sync if credential registration fails
+ }
- onSuccess?.(false);
+ return hasNewVault;
+ } catch (err) {
+ if (err instanceof VaultVersionIncompatibleError) {
+ await app.logout(t(err.message));
+ return false;
+ }
- // Register credential identities even when vault is up to date
- try {
- await NativeVaultManager.registerCredentialIdentities();
- console.log('Vault sync: Successfully registered credential identities (vault up to date)');
- } catch (error) {
- console.warn('Vault sync: Failed to register credential identities:', error);
- // Don't fail the sync if credential registration fails
+ // Vault could not be unlocked
+ throw new Error(t('vault.errors.vaultDecryptFailed'));
}
-
- return false;
} catch (err) {
console.error('Vault sync error:', err);
diff --git a/apps/mobile-app/ios/Autofill/CredentialProviderViewController+Passkey.swift b/apps/mobile-app/ios/Autofill/CredentialProviderViewController+Passkey.swift
index 9615bda4a..203f7144f 100644
--- a/apps/mobile-app/ios/Autofill/CredentialProviderViewController+Passkey.swift
+++ b/apps/mobile-app/ios/Autofill/CredentialProviderViewController+Passkey.swift
@@ -178,8 +178,18 @@ extension CredentialProviderViewController: PasskeyProviderDelegate {
clientDataHash: Data,
vaultStore: VaultStore
) {
+ // Store parameters for closure capture
+ let capturedRpId = rpId
+ let capturedUserName = userName
+ let capturedUserDisplayName = userDisplayName
+ let capturedUserId = userId
+ let capturedClientDataHash = clientDataHash
+ let capturedVaultStore = vaultStore
+
// Create view model with handlers
- let viewModel = PasskeyRegistrationViewModel(
+ // Use lazy initialization to avoid capturing viewModel before it's assigned
+ var viewModel: PasskeyRegistrationViewModel!
+ viewModel = PasskeyRegistrationViewModel(
requestId: "", // Not needed for direct creation
rpId: rpId,
origin: "https://\(rpId)",
@@ -190,12 +200,13 @@ extension CredentialProviderViewController: PasskeyProviderDelegate {
// Button was clicked - create the passkey directly in Swift
self.createPasskeyInSwift(
- rpId: rpId,
- userName: userName,
- userDisplayName: userDisplayName,
- userId: userId,
- clientDataHash: clientDataHash,
- vaultStore: vaultStore
+ rpId: capturedRpId,
+ userName: capturedUserName,
+ userDisplayName: capturedUserDisplayName,
+ userId: capturedUserId,
+ clientDataHash: capturedClientDataHash,
+ vaultStore: capturedVaultStore,
+ viewModel: viewModel
)
},
cancelHandler: { [weak self] in
@@ -242,11 +253,37 @@ extension CredentialProviderViewController: PasskeyProviderDelegate {
userDisplayName: String?,
userId: Data?,
clientDataHash: Data,
- vaultStore: VaultStore
+ vaultStore: VaultStore,
+ viewModel: PasskeyRegistrationViewModel
) {
// Create a Task to handle async operations
Task {
do {
+ // Initialize WebApiService for vault sync/mutate and favicon extraction
+ let webApiService = WebApiService()
+
+ // Step 1: Sync vault before creating passkey (to avoid conflicts)
+ await viewModel.setLoading(true, message: NSLocalizedString("vault_syncing", comment: "Syncing vault..."))
+
+ try await vaultStore.syncVault(using: webApiService)
+
+ // Step 2: Extract favicon from service URL
+ await viewModel.setLoading(true, message: NSLocalizedString("vault_syncing", comment: "Syncing vault..."))
+ print("PasskeyRegistration: Extracting favicon for \(rpId)...")
+ var logo: Data?
+ do {
+ logo = try await webApiService.extractFavicon(url: "https://\(rpId)")
+ if logo != nil {
+ print("PasskeyRegistration: Favicon extracted successfully")
+ } else {
+ print("PasskeyRegistration: No favicon found")
+ }
+ } catch {
+ print("PasskeyRegistration: Favicon extraction failed (continuing without logo): \(error)")
+ }
+
+ // Step 3: Create passkey credentials
+ await viewModel.setLoading(true, message: NSLocalizedString("creating_passkey", comment: "Creating passkey..."))
print("PasskeyRegistration: Creating passkey directly in Swift layer")
// Generate new credential ID (UUID that will be used as the passkey ID)
@@ -284,15 +321,18 @@ extension CredentialProviderViewController: PasskeyProviderDelegate {
isDeleted: false
)
+ // Step 4: Store credential with passkey in database
+ await viewModel.setLoading(true, message: NSLocalizedString("saving_to_vault", comment: "Saving to vault..."))
// Begin transaction
try vaultStore.beginTransaction()
- // Store credential with passkey in database
+ // Store credential with passkey and logo in database
let credential = try vaultStore.createCredentialWithPasskey(
rpId: rpId,
userName: userName,
userDisplayName: userDisplayName,
- passkey: passkey
+ passkey: passkey,
+ logo: logo
)
// Commit transaction to persist the data
@@ -300,13 +340,24 @@ extension CredentialProviderViewController: PasskeyProviderDelegate {
print("PasskeyRegistration: Credential and passkey stored in database - credentialId=\(credential.id.uuidString)")
- // Update the IdentityStore with the new credential (async call)
+ // Step 5: Upload vault changes to server
+ await viewModel.setLoading(true, message: NSLocalizedString("uploading_vault", comment: "Uploading vault..."))
+ print("PasskeyRegistration: Uploading vault changes to server...")
+ do {
+ try await vaultStore.mutateVault(using: webApiService)
+ print("PasskeyRegistration: Vault uploaded successfully")
+ } catch {
+ print("PasskeyRegistration: Vault upload failed (passkey saved locally): \(error)")
+ // Continue even if upload fails - passkey is saved locally
+ }
+
+ // Step 6: Update the IdentityStore with the new credential (async call)
let credentials = try vaultStore.getAllCredentials()
try await CredentialIdentityStore.shared.saveCredentialIdentities(credentials)
print("PasskeyRegistration: Updated CredentialIdentityStore")
- // Create the ASPasskeyRegistrationCredential to return to the system
+ // Step 7: Create the ASPasskeyRegistrationCredential to return to the system
let asCredential = ASPasskeyRegistrationCredential(
relyingParty: rpId,
clientDataHash: clientDataHash,
@@ -316,6 +367,9 @@ extension CredentialProviderViewController: PasskeyProviderDelegate {
print("PasskeyRegistration: Completing registration request")
+ // Hide loading overlay
+ await viewModel.setLoading(false)
+
// Complete the registration request (must be on main thread)
await MainActor.run {
self.extensionContext.completeRegistrationRequest(using: asCredential)
@@ -323,6 +377,10 @@ extension CredentialProviderViewController: PasskeyProviderDelegate {
} catch {
print("PasskeyRegistration error: \(error)")
+
+ // Hide loading overlay
+ await viewModel.setLoading(false)
+
// Cancel request (must be on main thread)
await MainActor.run {
self.extensionContext.cancelRequest(withError: NSError(
@@ -335,109 +393,6 @@ extension CredentialProviderViewController: PasskeyProviderDelegate {
}
}
- /**
- * 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
/**
diff --git a/apps/mobile-app/ios/VaultStoreKit/VaultStore+Passkey.swift b/apps/mobile-app/ios/VaultStoreKit/VaultStore+Passkey.swift
index 63fed0de4..adef1a2cc 100644
--- a/apps/mobile-app/ios/VaultStoreKit/VaultStore+Passkey.swift
+++ b/apps/mobile-app/ios/VaultStoreKit/VaultStore+Passkey.swift
@@ -392,7 +392,8 @@ extension VaultStore {
rpId: String,
userName: String?,
userDisplayName: String?,
- passkey: Passkey
+ passkey: Passkey,
+ logo: Data? = nil
) throws -> Credential {
guard let dbConn = dbConnection else {
throw VaultStoreError.vaultNotUnlocked
@@ -407,11 +408,15 @@ extension VaultStore {
// Create a minimal service for the RP
let serviceId = UUID()
let serviceTable = Table("Services")
+
+ // Convert logo Data to SQLite Blob if present
+ let logoBlob = logo.map { Blob(bytes: [UInt8]($0)) }
+
let serviceInsert = serviceTable.insert(
Expression<String>("Id") <- serviceId.uuidString,
Expression<String?>("Name") <- rpId,
Expression<String?>("Url") <- "https://\(rpId)",
- Expression<SQLite.Blob?>("Logo") <- nil,
+ Expression<SQLite.Blob?>("Logo") <- logoBlob,
Expression<String>("CreatedAt") <- timestamp,
Expression<String>("UpdatedAt") <- timestamp,
Expression<Int64>("IsDeleted") <- 0
@@ -442,7 +447,7 @@ extension VaultStore {
id: serviceId,
name: rpId,
url: "https://\(rpId)",
- logo: nil,
+ logo: logo,
createdAt: now,
updatedAt: now,
isDeleted: false
diff --git a/apps/mobile-app/ios/VaultStoreKit/VaultStore+PasskeyRegistration.swift b/apps/mobile-app/ios/VaultStoreKit/VaultStore+PasskeyRegistration.swift
deleted file mode 100644
index c0775018a..000000000
--- a/apps/mobile-app/ios/VaultStoreKit/VaultStore+PasskeyRegistration.swift
+++ /dev/null
@@ -1,78 +0,0 @@
-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/VaultStoreKit/VaultStore+Sync.swift b/apps/mobile-app/ios/VaultStoreKit/VaultStore+Sync.swift
index b1a8305c1..ec8104d3c 100644
--- a/apps/mobile-app/ios/VaultStoreKit/VaultStore+Sync.swift
+++ b/apps/mobile-app/ios/VaultStoreKit/VaultStore+Sync.swift
@@ -61,11 +61,13 @@ extension VaultStore {
requiresAuth: true
)
- // Check if we got a successful response (token refresh may have occurred)
+ // Check response status
+ // Note: WebApiService already handles 401 with automatic token refresh and retry
+ // If we still get a 401 here, it means the refresh failed and we should logout
guard statusResponse.statusCode == 200 else {
- // If still unauthorized after token refresh attempt
if statusResponse.statusCode == 401 {
- print("VaultStore: Authentication failed (401), tokens may be expired")
+ // Authentication failed even after token refresh attempt
+ print("VaultStore: Authentication failed (401) - token refresh also failed")
throw NSError(
domain: "VaultStore",
code: 401,
@@ -73,11 +75,12 @@ extension VaultStore {
)
}
+ // Other error (5xx, network, etc.) - go offline
setOfflineMode(true)
throw NSError(
domain: "VaultStore",
- code: -1,
- userInfo: [NSLocalizedDescriptionKey: "Server not available"]
+ code: statusResponse.statusCode,
+ userInfo: [NSLocalizedDescriptionKey: "Server returned status \(statusResponse.statusCode)"]
)
}
diff --git a/apps/mobile-app/ios/VaultStoreKit/WebApiService.swift b/apps/mobile-app/ios/VaultStoreKit/WebApiService.swift
index f570ef6cd..41179ee7e 100644
--- a/apps/mobile-app/ios/VaultStoreKit/WebApiService.swift
+++ b/apps/mobile-app/ios/VaultStoreKit/WebApiService.swift
@@ -30,6 +30,9 @@ public class WebApiService {
// Default API URL
private let defaultApiUrl = "https://app.aliasvault.net/api"
+ /// Shared UserDefaults for communication between main app and extension
+ private let userDefaults = UserDefaults(suiteName: VaultConstants.userDefaultsSuite)!
+
public init() {}
// MARK: - Configuration Management
@@ -38,14 +41,15 @@ public class WebApiService {
* Set the API URL
*/
public func setApiUrl(_ url: String) throws {
- UserDefaults.standard.set(url, forKey: apiUrlKey)
+ userDefaults.set(url, forKey: apiUrlKey)
+ userDefaults.synchronize()
}
/**
* Get the API URL
*/
public func getApiUrl() -> String {
- return UserDefaults.standard.string(forKey: apiUrlKey) ?? defaultApiUrl
+ return userDefaults.string(forKey: apiUrlKey) ?? defaultApiUrl
}
/**
@@ -63,30 +67,32 @@ public class WebApiService {
* Set both access and refresh tokens
*/
public func setAuthTokens(accessToken: String, refreshToken: String) throws {
- UserDefaults.standard.set(accessToken, forKey: accessTokenKey)
- UserDefaults.standard.set(refreshToken, forKey: refreshTokenKey)
+ userDefaults.set(accessToken, forKey: accessTokenKey)
+ userDefaults.set(refreshToken, forKey: refreshTokenKey)
+ userDefaults.synchronize()
}
/**
* Get the access token
*/
public func getAccessToken() -> String? {
- return UserDefaults.standard.string(forKey: accessTokenKey)
+ return userDefaults.string(forKey: accessTokenKey)
}
/**
* Get the refresh token
*/
public func getRefreshToken() -> String? {
- return UserDefaults.standard.string(forKey: refreshTokenKey)
+ return userDefaults.string(forKey: refreshTokenKey)
}
/**
* Clear both access and refresh tokens
*/
public func clearAuthTokens() {
- UserDefaults.standard.removeObject(forKey: accessTokenKey)
- UserDefaults.standard.removeObject(forKey: refreshTokenKey)
+ userDefaults.removeObject(forKey: accessTokenKey)
+ userDefaults.removeObject(forKey: refreshTokenKey)
+ userDefaults.synchronize()
}
// MARK: - HTTP Request Execution
@@ -121,19 +127,26 @@ public class WebApiService {
// Handle 401 Unauthorized - attempt token refresh
if response.statusCode == 401 && requiresAuth {
+ print("WebApiService: Got 401 response, attempting token refresh...")
+
if let newToken = try await refreshAccessToken() {
+ print("WebApiService: Token refresh successful, retrying original request")
// Retry the request with the new token
var retryHeaders = headers
retryHeaders["Authorization"] = "Bearer \(newToken)"
retryHeaders["X-AliasVault-Client"] = getClientVersionHeader()
- return try await executeRawRequest(
+ let retryResponse = try await executeRawRequest(
method: method,
endpoint: endpoint,
body: body,
headers: retryHeaders
)
+
+ print("WebApiService: Retry completed with status \(retryResponse.statusCode)")
+ return retryResponse
} else {
+ print("WebApiService: Token refresh failed, returning 401")
// Token refresh failed, return 401 response
return response
}
@@ -275,6 +288,57 @@ public class WebApiService {
return "ios-\(baseVersion)"
}
+ // MARK: - Favicon Extraction
+
+ /**
+ * Extract favicon from a URL
+ * Returns the favicon image data as base64-decoded bytes, or nil if extraction failed
+ */
+ public func extractFavicon(url: String) async throws -> Data? {
+ // URL encode the service URL parameter
+ guard let encodedUrl = url.addingPercentEncoding(withAllowedCharacters: .urlQueryAllowed) else {
+ print("WebApiService: Failed to encode URL for favicon extraction")
+ return nil
+ }
+
+ do {
+ // Make request with 5 second timeout
+ let response = try await executeRequest(
+ method: "GET",
+ endpoint: "Favicon/Extract?url=\(encodedUrl)",
+ body: nil,
+ headers: [:],
+ requiresAuth: false
+ )
+
+ guard response.statusCode == 200 else {
+ print("WebApiService: Favicon extraction failed with status \(response.statusCode)")
+ return nil
+ }
+
+ // Parse JSON response
+ guard let responseData = response.body.data(using: .utf8),
+ let json = try? JSONSerialization.jsonObject(with: responseData) as? [String: Any],
+ let imageBase64 = json["image"] as? String else {
+ print("WebApiService: Failed to parse favicon response")
+ return nil
+ }
+
+ // Decode base64 image
+ guard let imageData = Data(base64Encoded: imageBase64) else {
+ print("WebApiService: Failed to decode base64 favicon image")
+ return nil
+ }
+
+ print("WebApiService: Successfully extracted favicon (\(imageData.count) bytes)")
+ return imageData
+
+ } catch {
+ print("WebApiService: Favicon extraction error: \(error)")
+ return nil
+ }
+ }
+
// MARK: - Token Revocation
/**
diff --git a/apps/mobile-app/ios/VaultUI/Views/PasskeyRegistrationView.swift b/apps/mobile-app/ios/VaultUI/Views/PasskeyRegistrationView.swift
index a783317ea..0206517e8 100644
--- a/apps/mobile-app/ios/VaultUI/Views/PasskeyRegistrationView.swift
+++ b/apps/mobile-app/ios/VaultUI/Views/PasskeyRegistrationView.swift
@@ -17,6 +17,7 @@ public struct PasskeyRegistrationView: View {
(colorScheme == .dark ? ColorConstants.Dark.background : ColorConstants.Light.background)
.ignoresSafeArea()
+ // Main content
ScrollView {
VStack(spacing: 24) {
// Header
@@ -107,12 +108,70 @@ public struct PasskeyRegistrationView: View {
.padding(.bottom, 20)
}
}
+ .opacity(viewModel.isLoading ? 0.3 : 1.0)
+ .disabled(viewModel.isLoading)
+
+ // Loading overlay
+ if viewModel.isLoading {
+ LoadingOverlayView(message: viewModel.loadingMessage)
+ }
}
.navigationBarHidden(true)
}
}
}
+/// Loading overlay component with AliasVault branding
+private struct LoadingOverlayView: View {
+ let message: String
+ @State private var isAnimating = false
+
+ var body: some View {
+ ZStack {
+ // Semi-transparent background
+ Color.black.opacity(0.4)
+ .ignoresSafeArea()
+
+ // Loading card
+ VStack(spacing: 20) {
+ // AliasVault logo animation
+ Image(systemName: "shield.fill")
+ .font(.system(size: 60))
+ .foregroundColor(ColorConstants.Light.primary)
+ .rotationEffect(Angle(degrees: isAnimating ? 360 : 0))
+ .animation(
+ Animation.linear(duration: 2.0)
+ .repeatForever(autoreverses: false),
+ value: isAnimating
+ )
+ .onAppear {
+ isAnimating = true
+ }
+
+ // Loading message
+ if !message.isEmpty {
+ Text(message)
+ .font(.body)
+ .foregroundColor(.white)
+ .multilineTextAlignment(.center)
+ .padding(.horizontal)
+ }
+
+ // Progress indicator
+ ProgressView()
+ .progressViewStyle(CircularProgressViewStyle(tint: .white))
+ .scaleEffect(1.2)
+ }
+ .padding(30)
+ .background(
+ RoundedRectangle(cornerRadius: 16)
+ .fill(Color(white: 0.2, opacity: 0.95))
+ )
+ .shadow(radius: 20)
+ }
+ }
+}
+
/// Info row component for displaying passkey registration details
private struct InfoRow: View {
let label: String
@@ -154,6 +213,8 @@ public class PasskeyRegistrationViewModel: ObservableObject {
@Published public var origin: String
@Published public var userName: String?
@Published public var userDisplayName: String?
+ @Published public var isLoading: Bool = false
+ @Published public var loadingMessage: String = ""
private let completionHandler: (Bool) -> Void
private let cancelHandler: () -> Void
@@ -176,6 +237,13 @@ public class PasskeyRegistrationViewModel: ObservableObject {
self.cancelHandler = cancelHandler
}
+ /// Update loading state (called from main thread)
+ @MainActor
+ public func setLoading(_ loading: Bool, message: String = "") {
+ self.isLoading = loading
+ self.loadingMessage = message
+ }
+
public func createPasskey() {
// Trigger passkey creation in Swift
print("PasskeyRegistration: Create passkey button clicked")