Skip to content

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

Update VaultStore logic, getAllCredentials currently breaks (#771)

Leendert de Borst5a7e0cf9e5d8
diff --git a/mobile-app/ios/AliasVault.xcodeproj/xcshareddata/xcschemes/Autofill.xcscheme b/mobile-app/ios/AliasVault.xcodeproj/xcshareddata/xcschemes/Autofill.xcscheme
new file mode 100644
index 000000000..1e9b86a48
--- /dev/null
+++ b/mobile-app/ios/AliasVault.xcodeproj/xcshareddata/xcschemes/Autofill.xcscheme
@@ -0,0 +1,104 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<Scheme
+ LastUpgradeVersion = "1630"
+ wasCreatedForAppExtension = "YES"
+ version = "1.7">
+ <BuildAction
+ parallelizeBuildables = "YES"
+ buildImplicitDependencies = "YES"
+ buildArchitectures = "Automatic">
+ <BuildActionEntries>
+ <BuildActionEntry
+ buildForTesting = "YES"
+ buildForRunning = "YES"
+ buildForProfiling = "YES"
+ buildForArchiving = "YES"
+ buildForAnalyzing = "YES">
+ <BuildableReference
+ BuildableIdentifier = "primary"
+ BlueprintIdentifier = "CEE9097D2DA548C7008D568F"
+ BuildableName = "Autofill.appex"
+ BlueprintName = "Autofill"
+ ReferencedContainer = "container:AliasVault.xcodeproj">
+ </BuildableReference>
+ </BuildActionEntry>
+ <BuildActionEntry
+ buildForTesting = "YES"
+ buildForRunning = "YES"
+ buildForProfiling = "YES"
+ buildForArchiving = "YES"
+ buildForAnalyzing = "YES">
+ <BuildableReference
+ BuildableIdentifier = "primary"
+ BlueprintIdentifier = "13B07F861A680F5B00A75B9A"
+ BuildableName = "AliasVault.app"
+ BlueprintName = "AliasVault"
+ ReferencedContainer = "container:AliasVault.xcodeproj">
+ </BuildableReference>
+ </BuildActionEntry>
+ </BuildActionEntries>
+ </BuildAction>
+ <TestAction
+ buildConfiguration = "Debug"
+ selectedDebuggerIdentifier = "Xcode.DebuggerFoundation.Debugger.LLDB"
+ selectedLauncherIdentifier = "Xcode.DebuggerFoundation.Launcher.LLDB"
+ shouldUseLaunchSchemeArgsEnv = "YES"
+ shouldAutocreateTestPlan = "YES">
+ </TestAction>
+ <LaunchAction
+ buildConfiguration = "Debug"
+ selectedDebuggerIdentifier = "Xcode.DebuggerFoundation.Debugger.LLDB"
+ selectedLauncherIdentifier = "Xcode.DebuggerFoundation.Launcher.LLDB"
+ launchStyle = "0"
+ useCustomWorkingDirectory = "NO"
+ ignoresPersistentStateOnLaunch = "NO"
+ debugDocumentVersioning = "YES"
+ debugServiceExtension = "internal"
+ allowLocationSimulation = "YES">
+ <BuildableProductRunnable
+ runnableDebuggingMode = "0">
+ <BuildableReference
+ BuildableIdentifier = "primary"
+ BlueprintIdentifier = "CEE9097D2DA548C7008D568F"
+ BuildableName = "Autofill.appex"
+ BlueprintName = "Autofill"
+ ReferencedContainer = "container:AliasVault.xcodeproj">
+ </BuildableReference>
+ </BuildableProductRunnable>
+ <MacroExpansion>
+ <BuildableReference
+ BuildableIdentifier = "primary"
+ BlueprintIdentifier = "13B07F861A680F5B00A75B9A"
+ BuildableName = "AliasVault.app"
+ BlueprintName = "AliasVault"
+ ReferencedContainer = "container:AliasVault.xcodeproj">
+ </BuildableReference>
+ </MacroExpansion>
+ </LaunchAction>
+ <ProfileAction
+ buildConfiguration = "Release"
+ shouldUseLaunchSchemeArgsEnv = "YES"
+ savedToolIdentifier = ""
+ useCustomWorkingDirectory = "NO"
+ debugDocumentVersioning = "YES"
+ askForAppToLaunch = "Yes"
+ launchAutomaticallySubstyle = "2">
+ <BuildableProductRunnable
+ runnableDebuggingMode = "0">
+ <BuildableReference
+ BuildableIdentifier = "primary"
+ BlueprintIdentifier = "13B07F861A680F5B00A75B9A"
+ BuildableName = "AliasVault.app"
+ BlueprintName = "AliasVault"
+ ReferencedContainer = "container:AliasVault.xcodeproj">
+ </BuildableReference>
+ </BuildableProductRunnable>
+ </ProfileAction>
+ <AnalyzeAction
+ buildConfiguration = "Debug">
+ </AnalyzeAction>
+ <ArchiveAction
+ buildConfiguration = "Release"
+ revealArchiveInOrganizer = "YES">
+ </ArchiveAction>
+</Scheme>
diff --git a/mobile-app/ios/Autofill/CredentialIdentityStore.swift b/mobile-app/ios/Autofill/CredentialIdentityStore.swift
index fa2af5e88..b3c0aea80 100644
--- a/mobile-app/ios/Autofill/CredentialIdentityStore.swift
+++ b/mobile-app/ios/Autofill/CredentialIdentityStore.swift
@@ -15,13 +15,13 @@ class CredentialIdentityStore {
func saveCredentialIdentities(_ credentials: [Credential]) async throws {
let identities = credentials.map { credential in
let serviceIdentifier = ASCredentialServiceIdentifier(
- identifier: credential.service,
+ identifier: credential.service.name ?? "",
type: .domain
)
return ASPasswordCredentialIdentity(
serviceIdentifier: serviceIdentifier,
- user: credential.username,
+ user: credential.username ?? "",
// TODO: Use the actual record identifier when implementing the actual vault
recordIdentifier: UUID().uuidString
)
@@ -37,13 +37,13 @@ class CredentialIdentityStore {
func removeCredentialIdentities(_ credentials: [Credential]) async throws {
let identities = credentials.map { credential in
let serviceIdentifier = ASCredentialServiceIdentifier(
- identifier: credential.service,
+ identifier: credential.service.name ?? "",
type: .domain
)
return ASPasswordCredentialIdentity(
serviceIdentifier: serviceIdentifier,
- user: credential.username,
+ user: credential.username ?? "",
// TODO: Use the actual record identifier when implementing the actual vault
recordIdentifier: UUID().uuidString
)
@@ -51,4 +51,4 @@ class CredentialIdentityStore {
try await store.removeCredentialIdentities(identities)
}
-}
\ No newline at end of file
+}
diff --git a/mobile-app/ios/Autofill/CredentialProviderView.swift b/mobile-app/ios/Autofill/CredentialProviderView.swift
index 9d6b21aa5..7ed627d58 100644
--- a/mobile-app/ios/Autofill/CredentialProviderView.swift
+++ b/mobile-app/ios/Autofill/CredentialProviderView.swift
@@ -1,37 +1,65 @@
import SwiftUI
import AuthenticationServices
+struct ColorConstants {
+ struct Light {
+ static let text = Color(hex: "#11181C")
+ static let textMuted = Color(hex: "#4b5563")
+ static let background = Color(hex: "#ffffff")
+ static let accentBackground = Color(hex: "#fff")
+ static let accentBorder = Color(hex: "#d1d5db")
+ static let primary = Color(hex: "#f49541")
+ static let secondary = Color(hex: "#6b7280")
+ static let icon = Color(hex: "#687076")
+ }
+
+ struct Dark {
+ static let text = Color(hex: "#ECEDEE")
+ static let textMuted = Color(hex: "#9BA1A6")
+ static let background = Color(hex: "#111827")
+ static let accentBackground = Color(hex: "#1f2937")
+ static let accentBorder = Color(hex: "#4b5563")
+ static let primary = Color(hex: "#f49541")
+ static let secondary = Color(hex: "#6b7280")
+ static let icon = Color(hex: "#9BA1A6")
+ }
+}
+
struct CredentialProviderView: View {
@ObservedObject var viewModel: CredentialProviderViewModel
@Environment(\.dismiss) private var dismiss
+ @Environment(\.colorScheme) private var colorScheme
var body: some View {
NavigationView {
ZStack {
+ (colorScheme == .dark ? ColorConstants.Dark.background : ColorConstants.Light.background)
+ .ignoresSafeArea()
+
if viewModel.isLoading {
ProgressView("Loading credentials...")
.progressViewStyle(.circular)
.scaleEffect(1.5)
} else {
- VStack {
+ 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()
}
- List(viewModel.filteredCredentials, id: \.service) { credential in
- Button(action: {
- viewModel.selectCredential(credential)
- }) {
- VStack(alignment: .leading) {
- Text(credential.service)
- .font(.headline)
- Text(credential.username)
- .font(.subheadline)
- .foregroundColor(.secondary)
+ ScrollView {
+ LazyVStack(spacing: 12) {
+ ForEach(viewModel.filteredCredentials, id: \.service) { credential in
+ CredentialCard(credential: credential) {
+ viewModel.selectCredential(credential)
+ }
}
}
+ .padding(.horizontal)
+ .padding(.top, 8)
}
.refreshable {
viewModel.loadCredentials()
@@ -46,7 +74,7 @@ struct CredentialProviderView: View {
Button("Cancel") {
viewModel.cancel()
}
- .foregroundColor(.red)
+ .foregroundColor(ColorConstants.Light.primary)
}
ToolbarItem(placement: .navigationBarTrailing) {
@@ -55,11 +83,13 @@ struct CredentialProviderView: View {
viewModel.loadCredentials()
} label: {
Image(systemName: "arrow.clockwise")
+ .foregroundColor(colorScheme == .dark ? ColorConstants.Dark.icon : ColorConstants.Light.icon)
}
Button("Add") {
viewModel.showAddCredential = true
}
+ .foregroundColor(ColorConstants.Light.primary)
}
}
}
@@ -74,7 +104,6 @@ struct CredentialProviderView: View {
Text(viewModel.errorMessage)
}
.task {
- // wait for .1sec
try? await Task.sleep(nanoseconds: 100_000_000)
viewModel.loadCredentials()
}
@@ -85,6 +114,90 @@ struct CredentialProviderView: View {
}
}
+struct ServiceLogoView: View {
+ let logoData: Data?
+ @Environment(\.colorScheme) private var colorScheme
+
+ var body: some View {
+ Group {
+ if let logoData = logoData {
+ if let image = UIImage(data: logoData) {
+ Image(uiImage: image)
+ .resizable()
+ .aspectRatio(contentMode: .fit)
+ .frame(width: 24, height: 24)
+ } else if let svgString = String(data: logoData, encoding: .utf8),
+ svgString.contains("<svg") || svgString.contains("<?xml") {
+ // For SVG, we'll use a placeholder for now since SwiftUI doesn't have built-in SVG support
+ // In a real implementation, you might want to use a third-party SVG renderer
+ Circle()
+ .fill(colorScheme == .dark ? ColorConstants.Dark.accentBackground : ColorConstants.Light.background)
+ .frame(width: 40, height: 40)
+ .overlay(
+ Circle()
+ .stroke(colorScheme == .dark ? ColorConstants.Dark.accentBorder : ColorConstants.Light.accentBorder, lineWidth: 1)
+ )
+ } else {
+ // Fallback for other formats
+ Circle()
+ .fill(colorScheme == .dark ? ColorConstants.Dark.accentBackground : ColorConstants.Light.background)
+ .frame(width: 40, height: 40)
+ .overlay(
+ Circle()
+ .stroke(colorScheme == .dark ? ColorConstants.Dark.accentBorder : ColorConstants.Light.accentBorder, lineWidth: 1)
+ )
+ }
+ } else {
+ Circle()
+ .fill(colorScheme == .dark ? ColorConstants.Dark.accentBackground : ColorConstants.Light.background)
+ .frame(width: 40, height: 40)
+ .overlay(
+ Circle()
+ .stroke(colorScheme == .dark ? ColorConstants.Dark.accentBorder : ColorConstants.Light.accentBorder, lineWidth: 1)
+ )
+ }
+ }
+ }
+}
+
+struct CredentialCard: View {
+ let credential: Credential
+ let action: () -> Void
+ @Environment(\.colorScheme) private var colorScheme
+
+ var body: some View {
+ Button(action: action) {
+ HStack(spacing: 16) {
+ // Service logo
+ ServiceLogoView(logoData: credential.service.logo)
+ .frame(width: 40, height: 40)
+
+ VStack(alignment: .leading, spacing: 4) {
+ Text(credential.service.name ?? "Unknown Service")
+ .font(.headline)
+ .foregroundColor(colorScheme == .dark ? ColorConstants.Dark.text : ColorConstants.Light.text)
+
+ Text(credential.username ?? "No username")
+ .font(.subheadline)
+ .foregroundColor(colorScheme == .dark ? ColorConstants.Dark.textMuted : ColorConstants.Light.textMuted)
+ }
+
+ Spacer()
+
+ Image(systemName: "chevron.right")
+ .foregroundColor(colorScheme == .dark ? ColorConstants.Dark.icon : ColorConstants.Light.icon)
+ }
+ .padding(16)
+ .background(colorScheme == .dark ? ColorConstants.Dark.accentBackground : ColorConstants.Light.background)
+ .overlay(
+ RoundedRectangle(cornerRadius: 12)
+ .stroke(colorScheme == .dark ? ColorConstants.Dark.accentBorder : ColorConstants.Light.accentBorder, lineWidth: 1)
+ )
+ .cornerRadius(12)
+ }
+ }
+}
+
struct AddCredentialView: View {
@ObservedObject var viewModel: CredentialProviderViewModel
@Environment(\.dismiss) private var dismiss
@@ -176,7 +289,7 @@ class CredentialProviderViewModel: ObservableObject {
do {
let vaultStore = VaultStore()
- // Init DB
+ // Initialize the DB. Note: this can prompt the user for biometric authentication.
try vaultStore.initializeDatabase()
credentials = try vaultStore.getAllCredentials()
@@ -202,23 +315,58 @@ class CredentialProviderViewModel: ObservableObject {
filteredCredentials = credentials
} else {
filteredCredentials = credentials.filter { credential in
- credential.service.localizedCaseInsensitiveContains(searchText) ||
- credential.username.localizedCaseInsensitiveContains(searchText)
+ (credential.service.name?.localizedCaseInsensitiveContains(searchText) ?? false) ||
+ (credential.username?.localizedCaseInsensitiveContains(searchText) ?? false)
}
}
}
func selectCredential(_ credential: Credential) {
- let passwordCredential = ASPasswordCredential(user: credential.username,
- password: credential.password)
+ guard let username = credential.username else {
+ handleError(NSError(domain: "CredentialProvider", code: -1, userInfo: [NSLocalizedDescriptionKey: "Username is required"]))
+ return
+ }
+
+ // Note: We need to get the password from the Password model
+ // This will need to be updated once we have access to the Password model
+ let passwordCredential = ASPasswordCredential(user: username, password: "")
extensionContext?.completeRequest(withSelectedCredential: passwordCredential,
completionHandler: nil)
}
func addCredential() {
- let credential = Credential(username: newUsername,
- password: newPassword,
- service: newService)
+ // Note: This will need to be updated to create proper Service and Password models
+ // For now, we'll just create a basic credential
+ let service = Service(
+ id: UUID(),
+ name: newService,
+ url: nil,
+ logo: nil,
+ createdAt: Date(),
+ updatedAt: Date(),
+ isDeleted: false
+ )
+
+ let password = Password(
+ id: UUID(),
+ credentialId: UUID(),
+ value: newPassword,
+ createdAt: Date(),
+ updatedAt: Date(),
+ isDeleted: false
+ )
+
+ let credential = Credential(
+ id: UUID(),
+ aliasId: UUID(), // This should be provided by the system
+ service: service,
+ username: newUsername,
+ notes: nil,
+ password: password,
+ createdAt: Date(),
+ updatedAt: Date(),
+ isDeleted: false
+ )
do {
let vaultStore = VaultStore()
@@ -254,3 +402,30 @@ class CredentialProviderViewModel: ObservableObject {
}
}
}
+
+// Add Color extension for hex support
+extension Color {
+ init(hex: String) {
+ let hex = hex.trimmingCharacters(in: CharacterSet.alphanumerics.inverted)
+ var int: UInt64 = 0
+ Scanner(string: hex).scanHexInt64(&int)
+ let a, r, g, b: UInt64
+ switch hex.count {
+ case 3: // RGB (12-bit)
+ (a, r, g, b) = (255, (int >> 8) * 17, (int >> 4 & 0xF) * 17, (int & 0xF) * 17)
+ case 6: // RGB (24-bit)
+ (a, r, g, b) = (255, int >> 16, int >> 8 & 0xFF, int & 0xFF)
+ case 8: // ARGB (32-bit)
+ (a, r, g, b) = (int >> 24, int >> 16 & 0xFF, int >> 8 & 0xFF, int & 0xFF)
+ default:
+ (a, r, g, b) = (1, 1, 1, 0)
+ }
+ self.init(
+ .sRGB,
+ red: Double(r) / 255,
+ green: Double(g) / 255,
+ blue: Double(b) / 255,
+ opacity: Double(a) / 255
+ )
+ }
+}
diff --git a/mobile-app/ios/Autofill/CredentialProviderViewController.swift b/mobile-app/ios/Autofill/CredentialProviderViewController.swift
index 44377fc47..7ff7d8b7a 100644
--- a/mobile-app/ios/Autofill/CredentialProviderViewController.swift
+++ b/mobile-app/ios/Autofill/CredentialProviderViewController.swift
@@ -8,18 +8,26 @@
import AuthenticationServices
import SwiftUI
+/**
+ * This class is the main entry point for the autofill extension.
+ * It is responsible for displaying the credential provider view and handling user interactions.
+ *
+ * It also contains interface implementations for ASCredentialProviderViewController that allow
+ * us to provide credentials to native system operations that request credentials (e.g. suggesting
+ * logins in the keyboard).
+ */
class CredentialProviderViewController: ASCredentialProviderViewController {
override func viewDidLoad() {
super.viewDidLoad()
-
+
let viewModel = CredentialProviderViewModel(extensionContext: extensionContext)
let hostingController = UIHostingController(
rootView: CredentialProviderView(viewModel: viewModel)
)
-
+
addChild(hostingController)
view.addSubview(hostingController.view)
-
+
hostingController.view.translatesAutoresizingMaskIntoConstraints = false
NSLayoutConstraint.activate([
hostingController.view.topAnchor.constraint(equalTo: view.topAnchor),
@@ -27,18 +35,18 @@ class CredentialProviderViewController: ASCredentialProviderViewController {
hostingController.view.trailingAnchor.constraint(equalTo: view.trailingAnchor),
hostingController.view.bottomAnchor.constraint(equalTo: view.bottomAnchor)
])
-
+
hostingController.didMove(toParent: self)
}
-
+
override func prepareCredentialList(for serviceIdentifiers: [ASCredentialServiceIdentifier]) {
// This is handled in the SwiftUI view's onAppear
}
-
+
override func prepareInterfaceForUserChoosingTextToInsert() {
// This is handled in the SwiftUI view's onAppear
}
-
+
override func provideCredentialWithoutUserInteraction(for credentialIdentity: ASPasswordCredentialIdentity) {
// Get credentials and return the first one that matches the identity
// TODO: how do we handle authentication here? We need Face ID access before we can access credentials..
@@ -47,10 +55,10 @@ class CredentialProviderViewController: ASCredentialProviderViewController {
// autofill the username? Check how this should work functionally.
do {
let credentials = try VaultStore.shared.getAllCredentials()
- if let matchingCredential = credentials.first(where: { $0.service == credentialIdentity.serviceIdentifier.identifier }) {
+ if let matchingCredential = credentials.first(where: { $0.service.name ?? "" == credentialIdentity.serviceIdentifier.identifier }) {
let passwordCredential = ASPasswordCredential(
- user: matchingCredential.username,
- password: matchingCredential.password
+ user: matchingCredential.username ?? "",
+ password: matchingCredential.password?.value ?? ""
)
self.extensionContext.completeRequest(withSelectedCredential: passwordCredential, completionHandler: nil)
} else {
diff --git a/mobile-app/ios/NativeVaultManager/VaultManager.swift b/mobile-app/ios/NativeVaultManager/VaultManager.swift
index de5b63417..9eabb1e81 100644
--- a/mobile-app/ios/NativeVaultManager/VaultManager.swift
+++ b/mobile-app/ios/NativeVaultManager/VaultManager.swift
@@ -107,8 +107,9 @@ public class VaultManager: NSObject {
@objc
func addCredential(_ username: String, password: String, service: String) {
do {
- let credential = Credential(username: username, password: password, service: service)
- try vaultStore.addCredential(credential)
+ // TODO: implement this
+ //let credential = Credential(username: username, password: password, service: service)
+ //try vaultStore.addCredential(credential)
} catch {
print("Failed to add credential: \(error)")
}
diff --git a/mobile-app/ios/VaultStore/Models/Credential.swift b/mobile-app/ios/VaultStore/Models/Credential.swift
index 7fac9f2f9..5abb73d2a 100644
--- a/mobile-app/ios/VaultStore/Models/Credential.swift
+++ b/mobile-app/ios/VaultStore/Models/Credential.swift
@@ -1,11 +1,88 @@
+import Foundation
+
public struct Credential: Codable {
- public let username: String
- public let password: String
- public let service: String
-
- public init(username: String, password: String, service: String) {
+ public let id: UUID
+ public let aliasId: UUID
+ public let service: Service
+ public let username: String?
+ public let notes: String?
+ public let password: Password?
+ public let createdAt: Date
+ public let updatedAt: Date
+ public let isDeleted: Bool
+
+ public init(
+ id: UUID,
+ aliasId: UUID,
+ service: Service,
+ username: String?,
+ notes: String?,
+ password: Password?,
+ createdAt: Date,
+ updatedAt: Date,
+ isDeleted: Bool
+ ) {
+ self.id = id
+ self.aliasId = aliasId
+ self.service = service
self.username = username
+ self.notes = notes
self.password = password
- self.service = service
+ self.createdAt = createdAt
+ self.updatedAt = updatedAt
+ self.isDeleted = isDeleted
+ }
+}
+
+public struct Service: Codable, Hashable {
+ public let id: UUID
+ public let name: String?
+ public let url: String?
+ public let logo: Data?
+ public let createdAt: Date
+ public let updatedAt: Date
+ public let isDeleted: Bool
+
+ public init(
+ id: UUID,
+ name: String?,
+ url: String?,
+ logo: Data?,
+ createdAt: Date,
+ updatedAt: Date,
+ isDeleted: Bool
+ ) {
+ self.id = id
+ self.name = name
+ self.url = url
+ self.logo = logo
+ self.createdAt = createdAt
+ self.updatedAt = updatedAt
+ self.isDeleted = isDeleted
+ }
+}
+
+public struct Password: Codable {
+ public let id: UUID
+ public let credentialId: UUID
+ public let value: String
+ public let createdAt: Date
+ public let updatedAt: Date
+ public let isDeleted: Bool
+
+ public init(
+ id: UUID,
+ credentialId: UUID,
+ value: String,
+ createdAt: Date,
+ updatedAt: Date,
+ isDeleted: Bool
+ ) {
+ self.id = id
+ self.credentialId = credentialId
+ self.value = value
+ self.createdAt = createdAt
+ self.updatedAt = updatedAt
+ self.isDeleted = isDeleted
}
}
\ No newline at end of file
diff --git a/mobile-app/ios/VaultStore/VaultStore.swift b/mobile-app/ios/VaultStore/VaultStore.swift
index 682fc021e..ff7a3e3ff 100644
--- a/mobile-app/ios/VaultStore/VaultStore.swift
+++ b/mobile-app/ios/VaultStore/VaultStore.swift
@@ -27,6 +27,15 @@ class VaultStore {
private let authMethodsKey = "aliasvault_auth_methods"
private let autoLockTimeoutKey = "aliasvault_auto_lock_timeout"
+ // Date formatter for parsing SQLite datetime strings
+ private lazy var dateFormatter: 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
+ }()
+
// User config with default values
private var enabledAuthMethods: AuthMethods = [.password, .faceID] // Default to Face ID and password
private var autoLockTimeout: Int = 3600 // Default to 1 hour (3600 seconds)
@@ -346,9 +355,9 @@ class VaultStore {
try db.run(credentials.insert(
id <- UUID().uuidString,
- username <- credential.username,
- password <- credential.password,
- service <- credential.service,
+ username <- credential.username ?? "",
+ password <- credential.password?.value ?? "",
+ service <- credential.service.name ?? "",
createdAt <- Date(),
updatedAt <- Date()
))
@@ -360,30 +369,115 @@ class VaultStore {
throw NSError(domain: "VaultStore", code: 4, userInfo: [NSLocalizedDescriptionKey: "Database not initialized"])
}
+ print("Executing get all credentials query..")
+
let query = """
- SELECT DISTINCT
+ WITH LatestPasswords AS (
+ SELECT
+ p.Id as password_id,
+ p.CredentialId,
+ p.Value,
+ p.CreatedAt,
+ p.UpdatedAt,
+ p.IsDeleted,
+ ROW_NUMBER() OVER (PARTITION BY p.CredentialId ORDER BY p.CreatedAt DESC) as rn
+ FROM Passwords p
+ WHERE p.IsDeleted = 0
+ )
+ SELECT
+ c.Id,
+ c.AliasId,
c.Username,
- s.Name as ServiceName,
- p.Value as Password
+ c.Notes,
+ c.CreatedAt,
+ c.UpdatedAt,
+ c.IsDeleted,
+ s.Id as service_id,
+ s.Name as service_name,
+ s.Url as service_url,
+ s.Logo as service_logo,
+ s.CreatedAt as service_created_at,
+ s.UpdatedAt as service_updated_at,
+ s.IsDeleted as service_is_deleted,
+ lp.password_id,
+ lp.Value as password_value,
+ lp.CreatedAt as password_created_at,
+ lp.UpdatedAt as password_updated_at,
+ lp.IsDeleted as password_is_deleted
FROM Credentials c
- LEFT JOIN Services s ON c.ServiceId = s.Id
- LEFT JOIN Passwords p ON p.CredentialId = c.Id
+ LEFT JOIN Services s ON s.Id = c.ServiceId AND s.IsDeleted = 0
+ LEFT JOIN LatestPasswords lp ON lp.CredentialId = c.Id AND lp.rn = 1
WHERE c.IsDeleted = 0
ORDER BY c.CreatedAt DESC
"""
var result: [Credential] = []
for row in try db.prepare(query) {
- let username = row[0] as? String ?? ""
- let service = row[1] as? String ?? ""
- let password = row[2] as? String ?? ""
+ guard let idString = row[0] as? String,
+ let aliasIdString = row[1] as? String,
+ let createdAtString = row[4] as? String,
+ let updatedAtString = row[5] as? String,
+ let isDeleted = row[6] as? Int,
+ let createdAt = dateFormatter.date(from: createdAtString),
+ let updatedAt = dateFormatter.date(from: updatedAtString) else {
+ continue
+ }
- result.append(Credential(
- username: username,
- password: password,
+ // Create Service object if service data exists
+ guard let serviceId = row[7] as? String,
+ let serviceCreatedAtString = row[11] as? String,
+ let serviceUpdatedAtString = row[12] as? String,
+ let serviceIsDeleted = row[13] as? Int,
+ let serviceCreatedAt = dateFormatter.date(from: serviceCreatedAtString),
+ let serviceUpdatedAt = dateFormatter.date(from: serviceUpdatedAtString) else {
+ continue
+ }
+
+ let service = Service(
+ id: UUID(uuidString: serviceId)!,
+ name: row[8] as? String,
+ url: row[9] as? String,
+ logo: row[10] as? Data,
+ createdAt: serviceCreatedAt,
+ updatedAt: serviceUpdatedAt,
+ isDeleted: serviceIsDeleted == 1
+ )
+
+ // Create Password object if password data exists
+ var password: Password? = nil
+ if let passwordIdString = row[14] as? String,
+ let passwordValue = row[15] as? String,
+ let passwordCreatedAtString = row[16] as? String,
+ let passwordUpdatedAtString = row[17] as? String,
+ let passwordIsDeleted = row[18] as? Int,
+ let passwordCreatedAt = dateFormatter.date(from: passwordCreatedAtString),
+ let passwordUpdatedAt = dateFormatter.date(from: passwordUpdatedAtString) {
+ password = Password(
+ id: UUID(uuidString: passwordIdString)!,
+ credentialId: UUID(uuidString: idString)!,
+ value: passwordValue,
+ createdAt: passwordCreatedAt,
+ updatedAt: passwordUpdatedAt,
+ isDeleted: passwordIsDeleted == 1
+ )
+ }
+
+ let credential = Credential(
+ id: UUID(uuidString: idString)!,
+ aliasId: UUID(uuidString: aliasIdString)!,
service: service,
- ))
+ username: row[2] as? String,
+ notes: row[3] as? String,
+ password: password,
+ createdAt: createdAt,
+ updatedAt: updatedAt,
+ isDeleted: isDeleted == 1
+ )
+ result.append(credential)
}
+
+ print("Found \(result.count) credentials")
+
return result
}