Cotton code
149 lines · 6.3 KB · SwiftRaw
// Cotton Keys' side of Credential Exchange: passkeys handed over by Apple's// Passwords app (or any exporter) become Keys rows.//// The provider extension's Info.plist says Keys is an import destination// (`SupportsCredentialExchange`, `SupportedCredentialExchangeVersions` 1.0,// project.yml). The person exports in Passwords and picks Cotton Keys; iOS// opens THIS APP with an NSUserActivity of type `ASCredentialExchangeActivity`// whose `userInfo[ASCredentialImportToken]` is a UUID. The token is held until// the file is open, then `CottonKit/PasskeyImport.swift` reads the export// through `ASCredentialImportManager` and lands it through// `passkey.importCxf`; the toast says how many, what was skipped and why, and// the app lands on Keys › All (the deck at its root).//// THE WALK HOOK (Keys Dev only): `WALK_KEYS_IMPORT=1` with the export's JSON in// `WALK_KEYS_IMPORT_JSON` feeds that JSON through the same path from the read// on, since a simulator has no Passwords export to hand over.import CottonKitimport CottonValuesimport Foundation#if os(iOS)    import AuthenticationServices#endif@MainActorfinal class KeysImport {    /// Whether this app imports passkeys: Cotton Keys alone.    static var applies: Bool { KeysPasskeys.applies }    private let core: any CottonCalling    private let importer: PasskeyImport    private let say: @MainActor (String) -> Void    private var ready = false    private var held: [Asked] = []    private var running = false    enum Asked {        case token(UUID)        case json(String)    }    init(core: any CottonCalling, say: @escaping @MainActor (String) -> Void) {        self.core = core        importer = PasskeyImport(core: core)        self.say = say    }    #if os(iOS)        /// `ASCredentialExchangeActivity`, as `onContinueUserActivity` takes it.        static var activityType: String {            if #available(iOS 26.0, *) { return ASCredentialExchangeActivity }            return "com.apple.AuthenticationServices.CredentialExchange.unavailable"        }        /// The activity iOS opens the app with, when it is an import.        func receive(_ activity: NSUserActivity, land: @escaping @MainActor () -> Void) {            guard #available(iOS 26.0, *), activity.activityType == ASCredentialExchangeActivity else { return }            guard let token = Self.token(activity.userInfo?[ASCredentialImportToken]) else {                PasskeyImport.log.error("import: the activity carried no token (userInfo keys: \((activity.userInfo?.keys.map { "\($0)" } ?? []).joined(separator: ", "), privacy: .public))")                say(ShellLines.line("passwords", "passkeys.import_refused", ["reason": ShellLines.line("passwords", "passkeys.import_no_token")]))                return            }            ask(.token(token), land: land)        }        private static func token(_ value: Any?) -> UUID? {            if let uuid = value as? UUID { return uuid }            if let text = value as? String { return UUID(uuidString: text) }            return nil        }    #endif    /// The file is open: what arrived before it runs now, and the walk's    /// export when the walk asks for one.    func opened(land: @escaping @MainActor () -> Void) {        ready = true        #if COTTON_DEV            let environment = ProcessInfo.processInfo.environment            if environment["WALK_KEYS_IMPORT"] == "1", let json = environment["WALK_KEYS_IMPORT_JSON"], !json.isEmpty {                held.append(.json(json))            }            Task { @MainActor in await WalkVault.run(core: self.core, say: self.say) }        #endif        run(land: land)    }    private func ask(_ asked: Asked, land: @escaping @MainActor () -> Void) {        held.append(asked)        if ready { run(land: land) }    }    private func run(land: @escaping @MainActor () -> Void) {        guard !running, !held.isEmpty else { return }        running = true        let next = held.removeFirst()        Task { @MainActor in            let outcome = await self.take(next)            land()            self.say(Self.said(outcome))            self.running = false            self.run(land: land)        }    }    private func take(_ asked: Asked) async -> PasskeyImported {        switch asked {        case .json(let json):            return await importer.run(json: json)        case .token(let token):            return await handedOver(token)        }    }    private func handedOver(_ token: UUID) async -> PasskeyImported {        #if os(iOS)            if #available(iOS 26.0, *) {                do {                    return await importer.run(json: try await PasskeyImport.exported(token: token))                } catch {                    PasskeyImport.log.error("import: the system did not hand the export over: \(String(describing: error), privacy: .public)")                    return .refused(error.localizedDescription)                }            }        #endif        return .refused(ShellLines.line("passwords", "passkeys.import_no_token"))    }    /// The toast: how many, then each skip's title and reason.    static func said(_ outcome: PasskeyImported) -> String {        if outcome.locked { return ShellLines.line("passwords", "passkeys.import_locked") }        if let refused = outcome.refused { return ShellLines.line("passwords", "passkeys.import_refused", ["reason": refused]) }        let n = outcome.sites.count        let p = outcome.passwords.count        let m = outcome.skipped.count        let counts = ["n": String(n), "p": String(p), "m": String(m)]        var said: String        switch (n, p) {        case (_, 0): said = ShellLines.line("passwords", n == 1 ? "passkeys.imported_one" : "passkeys.imported_many", counts)        case (0, _): said = ShellLines.line("passwords", p == 1 ? "passkeys.passwords_imported_one" : "passkeys.passwords_imported_many", counts)        default: said = ShellLines.line("passwords", "passkeys.imported_with_passwords", counts)        }        for skip in outcome.skipped {            let title = skip.title.isEmpty ? ShellLines.line("passwords", "passkeys.import_untitled") : skip.title            said += "\n" + ShellLines.line("passwords", "passkeys.import_skip", ["title": title, "reason": skip.reason])        }        return said    }}