SPB Git

Repository Public

AutoFillModel.swift 8.8 KB 182 lines swift

1// SP Vault AutoFill — state of one credential request, from the system's call to the answer.2// Lives in Core (compiled into the app too) only so that the app's unit tests can drive it; the app never uses it.3import Foundation4import Observation5import SharedVaultKit67@MainActor8@Observable9final class AutoFillModel {10    struct PasskeyParameters: Sendable, Equatable {11        let relyingParty: String12        let clientDataHash: Data13        let allowedCredentialIDs: [Data]14    }1516    enum Request: Sendable, Equatable {17        case password(recordIdentifier: String?, service: AutoFillCore.Service, user: String)18        case oneTimeCode(recordIdentifier: String?, service: AutoFillCore.Service, label: String)19        case passkeyAssertion(relyingParty: String, credentialID: Data, recordIdentifier: String?, clientDataHash: Data, userName: String)20        case list(services: [AutoFillCore.Service], mode: AutoFillCore.ListMode, passkey: PasskeyParameters?)21        case registration(relyingParty: String, userName: String, userHandle: Data, clientDataHash: Data, algorithms: [Int], excluded: [Data])22    }2324    enum Stage: Equatable { case idle, prompt, unlocking, list, failed(String) }25    enum CancelReason: Sendable { case userCanceled, failed, notFound }2627    struct PendingConfirmation: Identifiable, Equatable {28        let id = UUID()29        let row: AutoFillCore.Row30        let text: AutoFillCore.Confirmation31    }3233    private(set) var request: Request?34    private(set) var stage: Stage = .idle35    private(set) var vault: UnlockedVault?36    private(set) var failureReason: CancelReason = .failed37    /// The unlock in progress (awaited by tests).38    @ObservationIgnored private(set) var flow: Task<Void, Never>?39    var query = ""40    var confirmation: PendingConfirmation?4142    // answers (set by the view controller)43    @ObservationIgnored var onPassword: ((AutoFillCore.PasswordResult) -> Void)?44    @ObservationIgnored var onOneTimeCode: ((String) -> Void)?45    @ObservationIgnored var onAssertion: ((AutoFillCore.AssertionResult) -> Void)?46    @ObservationIgnored var onRegistration: ((AutoFillCore.RegistrationResult) -> Void)?47    @ObservationIgnored var onCancel: ((CancelReason) -> Void)?48    /// Injected so that tests / previews can replace the unlock.49    @ObservationIgnored var unlocker: @Sendable (String) async throws -> UnlockedVault = { try await AutoFillVault.unlock(reason: $0) }50    @ObservationIgnored var pendingQueue: @Sendable () throws -> PendingItems = { try PendingItems() }51    @ObservationIgnored var announce: @Sendable ([ItemView]) async -> Void = { await CredentialIdentitySync.add(for: $0) }5253    // ── request description ──54    var services: [AutoFillCore.Service] {55        switch request {56        case .password(_, let s, _), .oneTimeCode(_, let s, _): [s]57        case .list(let s, _, _): s58        case .passkeyAssertion(let rp, _, _, _, _), .registration(let rp, _, _, _, _, _): [AutoFillCore.Service(identifier: rp, isURL: false)]59        case nil: []60        }61    }62    var destination: String { AutoFillCore.destination(services) }63    var hasDestination: Bool { !services.isEmpty }6465    var title: String {66        switch request {67        case .password: "Fill password"68        case .oneTimeCode: "Fill one-time code"69        case .passkeyAssertion: "Sign in with passkey"70        case .list(_, let mode, _): mode == .oneTimeCodes ? "Choose a one-time code" : "Choose a credential"71        case .registration: "Save a passkey"72        case nil: "SP Vault"73        }74    }7576    /// Account / label announced by the system for a direct request (not a secret).77    var accountLabel: String? {78        switch request {79        case .password(_, _, let user): user.isEmpty ? nil : user80        case .oneTimeCode(_, _, let label): label.isEmpty ? nil : label81        case .passkeyAssertion(_, _, _, _, let name), .registration(_, let name, _, _, _, _): name.isEmpty ? nil : name82        default: nil83        }84    }8586    var isRegistration: Bool { if case .registration = request { return true }; return false }8788    var listing: AutoFillCore.Listing? {89        guard case .list(let services, let mode, let passkey) = request, let vault else { return nil }90        return AutoFillCore.listing(items: vault.items, services: services, mode: mode, query: query,91                                    passkeyRelyingParty: passkey?.relyingParty, allowedCredentialIDs: passkey?.allowedCredentialIDs ?? [])92    }9394    // ── flow ──95    /// Called by the view controller for each system request. Everything but a registration unlocks right away;96    /// creating a passkey waits for an explicit "Save".97    func begin(_ request: Request) {98        self.request = request99        vault = nil; query = ""; confirmation = nil100        stage = .prompt101        if !isRegistration { proceed() }102    }103104    func proceed() {105        guard stage == .prompt, request != nil else { return }106        stage = .unlocking107        let reason = isRegistration ? "Save a passkey in SP Vault" : "Unlock SP Vault to fill on \(destination)"108        flow = Task {109            do {110                let v = try await unlocker(reason)111                vault = v112                try await resolve(v)113            } catch {114                if AutoFillVault.isUserCancel(error) { stage = .prompt } else { fail(error) }115            }116        }117    }118119    private func fail(_ error: Error) {120        let e = error as? AutoFillError121        failureReason = (e == .itemNotFound) ? .notFound : .failed122        stage = .failed(e?.errorDescription ?? "SP Vault could not handle this request.")123    }124125    private func resolve(_ v: UnlockedVault) async throws {126        switch request {127        case .password(let id, let service, _):128            guard let it = AutoFillCore.item(id, in: v.items) else { throw AutoFillError.itemNotFound }129            onPassword?(try AutoFillCore.password(for: it.item, services: [service]))130        case .oneTimeCode(let id, let service, _):131            guard let it = AutoFillCore.item(id, in: v.items) else { throw AutoFillError.itemNotFound }132            onOneTimeCode?(try AutoFillCore.oneTimeCode(for: it.item, services: [service]))133        case .passkeyAssertion(let rp, let cid, let id, let hash, _):134            guard let it = AutoFillCore.passkey(in: v.items, relyingParty: rp, credentialID: cid, recordIdentifier: id) else { throw AutoFillError.itemNotFound }135            onAssertion?(try AutoFillCore.assertion(item: it.item, relyingParty: rp, clientDataHash: hash))136        case .list:137            stage = .list138        case .registration(let rp, let userName, let userHandle, let hash, let algorithms, let excluded):139            let r = try AutoFillCore.register(relyingParty: rp, userName: userName, userHandle: userHandle, clientDataHash: hash,140                                              supportedAlgorithms: algorithms, excludedCredentialIDs: excluded, existing: v.items)141            // persisted before the site hears about it: a passkey the site knows but the vault lost would lock the user out142            let id = try pendingQueue().add(r.item, identity: v.identity, deviceEncPub: v.deviceEncPub)143            await announce([ItemView(vaultId: AutoFillCore.pendingVaultId, recordId: id, rev: 0, item: r.item, pending: true, updatedAt: nil)])144            onRegistration?(r)145        case nil: break146        }147    }148149    /// A row of the list was chosen. A clean match is returned at once; anything else asks first.150    func pick(_ row: AutoFillCore.Row) {151        guard case .list(let services, _, let passkey) = request else { return }152        if row.isPasskey {153            guard let passkey else { return }154            do { onAssertion?(try AutoFillCore.assertion(item: row.view.item, relyingParty: passkey.relyingParty, clientDataHash: passkey.clientDataHash, allowedCredentialIDs: passkey.allowedCredentialIDs)) }155            catch { fail(error) }156            return157        }158        if let text = AutoFillCore.confirmation(for: row.view.item, services: services) { confirmation = PendingConfirmation(row: row, text: text) }159        else { deliver(row, confirmed: false) }160    }161162    /// The user accepted the dialog naming the site and the item.163    func confirmPick(_ c: PendingConfirmation) {164        confirmation = nil165        deliver(c.row, confirmed: true)166    }167168    private func deliver(_ row: AutoFillCore.Row, confirmed: Bool) {169        guard case .list(let services, let mode, _) = request else { return }170        do {171            switch mode {172            case .passwords: onPassword?(try AutoFillCore.password(for: row.view.item, services: services, confirmed: confirmed))173            case .oneTimeCodes: onOneTimeCode?(try AutoFillCore.oneTimeCode(for: row.view.item, services: services, confirmed: confirmed))174            }175        } catch { fail(error) }176    }177178    func cancel() {179        if case .failed = stage { onCancel?(failureReason) } else { onCancel?(.userCanceled) }180    }181}182
Files main
Menu

Theme