Privacy-first password manager with built-in email aliasing. Fully encrypted and self-hostable.
import Foundation
import VaultModels
import VaultUtils
/// Extension for the VaultStore class to handle metadata management
extension VaultStore {
/// Store the metadata - the metadata for the vault
public func storeMetadata(_ metadata: String) throws {
userDefaults.set(metadata, forKey: VaultConstants.vaultMetadataKey)
userDefaults.synchronize()
}
/// Get the metadata - the metadata for the vault
public func getVaultMetadata() -> String? {
return userDefaults.string(forKey: VaultConstants.vaultMetadataKey)
}
/// Get the metadata object - the metadata for the vault
internal func getVaultMetadataObject() -> VaultMetadata? {
guard let jsonString = getVaultMetadata(),
let data = jsonString.data(using: .utf8),
let metadata = try? JSONDecoder().decode(VaultMetadata.self, from: data) else {
return nil
}
return metadata
}
/// Get the current vault revision number - the revision number of the vault
public func getCurrentVaultRevisionNumber() -> Int {
guard let metadata = getVaultMetadataObject() else {
return 0
}
return metadata.vaultRevisionNumber
}
/// Set the current vault revision number - the revision number of the vault
public func setCurrentVaultRevisionNumber(_ revisionNumber: Int) {
var metadata: VaultMetadata
if let existingMetadata = getVaultMetadataObject() {
metadata = existingMetadata
} else {
metadata = VaultMetadata(
publicEmailDomains: [],
privateEmailDomains: [],
hiddenPrivateEmailDomains: [],
vaultRevisionNumber: revisionNumber
)
}
metadata.vaultRevisionNumber = revisionNumber
if let data = try? JSONEncoder().encode(metadata),
let jsonString = String(data: data, encoding: .utf8) {
userDefaults.set(jsonString, forKey: VaultConstants.vaultMetadataKey)
userDefaults.synchronize()
}
}
/// The id of the user's personal manifest as the last sync recorded it, or nil before the first pull.
public func getPersonalManifestId() -> String? {
return VaultSyncEngine.persistedState(forKey: VaultSyncEngine.personalManifestIdStateKey, in: userDefaults) as? String
}
// MARK: - Username Storage
/// Store the username
public func setUsername(_ username: String) {
userDefaults.set(username, forKey: VaultConstants.usernameKey)
userDefaults.synchronize()
}
/// Get the username
public func getUsername() -> String? {
return userDefaults.string(forKey: VaultConstants.usernameKey)
}
/// Clear the username
public func clearUsername() {
userDefaults.removeObject(forKey: VaultConstants.usernameKey)
userDefaults.synchronize()
}
// MARK: - Offline Mode Storage
/// Set offline mode flag
public func setOfflineMode(_ isOffline: Bool) {
userDefaults.set(isOffline, forKey: VaultConstants.offlineModeKey)
userDefaults.synchronize()
}
/// Get offline mode flag
public func getOfflineMode() -> Bool {
return userDefaults.bool(forKey: VaultConstants.offlineModeKey)
}
// MARK: - Server Version Storage
/// Set the server API version
public func setServerVersion(_ version: String) {
userDefaults.set(version, forKey: VaultConstants.serverVersionKey)
userDefaults.synchronize()
}
/// Get the server API version
public func getServerVersion() -> String? {
return userDefaults.string(forKey: VaultConstants.serverVersionKey)
}
/// Clear the server version
public func clearServerVersion() {
userDefaults.removeObject(forKey: VaultConstants.serverVersionKey)
userDefaults.synchronize()
}
// MARK: - Capabilities Storage
/// Set the capabilities the server resolved for this account, as a JSON object
public func setCapabilities(_ json: String) {
userDefaults.set(json, forKey: VaultConstants.capabilitiesKey)
}
/// Get the capabilities the server resolved for this account, as a JSON object
public func getCapabilities() -> String? {
return userDefaults.string(forKey: VaultConstants.capabilitiesKey)
}
// MARK: - Sync State Storage (isDirty, mutationSequence, isSyncing)
/// Set the dirty flag indicating local changes need to be synced. Clearing it forgets the pending scopes
/// with it, since a clean vault has nothing left to push.
public func setIsDirty(_ isDirty: Bool) {
userDefaults.set(isDirty, forKey: VaultConstants.isDirtyKey)
if !isDirty {
userDefaults.removeObject(forKey: VaultConstants.dirtyScopesKey)
}
userDefaults.synchronize()
}
/// Mark the vault dirty and record what the mutation touched, so the next sync can push only that scope.
/// - Parameter scope: The mutation scope, defaulting to a full-manifest change
public func markDirty(scope: String = VaultMutationScope.main) {
setIsDirty(true)
addDirtyScope(scope)
}
/// The mutation scopes that have pending changes.
public func getDirtyScopes() -> [String] {
return userDefaults.stringArray(forKey: VaultConstants.dirtyScopesKey) ?? []
}
/// Record one scope as having pending changes.
/// - Parameter scope: The mutation scope; an unknown one counts as a full-manifest change
public func addDirtyScope(_ scope: String) {
let known = VaultMutationScope.known(scope)
var scopes = getDirtyScopes()
guard !scopes.contains(known) else {
return
}
scopes.append(known)
userDefaults.set(scopes, forKey: VaultConstants.dirtyScopesKey)
userDefaults.synchronize()
}
/// The random id of this install, created on first use and shared by the app and the autofill extension.
/// Per-device vault rows (item usage statistics) are keyed by it.
public func getOrCreateDeviceId() -> String {
if let deviceId = userDefaults.string(forKey: VaultConstants.deviceIdKey), !deviceId.isEmpty {
return deviceId
}
let deviceId = UUID().uuidString.lowercased()
userDefaults.set(deviceId, forKey: VaultConstants.deviceIdKey)
return deviceId
}
/// Get the dirty flag
public func getIsDirty() -> Bool {
return userDefaults.bool(forKey: VaultConstants.isDirtyKey)
}
/// Get the current mutation sequence number
public func getMutationSequence() -> Int {
return userDefaults.integer(forKey: VaultConstants.mutationSequenceKey)
}
/// Set the mutation sequence number
public func setMutationSequence(_ sequence: Int) {
userDefaults.set(sequence, forKey: VaultConstants.mutationSequenceKey)
userDefaults.synchronize()
}
/// Increment the mutation sequence and return the new value
public func incrementMutationSequence() -> Int {
let current = getMutationSequence()
let newValue = current + 1
setMutationSequence(newValue)
return newValue
}
/// Set the syncing flag
public func setIsSyncing(_ isSyncing: Bool) {
userDefaults.set(isSyncing, forKey: VaultConstants.isSyncingKey)
userDefaults.synchronize()
}
/// Get the syncing flag
public func getIsSyncing() -> Bool {
return userDefaults.bool(forKey: VaultConstants.isSyncingKey)
}
/// Get the complete sync state
public func getSyncState() -> SyncStateResult {
return SyncStateResult(
isDirty: getIsDirty(),
dirtyScopes: getDirtyScopes(),
mutationSequence: getMutationSequence(),
serverRevision: getCurrentVaultRevisionNumber(),
isSyncing: getIsSyncing()
)
}
/// Store encrypted vault with sync state atomically.
/// Two modes:
/// 1. markDirty=true: Local mutation - always succeeds, increments mutation sequence
/// 2. expectedMutationSeq provided: Sync operation - only succeeds if no mutations happened
///
/// - Parameters:
/// - encryptedVault: The encrypted vault blob
/// - markDirty: If true, marks vault as dirty and increments mutation sequence
/// - serverRevision: Optional server revision to set
/// - expectedMutationSeq: If provided, only store if current sequence matches
/// - scope: What the mutation touched, when it marks the vault dirty
/// - Returns: (success, mutationSequence) - success=false if expectedMutationSeq didn't match
public func storeEncryptedVaultWithSyncState(
encryptedVault: String,
markDirty: Bool = false,
serverRevision: Int? = nil,
expectedMutationSeq: Int? = nil,
scope: String = VaultMutationScope.main
) throws -> (success: Bool, mutationSequence: Int) {
var mutationSequence = getMutationSequence()
// Race detection for sync operations
if let expectedSeq = expectedMutationSeq, expectedSeq != mutationSequence {
return (success: false, mutationSequence: mutationSequence)
}
if markDirty {
mutationSequence += 1
}
// Store vault and sync state atomically
try storeEncryptedDatabase(encryptedVault)
if markDirty {
setMutationSequence(mutationSequence)
self.markDirty(scope: scope)
}
if let revision = serverRevision {
setCurrentVaultRevisionNumber(revision)
}
return (success: true, mutationSequence: mutationSequence)
}
/// Mark the vault as clean after successful sync.
/// Only clears dirty flag if no mutations happened during sync.
///
/// - Parameters:
/// - mutationSeqAtStart: The mutation sequence when sync started
/// - newServerRevision: The new server revision after successful upload
/// - Returns: Whether the dirty flag was cleared
public func markVaultClean(mutationSeqAtStart: Int, newServerRevision: Int) -> Bool {
let currentMutationSeq = getMutationSequence()
// Always update server revision
setCurrentVaultRevisionNumber(newServerRevision)
if currentMutationSeq == mutationSeqAtStart {
// No mutations during sync - safe to mark as clean
setIsDirty(false)
return true
}
// Mutations happened during sync - keep dirty
return false
}
/// Clear all sync state (used on logout)
public func clearSyncState() {
userDefaults.removeObject(forKey: VaultConstants.isDirtyKey)
userDefaults.removeObject(forKey: VaultConstants.dirtyScopesKey)
userDefaults.removeObject(forKey: VaultConstants.mutationSequenceKey)
userDefaults.removeObject(forKey: VaultConstants.isSyncingKey)
userDefaults.synchronize()
}
}