Skip to content

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

Update iOS logic and queries with manifest scoping (#2159)

Leendert de Borst264fc0ed3ada
diff --git a/apps/mobile-app/ios/Autofill/CredentialProviderViewController+Credential.swift b/apps/mobile-app/ios/Autofill/CredentialProviderViewController+Credential.swift
index be4de191b..60a39f598 100644
--- a/apps/mobile-app/ios/Autofill/CredentialProviderViewController+Credential.swift
+++ b/apps/mobile-app/ios/Autofill/CredentialProviderViewController+Credential.swift
@@ -58,6 +58,13 @@ extension CredentialProviderViewController: CredentialProviderDelegate {
} catch {
print("[Autofill] Failed to refresh iOS credential identity cache: \(error)")
}
+ },
+ usageRecorder: { itemId in
+ do {
+ try vaultStore.recordItemUsage(itemId: itemId, action: .autofill)
+ } catch {
+ print("[Autofill] Failed to record credential usage: \(error)")
+ }
}
)
@@ -130,6 +137,13 @@ extension CredentialProviderViewController: CredentialProviderDelegate {
// 2FA field after the autofill completes.
TotpClipboard.copyCodeIfEnabled(totp: matchingCredential.totp)
+ // Recorded before the request completes: the host may tear the extension down right after.
+ do {
+ try vaultStore.recordItemUsage(itemId: matchingCredential.id, manifestId: matchingCredential.manifestId, action: .autofill)
+ } catch {
+ print("[Autofill] Failed to record credential usage: \(error)")
+ }
+
// Use the identifier that matches the credential identity
let identifier = request.credentialIdentity.user
let passwordCredential = ASPasswordCredential(
diff --git a/apps/mobile-app/ios/Autofill/CredentialProviderViewController+Passkey.swift b/apps/mobile-app/ios/Autofill/CredentialProviderViewController+Passkey.swift
index f72229c36..f0fc6f22e 100644
--- a/apps/mobile-app/ios/Autofill/CredentialProviderViewController+Passkey.swift
+++ b/apps/mobile-app/ios/Autofill/CredentialProviderViewController+Passkey.swift
@@ -20,7 +20,7 @@ extension CredentialProviderViewController: PasskeyProviderDelegate {
},
selectionHandler: { credential in
// For passkey authentication, we assume the data is available
- self.handlePasskeySelection(credential: credential, clientDataHash: clientDataHash, rpId: rpId)
+ self.handlePasskeySelection(credential: credential, clientDataHash: clientDataHash, rpId: rpId, vaultStore: vaultStore)
},
cancelHandler: {
self.handleCancel()
@@ -87,9 +87,11 @@ extension CredentialProviderViewController: PasskeyProviderDelegate {
// If the item behind this passkey also has a TOTP code and the user has the
// copy-on-fill setting enabled (default), put the current code on the clipboard.
- let totp = (try? vaultStore.getFirstTotpCode(forItemId: passkey.parentItemId)) ?? nil
+ let totp = (try? vaultStore.getFirstTotpCode(forItemId: passkey.parentItemId, manifestId: passkey.manifestId)) ?? nil
TotpClipboard.copyCodeIfEnabled(totp: totp)
+ recordPasskeyUsage(vaultStore: vaultStore, passkey: passkey)
+
// Build extension output if PRF results are available (iOS 18+)
if #available(iOS 18.0, *), let prfResults = assertion.prfResults {
// Convert Data to SymmetricKey for PRF output
@@ -646,10 +648,22 @@ extension CredentialProviderViewController: PasskeyProviderDelegate {
extensionContext.completeAssertionRequest(using: credential)
}
+ /**
+ * Record a passkey assertion in the item's usage statistics.
+ * Recorded before the request completes: the host may tear the extension down right after.
+ */
+ private func recordPasskeyUsage(vaultStore: VaultStore, passkey: Passkey) {
+ do {
+ try vaultStore.recordItemUsage(itemId: passkey.parentItemId, manifestId: passkey.manifestId, action: .passkey)
+ } catch {
+ print("[Autofill] Failed to record passkey usage: \(error)")
+ }
+ }
+
/**
* Handle passkey credential selection from picker
*/
- internal func handlePasskeySelection(credential: AutofillCredential, clientDataHash: Data, rpId: String) {
+ internal func handlePasskeySelection(credential: AutofillCredential, clientDataHash: Data, rpId: String, vaultStore: VaultStore) {
do {
// Get the passkey and verify it matches the RP ID
guard let passkey = credential.passkey,
@@ -665,6 +679,8 @@ extension CredentialProviderViewController: PasskeyProviderDelegate {
// enabled (default), put the current code on the clipboard.
TotpClipboard.copyCodeIfEnabled(totp: credential.totp)
+ recordPasskeyUsage(vaultStore: vaultStore, passkey: passkey)
+
// Extract PRF inputs from the passkey request if available
var prfInputs: PrfInputs?
if #available(iOS 18.0, *), let extensionInput = self.currentPasskeyRequest?.extensionInput {
diff --git a/apps/mobile-app/ios/Autofill/CredentialProviderViewController.swift b/apps/mobile-app/ios/Autofill/CredentialProviderViewController.swift
index 006326d16..abbc72744 100644
--- a/apps/mobile-app/ios/Autofill/CredentialProviderViewController.swift
+++ b/apps/mobile-app/ios/Autofill/CredentialProviderViewController.swift
@@ -14,7 +14,7 @@ protocol CredentialProviderDelegate: AnyObject {
protocol PasskeyProviderDelegate: AnyObject {
func setupPasskeyView(vaultStore: VaultStore, rpId: String, clientDataHash: Data) throws -> UIViewController
- func handlePasskeySelection(credential: AutofillCredential, clientDataHash: Data, rpId: String)
+ func handlePasskeySelection(credential: AutofillCredential, clientDataHash: Data, rpId: String, vaultStore: VaultStore)
}
/**
@@ -592,7 +592,7 @@ public class CredentialProviderViewController: ASCredentialProviderViewControlle
title = NSLocalizedString("version_not_supported_title", comment: "Update Required")
message = NSLocalizedString("version_not_supported_message", comment: "Your app version is no longer supported. Please update to the latest version.")
- case .serverVersionNotSupported:
+ case .serverVersionNotSupported, .serverUpdateRequired:
title = NSLocalizedString("server_version_not_supported_title", comment: "Server Update Required")
message = NSLocalizedString("server_version_not_supported_message", comment: "The server version is outdated. Please contact your administrator to update the server.")
diff --git a/apps/mobile-app/ios/VaultModels/AutofillCredential.swift b/apps/mobile-app/ios/VaultModels/AutofillCredential.swift
index fb3a8b91c..9f78f585b 100644
--- a/apps/mobile-app/ios/VaultModels/AutofillCredential.swift
+++ b/apps/mobile-app/ios/VaultModels/AutofillCredential.swift
@@ -5,8 +5,8 @@ import Foundation
/// This replaces the legacy Credential model which was based on the old data structure.
public struct AutofillCredential: Codable, Hashable, Equatable {
public let id: UUID
+ public let manifestId: String?
public let serviceName: String?
- /// All URLs associated with this credential (for multi-URL support)
public let serviceUrls: [String]
public let logo: Data?
public let username: String?
@@ -25,6 +25,7 @@ public struct AutofillCredential: Codable, Hashable, Equatable {
public init(
id: UUID,
+ manifestId: String? = nil,
serviceName: String?,
serviceUrls: [String],
logo: Data?,
@@ -38,6 +39,7 @@ public struct AutofillCredential: Codable, Hashable, Equatable {
updatedAt: Date
) {
self.id = id
+ self.manifestId = manifestId
self.serviceName = serviceName
self.serviceUrls = serviceUrls
self.logo = logo
@@ -58,6 +60,7 @@ public struct AutofillCredential: Codable, Hashable, Equatable {
/// - totp: Optional TOTP code for this item
public init(from item: Item, passkey: Passkey? = nil, totp: TotpCode? = nil) {
self.id = item.id
+ self.manifestId = item.manifestId
self.serviceName = item.name
self.serviceUrls = item.urls
self.logo = item.logo
diff --git a/apps/mobile-app/ios/VaultModels/Item.swift b/apps/mobile-app/ios/VaultModels/Item.swift
index a470812bc..ae5570dc4 100644
--- a/apps/mobile-app/ios/VaultModels/Item.swift
+++ b/apps/mobile-app/ios/VaultModels/Item.swift
@@ -3,6 +3,7 @@ import Foundation
/// Item type representing vault entries in the new field-based data model.
public struct Item: Codable, Hashable, Equatable {
public let id: UUID
+ public let manifestId: String
public let name: String?
public let itemType: String
public let logo: Data?
@@ -17,6 +18,7 @@ public struct Item: Codable, Hashable, Equatable {
public init(
id: UUID,
+ manifestId: String,
name: String?,
itemType: String,
logo: Data?,
@@ -30,6 +32,7 @@ public struct Item: Codable, Hashable, Equatable {
updatedAt: Date
) {
self.id = id
+ self.manifestId = manifestId
self.name = name
self.itemType = itemType
self.logo = logo
diff --git a/apps/mobile-app/ios/VaultModels/Passkey.swift b/apps/mobile-app/ios/VaultModels/Passkey.swift
index a93fe694b..2ff898cc7 100644
--- a/apps/mobile-app/ios/VaultModels/Passkey.swift
+++ b/apps/mobile-app/ios/VaultModels/Passkey.swift
@@ -17,6 +17,8 @@ public struct Passkey: Codable, Hashable, Equatable {
public let createdAt: Date
public let updatedAt: Date
public let isDeleted: Bool
+ public let manifestId: String?
+ public let additionalData: String?
public init(
id: UUID,
@@ -30,7 +32,9 @@ public struct Passkey: Codable, Hashable, Equatable {
displayName: String,
createdAt: Date,
updatedAt: Date,
- isDeleted: Bool
+ isDeleted: Bool,
+ manifestId: String? = nil,
+ additionalData: String? = nil
) {
self.id = id
self.parentItemId = parentItemId
@@ -44,6 +48,8 @@ public struct Passkey: Codable, Hashable, Equatable {
self.createdAt = createdAt
self.updatedAt = updatedAt
self.isDeleted = isDeleted
+ self.manifestId = manifestId
+ self.additionalData = additionalData
}
public static func == (lhs: Passkey, rhs: Passkey) -> Bool {
diff --git a/apps/mobile-app/ios/VaultStoreKit/Database/DatabaseClient.swift b/apps/mobile-app/ios/VaultStoreKit/Database/DatabaseClient.swift
index 0e76d9e4a..029ac9794 100644
--- a/apps/mobile-app/ios/VaultStoreKit/Database/DatabaseClient.swift
+++ b/apps/mobile-app/ios/VaultStoreKit/Database/DatabaseClient.swift
@@ -18,6 +18,7 @@ public protocol DatabaseClient: AnyObject {
/// - query: The SQL query to execute
/// - params: The parameters to bind to the query
/// - Returns: Number of rows affected
+ @discardableResult
func executeUpdate(_ query: String, params: [SqliteBindValue]) throws -> Int
/// Begin a database transaction.
diff --git a/apps/mobile-app/ios/VaultStoreKit/Database/Mappers/FieldMapper.swift b/apps/mobile-app/ios/VaultStoreKit/Database/Mappers/FieldMapper.swift
index 7bd6a8022..48dc291a9 100644
--- a/apps/mobile-app/ios/VaultStoreKit/Database/Mappers/FieldMapper.swift
+++ b/apps/mobile-app/ios/VaultStoreKit/Database/Mappers/FieldMapper.swift
@@ -4,6 +4,7 @@ import VaultModels
/// Raw field row from database query.
public struct FieldRow {
public let itemId: String
+ public let manifestId: String
public let fieldKey: String?
public let fieldDefinitionId: String?
public let customLabel: String?
@@ -15,6 +16,7 @@ public struct FieldRow {
public init(
itemId: String,
+ manifestId: String,
fieldKey: String?,
fieldDefinitionId: String?,
customLabel: String?,
@@ -25,6 +27,7 @@ public struct FieldRow {
displayOrder: Int
) {
self.itemId = itemId
+ self.manifestId = manifestId
self.fieldKey = fieldKey
self.fieldDefinitionId = fieldDefinitionId
self.customLabel = customLabel
@@ -37,33 +40,10 @@ public struct FieldRow {
/// Initialize from a database row dictionary.
public init?(from row: [String: Any]) {
- guard let itemId = row["ItemId"] as? String else { return nil }
+ guard let itemId = row["ItemId"] as? String, let manifestId = row["ManifestId"] as? String else { return nil }
self.itemId = itemId
- self.fieldKey = row["FieldKey"] as? String
- self.fieldDefinitionId = row["FieldDefinitionId"] as? String
- self.customLabel = row["CustomLabel"] as? String
- self.customFieldType = row["CustomFieldType"] as? String
- self.customIsHidden = row["CustomIsHidden"] as? Int64
- self.customEnableHistory = row["CustomEnableHistory"] as? Int64
- self.value = row["Value"] as? String ?? ""
- self.displayOrder = Int(row["DisplayOrder"] as? Int64 ?? 0)
- }
-}
-
-/// Raw field row for single item queries (without ItemId).
-public struct SingleItemFieldRow {
- public let fieldKey: String?
- public let fieldDefinitionId: String?
- public let customLabel: String?
- public let customFieldType: String?
- public let customIsHidden: Int64?
- public let customEnableHistory: Int64?
- public let value: String
- public let displayOrder: Int
-
- /// Initialize from a database row dictionary.
- public init?(from row: [String: Any]) {
+ self.manifestId = manifestId
self.fieldKey = row["FieldKey"] as? String
self.fieldDefinitionId = row["FieldDefinitionId"] as? String
self.customLabel = row["CustomLabel"] as? String
@@ -78,6 +58,7 @@ public struct SingleItemFieldRow {
/// Intermediate field representation before grouping.
public struct ProcessedField {
public let itemId: String
+ public let manifestId: String
public let fieldKey: String
public let label: String
public let fieldType: String
@@ -91,23 +72,19 @@ public struct ProcessedField {
/// Mapper class for processing database field rows into ItemField objects.
/// Handles both system fields (with FieldKey) and custom fields (with FieldDefinitionId).
public struct FieldMapper {
- /// Process raw field rows from database into a map of ItemId -> [ItemField].
+ /// Process raw field rows from database into a map of scoped item key (see `scopedKey`) -> [ItemField].
/// Handles system vs custom fields. Multi-value fields (like URLs) create separate ItemField entries
/// with the same fieldKey but different values, allowing Item.getFieldValues() to return all values.
/// - Parameter rows: Raw field rows from database
- /// - Returns: Dictionary of ItemId to array of ItemField objects
+ /// - Returns: Dictionary of scoped item key to array of ItemField objects
public static func processFieldRows(_ rows: [FieldRow]) -> [String: [ItemField]] {
// First, convert rows to processed fields with proper metadata
let processedFields = rows.map { processFieldRow($0) }
- // Group fields by ItemId, keeping separate entries for multi-value fields
+ // Group fields by item key, keeping separate entries for multi-value fields
var fieldsByItem: [String: [ItemField]] = [:]
for field in processedFields {
- if fieldsByItem[field.itemId] == nil {
- fieldsByItem[field.itemId] = []
- }
-
// Create an ItemField for each row (including duplicates for multi-value fields)
let itemField = ItemField(
fieldKey: field.fieldKey,
@@ -119,7 +96,7 @@ public struct FieldMapper {
isCustomField: field.isCustomField,
enableHistory: field.enableHistory
)
- fieldsByItem[field.itemId]!.append(itemField)
+ fieldsByItem[scopedKey(manifestId: field.manifestId, id: field.itemId), default: []].append(itemField)
}
return fieldsByItem
@@ -143,6 +120,7 @@ public struct FieldMapper {
)
return ProcessedField(
itemId: row.itemId,
+ manifestId: row.manifestId,
fieldKey: fieldKey,
label: metadata.label,
fieldType: metadata.fieldType,
@@ -157,6 +135,7 @@ public struct FieldMapper {
let fieldKey = row.fieldDefinitionId ?? ""
return ProcessedField(
itemId: row.itemId,
+ manifestId: row.manifestId,
fieldKey: fieldKey,
label: row.customLabel ?? "",
fieldType: row.customFieldType ?? FieldType.text,
@@ -169,53 +148,6 @@ public struct FieldMapper {
}
}
- /// Process field rows for a single item (without ItemId in result).
- /// Used when fetching a single item by ID.
- /// Multi-value fields (like URLs) create separate ItemField entries with the same fieldKey.
- /// - Parameter rows: Raw field rows for a single item
- /// - Returns: Array of ItemField objects
- public static func processFieldRowsForSingleItem(_ rows: [SingleItemFieldRow]) -> [ItemField] {
- // Create an ItemField for each row (including duplicates for multi-value fields)
- return rows.map { row in
- let fieldKey = row.fieldKey ?? row.fieldDefinitionId ?? ""
- let isCustomField = row.fieldKey == nil || row.fieldKey!.isEmpty
-
- if !isCustomField, let rowFieldKey = row.fieldKey {
- // System field
- let metadata = resolveFieldMetadata(
- fieldKey: rowFieldKey,
- customLabel: nil,
- customFieldType: nil,
- customIsHidden: false,
- customEnableHistory: false,
- isCustomField: false
- )
- return ItemField(
- fieldKey: rowFieldKey,
- label: metadata.label,
- fieldType: metadata.fieldType,
- value: row.value,
- isHidden: metadata.isHidden,
- displayOrder: row.displayOrder,
- isCustomField: false,
- enableHistory: metadata.enableHistory
- )
- } else {
- // Custom field
- return ItemField(
- fieldKey: fieldKey,
- label: row.customLabel ?? "",
- fieldType: row.customFieldType ?? FieldType.text,
- value: row.value,
- isHidden: row.customIsHidden == 1,
- displayOrder: row.displayOrder,
- isCustomField: true,
- enableHistory: row.customEnableHistory == 1
- )
- }
- }.sorted { $0.displayOrder < $1.displayOrder }
- }
-
// MARK: - Field Metadata Resolution
/// Helper struct to hold resolved field metadata.
diff --git a/apps/mobile-app/ios/VaultStoreKit/Database/Mappers/ItemMapper.swift b/apps/mobile-app/ios/VaultStoreKit/Database/Mappers/ItemMapper.swift
index c4a2ef17b..09d452599 100644
--- a/apps/mobile-app/ios/VaultStoreKit/Database/Mappers/ItemMapper.swift
+++ b/apps/mobile-app/ios/VaultStoreKit/Database/Mappers/ItemMapper.swift
@@ -5,6 +5,7 @@ import VaultUtils
/// Raw item row from database query.
public struct ItemRow {
public let id: String
+ public let manifestId: String
public let name: String?
public let itemType: String
public let folderId: String?
@@ -20,6 +21,7 @@ public struct ItemRow {
/// Initialize from a database row dictionary.
public init?(from row: [String: Any]) {
guard let id = row["Id"] as? String,
+ let manifestId = row["ManifestId"] as? String,
let itemType = row["ItemType"] as? String,
let createdAt = row["CreatedAt"] as? String,
let updatedAt = row["UpdatedAt"] as? String else {
@@ -27,6 +29,7 @@ public struct ItemRow {
}
self.id = id
+ self.manifestId = manifestId
self.name = row["Name"] as? String
self.itemType = itemType
self.folderId = row["FolderId"] as? String
@@ -46,46 +49,10 @@ public struct ItemRow {
self.deletedAt = row["DeletedAt"] as? String
self.archivedAt = row["ArchivedAt"] as? String
}
-}
-
-/// Raw tag row from database query.
-public struct TagRow {
- public let itemId: String
- public let id: String
- public let name: String
- public let color: String?
-
- /// Initialize from a database row dictionary.
- public init?(from row: [String: Any]) {
- guard let itemId = row["ItemId"] as? String,
- let id = row["Id"] as? String,
- let name = row["Name"] as? String else {
- return nil
- }
-
- self.itemId = itemId
- self.id = id
- self.name = name
- self.color = row["Color"] as? String
- }
-}
-
-/// Tag reference for single item queries (without ItemId).
-public struct SingleItemTagRow {
- public let id: String
- public let name: String
- public let color: String?
-
- /// Initialize from a database row dictionary.
- public init?(from row: [String: Any]) {
- guard let id = row["Id"] as? String,
- let name = row["Name"] as? String else {
- return nil
- }
- self.id = id
- self.name = name
- self.color = row["Color"] as? String
+ /// The key this item's child rows and folder path are grouped under (see `scopedKey`).
+ internal var scopedItemKey: String {
+ return scopedKey(manifestId: manifestId, id: id)
}
}
@@ -97,18 +64,14 @@ public struct ItemMapper {
/// - fields: Processed fields for this item
/// - folderPath: Computed folder path array (optional)
/// - Returns: Item object
- public static func mapRow(
- _ row: ItemRow,
- fields: [ItemField] = [],
- folderPath: [String]? = nil
- ) -> Item? {
- guard let createdAt = DateHelpers.parseDateString(row.createdAt),
- let updatedAt = DateHelpers.parseDateString(row.updatedAt) else {
+ public static func mapRow(_ row: ItemRow, fields: [ItemField] = [], folderPath: [String]? = nil) -> Item? {
+ guard let createdAt = DateHelpers.parseDateString(row.createdAt), let updatedAt = DateHelpers.parseDateString(row.updatedAt) else {
return nil
}
return Item(
id: UUID(uuidString: row.id) ?? UUID(),
+ manifestId: row.manifestId,
name: row.name,
itemType: row.itemType,
logo: row.logo,
@@ -126,34 +89,14 @@ public struct ItemMapper {
/// Map multiple database rows to Item objects with their fields.
/// - Parameters:
/// - rows: Raw item rows from database
- /// - fieldsByItem: Dictionary of ItemId to array of fields
- /// - folderPathsByFolderId: Dictionary of FolderId to folder path array (optional)
+ /// - fieldsByItem: Dictionary of scoped item key to array of fields
+ /// - folderPathsByFolderKey: Dictionary of scoped folder key to folder path array (optional)
/// - Returns: Array of Item objects
- public static func mapRows(
- _ rows: [ItemRow],
- fieldsByItem: [String: [ItemField]],
- folderPathsByFolderId: [UUID: [String]] = [:]
- ) -> [Item] {
+ public static func mapRows(_ rows: [ItemRow], fieldsByItem: [String: [ItemField]], folderPathsByFolderKey: [String: [String]] = [:]) -> [Item] {
return rows.compactMap { row in
- let fields = fieldsByItem[row.id] ?? []
- let folderPath = row.folderId
- .flatMap { UUID(uuidString: $0) }
- .flatMap { folderPathsByFolderId[$0] }
+ let fields = fieldsByItem[row.scopedItemKey] ?? []
+ let folderPath = row.folderId.flatMap { folderPathsByFolderKey[scopedKey(manifestId: row.manifestId, id: $0.lowercased())] }
return mapRow(row, fields: fields, folderPath: folderPath)
}
}
-
- /// Map a single item row for recently deleted items (includes DeletedAt).
- /// - Parameters:
- /// - row: Raw item row with DeletedAt
- /// - fields: Processed fields for this item
- /// - folderPath: Computed folder path array (optional)
- /// - Returns: Item object (deletedAt stored as extension or separate property if needed)
- public static func mapDeletedItemRow(
- _ row: ItemRow,
- fields: [ItemField] = [],
- folderPath: [String]? = nil
- ) -> Item? {
- return mapRow(row, fields: fields, folderPath: folderPath)
- }
}
diff --git a/apps/mobile-app/ios/VaultStoreKit/Database/Mappers/PasskeyMapper.swift b/apps/mobile-app/ios/VaultStoreKit/Database/Mappers/PasskeyMapper.swift
index 86e3290e4..4d6692401 100644
--- a/apps/mobile-app/ios/VaultStoreKit/Database/Mappers/PasskeyMapper.swift
+++ b/apps/mobile-app/ios/VaultStoreKit/Database/Mappers/PasskeyMapper.swift
@@ -6,12 +6,14 @@ import VaultUtils
public struct PasskeyRow {
public let id: String
public let itemId: String
+ public let manifestId: String
public let rpId: String
public let userHandle: Data?
public let publicKey: String
public let privateKey: String
public let prfKey: Data?
public let displayName: String
+ public let additionalData: String?
public let createdAt: String
public let updatedAt: String
public let isDeleted: Int64
@@ -20,6 +22,7 @@ public struct PasskeyRow {
public init?(from row: [String: Any]) {
guard let id = row["Id"] as? String,
let itemId = row["ItemId"] as? String,
+ let manifestId = row["ManifestId"] as? String,
let rpId = row["RpId"] as? String,
let publicKey = row["PublicKey"] as? String,
let privateKey = row["PrivateKey"] as? String,
@@ -32,10 +35,12 @@ public struct PasskeyRow {
self.id = id
self.itemId = itemId
+ self.manifestId = manifestId
self.rpId = rpId
self.publicKey = publicKey
self.privateKey = privateKey
self.displayName = displayName
+ self.additionalData = row["AdditionalData"] as? String
self.createdAt = createdAt
self.updatedAt = updatedAt
self.isDeleted = isDeleted
@@ -129,7 +134,9 @@ public struct PasskeyMapper {
displayName: row.displayName,
createdAt: createdAt,
updatedAt: updatedAt,
- isDeleted: row.isDeleted == 1
+ isDeleted: row.isDeleted == 1,
+ manifestId: row.manifestId,
+ additionalData: row.additionalData
)
}
diff --git a/apps/mobile-app/ios/VaultStoreKit/Database/Queries/ItemQueries.swift b/apps/mobile-app/ios/VaultStoreKit/Database/Queries/ItemQueries.swift
index 35f84e30e..d587ab83d 100644
--- a/apps/mobile-app/ios/VaultStoreKit/Database/Queries/ItemQueries.swift
+++ b/apps/mobile-app/ios/VaultStoreKit/Database/Queries/ItemQueries.swift
@@ -1,76 +1,43 @@
import Foundation
/// SQL query constants for Item operations.
-/// Centralizes all item-related queries to avoid duplication.
-/// Mirrors the React Native implementation.
public struct ItemQueries {
/// Base SELECT for items with common fields.
/// Includes LEFT JOIN to Logos and subqueries for HasPasskey/HasAttachment/HasTotp.
public static let baseSelect = """
SELECT DISTINCT
i.Id,
+ i.ManifestId,
i.Name,
i.ItemType,
i.FolderId,
l.FileData as Logo,
- CASE WHEN EXISTS (SELECT 1 FROM Passkeys pk WHERE pk.ItemId = i.Id AND pk.IsDeleted = 0) THEN 1 ELSE 0 END as HasPasskey,
- CASE WHEN EXISTS (SELECT 1 FROM Attachments att WHERE att.ItemId = i.Id AND att.IsDeleted = 0) THEN 1 ELSE 0 END as HasAttachment,
- CASE WHEN EXISTS (SELECT 1 FROM TotpCodes tc WHERE tc.ItemId = i.Id AND tc.IsDeleted = 0) THEN 1 ELSE 0 END as HasTotp,
+ CASE WHEN EXISTS (SELECT 1 FROM Passkeys pk WHERE pk.ItemId = i.Id AND pk.ManifestId = i.ManifestId AND pk.IsDeleted = 0) THEN 1 ELSE 0 END as HasPasskey,
+ CASE WHEN EXISTS (SELECT 1 FROM Attachments att WHERE att.ItemId = i.Id AND att.ManifestId = i.ManifestId AND att.IsDeleted = 0) THEN 1 ELSE 0 END as HasAttachment,
+ CASE WHEN EXISTS (SELECT 1 FROM TotpCodes tc WHERE tc.ItemId = i.Id AND tc.ManifestId = i.ManifestId AND tc.IsDeleted = 0) THEN 1 ELSE 0 END as HasTotp,
i.CreatedAt,
i.UpdatedAt,
i.ArchivedAt
FROM Items i
- LEFT JOIN Logos l ON i.LogoId = l.Id
+ LEFT JOIN Logos l ON i.LogoId = l.Id AND l.ManifestId = i.ManifestId
"""
- /// Get all active items (not deleted, not in deleted items, not archived).
+ /// Get all active items (not deleted, not in trash, not archived). This is what autofill reads.
public static let getAllActive = """
\(baseSelect)
WHERE i.IsDeleted = 0 AND i.DeletedAt IS NULL AND i.ArchivedAt IS NULL
ORDER BY i.CreatedAt DESC
"""
- /// Get all archived items. Deleted items are excluded.
- public static let getArchived = """
- \(baseSelect)
- WHERE i.IsDeleted = 0 AND i.DeletedAt IS NULL AND i.ArchivedAt IS NOT NULL
- ORDER BY i.ArchivedAt DESC
- """
-
- /// Count of archived items.
- public static let countArchived = """
- SELECT COUNT(*) as count
- FROM Items
- WHERE IsDeleted = 0 AND DeletedAt IS NULL AND ArchivedAt IS NOT NULL
- """
-
- /// Get a single item by ID.
- public static let getById = """
- SELECT
- i.Id,
- i.Name,
- i.ItemType,
- i.FolderId,
- l.FileData as Logo,
- CASE WHEN EXISTS (SELECT 1 FROM Passkeys pk WHERE pk.ItemId = i.Id AND pk.IsDeleted = 0) THEN 1 ELSE 0 END as HasPasskey,
- CASE WHEN EXISTS (SELECT 1 FROM Attachments att WHERE att.ItemId = i.Id AND att.IsDeleted = 0) THEN 1 ELSE 0 END as HasAttachment,
- CASE WHEN EXISTS (SELECT 1 FROM TotpCodes tc WHERE tc.ItemId = i.Id AND tc.IsDeleted = 0) THEN 1 ELSE 0 END as HasTotp,
- i.CreatedAt,
- i.UpdatedAt,
- i.ArchivedAt
- FROM Items i
- LEFT JOIN Logos l ON i.LogoId = l.Id
- WHERE i.Id = ? AND i.IsDeleted = 0
- """
-
- /// Get field values for multiple items.
+ /// Get field values for multiple items, matched on the whole item key.
/// - Parameter itemCount: Number of items (for placeholder generation)
- /// - Returns: Query with placeholders
+ /// - Returns: Query with one (?, ?) placeholder pair per item, bound as [manifestId, itemId, ...]
public static func getFieldValuesForItems(_ itemCount: Int) -> String {
- let placeholders = Array(repeating: "?", count: itemCount).joined(separator: ",")
+ let placeholders = Array(repeating: "(?, ?)", count: itemCount).joined(separator: ", ")
return """
SELECT
fv.ItemId,
+ fv.ManifestId,
fv.FieldKey,
fv.FieldDefinitionId,
fd.Label as CustomLabel,
@@ -80,193 +47,48 @@ public struct ItemQueries {
fv.Value,
fv.Weight as DisplayOrder
FROM FieldValues fv
- LEFT JOIN FieldDefinitions fd ON fv.FieldDefinitionId = fd.Id
- WHERE fv.ItemId IN (\(placeholders))
+ LEFT JOIN FieldDefinitions fd ON fd.ManifestId = fv.ManifestId AND fd.Id = fv.FieldDefinitionId
+ WHERE (fv.ManifestId, fv.ItemId) IN (VALUES \(placeholders))
AND fv.IsDeleted = 0
ORDER BY fv.ItemId, fv.Weight
"""
}
- /// Get field values for a single item.
- public static let getFieldValuesForItem = """
- SELECT
- fv.FieldKey,
- fv.FieldDefinitionId,
- fd.Label as CustomLabel,
- fd.FieldType as CustomFieldType,
- fd.IsHidden as CustomIsHidden,
- fd.EnableHistory as CustomEnableHistory,
- fv.Value,
- fv.Weight as DisplayOrder
- FROM FieldValues fv
- LEFT JOIN FieldDefinitions fd ON fv.FieldDefinitionId = fd.Id
- WHERE fv.ItemId = ? AND fv.IsDeleted = 0
- ORDER BY fv.Weight
- """
-
- /// Get all unique email addresses from field values.
- public static let getAllEmailAddresses = """
- SELECT DISTINCT fv.Value as Email
- FROM FieldValues fv
- INNER JOIN Items i ON fv.ItemId = i.Id
- WHERE fv.FieldKey = ?
- AND fv.Value IS NOT NULL
- AND fv.Value != ''
- AND fv.IsDeleted = 0
- AND i.IsDeleted = 0
- AND i.DeletedAt IS NULL
+ /// All live folders, for building folder paths one manifest's tree at a time.
+ public static let getAllFolders = """
+ SELECT Id, ManifestId, Name, ParentFolderId FROM Folders WHERE IsDeleted = 0
"""
- /// Get all recently deleted items (in trash).
- public static let getRecentlyDeleted = """
- SELECT DISTINCT
- i.Id,
- i.Name,
- i.ItemType,
- i.FolderId,
- f.Name as FolderPath,
- l.FileData as Logo,
- CASE WHEN EXISTS (SELECT 1 FROM Passkeys pk WHERE pk.ItemId = i.Id AND pk.IsDeleted = 0) THEN 1 ELSE 0 END as HasPasskey,
- CASE WHEN EXISTS (SELECT 1 FROM Attachments att WHERE att.ItemId = i.Id AND att.IsDeleted = 0) THEN 1 ELSE 0 END as HasAttachment,
- CASE WHEN EXISTS (SELECT 1 FROM TotpCodes tc WHERE tc.ItemId = i.Id AND tc.IsDeleted = 0) THEN 1 ELSE 0 END as HasTotp,
- i.CreatedAt,
- i.UpdatedAt,
- i.DeletedAt
- FROM Items i
- LEFT JOIN Logos l ON i.LogoId = l.Id
- LEFT JOIN Folders f ON i.FolderId = f.Id
- WHERE i.IsDeleted = 0 AND i.DeletedAt IS NOT NULL
- ORDER BY i.DeletedAt DESC
- """
-
- /// Count of recently deleted items.
- public static let countRecentlyDeleted = """
- SELECT COUNT(*) as count
- FROM Items
- WHERE IsDeleted = 0 AND DeletedAt IS NOT NULL
- """
-
- /// Insert a new item.
+ /// Insert a new item, stamped with the manifest of the folder it is placed in.
public static let insertItem = """
INSERT INTO Items (Id, Name, ItemType, LogoId, FolderId, CreatedAt, UpdatedAt, IsDeleted, ManifestId)
VALUES (?, ?, ?, ?, ?, ?, ?, ?, COALESCE((SELECT ManifestId FROM Folders WHERE Id = ?), ?))
"""
- /// Update an existing item.
- public static let updateItem = """
- UPDATE Items
- SET Name = ?,
- ItemType = ?,
- FolderId = ?,
- LogoId = COALESCE(?, LogoId),
- UpdatedAt = ?
- WHERE Id = ?
- """
-
- /// Move item to trash (set DeletedAt).
- public static let trashItem = """
- UPDATE Items
- SET DeletedAt = ?,
- UpdatedAt = ?
- WHERE Id = ? AND IsDeleted = 0
- """
-
- /// Restore item from trash (clear DeletedAt).
- public static let restoreItem = """
- UPDATE Items
- SET DeletedAt = NULL,
- UpdatedAt = ?
- WHERE Id = ? AND IsDeleted = 0 AND DeletedAt IS NOT NULL
- """
-
- /// Archive an item (set ArchivedAt).
- public static let archiveItem = """
- UPDATE Items
- SET ArchivedAt = ?,
- UpdatedAt = ?
- WHERE Id = ? AND IsDeleted = 0 AND ArchivedAt IS NULL
- """
-
- /// Unarchive an item (clear ArchivedAt).
- public static let unarchiveItem = """
- UPDATE Items
- SET ArchivedAt = NULL,
- UpdatedAt = ?
- WHERE Id = ? AND IsDeleted = 0 AND ArchivedAt IS NOT NULL
- """
-
- /// Convert item to tombstone for permanent deletion.
- public static let tombstoneItem = """
- UPDATE Items
- SET IsDeleted = 1,
- Name = NULL,
- LogoId = NULL,
- FolderId = NULL,
- ArchivedAt = NULL,
- UpdatedAt = ?
- WHERE Id = ?
+ /// Bump an item's UpdatedAt so a child-row change is picked up by sync.
+ public static let touchItem = """
+ UPDATE Items SET UpdatedAt = ? WHERE Id = ? AND ManifestId = ?
"""
}
/// SQL query constants for FieldValue operations.
public struct FieldValueQueries {
- /// Get existing field values for an item.
- public static let getExistingForItem = """
- SELECT Id, FieldKey, FieldDefinitionId, Value
- FROM FieldValues
- WHERE ItemId = ? AND IsDeleted = 0
- """
-
- /// Insert a new field value.
+ /// Insert a new field value, stamped with the manifest of the item it hangs off.
public static let insert = """
INSERT INTO FieldValues (Id, ItemId, FieldDefinitionId, FieldKey, Value, Weight, CreatedAt, UpdatedAt, IsDeleted, ManifestId)
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, COALESCE((SELECT ManifestId FROM Items WHERE Id = ?), ?))
"""
- /// Update an existing field value.
- public static let update = """
- UPDATE FieldValues
- SET Value = ?,
- Weight = ?,
- UpdatedAt = ?
- WHERE Id = ?
- """
-
- /// Soft delete a field value.
- public static let softDelete = """
- UPDATE FieldValues
- SET IsDeleted = 1,
- UpdatedAt = ?
- WHERE Id = ?
- """
-}
-
-/// SQL query constants for Tag operations.
-public struct TagQueries {
- /// Get tags for multiple items.
- /// - Parameter itemCount: Number of items (for placeholder generation)
- /// - Returns: Query with placeholders
- public static func getTagsForItems(_ itemCount: Int) -> String {
- let placeholders = Array(repeating: "?", count: itemCount).joined(separator: ",")
- return """
- SELECT it.ItemId, t.Id, t.Name, t.Color
- FROM ItemTags it
- INNER JOIN Tags t ON it.TagId = t.Id
- WHERE it.ItemId IN (\(placeholders))
- AND it.IsDeleted = 0
- AND t.IsDeleted = 0
- ORDER BY t.DisplayOrder
- """
+ /// The Weight a system field's values are written with: the field's DefaultDisplayOrder from
+ /// core/models `SystemFieldRegistry.ts`, which is what the TypeScript writers store.
+ public static func defaultWeight(forFieldKey fieldKey: String) -> Int {
+ switch fieldKey {
+ case "login.url":
+ return 5
+ case "login.username":
+ return 15
+ default:
+ return 0
+ }
}
-
- /// Get tags for a single item.
- public static let getTagsForItem = """
- SELECT t.Id, t.Name, t.Color
- FROM ItemTags it
- INNER JOIN Tags t ON it.TagId = t.Id
- WHERE it.ItemId = ?
- AND it.IsDeleted = 0
- AND t.IsDeleted = 0
- ORDER BY t.DisplayOrder
- """
}
diff --git a/apps/mobile-app/ios/VaultStoreKit/Database/Queries/ItemStatsQueries.swift b/apps/mobile-app/ios/VaultStoreKit/Database/Queries/ItemStatsQueries.swift
new file mode 100644
index 000000000..375839b19
--- /dev/null
+++ b/apps/mobile-app/ios/VaultStoreKit/Database/Queries/ItemStatsQueries.swift
@@ -0,0 +1,33 @@
+import Foundation
+
+/// SQL query constants for per-item usage statistics.
+public struct ItemStatsQueries {
+ /// Create the stats row for an item on its first recorded use, bound as [manifestId, itemId, now, now].
+ public static let insertRow = """
+ INSERT OR IGNORE INTO ItemStats (
+ ManifestId, Id, LastUsedAt, UseCount, LastAutofilledAt, AutofillCount,
+ LastCopiedAt, CopyCount, LastPasskeyAuthAt, PasskeyAuthCount, CreatedAt, UpdatedAt, IsDeleted
+ )
+ VALUES (?, ?, NULL, 0, NULL, 0, NULL, 0, NULL, 0, ?, ?, 0)
+ """
+
+ /// Record one use of an item, bumping the aggregate and the per-action pair. The column names come from
+ /// the closed set in `ItemUsageAction`, never from caller input. `IsDeleted` is cleared because a use
+ /// resurrects a row the pruner tombstoned.
+ /// - Parameters:
+ /// - lastColumn: The per-action timestamp column
+ /// - countColumn: The per-action counter column
+ /// - Returns: The UPDATE statement, bound as [now, now, now, manifestId, itemId]
+ public static func forAction(lastColumn: String, countColumn: String) -> String {
+ return """
+ UPDATE ItemStats
+ SET LastUsedAt = ?,
+ UseCount = UseCount + 1,
+ \(lastColumn) = ?,
+ \(countColumn) = \(countColumn) + 1,
+ UpdatedAt = ?,
+ IsDeleted = 0
+ WHERE ManifestId = ? AND Id = ?
+ """
+ }
+}
diff --git a/apps/mobile-app/ios/VaultStoreKit/Database/Queries/PasskeyQueries.swift b/apps/mobile-app/ios/VaultStoreKit/Database/Queries/PasskeyQueries.swift
index c45c4b777..a554f4821 100644
--- a/apps/mobile-app/ios/VaultStoreKit/Database/Queries/PasskeyQueries.swift
+++ b/apps/mobile-app/ios/VaultStoreKit/Database/Queries/PasskeyQueries.swift
@@ -1,41 +1,37 @@
import Foundation
/// SQL query constants for Passkey operations.
-/// Centralizes all passkey-related queries to avoid duplication.
public struct PasskeyQueries {
- /// Base SELECT for passkeys with common fields.
- public static let baseSelect = """
- SELECT
+ /// The passkey columns every SELECT projects.
+ private static let columns = """
p.Id,
p.ItemId,
+ p.ManifestId,
p.RpId,
p.UserHandle,
p.PublicKey,
p.PrivateKey,
p.PrfKey,
p.DisplayName,
+ p.AdditionalData,
p.CreatedAt,
p.UpdatedAt,
p.IsDeleted
+ """
+
+ /// Base SELECT for passkeys without item information.
+ public static let baseSelect = """
+ SELECT
+ \(columns)
FROM Passkeys p
"""
- /// Base SELECT for passkeys joined with Items to check parent item deletion status.
+ /// Base SELECT for passkeys joined with their item, which must be live (not deleted, not in trash).
public static let baseSelectWithItemCheck = """
SELECT
- p.Id,
- p.ItemId,
- p.RpId,
- p.UserHandle,
- p.PublicKey,
- p.PrivateKey,
- p.PrfKey,
- p.DisplayName,
- p.CreatedAt,
- p.UpdatedAt,
- p.IsDeleted
+ \(columns)
FROM Passkeys p
- INNER JOIN Items i ON p.ItemId = i.Id AND i.IsDeleted = 0 AND i.DeletedAt IS NULL
+ INNER JOIN Items i ON p.ItemId = i.Id AND i.ManifestId = p.ManifestId AND i.IsDeleted = 0 AND i.DeletedAt IS NULL
"""
/// Get a passkey by its ID (credential ID).
@@ -44,10 +40,10 @@ public struct PasskeyQueries {
WHERE p.Id = ? AND p.IsDeleted = 0
"""
- /// Get all passkeys for an item.
+ /// Get all passkeys for one item, bound as [itemId, manifestId].
public static let getByItemId = """
- \(baseSelectWithItemCheck)
- WHERE p.ItemId = ? AND p.IsDeleted = 0
+ \(baseSelect)
+ WHERE p.ItemId = ? AND p.ManifestId = ? AND p.IsDeleted = 0
ORDER BY p.CreatedAt DESC
"""
@@ -59,154 +55,154 @@ public struct PasskeyQueries {
"""
/// Get passkeys with item info for a specific rpId.
- /// Joins with Items and FieldValues to get display info.
public static let getWithItemInfoByRpId = """
SELECT
- p.Id,
- p.ItemId,
- p.RpId,
- p.UserHandle,
- p.PublicKey,
- p.PrivateKey,
- p.PrfKey,
- p.DisplayName,
- p.CreatedAt,
- p.UpdatedAt,
- p.IsDeleted,
+ \(columns),
i.Name as ServiceName,
- fv.Value as Username,
- fv_email.Value as Email
+ (SELECT fv.Value FROM FieldValues fv WHERE fv.ItemId = i.Id AND fv.ManifestId = i.ManifestId AND fv.FieldKey = 'login.username' AND fv.IsDeleted = 0 LIMIT 1) as Username,
+ (SELECT fv.Value FROM FieldValues fv WHERE fv.ItemId = i.Id AND fv.ManifestId = i.ManifestId AND fv.FieldKey = 'login.email' AND fv.IsDeleted = 0 LIMIT 1) as Email
FROM Passkeys p
- INNER JOIN Items i ON p.ItemId = i.Id
- LEFT JOIN FieldValues fv ON fv.ItemId = i.Id AND fv.FieldKey = 'login.username' AND fv.IsDeleted = 0
- LEFT JOIN FieldValues fv_email ON fv_email.ItemId = i.Id AND fv_email.FieldKey = 'login.email' AND fv_email.IsDeleted = 0
+ INNER JOIN Items i ON p.ItemId = i.Id AND i.ManifestId = p.ManifestId
WHERE p.RpId = ? AND p.IsDeleted = 0 AND i.IsDeleted = 0 AND i.DeletedAt IS NULL
ORDER BY p.CreatedAt DESC
"""
- /// Insert a new passkey.
+ /// Insert a new passkey, stamped with the manifest of the item it hangs off. Binds the item id twice:
+ /// once for the column, once for the manifest lookup, followed by the fallback manifest.
public static let insert = """
- INSERT INTO Passkeys (Id, ItemId, RpId, UserHandle, PublicKey, PrivateKey, PrfKey, DisplayName, CreatedAt, UpdatedAt, IsDeleted, ManifestId)
- VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, COALESCE((SELECT ManifestId FROM Items WHERE Id = ?), ?))
+ INSERT INTO Passkeys (Id, ItemId, ManifestId, RpId, UserHandle, PublicKey, PrivateKey, PrfKey, DisplayName, AdditionalData, CreatedAt, UpdatedAt, IsDeleted)
+ VALUES (?, ?, COALESCE((SELECT ManifestId FROM Items WHERE Id = ?), ?), ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
"""
- /// Soft delete a passkey.
+ /// Soft delete a passkey, bound as [now, passkeyId, manifestId].
public static let softDelete = """
UPDATE Passkeys
SET IsDeleted = 1,
UpdatedAt = ?
- WHERE Id = ?
+ WHERE Id = ? AND ManifestId = ?
"""
- /// Update passkey display name.
+ /// Update passkey display name, bound as [displayName, now, passkeyId, manifestId].
public static let updateDisplayName = """
UPDATE Passkeys
SET DisplayName = ?,
UpdatedAt = ?
- WHERE Id = ? AND IsDeleted = 0
+ WHERE Id = ? AND ManifestId = ? AND IsDeleted = 0
"""
/// Get Items that match an rpId but don't have a passkey yet.
- /// Used for finding existing credentials that could have a passkey added to them.
/// Note: The public API now uses getAllItemsWithoutPasskey + Rust credential matcher for consistent cross-platform matching.
/// This query is kept for potential fallback scenarios.
public static let getItemsWithoutPasskeyForRpId = """
- SELECT i.Id, i.Name, i.CreatedAt, i.UpdatedAt,
+ SELECT i.Id, i.ManifestId, i.Name, i.CreatedAt, i.UpdatedAt,
fv_url.Value as Url,
fv_username.Value as Username,
fv_email.Value as Email,
fv_password.Value as Password
FROM Items i
- INNER JOIN FieldValues fv_url ON fv_url.ItemId = i.Id
+ INNER JOIN FieldValues fv_url ON fv_url.ItemId = i.Id AND fv_url.ManifestId = i.ManifestId
AND fv_url.FieldKey = 'login.url'
AND fv_url.IsDeleted = 0
- LEFT JOIN FieldValues fv_username ON fv_username.ItemId = i.Id
+ LEFT JOIN FieldValues fv_username ON fv_username.ItemId = i.Id AND fv_username.ManifestId = i.ManifestId
AND fv_username.FieldKey = 'login.username'
AND fv_username.IsDeleted = 0
- LEFT JOIN FieldValues fv_email ON fv_email.ItemId = i.Id
+ LEFT JOIN FieldValues fv_email ON fv_email.ItemId = i.Id AND fv_email.ManifestId = i.ManifestId
AND fv_email.FieldKey = 'login.email'
AND fv_email.IsDeleted = 0
- LEFT JOIN FieldValues fv_password ON fv_password.ItemId = i.Id
+ LEFT JOIN FieldValues fv_password ON fv_password.ItemId = i.Id AND fv_password.ManifestId = i.ManifestId
AND fv_password.FieldKey = 'login.password'
AND fv_password.IsDeleted = 0
WHERE i.IsDeleted = 0
AND i.DeletedAt IS NULL
+ AND i.ArchivedAt IS NULL
AND i.ItemType = 'Login'
AND (LOWER(fv_url.Value) LIKE ? OR LOWER(fv_url.Value) LIKE ?)
AND NOT EXISTS (
SELECT 1 FROM Passkeys p
- WHERE p.ItemId = i.Id AND p.IsDeleted = 0
+ WHERE p.ItemId = i.Id AND p.ManifestId = i.ManifestId AND p.IsDeleted = 0
)
ORDER BY i.UpdatedAt DESC
"""
- /// Get ALL Login items that don't have a passkey yet (no URL filtering).
+ /// Get ALL active Login items that don't have a passkey yet (no URL filtering).
/// Used with Rust credential matcher for intelligent filtering.
/// Returns items with their URLs aggregated using GROUP_CONCAT for multi-URL support.
public static let getAllItemsWithoutPasskey = """
- SELECT i.Id, i.Name, i.CreatedAt, i.UpdatedAt,
+ SELECT i.Id, i.ManifestId, i.Name, i.CreatedAt, i.UpdatedAt,
GROUP_CONCAT(DISTINCT fv_url.Value) as Urls,
fv_username.Value as Username,
fv_email.Value as Email,
fv_password.Value as Password
FROM Items i
- LEFT JOIN FieldValues fv_url ON fv_url.ItemId = i.Id
+ LEFT JOIN FieldValues fv_url ON fv_url.ItemId = i.Id AND fv_url.ManifestId = i.ManifestId
AND fv_url.FieldKey = 'login.url'
AND fv_url.IsDeleted = 0
- LEFT JOIN FieldValues fv_username ON fv_username.ItemId = i.Id
+ LEFT JOIN FieldValues fv_username ON fv_username.ItemId = i.Id AND fv_username.ManifestId = i.ManifestId
AND fv_username.FieldKey = 'login.username'
AND fv_username.IsDeleted = 0
- LEFT JOIN FieldValues fv_email ON fv_email.ItemId = i.Id
+ LEFT JOIN FieldValues fv_email ON fv_email.ItemId = i.Id AND fv_email.ManifestId = i.ManifestId
AND fv_email.FieldKey = 'login.email'
AND fv_email.IsDeleted = 0
- LEFT JOIN FieldValues fv_password ON fv_password.ItemId = i.Id
+ LEFT JOIN FieldValues fv_password ON fv_password.ItemId = i.Id AND fv_password.ManifestId = i.ManifestId
AND fv_password.FieldKey = 'login.password'
AND fv_password.IsDeleted = 0
WHERE i.IsDeleted = 0
AND i.DeletedAt IS NULL
+ AND i.ArchivedAt IS NULL
AND i.ItemType = 'Login'
AND NOT EXISTS (
SELECT 1 FROM Passkeys p
- WHERE p.ItemId = i.Id AND p.IsDeleted = 0
+ WHERE p.ItemId = i.Id AND p.ManifestId = i.ManifestId AND p.IsDeleted = 0
)
- GROUP BY i.Id
+ GROUP BY i.ManifestId, i.Id
ORDER BY i.UpdatedAt DESC
"""
}
/// SQL query constants for Logo operations used during passkey/item creation.
+/// Mirrors core/client `LogoQueries.ts`.
public struct LogoQueries {
- /// Insert a new logo.
- public static let insert = """
- INSERT INTO Logos (Id, Kind, Source, ManifestId, FileData, MimeType, FetchedAt, CreatedAt, UpdatedAt, IsDeleted)
- VALUES (?, 'favicon', ?, ?, ?, ?, ?, ?, ?, ?)
+ /// The logo of a given kind and key within one manifest, bound as [manifestId, kind, source].
+ public static let getIdForKey = """
+ SELECT Id FROM Logos
+ WHERE ManifestId = ? AND Kind = ? AND Source = ? AND IsDeleted = 0
+ LIMIT 1
"""
- /// Update logo file data.
- public static let updateFileData = """
- UPDATE Logos
- SET FileData = ?,
- UpdatedAt = ?
- WHERE Id = ?
+ /// The best row to copy from when a manifest needs a logo it does not have but the vault does, bound as [kind, source].
+ public static let getBestForKey = """
+ SELECT FileData, MimeType, Name FROM Logos
+ WHERE Kind = ? AND Source = ? AND IsDeleted = 0
+ ORDER BY (FileData IS NOT NULL AND LENGTH(FileData) > 0) DESC, UpdatedAt DESC
+ LIMIT 1
"""
- /// Get logo ID by source.
- public static let getBySource = """
- SELECT Id, IsDeleted FROM Logos WHERE Source = ? LIMIT 1
+ /// The kind and key of an existing logo.
+ public static let getById = """
+ SELECT Id, Kind, Source, Name FROM Logos
+ WHERE Id = ? AND IsDeleted = 0
+ LIMIT 1
"""
- /// Restore a soft-deleted logo.
- public static let restore = """
- UPDATE Logos SET IsDeleted = 0, UpdatedAt = ? WHERE Id = ?
+ /// Insert or update a logo, bound as [id, kind, source, manifestId, fileData, mimeType, name, now, now].
+ public static let upsert = """
+ INSERT INTO Logos (Id, Kind, Source, ManifestId, FileData, MimeType, Name, CreatedAt, UpdatedAt, IsDeleted)
+ VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, 0)
+ ON CONFLICT(ManifestId, Id) DO UPDATE SET
+ FileData = excluded.FileData,
+ MimeType = excluded.MimeType,
+ Name = COALESCE(excluded.Name, Logos.Name),
+ UpdatedAt = excluded.UpdatedAt,
+ IsDeleted = 0
"""
- /// Get logo ID from an item.
+ /// Get the logo ID of one item, bound as [itemId, manifestId].
public static let getLogoIdFromItem = """
- SELECT LogoId FROM Items WHERE Id = ?
+ SELECT LogoId FROM Items WHERE Id = ? AND ManifestId = ?
"""
- /// Update item logo ID.
+ /// Point an item at a logo, bound as [logoId, now, itemId, manifestId].
public static let updateItemLogoId = """
- UPDATE Items SET LogoId = ?, UpdatedAt = ? WHERE Id = ?
+ UPDATE Items SET LogoId = ?, UpdatedAt = ? WHERE Id = ? AND ManifestId = ?
"""
}
diff --git a/apps/mobile-app/ios/VaultStoreKit/Database/Repositories/ItemRepository.swift b/apps/mobile-app/ios/VaultStoreKit/Database/Repositories/ItemRepository.swift
index cc41224f8..ab85a55b5 100644
--- a/apps/mobile-app/ios/VaultStoreKit/Database/Repositories/ItemRepository.swift
+++ b/apps/mobile-app/ios/VaultStoreKit/Database/Repositories/ItemRepository.swift
@@ -1,474 +1,85 @@
import Foundation
import VaultModels
-/// Repository for Item CRUD operations.
-/// Handles fetching, creating, updating, and deleting items with their related data.
+/// Repository for reading items and appending field values.
public class ItemRepository: BaseRepository {
// MARK: - Read Operations
- /// Build folder paths for all folders.
- /// Returns a map of FolderId -> path array.
- /// - Returns: Dictionary of folder ID to folder path array
- private func buildFolderPaths() throws -> [UUID: [String]] {
- var folderPathMap: [UUID: [String]] = [:]
+ /// Build folder paths for all folders, keyed by scoped folder key (see `scopedKey`).
+ /// The tree is walked per manifest: a parent link only ever resolves inside its own namespace.
+ /// - Returns: Dictionary of scoped folder key to folder path array
+ private func buildFolderPaths() throws -> [String: [String]] {
+ var folderPathMap: [String: [String]] = [:]
+ let folderResults: [[String: Any]]
do {
- // Get all folders from database
- let folderQuery = "SELECT Id, Name, ParentFolderId FROM Folders WHERE IsDeleted = 0"
- let folderResults = try client.executeQuery(folderQuery, params: [])
-
- if folderResults.isEmpty {
- return folderPathMap
- }
-
- // Convert to FolderUtils.Folder format
- let folders = folderResults.compactMap { row -> FolderUtils.Folder? in
- guard let idString = row["Id"] as? String,
- let id = UUID(uuidString: idString),
- let name = row["Name"] as? String else {
- return nil
- }
-
- let parentFolderId: UUID? = {
- guard let parentIdString = row["ParentFolderId"] as? String else {
- return nil
- }
- return UUID(uuidString: parentIdString)
- }()
+ folderResults = try client.executeQuery(ItemQueries.getAllFolders, params: [])
+ } catch {
+ // Folders table may not exist in older vault versions
+ return folderPathMap
+ }
- return FolderUtils.Folder(id: id, name: name, parentFolderId: parentFolderId)
+ var foldersByManifest: [String: [FolderUtils.Folder]] = [:]
+ for row in folderResults {
+ guard let manifestId = row["ManifestId"] as? String, let idString = row["Id"] as? String, let id = UUID(uuidString: idString), let name = row["Name"] as? String else {
+ continue
}
+ let parentFolderId = (row["ParentFolderId"] as? String).flatMap { UUID(uuidString: $0) }
+ foldersByManifest[manifestId, default: []].append(FolderUtils.Folder(id: id, name: name, parentFolderId: parentFolderId))
+ }
- // Use shared utility to build paths for all folders
+ for (manifestId, folders) in foldersByManifest {
for folder in folders {
let path = FolderUtils.getFolderPath(folderId: folder.id, folders: folders)
if !path.isEmpty {
- folderPathMap[folder.id] = path
+ folderPathMap[scopedKey(manifestId: manifestId, id: folder.id.uuidString.lowercased())] = path
}
}
-
- return folderPathMap
- } catch {
- // Folders table may not exist in older vault versions
- return folderPathMap
}
+
+ return folderPathMap
}
- /// Fetch all active items (not deleted, not in trash) with their fields.
+ /// Fetch all active items (not deleted, not in trash, not archived) with their fields.
/// - Returns: Array of Item objects
public func getAll() throws -> [Item] {
- // 1. Fetch all item rows
- let itemResults = try client.executeQuery(ItemQueries.getAllActive, params: [])
- let itemRows = itemResults.compactMap { ItemRow(from: $0) }
-
+ let itemRows = try client.executeQuery(ItemQueries.getAllActive, params: []).compactMap { ItemRow(from: $0) }
if itemRows.isEmpty {
return []
}
- // 2. Fetch field values for all items
- let itemIds = itemRows.map { $0.id }
- let fieldQuery = ItemQueries.getFieldValuesForItems(itemIds.count)
- let fieldResults = try client.executeQuery(fieldQuery, params: itemIds.map { $0 as SqliteBindValue })
- let fieldRows = fieldResults.compactMap { FieldRow(from: $0) }
-
- // 3. Process fields into a dictionary by ItemId
+ // Fields are matched on the whole (ManifestId, Id) key, bound as one pair per item.
+ let keyParams = itemRows.flatMap { [$0.manifestId as SqliteBindValue, $0.id as SqliteBindValue] }
+ let fieldRows = try client.executeQuery(ItemQueries.getFieldValuesForItems(itemRows.count), params: keyParams).compactMap { FieldRow(from: $0) }
let fieldsByItem = FieldMapper.processFieldRows(fieldRows)
-
- // 4. Build folder paths
let folderPaths = try buildFolderPaths()
- // 5. Map rows to Item objects
- return ItemMapper.mapRows(itemRows, fieldsByItem: fieldsByItem, folderPathsByFolderId: folderPaths)
- }
-
- /// Fetch a single item by ID with its fields.
- /// - Parameter itemId: The ID of the item to fetch
- /// - Returns: Item object or nil if not found
- public func getById(_ itemId: String) throws -> Item? {
- // 1. Fetch item row
- let itemResults = try client.executeQuery(ItemQueries.getById, params: [itemId])
- guard let itemRow = itemResults.first.flatMap({ ItemRow(from: $0) }) else {
- return nil
- }
-
- // 2. Fetch field values
- let fieldResults = try client.executeQuery(ItemQueries.getFieldValuesForItem, params: [itemId])
- let fieldRows = fieldResults.compactMap { SingleItemFieldRow(from: $0) }
- let fields = FieldMapper.processFieldRowsForSingleItem(fieldRows)
-
- // 3. Build folder paths
- let folderPaths = try buildFolderPaths()
-
- // 4. Get folder path if item is in a folder
- let folderPath = itemRow.folderId
- .flatMap { UUID(uuidString: $0) }
- .flatMap { folderPaths[$0] }
-
- // 5. Map to Item object
- return ItemMapper.mapRow(itemRow, fields: fields, folderPath: folderPath)
- }
-
- /// Fetch all unique email addresses from field values.
- /// - Returns: Array of email addresses
- public func getAllEmailAddresses() throws -> [String] {
- let results = try client.executeQuery(
- ItemQueries.getAllEmailAddresses,
- params: [FieldKey.loginEmail]
- )
- return results.compactMap { $0["Email"] as? String }
- }
-
- /// Get recently deleted items (in trash).
- /// - Returns: Array of items
- public func getRecentlyDeleted() throws -> [Item] {
- let itemResults = try client.executeQuery(ItemQueries.getRecentlyDeleted, params: [])
- let itemRows = itemResults.compactMap { ItemRow(from: $0) }
-
- if itemRows.isEmpty {
- return []
- }
-
- // Fetch fields for deleted items
- let itemIds = itemRows.map { $0.id }
- let fieldQuery = ItemQueries.getFieldValuesForItems(itemIds.count)
- let fieldResults = try client.executeQuery(fieldQuery, params: itemIds.map { $0 as SqliteBindValue })
- let fieldRows = fieldResults.compactMap { FieldRow(from: $0) }
- let fieldsByItem = FieldMapper.processFieldRows(fieldRows)
-
- // Build folder paths
- let folderPaths = try buildFolderPaths()
-
- return itemRows.compactMap { row in
- let folderPath = row.folderId
- .flatMap { UUID(uuidString: $0) }
- .flatMap { folderPaths[$0] }
- return ItemMapper.mapDeletedItemRow(row, fields: fieldsByItem[row.id] ?? [], folderPath: folderPath)
- }
- }
-
- /// Get count of items in trash.
- /// - Returns: Number of items in trash
- public func getRecentlyDeletedCount() throws -> Int {
- let results = try client.executeQuery(ItemQueries.countRecentlyDeleted, params: [])
- return Int(results.first?["count"] as? Int64 ?? 0)
- }
-
- /// Get archived items.
- /// - Returns: Array of items
- public func getArchived() throws -> [Item] {
- let itemResults = try client.executeQuery(ItemQueries.getArchived, params: [])
- let itemRows = itemResults.compactMap { ItemRow(from: $0) }
-
- if itemRows.isEmpty {
- return []
- }
-
- // Fetch fields for archived items
- let itemIds = itemRows.map { $0.id }
- let fieldQuery = ItemQueries.getFieldValuesForItems(itemIds.count)
- let fieldResults = try client.executeQuery(fieldQuery, params: itemIds.map { $0 as SqliteBindValue })
- let fieldRows = fieldResults.compactMap { FieldRow(from: $0) }
- let fieldsByItem = FieldMapper.processFieldRows(fieldRows)
-
- // Build folder paths
- let folderPaths = try buildFolderPaths()
-
- return itemRows.compactMap { row in
- let folderPath = row.folderId
- .flatMap { UUID(uuidString: $0) }
- .flatMap { folderPaths[$0] }
- return ItemMapper.mapRow(row, fields: fieldsByItem[row.id] ?? [], folderPath: folderPath)
- }
- }
-
- /// Get count of archived items.
- /// - Returns: Number of archived items
- public func getArchivedCount() throws -> Int {
- let results = try client.executeQuery(ItemQueries.countArchived, params: [])
- return Int(results.first?["count"] as? Int64 ?? 0)
+ return ItemMapper.mapRows(itemRows, fieldsByItem: fieldsByItem, folderPathsByFolderKey: folderPaths)
}
// MARK: - Write Operations
- /// Move an item to trash (set DeletedAt timestamp).
- /// - Parameter itemId: The ID of the item to trash
- /// - Returns: Number of rows affected
- @discardableResult
- public func trash(_ itemId: String) throws -> Int {
- let now = self.now()
- return try withTransaction {
- try client.executeUpdate(ItemQueries.trashItem, params: [now, now, itemId])
- }
- }
-
- /// Restore an item from trash (clear DeletedAt).
- /// - Parameter itemId: The ID of the item to restore
- /// - Returns: Number of rows affected
- @discardableResult
- public func restore(_ itemId: String) throws -> Int {
- let now = self.now()
- return try withTransaction {
- try client.executeUpdate(ItemQueries.restoreItem, params: [now, itemId])
- }
- }
-
- /// Archive an item: it disappears from the main list and from autofill, but keeps all of its
- /// data and its email aliases, and is never auto-pruned.
- /// - Parameter itemId: The ID of the item to archive
- /// - Returns: Number of rows affected
- @discardableResult
- public func archive(_ itemId: String) throws -> Int {
- let now = self.now()
- return try withTransaction {
- try client.executeUpdate(ItemQueries.archiveItem, params: [now, now, itemId])
- }
- }
-
- /// Unarchive an item, returning it to the main list and to autofill.
- /// - Parameter itemId: The ID of the item to unarchive
- /// - Returns: Number of rows affected
- @discardableResult
- public func unarchive(_ itemId: String) throws -> Int {
- let now = self.now()
- return try withTransaction {
- try client.executeUpdate(ItemQueries.unarchiveItem, params: [now, itemId])
- }
- }
-
- /// Permanently delete an item (tombstone).
- /// Converts item to tombstone and soft deletes all related data.
- /// - Parameter itemId: The ID of the item to permanently delete
- /// - Returns: Number of rows affected
- @discardableResult
- public func permanentlyDelete(_ itemId: String) throws -> Int {
- return try withTransaction {
- let now = self.now()
-
- // Soft delete related FieldValues
- try softDeleteByForeignKey(table: "FieldValues", foreignKey: "ItemId", foreignKeyValue: itemId)
-
- // Soft delete related data
- try softDeleteByForeignKey(table: "TotpCodes", foreignKey: "ItemId", foreignKeyValue: itemId)
-
- // Soft delete attachments AND zero their blob bytes so storage is reclaimed
- // immediately while the row remains as a tombstone for LWW sync.
- try client.executeUpdate(
- "UPDATE Attachments SET IsDeleted = 1, Blob = NULL, UpdatedAt = ? WHERE ItemId = ? AND IsDeleted = 0",
- params: [now, itemId]
- )
-
- try softDeleteByForeignKey(table: "Passkeys", foreignKey: "ItemId", foreignKeyValue: itemId)
-
- if try tableExists("ItemTags") {
- try softDeleteByForeignKey(table: "ItemTags", foreignKey: "ItemId", foreignKeyValue: itemId)
- }
- if try tableExists("FieldHistories") {
- try softDeleteByForeignKey(table: "FieldHistories", foreignKey: "ItemId", foreignKeyValue: itemId)
- }
-
- // Convert item to tombstone
- return try client.executeUpdate(ItemQueries.tombstoneItem, params: [now, itemId])
- }
- }
-
- /// Create a new item with its fields.
- /// - Parameter item: The item to create
- /// - Returns: The ID of the created item
- @discardableResult
- public func create(_ item: Item) throws -> String {
- return try withTransaction {
- let now = self.now()
- let itemId = item.id.uuidString.lowercased()
-
- // 1. Insert Item
- try client.executeUpdate(ItemQueries.insertItem, params: [
- itemId,
- item.name as SqliteBindValue,
- item.itemType,
- nil, // LogoId - handled separately if needed
- item.folderId?.uuidString.lowercased() as SqliteBindValue,
- now,
- now,
- 0,
- item.folderId?.uuidString.lowercased() as SqliteBindValue,
- activeManifestId()
- ])
-
- // 2. Insert FieldValues
- try insertFieldValues(itemId: itemId, fields: item.fields, now: now)
-
- return itemId
- }
- }
-
- /// Update an existing item with its fields.
- /// - Parameter item: The item to update
- /// - Returns: Number of rows affected
- @discardableResult
- public func update(_ item: Item) throws -> Int {
- return try withTransaction {
- let now = self.now()
- let itemId = item.id.uuidString.lowercased()
-
- // 1. Update Item
- try client.executeUpdate(ItemQueries.updateItem, params: [
- item.name as SqliteBindValue,
- item.itemType,
- item.folderId?.uuidString.lowercased() as SqliteBindValue,
- nil, // LogoId update handled separately if needed
- now,
- itemId
- ])
-
- // 2. Update FieldValues using preserve-and-track strategy
- try updateFieldValues(itemId: itemId, fields: item.fields, now: now)
-
- return 1
- }
- }
-
- /// Append a single value to a multi-value field on an existing item without
- /// touching other field rows.
+ /// 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)
+ /// - itemId: The id of the item to append the value to (lowercase 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
+ /// - manifestId: The manifest the item belongs to, when the caller knows it
+ /// - Returns: The number of rows affected by the parent Item's UpdatedAt bump, 0 when no such item exists
@discardableResult
- public func appendFieldValue(
- itemId: String,
- fieldKey: String,
- value: String
- ) throws -> Int {
+ public func appendFieldValue(itemId: String, fieldKey: String, value: String, manifestId: String? = nil) 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,
- itemId,
- activeManifestId()
- ])
-
- // 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.
- private func insertFieldValues(itemId: String, fields: [ItemField], now: String) throws {
- for (index, field) in fields.enumerated() {
- if field.value.isEmpty { continue }
-
- try client.executeUpdate(FieldValueQueries.insert, params: [
- generateId(),
- itemId,
- field.isCustomField ? field.fieldKey : nil, // FieldDefinitionId for custom
- field.isCustomField ? nil : field.fieldKey, // FieldKey for system
- field.value,
- index * 100, // Weight for ordering
- now,
- now,
- 0,
- itemId,
- activeManifestId()
- ])
- }
- }
-
- /// Update field values using preserve-and-track strategy.
- /// Preserves existing field value IDs when possible for stable merge behavior.
- private func updateFieldValues(itemId: String, fields: [ItemField], now: String) throws {
- // 1. Get existing field values
- let existingResults = try client.executeQuery(FieldValueQueries.getExistingForItem, params: [itemId])
-
- struct ExistingField {
- let id: String
- let fieldKey: String?
- let fieldDefinitionId: String?
- let value: String
- }
-
- let existingFields = existingResults.compactMap { row -> ExistingField? in
- guard let id = row["Id"] as? String else { return nil }
- return ExistingField(
- id: id,
- fieldKey: row["FieldKey"] as? String,
- fieldDefinitionId: row["FieldDefinitionId"] as? String,
- value: row["Value"] as? String ?? ""
- )
- }
-
- // 2. Build lookup by composite key (FieldKey or FieldDefinitionId)
- var existingByKey: [String: [ExistingField]] = [:]
- for existing in existingFields {
- let key = existing.fieldKey ?? existing.fieldDefinitionId ?? ""
- if existingByKey[key] == nil {
- existingByKey[key] = []
+ guard let scope = try manifestId ?? resolveRowManifestId(table: "Items", id: itemId) else {
+ return 0
}
- existingByKey[key]!.append(existing)
- }
- // 3. Track which existing IDs we've processed
- var processedIds = Set<String>()
-
- // 4. Process each field
- for (index, field) in fields.enumerated() {
- if field.value.isEmpty { continue }
-
- let existingForKey = existingByKey[field.fieldKey] ?? []
- let existingEntry = existingForKey.first
-
- if let existing = existingEntry {
- // Update existing if value changed
- processedIds.insert(existing.id)
- if existing.value != field.value {
- try client.executeUpdate(FieldValueQueries.update, params: [
- field.value,
- index * 100,
- now,
- existing.id
- ])
- }
- } else {
- // Insert new field value
- try client.executeUpdate(FieldValueQueries.insert, params: [
- generateId(),
- itemId,
- field.isCustomField ? field.fieldKey : nil,
- field.isCustomField ? nil : field.fieldKey,
- field.value,
- index * 100,
- now,
- now,
- 0,
- itemId,
- activeManifestId()
- ])
- }
- }
+ let now = self.now()
+ let weight = FieldValueQueries.defaultWeight(forFieldKey: fieldKey)
+ try client.executeUpdate(FieldValueQueries.insert, params: [generateId(), itemId, nil, fieldKey, value, weight, now, now, 0, itemId, scope])
- // 5. Soft delete removed fields
- for existing in existingFields {
- if !processedIds.contains(existing.id) {
- try client.executeUpdate(FieldValueQueries.softDelete, params: [now, existing.id])
- }
+ // Bump the parent Item's UpdatedAt so the change is picked up by the sync layer.
+ return try client.executeUpdate(ItemQueries.touchItem, params: [now, itemId, scope])
}
}
}
diff --git a/apps/mobile-app/ios/VaultStoreKit/Database/Repositories/ItemStatsRepository.swift b/apps/mobile-app/ios/VaultStoreKit/Database/Repositories/ItemStatsRepository.swift
new file mode 100644
index 000000000..6aace52f1
--- /dev/null
+++ b/apps/mobile-app/ios/VaultStoreKit/Database/Repositories/ItemStatsRepository.swift
@@ -0,0 +1,48 @@
+import Foundation
+
+/// The actions whose use of an item is recorded. Each maps to its own timestamp + counter pair alongside the
+/// aggregate `LastUsedAt` / `UseCount`.
+public enum ItemUsageAction {
+ /// A credential filled into a form.
+ case autofill
+ /// A value copied to the clipboard.
+ case copy
+ /// A passkey assertion.
+ case passkey
+
+ /// The column pair this action bumps. Closed set: nothing here is ever built from caller input.
+ internal var columns: (last: String, count: String) {
+ switch self {
+ case .autofill:
+ return ("LastAutofilledAt", "AutofillCount")
+ case .copy:
+ return ("LastCopiedAt", "CopyCount")
+ case .passkey:
+ return ("LastPasskeyAuthAt", "PasskeyAuthCount")
+ }
+ }
+}
+
+/// Repository for per-item usage statistics.
+public class ItemStatsRepository: BaseRepository {
+ /// Record one use of an item. Runs in its own transaction so the vault is persisted and marked dirty.
+ /// - Parameters:
+ /// - itemId: The item that was used
+ /// - manifestId: The manifest the item belongs to, when the caller knows it
+ /// - action: What the user did with it
+ /// - Returns: True when a use was recorded, false when no such item exists
+ @discardableResult
+ public func recordUsage(itemId: String, manifestId: String? = nil, action: ItemUsageAction) throws -> Bool {
+ return try withTransaction {
+ guard let scope = try manifestId ?? resolveRowManifestId(table: "Items", id: itemId) else {
+ return false
+ }
+
+ let now = self.now()
+ let columns = action.columns
+ try client.executeUpdate(ItemStatsQueries.insertRow, params: [scope, itemId, now, now])
+ try client.executeUpdate(ItemStatsQueries.forAction(lastColumn: columns.last, countColumn: columns.count), params: [now, now, now, scope, itemId])
+ return true
+ }
+ }
+}
diff --git a/apps/mobile-app/ios/VaultStoreKit/Database/Repositories/PasskeyRepository.swift b/apps/mobile-app/ios/VaultStoreKit/Database/Repositories/PasskeyRepository.swift
index d2b495e26..976920681 100644
--- a/apps/mobile-app/ios/VaultStoreKit/Database/Repositories/PasskeyRepository.swift
+++ b/apps/mobile-app/ios/VaultStoreKit/Database/Repositories/PasskeyRepository.swift
@@ -21,12 +21,16 @@ public class PasskeyRepository: BaseRepository {
}
/// Get all passkeys for an item.
- /// - Parameter itemId: The item ID (UUID string)
+ /// - Parameters:
+ /// - itemId: The item ID (UUID string)
+ /// - manifestId: The manifest the item belongs to, when the caller knows it
/// - Returns: Array of Passkey objects
- public func getByItemId(_ itemId: String) throws -> [Passkey] {
- let results = try client.executeQuery(PasskeyQueries.getByItemId, params: [itemId])
- let rows = results.compactMap { PasskeyRow(from: $0) }
- return PasskeyMapper.mapRows(rows)
+ public func getByItemId(_ itemId: String, manifestId: String? = nil) throws -> [Passkey] {
+ guard let scope = try manifestId ?? resolveRowManifestId(table: "Items", id: itemId) else {
+ return []
+ }
+ let results = try client.executeQuery(PasskeyQueries.getByItemId, params: [itemId, scope])
+ return PasskeyMapper.mapRows(results.compactMap { PasskeyRow(from: $0) })
}
/// Get all passkeys for a relying party (rpId).
@@ -34,8 +38,7 @@ public class PasskeyRepository: BaseRepository {
/// - Returns: Array of Passkey objects
public func getByRpId(_ rpId: String) throws -> [Passkey] {
let results = try client.executeQuery(PasskeyQueries.getByRpId, params: [rpId])
- let rows = results.compactMap { PasskeyRow(from: $0) }
- return PasskeyMapper.mapRows(rows)
+ return PasskeyMapper.mapRows(results.compactMap { PasskeyRow(from: $0) })
}
/// Get passkeys with item info for a specific rpId.
@@ -74,42 +77,13 @@ public class PasskeyRepository: BaseRepository {
let results = try client.executeQuery(PasskeyQueries.getItemsWithoutPasskeyForRpId, params: [urlPattern1, urlPattern2])
- var items: [ItemWithCredentialInfoData] = []
-
- for row in results {
- guard let idString = row["Id"] as? String,
- let itemId = UUID(uuidString: idString) else {
- continue
- }
-
- let serviceName = row["Name"] as? String
- let url = row["Url"] as? String
- let itemUsername = row["Username"] as? String
- let itemEmail = row["Email"] as? String
- let password = row["Password"] as? String
- let hasPassword = password != nil && !password!.isEmpty
-
- // Filter by username if provided
- if let userName = userName, itemUsername != userName {
- continue
+ return results.compactMap { row -> ItemWithCredentialInfoData? in
+ let item = mapItemWithCredentialInfo(row, urls: (row["Url"] as? String).map { [$0] } ?? [])
+ if let userName = userName, item?.username != userName {
+ return nil
}
-
- let createdAt = DateHelpers.parseDateString(row["CreatedAt"] as? String ?? "") ?? Date.distantPast
- let updatedAt = DateHelpers.parseDateString(row["UpdatedAt"] as? String ?? "") ?? Date.distantPast
-
- items.append(ItemWithCredentialInfoData(
- itemId: itemId,
- serviceName: serviceName,
- urls: url.map { [$0] } ?? [],
- username: itemUsername,
- email: itemEmail,
- hasPassword: hasPassword,
- createdAt: createdAt,
- updatedAt: updatedAt
- ))
+ return item
}
-
- return items
}
/// Get ALL Login items that don't have a passkey yet (no URL filtering).
@@ -118,88 +92,55 @@ public class PasskeyRepository: BaseRepository {
public func getAllItemsWithoutPasskey() throws -> [ItemWithCredentialInfoData] {
let results = try client.executeQuery(PasskeyQueries.getAllItemsWithoutPasskey, params: [])
- var items: [ItemWithCredentialInfoData] = []
-
- for row in results {
- guard let idString = row["Id"] as? String,
- let itemId = UUID(uuidString: idString) else {
- continue
- }
+ return results.compactMap { row -> ItemWithCredentialInfoData? in
+ let urls = (row["Urls"] as? String)?.components(separatedBy: ",").filter { !$0.isEmpty } ?? []
+ return mapItemWithCredentialInfo(row, urls: urls)
+ }
+ }
- let serviceName = row["Name"] as? String
- let urlsString = row["Urls"] as? String
- let urls = urlsString?.components(separatedBy: ",").filter { !$0.isEmpty } ?? []
- let itemUsername = row["Username"] as? String
- let itemEmail = row["Email"] as? String
- let password = row["Password"] as? String
- let hasPassword = password != nil && !password!.isEmpty
-
- let createdAt = DateHelpers.parseDateString(row["CreatedAt"] as? String ?? "") ?? Date.distantPast
- let updatedAt = DateHelpers.parseDateString(row["UpdatedAt"] as? String ?? "") ?? Date.distantPast
-
- items.append(ItemWithCredentialInfoData(
- itemId: itemId,
- serviceName: serviceName,
- urls: urls,
- username: itemUsername,
- email: itemEmail,
- hasPassword: hasPassword,
- createdAt: createdAt,
- updatedAt: updatedAt
- ))
+ /// Map one row of the without-passkey queries.
+ private func mapItemWithCredentialInfo(_ row: [String: Any], urls: [String]) -> ItemWithCredentialInfoData? {
+ guard let idString = row["Id"] as? String, let itemId = UUID(uuidString: idString) else {
+ return nil
}
- return items
+ let password = row["Password"] as? String
+ return ItemWithCredentialInfoData(
+ itemId: itemId,
+ serviceName: row["Name"] as? String,
+ urls: urls,
+ username: row["Username"] as? String,
+ email: row["Email"] as? String,
+ hasPassword: !(password ?? "").isEmpty,
+ createdAt: DateHelpers.parseDateString(row["CreatedAt"] as? String ?? "") ?? Date.distantPast,
+ updatedAt: DateHelpers.parseDateString(row["UpdatedAt"] as? String ?? "") ?? Date.distantPast,
+ manifestId: row["ManifestId"] as? String
+ )
}
// MARK: - Write Operations
- /// Create a new passkey.
+ /// Create a new passkey. The manifest is read from the item the passkey hangs off.
/// - Parameter passkey: The passkey to create
@discardableResult
public func create(_ passkey: Passkey) throws -> String {
return try withTransaction {
- let passkeyId = passkey.id.uuidString.lowercased()
- let now = self.now()
-
- // Convert keys to string for storage
- guard let publicKeyString = String(data: passkey.publicKey, encoding: .utf8),
- let privateKeyString = String(data: passkey.privateKey, encoding: .utf8) else {
- throw PasskeyRepositoryError.invalidKeyData
- }
-
- // Convert blob data to base64 with prefix for VaultStore+Query processing
- let userHandleParam: SqliteBindValue = passkey.userHandle.map { "av-base64-to-blob:\($0.base64EncodedString())" }
- let prfKeyParam: SqliteBindValue = passkey.prfKey.map { "av-base64-to-blob:\($0.base64EncodedString())" }
-
- try client.executeUpdate(PasskeyQueries.insert, params: [
- passkeyId,
- passkey.parentItemId.uuidString.lowercased(),
- passkey.rpId,
- userHandleParam,
- publicKeyString,
- privateKeyString,
- prfKeyParam,
- passkey.displayName,
- now,
- now,
- 0,
- passkey.parentItemId.uuidString.lowercased(),
- activeManifestId()
- ])
-
- return passkeyId
+ try insertPasskey(passkey, itemId: passkey.parentItemId.uuidString.lowercased(), displayName: passkey.displayName, now: self.now())
}
}
/// Soft delete a passkey.
- /// - Parameter passkeyId: The ID of the passkey to delete
+ /// - Parameters:
+ /// - passkeyId: The ID of the passkey to delete
+ /// - manifestId: The manifest the passkey belongs to, when the caller knows it
/// - Returns: Number of rows affected
@discardableResult
- public func delete(_ passkeyId: String) throws -> Int {
+ public func delete(_ passkeyId: String, manifestId: String? = nil) throws -> Int {
return try withTransaction {
- let now = self.now()
- return try client.executeUpdate(PasskeyQueries.softDelete, params: [now, passkeyId])
+ guard let scope = try manifestId ?? resolveRowManifestId(table: "Passkeys", id: passkeyId) else {
+ return 0
+ }
+ return try client.executeUpdate(PasskeyQueries.softDelete, params: [self.now(), passkeyId, scope])
}
}
@@ -207,69 +148,42 @@ public class PasskeyRepository: BaseRepository {
/// - Parameters:
/// - passkeyId: The ID of the passkey to update
/// - displayName: The new display name
+ /// - manifestId: The manifest the passkey belongs to, when the caller knows it
/// - Returns: Number of rows affected
@discardableResult
- public func updateDisplayName(_ passkeyId: String, displayName: String) throws -> Int {
+ public func updateDisplayName(_ passkeyId: String, displayName: String, manifestId: String? = nil) throws -> Int {
return try withTransaction {
- let now = self.now()
- return try client.executeUpdate(PasskeyQueries.updateDisplayName, params: [displayName, now, passkeyId])
+ guard let scope = try manifestId ?? resolveRowManifestId(table: "Passkeys", id: passkeyId) else {
+ return 0
+ }
+ return try client.executeUpdate(PasskeyQueries.updateDisplayName, params: [displayName, self.now(), passkeyId, scope])
}
}
- /// Replace an existing passkey with a new one, optionally updating the item's logo.
- /// Deletes the old passkey and creates a new one linked to the same item.
+ /// Replace an existing passkey with a new one, optionally refreshing the item's logo.
+ /// Soft deletes the old passkey and creates a new one linked to the same item, in that item's manifest.
/// - Parameters:
/// - oldPasskeyId: The ID of the passkey to replace
/// - newPasskey: The new passkey to create
/// - displayName: The display name for the new passkey
- /// - logo: Optional logo data to update
+ /// - logo: Optional favicon bytes fetched for the passkey's rpId
/// - Returns: The ID of the new passkey
@discardableResult
public func replace(oldPasskeyId: String, with newPasskey: Passkey, displayName: String, logo: Data? = nil) throws -> String {
return try withTransaction {
- let now = self.now()
-
- // Update logo if provided
- if let logo = logo {
- try updateItemLogoInternal(
- itemId: newPasskey.parentItemId.uuidString.lowercased(),
- logo: logo,
- rpId: newPasskey.rpId,
- now: now
- )
+ guard let scope = try newPasskey.manifestId ?? resolveRowManifestId(table: "Passkeys", id: oldPasskeyId) else {
+ throw PasskeyRepositoryError.passkeyNotFound
}
- // Delete the old passkey
- try client.executeUpdate(PasskeyQueries.softDelete, params: [now, oldPasskeyId])
-
- // Create the new passkey
- let newPasskeyId = newPasskey.id.uuidString.lowercased()
+ let now = self.now()
+ let itemId = newPasskey.parentItemId.uuidString.lowercased()
- guard let publicKeyString = String(data: newPasskey.publicKey, encoding: .utf8),
- let privateKeyString = String(data: newPasskey.privateKey, encoding: .utf8) else {
- throw PasskeyRepositoryError.invalidKeyData
+ if let logo = logo {
+ try refreshItemLogo(itemId: itemId, manifestId: scope, rpId: newPasskey.rpId, logo: logo, now: now)
}
- let userHandleParam: SqliteBindValue = newPasskey.userHandle.map { "av-base64-to-blob:\($0.base64EncodedString())" }
- let prfKeyParam: SqliteBindValue = newPasskey.prfKey.map { "av-base64-to-blob:\($0.base64EncodedString())" }
-
- try client.executeUpdate(PasskeyQueries.insert, params: [
- newPasskeyId,
- newPasskey.parentItemId.uuidString.lowercased(),
- newPasskey.rpId,
- userHandleParam,
- publicKeyString,
- privateKeyString,
- prfKeyParam,
- displayName,
- now,
- now,
- 0,
- newPasskey.parentItemId.uuidString.lowercased(),
- activeManifestId()
- ])
-
- return newPasskeyId
+ try client.executeUpdate(PasskeyQueries.softDelete, params: [now, oldPasskeyId, scope])
+ return try insertPasskey(newPasskey, itemId: itemId, displayName: displayName, now: now)
}
}
@@ -282,150 +196,41 @@ public class PasskeyRepository: BaseRepository {
/// - userName: Optional username
/// - displayName: Display name for the item
/// - passkey: The passkey to create
- /// - logo: Optional logo data
+ /// - logo: Optional favicon bytes fetched for the rpId
/// - Returns: The created item ID
@discardableResult
- public func createItemWithPasskey(
- rpId: String,
- userName: String?,
- displayName: String,
- passkey: Passkey,
- logo: Data? = nil
- ) throws -> String {
+ public func createItemWithPasskey(rpId: String, userName: String?, displayName: String, passkey: Passkey, logo: Data? = nil) throws -> String {
return try withTransaction {
let itemId = passkey.parentItemId.uuidString.lowercased()
let now = self.now()
- // Create or reuse logo if provided
- var logoId: String?
- if let logo = logo {
- let source = rpId.lowercased().replacingOccurrences(of: "www.", with: "")
- logoId = try getOrCreateLogo(source: source, logoData: logo, now: now)
- }
+ // An item outside any folder lands in the write manifest, which is the scope its logo has to live in too.
+ let scope = try writeManifestId()
+ let logoId = try resolveLogoId(existingLogoId: nil, manifestId: scope, rpId: rpId, logo: logo, now: now)
- // Create the Item
- try client.executeUpdate(ItemQueries.insertItem, params: [
- itemId,
- displayName as SqliteBindValue,
- ItemType.login,
- logoId as SqliteBindValue,
- nil, // FolderId
- now,
- now,
- 0,
- nil,
- activeManifestId()
- ])
-
- // Create field values - login.url
- let urlFieldId = generateId()
- try client.executeUpdate(FieldValueQueries.insert, params: [
- urlFieldId,
- itemId,
- nil, // FieldDefinitionId
- FieldKey.loginUrl,
- "https://\(rpId)",
- 0, // Weight
- now,
- now,
- 0,
- itemId,
- activeManifestId()
- ])
-
- // Create field values - login.username if provided
- if let userName = userName, !userName.isEmpty {
- let usernameFieldId = generateId()
- try client.executeUpdate(FieldValueQueries.insert, params: [
- usernameFieldId,
- itemId,
- nil, // FieldDefinitionId
- FieldKey.loginUsername,
- userName,
- 0, // Weight
- now,
- now,
- 0,
- itemId,
- activeManifestId()
- ])
- }
+ try client.executeUpdate(ItemQueries.insertItem, params: [itemId, displayName as SqliteBindValue, ItemType.login, logoId as SqliteBindValue, nil, now, now, 0, nil, scope])
- // Create the passkey
- guard let publicKeyString = String(data: passkey.publicKey, encoding: .utf8),
- let privateKeyString = String(data: passkey.privateKey, encoding: .utf8) else {
- throw PasskeyRepositoryError.invalidKeyData
+ try insertSystemField(itemId: itemId, fieldKey: FieldKey.loginUrl, value: "https://\(rpId)", manifestId: scope, now: now)
+ if let userName = userName, !userName.isEmpty {
+ try insertSystemField(itemId: itemId, fieldKey: FieldKey.loginUsername, value: userName, manifestId: scope, now: now)
}
- let userHandleParam: SqliteBindValue = passkey.userHandle.map { "av-base64-to-blob:\($0.base64EncodedString())" }
- let prfKeyParam: SqliteBindValue = passkey.prfKey.map { "av-base64-to-blob:\($0.base64EncodedString())" }
-
- try client.executeUpdate(PasskeyQueries.insert, params: [
- passkey.id.uuidString.lowercased(),
- itemId,
- passkey.rpId,
- userHandleParam,
- publicKeyString,
- privateKeyString,
- prfKeyParam,
- passkey.displayName,
- now,
- now,
- 0,
- itemId,
- activeManifestId()
- ])
-
+ _ = try insertPasskey(passkey, itemId: itemId, displayName: passkey.displayName, now: now)
return itemId
}
}
- /// Update item logo.
- /// Note: This only updates the logo, NOT the item name.
+ /// Refresh an item's logo from a freshly fetched favicon. Only the logo is touched, never the item name.
/// - Parameters:
/// - itemId: The item ID
- /// - logo: The new logo data
- /// - rpId: The relying party ID for logo source
+ /// - logo: The favicon bytes
+ /// - rpId: The relying party ID the favicon was fetched for
public func updateItemLogo(itemId: String, logo: Data, rpId: String) throws {
try withTransaction {
- let now = self.now()
- try updateItemLogoInternal(itemId: itemId, logo: logo, rpId: rpId, now: now)
- }
- }
-
- /// Internal helper to update item logo without creating a transaction.
- /// Used within larger transactions to avoid nested transaction issues.
- /// Note: This only updates the logo, never the item name.
- /// - Parameters:
- /// - itemId: The item ID
- /// - logo: The new logo data
- /// - rpId: The relying party ID for logo source (used when creating new logo)
- /// - now: The current timestamp
- private func updateItemLogoInternal(
- itemId: String,
- logo: Data,
- rpId: String,
- now: String
- ) throws {
- // Get current logo ID from item
- let itemResults = try client.executeQuery(LogoQueries.getLogoIdFromItem, params: [itemId])
-
- let logoDataParam = "av-base64-to-blob:\(logo.base64EncodedString())"
-
- if let existingLogoId = itemResults.first?["LogoId"] as? String {
- // Update existing logo
- try client.executeUpdate(LogoQueries.updateFileData, params: [
- logoDataParam,
- now,
- existingLogoId
- ])
- } else {
- // Create or reuse logo with unique source check
- let source = rpId.lowercased().replacingOccurrences(of: "www.", with: "")
- let newLogoId = try getOrCreateLogo(source: source, logoData: logo, now: now)
-
- // Update item with new logo ID
- try client.executeUpdate(LogoQueries.updateItemLogoId, params: [newLogoId, now, itemId])
+ guard let scope = try resolveRowManifestId(table: "Items", id: itemId) else {
+ throw PasskeyRepositoryError.itemNotFound
+ }
+ try refreshItemLogo(itemId: itemId, manifestId: scope, rpId: rpId, logo: logo, now: self.now())
}
}
@@ -433,135 +238,149 @@ public class PasskeyRepository: BaseRepository {
/// - Parameters:
/// - itemId: The UUID of the existing Item to add the passkey to
/// - passkey: The passkey to add
- /// - logo: Optional logo data to update/add
+ /// - logo: Optional favicon bytes fetched for the passkey's rpId
/// - Returns: The ID of the created passkey
@discardableResult
- public func addPasskeyToExistingItem(
- itemId: UUID,
- passkey: Passkey,
- logo: Data? = nil
- ) throws -> String {
+ public func addPasskeyToExistingItem(itemId: UUID, passkey: Passkey, logo: Data? = nil) throws -> String {
return try withTransaction {
let itemIdString = itemId.uuidString.lowercased()
- let now = self.now()
+ guard let scope = try resolveRowManifestId(table: "Items", id: itemIdString) else {
+ throw PasskeyRepositoryError.itemNotFound
+ }
- // Update logo if provided
+ let now = self.now()
if let logo = logo {
- try updateItemLogoInternal(
- itemId: itemIdString,
- logo: logo,
- rpId: passkey.rpId,
- now: now
- )
+ try refreshItemLogo(itemId: itemIdString, manifestId: scope, rpId: passkey.rpId, logo: logo, now: now)
}
- // Create the passkey linked to the existing item
- let passkeyId = passkey.id.uuidString.lowercased()
+ return try insertPasskey(passkey, itemId: itemIdString, displayName: passkey.displayName, now: now)
+ }
+ }
- guard let publicKeyString = String(data: passkey.publicKey, encoding: .utf8),
- let privateKeyString = String(data: passkey.privateKey, encoding: .utf8) else {
- throw PasskeyRepositoryError.invalidKeyData
- }
+ // MARK: - Row Helpers
- let userHandleParam: SqliteBindValue = passkey.userHandle.map { "av-base64-to-blob:\($0.base64EncodedString())" }
- let prfKeyParam: SqliteBindValue = passkey.prfKey.map { "av-base64-to-blob:\($0.base64EncodedString())" }
-
- try client.executeUpdate(PasskeyQueries.insert, params: [
- passkeyId,
- itemIdString,
- passkey.rpId,
- userHandleParam,
- publicKeyString,
- privateKeyString,
- prfKeyParam,
- passkey.displayName,
- now,
- now,
- 0,
- itemIdString,
- activeManifestId()
- ])
-
- return passkeyId
- }
+ /// Base64 text the query bridge binds as a BLOB, or nil.
+ private func blobParam(_ data: Data?) -> SqliteBindValue {
+ return data.map { "av-base64-to-blob:\($0.base64EncodedString())" }
}
- // MARK: - Helper Methods
+ /// Insert one system field value for an item.
+ private func insertSystemField(itemId: String, fieldKey: String, value: String, manifestId: String, now: String) throws {
+ let weight = FieldValueQueries.defaultWeight(forFieldKey: fieldKey)
+ try client.executeUpdate(FieldValueQueries.insert, params: [generateId(), itemId, nil, fieldKey, value, weight, now, now, 0, itemId, manifestId])
+ }
- /// Get an existing logo ID for a source, or create a new logo if none exists.
- /// This prevents UNIQUE constraint violations on Logos.Source.
- /// - Parameters:
- /// - source: The normalized source domain (e.g., 'github.com')
- /// - logoData: The logo image data
- /// - now: The current timestamp for CreatedAt/UpdatedAt
- /// - Returns: The logo ID (existing or newly created)
- private func getOrCreateLogo(source: String, logoData: Data, now: String) throws -> String {
- // Check if a logo for this source already exists
- let existingLogos = try client.executeQuery(LogoQueries.getBySource, params: [source])
-
- if let existingLogo = existingLogos.first,
- let existingLogoId = existingLogo["Id"] as? String {
- let isDeleted = (existingLogo["IsDeleted"] as? Int64) == 1
-
- // Sanity check: restore if soft-deleted
- if isDeleted {
- let logoDataParam = "av-base64-to-blob:\(logoData.base64EncodedString())"
- try client.executeUpdate(LogoQueries.restore, params: [now, existingLogoId])
- try client.executeUpdate(LogoQueries.updateFileData, params: [logoDataParam, now, existingLogoId])
- }
- return existingLogoId
+ /// Insert a passkey row linked to an item, stamped with the item's manifest.
+ /// - Returns: The passkey ID
+ private func insertPasskey(_ passkey: Passkey, itemId: String, displayName: String, now: String) throws -> String {
+ let passkeyId = passkey.id.uuidString.lowercased()
+ guard let publicKeyString = String(data: passkey.publicKey, encoding: .utf8), let privateKeyString = String(data: passkey.privateKey, encoding: .utf8) else {
+ throw PasskeyRepositoryError.invalidKeyData
}
- // Create new logo entry. The id is derived from (manifest, kind, source) by the Rust core.
- let manifestId = activeManifestId()
- let logoId = RustCoreFramework.vaultCodecLogoIdFor(manifestId: manifestId, kind: "favicon", source: source)
- let logoDataParam = "av-base64-to-blob:\(logoData.base64EncodedString())"
-
- try client.executeUpdate(LogoQueries.insert, params: [
- logoId,
- source,
- manifestId,
- logoDataParam,
- "image/png",
- nil,
+ let fallbackManifestId = try writeManifestId()
+ try client.executeUpdate(PasskeyQueries.insert, params: [
+ passkeyId,
+ itemId,
+ itemId,
+ fallbackManifestId,
+ passkey.rpId,
+ blobParam(passkey.userHandle),
+ publicKeyString,
+ privateKeyString,
+ blobParam(passkey.prfKey),
+ displayName,
+ passkey.additionalData as SqliteBindValue,
now,
now,
0
])
- return logoId
+ return passkeyId
}
-}
-/// Data class to hold Item info for Items without passkeys (internal VaultStoreKit type).
-/// Used for showing existing credentials that can have a passkey added.
-/// Note: VaultUI has its own ItemWithCredentialInfo type for UI usage.
-public struct ItemWithCredentialInfoData {
- public let itemId: UUID
- public let serviceName: String?
- /// All URLs associated with this item (supports multi-value URL fields)
- public let urls: [String]
- public let username: String?
- public let email: String?
- public let hasPassword: Bool
- public let createdAt: Date
- public let updatedAt: Date
-
- public init(itemId: UUID, serviceName: String?, urls: [String], username: String?, email: String? = nil, hasPassword: Bool, createdAt: Date, updatedAt: Date) {
- self.itemId = itemId
- self.serviceName = serviceName
- self.urls = urls
- self.username = username
- self.email = email
- self.hasPassword = hasPassword
- self.createdAt = createdAt
- self.updatedAt = updatedAt
+ // MARK: - Logo Helpers
+
+ /// The natural key a logo row is addressed by, and the manifest it lives in.
+ private struct LogoKey {
+ let manifestId: String
+ let kind: String
+ let source: String
}
-}
-/// Errors that can occur in PasskeyRepository operations.
-public enum PasskeyRepositoryError: Error {
- case invalidKeyData
- case passkeyNotFound
- case itemNotFound
+ /// The image bytes and metadata written into a logo row.
+ private struct LogoImage {
+ let data: Data?
+ let mimeType: String?
+ let name: String?
+ }
+
+ /// The kind and key of an existing logo, or nil when it no longer exists.
+ private func getLogo(byId logoId: String) throws -> (kind: String, source: String)? {
+ guard let row = try client.executeQuery(LogoQueries.getById, params: [logoId]).first, let kind = row["Kind"] as? String, let source = row["Source"] as? String else {
+ return nil
+ }
+ return (kind, source)
+ }
+
+ /// Point an item at the favicon fetched for `rpId`, following the item-logo write rules in core/client
+ /// `ItemRepository.resolveLogoId`.
+ private func refreshItemLogo(itemId: String, manifestId: String, rpId: String, logo: Data, now: String) throws {
+ let rows = try client.executeQuery(LogoQueries.getLogoIdFromItem, params: [itemId, manifestId])
+ let existingLogoId = rows.first?["LogoId"] as? String
+
+ guard let logoId = try resolveLogoId(existingLogoId: existingLogoId, manifestId: manifestId, rpId: rpId, logo: logo, now: now), logoId != existingLogoId else {
+ return
+ }
+ try client.executeUpdate(LogoQueries.updateItemLogoId, params: [logoId, now, itemId, manifestId])
+ }
+
+ /// The logo id an item should carry after a favicon was fetched for `rpId` (core/client `ItemRepository.resolveLogoId`):
+ /// a built-in or uploaded logo the user chose is kept, a favicon already on file for this domain is reused, fresh
+ /// bytes go under the domain's own row, and without a derivable domain the logo is left as it is.
+ private func resolveLogoId(existingLogoId: String?, manifestId: String, rpId: String, logo: Data?, now: String) throws -> String? {
+ let existing = try existingLogoId.flatMap { try getLogo(byId: $0) }
+ if let existing = existing, existing.kind != "favicon" {
+ return try adoptIntoScope(LogoKey(manifestId: manifestId, kind: existing.kind, source: existing.source), now: now)
+ }
+
+ // The same URL string the item's login.url field is written with, which is what the TypeScript side derives the favicon target from.
+ let source = RustCoreFramework.faviconSourceKey(url: "https://\(rpId)")
+ if source.isEmpty {
+ return existingLogoId
+ }
+
+ let key = LogoKey(manifestId: manifestId, kind: "favicon", source: source)
+ if let existing = existing, existing.source == source {
+ return try adoptIntoScope(key, now: now)
+ }
+ if let logo = logo, !logo.isEmpty {
+ return try getOrCreateLogo(key, image: LogoImage(data: logo, mimeType: "image/x-icon", name: nil), now: now)
+ }
+ return try adoptIntoScope(key, now: now)
+ }
+
+ /// Get or create the logo for a key inside one manifest, refreshing its image data.
+ /// The row's stamp and the id derived for it come from the same manifest.
+ private func getOrCreateLogo(_ key: LogoKey, image: LogoImage, now: String) throws -> String {
+ let logoId = RustCoreFramework.vaultCodecLogoIdFor(manifestId: key.manifestId, kind: key.kind, source: key.source)
+ let params: [SqliteBindValue] = [logoId, key.kind, key.source, key.manifestId, blobParam(image.data), image.mimeType, image.name, now, now]
+ try client.executeUpdate(LogoQueries.upsert, params: params)
+ return logoId
+ }
+
+ /// The id this logo has inside the key's manifest, copying it in from another manifest when it is not there yet.
+ /// - Returns: The logo id inside this manifest, or nil when the vault holds no such logo at all
+ private func adoptIntoScope(_ key: LogoKey, now: String) throws -> String? {
+ let inScope = try client.executeQuery(LogoQueries.getIdForKey, params: [key.manifestId, key.kind, key.source])
+ if let logoId = inScope.first?["Id"] as? String {
+ return logoId
+ }
+
+ guard let origin = try client.executeQuery(LogoQueries.getBestForKey, params: [key.kind, key.source]).first else {
+ return nil
+ }
+ let data = (origin["FileData"] as? String).flatMap { Data(base64Encoded: $0) }
+ return try getOrCreateLogo(key, image: LogoImage(data: data, mimeType: origin["MimeType"] as? String, name: origin["Name"] as? String), now: now)
+ }
}
diff --git a/apps/mobile-app/ios/VaultStoreKit/Database/Repositories/PasskeyRepositoryTypes.swift b/apps/mobile-app/ios/VaultStoreKit/Database/Repositories/PasskeyRepositoryTypes.swift
new file mode 100644
index 000000000..1cbd72ac7
--- /dev/null
+++ b/apps/mobile-app/ios/VaultStoreKit/Database/Repositories/PasskeyRepositoryTypes.swift
@@ -0,0 +1,48 @@
+import Foundation
+
+/// Data class to hold Item info for Items without passkeys (internal VaultStoreKit type).
+/// Used for showing existing credentials that can have a passkey added.
+/// Note: VaultUI has its own ItemWithCredentialInfo type for UI usage.
+public struct ItemWithCredentialInfoData {
+ /// The item id.
+ public let itemId: UUID
+ /// The item name.
+ public let serviceName: String?
+ /// All URLs associated with this item (supports multi-value URL fields)
+ public let urls: [String]
+ /// The login.username value, if any.
+ public let username: String?
+ /// The login.email value, if any.
+ public let email: String?
+ /// Whether the item has a non-empty password.
+ public let hasPassword: Bool
+ /// When the item was created.
+ public let createdAt: Date
+ /// When the item was last updated.
+ public let updatedAt: Date
+ /// The manifest the item lives in, when known.
+ public let manifestId: String?
+
+ /// Create an entry from the mapped row values.
+ public init(itemId: UUID, serviceName: String?, urls: [String], username: String?, email: String? = nil, hasPassword: Bool, createdAt: Date, updatedAt: Date, manifestId: String? = nil) {
+ self.itemId = itemId
+ self.serviceName = serviceName
+ self.urls = urls
+ self.username = username
+ self.email = email
+ self.hasPassword = hasPassword
+ self.createdAt = createdAt
+ self.updatedAt = updatedAt
+ self.manifestId = manifestId
+ }
+}
+
+/// Errors that can occur in PasskeyRepository operations.
+public enum PasskeyRepositoryError: Error {
+ /// The passkey's public or private key is not valid UTF-8 JWK text.
+ case invalidKeyData
+ /// No live passkey with the given id exists.
+ case passkeyNotFound
+ /// No item with the given id exists.
+ case itemNotFound
+}
diff --git a/apps/mobile-app/ios/VaultStoreKit/Database/Repositories/TotpRepository.swift b/apps/mobile-app/ios/VaultStoreKit/Database/Repositories/TotpRepository.swift
index 3bcd617a1..7e6538d68 100644
--- a/apps/mobile-app/ios/VaultStoreKit/Database/Repositories/TotpRepository.swift
+++ b/apps/mobile-app/ios/VaultStoreKit/Database/Repositories/TotpRepository.swift
@@ -1,61 +1,54 @@
import Foundation
import VaultModels
-/// Repository for managing TOTP codes in the vault database.
+/// Repository for reading TOTP codes from the vault database.
public class TotpRepository: BaseRepository {
- /// Get all TOTP codes for a specific item.
- /// - Parameter itemId: The UUID of the item
- /// - Returns: Array of TotpCode objects for the item
- /// - Throws: Database errors
- public func getTotpCodesForItem(_ itemId: UUID) throws -> [TotpCode] {
- let query = """
- SELECT Id, Name, SecretKey, Algorithm, Digits, Period, ItemId, COALESCE(IsDeleted, 0) as IsDeleted
+ /// An item's TOTP codes, scoped by manifest as well as item (core/client `TotpCodeQueries.GET_BY_ITEM_ID`).
+ private static let getByItemId = """
+ SELECT Id, Name, SecretKey, Algorithm, Digits, Period, ItemId
FROM TotpCodes
- WHERE ItemId = ? AND IsDeleted = 0
- ORDER BY Name ASC
+ WHERE ItemId = ? AND ManifestId = ? AND IsDeleted = 0
"""
- let results = try client.executeQuery(query, params: [itemId.uuidString.lowercased()])
- var totpCodes: [TotpCode] = []
+ /// Get all TOTP codes for a specific item.
+ /// - Parameters:
+ /// - itemId: The UUID of the item
+ /// - manifestId: The manifest the item belongs to, when the caller knows it
+ /// - Returns: Array of TotpCode objects for the item
+ public func getTotpCodesForItem(_ itemId: UUID, manifestId: String? = nil) throws -> [TotpCode] {
+ let itemIdString = itemId.uuidString.lowercased()
+ guard let scope = try manifestId ?? resolveRowManifestId(table: "Items", id: itemIdString) else {
+ return []
+ }
- for row in results {
- guard let idString = row["Id"] as? String,
- let id = UUID(uuidString: idString),
- let name = row["Name"] as? String,
- let secretKey = row["SecretKey"] as? String,
- let itemIdString = row["ItemId"] as? String,
- let itemIdParsed = UUID(uuidString: itemIdString) else {
- continue
+ let results = try client.executeQuery(Self.getByItemId, params: [itemIdString, scope])
+ return results.compactMap { row -> TotpCode? in
+ guard let idString = row["Id"] as? String, let id = UUID(uuidString: idString), let name = row["Name"] as? String, let secretKey = row["SecretKey"] as? String else {
+ return nil
+ }
+ guard let rowItemId = row["ItemId"] as? String, let itemIdParsed = UUID(uuidString: rowItemId) else {
+ return nil
}
- let isDeleted = (row["IsDeleted"] as? Int64 ?? 0) != 0
- let algorithm = row["Algorithm"] as? String ?? TotpCode.defaultAlgorithm
- let digits = Int(row["Digits"] as? Int64 ?? Int64(TotpCode.defaultDigits))
- let period = Int(row["Period"] as? Int64 ?? Int64(TotpCode.defaultPeriod))
-
- let totpCode = TotpCode(
+ return TotpCode(
id: id,
name: name,
secretKey: secretKey,
- algorithm: algorithm,
- digits: digits,
- period: period,
+ algorithm: row["Algorithm"] as? String ?? TotpCode.defaultAlgorithm,
+ digits: Int(row["Digits"] as? Int64 ?? Int64(TotpCode.defaultDigits)),
+ period: Int(row["Period"] as? Int64 ?? Int64(TotpCode.defaultPeriod)),
itemId: itemIdParsed,
- isDeleted: isDeleted
+ isDeleted: false
)
-
- totpCodes.append(totpCode)
}
-
- return totpCodes
}
/// Get the first TOTP code for a specific item (convenience method).
- /// - Parameter itemId: The UUID of the item
+ /// - Parameters:
+ /// - itemId: The UUID of the item
+ /// - manifestId: The manifest the item belongs to, when the caller knows it
/// - Returns: Optional TotpCode if one exists
- /// - Throws: Database errors
- public func getFirstTotpCodeForItem(_ itemId: UUID) throws -> TotpCode? {
- let codes = try getTotpCodesForItem(itemId)
- return codes.first
+ public func getFirstTotpCodeForItem(_ itemId: UUID, manifestId: String? = nil) throws -> TotpCode? {
+ return try getTotpCodesForItem(itemId, manifestId: manifestId).first
}
}
diff --git a/apps/mobile-app/ios/VaultStoreKit/Enums/AppError.swift b/apps/mobile-app/ios/VaultStoreKit/Enums/AppError.swift
index ffd344ca1..bdbfb6c55 100644
--- a/apps/mobile-app/ios/VaultStoreKit/Enums/AppError.swift
+++ b/apps/mobile-app/ios/VaultStoreKit/Enums/AppError.swift
@@ -18,6 +18,7 @@ public enum AppError: Error {
case clientVersionNotSupported
case serverVersionNotSupported
case vaultVersionIncompatible
+ case serverUpdateRequired
// Vault status errors
case vaultMergeRequired
@@ -47,6 +48,7 @@ public enum AppError: Error {
case storageWriteFailed(message: String)
case databaseInitFailed(message: String)
case vaultStoreFailed(message: String)
+ case manifestNotRecorded
// Merge errors
case vaultMergeFailed(message: String)
@@ -107,6 +109,8 @@ public enum AppError: Error {
return "E-302"
case .vaultVersionIncompatible:
return "E-303"
+ case .serverUpdateRequired:
+ return "E-304"
case .vaultMergeRequired:
return "E-401"
case .vaultOutdated:
@@ -153,6 +157,8 @@ public enum AppError: Error {
return "E-603"
case .vaultStoreFailed:
return "E-604"
+ case .manifestNotRecorded:
+ return "E-605"
case .vaultMergeFailed:
return "E-701"
case .mergeUploadFailed:
@@ -201,6 +207,8 @@ public enum AppError: Error {
return "Server version not supported"
case .vaultVersionIncompatible:
return "Vault version incompatible"
+ case .serverUpdateRequired:
+ return "Server update required"
case .vaultMergeRequired:
return "Vault merge required"
case .vaultOutdated:
@@ -247,6 +255,8 @@ public enum AppError: Error {
return "Database init failed: \(message)"
case .vaultStoreFailed(let message):
return "Failed to store vault: \(message)"
+ case .manifestNotRecorded:
+ return "No personal manifest recorded yet; sync once before writing"
case .vaultMergeFailed(let message):
return "Vault merge failed: \(message)"
case .mergeUploadFailed(let message):
@@ -292,10 +302,10 @@ public enum AppError: Error {
}
}
- /// Check if this is a network error (offline mode).
+ /// Check if this is a network error (offline mode). A timeout is not: the sync engine reports it as a failed sync.
public var isNetworkError: Bool {
switch self {
- case .serverUnavailable, .networkError, .timeout:
+ case .serverUnavailable, .networkError:
return true
default:
return false
diff --git a/apps/mobile-app/ios/VaultStoreKit/Services/VaultSync.swift b/apps/mobile-app/ios/VaultStoreKit/Services/VaultSync.swift
new file mode 100644
index 000000000..2a5dc350d
--- /dev/null
+++ b/apps/mobile-app/ios/VaultStoreKit/Services/VaultSync.swift
@@ -0,0 +1,226 @@
+import Foundation
+import VaultModels
+import VaultUtils
+
+/// The vault sync wrapper: one method per engine operation, adoption of what the engine reported, and the mapping of
+/// its failures into the native error. The driver below it is VaultSyncEngine, which turns the Rust engine's
+/// commands into host actions.
+///
+/// When updating this logic, make sure to update the same logic on the other platforms:
+/// - core/client/src/sync/VaultSync.ts (shared core client for web apps)
+/// - apps/mobile-app/ios/VaultStoreKit/Services/VaultSync.swift (this file)
+/// - apps/mobile-app/android/app/src/main/java/net/aliasvault/app/vaultstore/VaultSync.kt
+internal final class VaultSync {
+ private let vaultStore: VaultStore
+
+ init(vaultStore: VaultStore) {
+ self.vaultStore = vaultStore
+ }
+
+ /// Full vault sync: status check, then pull (and merge) or push as the server and local revisions decide. Never throws.
+ func syncVaultWithServer(using webApiService: WebApiService) async -> VaultSyncResult {
+ let startedAt = Date()
+ vaultStore.setIsSyncing(true)
+ defer {
+ vaultStore.setIsSyncing(false)
+ print("[VaultSync] Sync finished in \(VaultSyncRunLog.elapsedMs(since: startedAt))ms")
+ }
+
+ let wasDirty = vaultStore.getIsDirty()
+ let result: [String: Any]
+ do {
+ result = try await run("fullSync", using: webApiService)
+ } catch {
+ return failedSync(Self.driverError(error), wasOffline: vaultStore.getOfflineMode())
+ }
+
+ let wasOffline = result["wasOffline"] as? Bool ?? false
+ guard result["success"] as? Bool == true else {
+ return failedSync(Self.syncError(from: result), wasOffline: wasOffline)
+ }
+ if wasOffline {
+ let offlineCode = AppError.networkError(underlyingError: NSError(domain: "VaultSync", code: 0)).code
+ return VaultSyncResult(success: false, action: .error, newRevision: vaultStore.getCurrentVaultRevisionNumber(), wasOffline: true, error: offlineCode)
+ }
+
+ /*
+ * A vault that still has to be upgraded is reported, never migrated here: the app routes it to the upgrade
+ * page, which asks first when the migration signs out every other pre-format client (see migrateVaultManifest).
+ */
+ let hasNewVault = result["hasNewVault"] as? Bool ?? false
+ let action: SyncAction = hasNewVault ? (wasDirty ? .merged : .downloaded) : (wasDirty ? .uploaded : .alreadyInSync)
+ return VaultSyncResult(
+ success: true,
+ action: action,
+ newRevision: vaultStore.getCurrentVaultRevisionNumber(),
+ wasOffline: false,
+ sqliteBlobUpgradeRequired: result["sqliteBlobUpgradeRequired"] as? Bool ?? false,
+ manifestMigrationRequired: result["manifestMigrationRequired"] as? Bool ?? false
+ )
+ }
+
+ /// One status call: whether the server holds newer state than this device.
+ func checkVaultVersion(using webApiService: WebApiService) async throws -> VaultVersionCheckResult {
+ let result = try await run("statusCheck", using: webApiService)
+ if result["isOffline"] as? Bool == true {
+ vaultStore.setOfflineMode(true)
+ throw AppError.serverUnavailable(statusCode: 0)
+ }
+ if result["requiresLogout"] as? Bool == true || result["success"] as? Bool != true {
+ throw Self.syncError(from: result)
+ }
+ vaultStore.setOfflineMode(false)
+ return VaultVersionCheckResult(isNewVersionAvailable: result["hasNewerVault"] as? Bool ?? false, syncState: vaultStore.getSyncState())
+ }
+
+ /// Resolve the vault key right after login: the account's key chain is opened with the password-derived key and the
+ /// VEK is stored as the session key; a legacy account keeps the derived key. Every sync assumes the key this stored.
+ /// Returns the stored key (base64).
+ func resolveVaultKey(using webApiService: WebApiService, derivedKeyBase64: String) async throws -> String {
+ let result = try await run("resolveVaultKey", using: webApiService, encryptionKey: derivedKeyBase64)
+ guard result["success"] as? Bool == true else {
+ throw Self.syncError(from: result)
+ }
+ let key = result["encryptionKey"] as? String ?? derivedKeyBase64
+ try vaultStore.storeEncryptionKey(base64Key: key)
+ return key
+ }
+
+ /// Classify the pending manifest migration as the engine sees it: `none`, `schema-rebuild` (runs unattended) or
+ /// `storage-format-upgrade` (the app asks first). A vault still on the sqlite-blob chain classifies as `none`.
+ func getVaultMigrationStatus(using webApiService: WebApiService) async throws -> String {
+ let status = try await run("migrationStatus", using: webApiService)
+ return status["kind"] as? String ?? "storage-format-upgrade"
+ }
+
+ /// Bring the local vault onto the current storage model (a schema rebuild after an app update, or the one-time
+ /// account-key upgrade of a legacy vault) and push it. Driven by the app's upgrade page only: a sync never runs
+ /// it on its own, because the storage format move signs out every other client that predates the format. Never throws.
+ func migrateVaultManifest(using webApiService: WebApiService) async -> VaultMigrationResult {
+ let result: [String: Any]
+ do {
+ result = try await run("migrateManifest", using: webApiService)
+ } catch {
+ return failedMigration(Self.driverError(error))
+ }
+ guard result["success"] as? Bool == true else {
+ return failedMigration(Self.syncError(from: result))
+ }
+ let pushed = result["pushed"] as? Bool ?? false
+ print("[VaultSync] Manifest migration complete: pushed=\(pushed)")
+ return VaultMigrationResult(success: true, pushed: pushed)
+ }
+
+ /// Push the pending local changes (after a native mutation such as an autofill link or a passkey creation).
+ func mutateVault(using webApiService: WebApiService) async throws {
+ let result = await syncVaultWithServer(using: webApiService)
+ if !result.success && !result.wasOffline {
+ throw AppError.vaultUploadFailed(message: result.errorMessage ?? result.error ?? "Vault sync failed")
+ }
+ }
+
+ /// Run one engine operation and adopt what it reported. A driver failure surfaces as the native error.
+ private func run(_ operation: String, using webApiService: WebApiService, encryptionKey: String? = nil) async throws -> [String: Any] {
+ let result: [String: Any]
+ do {
+ result = try await VaultSyncEngine(vaultStore: vaultStore, webApiService: webApiService).run(operation: operation, encryptionKey: encryptionKey)
+ } catch {
+ throw Self.driverError(error)
+ }
+ adoptSyncResult(result)
+ return result
+ }
+
+ /// Persist what the engine reported: server version, offline mode, session values it changed, and the email
+ /// routing a pulled vault came with. Capabilities are not stored: the mobile app has no capability gate yet.
+ private func adoptSyncResult(_ result: [String: Any]) {
+ if let serverVersion = result["serverVersion"] as? String, !serverVersion.isEmpty {
+ vaultStore.setServerVersion(serverVersion)
+ }
+ if let offline = result["isOfflineMode"] as? Bool {
+ vaultStore.setOfflineMode(offline)
+ }
+ if let updates = result["sessionUpdates"] as? [String: Any] {
+ if let newKey = updates["encryptionKey"] as? String {
+ try? vaultStore.adoptEncryptionKey(base64Key: newKey)
+ }
+ if let privateKey = updates["accountPrivateKey"] as? String {
+ vaultStore.accountPrivateKey = privateKey
+ }
+ }
+ if let routing = result["emailRouting"] as? [String: Any] {
+ let metadata = VaultMetadata(
+ publicEmailDomains: routing["publicEmailDomainList"] as? [String] ?? [],
+ privateEmailDomains: routing["privateEmailDomainList"] as? [String] ?? [],
+ hiddenPrivateEmailDomains: routing["hiddenPrivateEmailDomainList"] as? [String] ?? [],
+ vaultRevisionNumber: result["pulledRevision"] as? Int ?? vaultStore.getCurrentVaultRevisionNumber()
+ )
+ if let data = try? JSONEncoder().encode(metadata), let json = String(data: data, encoding: .utf8) {
+ try? vaultStore.storeMetadata(json)
+ }
+ }
+ }
+
+ /// A failed sync return.
+ private func failedSync(_ error: AppError, wasOffline: Bool) -> VaultSyncResult {
+ print("[VaultSync] Sync failed (\(error.code)): \(error.message)")
+ return VaultSyncResult(success: false, action: .error, newRevision: vaultStore.getCurrentVaultRevisionNumber(), wasOffline: wasOffline, error: error.code, errorMessage: error.message)
+ }
+
+ /// A failed migration return.
+ private func failedMigration(_ error: AppError) -> VaultMigrationResult {
+ print("[VaultSync] Manifest migration failed (\(error.code)): \(error.message)")
+ return VaultMigrationResult(success: false, pushed: false, error: error.code, errorMessage: error.message)
+ }
+
+ /// An error the driver itself threw (a request it could not build, a command it could not decode).
+ private static func driverError(_ error: Error) -> AppError {
+ if let appError = error as? AppError {
+ return appError
+ }
+ return .syncEngineFailed(message: "\(error)")
+ }
+
+ /// The engine's failure as the native error: a forced logout by its reason, else by its error code.
+ private static func syncError(from result: [String: Any]) -> AppError {
+ if let reason = result["errorKey"] as? String, let error = logoutErrors[reason] {
+ return error
+ }
+ // The engine's message is diagnostic detail; the code decides what the user sees.
+ let message = result["error"] as? String ?? "Vault sync failed"
+ let code = result["errorCode"] as? String ?? ""
+ return (codedErrors[code] ?? { .unknownError(message: $0) })(message)
+ }
+
+ /// The forced logouts by the engine's reason.
+ private static let logoutErrors: [String: AppError] = [
+ "clientVersionNotSupported": .clientVersionNotSupported,
+ "serverVersionNotSupported": .serverVersionNotSupported,
+ "sessionExpired": .sessionExpired,
+ "passwordChanged": .passwordChanged,
+ "vaultVersionIncompatible": .vaultVersionIncompatible
+ ]
+
+ /// The native error for each engine error code, given the engine's message.
+ private static let codedErrors: [String: (String) -> AppError] = [
+ "E-202": { _ in .encryptionKeyNotFound },
+ "E-203": { _ in .vaultDecryptFailed },
+ "E-502": { .syncVaultFetchFailed(message: $0) },
+ "E-503": { _ in .vaultDecryptFailed },
+ "E-505": { _ in .serverUnavailable(statusCode: 0) },
+ "E-506": { .serverError(message: $0) },
+ "E-507": { .syncResponseInvalid(message: $0) },
+ "E-508": { .syncCodecFailed(message: $0) },
+ "E-509": { .syncEngineFailed(message: $0) },
+ "E-601": { .storageReadFailed(message: $0) },
+ "E-602": { .storageWriteFailed(message: $0) },
+ "E-603": { .databaseInitFailed(message: $0) },
+ "E-701": { .vaultMergeFailed(message: $0) },
+ "E-702": { _ in .maxRetriesReached },
+ "E-801": { .vaultUploadFailed(message: $0) },
+ "E-804": { _ in .vaultTooLarge },
+ "E-805": { _ in .timeout },
+ "E-901": { .migrationCheckFailed(message: $0) },
+ "E-903": { _ in .serverUpdateRequired }
+ ]
+}
diff --git a/apps/mobile-app/ios/VaultStoreKit/VaultStore+DatabaseClient.swift b/apps/mobile-app/ios/VaultStoreKit/VaultStore+DatabaseClient.swift
index 6509cc1d0..b7f121a1f 100644
--- a/apps/mobile-app/ios/VaultStoreKit/VaultStore+DatabaseClient.swift
+++ b/apps/mobile-app/ios/VaultStoreKit/VaultStore+DatabaseClient.swift
@@ -22,4 +22,9 @@ extension VaultStore: DatabaseClient {
public var totpRepository: TotpRepository {
return TotpRepository(client: self)
}
+
+ /// The ItemStatsRepository instance for this VaultStore.
+ public var itemStatsRepository: ItemStatsRepository {
+ return ItemStatsRepository(client: self)
+ }
}
diff --git a/apps/mobile-app/ios/VaultStoreKit/VaultStore+Passkey.swift b/apps/mobile-app/ios/VaultStoreKit/VaultStore+Passkey.swift
index 0ab79583a..0e1973410 100644
--- a/apps/mobile-app/ios/VaultStoreKit/VaultStore+Passkey.swift
+++ b/apps/mobile-app/ios/VaultStoreKit/VaultStore+Passkey.swift
@@ -24,10 +24,10 @@ extension VaultStore {
}
/**
- * Get all passkeys for an item (new model)
+ * Get all passkeys for an item.
*/
- public func getPasskeys(forItemId itemId: UUID) throws -> [Passkey] {
- return try passkeyRepository.getByItemId(itemId.uuidString.lowercased())
+ public func getPasskeys(forItemId itemId: UUID, manifestId: String? = nil) throws -> [Passkey] {
+ return try passkeyRepository.getByItemId(itemId.uuidString.lowercased(), manifestId: manifestId)
}
/**
@@ -121,7 +121,7 @@ extension VaultStore {
let itemId = oldPasskey.parentItemId
- // Create the new passkey with the same item ID
+ // Create the new passkey with the same item ID, in the same manifest
let updatedPasskey = Passkey(
id: newPasskey.id,
parentItemId: itemId, // Use the old item ID
@@ -134,7 +134,8 @@ extension VaultStore {
displayName: displayName,
createdAt: Date(),
updatedAt: Date(),
- isDeleted: false
+ isDeleted: false,
+ manifestId: oldPasskey.manifestId
)
// Replace the passkey (handles logo update in same transaction)
diff --git a/apps/mobile-app/ios/VaultStoreKit/VaultStore+Query.swift b/apps/mobile-app/ios/VaultStoreKit/VaultStore+Query.swift
index 52e047060..2a00d8492 100644
--- a/apps/mobile-app/ios/VaultStoreKit/VaultStore+Query.swift
+++ b/apps/mobile-app/ios/VaultStoreKit/VaultStore+Query.swift
@@ -28,6 +28,7 @@ extension VaultStore {
}
/// Execute an UPDATE, INSERT, or DELETE query on the database (which will modify the database).
+ @discardableResult
public func executeUpdate(_ query: String, params: [SqliteBindValue]) throws -> Int {
return Int(try requireDatabase().execute(sql: query, params: params.map(Self.toSqlValue)))
}
@@ -136,110 +137,12 @@ extension VaultStore {
// MARK: - Items (Using Repository Pattern)
- /// Get all items from the database using the new field-based model.
+ /// Get all active items from the database using the field-based model.
/// Delegates to ItemRepository for the actual query logic.
public func getAllItems() throws -> [Item] {
return try itemRepository.getAll()
}
- /// Get a single item by ID.
- /// - Parameter itemId: The UUID of the item to fetch
- /// - Returns: Item object or nil if not found
- public func getItemById(_ itemId: UUID) throws -> Item? {
- return try itemRepository.getById(itemId.uuidString.lowercased())
- }
-
- /// Get all items that have passkeys.
- public func getAllItemsWithPasskeys() throws -> [Item] {
- return try getAllItems().filter { $0.hasPasskey }
- }
-
- /// Get all unique email addresses from items.
- /// - Returns: Array of email addresses
- public func getAllItemEmailAddresses() throws -> [String] {
- return try itemRepository.getAllEmailAddresses()
- }
-
- /// Get recently deleted items (in trash).
- /// - Returns: Array of items
- public func getRecentlyDeletedItems() throws -> [Item] {
- return try itemRepository.getRecentlyDeleted()
- }
-
- /// Get count of items in trash.
- /// - Returns: Number of items in trash
- public func getRecentlyDeletedCount() throws -> Int {
- return try itemRepository.getRecentlyDeletedCount()
- }
-
- /// Get archived items.
- /// - Returns: Array of items
- public func getArchivedItems() throws -> [Item] {
- return try itemRepository.getArchived()
- }
-
- /// Get count of archived items.
- /// - Returns: Number of archived items
- public func getArchivedCount() throws -> Int {
- return try itemRepository.getArchivedCount()
- }
-
- /// Archive an item, hiding it from the main list and from autofill.
- /// - Parameter itemId: The UUID of the item to archive
- /// - Returns: Number of rows affected
- @discardableResult
- public func archiveItem(_ itemId: UUID) throws -> Int {
- return try itemRepository.archive(itemId.uuidString.lowercased())
- }
-
- /// Unarchive an item.
- /// - Parameter itemId: The UUID of the item to unarchive
- /// - Returns: Number of rows affected
- @discardableResult
- public func unarchiveItem(_ itemId: UUID) throws -> Int {
- return try itemRepository.unarchive(itemId.uuidString.lowercased())
- }
-
- /// Move an item to trash.
- /// - Parameter itemId: The UUID of the item to trash
- /// - Returns: Number of rows affected
- @discardableResult
- public func trashItem(_ itemId: UUID) throws -> Int {
- return try itemRepository.trash(itemId.uuidString.lowercased())
- }
-
- /// Restore an item from trash.
- /// - Parameter itemId: The UUID of the item to restore
- /// - Returns: Number of rows affected
- @discardableResult
- public func restoreItem(_ itemId: UUID) throws -> Int {
- return try itemRepository.restore(itemId.uuidString.lowercased())
- }
-
- /// Permanently delete an item.
- /// - Parameter itemId: The UUID of the item to permanently delete
- /// - Returns: Number of rows affected
- @discardableResult
- public func permanentlyDeleteItem(_ itemId: UUID) throws -> Int {
- return try itemRepository.permanentlyDelete(itemId.uuidString.lowercased())
- }
-
- /// Create a new item.
- /// - Parameter item: The item to create
- /// - Returns: The ID of the created item
- @discardableResult
- public func createItem(_ item: Item) throws -> String {
- return try itemRepository.create(item)
- }
-
- /// Update an existing item.
- /// - Parameter item: The item to update
- /// - Returns: Number of rows affected
- @discardableResult
- public func updateItem(_ item: Item) throws -> Int {
- 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.
@@ -247,11 +150,16 @@ extension VaultStore {
/// - 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.lowercased(),
- fieldKey: FieldKey.loginUrl,
- value: url
- )
+ try itemRepository.appendFieldValue(itemId: itemId.uuidString.lowercased(), fieldKey: FieldKey.loginUrl, value: url)
+ }
+
+ /// Record one use of an item in its ItemStats row. Runs in a transaction, so the vault is persisted and marked dirty.
+ /// - Parameters:
+ /// - itemId: The item that was used
+ /// - manifestId: The manifest the item belongs to, when the caller knows it
+ /// - action: What the user did with it
+ public func recordItemUsage(itemId: UUID, manifestId: String? = nil, action: ItemUsageAction) throws {
+ try itemStatsRepository.recordUsage(itemId: itemId.uuidString.lowercased(), manifestId: manifestId, action: action)
}
// MARK: - Autofill Credentials
@@ -266,34 +174,28 @@ extension VaultStore {
/// Convert an Item to an AutofillCredential for iOS Autofill.
private func convertItemToAutofillCredential(_ item: Item) -> AutofillCredential? {
// Load passkey for this item (gets first non-deleted passkey)
- let passkeys = try? getPasskeys(forItemId: item.id)
- let passkey = passkeys?.first
+ let passkey = (try? getPasskeys(forItemId: item.id, manifestId: item.manifestId))?.first
// Load the TOTP code for this item (gets first non-deleted TOTP code)
- let totpCode = try? getFirstTotpCode(forItemId: item.id)
+ let totpCode = (try? getFirstTotpCode(forItemId: item.id, manifestId: item.manifestId)) ?? nil
- return AutofillCredential(from: item, passkey: passkey, totp: totpCode ?? nil)
+ return AutofillCredential(from: item, passkey: passkey, totp: totpCode)
}
/// Get all items that have passkeys for passkey autofill.
public func getAllAutofillCredentialsWithPasskeys() throws -> [AutofillCredential] {
- var credentials = try getAllAutofillCredentials()
-
- // Filter to only include credentials that actually have a passkey
- credentials = credentials.filter { credential in
- return credential.hasPasskey
- }
-
- return credentials
+ return try getAllAutofillCredentials().filter { $0.hasPasskey }
}
// MARK: - TOTP Operations
/// Get the first TOTP code for a specific item.
- /// - Parameter itemId: The UUID of the item
+ /// - Parameters:
+ /// - itemId: The UUID of the item
+ /// - manifestId: The manifest the item belongs to, when the caller knows it
/// - Returns: Optional TotpCode if one exists
/// - Throws: Database errors
- public func getFirstTotpCode(forItemId itemId: UUID) throws -> TotpCode? {
- return try totpRepository.getFirstTotpCodeForItem(itemId)
+ public func getFirstTotpCode(forItemId itemId: UUID, manifestId: String? = nil) throws -> TotpCode? {
+ return try totpRepository.getFirstTotpCodeForItem(itemId, manifestId: manifestId)
}
}
diff --git a/apps/mobile-app/ios/VaultStoreKit/VaultStore+Sync.swift b/apps/mobile-app/ios/VaultStoreKit/VaultStore+Sync.swift
index 6bfd2afc1..242e89583 100644
--- a/apps/mobile-app/ios/VaultStoreKit/VaultStore+Sync.swift
+++ b/apps/mobile-app/ios/VaultStoreKit/VaultStore+Sync.swift
@@ -2,234 +2,48 @@ import Foundation
import VaultModels
import VaultUtils
-/// Vault sync through the Rust sync engine. Every decision (pull, merge, push, migrations) is mae by the shared Rust engine.
+/// The sync operations of the store, forwarded to VaultSync (the wrapper around the Rust sync engine).
extension VaultStore {
/// Full vault sync: status check, then pull (and merge) or push as the server and local revisions decide.
public func syncVaultWithServer(using webApiService: WebApiService) async -> VaultSyncResult {
- let startedAt = Date()
- setIsSyncing(true)
- defer {
- setIsSyncing(false)
- print("[VaultSync] Sync finished in \(VaultSyncRunLog.elapsedMs(since: startedAt))ms")
- }
-
- let wasDirty = getIsDirty()
- let result: [String: Any]
- do {
- result = try await VaultSyncEngine(vaultStore: self, webApiService: webApiService).run(operation: "fullSync")
- } catch {
- return failedSync(Self.driverError(error), wasOffline: getOfflineMode())
- }
-
- adoptSyncSideEffects(result)
-
- let wasOffline = result["wasOffline"] as? Bool ?? false
- guard result["success"] as? Bool == true else {
- return failedSync(Self.syncError(from: result), wasOffline: wasOffline)
- }
-
- if wasOffline {
- return VaultSyncResult(success: false, action: .error, newRevision: getCurrentVaultRevisionNumber(), wasOffline: true, error: AppError.networkError(underlyingError: NSError(domain: "VaultSync", code: 0)).code)
- }
-
- /*
- * A vault that still has to be upgraded is reported, never migrated here: the app routes it to the upgrade
- * page, which asks first when the migration signs out every other pre-format client (see migrateVaultManifest).
- */
- let hasNewVault = result["hasNewVault"] as? Bool ?? false
- let action: SyncAction = hasNewVault ? (wasDirty ? .merged : .downloaded) : (wasDirty ? .uploaded : .alreadyInSync)
- return VaultSyncResult(
- success: true,
- action: action,
- newRevision: getCurrentVaultRevisionNumber(),
- wasOffline: false,
- sqliteBlobUpgradeRequired: result["sqliteBlobUpgradeRequired"] as? Bool ?? false,
- manifestMigrationRequired: result["manifestMigrationRequired"] as? Bool ?? false
- )
+ return await sync.syncVaultWithServer(using: webApiService)
}
- /// Resolve the vault key right after login.
- public func resolveVaultKey(using webApiService: WebApiService, derivedKeyBase64: String) async throws -> String {
- let result: [String: Any]
- do {
- result = try await VaultSyncEngine(vaultStore: self, webApiService: webApiService).run(operation: "resolveVaultKey", encryptionKey: derivedKeyBase64)
- } catch {
- throw Self.driverError(error)
- }
- guard result["success"] as? Bool == true else {
- throw Self.syncError(from: result)
- }
- let key = result["encryptionKey"] as? String ?? derivedKeyBase64
- try storeEncryptionKey(base64Key: key)
- if let updates = result["sessionUpdates"] as? [String: Any], let privateKey = updates["accountPrivateKey"] as? String {
- accountPrivateKey = privateKey
- }
- return key
+ /// One status call: whether the server holds newer state than this device.
+ public func checkVaultVersion(using webApiService: WebApiService) async throws -> VaultVersionCheckResult {
+ return try await sync.checkVaultVersion(using: webApiService)
}
- /// Adopt the session key the engine reports.
- public func adoptEncryptionKey(base64Key: String) throws {
- if let current = encryptionKey, current == Data(base64Encoded: base64Key) {
- return
- }
- try storeEncryptionKey(base64Key: base64Key)
+ /// Resolve and store the vault key right after login from the password-derived key (see VaultSync.resolveVaultKey).
+ public func resolveVaultKey(using webApiService: WebApiService, derivedKeyBase64: String) async throws -> String {
+ return try await sync.resolveVaultKey(using: webApiService, derivedKeyBase64: derivedKeyBase64)
}
- /// Report a failed sync.
- private func failedSync(_ error: AppError, wasOffline: Bool) -> VaultSyncResult {
- print("[VaultSync] Sync failed (\(error.code)): \(error.message)")
- return VaultSyncResult(success: false, action: .error, newRevision: getCurrentVaultRevisionNumber(), wasOffline: wasOffline, error: error.code, errorMessage: error.message)
+ /// Classify the pending manifest migration (see VaultSync.getVaultMigrationStatus).
+ public func getVaultMigrationStatus(using webApiService: WebApiService) async throws -> String {
+ return try await sync.getVaultMigrationStatus(using: webApiService)
}
- /// Report an error thrown by the Rust core.
- private static func driverError(_ error: Error) -> AppError {
- if let appError = error as? AppError {
- return appError
- }
- return .syncEngineFailed(message: "\(error)")
+ /// Run the pending manifest migration and push it (see VaultSync.migrateVaultManifest).
+ public func migrateVaultManifest(using webApiService: WebApiService) async -> VaultMigrationResult {
+ return await sync.migrateVaultManifest(using: webApiService)
}
/// Push the pending local changes (after a native mutation such as an autofill link or a passkey creation).
public func mutateVault(using webApiService: WebApiService) async throws {
- let result = await syncVaultWithServer(using: webApiService)
- if !result.success && !result.wasOffline {
- throw AppError.vaultUploadFailed(message: result.errorMessage ?? result.error ?? "Vault sync failed")
- }
+ try await sync.mutateVault(using: webApiService)
}
- /// Check the server's vault revision number via a status check.
- public func checkVaultVersion(using webApiService: WebApiService) async throws -> VaultVersionCheckResult {
- let result: [String: Any]
- do {
- result = try await VaultSyncEngine(vaultStore: self, webApiService: webApiService).run(operation: "statusCheck")
- } catch {
- throw Self.driverError(error)
- }
-
- if let serverVersion = result["serverVersion"] as? String, !serverVersion.isEmpty {
- setServerVersion(serverVersion)
- }
- if result["isOffline"] as? Bool == true {
- setOfflineMode(true)
- throw AppError.serverUnavailable(statusCode: 0)
- }
- if result["requiresLogout"] as? Bool == true || result["success"] as? Bool != true {
- throw Self.syncError(from: result)
+ /// Adopt the session key the engine reports, unless it is the key already in memory.
+ public func adoptEncryptionKey(base64Key: String) throws {
+ if let current = encryptionKey, current == Data(base64Encoded: base64Key) {
+ return
}
- setOfflineMode(false)
- return VaultVersionCheckResult(isNewVersionAvailable: result["hasNewerVault"] as? Bool ?? false, syncState: getSyncState())
+ try storeEncryptionKey(base64Key: base64Key)
}
/// The logs of the recent sync engine runs as JSON text, newest first, for the developer tools.
public func getVaultSyncLogs() -> String {
return VaultSyncRunLog.persistedLogs(in: userDefaults)
}
-
- /// Persist sync results.
- private func adoptSyncSideEffects(_ result: [String: Any]) {
- if let serverVersion = result["serverVersion"] as? String, !serverVersion.isEmpty {
- setServerVersion(serverVersion)
- }
- if let offline = result["isOfflineMode"] as? Bool {
- setOfflineMode(offline)
- }
- if let updates = result["sessionUpdates"] as? [String: Any] {
- if let newKey = updates["encryptionKey"] as? String {
- try? adoptEncryptionKey(base64Key: newKey)
- }
- if let privateKey = updates["accountPrivateKey"] as? String {
- accountPrivateKey = privateKey
- }
- }
- if let routing = result["emailRouting"] as? [String: Any] {
- let metadata = VaultMetadata(
- publicEmailDomains: routing["publicEmailDomainList"] as? [String] ?? [],
- privateEmailDomains: routing["privateEmailDomainList"] as? [String] ?? [],
- hiddenPrivateEmailDomains: routing["hiddenPrivateEmailDomainList"] as? [String] ?? [],
- vaultRevisionNumber: result["pulledRevision"] as? Int ?? getCurrentVaultRevisionNumber()
- )
- if let data = try? JSONEncoder().encode(metadata), let json = String(data: data, encoding: .utf8) {
- try? storeMetadata(json)
- }
- }
- }
-
- /// Classify the pending manifest migration as the engine sees it: `none`, `schema-rebuild` (runs unattended) or
- /// `storage-format-upgrade` (the app asks first). A vault still on the sqlite-blob chain classifies as `none`.
- public func getVaultMigrationStatus(using webApiService: WebApiService) async throws -> String {
- let status: [String: Any]
- do {
- status = try await VaultSyncEngine(vaultStore: self, webApiService: webApiService).run(operation: "migrationStatus")
- } catch {
- throw Self.driverError(error)
- }
- return status["kind"] as? String ?? "storage-format-upgrade"
- }
-
- /// Bring the local vault onto the current storage model (a schema rebuild after an app update, or the one-time
- /// account-key upgrade of a legacy vault) and push it. Driven by the app's upgrade page only: a sync never runs
- /// it on its own, because the storage format move signs out every other client that predates the format.
- public func migrateVaultManifest(using webApiService: WebApiService) async -> VaultMigrationResult {
- let result: [String: Any]
- do {
- result = try await VaultSyncEngine(vaultStore: self, webApiService: webApiService).run(operation: "migrateManifest")
- } catch {
- return failedMigration(Self.driverError(error))
- }
- adoptSyncSideEffects(result)
- guard result["success"] as? Bool == true else {
- return failedMigration(Self.syncError(from: result))
- }
- let pushed = result["pushed"] as? Bool ?? false
- print("[VaultSync] Manifest migration complete: pushed=\(pushed)")
- return VaultMigrationResult(success: true, pushed: pushed)
- }
-
- /// A failed migration as the app reads it: the native error code plus the technical detail, logged once here.
- private func failedMigration(_ error: AppError) -> VaultMigrationResult {
- print("[VaultSync] Manifest migration failed (\(error.code)): \(error.message)")
- return VaultMigrationResult(success: false, pushed: false, error: error.code, errorMessage: error.message)
- }
-
- /// Report sync engine failure.
- private static func syncError(from result: [String: Any]) -> AppError {
- if let reason = result["errorKey"] as? String, let error = logoutErrors[reason] {
- return error
- }
- let message = result["error"] as? String ?? "Vault sync failed"
- let code = result["errorCode"] as? String ?? ""
- return (codedErrors[code] ?? { .unknownError(message: $0) })(message)
- }
-
- /// The forced logouts by the engine's reason.
- private static let logoutErrors: [String: AppError] = [
- "clientVersionNotSupported": .clientVersionNotSupported,
- "serverVersionNotSupported": .serverVersionNotSupported,
- "sessionExpired": .sessionExpired,
- "passwordChanged": .passwordChanged,
- "vaultVersionIncompatible": .vaultVersionIncompatible
- ]
-
- /// The native error for each engine error code, given the engine's message.
- private static let codedErrors: [String: (String) -> AppError] = [
- "E-202": { _ in .encryptionKeyNotFound },
- "E-203": { _ in .vaultDecryptFailed },
- "E-502": { .syncVaultFetchFailed(message: $0) },
- "E-503": { _ in .vaultDecryptFailed },
- "E-505": { _ in .serverUnavailable(statusCode: 0) },
- "E-506": { .serverError(message: $0) },
- "E-507": { .syncResponseInvalid(message: $0) },
- "E-508": { .syncCodecFailed(message: $0) },
- "E-509": { .syncEngineFailed(message: $0) },
- "E-601": { .storageReadFailed(message: $0) },
- "E-602": { .storageWriteFailed(message: $0) },
- "E-603": { .databaseInitFailed(message: $0) },
- "E-701": { .vaultMergeFailed(message: $0) },
- "E-702": { _ in .maxRetriesReached },
- "E-801": { .vaultUploadFailed(message: $0) },
- "E-804": { _ in .vaultTooLarge },
- "E-805": { _ in .timeout },
- "E-901": { .migrationCheckFailed(message: $0) },
- "E-903": { _ in .serverVersionNotSupported }
- ]
}
diff --git a/apps/mobile-app/ios/VaultStoreKit/VaultStore.swift b/apps/mobile-app/ios/VaultStoreKit/VaultStore.swift
index 0e89486af..1d9949833 100644
--- a/apps/mobile-app/ios/VaultStoreKit/VaultStore.swift
+++ b/apps/mobile-app/ios/VaultStoreKit/VaultStore.swift
@@ -50,6 +50,9 @@ public class VaultStore {
/// The key derivation parameters used to derive the encryption key from the password.
internal var keyDerivationParams: String?
+ /// The sync operations on this store (the wrapper around the Rust sync engine).
+ internal lazy var sync = VaultSync(vaultStore: self)
+
/// The timer for the auto-lock timeout.
private var clearCacheTimer: Timer?
diff --git a/apps/mobile-app/ios/VaultUI/Selection/CredentialProviderView.swift b/apps/mobile-app/ios/VaultUI/Selection/CredentialProviderView.swift
index ad323e451..034aba9e9 100644
--- a/apps/mobile-app/ios/VaultUI/Selection/CredentialProviderView.swift
+++ b/apps/mobile-app/ios/VaultUI/Selection/CredentialProviderView.swift
@@ -337,18 +337,24 @@ public class CredentialProviderViewModel: ObservableObject {
/// directly to `selectionHandler`.
private let urlLinker: ((UUID, String) async -> Void)?
+ /// Optional handler called with the item id right before a fill is handed to the host, so the
+ /// vault can record the use.
+ private let usageRecorder: ((UUID) -> Void)?
+
public init(
loader: @escaping () async throws -> [AutofillCredential],
selectionHandler: @escaping (String, String) -> Void,
cancelHandler: @escaping () -> Void,
serviceUrl: String? = nil,
- urlLinker: ((UUID, String) async -> Void)? = nil
+ urlLinker: ((UUID, String) async -> Void)? = nil,
+ usageRecorder: ((UUID) -> Void)? = nil
) {
self.loader = loader
self.selectionHandler = selectionHandler
self.cancelHandler = cancelHandler
self.serviceUrl = serviceUrl
self.urlLinker = urlLinker
+ self.usageRecorder = usageRecorder
if let url = serviceUrl {
self.searchText = url
}
@@ -403,7 +409,7 @@ public class CredentialProviderViewModel: ObservableObject {
let serviceUrl = serviceUrl,
!serviceUrl.isEmpty,
urlLinker != nil else {
- selectionHandler(username, password)
+ complete(credentialId: credential.id, username: username, password: password)
return
}
@@ -416,7 +422,7 @@ public class CredentialProviderViewModel: ObservableObject {
AutofillUrlNormalizer.comparisonKey(existing) == serviceKey
}
if alreadyLinked {
- selectionHandler(username, password)
+ complete(credentialId: credential.id, username: username, password: password)
return
}
@@ -443,7 +449,7 @@ public class CredentialProviderViewModel: ObservableObject {
Task { @MainActor in
await urlLinker(pending.credentialId, serviceUrl)
isLinkingUrl = false
- selectionHandler(pending.username, pending.password)
+ complete(credentialId: pending.credentialId, username: pending.username, password: pending.password)
}
}
@@ -454,7 +460,13 @@ public class CredentialProviderViewModel: ObservableObject {
return
}
pendingLinkSelection = nil
- selectionHandler(pending.username, pending.password)
+ complete(credentialId: pending.credentialId, username: pending.username, password: pending.password)
+ }
+
+ /// Complete a fill: record the use of the credential, then hand the values to the host.
+ private func complete(credentialId: UUID, username: String, password: String) {
+ usageRecorder?(credentialId)
+ selectionHandler(username, password)
}
func handleSelection(username: String, password: String) {
diff --git a/apps/mobile-app/ios/VaultUtils/DateHelpers.swift b/apps/mobile-app/ios/VaultUtils/DateHelpers.swift
index da98af455..e5fadee7a 100644
--- a/apps/mobile-app/ios/VaultUtils/DateHelpers.swift
+++ b/apps/mobile-app/ios/VaultUtils/DateHelpers.swift
@@ -13,13 +13,28 @@ import Foundation
* - Lexicographic sorting works correctly
*/
public class DateHelpers {
- /// Format a Date to the standard format string: "yyyy-MM-dd HH:mm:ss.SSS" (23 characters).
- public static func toStandardFormat(_ date: Date) -> String {
+ /// Date formatter for a given pattern.
+ private static func makeFormatter(_ pattern: String) -> DateFormatter {
let formatter = DateFormatter()
- formatter.dateFormat = "yyyy-MM-dd HH:mm:ss.SSS"
+ formatter.dateFormat = pattern
formatter.locale = Locale(identifier: "en_US_POSIX")
formatter.timeZone = TimeZone(secondsFromGMT: 0)
- return formatter.string(from: date)
+ return formatter
+ }
+
+ private static let standardFormatter = makeFormatter("yyyy-MM-dd HH:mm:ss.SSS")
+ private static let withoutMillisFormatter = makeFormatter("yyyy-MM-dd HH:mm:ss")
+ private static let birthDateFormatter = makeFormatter("yyyy-MM-dd 00:00:00")
+ private static let isoFormatter: ISO8601DateFormatter = {
+ let formatter = ISO8601DateFormatter()
+ formatter.formatOptions = [.withInternetDateTime, .withFractionalSeconds]
+ formatter.timeZone = TimeZone(secondsFromGMT: 0)
+ return formatter
+ }()
+
+ /// Format a Date to the standard format string: "yyyy-MM-dd HH:mm:ss.SSS" (23 characters).
+ public static func toStandardFormat(_ date: Date) -> String {
+ return standardFormatter.string(from: date)
}
/// Format the current UTC time to the standard format string.
@@ -30,11 +45,7 @@ public class DateHelpers {
/// Format a Date to the birth date format (no milliseconds, time set to 00:00:00).
/// Format: "yyyy-MM-dd 00:00:00" (19 characters).
public static func toBirthDateFormat(_ date: Date) -> String {
- let formatter = DateFormatter()
- formatter.dateFormat = "yyyy-MM-dd 00:00:00"
- formatter.locale = Locale(identifier: "en_US_POSIX")
- formatter.timeZone = TimeZone(secondsFromGMT: 0)
- return formatter.string(from: date)
+ return birthDateFormatter.string(from: date)
}
/// Parse a date string to a Date object for use in queries.
@@ -43,48 +54,22 @@ public class DateHelpers {
/// - "yyyy-MM-dd HH:mm:ss" (standard format without milliseconds)
/// - ISO8601 with fractional seconds and timezone
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) {
+ if let isoDate = isoFormatter.date(from: cleanedDateString) {
return isoDate
}
}
// Try parsing with milliseconds
- if let dateWithMillis = StaticFormatters.formatterWithMillis.date(from: cleanedDateString) {
+ if let dateWithMillis = standardFormatter.date(from: cleanedDateString) {
return dateWithMillis
}
// Try parsing without milliseconds
- if let dateWithoutMillis = StaticFormatters.formatterWithoutMillis.date(from: cleanedDateString) {
+ if let dateWithoutMillis = withoutMillisFormatter.date(from: cleanedDateString) {
return dateWithoutMillis
}