Skip to content

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

Add "link to credential" prompt for iOS autofill (#1979)

Leendert de Borst04968032fd1e
diff --git a/apps/mobile-app/ios/Autofill/CredentialProviderViewController+Credential.swift b/apps/mobile-app/ios/Autofill/CredentialProviderViewController+Credential.swift
index d150629fe..1eb961a27 100644
--- a/apps/mobile-app/ios/Autofill/CredentialProviderViewController+Credential.swift
+++ b/apps/mobile-app/ios/Autofill/CredentialProviderViewController+Credential.swift
@@ -24,7 +24,41 @@ extension CredentialProviderViewController: CredentialProviderDelegate {
cancelHandler: {
self.handleCancel()
},
- serviceUrl: serviceUrl
+ serviceUrl: serviceUrl,
+ urlLinker: { itemId, url in
+ /*
+ * Step 1 — Append the URL/app identifier to the chosen credential's
+ * `login.url` multi-value field.
+ */
+ do {
+ try vaultStore.appendUrl(toItemId: itemId, url: url)
+ } catch {
+ print("[Autofill] Failed to append URL to credential: \(error)")
+ return
+ }
+
+ /*
+ * Step 2 — Push the change to the server (skipped if offline, client will retry later).
+ */
+ let webApiService = WebApiService()
+ do {
+ try await vaultStore.mutateVault(using: webApiService)
+ } catch {
+ print("[Autofill] Vault sync after URL link failed (vault stays dirty for main app to retry): \(error)")
+ }
+
+ /*
+ * Step 3 — Refresh the iOS credential identity store with the
+ * new URL.
+ */
+ do {
+ let credentials = try vaultStore.getAllAutofillCredentials()
+ try await CredentialIdentityStore.shared.saveCredentialIdentities(credentials)
+ print("[Autofill] Refreshed iOS credential identity cache (\(credentials.count) credentials)")
+ } catch {
+ print("[Autofill] Failed to refresh iOS credential identity cache: \(error)")
+ }
+ }
)
// Set text insertion mode if needed
diff --git a/apps/mobile-app/ios/Autofill/CredentialProviderViewController.swift b/apps/mobile-app/ios/Autofill/CredentialProviderViewController.swift
index 769b4e534..8cb783011 100644
--- a/apps/mobile-app/ios/Autofill/CredentialProviderViewController.swift
+++ b/apps/mobile-app/ios/Autofill/CredentialProviderViewController.swift
@@ -320,9 +320,11 @@ public class CredentialProviderViewController: ASCredentialProviderViewControlle
override public func prepareCredentialList(for serviceIdentifiers: [ASCredentialServiceIdentifier]) {
let matchedDomains = serviceIdentifiers.map { $0.identifier.lowercased() }
if let firstDomain = matchedDomains.first {
- print("CredentialProviderViewController: First domain: \(firstDomain)")
+ // Normalize URL to remove query parameters and trailing slashes
+ let normalized = AutofillUrlNormalizer.normalize(firstDomain)
+ print("CredentialProviderViewController: First domain: \(firstDomain) → normalized: \(normalized)")
- initialServiceUrl = firstDomain
+ initialServiceUrl = normalized
}
}
diff --git a/apps/mobile-app/ios/VaultStoreKit/Database/Repositories/ItemRepository.swift b/apps/mobile-app/ios/VaultStoreKit/Database/Repositories/ItemRepository.swift
index db1edd7b3..c7895c8c4 100644
--- a/apps/mobile-app/ios/VaultStoreKit/Database/Repositories/ItemRepository.swift
+++ b/apps/mobile-app/ios/VaultStoreKit/Database/Repositories/ItemRepository.swift
@@ -261,6 +261,45 @@ public class ItemRepository: BaseRepository {
}
}
+ /// Append a single value to a multi-value field on an existing item without
+ /// touching other field rows.
+ /// - Parameters:
+ /// - itemId: The UUID of the item to append the value to (uppercased string)
+ /// - fieldKey: The system FieldKey to append under (e.g. `FieldKey.loginUrl`)
+ /// - value: The value to append
+ /// - Returns: The number of rows affected by the parent Item's UpdatedAt bump
+ @discardableResult
+ public func appendFieldValue(
+ itemId: String,
+ fieldKey: String,
+ value: String
+ ) throws -> Int {
+ return try withTransaction {
+ let now = self.now()
+
+ // Insert a fresh FieldValue row. Using a high weight so the new
+ // value sorts after any existing rows for the same key.
+ try client.executeUpdate(FieldValueQueries.insert, params: [
+ generateId(),
+ itemId,
+ nil, // FieldDefinitionId (system field)
+ fieldKey,
+ value,
+ 9999,
+ now,
+ now,
+ 0
+ ])
+
+ // Bump the parent Item's UpdatedAt so the change is picked up by
+ // the sync layer.
+ return try client.executeUpdate(
+ "UPDATE Items SET UpdatedAt = ? WHERE Id = ?",
+ params: [now, itemId]
+ )
+ }
+ }
+
// MARK: - Private Helpers
/// Insert field values for an item.
diff --git a/apps/mobile-app/ios/VaultStoreKit/VaultStore+Query.swift b/apps/mobile-app/ios/VaultStoreKit/VaultStore+Query.swift
index b6b6a8aff..390099648 100644
--- a/apps/mobile-app/ios/VaultStoreKit/VaultStore+Query.swift
+++ b/apps/mobile-app/ios/VaultStoreKit/VaultStore+Query.swift
@@ -290,6 +290,20 @@ extension VaultStore {
return try itemRepository.update(item)
}
+ /// Append a URL to an existing credential's `login.url` multi-value field
+ /// without disturbing existing URLs on the credential. Caller is responsible
+ /// for kicking off `mutateVault(using:)` afterwards to push the change.
+ /// - Parameters:
+ /// - itemId: The UUID of the credential to append to
+ /// - url: The URL or app package identifier to add
+ public func appendUrl(toItemId itemId: UUID, url: String) throws {
+ try itemRepository.appendFieldValue(
+ itemId: itemId.uuidString.uppercased(),
+ fieldKey: FieldKey.loginUrl,
+ value: url
+ )
+ }
+
// MARK: - Autofill Credentials
/// Get all items for autofill from the database.
diff --git a/apps/mobile-app/ios/VaultUI/Selection/CredentialProviderView.swift b/apps/mobile-app/ios/VaultUI/Selection/CredentialProviderView.swift
index ca53d8a8c..89fe99438 100644
--- a/apps/mobile-app/ios/VaultUI/Selection/CredentialProviderView.swift
+++ b/apps/mobile-app/ios/VaultUI/Selection/CredentialProviderView.swift
@@ -61,18 +61,11 @@ public struct CredentialProviderView: View {
if !viewModel.isChoosingTextToInsert {
VStack(spacing: 12) {
Button(action: {
- var urlString = "aliasvault://items/add-edit-page"
- if let serviceUrl = viewModel.serviceUrl {
- let encodedUrl = serviceUrl.addingPercentEncoding(withAllowedCharacters: .urlQueryAllowed) ?? ""
- urlString += "?itemUrl=\(encodedUrl)"
- }
- if let url = URL(string: urlString) {
- UIApplication.shared.open(url, options: [:], completionHandler: nil)
- }
+ openAutofillActionPicker(serviceUrl: viewModel.serviceUrl)
}, label: {
HStack {
Image(systemName: "plus.circle.fill")
- Text(String(localized: "create_new_item", bundle: locBundle))
+ Text(String(localized: "open_aliasvault", bundle: locBundle))
}
.padding()
.frame(maxWidth: .infinity)
@@ -92,7 +85,11 @@ public struct CredentialProviderView: View {
credential: credential,
isChoosingTextToInsert: viewModel.isChoosingTextToInsert,
onSelect: { username, password in
- viewModel.handleSelection(username: username, password: password)
+ viewModel.requestSelection(
+ credential: credential,
+ username: username,
+ password: password
+ )
},
onCopy: {
viewModel.cancel()
@@ -122,14 +119,7 @@ public struct CredentialProviderView: View {
ToolbarItem(placement: .navigationBarTrailing) {
HStack {
Button(action: {
- var urlString = "aliasvault://items/add-edit-page"
- if let serviceUrl = viewModel.serviceUrl {
- let encodedUrl = serviceUrl.addingPercentEncoding(withAllowedCharacters: .urlQueryAllowed) ?? ""
- urlString += "?itemUrl=\(encodedUrl)"
- }
- if let url = URL(string: urlString) {
- UIApplication.shared.open(url, options: [:], completionHandler: nil)
- }
+ openAutofillActionPicker(serviceUrl: viewModel.serviceUrl)
}, label: {
Image(systemName: "plus")
.foregroundColor(colors.primary)
@@ -144,6 +134,35 @@ public struct CredentialProviderView: View {
} message: {
Text(viewModel.errorMessage)
}
+ .alert(
+ String(localized: "link_url_prompt_title", bundle: locBundle),
+ isPresented: linkPromptIsPresented,
+ presenting: viewModel.pendingLinkSelection
+ ) { _ in
+ Button(String(localized: "link_url_prompt_link_action", bundle: locBundle)) {
+ viewModel.confirmLinkAndFill()
+ }
+ Button(String(localized: "link_url_prompt_skip_action", bundle: locBundle)) {
+ viewModel.declineLinkAndFill()
+ }
+ Button(String(localized: "cancel", bundle: locBundle), role: .cancel) {
+ viewModel.pendingLinkSelection = nil
+ }
+ } message: { pending in
+ Text(linkPromptMessage(for: pending))
+ }
+ .overlay {
+ if viewModel.isLinkingUrl {
+ ZStack {
+ Color.black.opacity(0.4)
+ .ignoresSafeArea()
+ ProgressView(String(localized: "linking_url", bundle: locBundle))
+ .padding(20)
+ .background(colors.background)
+ .cornerRadius(12)
+ }
+ }
+ }
.task {
try? await Task.sleep(nanoseconds: 100_000_000)
await viewModel.loadCredentials()
@@ -153,6 +172,47 @@ public struct CredentialProviderView: View {
}
}
}
+
+ /// Two-way binding that maps the optional pendingLinkSelection to a Bool
+ /// for SwiftUI's `alert(_:isPresented:presenting:)` modifier. Setting the
+ /// bound value to `false` clears the pending selection on the view-model.
+ private var linkPromptIsPresented: Binding<Bool> {
+ Binding(
+ get: { viewModel.pendingLinkSelection != nil },
+ set: { newValue in
+ if !newValue {
+ viewModel.pendingLinkSelection = nil
+ }
+ }
+ )
+ }
+
+ /// Build the alert message, substituting the requesting URL/app and the
+ /// chosen credential's name into the localized template.
+ private func linkPromptMessage(for pending: PendingLinkSelection) -> String {
+ let template = String(localized: "link_url_prompt_message", bundle: locBundle)
+ let serviceUrl = viewModel.serviceUrl ?? ""
+ let name = pending.credentialName.isEmpty
+ ? String(localized: "untitled_credential", bundle: locBundle)
+ : pending.credentialName
+ return template
+ .replacingOccurrences(of: "{{url}}", with: serviceUrl)
+ .replacingOccurrences(of: "{{name}}", with: name)
+ }
+}
+
+/// Open the React Native "what would you like to do?" picker in the main
+/// AliasVault app via deep link. Shared by the empty-state CTA and the
+/// toolbar "+" button so iOS and Android land in the same flow.
+private func openAutofillActionPicker(serviceUrl: String?) {
+ var urlString = "aliasvault://items/autofill-open-app"
+ if let serviceUrl = serviceUrl,
+ let encodedUrl = serviceUrl.addingPercentEncoding(withAllowedCharacters: .urlQueryAllowed) {
+ urlString += "?itemUrl=\(encodedUrl)"
+ }
+ if let url = URL(string: urlString) {
+ UIApplication.shared.open(url, options: [:], completionHandler: nil)
+ }
}
// MARK: - AutofillCredentialCardWithSelection
@@ -219,6 +279,15 @@ private struct AutofillCredentialCardWithSelection: View {
// MARK: - ViewModel
+/// State for the "do you want to link this URL/app to the credential?" alert.
+/// Held on the view-model while the alert is visible.
+public struct PendingLinkSelection {
+ public let credentialId: UUID
+ public let credentialName: String
+ public let username: String
+ public let password: String
+}
+
public class CredentialProviderViewModel: ObservableObject {
@Published var credentials: [AutofillCredential] = []
@Published var filteredCredentials: [AutofillCredential] = []
@@ -228,21 +297,31 @@ public class CredentialProviderViewModel: ObservableObject {
@Published var errorMessage = ""
@Published public var isChoosingTextToInsert = false
@Published public var serviceUrl: String?
+ @Published public var pendingLinkSelection: PendingLinkSelection?
+ @Published public var isLinkingUrl = false
private let loader: () async throws -> [AutofillCredential]
private let selectionHandler: (String, String) -> Void
private let cancelHandler: () -> Void
+ /// Optional async handler that, given an item ID and the requesting service URL,
+ /// appends the URL to that item's `login.url` field and syncs the vault.
+ /// When nil, the link-prompt flow is disabled and selection always falls through
+ /// directly to `selectionHandler`.
+ private let urlLinker: ((UUID, String) async -> Void)?
+
public init(
loader: @escaping () async throws -> [AutofillCredential],
selectionHandler: @escaping (String, String) -> Void,
cancelHandler: @escaping () -> Void,
- serviceUrl: String? = nil
+ serviceUrl: String? = nil,
+ urlLinker: ((UUID, String) async -> Void)? = nil
) {
self.loader = loader
self.selectionHandler = selectionHandler
self.cancelHandler = cancelHandler
self.serviceUrl = serviceUrl
+ self.urlLinker = urlLinker
if let url = serviceUrl {
self.searchText = url
}
@@ -286,6 +365,67 @@ public class CredentialProviderViewModel: ObservableObject {
}
}
+ /// Called by the credential card when the user taps a credential to fill.
+ /// Decides between filling immediately or first prompting the user to
+ /// link the requesting URL/app to this credential's URL list.
+ @MainActor
+ func requestSelection(credential: AutofillCredential, username: String, password: String) {
+ // Skip the link-prompt flow when we don't have everything we need
+ // (no service URL, no linker injected, or in text-insertion mode).
+ guard !isChoosingTextToInsert,
+ let serviceUrl = serviceUrl,
+ !serviceUrl.isEmpty,
+ urlLinker != nil else {
+ selectionHandler(username, password)
+ return
+ }
+
+ // If the requesting URL is already on this credential, we don't need to prompt again.
+ let alreadyLinked = credential.serviceUrls.contains { existing in
+ AutofillUrlNormalizer.normalize(existing).caseInsensitiveCompare(serviceUrl) == .orderedSame
+ }
+ if alreadyLinked {
+ selectionHandler(username, password)
+ return
+ }
+
+ pendingLinkSelection = PendingLinkSelection(
+ credentialId: credential.id,
+ credentialName: credential.serviceName ?? "",
+ username: username,
+ password: password
+ )
+ }
+
+ /// User confirmed linking. Append the URL locally + sync, then complete fill.
+ @MainActor
+ func confirmLinkAndFill() {
+ guard let pending = pendingLinkSelection,
+ let serviceUrl = serviceUrl,
+ let urlLinker = urlLinker else {
+ pendingLinkSelection = nil
+ return
+ }
+ pendingLinkSelection = nil
+ isLinkingUrl = true
+
+ Task { @MainActor in
+ await urlLinker(pending.credentialId, serviceUrl)
+ isLinkingUrl = false
+ selectionHandler(pending.username, pending.password)
+ }
+ }
+
+ /// User declined linking. Just complete the fill as-is.
+ @MainActor
+ func declineLinkAndFill() {
+ guard let pending = pendingLinkSelection else {
+ return
+ }
+ pendingLinkSelection = nil
+ selectionHandler(pending.username, pending.password)
+ }
+
func handleSelection(username: String, password: String) {
selectionHandler(username, password)
}
diff --git a/apps/mobile-app/ios/VaultUI/Selection/Utils/AutofillUrlNormalizer.swift b/apps/mobile-app/ios/VaultUI/Selection/Utils/AutofillUrlNormalizer.swift
new file mode 100644
index 000000000..ae7c1659d
--- /dev/null
+++ b/apps/mobile-app/ios/VaultUI/Selection/Utils/AutofillUrlNormalizer.swift
@@ -0,0 +1,36 @@
+import Foundation
+
+/// Normalizes service URLs supplied by the iOS autofill subsystem before
+/// we store them on a credential or compare them to existing credential URLs.
+public enum AutofillUrlNormalizer {
+ /// Regex matching any `<scheme>://` prefix (RFC 3986 scheme syntax).
+ /// Used so we don't accidentally prepend `https://` onto strings that
+ /// already have a non-http scheme like `chrome://` or `app://`.
+ private static let schemePrefixPattern = "^[a-zA-Z][a-zA-Z0-9+.-]*://"
+
+ /// Normalize a service URL/identifier for storage and comparison.
+ /// - Parameter raw: The URL or bare domain as supplied by iOS, possibly
+ /// already lowercased and with a trailing path/query/fragment.
+ /// - Returns: A canonical URL string (`https://host[/path]`) suitable for
+ /// storage. Returns the trimmed input unchanged if it's empty or if
+ /// `URLComponents` can't parse the result.
+ public static func normalize(_ raw: String) -> String {
+ let trimmed = raw.trimmingCharacters(in: .whitespacesAndNewlines)
+ guard !trimmed.isEmpty else {
+ return trimmed
+ }
+
+ // Prepend https:// only when there isn't already a scheme. We test for
+ // any scheme (not just http/https) so values like `chrome://newtab`
+ // pass through unchanged rather than becoming `https://chrome://newtab`.
+ let hasScheme = trimmed.range(of: schemePrefixPattern, options: .regularExpression) != nil
+ let withScheme = hasScheme ? trimmed : "https://\(trimmed)"
+
+ guard var components = URLComponents(string: withScheme) else {
+ return withScheme
+ }
+ components.query = nil
+ components.fragment = nil
+ return components.url?.absoluteString ?? withScheme
+ }
+}
diff --git a/apps/mobile-app/ios/VaultUI/en.lproj/Localizable.strings b/apps/mobile-app/ios/VaultUI/en.lproj/Localizable.strings
index b5529bcb7..9cdb8bf1f 100644
--- a/apps/mobile-app/ios/VaultUI/en.lproj/Localizable.strings
+++ b/apps/mobile-app/ios/VaultUI/en.lproj/Localizable.strings
@@ -13,6 +13,13 @@
"no_items_found" = "No items found";
"no_items_match" = "No existing items match your search";
"create_new_item" = "Create New Item";
+"open_aliasvault" = "Open AliasVault";
+"untitled_credential" = "this credential";
+"link_url_prompt_title" = "Link to credential?";
+"link_url_prompt_message" = "Add \"{{url}}\" to {{name}} so AliasVault recognises this app or website next time?";
+"link_url_prompt_link_action" = "Link and fill";
+"link_url_prompt_skip_action" = "Just fill";
+"linking_url" = "Linking...";
"select_item" = "Select Item";
"select_text_to_insert" = "Select Text to Insert";
"choose_username" = "Choose Username";