Skip to content

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

Refactor native iOS parts (#771)

Leendert de Borst30a6315e9e48
diff --git a/apps/mobile-app/ios/.swiftlint.yml b/apps/mobile-app/ios/.swiftlint.yml
index 995cd787d..c8eeb636d 100644
--- a/apps/mobile-app/ios/.swiftlint.yml
+++ b/apps/mobile-app/ios/.swiftlint.yml
@@ -1,4 +1,3 @@
-# .swiftlint.yml
included:
- AliasVault
- Autofill
@@ -6,49 +5,52 @@ included:
- VaultStoreKit
- VaultStoreKitTests
- VaultUI
+
excluded:
- Pods
- Carthage
+# Rules that require 'analyze' mode
+analyzer_rules:
+ - explicit_self
+
opt_in_rules:
- explicit_top_level_acl
- - comment_spacing
- vertical_whitespace
- missing_docs
- file_header
- - multiline_comment_briefs
- function_parameter_count
- redundant_optional_initialization
- discouraged_optional_boolean
disabled_rules:
- trailing_whitespace
- - line_length
# Customize rules
line_length:
- warning: 120
- error: 150
+ warning: 200
+ error: 250
-comment_spacing:
- error: true
+comment_spacing: # fixed invalid configuration
+ severity: error
missing_docs:
warning: true
- include:
+ included:
- public
vertical_whitespace:
max_empty_lines: 1
-explicit_top_level_acl: warning
+explicit_top_level_acl:
+ severity: warning
file_header:
- required: true
-
-multiline_comment_briefs:
- warning: true
-
-indentation:
- indentation_width: 2
- include_comments: true
+ required: always
+ template: |
+ //
+ // %file%
+ // %project%
+ //
+ // Created by %author% on %date%.
+ //
\ No newline at end of file
diff --git a/apps/mobile-app/ios/AliasVault.xcodeproj/project.pbxproj b/apps/mobile-app/ios/AliasVault.xcodeproj/project.pbxproj
index b78acf552..3072c0675 100644
--- a/apps/mobile-app/ios/AliasVault.xcodeproj/project.pbxproj
+++ b/apps/mobile-app/ios/AliasVault.xcodeproj/project.pbxproj
@@ -3,7 +3,7 @@
archiveVersion = 1;
classes = {
};
- objectVersion = 60;
+ objectVersion = 70;
objects = {
/* Begin PBXBuildFile section */
@@ -190,7 +190,7 @@
/* End PBXFileReference section */
/* Begin PBXFileSystemSynchronizedBuildFileExceptionSet section */
- CEE9098F2DA548C7008D568F /* Exceptions for "Autofill" folder in "Autofill" target */ = {
+ CEE9098F2DA548C7008D568F /* PBXFileSystemSynchronizedBuildFileExceptionSet */ = {
isa = PBXFileSystemSynchronizedBuildFileExceptionSet;
membershipExceptions = (
Info.plist,
@@ -200,62 +200,11 @@
/* End PBXFileSystemSynchronizedBuildFileExceptionSet section */
/* Begin PBXFileSystemSynchronizedRootGroup section */
- CEE480882DBE86DC00F4A367 /* VaultStoreKit */ = {
- isa = PBXFileSystemSynchronizedRootGroup;
- exceptions = (
- );
- explicitFileTypes = {
- };
- explicitFolders = (
- );
- path = VaultStoreKit;
- sourceTree = "<group>";
- };
- CEE480972DBE86DD00F4A367 /* VaultStoreKitTests */ = {
- isa = PBXFileSystemSynchronizedRootGroup;
- exceptions = (
- );
- explicitFileTypes = {
- };
- explicitFolders = (
- );
- path = VaultStoreKitTests;
- sourceTree = "<group>";
- };
- CEE4816B2DBE8AC800F4A367 /* VaultUI */ = {
- isa = PBXFileSystemSynchronizedRootGroup;
- exceptions = (
- );
- explicitFileTypes = {
- };
- explicitFolders = (
- );
- path = VaultUI;
- sourceTree = "<group>";
- };
- CEE482AB2DBE8EFE00F4A367 /* VaultModels */ = {
- isa = PBXFileSystemSynchronizedRootGroup;
- exceptions = (
- );
- explicitFileTypes = {
- };
- explicitFolders = (
- );
- path = VaultModels;
- sourceTree = "<group>";
- };
- CEE909812DA548C7008D568F /* Autofill */ = {
- isa = PBXFileSystemSynchronizedRootGroup;
- exceptions = (
- CEE9098F2DA548C7008D568F /* Exceptions for "Autofill" folder in "Autofill" target */,
- );
- explicitFileTypes = {
- };
- explicitFolders = (
- );
- path = Autofill;
- sourceTree = "<group>";
- };
+ CEE480882DBE86DC00F4A367 /* VaultStoreKit */ = {isa = PBXFileSystemSynchronizedRootGroup; explicitFileTypes = {}; explicitFolders = (); path = VaultStoreKit; sourceTree = "<group>"; };
+ CEE480972DBE86DD00F4A367 /* VaultStoreKitTests */ = {isa = PBXFileSystemSynchronizedRootGroup; explicitFileTypes = {}; explicitFolders = (); path = VaultStoreKitTests; sourceTree = "<group>"; };
+ CEE4816B2DBE8AC800F4A367 /* VaultUI */ = {isa = PBXFileSystemSynchronizedRootGroup; explicitFileTypes = {}; explicitFolders = (); path = VaultUI; sourceTree = "<group>"; };
+ CEE482AB2DBE8EFE00F4A367 /* VaultModels */ = {isa = PBXFileSystemSynchronizedRootGroup; explicitFileTypes = {}; explicitFolders = (); path = VaultModels; sourceTree = "<group>"; };
+ CEE909812DA548C7008D568F /* Autofill */ = {isa = PBXFileSystemSynchronizedRootGroup; exceptions = (CEE9098F2DA548C7008D568F /* PBXFileSystemSynchronizedBuildFileExceptionSet */, ); explicitFileTypes = {}; explicitFolders = (); path = Autofill; sourceTree = "<group>"; };
/* End PBXFileSystemSynchronizedRootGroup section */
/* Begin PBXFrameworksBuildPhase section */
@@ -493,6 +442,7 @@
CEE480A12DBE86DD00F4A367 /* Embed Frameworks */,
F09C43BBB1E788B0094C9F0D /* [CP] Embed Pods Frameworks */,
237430D176B6590F50FD5A12 /* [CP] Copy Pods Resources */,
+ CE3AE4A42DC7FADC00E7745E /* Run Script */,
);
buildRules = (
);
@@ -561,7 +511,6 @@
CEE481662DBE8AC800F4A367 /* Sources */,
CEE481672DBE8AC800F4A367 /* Frameworks */,
CEE481682DBE8AC800F4A367 /* Resources */,
- CE3AE2AF2DC7ACC100E7745E /* ShellScript */,
);
buildRules = (
);
@@ -605,6 +554,7 @@
CEE9097B2DA548C7008D568F /* Frameworks */,
CEE9097C2DA548C7008D568F /* Resources */,
CEE480B02DBE88AB00F4A367 /* Embed Frameworks */,
+ CE3AE50F2DC7FB5500E7745E /* ShellScript */,
);
buildRules = (
);
@@ -887,8 +837,36 @@
shellScript = "diff \"${PODS_PODFILE_DIR_PATH}/Podfile.lock\" \"${PODS_ROOT}/Manifest.lock\" > /dev/null\nif [ $? != 0 ] ; then\n # print error to STDERR\n echo \"error: The sandbox is not in sync with the Podfile.lock. Run 'pod install' or update your CocoaPods installation.\" >&2\n exit 1\nfi\n# This output is used by Xcode 'outputs' to avoid re-running this script phase.\necho \"SUCCESS\" > \"${SCRIPT_OUTPUT_FILE_0}\"\n";
showEnvVarsInLog = 0;
};
- CE3AE2AF2DC7ACC100E7745E /* ShellScript */ = {
+ CE3AE4A42DC7FADC00E7745E /* Run Script */ = {
isa = PBXShellScriptBuildPhase;
+ alwaysOutOfDate = 1;
+ buildActionMask = 2147483647;
+ files = (
+ );
+ inputFileListPaths = (
+ );
+ inputPaths = (
+ "$(SRCROOT)/.swiftlint.yml",
+ "$(SRCROOT)/**/.swiftlint.yml",
+ "$(SRCROOT)/AliasVault",
+ "$(SRCROOT)/Autofill",
+ "$(SRCROOT)/VaultStoreKit",
+ "$(SRCROOT)/VaultStoreKitTests",
+ "$(SRCROOT)/VaultUI",
+ "$(SRCROOT)/VaultModels",
+ );
+ name = "Run Script";
+ outputFileListPaths = (
+ );
+ outputPaths = (
+ );
+ runOnlyForDeploymentPostprocessing = 0;
+ shellPath = /bin/sh;
+ shellScript = "# Type a script or drag a script file from your workspace to insert its path.\n\"${PODS_ROOT}/SwiftLint/swiftlint\" --config \"${SRCROOT}/.swiftlint.yml\"\n";
+ };
+ CE3AE50F2DC7FB5500E7745E /* ShellScript */ = {
+ isa = PBXShellScriptBuildPhase;
+ alwaysOutOfDate = 1;
buildActionMask = 2147483647;
files = (
);
@@ -1181,10 +1159,7 @@
LIBRARY_SEARCH_PATHS = "$(SDKROOT)/usr/lib/swift\"$(inherited)\"";
MTL_ENABLE_DEBUG_INFO = YES;
ONLY_ACTIVE_ARCH = YES;
- OTHER_LDFLAGS = (
- "$(inherited)",
- " ",
- );
+ OTHER_LDFLAGS = "$(inherited) ";
REACT_NATIVE_PATH = "${PODS_ROOT}/../../node_modules/react-native";
SDKROOT = iphoneos;
SWIFT_ACTIVE_COMPILATION_CONDITIONS = "$(inherited) DEBUG";
@@ -1239,10 +1214,7 @@
);
LIBRARY_SEARCH_PATHS = "$(SDKROOT)/usr/lib/swift\"$(inherited)\"";
MTL_ENABLE_DEBUG_INFO = NO;
- OTHER_LDFLAGS = (
- "$(inherited)",
- " ",
- );
+ OTHER_LDFLAGS = "$(inherited) ";
REACT_NATIVE_PATH = "${PODS_ROOT}/../../node_modules/react-native";
SDKROOT = iphoneos;
USE_HERMES = true;
diff --git a/apps/mobile-app/ios/Autofill/CredentialIdentityStore.swift b/apps/mobile-app/ios/Autofill/CredentialIdentityStore.swift
index 1824a4e40..289b93fc1 100644
--- a/apps/mobile-app/ios/Autofill/CredentialIdentityStore.swift
+++ b/apps/mobile-app/ios/Autofill/CredentialIdentityStore.swift
@@ -7,13 +7,14 @@ import VaultModels
* This class is used to save and remove credential identities from the system.
* It is used to provide credentials to the system when the user is autocompleting a password.
*/
-class CredentialIdentityStore {
+public class CredentialIdentityStore {
static let shared = CredentialIdentityStore()
private let store = ASCredentialIdentityStore.shared
private init() {}
- func saveCredentialIdentities(_ credentials: [Credential]) async throws {
+ /// Save credentials into the native iOS credential store.
+ public func saveCredentialIdentities(_ credentials: [Credential]) async throws {
let identities: [ASPasswordCredentialIdentity] = credentials.compactMap { credential in
guard let urlString = credential.service.url,
let url = URL(string: urlString),
@@ -51,11 +52,13 @@ class CredentialIdentityStore {
}
}
- func removeAllCredentialIdentities() async throws {
+ /// Remove all credentials from iOS credential store.
+ public func removeAllCredentialIdentities() async throws {
try await store.removeAllCredentialIdentities()
}
- func removeCredentialIdentities(_ credentials: [Credential]) async throws {
+ /// Remove one or more specific credentials from iOS credential store.
+ public func removeCredentialIdentities(_ credentials: [Credential]) async throws {
let identities = credentials.map { credential in
let serviceIdentifier = ASCredentialServiceIdentifier(
identifier: credential.service.name ?? "",
diff --git a/apps/mobile-app/ios/Autofill/CredentialProviderViewController.swift b/apps/mobile-app/ios/Autofill/CredentialProviderViewController.swift
index b1d6ab953..e2b84a7fe 100644
--- a/apps/mobile-app/ios/Autofill/CredentialProviderViewController.swift
+++ b/apps/mobile-app/ios/Autofill/CredentialProviderViewController.swift
@@ -30,89 +30,24 @@ public class CredentialProviderViewController: ASCredentialProviderViewControlle
// 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()
- if !vaultStore.hasEncryptedDatabase {
- let alert = UIAlertController(
- title: "Login Required",
- message: "To use Autofill, please login to your AliasVault account in the AliasVault app.",
- preferredStyle: .alert
- )
- alert.addAction(UIAlertAction(title: "OK", style: .default) { [weak self] _ in
- self?.extensionContext.cancelRequest(withError: NSError(
- domain: ASExtensionErrorDomain,
- code: ASExtensionError.userCanceled.rawValue
- ))
- })
- present(alert, animated: true)
- return
- }
- // Check if Face ID/Touch ID is enabled
- let context = LAContext()
- var authMethod = "Face ID / Touch ID"
- if context.canEvaluatePolicy(.deviceOwnerAuthenticationWithBiometrics, error: nil) {
- switch context.biometryType {
- case .faceID:
- authMethod = "Face ID"
- case .touchID:
- authMethod = "Touch ID"
- default:
- break
- }
- }
-
- if !vaultStore.getAuthMethods().contains(.faceID) {
- let alert = UIAlertController(
- title: "\(authMethod) Required",
- message: "To use Autofill, please enable \(authMethod) as your vault unlock method in the AliasVault app settings.",
- preferredStyle: .alert
- )
- alert.addAction(UIAlertAction(title: "OK", style: .default) { [weak self] _ in
- self?.extensionContext.cancelRequest(withError: NSError(
- domain: ASExtensionErrorDomain,
- code: ASExtensionError.userCanceled.rawValue
- ))
- })
- present(alert, animated: true)
+ if !sanityChecks(vaultStore: vaultStore) {
+ // Sanity checks failed and dialog has been shown.
+ // Do not open the view so return here.
return
}
- // Create the ViewModel with INJECTED behaviors
+ // Create the ViewModel with injected behaviors
let viewModel = CredentialProviderViewModel(
- loader: {
- try vaultStore.unlockVault()
- let credentials = try vaultStore.getAllCredentials()
- await self.registerCredentialIdentities(credentials: credentials)
- return credentials
- },
- selectionHandler: { [weak self] identifier, password in
- guard let self = self else { return }
- if self.isChoosingTextToInsert {
- // For text insertion, insert only the selected text
- if #available(iOS 18.0, *) {
- self.extensionContext.completeRequest(
- withTextToInsert: identifier,
- completionHandler: nil
- )
- } else {
- // Fallback on earlier versions: do nothing as this feature
- // is not supported and we should not reach this point?
- }
- } else {
- // For regular credential selection
- let passwordCredential = ASPasswordCredential(
- user: identifier,
- password: password
- )
- self.extensionContext.completeRequest(withSelectedCredential: passwordCredential, completionHandler: nil)
- }
- },
- cancelHandler: { [weak self] in
- guard let self = self else { return }
- self.extensionContext.cancelRequest(withError: NSError(
- domain: ASExtensionErrorDomain,
- code: ASExtensionError.userCanceled.rawValue
- ))
- }
+ loader: {
+ return try await self.loadCredentials()
+ },
+ selectionHandler: { identifier, password in
+ self.handleCredentialSelection(identifier: identifier, password: password)
+ },
+ cancelHandler: {
+ self.handleCancel()
+ }
)
self.viewModel = viewModel
@@ -190,10 +125,9 @@ public class CredentialProviderViewController: ASCredentialProviderViewControlle
}
}
- /**
- * 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 shown above the iOS keyboard, which saves the user one step.
- */
+ /// 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.
private func registerCredentialIdentities(credentials: [Credential]) async {
do {
try await CredentialIdentityStore.shared.saveCredentialIdentities(credentials)
@@ -201,4 +135,100 @@ public class CredentialProviderViewController: ASCredentialProviderViewControlle
print("Failed to save credential identities: \(error)")
}
}
+
+ /// Run sanity checks on the vault store before opening the autofill view to check things like if user is logged in,
+ /// vault is available etc.
+ /// - 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 {
+ if !vaultStore.hasEncryptedDatabase {
+ let alert = UIAlertController(
+ title: "Login Required",
+ message: "To use Autofill, please login to your AliasVault account in the AliasVault app.",
+ preferredStyle: .alert
+ )
+ alert.addAction(UIAlertAction(title: "OK", style: .default) { [weak self] _ in
+ self?.extensionContext.cancelRequest(withError: NSError(
+ domain: ASExtensionErrorDomain,
+ code: ASExtensionError.userCanceled.rawValue
+ ))
+ })
+ present(alert, animated: true)
+ return false
+ }
+
+ // Check if Face ID/Touch ID is enabled
+ let context = LAContext()
+ var authMethod = "Face ID / Touch ID"
+ if context.canEvaluatePolicy(.deviceOwnerAuthenticationWithBiometrics, error: nil) {
+ switch context.biometryType {
+ case .faceID:
+ authMethod = "Face ID"
+ case .touchID:
+ authMethod = "Touch ID"
+ default:
+ break
+ }
+ }
+
+ if !vaultStore.getAuthMethods().contains(.faceID) {
+ let alert = UIAlertController(
+ title: "\(authMethod) Required",
+ message: "To use Autofill, please enable \(authMethod) as your vault unlock method in the AliasVault app settings.",
+ preferredStyle: .alert
+ )
+ alert.addAction(UIAlertAction(title: "OK", style: .default) { [weak self] _ in
+ self?.extensionContext.cancelRequest(withError: NSError(
+ domain: ASExtensionErrorDomain,
+ code: ASExtensionError.userCanceled.rawValue
+ ))
+ })
+ present(alert, animated: true)
+ return false
+ }
+
+ return true
+ }
+
+ /// Load credentials from the vault store and register them as credential identities
+ /// and then return them to the caller (view model).
+ private func loadCredentials() async throws -> [Credential] {
+ let vaultStore = VaultStore()
+ try vaultStore.unlockVault()
+ let credentials = try vaultStore.getAllCredentials()
+ await self.registerCredentialIdentities(credentials: credentials)
+ return credentials
+ }
+
+ /// Handle autofill view credential selection.
+ private func handleCredentialSelection(identifier: String, password: String) {
+ if isChoosingTextToInsert {
+ // For text insertion, insert only the selected text
+ if #available(iOS 18.0, *) {
+ self.extensionContext.completeRequest(
+ withTextToInsert: identifier,
+ completionHandler: nil
+ )
+ } else {
+ // Fallback on earlier versions: do nothing as this feature
+ // is not supported and we should not reach this point?
+ }
+ } else {
+ // For regular credential selection
+ let passwordCredential = ASPasswordCredential(
+ user: identifier,
+ password: password
+ )
+ self.extensionContext.completeRequest(withSelectedCredential: passwordCredential, completionHandler: nil)
+ }
+ }
+
+ /// Handle autofill view cancel action.
+ private func handleCancel() {
+ self.extensionContext.cancelRequest(withError: NSError(
+ domain: ASExtensionErrorDomain,
+ code: ASExtensionError.userCanceled.rawValue
+ ))
+ }
}
diff --git a/apps/mobile-app/ios/NativeVaultManager/RCTNativeVaultManager.mm b/apps/mobile-app/ios/NativeVaultManager/RCTNativeVaultManager.mm
index 9cd152572..848829333 100644
--- a/apps/mobile-app/ios/NativeVaultManager/RCTNativeVaultManager.mm
+++ b/apps/mobile-app/ios/NativeVaultManager/RCTNativeVaultManager.mm
@@ -72,10 +72,6 @@
[vaultManager getAutoLockTimeout:resolve rejecter:reject];
}
-- (void)getCredentials:(RCTPromiseResolveBlock)resolve reject:(RCTPromiseRejectBlock)reject {
- [vaultManager getCredentials];
-}
-
- (void)getVaultMetadata:(RCTPromiseResolveBlock)resolve reject:(RCTPromiseRejectBlock)reject {
[vaultManager getVaultMetadata:resolve rejecter:reject];
}
diff --git a/apps/mobile-app/ios/NativeVaultManager/VaultManager.swift b/apps/mobile-app/ios/NativeVaultManager/VaultManager.swift
index 8e884a591..4dc58619c 100644
--- a/apps/mobile-app/ios/NativeVaultManager/VaultManager.swift
+++ b/apps/mobile-app/ios/NativeVaultManager/VaultManager.swift
@@ -141,24 +141,6 @@ public class VaultManager: NSObject {
}
}
- @objc
- func getCredentials() -> [String: Any] {
- do {
- let credentials = try vaultStore.getAllCredentials()
- let credentialDicts = credentials.map { credential in
- return [
- "username": credential.username,
- "password": credential.password,
- "service": credential.service
- ]
- }
- return ["credentials": credentialDicts]
- } catch {
- print("Failed to get credentials: \(error)")
- return [:]
- }
- }
-
@objc
func clearVault() {
do {
@@ -196,30 +178,22 @@ public class VaultManager: NSObject {
@objc
func hasEncryptedDatabase(_ resolve: @escaping RCTPromiseResolveBlock,
rejecter reject: @escaping RCTPromiseRejectBlock) {
- do {
- let isInitialized = try vaultStore.hasEncryptedDatabase
- resolve(isInitialized)
- } catch {
- reject("VAULT_ERROR", "Failed to check vault initialization: \(error.localizedDescription)", error)
- }
+ let isInitialized = vaultStore.hasEncryptedDatabase
+ resolve(isInitialized)
}
@objc
func isVaultUnlocked(_ resolve: @escaping RCTPromiseResolveBlock,
rejecter reject: @escaping RCTPromiseRejectBlock) {
- let isUnlocked = try vaultStore.isVaultUnlocked
+ let isUnlocked = vaultStore.isVaultUnlocked
resolve(isUnlocked)
}
@objc
func getVaultMetadata(_ resolve: @escaping RCTPromiseResolveBlock,
rejecter reject: @escaping RCTPromiseRejectBlock) {
- do {
- let metadata = try vaultStore.getVaultMetadata()
- resolve(metadata)
- } catch {
- reject("METADATA_ERROR", "Failed to get vault metadata: \(error.localizedDescription)", error)
- }
+ let metadata = vaultStore.getVaultMetadata()
+ resolve(metadata)
}
@objc
@@ -266,21 +240,17 @@ public class VaultManager: NSObject {
@objc
func getAuthMethods(_ resolve: @escaping RCTPromiseResolveBlock,
rejecter reject: @escaping RCTPromiseRejectBlock) {
- do {
- let methods = try vaultStore.getAuthMethods()
- var methodStrings: [String] = []
-
- if methods.contains(.faceID) {
- methodStrings.append("faceid")
- }
- if methods.contains(.password) {
- methodStrings.append("password")
- }
+ let methods = vaultStore.getAuthMethods()
+ var methodStrings: [String] = []
- resolve(methodStrings)
- } catch {
- reject("AUTH_METHOD_ERROR", "Failed to get authentication methods: \(error.localizedDescription)", error)
+ if methods.contains(.faceID) {
+ methodStrings.append("faceid")
}
+ if methods.contains(.password) {
+ methodStrings.append("password")
+ }
+
+ resolve(methodStrings)
}
@objc
diff --git a/apps/mobile-app/ios/VaultModels/Credential.swift b/apps/mobile-app/ios/VaultModels/Credential.swift
index 6a02a9696..d136bbeb1 100644
--- a/apps/mobile-app/ios/VaultModels/Credential.swift
+++ b/apps/mobile-app/ios/VaultModels/Credential.swift
@@ -122,4 +122,4 @@ public struct Alias: Codable, Hashable {
self.updatedAt = updatedAt
self.isDeleted = isDeleted
}
-}
\ No newline at end of file
+}
diff --git a/apps/mobile-app/ios/VaultStoreKit/Utils/DateHelper.swift b/apps/mobile-app/ios/VaultStoreKit/Utils/DateHelper.swift
deleted file mode 100644
index 0adc70869..000000000
--- a/apps/mobile-app/ios/VaultStoreKit/Utils/DateHelper.swift
+++ /dev/null
@@ -1,61 +0,0 @@
-//
-// DateHelper.swift
-// VaultStoreKit
-//
-// Created by Leendert de Borst on 04/05/2025.
-//
-
-import Foundation
-
-/// DateHelper class which contains helper methods for date strings and objects.
-public class DateHelper {
- public static func parseDateString(_ dateString: String) -> Date? {
- // Static date formatters for performance
- 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
- }()
- }
-
- let cleanedDateString = dateString.trimmingCharacters(in: .whitespacesAndNewlines)
-
- // If ends with 'Z' or contains timezone, attempt ISO8601 parsing
- if cleanedDateString.contains("Z") || cleanedDateString.contains("+") || cleanedDateString.contains("-") {
- if let isoDate = StaticFormatters.isoFormatter.date(from: cleanedDateString) {
- return isoDate
- }
- }
-
- // Try parsing with milliseconds
- if let dateWithMillis = StaticFormatters.formatterWithMillis.date(from: cleanedDateString) {
- return dateWithMillis
- }
-
- // Try parsing without milliseconds
- if let dateWithoutMillis = StaticFormatters.formatterWithoutMillis.date(from: cleanedDateString) {
- return dateWithoutMillis
- }
-
- // If parsing still fails, return nil
- return nil
- }
-}
diff --git a/apps/mobile-app/ios/VaultStoreKit/VaultConstants.swift b/apps/mobile-app/ios/VaultStoreKit/VaultConstants.swift
index edadf37ae..d48cb6357 100644
--- a/apps/mobile-app/ios/VaultStoreKit/VaultConstants.swift
+++ b/apps/mobile-app/ios/VaultStoreKit/VaultConstants.swift
@@ -1,7 +1,8 @@
import Foundation
import VaultModels
-struct VaultConstants {
+/// Constants used for userDefaults keys and other things.
+public struct VaultConstants {
static let keychainService = "net.aliasvault.autofill"
static let keychainAccessGroup = "group.net.aliasvault.autofill"
static let userDefaultsSuite = "group.net.aliasvault.autofill"
@@ -15,4 +16,3 @@ struct VaultConstants {
static let defaultAutoLockTimeout: Int = 3600 // 1 hour in seconds
static let defaultAuthMethods: AuthMethods = [.password, .faceID]
}
-
diff --git a/apps/mobile-app/ios/VaultStoreKit/VaultStore+Auth.swift b/apps/mobile-app/ios/VaultStoreKit/VaultStore+Auth.swift
index 96c4f34fe..450718108 100644
--- a/apps/mobile-app/ios/VaultStoreKit/VaultStore+Auth.swift
+++ b/apps/mobile-app/ios/VaultStoreKit/VaultStore+Auth.swift
@@ -7,14 +7,14 @@ import VaultModels
extension VaultStore {
/// Set the enabled authentication methods for the vault
public func setAuthMethods(_ methods: AuthMethods) throws {
- enabledAuthMethods = methods
- userDefaults.set(methods.rawValue, forKey: VaultConstants.authMethodsKey)
- userDefaults.synchronize()
+ self.enabledAuthMethods = methods
+ self.userDefaults.set(methods.rawValue, forKey: VaultConstants.authMethodsKey)
+ self.userDefaults.synchronize()
- if !enabledAuthMethods.contains(.faceID) {
+ if !self.enabledAuthMethods.contains(.faceID) {
print("Face ID is now disabled, removing key from keychain immediately")
do {
- try keychain
+ try self.keychain
.authenticationPrompt("Authenticate to remove your vault decryption key")
.remove(VaultConstants.encryptionKeyKey)
print("Successfully removed encryption key from keychain")
@@ -29,16 +29,16 @@ extension VaultStore {
/// Get the enabled authentication methods for the vault
public func getAuthMethods() -> AuthMethods {
- return enabledAuthMethods
+ return self.enabledAuthMethods
}
/// Get the enabled authentication methods for the vault as strings
public func getAuthMethodsAsStrings() -> [String] {
var methods: [String] = []
- if enabledAuthMethods.contains(.faceID) {
+ if self.enabledAuthMethods.contains(.faceID) {
methods.append("faceid")
}
- if enabledAuthMethods.contains(.password) {
+ if self.enabledAuthMethods.contains(.password) {
methods.append("password")
}
return methods
diff --git a/apps/mobile-app/ios/VaultStoreKit/VaultStore+Cache.swift b/apps/mobile-app/ios/VaultStoreKit/VaultStore+Cache.swift
index b560fe4b6..53ab1c929 100644
--- a/apps/mobile-app/ios/VaultStoreKit/VaultStore+Cache.swift
+++ b/apps/mobile-app/ios/VaultStoreKit/VaultStore+Cache.swift
@@ -5,16 +5,16 @@ extension VaultStore {
/// Clear the memory - remove the encryption key and decrypted database from memory
public func clearCache() {
print("Clearing cache - removing encryption key and decrypted database from memory")
- encryptionKey = nil
- dbConnection = nil
+ self.encryptionKey = nil
+ self.dbConnection = nil
}
/// Clear the vault storage - remove the encryption key and encrypted database from the device
- public func clearVault() {
+ public func clearVault() throws {
print("Clearing vault - removing all stored data")
do {
- try keychain
+ try self.keychain
.authenticationPrompt("Authenticate to remove your vault decryption key")
.remove(VaultConstants.encryptionKeyKey)
print("Successfully removed encryption key from keychain")
@@ -27,12 +27,13 @@ extension VaultStore {
print("Successfully removed encrypted database file")
} catch {
print("Failed to remove encrypted database file: \(error)")
+ throw error
}
- userDefaults.removeObject(forKey: VaultConstants.vaultMetadataKey)
- userDefaults.removeObject(forKey: VaultConstants.authMethodsKey)
- userDefaults.removeObject(forKey: VaultConstants.autoLockTimeoutKey)
- userDefaults.synchronize()
+ self.userDefaults.removeObject(forKey: VaultConstants.vaultMetadataKey)
+ self.userDefaults.removeObject(forKey: VaultConstants.authMethodsKey)
+ self.userDefaults.removeObject(forKey: VaultConstants.autoLockTimeoutKey)
+ self.userDefaults.synchronize()
print("Cleared UserDefaults")
clearCache()
@@ -41,13 +42,13 @@ extension VaultStore {
/// Set the auto-lock timeout - the number of seconds after which the vault will be locked automatically
public func setAutoLockTimeout(_ timeout: Int) {
print("Setting auto-lock timeout to \(timeout) seconds")
- autoLockTimeout = timeout
- userDefaults.set(timeout, forKey: VaultConstants.autoLockTimeoutKey)
- userDefaults.synchronize()
+ self.autoLockTimeout = timeout
+ self.userDefaults.set(timeout, forKey: VaultConstants.autoLockTimeoutKey)
+ self.userDefaults.synchronize()
}
/// Get the auto-lock timeout - the number of seconds after which the vault will be locked automatically
public func getAutoLockTimeout() -> Int {
- return autoLockTimeout
+ return self.autoLockTimeout
}
-}
\ No newline at end of file
+}
diff --git a/apps/mobile-app/ios/VaultStoreKit/VaultStore+Crypto.swift b/apps/mobile-app/ios/VaultStoreKit/VaultStore+Crypto.swift
index 8dc91bda2..c2ff7cc9d 100644
--- a/apps/mobile-app/ios/VaultStoreKit/VaultStore+Crypto.swift
+++ b/apps/mobile-app/ios/VaultStoreKit/VaultStore+Crypto.swift
@@ -15,13 +15,13 @@ extension VaultStore {
throw NSError(domain: "VaultStore", code: 7, userInfo: [NSLocalizedDescriptionKey: "Invalid key length. Expected 32 bytes"])
}
- encryptionKey = keyData
+ self.encryptionKey = keyData
print("Stored key in memory")
- if enabledAuthMethods.contains(.faceID) {
+ if self.enabledAuthMethods.contains(.faceID) {
print("Face ID is enabled, storing key in keychain")
do {
- try keychain
+ try self.keychain
.authenticationPrompt("Authenticate to save your vault decryption key in the iOS keychain")
.set(keyData, key: VaultConstants.encryptionKeyKey)
print("Encryption key saved successfully to keychain")
@@ -35,18 +35,18 @@ extension VaultStore {
/// Encrypt the data using the encryption key
internal func encrypt(data: Data) throws -> Data {
- let localEncryptionKey = try getEncryptionKey()
+ let encryptionKey = try getEncryptionKey()
- let key = SymmetricKey(data: localEncryptionKey)
+ let key = SymmetricKey(data: encryptionKey)
let sealedBox = try AES.GCM.seal(data, using: key)
return sealedBox.combined!
}
/// Decrypt the data using the encryption key
internal func decrypt(data: Data) throws -> Data {
- let localEncryptionKey = try getEncryptionKey()
+ let encryptionKey = try getEncryptionKey()
- let key = SymmetricKey(data: localEncryptionKey)
+ let key = SymmetricKey(data: encryptionKey)
let sealedBox = try AES.GCM.SealedBox(combined: data)
return try AES.GCM.open(sealedBox, using: key)
}
@@ -55,11 +55,11 @@ extension VaultStore {
/// This method is meant to only be used internally by the VaultStore class and not
/// be exposed to the public API or React Native for security reasons.
internal func getEncryptionKey() throws -> Data {
- if let key = encryptionKey {
+ if let key = self.encryptionKey {
return key
}
- if enabledAuthMethods.contains(.faceID) {
+ if self.enabledAuthMethods.contains(.faceID) {
let context = LAContext()
var error: NSError?
@@ -73,12 +73,12 @@ extension VaultStore {
print("Attempting to get encryption key from keychain as Face ID is enabled as an option")
do {
- guard let keyData = try keychain
+ guard let keyData = try self.keychain
.authenticationPrompt("Authenticate to unlock your vault")
.getData(VaultConstants.encryptionKeyKey) else {
throw NSError(domain: "VaultStore", code: 2, userInfo: [NSLocalizedDescriptionKey: "No encryption key found"])
}
- encryptionKey = keyData
+ self.encryptionKey = keyData
return keyData
} catch let keychainError as KeychainAccess.Status {
switch keychainError {
@@ -96,4 +96,4 @@ extension VaultStore {
throw NSError(domain: "VaultStore", code: 3, userInfo: [NSLocalizedDescriptionKey: "No encryption key found in memory"])
}
-}
\ No newline at end of file
+}
diff --git a/apps/mobile-app/ios/VaultStoreKit/VaultStore+Database.swift b/apps/mobile-app/ios/VaultStoreKit/VaultStore+Database.swift
index 07cc601a6..f020dd1e9 100644
--- a/apps/mobile-app/ios/VaultStoreKit/VaultStore+Database.swift
+++ b/apps/mobile-app/ios/VaultStoreKit/VaultStore+Database.swift
@@ -49,8 +49,8 @@ extension VaultStore {
}
/// Remove the encrypted database from the local filesystem
- internal func removeEncryptedDatabase() {
- try? FileManager.default.removeItem(at: getEncryptedDbPath())
+ internal func removeEncryptedDatabase() throws {
+ try FileManager.default.removeItem(at: getEncryptedDbPath())
}
/// Get the path to the encrypted database file
@@ -70,27 +70,27 @@ extension VaultStore {
let tempDbPath = FileManager.default.temporaryDirectory.appendingPathComponent("temp_db.sqlite")
try decryptedDbData.write(to: tempDbPath)
- dbConnection = try Connection(":memory:")
+ self.dbConnection = try Connection(":memory:")
- try dbConnection?.attach(.uri(tempDbPath.path, parameters: [.mode(.readOnly)]), as: "source")
- try dbConnection?.execute("BEGIN TRANSACTION")
+ try self.dbConnection?.attach(.uri(tempDbPath.path, parameters: [.mode(.readOnly)]), as: "source")
+ try self.dbConnection?.execute("BEGIN TRANSACTION")
- let tables = try dbConnection?.prepare("SELECT name FROM source.sqlite_master WHERE type='table' AND name NOT LIKE 'sqlite_%'")
+ let tables = try self.dbConnection?.prepare("SELECT name FROM source.sqlite_master WHERE type='table' AND name NOT LIKE 'sqlite_%'")
for table in tables! {
guard let tableName = table[0] as? String else {
print("Warning: Unexpected value in table name column")
continue
}
- try dbConnection?.execute("CREATE TABLE \(tableName) AS SELECT * FROM source.\(tableName)")
+ try self.dbConnection?.execute("CREATE TABLE \(tableName) AS SELECT * FROM source.\(tableName)")
}
- try dbConnection?.execute("COMMIT")
- try dbConnection?.execute("DETACH DATABASE source")
+ try self.dbConnection?.execute("COMMIT")
+ try self.dbConnection?.execute("DETACH DATABASE source")
try? FileManager.default.removeItem(at: tempDbPath)
- try dbConnection?.execute("PRAGMA journal_mode = WAL")
- try dbConnection?.execute("PRAGMA synchronous = NORMAL")
- try dbConnection?.execute("PRAGMA foreign_keys = ON")
+ try self.dbConnection?.execute("PRAGMA journal_mode = WAL")
+ try self.dbConnection?.execute("PRAGMA synchronous = NORMAL")
+ try self.dbConnection?.execute("PRAGMA foreign_keys = ON")
}
}
diff --git a/apps/mobile-app/ios/VaultStoreKit/VaultStore+Metadata.swift b/apps/mobile-app/ios/VaultStoreKit/VaultStore+Metadata.swift
index 7ef073625..08a6c2f65 100644
--- a/apps/mobile-app/ios/VaultStoreKit/VaultStore+Metadata.swift
+++ b/apps/mobile-app/ios/VaultStoreKit/VaultStore+Metadata.swift
@@ -53,4 +53,4 @@ extension VaultStore {
userDefaults.synchronize()
}
}
-}
\ No newline at end of file
+}
diff --git a/apps/mobile-app/ios/VaultStoreKit/VaultStore+Query.swift b/apps/mobile-app/ios/VaultStoreKit/VaultStore+Query.swift
index c1d20bb1e..d86a7c36c 100644
--- a/apps/mobile-app/ios/VaultStoreKit/VaultStore+Query.swift
+++ b/apps/mobile-app/ios/VaultStoreKit/VaultStore+Query.swift
@@ -6,7 +6,7 @@ import VaultModels
extension VaultStore {
/// Execute a SELECT query on the database
public func executeQuery(_ query: String, params: [Binding?]) throws -> [[String: Any]] {
- guard let dbConnection = dbConnection else {
+ guard let dbConnection = self.dbConnection else {
throw NSError(domain: "VaultStore", code: 4, userInfo: [NSLocalizedDescriptionKey: "Database not initialized"])
}
@@ -53,7 +53,7 @@ extension VaultStore {
/// Execute an UPDATE, INSERT, or DELETE query on the database (which will modify the database).
public func executeUpdate(_ query: String, params: [Binding?]) throws -> Int {
- guard let dbConnection = dbConnection else {
+ guard let dbConnection = self.dbConnection else {
throw NSError(domain: "VaultStore", code: 4, userInfo: [NSLocalizedDescriptionKey: "Database not initialized"])
}
@@ -76,7 +76,7 @@ extension VaultStore {
/// Begin a transaction on the database. This is required for all database operations that modify the database.
public func beginTransaction() throws {
- guard let dbConnection = dbConnection else {
+ guard let dbConnection = self.dbConnection else {
throw NSError(domain: "VaultStore", code: 4, userInfo: [NSLocalizedDescriptionKey: "Database not initialized"])
}
try dbConnection.execute("BEGIN TRANSACTION")
@@ -85,7 +85,7 @@ extension VaultStore {
/// Commit a transaction on the database. This is required for all database operations that modify the database.
/// Committing a transaction will also trigger a persist from the in-memory database to the encrypted database file.
public func commitTransaction() throws {
- guard let dbConnection = dbConnection else {
+ guard let dbConnection = self.dbConnection else {
throw NSError(domain: "VaultStore", code: 4, userInfo: [NSLocalizedDescriptionKey: "Database not initialized"])
}
@@ -121,7 +121,7 @@ extension VaultStore {
/// Rollback a transaction on the database on error.
public func rollbackTransaction() throws {
- guard let dbConnection = dbConnection else {
+ guard let dbConnection = self.dbConnection else {
throw NSError(domain: "VaultStore", code: 4, userInfo: [NSLocalizedDescriptionKey: "Database not initialized"])
}
try dbConnection.execute("ROLLBACK")
@@ -130,7 +130,7 @@ extension VaultStore {
// swiftlint:disable function_body_length
/// Get all credentials from the database.
public func getAllCredentials() throws -> [Credential] {
- guard let dbConnection = dbConnection else {
+ guard let dbConnection = self.dbConnection else {
throw NSError(domain: "VaultStore", code: 4, userInfo: [NSLocalizedDescriptionKey: "Database not initialized"])
}
@@ -230,7 +230,7 @@ extension VaultStore {
isDeleted: serviceIsDeleted
)
- var alias: Alias? = nil
+ var alias: Alias?
if let aliasIdString = row[19] as? String,
let aliasCreatedAtString = row[26] as? String,
let aliasUpdatedAtString = row[27] as? String,
diff --git a/apps/mobile-app/ios/VaultStoreKit/VaultStore.swift b/apps/mobile-app/ios/VaultStoreKit/VaultStore.swift
index 094538941..6ea324cf3 100644
--- a/apps/mobile-app/ios/VaultStoreKit/VaultStore.swift
+++ b/apps/mobile-app/ios/VaultStoreKit/VaultStore.swift
@@ -17,8 +17,7 @@ public class VaultStore {
public static let shared = VaultStore()
/// The keychain to access the vault's encryption key.
- internal let keychain = Keychain(service: VaultConstants.keychainService,
- accessGroup: VaultConstants.keychainAccessGroup)
+ internal let keychain = Keychain(service: VaultConstants.keychainService, accessGroup: VaultConstants.keychainAccessGroup)
.accessibility(.whenPasscodeSetThisDeviceOnly, authenticationPolicy: .biometryAny)
/// The user defaults using the shared container which is accessible by both the React Native
@@ -49,7 +48,7 @@ public class VaultStore {
/// Deinitialize the VaultStore
deinit {
NotificationCenter.default.removeObserver(self)
- clearCacheTimer?.invalidate()
+ self.clearCacheTimer?.invalidate()
}
/// Whether the vault is currently unlocked
@@ -60,11 +59,11 @@ public class VaultStore {
private func loadSavedSettings() {
if userDefaults.object(forKey: VaultConstants.authMethodsKey) != nil {
let savedRawValue = userDefaults.integer(forKey: VaultConstants.authMethodsKey)
- enabledAuthMethods = AuthMethods(rawValue: savedRawValue)
+ self.enabledAuthMethods = AuthMethods(rawValue: savedRawValue)
}
if userDefaults.object(forKey: VaultConstants.autoLockTimeoutKey) != nil {
- autoLockTimeout = userDefaults.integer(forKey: VaultConstants.autoLockTimeoutKey)
+ self.autoLockTimeout = userDefaults.integer(forKey: VaultConstants.autoLockTimeoutKey)
}
}
@@ -87,8 +86,8 @@ public class VaultStore {
// MARK: - Background/Foreground Handling
@objc private func appDidEnterBackground() {
print("App entered background, starting auto-lock timer with \(autoLockTimeout) seconds")
- if autoLockTimeout > 0 {
- clearCacheTimer = Timer.scheduledTimer(withTimeInterval: TimeInterval(autoLockTimeout), repeats: false) { [weak self] _ in
+ if self.autoLockTimeout > 0 {
+ self.clearCacheTimer = Timer.scheduledTimer(withTimeInterval: TimeInterval(self.autoLockTimeout), repeats: false) { [weak self] _ in
print("Auto-lock timer fired, clearing cache")
self?.clearCache()
}
@@ -98,12 +97,12 @@ public class VaultStore {
@objc private func appWillEnterForeground() {
print("App will enter foreground, canceling clear cache timer")
- if let timer = clearCacheTimer, timer.fireDate < Date() {
+ if let timer = self.clearCacheTimer, timer.fireDate < Date() {
print("Timer has elapsed, cache should have been cleared already when app was in background, but clearing it again to be sure")
clearCache()
}
- clearCacheTimer?.invalidate()
- clearCacheTimer = nil
+ self.clearCacheTimer?.invalidate()
+ self.clearCacheTimer = nil
}
}
diff --git a/apps/mobile-app/ios/VaultUI/Components/CredentialCardView.swift b/apps/mobile-app/ios/VaultUI/Components/CredentialCardView.swift
index 3c8994472..145ea1d6c 100644
--- a/apps/mobile-app/ios/VaultUI/Components/CredentialCardView.swift
+++ b/apps/mobile-app/ios/VaultUI/Components/CredentialCardView.swift
@@ -7,14 +7,15 @@
import SwiftUI
import VaultModels
-struct CredentialCard: View {
+/// Credential card view
+public struct CredentialCard: View {
let credential: Credential
let action: () -> Void
@Environment(\.colorScheme) private var colorScheme
@State private var showCopyToast = false
@State private var copyToastMessage = ""
- var body: some View {
+ public var body: some View {
Button(action: action) {
HStack(spacing: 16) {
// Service logo
@@ -46,26 +47,25 @@ struct CredentialCard: View {
)
.cornerRadius(8)
}
- .contextMenu {
+ .contextMenu(menuItems: {
Button(action: {
if let username = credential.username {
UIPasteboard.general.string = username
copyToastMessage = "Username copied"
showCopyToast = true
}
- }) {
+ }, label: {
Label("Copy Username", systemImage: "person")
- }
-
+ })
Button(action: {
if let password = credential.password?.value {
UIPasteboard.general.string = password
copyToastMessage = "Password copied"
showCopyToast = true
}
- }) {
+ }, label: {
Label("Copy Password", systemImage: "key")
- }
+ })
Button(action: {
if let email = credential.alias?.email {
@@ -73,9 +73,9 @@ struct CredentialCard: View {
copyToastMessage = "Email copied"
showCopyToast = true
}
- }) {
+ }, label: {
Label("Copy Email", systemImage: "envelope")
- }
+ })
Divider()
@@ -83,18 +83,18 @@ struct CredentialCard: View {
if let url = URL(string: "aliasvault://credentials/\(credential.id.uuidString)") {
UIApplication.shared.open(url)
}
- }) {
+ }, label: {
Label("View Details", systemImage: "eye")
- }
+ })
Button(action: {
if let url = URL(string: "aliasvault://credentials/add-edit?id=\(credential.id.uuidString)") {
UIApplication.shared.open(url)
}
- }) {
+ }, label: {
Label("Edit", systemImage: "pencil")
- }
- }
+ })
+ })
.overlay(
Group {
if showCopyToast {
@@ -121,7 +121,8 @@ struct CredentialCard: View {
}
}
-func usernameOrEmail(credential: Credential) -> String {
+/// Returns username or email depending on if they are not null
+public func usernameOrEmail(credential: Credential) -> String {
if let username = credential.username, !username.isEmpty {
return username
}
@@ -131,7 +132,8 @@ func usernameOrEmail(credential: Credential) -> String {
return ""
}
-func truncateText(_ text: String?, limit: Int) -> String {
+/// Truncate text to a maximum limit and appends "..." at the end
+public func truncateText(_ text: String?, limit: Int) -> String {
guard let text = text else { return "" }
if text.count > limit {
let index = text.index(text.startIndex, offsetBy: limit)
@@ -183,4 +185,3 @@ func truncateText(_ text: String?, limit: Int) -> String {
action: {}
)
}
-
diff --git a/apps/mobile-app/ios/VaultUI/Components/SearchBar.swift b/apps/mobile-app/ios/VaultUI/Components/SearchBar.swift
new file mode 100644
index 000000000..fa64a2809
--- /dev/null
+++ b/apps/mobile-app/ios/VaultUI/Components/SearchBar.swift
@@ -0,0 +1,52 @@
+//
+// ServiceLogoView.swift
+// VaultUI
+//
+// Created by Leendert de Borst on 27/04/2025.
+//
+
+import SwiftUI
+import Macaw
+
+/// Service logo view
+public struct SearchBarView: View {
+ @Binding var text: String
+ @Environment(\.colorScheme) private var colorScheme
+
+ public var body: some View {
+ ZStack {
+ HStack {
+ Image(systemName: "magnifyingglass")
+ .foregroundColor(colorScheme == .dark ? ColorConstants.Dark.text : ColorConstants.Light.text)
+ .padding(.leading, 8)
+
+ TextField("Search credentials...", text: $text)
+ .autocapitalization(.none)
+ .foregroundColor(colorScheme == .dark ? ColorConstants.Dark.text : ColorConstants.Light.text)
+ .padding(.leading, 4)
+ .padding(.trailing, 28) // Space for clear button
+ }
+ .padding(8)
+ .padding(.vertical, 2)
+ .background(colorScheme == .dark ? ColorConstants.Dark.accentBackground : ColorConstants.Light.accentBackground)
+ .cornerRadius(8)
+
+ if !text.isEmpty {
+ HStack {
+ Spacer()
+ Button(action: {
+ text = ""
+ }, label: {
+ Image(systemName: "xmark.circle.fill")
+ .foregroundColor(colorScheme == .dark ? ColorConstants.Dark.text : ColorConstants.Light.text)
+ })
+ .padding(.trailing, 8)
+ }
+ }
+ }
+ }
+}
+
+#Preview {
+ SearchBarView(text: .constant("Example"))
+}
diff --git a/apps/mobile-app/ios/VaultUI/Components/ServiceLogoView.swift b/apps/mobile-app/ios/VaultUI/Components/ServiceLogoView.swift
index 803a6da2d..31ed4b31b 100644
--- a/apps/mobile-app/ios/VaultUI/Components/ServiceLogoView.swift
+++ b/apps/mobile-app/ios/VaultUI/Components/ServiceLogoView.swift
@@ -8,8 +8,10 @@
import SwiftUI
import Macaw
-struct ServiceLogoView: View {
- private let placeholderImageBase64 = "UklGRjoEAABXRUJQVlA4IC4EAAAwFwCdASqAAIAAPpFCm0olo6Ihp5IraLASCWUA0eb/0s56RrLtCnYfLPiBshdXWMx8j1Ez65f169iA4xUDBTEV6ylMQeCIj2b7RngGi7gKZ9WjKdSoy9R8JcgOmjCMlDmLG20KhNo/i/Dc/Ah5GAvGfm8kfniV3AkR6fxN6eKwjDc6xrDgSfS48G5uGV6WzQt24YAVlLSK9BMwndzfHnePK1KFchFrL7O3ulB8cGNCeomu4o+l0SrS/JKblJ4WTzj0DAD++lCUEouSfgRKdiV2TiYCD+H+l3tANKSPQFPQuzi7rbvxqGeRmXB9kDwURaoSTTpYjA9REMUi9uA6aV7PWtBNXgUzMLowYMZeos6Xvyhb34GmufswMHA5ZyYpxzjTphOak4ZjNOiz8aScO5ygiTx99SqwX/uL+HSeVOSraHw8IymrMwm+jLxqN8BS8dGcItLlm/ioulqH2j4V8glDgSut+ExkxiD7m8TGPrrjCQNJbRDzpOFsyCyfBZupvp8QjGKW2KGziSZeIWes4aTB9tRmeEBhnUrmTDZQuXcc67Fg82KHrSfaeeOEq6jjuUjQ8wUnzM4Zz3dhrwSyslVz/WvnKqYkr4V/TTXPFF5EjF4rM1bHZ8bK63EfTnK41+n3n4gEFoYP4mXkNH0hntnYcdTqiE7Gn+q0BpRRxnkpBSZlA6Wa70jpW0FGqkw5e591A5/H+OV+60WAo+4Mi+NlsKrvLZ9EiVaPnoEFZlJQx1fA777AJ2MjXJ4KSsrWDWJi1lE8yPs8V6XvcC0chDTYt8456sKXAagCZyY+fzQriFMaddXyKQdG8qBqcdYjAsiIcjzaRFBBoOK9sU+sFY7N6B6+xtrlu3c37rQKkI3O2EoiJOris54EjJ5OFuumA0M6riNUuBf/MEPFBVx1JRcUEs+upEBsCnwYski7FT3TTqHrx7v5AjgFN97xhPTkmVpu6sxRnWBi1fxIRp8eWZeFM6mUcGgVk1WeVb1yhdV9hoMo2TsNEPE0tHo/wvuSJSzbZo7wibeXM9v/rRfKcx7X93rfiXVnyQ9f/5CaAQ4lxedPp/6uzLtOS4FyL0bCNeZ6L5w+AiuyWCTDFIYaUzhwfG+/YTQpWyeZCdQIKzhV+3GeXI2cxoP0ER/DlOKymf1gm+zRU3sqf1lBVQ0y+mK/Awl9bS3uaaQmI0FUyUwHUKP7PKuXnO+LcwDv4OfPT6hph8smc1EtMe5ib/apar/qZ9dyaEaElALJ1KKxnHziuvVl8atk1fINSQh7OtXDyqbPw9o/nGIpTnv5iFmwmWJLis2oyEgPkJqyx0vYI8rjkVEzKc8eQavAJBYSpjMwM193Swt+yJyjvaGYWPnqExxKiNarpB2WSO7soCAZXhS1uEYHryrK47BH6W1dRiruqT0xpLih3MXiwU3VDwAAAA=="
+/// Service logo view
+public struct ServiceLogoView: View {
+
+ private let placeholderImageBase64 = "UklGRjoEAABXRUJQVlA4IC4EAAAwFwCdASqAAIAAPpFCm0olo6Ihp5IraLASCWUA0eb/0s56RrLtCnYfLPiBshdXWMx8j1Ez65f169iA4xUDBTEV6ylMQeCIj2b7RngGi7gKZ9WjKdSoy9R8JcgOmjCMlDmLG20KhNo/i/Dc/Ah5GAvGfm8kfniV3AkR6fxN6eKwjDc6xrDgSfS48G5uGV6WzQt24YAVlLSK9BMwndzfHnePK1KFchFrL7O3ulB8cGNCeomu4o+l0SrS/JKblJ4WTzj0DAD++lCUEouSfgRKdiV2TiYCD+H+l3tANKSPQFPQuzi7rbvxqGeRmXB9kDwURaoSTTpYjA9REMUi9uA6aV7PWtBNXgUzMLowYMZeos6Xvyhb34GmufswMHA5ZyYpxzjTphOak4ZjNOiz8aScO5ygiTx99SqwX/uL+HSeVOSraHw8IymrMwm+jLxqN8BS8dGcItLlm/ioulqH2j4V8glDgSut+ExkxiD7m8TGPrrjCQNJbRDzpOFsyCyfBZupvp8QjGKW2KGziSZeIWes4aTB9tRmeEBhnUrmTDZQuXcc67Fg82KHrSfaeeOEq6jjuUjQ8wUnzM4Zz3dhrwSyslVz/WvnKqYkr4V/TTXPFF5EjF4rM1bHZ8bK63EfTnK41+n3n4gEFoYP4mXkNH0hntnYcdTqiE7Gn+q0BpRRxnkpBSZlA6Wa70jpW0FGqkw5e591A5/H+OV+60WAo+4Mi+NlsKrvLZ9EiVaPnoEFZlJQx1fA777AJ2MjXJ4KSsrWDWJi1lE8yPs8V6XvcC0chDTYt8456sKXAagCZyY+fzQriFMaddXyKQdG8qBqcdYjAsiIcjzaRFBBoOK9sU+sFY7N6B6+xtrlu3c37rQKkI3O2EoiJOris54EjJ5OFuumA0M6riNUuBf/MEPFBVx1JRcUEs+upEBsCnwYski7FT3TTqHrx7v5AjgFN97xhPTkmVpu6sxRnWBi1fxIRp8eWZeFM6mUcGgVk1WeVb1yhdV9hoMo2TsNEPE0tHo/wvuSJSzbZo7wibeXM9v/rRfKcx7X93rfiXVnyQ9f/5CaAQ4lxedPp/6uzLtOS4FyL0bCNeZ6L5w+AiuyWCTDFIYaUzhwfG+/YTQpWyeZCdQIKzhV+3GeXI2cxoP0ER/DlOKymf1gm+zRU3sqf1lBVQ0y+mK/Awl9bS3uaaQmI0FUyUwHUKP7PKuXnO+LcwDv4OfPT6hph8smc1EtMe5ib/apar/qZ9dyaEaElALJ1KKxnHziuvVl8atk1fINSQh7OtXDyqbPw9o/nGIpTnv5iFmwmWJLis2oyEgPkJqyx0vYI8rjkVEzKc8eQavAJBYSpjMwM193Swt+yJyjvaGYWPnqExxKiNarpB2WSO7soCAZXhS1uEYHryrK47BH6W1dRiruqT0xpLih3MXiwU3VDwAAAA==" // swiftlint:disable:this line_length
let logoData: Data?
@Environment(\.colorScheme) private var colorScheme
@@ -65,7 +67,7 @@ struct ServiceLogoView: View {
}
}
- var body: some View {
+ public var body: some View {
Group {
if let logoData = logoData {
let mimeType = detectMimeType(logoData)
@@ -85,7 +87,7 @@ struct ServiceLogoView: View {
.resizable()
.aspectRatio(contentMode: .fit)
.frame(width: 32, height: 32)
- .clipShape(RoundedRectangle(cornerRadius:4))
+ .clipShape(RoundedRectangle(cornerRadius: 4))
}
} else if let placeholder = placeholderImage {
Image(uiImage: placeholder)
diff --git a/apps/mobile-app/ios/VaultUI/Views/CredentialProviderView.swift b/apps/mobile-app/ios/VaultUI/Views/CredentialProviderView.swift
index b17dcbc0e..0ea705be7 100644
--- a/apps/mobile-app/ios/VaultUI/Views/CredentialProviderView.swift
+++ b/apps/mobile-app/ios/VaultUI/Views/CredentialProviderView.swift
@@ -2,6 +2,7 @@ import SwiftUI
import AuthenticationServices
import VaultModels
+/// Credential provider view
public struct CredentialProviderView: View {
@ObservedObject public var viewModel: CredentialProviderViewModel
@@ -18,20 +19,22 @@ public struct CredentialProviderView: View {
(colorScheme == .dark ? ColorConstants.Dark.background : ColorConstants.Light.background)
.ignoresSafeArea()
- if viewModel.isLoading {
- ProgressView("Loading credentials...")
- .progressViewStyle(.circular)
- .scaleEffect(1.5)
- } else {
- VStack(spacing: 0) {
- SearchBar(text: $viewModel.searchText)
- .padding(.horizontal)
- .padding(.vertical, 8)
- .background(colorScheme == .dark ? ColorConstants.Dark.background : ColorConstants.Light.background)
- .onChange(of: viewModel.searchText) { _ in
- viewModel.filterCredentials()
- }
+ 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("Loading credentials...")
+ .progressViewStyle(.circular)
+ .scaleEffect(1.5)
+ Spacer()
+ } else {
ScrollView {
if viewModel.filteredCredentials.isEmpty {
VStack(spacing: 20) {
@@ -57,7 +60,7 @@ public struct CredentialProviderView: View {
UIApplication.shared.open(url, options: [:], completionHandler: nil)
}
}
- }) {
+ }, label: {
HStack {
Image(systemName: "plus.circle.fill")
Text("Create New Credential")
@@ -67,7 +70,7 @@ public struct CredentialProviderView: View {
.background(ColorConstants.Light.primary)
.foregroundColor(.white)
.cornerRadius(8)
- }
+ })
}
.padding(.horizontal, 40)
}
@@ -102,7 +105,6 @@ public struct CredentialProviderView: View {
}
ToolbarItem(placement: .navigationBarTrailing) {
HStack {
- // Make this button show a + icon instead of text
Button(action: {
if let serviceUrl = viewModel.serviceUrl {
let encodedUrl = serviceUrl.addingPercentEncoding(withAllowedCharacters: .urlQueryAllowed) ?? ""
@@ -110,10 +112,10 @@ public struct CredentialProviderView: View {
UIApplication.shared.open(url, options: [:], completionHandler: nil)
}
}
- }) {
+ }, label: {
Image(systemName: "plus")
.foregroundColor(ColorConstants.Light.primary)
- }
+ })
}
}
}
@@ -141,8 +143,7 @@ public struct CredentialProviderView: View {
buttons.append(.default(Text("Password")) {
viewModel.selectPassword()
})
- }
- else {
+ } else {
if let username = credential.username, !username.isEmpty {
buttons.append(.default(Text("Username: \(username)")) {
viewModel.selectUsernamePassword()
@@ -380,48 +381,6 @@ public class CredentialProviderViewModel: ObservableObject {
}
}
-// MARK: - SearchBar
-
-struct SearchBar: View {
- @Binding var text: String
- @Environment(\.colorScheme) private var colorScheme
-
- var body: some View {
- ZStack {
- HStack {
- Image(systemName: "magnifyingglass")
- .foregroundColor(colorScheme == .dark ? ColorConstants.Dark.text : ColorConstants.Light.text)
- .padding(.leading, 8)
-
- TextField("Search credentials...", text: $text)
- .autocapitalization(.none)
- .foregroundColor(colorScheme == .dark ? ColorConstants.Dark.text : ColorConstants.Light.text)
- .padding(.leading, 4)
- .padding(.trailing, 28) // Space for clear button
- }
- .padding(8)
- .padding(.vertical, 2)
- .background(colorScheme == .dark ? ColorConstants.Dark.accentBackground : ColorConstants.Light.accentBackground)
- .cornerRadius(8)
-
- if !text.isEmpty {
- HStack {
- Spacer()
- Button(action: {
- text = ""
- }) {
- Image(systemName: "xmark.circle.fill")
- .foregroundColor(colorScheme == .dark ? ColorConstants.Dark.text : ColorConstants.Light.text)
- }
- .padding(.trailing, 8)
- }
- }
- }
- }
-}
-
-
-
// MARK: - Preview Helpers
extension Service {
static var preview: Service {
@@ -483,9 +442,8 @@ extension Credential {
}
}
-
// Preview setup
-class PreviewCredentialProviderViewModel: CredentialProviderViewModel {
+public class PreviewCredentialProviderViewModel: CredentialProviderViewModel {
init() {
let previewCredentials = [
.preview,
@@ -526,19 +484,19 @@ class PreviewCredentialProviderViewModel: CredentialProviderViewModel {
}
}
-struct CredentialProviderView_Previews: PreviewProvider {
+public struct CredentialProviderView_Previews: PreviewProvider {
static func makePreview(isChoosing: Bool, showingSelection: Bool, colorScheme: ColorScheme) -> some View {
- let vm = PreviewCredentialProviderViewModel()
- vm.isChoosingTextToInsert = isChoosing
+ let viewModel = PreviewCredentialProviderViewModel()
+ viewModel.isChoosingTextToInsert = isChoosing
if showingSelection {
- vm.selectedCredential = .preview
- vm.showSelectionOptions = true
+ viewModel.selectedCredential = .preview
+ viewModel.showSelectionOptions = true
}
- return CredentialProviderView(viewModel: vm)
+ return CredentialProviderView(viewModel: viewModel)
.environment(\.colorScheme, colorScheme)
}
- static var previews: some View {
+ public static var previews: some View {
Group {
makePreview(isChoosing: false, showingSelection: false, colorScheme: .light)
.previewDisplayName("Light - Normal")
diff --git a/apps/mobile-app/specs/NativeVaultManager.ts b/apps/mobile-app/specs/NativeVaultManager.ts
index 98964c051..7a30e7a86 100644
--- a/apps/mobile-app/specs/NativeVaultManager.ts
+++ b/apps/mobile-app/specs/NativeVaultManager.ts
@@ -4,7 +4,6 @@ import { TurboModuleRegistry } from 'react-native';
// eslint-disable-next-line @typescript-eslint/naming-convention
export interface Spec extends TurboModule {
// Basic credential operations
- getCredentials(): Promise<{ credentials: { username: string; password: string; service: string }[] }>;
clearVault(): Promise<void>;
// Vault state management