SPB Git

Repository Public

Vault.swift 22.4 KB 521 lines swift

1// =============================================================================2//                  SP BOUCHER | SOFTWARE & RESEARCH3//             ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4// =============================================================================5//6// Project          : SP ID & Card Vault7// File             : SPVault/Core/Security/Vault.swift8// Module           : SPVault9// Repository       : https://git.spboucher.ai/sp-id-card-vault10// Project Website  : Not specified11// Created          : 2026-12-0212// Last Modified    : 2026-12-0213//14// Author           : Simon-Pierre Boucher15// Position         : Professor of Finance16// Institution      : Université du Québec en Outaouais (UQO)17// Organization     : SP Boucher18// Website          : https://spboucher.ai19// Git              : https://git.spboucher.ai20//21// Preferred Contact: contact@spboucher.ai22// Development      : dev@spboucher.ai23// Support          : support@spboucher.ai24// Security/Admin   : admin@spboucher.ai25//26// Copyright (c) 202627// Simon-Pierre Boucher28// All rights reserved where applicable. This file is governed by the29// applicable project license, copyright notices and relevant law.30// Existing third-party rights and notices remain unaffected.31//32// License          : None specified (no license file in this repository)33//34// Do not embed credentials, private keys, access tokens,35// certificates or confidential personal information.36//37// =============================================================================38// END OF SP BOUCHER SOURCE HEADER39// =============================================================================4041import CryptoKit42import Foundation43import Observation44import UIKit4546enum VaultState: Equatable, Sendable {47    case loading48    /// No vault on this device yet: onboarding.49    case noVault50    case locked51    /// The vault files exist but the Keychain key is gone (biometric set changed,52    /// or the app was restored without its Keychain): recovery is required.53    case keyInvalidated54    case unlocked55}5657enum VaultError: Error, Equatable {58    case locked59    case weakPassphrase60    case biometryRequired(BiometryState)61}6263enum RestoreMode: Sendable { case merge, replace }6465/// Facts shown by the Security Center. Every value is measured when the report is66/// built; none is a constant.67struct SecurityReport: Sendable, Equatable {68    var biometry: BiometryState69    var keyPresent: Bool70    var keyProtection: String71    var cardCount: Int72    var damagedCards: Int73    var storage: StorageReport74    var recoveryConfigured: Bool75    var recoveryIterations: UInt32?76    var lastBackupAt: Date?77    var vaultCreatedAt: Date?78    var formatVersion: Int?79    /// Result of sealing and reopening a probe with the live key, plus a tamper check.80    var encryptionSelfTestPassed: Bool81}8283/// SP Vault Security Engine: owns the master key while the vault is unlocked and84/// is the only path to card data. Locking drops the key, the decrypted records,85/// the search index and every decoded image.86@MainActor87@Observable88final class Vault {89    private(set) var state: VaultState = .loading90    private(set) var cards: [Card] = []91    private(set) var customCategories: [CardCategory] = []92    private(set) var lastBackupAt: Date?93    private(set) var damagedCardIDs: [UUID] = []94    /// Bumped whenever a card's photograph changes, so views reload it.95    private(set) var imageRevision = 09697    @ObservationIgnored let repository: VaultRepository98    @ObservationIgnored let protector: any KeyProtector99    @ObservationIgnored var reminders: (any ExpiryReminderScheduling)?100    @ObservationIgnored private var masterKey: SymmetricKey?101    @ObservationIgnored private var manifest = VaultManifest()102    @ObservationIgnored private var index = SearchIndex()103    @ObservationIgnored private let imageCache = NSCache<NSString, UIImage>()104    /// Lower PBKDF2 cost for unit tests only; the app always uses the default.105    @ObservationIgnored var kdfIterations = KDFParameters.defaultIterations106107    init(repository: VaultRepository = VaultRepository(), protector: any KeyProtector = KeyProtectors.platformDefault()) {108        self.repository = repository109        self.protector = protector110        imageCache.totalCostLimit = 160 * 1024 * 1024111    }112113    var categories: [CardCategory] { CardCategory.builtIn + customCategories }114    var isUnlocked: Bool { state == .unlocked }115    var biometry: BiometryState { protector.biometryState() }116117    func category(id: String) -> CardCategory {118        categories.first { $0.id == id } ?? .other119    }120121    // MARK: State122123    /// Decides the starting state from what is really on disk and in the Keychain.124    func bootstrap() {125        guard state == .loading || state == .noVault else { return }126        if repository.exists {127            state = protector.masterKeyExists() ? .locked : .keyInvalidated128        } else {129            try? protector.deleteMasterKey()   // stale key of a previous install130            state = .noVault131        }132    }133134    /// Re-checks the Keychain while locked: a key that disappeared (biometric set135    /// changed) moves the vault to `.keyInvalidated`.136    func refreshLockState() {137        guard state == .locked || state == .keyInvalidated else { return }138        state = protector.masterKeyExists() ? .locked : .keyInvalidated139    }140141    /// Creates the vault: random master key → Keychain (biometric), optional142    /// recovery wrap, empty encrypted manifest. Ends unlocked.143    func createVault(recoveryPassphrase: String?) async throws {144        guard protector.biometryState().isAvailable else { throw VaultError.biometryRequired(protector.biometryState()) }145        if let recoveryPassphrase, !PassphrasePolicy.isAcceptable(recoveryPassphrase) { throw VaultError.weakPassphrase }146        let key = VaultCrypto.randomKey()147        try protector.storeMasterKey(VaultCrypto.keyData(key))148        let repository = repository, iterations = kdfIterations149        do {150            try await Task.detached { _ = try repository.create(masterKey: key, recoveryPassphrase: recoveryPassphrase, kdfIterations: iterations) }.value151        } catch {152            try? protector.deleteMasterKey()153            repository.destroy()154            throw error155        }156        try await open(with: key)157    }158159    /// Face ID → Keychain → master key → decrypt. Throws `KeyProtectorError`.160    func unlock(reason: String = "Unlock your vault") async throws {161        guard state == .locked || state == .keyInvalidated else { return }162        do {163            let data = try await protector.loadMasterKey(reason: reason)164            try await open(with: SymmetricKey(data: data))165        } catch KeyProtectorError.keyInvalidated {166            state = .keyInvalidated167            throw KeyProtectorError.keyInvalidated168        }169    }170171    private func open(with key: SymmetricKey) async throws {172        let repository = repository173        let (manifest, loaded, index) = try await Task.detached(priority: .userInitiated) {174            repository.removeStagingLeftovers()175            let manifest = try repository.loadManifest(masterKey: key)   // also proves the key is the right one176            let loaded = try repository.loadAllCards(masterKey: key)177            let index = try? repository.loadSearchIndex(masterKey: key)178            return (manifest, loaded, index)179        }.value180        masterKey = key181        self.manifest = manifest182        customCategories = manifest.customCategories183        lastBackupAt = manifest.lastBackupAt184        damagedCardIDs = loaded.damaged185        cards = Self.ordered(loaded.cards, by: manifest.order)186        if let index, Set(index.entries.keys) == Set(cards.map(\.id)) {187            self.index = index188        } else {189            rebuildIndex()190        }191        state = .unlocked192        reminders?.reschedule(for: cards)193    }194195    private static func ordered(_ cards: [Card], by order: [UUID]) -> [Card] {196        let position = Dictionary(order.enumerated().map { ($1, $0) }, uniquingKeysWith: { first, _ in first })197        return cards.sorted {198            let a = position[$0.id] ?? Int.max, b = position[$1.id] ?? Int.max199            return a != b ? a < b : $0.createdAt < $1.createdAt200        }201    }202203    /// Drops every secret held in memory. Called when the app leaves the foreground.204    func lock() {205        guard state == .unlocked else { return }206        masterKey = nil207        cards = []208        customCategories = []209        damagedCardIDs = []210        manifest = VaultManifest()211        index = SearchIndex()212        imageCache.removeAllObjects()213        state = .locked214    }215216    /// Fresh biometric check before revealing a full number or exporting. It goes217    /// through the Keychain again and compares the key: it is not a UI flag.218    func reauthenticate(reason: String) async -> Bool {219        guard let masterKey else { return false }220        guard let data = try? await protector.loadMasterKey(reason: reason) else { return false }221        return data == VaultCrypto.keyData(masterKey)222    }223224    /// Lost biometric access: unwrap the master key with the recovery passphrase,225    /// then bind it to the *current* biometric set again.226    func recover(passphrase: String) async throws {227        guard protector.biometryState().isAvailable else { throw VaultError.biometryRequired(protector.biometryState()) }228        let repository = repository229        let key = try await Task.detached(priority: .userInitiated) { try repository.recoverMasterKey(passphrase: passphrase) }.value230        try protector.storeMasterKey(VaultCrypto.keyData(key))231        try await open(with: key)232    }233234    /// Erases the vault and its key. The caller must have re-authenticated.235    func eraseEverything() {236        lock()237        try? protector.deleteMasterKey()238        repository.destroy()239        imageCache.removeAllObjects()240        reminders?.reschedule(for: [])241        state = .noVault242    }243244    private func requireKey() throws -> SymmetricKey {245        guard let masterKey else { throw VaultError.locked }246        return masterKey247    }248249    // MARK: Cards250251    private func persistManifest() throws {252        manifest.order = cards.map(\.id)253        manifest.customCategories = customCategories254        manifest.lastBackupAt = lastBackupAt255        try repository.saveManifest(manifest, masterKey: try requireKey())256    }257258    private func rebuildIndex() {259        var fresh = SearchIndex()260        for card in cards { fresh.index(card, categoryName: category(id: card.categoryID).name) }261        index = fresh262        persistIndex()263    }264265    private func persistIndex() {266        guard let masterKey else { return }267        try? repository.saveSearchIndex(index, masterKey: masterKey)268    }269270    func add(_ card: Card, images: CardImages) async throws {271        let key = try requireKey()272        var card = SensitiveDataPolicy.sanitized(card)273        try SensitiveDataPolicy.validate(card)274        card.hasBack = images.back != nil275        card.modifiedAt = Date()276        let repository = repository, stored = card277        try await Task.detached(priority: .userInitiated) { try repository.insert(stored, images: images, masterKey: key) }.value278        cards.insert(card, at: 0)279        index.index(card, categoryName: category(id: card.categoryID).name)280        try persistManifest()281        persistIndex()282        reminders?.reschedule(for: cards)283    }284285    func update(_ card: Card) throws {286        let key = try requireKey()287        try SensitiveDataPolicy.validate(card)288        guard let position = cards.firstIndex(where: { $0.id == card.id }) else { throw VaultStorageError.cardNotFound }289        var card = card290        card.modifiedAt = Date()291        try repository.update(card, masterKey: key)292        cards[position] = card293        index.index(card, categoryName: category(id: card.categoryID).name)294        persistIndex()295        reminders?.reschedule(for: cards)296    }297298    func toggleFavorite(_ id: UUID) {299        guard var card = cards.first(where: { $0.id == id }) else { return }300        card.isFavorite.toggle()301        try? update(card)302    }303304    /// Replaces (or with `nil`, removes) the photograph of one side.305    func setImage(_ image: Data?, thumbnail: Data?, side: CardSide, for id: UUID) throws {306        let key = try requireKey()307        guard var card = cards.first(where: { $0.id == id }) else { throw VaultStorageError.cardNotFound }308        try repository.setImage(image, thumbnail: thumbnail, side: side, cardID: id, masterKey: key)309        if side == .back { card.hasBack = image != nil }310        for thumb in [true, false] { imageCache.removeObject(forKey: cacheKey(id, side, thumb)) }311        imageRevision += 1312        try update(card)313    }314315    func delete(_ id: UUID) throws {316        _ = try requireKey()317        try repository.delete(id)318        cards.removeAll { $0.id == id }319        damagedCardIDs.removeAll { $0 == id }320        index.remove(id)321        for side in [CardSide.front, .back] {322            for thumb in [true, false] { imageCache.removeObject(forKey: cacheKey(id, side, thumb)) }323        }324        try persistManifest()325        persistIndex()326        reminders?.reschedule(for: cards)327    }328329    func move(fromOffsets: IndexSet, toOffset: Int) {330        cards.move(fromOffsets: fromOffsets, toOffset: toOffset)331        try? persistManifest()332    }333334    /// Reorders by moving one card to the position of another (drag and drop).335    func move(_ id: UUID, before target: UUID) {336        guard id != target, let from = cards.firstIndex(where: { $0.id == id }),337              let to = cards.firstIndex(where: { $0.id == target }) else { return }338        let card = cards.remove(at: from)339        cards.insert(card, at: to)340        try? persistManifest()341    }342343    // MARK: Categories344345    func addCategory(name: String, symbol: String, tint: RGB) throws {346        _ = try requireKey()347        let trimmed = name.trimmingCharacters(in: .whitespacesAndNewlines)348        guard !trimmed.isEmpty else { return }349        customCategories.append(CardCategory(id: "custom-" + UUID().uuidString.lowercased(), name: trimmed,350                                             symbol: symbol, tint: tint, isBuiltIn: false))351        try persistManifest()352    }353354    func renameCategory(id: String, name: String) throws {355        guard let position = customCategories.firstIndex(where: { $0.id == id }) else { return }356        customCategories[position].name = name357        try persistManifest()358        rebuildIndex()359    }360361    /// Removes a custom category; its cards go back to the category of their kind.362    func removeCategory(id: String) throws {363        guard customCategories.contains(where: { $0.id == id }) else { return }364        for card in cards where card.categoryID == id {365            var moved = card366            moved.categoryID = card.kind.categoryID367            try update(moved)368        }369        customCategories.removeAll { $0.id == id }370        try persistManifest()371    }372373    // MARK: Images374375    private func cacheKey(_ id: UUID, _ side: CardSide, _ thumbnail: Bool) -> NSString {376        "\(id.uuidString)/\(side.rawValue)/\(thumbnail ? "t" : "f")" as NSString377    }378379    func cachedImage(for id: UUID, side: CardSide, thumbnail: Bool) -> UIImage? {380        imageCache.object(forKey: cacheKey(id, side, thumbnail))381    }382383    /// Decrypts and decodes a photograph off the main thread. The clear bytes384    /// exist only in memory and are dropped at lock.385    func image(for id: UUID, side: CardSide, thumbnail: Bool) async -> UIImage? {386        let cacheKey = cacheKey(id, side, thumbnail)387        if let cached = imageCache.object(forKey: cacheKey) { return cached }388        guard let key = masterKey else { return nil }389        let repository = repository390        let image = await Task.detached(priority: .userInitiated) { () -> UIImage? in391            guard let data = try? repository.loadImage(cardID: id, side: side, thumbnail: thumbnail, masterKey: key),392                  let image = UIImage(data: data) else { return nil }393            return await image.byPreparingForDisplay() ?? image394        }.value395        guard let image, masterKey != nil else { return nil }   // locked meanwhile: keep nothing396        let cost = Int(image.size.width * image.scale * image.size.height * image.scale * 4)397        imageCache.setObject(image, forKey: cacheKey, cost: cost)398        return image399    }400401    // MARK: Search402403    func search(_ query: String) -> [Card] {404        let byID = Dictionary(uniqueKeysWithValues: cards.map { ($0.id, $0) })405        return index.search(query).compactMap { byID[$0] }406    }407408    // MARK: Backup and restore409410    /// Builds a `.spvault` file in the temporary directory. It contains only411    /// ciphertext; the caller hands it to the system exporter and removes it.412    func exportBackup(passphrase: String) async throws -> URL {413        let key = try requireKey()414        guard PassphrasePolicy.isAcceptable(passphrase) else { throw VaultError.weakPassphrase }415        let repository = repository, cards = cards, iterations = kdfIterations416        var manifest = manifest417        manifest.order = cards.map(\.id)418        let now = Date()419        let frozenManifest = manifest420        let url = try await Task.detached(priority: .userInitiated) {421            var entries: [BackupCard] = []422            for card in cards {423                let front = try repository.loadImage(cardID: card.id, side: .front, thumbnail: false, masterKey: key)424                let frontThumb = try repository.loadImage(cardID: card.id, side: .front, thumbnail: true, masterKey: key)425                let back = try? repository.loadImage(cardID: card.id, side: .back, thumbnail: false, masterKey: key)426                let backThumb = try? repository.loadImage(cardID: card.id, side: .back, thumbnail: true, masterKey: key)427                entries.append(BackupCard(card: card, front: front, frontThumbnail: frontThumb, back: back, backThumbnail: backThumb))428            }429            let file = try BackupArchive.encode(BackupContents(createdAt: now, manifest: frozenManifest, cards: entries),430                                                passphrase: passphrase, iterations: iterations)431            let stamp = now.formatted(Date.ISO8601FormatStyle(timeZone: .current).year().month().day().dateSeparator(.dash))432            let directory = URL.temporaryDirectory.appending(path: "export-\(UUID().uuidString)", directoryHint: .isDirectory)433            try FileManager.default.createDirectory(at: directory, withIntermediateDirectories: true)434            let url = directory.appending(path: "SP Vault \(stamp).\(BackupArchive.fileExtension)")435            try file.write(to: url, options: [.atomic, .completeFileProtection])436            return url437        }.value438        lastBackupAt = now439        try persistManifest()440        return url441    }442443    /// Restores a verified backup into the unlocked vault. Every card is444    /// re-encrypted under a new key of this device. Returns how many were written.445    @discardableResult446    func restoreBackup(_ file: Data, passphrase: String, mode: RestoreMode) async throws -> Int {447        let key = try requireKey()448        let contents = try await Task.detached(priority: .userInitiated) { try BackupArchive.decode(file, passphrase: passphrase) }.value449        if mode == .replace {450            for card in cards { try repository.delete(card.id) }451            cards = []452            customCategories = []453            imageCache.removeAllObjects()454        }455        for category in contents.manifest.customCategories where !customCategories.contains(where: { $0.id == category.id }) {456            customCategories.append(category)457        }458        let repository = repository459        var restored: [Card] = []460        for entry in contents.cards {461            let card = SensitiveDataPolicy.sanitized(entry.card)462            let images = CardImages(front: entry.front, frontThumbnail: entry.frontThumbnail, back: entry.back,463                                    backThumbnail: entry.backThumbnail)464            try await Task.detached(priority: .userInitiated) { try repository.insert(card, images: images, masterKey: key) }.value465            restored.append(card)466        }467        let restoredIDs = Set(restored.map(\.id))468        let merged = cards.filter { !restoredIDs.contains($0.id) } + restored469        cards = Self.ordered(merged, by: cards.map(\.id) + contents.manifest.order)470        manifest.lastRestoreAt = Date()471        imageCache.removeAllObjects()472        imageRevision += 1473        try persistManifest()474        rebuildIndex()475        reminders?.reschedule(for: cards)476        return restored.count477    }478479    // MARK: Recovery passphrase480481    var recoveryConfigured: Bool { (try? repository.readHeader())?.recoveryKDF != nil }482483    func setRecoveryPassphrase(_ passphrase: String?) async throws {484        let key = try requireKey()485        if let passphrase, !PassphrasePolicy.isAcceptable(passphrase) { throw VaultError.weakPassphrase }486        let repository = repository, iterations = kdfIterations487        try await Task.detached(priority: .userInitiated) {488            try repository.setRecovery(passphrase: passphrase, masterKey: key, kdfIterations: iterations)489        }.value490    }491492    // MARK: Security Center493494    func securityReport() -> SecurityReport {495        let header = try? repository.readHeader()496        var selfTest = false497        if let masterKey {498            let probe = Data("spvault-self-test".utf8), context = Data("probe".utf8)499            if let sealed = try? SealedBlob.seal(probe, key: masterKey, kind: .metadata, context: context),500               (try? SealedBlob.open(sealed, key: masterKey, kind: .metadata, context: context)) == probe {501                var tampered = sealed502                tampered[tampered.count - 20] ^= 0x01503                selfTest = (try? SealedBlob.open(tampered, key: masterKey, kind: .metadata, context: context)) == nil504            }505        }506        return SecurityReport(biometry: protector.biometryState(), keyPresent: protector.masterKeyExists(),507                              keyProtection: protector.protectionDescription, cardCount: cards.count,508                              damagedCards: damagedCardIDs.count, storage: repository.storageReport(),509                              recoveryConfigured: header?.recoveryKDF != nil,510                              recoveryIterations: header?.recoveryKDF?.iterations, lastBackupAt: lastBackupAt,511                              vaultCreatedAt: header?.createdAt, formatVersion: header?.formatVersion,512                              encryptionSelfTestPassed: selfTest)513    }514}515516/// Implemented by the notification layer; the vault only says "cards changed".517@MainActor518protocol ExpiryReminderScheduling: AnyObject {519    func reschedule(for cards: [Card])520}521
Files main
Menu

Theme