Cotton code
160 lines · 6.8 KB · SwiftRaw
// What Cotton Keys does with what its credential provider did with// passwords, and the copy the provider fills from.////   drain     password.saved → `password.save` (the password read from the//                              pending keychain store for this one call,//                              sealed by the core under the VMK), then the//                              pending item goes//             password.used  → `password.used` (last_used_at)//             an entry the core cannot apply yet (vault locked, not wrapped)//             waits in the mailbox, its pending item kept//   mirror    `password.mirror` with what the keychain holds (id → stamp)://             each login it answers is written to the shared keychain, each//             id it names gone is removed. The core opens only what changed,//             and only on an open vault (five-minute unlock, or the key lent//             for this pass); locked, what is gone still goes.//   identify  the passwords the keychain holds, as ASPasswordCredentialIdentity//             (`identities()`), told to iOS beside the passkeys by//             `PasskeyArrivals.identify` — one replace, so neither wipes the//             other.//// No password is logged, kept or returned beyond the keychain: one crosses// from the pending store into one call, or from one answer into the store.import CottonMailboximport Foundation#if os(iOS)    import AuthenticationServices#endif/// One pass's outcome over passwords.public struct PasswordPass: Equatable, Sendable {    /// Saves still waiting for the vault.    public var waiting: Int    /// Rows written or changed by saves this pass.    public var kept: Int}/// Cotton Keys' password drain and mirror.public struct PasswordArrivals: Sendable {    private let core: any CottonCalling    private let mailbox: PasswordMailbox    private let keychain: any PasswordKeys    private let pending: any PasswordKeys    /// The codes after which an entry waits rather than going.    static let waits: Set<String> = ["vault_locked", "vault_not_wrapped_yet", "vault_key_mismatch", "write_refused", "device_refused"]    public init(        core: any CottonCalling,        mailbox: PasswordMailbox = PasswordMailbox(),        keychain: any PasswordKeys = PasswordKeychain(),        pending: any PasswordKeys = PasswordKeychain.pending()    ) {        self.core = core        self.mailbox = mailbox        self.keychain = keychain        self.pending = pending    }    /// Every waiting entry through its call, oldest first; what cannot be    /// applied yet is put back.    func drain(lent: String?) async -> PasswordPass {        var back: [PasswordEntry] = []        var kept = 0        for entry in mailbox.drain() {            switch entry.kind {            case PasswordChannel.saved:                switch await save(entry, lent: lent) {                case .done: kept += 1                case .wait: back.append(entry)                case .drop: break                }            case PasswordChannel.used:                if await used(entry) == .wait { back.append(entry) }            default:                break  // a kind this build does not know: a newer provider's, dropped            }        }        mailbox.wait(back)        return PasswordPass(waiting: back.filter { $0.kind == PasswordChannel.saved }.count, kept: kept)    }    enum Outcome: Equatable { case done, wait, drop }    private func save(_ entry: PasswordEntry, lent: String?) async -> Outcome {        guard let pendingId = entry.pendingId, let site = entry.site,            let data = pending.password(id: pendingId), let password = String(data: data, encoding: .utf8)        else {            if let pendingId = entry.pendingId { pending.remove(id: pendingId) }            return .drop        }        var request: [String: String] = ["site": site, "password": password]        if let username = entry.username, !username.isEmpty { request["username"] = username }        if let title = entry.title, !title.isEmpty { request["name"] = title }        if let lent { request["privateKey"] = lent }        do {            _ = try await core.callJSON(CottonMethod.passwordSave, request)            pending.remove(id: pendingId)            return .done        } catch let refusal as CottonCallError where Self.waits.contains(refusal.code) {            return .wait        } catch is CottonCallError {            // Refused for good (a Worker-sealed login for this site, a site            // that is no address): nothing can make it a row.            pending.remove(id: pendingId)            return .drop        } catch {            return .wait        }    }    private func used(_ entry: PasswordEntry) async -> Outcome {        guard let id = entry.passwordId else { return .drop }        var request = ["id": id]        if let usedAt = entry.usedAt { request["usedAt"] = usedAt }        do {            _ = try await core.callJSON(CottonMethod.passwordUsed, request)            return .done        } catch let refusal as CottonCallError where Self.waits.contains(refusal.code) {            return .wait        } catch is CottonCallError {            return .drop        } catch {            return .wait        }    }    /// The keychain made to match what the core answers. Returns whether the    /// core found the vault locked with something left to open.    @discardableResult    func mirror(lent: String?) async -> Bool {        var held: [String: JSONValue] = [:]        for item in keychain.items() { held[item.id] = .string(item.stamp) }        var request: [String: JSONValue] = ["held": .object(held)]        if let lent { request["privateKey"] = .string(lent) }        guard let answer = try? await core.callJSON(CottonMethod.passwordMirror, request) else { return false }        for login in answer["passwords"]?.array ?? [] {            guard let id = login.text("id"), let site = login.text("site"), let stamp = login.text("stamp"),                let password = login.text("password")            else { continue }            let item = PasswordKeychainItem(id: id, site: site, username: login.text("username"), name: login.text("name"), stamp: stamp)            try? keychain.save(item, password: Data(password.utf8))        }        for id in answer["gone"]?.strings ?? [] { keychain.remove(id: id) }        return answer["locked"]?.bool ?? false    }    #if os(iOS)        /// The passwords the keychain holds, as the identity store takes them.        func identities() -> [ASCredentialIdentity] {            keychain.items().map { item in                ASPasswordCredentialIdentity(                    serviceIdentifier: ASCredentialServiceIdentifier(identifier: item.site, type: .domain),                    user: item.username ?? "", recordIdentifier: item.id                )            }        }    #endif}