SPB Git

Repository Public

AutoFillCore.swift 16.3 KB 281 lines swift

1// AutoFill request handling that does not need the operating system: which items may be offered for a site, when a2// confirmation is mandatory, and the bytes returned for a password, a one-time code, a passkey assertion or a new3// passkey. The extension's view controller only translates AuthenticationServices objects to and from these values,4// so that everything here is unit-tested (Tests/Unit/AutoFillCoreTests.swift).5//6// Rules enforced here:7//   * an item is returned without confirmation only when one of its URLs matches the page per `SPV1.matchUrl`8//     (registrable domain with the Public Suffix List, the item's own rule, never https → http);9//   * anything else needs an explicit confirmation that names both the site and the item (`Confirmation`);10//   * a passkey is only ever asserted for its own relying party — there is no override.11import Foundation12import SharedVaultKit1314enum AutoFillError: Error, Equatable, Sendable, LocalizedError {15    case notEnrolled16    case keysInvalidated17    case itemNotFound18    case noLongerMatches(site: String)19    case noPassword20    case noOneTimeCode21    case passkeyUnusable22    case relyingPartyMismatch23    case unsupportedAlgorithm24    case alreadyRegistered25    case invalidRequest(String)2627    var errorDescription: String? {28        switch self {29        case .notEnrolled: "Open SP Vault and sign in first. This device has no vault yet."30        case .keysInvalidated: "The keys of this device are no longer valid. Open SP Vault to enrol this device again (pairing or recovery key)."31        case .itemNotFound: "This item is no longer in your vault."32        case .noLongerMatches(let site): "The saved item no longer matches \(site). Pick it from the list if you really want to use it there."33        case .noPassword: "This item has no username or password."34        case .noOneTimeCode: "This item has no valid one-time-code secret."35        case .passkeyUnusable: "This passkey item is incomplete and cannot sign in."36        case .relyingPartyMismatch: "This passkey belongs to another site. A passkey is never used on a site other than its own."37        case .unsupportedAlgorithm: "This site asks for a kind of passkey SP Vault does not create (only ES256 is supported)."38        case .alreadyRegistered: "SP Vault already holds a passkey for this account on this site."39        case .invalidRequest(let what): "The request cannot be handled (\(what))."40        }41    }42}4344enum AutoFillCore {45    static let pendingVaultId = "pending"46    static let es256 = -74748    // ── services ──4950    /// What the system says is asking for a credential (`ASCredentialServiceIdentifier`).51    struct Service: Sendable, Equatable {52        let identifier: String53        /// True for the `.URL` type, false for `.domain`.54        let isURL: Bool55        init(identifier: String, isURL: Bool) { self.identifier = identifier; self.isURL = isURL }5657        /// The page URL matching is done against: a URL as is; a bare domain is assumed https (never http).58        var pageURL: String {59            let id = identifier.trimmingCharacters(in: .whitespacesAndNewlines)60            if isURL || id.contains("://") { return id }61            return "https://\(id)"62        }6364        /// Host shown to the user (IDN and mixed-script aware, from `SPV1.parseOrigin`). Falls back to the raw identifier.65        var displayHost: String { SPV1.parseOrigin(pageURL)?.display ?? identifier }66    }6768    /// Display name of the destination: the most specific service, or a neutral phrase when the system gave none.69    static func destination(_ services: [Service]) -> String { services.first?.displayHost ?? "this app or website" }7071    // ── matching ──7273    /// `.insecure`: the item was saved for an http page and the page is that http page (plain text on the network).74    /// A login saved for https is never a match for an http page at all (`.none`).75    enum MatchKind: Sendable, Equatable { case match, insecure, none }7677    /// Best match of an item against any of the services (the system lists the most specific first).78    static func match(_ item: Item, services: [Service]) -> MatchKind {79        var best = MatchKind.none80        for s in services {81            for u in item.urls {82                switch SPV1.matchUrl(saved: u, pageUrl: s.pageURL) {83                case .match: return .match84                case .insecure: best = .insecure85                case .no: break86                }87            }88        }89        return best90    }9192    /// True only for a clean match: the item can be returned without asking anything more.93    static func mayReturnWithoutConfirmation(_ item: Item, services: [Service]) -> Bool { match(item, services: services) == .match }9495    /// The sentence the user must accept before an item is filled somewhere it does not match. Names both sides.96    struct Confirmation: Sendable, Equatable {97        let title: String98        let message: String99        let confirmLabel: String100    }101102    static func confirmation(for item: Item, services: [Service]) -> Confirmation? {103        let kind = match(item, services: services)104        if kind == .match { return nil }105        let site = destination(services), name = item.title.isEmpty ? "Untitled" : item.title106        let saved = item.urls.compactMap { SPV1.parseOrigin($0.url)?.display }.first107        let savedText = saved.map { " It was saved for \($0)." } ?? " It has no website saved."108        switch kind {109        case .insecure:110            return Confirmation(title: "Fill “\(name)” on \(site) without encryption?",111                                message: "\(site) is not using https: what you fill there, including “\(name)”, can be read and altered on the network.\(savedText)",112                                confirmLabel: "Fill “\(name)” on \(site) anyway")113        default:114            return Confirmation(title: "Fill “\(name)” on \(site)?",115                                message: "“\(name)” does not match \(site).\(savedText) Filling a credential on the wrong site hands it to that site.",116                                confirmLabel: "Fill “\(name)” on \(site)")117        }118    }119120    // ── lists ──121122    enum ListMode: Sendable, Equatable { case passwords, oneTimeCodes }123124    struct Row: Sendable, Equatable, Identifiable {125        let view: ItemView126        let kind: MatchKind127        /// A passkey row (only offered for its own relying party).128        let isPasskey: Bool129        var id: String { (isPasskey ? "pk:" : "") + view.id }130        var isPending: Bool { view.vaultId == AutoFillCore.pendingVaultId }131    }132133    struct Listing: Sendable, Equatable {134        /// Passkeys of the requested relying party, then logins that match (clean matches before insecure ones).135        let suggested: [Row]136        /// Every other candidate; picking one requires a confirmation.137        let others: [Row]138        let lookalike: LookalikeWarning?139        var isEmpty: Bool { suggested.isEmpty && others.isEmpty }140    }141142    private static func eligible(_ v: ItemView, mode: ListMode) -> Bool {143        guard v.item.type == .login, (v.item.trashedAt ?? "").isEmpty else { return false }144        switch mode {145        case .passwords: return !(v.item.fields["username"] ?? "").isEmpty || !(v.item.fields["password"] ?? "").isEmpty146        case .oneTimeCodes: return (v.item.fields["totp"]).flatMap { try? SPV1.parseTotp($0) } != nil147        }148    }149150    private static func title(_ v: ItemView) -> String { v.item.title.isEmpty ? "Untitled" : v.item.title }151152    /// Builds the credential list. `passkeyRelyingParty` (with the credential ids the site allows) adds passkey rows.153    static func listing(items: [ItemView], services: [Service], mode: ListMode, query: String = "",154                        passkeyRelyingParty: String? = nil, allowedCredentialIDs: [Data] = []) -> Listing {155        let q = query.trimmingCharacters(in: .whitespaces)156        func visible(_ v: ItemView) -> Bool { q.isEmpty || SPV1.matchesQuery(haystack: SPV1.searchText(v.item), query: q) }157        var clean: [Row] = [], insecure: [Row] = [], others: [Row] = []158        for v in items where eligible(v, mode: mode) && visible(v) {159            switch match(v.item, services: services) {160            case .match: clean.append(Row(view: v, kind: .match, isPasskey: false))161            case .insecure: insecure.append(Row(view: v, kind: .insecure, isPasskey: false))162            case .none: others.append(Row(view: v, kind: .none, isPasskey: false))163            }164        }165        var keys: [Row] = []166        if let rp = passkeyRelyingParty, mode == .passwords {167            keys = passkeys(in: items, relyingParty: rp, allowedCredentialIDs: allowedCredentialIDs).filter(visible).map { Row(view: $0, kind: .match, isPasskey: true) }168        }169        let byTitle: (Row, Row) -> Bool = { title($0.view).localizedCaseInsensitiveCompare(title($1.view)) == .orderedAscending }170        let saved = SPV1.savedDomains(items.filter { ($0.item.trashedAt ?? "").isEmpty }.map(\.item))171        let warning = clean.isEmpty && keys.isEmpty ? services.lazy.compactMap { SPV1.lookalike(pageUrl: $0.pageURL, savedDomains: saved) }.first : nil172        return Listing(suggested: keys.sorted(by: byTitle) + clean.sorted(by: byTitle) + insecure.sorted(by: byTitle), others: others.sorted(by: byTitle), lookalike: warning)173    }174175    /// Usable passkeys stored for a relying party, optionally restricted to the credential ids the site allows.176    static func passkeys(in items: [ItemView], relyingParty: String, allowedCredentialIDs: [Data] = []) -> [ItemView] {177        items.filter { v in178            guard v.item.type == .passkey, (v.item.trashedAt ?? "").isEmpty, v.item.fields["rpId"] == relyingParty,179                  v.item.fields["privateKey"]?.isEmpty == false, let cid = try? SPV1.unb64u(v.item.fields["credentialId"] ?? ""), !cid.isEmpty else { return false }180            return allowedCredentialIDs.isEmpty || allowedCredentialIDs.contains(cid)181        }182    }183184    // ── pending items (passkeys created by the extension, not yet ingested by the app) ──185186    /// Items the reader decrypted plus the ones still waiting in the pending queue (record identifier `pending/<id>`).187    /// A pending passkey whose credential id already exists in the vault (ingested meanwhile) is not listed twice.188    static func merge(items: [ItemView], pending: [PendingItems.Entry]) -> [ItemView] {189        let known = Set(items.compactMap { $0.item.type == .passkey ? $0.item.fields["credentialId"] : nil })190        var out = items191        for p in pending {192            if p.item.type == .passkey, let cid = p.item.fields["credentialId"], known.contains(cid) { continue }193            out.append(ItemView(vaultId: pendingVaultId, recordId: p.id, rev: 0, item: p.item, pending: true, updatedAt: nil))194        }195        return out196    }197198    static func item(_ recordIdentifier: String?, in items: [ItemView]) -> ItemView? {199        guard let recordIdentifier else { return nil }200        return items.first { $0.id == recordIdentifier && ($0.item.trashedAt ?? "").isEmpty }201    }202203    // ── results ──204205    struct PasswordResult: Sendable, Equatable { let user: String; let password: String }206207    /// Username and password of a login. `confirmed` is true only after the user accepted `confirmation(for:services:)`.208    static func password(for item: Item, services: [Service], confirmed: Bool = false) throws -> PasswordResult {209        guard item.type == .login else { throw AutoFillError.itemNotFound }210        let user = item.fields["username"] ?? "", password = item.fields["password"] ?? ""211        guard !user.isEmpty || !password.isEmpty else { throw AutoFillError.noPassword }212        guard confirmed || mayReturnWithoutConfirmation(item, services: services) else { throw AutoFillError.noLongerMatches(site: destination(services)) }213        return PasswordResult(user: user, password: password)214    }215216    /// The current one-time code of a login.217    static func oneTimeCode(for item: Item, services: [Service], confirmed: Bool = false, atMs: Double? = nil) throws -> String {218        guard item.type == .login, let secret = item.fields["totp"], !secret.isEmpty, let params = try? SPV1.parseTotp(secret),219              let code = try? SPV1.totp(params, atMs: atMs) else { throw AutoFillError.noOneTimeCode }220        guard confirmed || mayReturnWithoutConfirmation(item, services: services) else { throw AutoFillError.noLongerMatches(site: destination(services)) }221        return code.code222    }223224    struct AssertionResult: Sendable, Equatable {225        let relyingParty: String226        let userHandle: Data227        let signature: Data228        let clientDataHash: Data229        let authenticatorData: Data230        let credentialID: Data231    }232233    /// Finds the passkey a request designates: by credential id (authoritative), within the relying party.234    static func passkey(in items: [ItemView], relyingParty: String, credentialID: Data, recordIdentifier: String? = nil) -> ItemView? {235        let all = passkeys(in: items, relyingParty: relyingParty)236        if !credentialID.isEmpty { return all.first { (try? SPV1.unb64u($0.item.fields["credentialId"] ?? "")) == credentialID } }237        return all.first { $0.id == recordIdentifier }238    }239240    /// Signs an assertion. The item's own `rpId` must be the requested relying party: no confirmation can override it.241    static func assertion(item: Item, relyingParty: String, clientDataHash: Data, allowedCredentialIDs: [Data] = [], userVerified: Bool = true) throws -> AssertionResult {242        guard item.type == .passkey, let rp = item.fields["rpId"], !rp.isEmpty, item.fields["privateKey"]?.isEmpty == false else { throw AutoFillError.passkeyUnusable }243        guard rp == relyingParty else { throw AutoFillError.relyingPartyMismatch }244        guard clientDataHash.count == 32 else { throw AutoFillError.invalidRequest("client data hash") }245        let a: PasskeyCrypto.Assertion246        do { a = try PasskeyCrypto.assert(fields: item.fields, clientDataHash: clientDataHash, userVerified: userVerified) } catch { throw AutoFillError.passkeyUnusable }247        guard allowedCredentialIDs.isEmpty || allowedCredentialIDs.contains(a.credentialID) else { throw AutoFillError.itemNotFound }248        return AssertionResult(relyingParty: rp, userHandle: a.userHandle, signature: a.signature, clientDataHash: clientDataHash, authenticatorData: a.authenticatorData, credentialID: a.credentialID)249    }250251    struct RegistrationResult: Sendable {252        let relyingParty: String253        let clientDataHash: Data254        let credentialID: Data255        let attestationObject: Data256        /// The `passkey` item to persist (through `PendingItems`).257        let item: Item258    }259260    /// Creates a passkey. Refuses when the site does not accept ES256 or already has one of its excluded credentials here.261    static func register(relyingParty: String, userName: String, userHandle: Data, clientDataHash: Data, supportedAlgorithms: [Int],262                         excludedCredentialIDs: [Data] = [], existing: [ItemView], userVerified: Bool = true) throws -> RegistrationResult {263        guard !relyingParty.isEmpty else { throw AutoFillError.invalidRequest("relying party") }264        guard supportedAlgorithms.isEmpty || supportedAlgorithms.contains(es256) else { throw AutoFillError.unsupportedAlgorithm }265        if !excludedCredentialIDs.isEmpty, !passkeys(in: existing, relyingParty: relyingParty, allowedCredentialIDs: excludedCredentialIDs).isEmpty { throw AutoFillError.alreadyRegistered }266        let c: PasskeyCrypto.CreatedCredential267        do { c = try PasskeyCrypto.createCredential(rpId: relyingParty, userName: userName, userHandle: userHandle, clientDataHash: clientDataHash, userVerified: userVerified) }268        catch { throw AutoFillError.invalidRequest("passkey parameters") }269        let title = userName.isEmpty ? relyingParty : "\(relyingParty) (\(userName))"270        return RegistrationResult(relyingParty: relyingParty, clientDataHash: clientDataHash, credentialID: c.credentialID, attestationObject: c.attestationObject,271                                  item: PasskeyCrypto.makeItem(c, title: title))272    }273274    /// Second line of a row: who, never a secret.275    static func subtitle(_ item: Item) -> String {276        let who = item.fields["username"] ?? item.fields["userName"] ?? ""277        let host = item.urls.compactMap { SPV1.parseOrigin($0.url)?.display }.first ?? item.fields["rpId"] ?? ""278        return [who, host].filter { !$0.isEmpty }.joined(separator: " · ")279    }280}281
Files main
Menu

Theme