Cotton code
208 lines · 9.3 KB · SwiftRaw
// What Cotton Keys does with what its passkey provider wrote down.////   drain     passkey.registered → `passkey.register` (the scalar read from//                                  the shared keychain for this one call,//                                  sealed by the core under the VMK)//             passkey.used       → `passkey.used` (uses + 1, last_used_at)//             an entry the core cannot apply yet (vault locked, not wrapped,//             the row a use counts for not written) waits in the mailbox//   mirror    every row this phone's keychain lacks (made on another device)//             gets its item when the vault opens (`passkey.mirror`); a kept//             item whose row is gone, and that no waiting entry names, goes//   identify  every kept passkey, and every password the keychain holds//             (`PasswordArrivals`), is told to ASCredentialIdentityStore in//             one replace, so iOS offers Cotton Keys for that site; the rest//             leave it//   passwords the provider's password entries drain and the password copy//             is mirrored in the same pass (`PasswordArrivals`), under the//             same lent key, so one Face ID serves both//// After a drain and after each sync pass (`run`). The vault is the// five-minute unlock's; when registrations wait and the person is here// (`presence: true`), this device's vault key is read once — the read IS the// Face ID prompt — and lent for those calls alone, never kept.//// No key material is logged, kept or returned: a scalar crosses from the// keychain into one call, or from one call into the keychain.import CottonMailboximport Foundation#if os(iOS)    import AuthenticationServices#endif/// One pass's outcome, for the line the app shows.public struct PasskeyPass: Equatable, Sendable {    /// Registrations still waiting for the vault.    public var waiting: Int    /// Rows written this pass.    public var kept: Int    /// Saved passwords still waiting for the vault.    public var passwordsWaiting: Int = 0}/// Cotton Keys' passkey drain, mirror and identity store.public struct PasskeyArrivals: Sendable {    private let core: any CottonCalling    private let mailbox: PasskeyMailbox    private let keychain: any PasskeyKeys    private let keyring: VaultKeyring    private let passwords: PasswordArrivals    /// The codes after which an entry waits rather than going: the vault is    /// not open here yet, or the row a use counts for is not written yet.    static let waits: Set<String> = ["vault_locked", "vault_not_wrapped_yet", "vault_key_mismatch", "passkey_not_found", "write_refused", "device_refused"]    public init(        core: any CottonCalling,        mailbox: PasskeyMailbox = PasskeyMailbox(),        keychain: any PasskeyKeys = PasskeyKeychain(),        keyring: VaultKeyring = VaultKeyring(),        passwords: PasswordArrivals? = nil    ) {        self.core = core        self.mailbox = mailbox        self.keychain = keychain        self.keyring = keyring        self.passwords = passwords ?? PasswordArrivals(core: core)    }    /// Drain, mirror and tell the identity store. `presence` says the person    /// is here, so a waiting registration may ask for Face ID once.    @discardableResult    public func run(presence: Bool) async -> PasskeyPass {        var lent: String?        var pass = await drain(lent: nil)        var saved = await passwords.drain(lent: nil)        if pass.waiting + saved.waiting > 0, presence, let key = await vaultKey() {            lent = key            pass = await drain(lent: key)            saved = await passwords.drain(lent: key)        }        await mirror(lent: lent)        await passwords.mirror(lent: lent)        await identify()        pass.passwordsWaiting = saved.waiting        return pass    }    /// Every waiting entry through its call, oldest first; what cannot be    /// applied yet is put back. A use waits behind its own registration.    func drain(lent: String?) async -> PasskeyPass {        let entries = mailbox.drain()        var back: [PasskeyEntry] = []        var kept = 0        for entry in entries {            switch entry.kind {            case PasskeyChannel.registered:                switch await register(entry, lent: lent) {                case .done: kept += 1                case .wait: back.append(entry)                case .drop: break                }            case PasskeyChannel.used:                if back.contains(where: { $0.credentialId == entry.credentialId }) {                    back.append(entry)                    continue                }                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 PasskeyPass(waiting: back.filter { $0.kind == PasskeyChannel.registered }.count, kept: kept)    }    enum Outcome: Equatable { case done, wait, drop }    private func register(_ entry: PasskeyEntry, lent: String?) async -> Outcome {        // No item: this entry's key was never kept here (or was removed), so        // there is nothing to seal and the entry goes.        guard let scalar = keychain.scalar(credentialId: entry.credentialId) else { return .drop }        var request: [String: String] = entry.arguments        request["privateScalar"] = PasskeyAuthenticator.base64url(scalar)        if let lent { request["privateKey"] = lent }        do {            _ = try await core.callJSON(CottonMethod.passkeyRegister, request)            return .done        } catch let refusal as CottonCallError where Self.waits.contains(refusal.code) {            return .wait        } catch is CottonCallError {            // Refused for good (a scalar that does not make its public key):            // nothing can make it a row, so the entry goes.            return .drop        } catch {            return .wait        }    }    private func used(_ entry: PasskeyEntry) async -> Outcome {        do {            _ = try await core.callJSON(CottonMethod.passkeyUsed, entry.arguments)            return .done        } catch let refusal as CottonCallError where Self.waits.contains(refusal.code) {            return .wait        } catch is CottonCallError {            return .drop        } catch {            return .wait        }    }    /// This device's vault key, read once after the presence prompt; nil on    /// cancel or with no key.    private func vaultKey() async -> String? {        let keyring = self.keyring        return await Task.detached(priority: .userInitiated) { try? keyring.privateKey() }.value    }    /// The rows this phone's keychain lacks get their items; kept items whose    /// row is gone go, unless a waiting entry still names them.    func mirror(lent: String?) async {        guard let rows = try? await core.callJSON(CottonMethod.passkeyIdentities)["identities"]?.array else { return }        let rowIds = Set(rows.compactMap { $0.text("credential_id") })        let kept = keychain.items(rpId: nil)        let keptIds = Set(kept.map(\.credentialId))        let missing = rowIds.subtracting(keptIds)        if !missing.isEmpty {            var request: [String: JSONValue] = ["credentialIds": .array(missing.sorted().map { .string($0) })]            if let lent { request["privateKey"] = .string(lent) }            if let answer = try? await core.callJSON(CottonMethod.passkeyMirror, request), let keys = answer["keys"]?.array {                for key in keys {                    guard let credential = key.text("credential_id"), let rpId = key.text("rp_id"),                        let handle = key.text("user_handle"), let scalar = key.text("privateScalar").flatMap(PasskeyAuthenticator.fromBase64url)                    else { continue }                    let item = PasskeyKeychainItem(                        credentialId: credential, rpId: rpId, rpName: key.text("rp_name"), userName: key.text("user_name"),                        userHandle: handle, createdAt: key.text("created_at") ?? ""                    )                    try? keychain.save(item, scalar: scalar)                }            }        }        let waitingIds = Set(mailbox.waiting().map(\.credentialId))        for item in kept where !rowIds.contains(item.credentialId) && !waitingIds.contains(item.credentialId) {            keychain.remove(credentialId: item.credentialId)        }    }    /// Tell iOS every passkey this phone can sign with; the rest leave.    func identify() async {        #if os(iOS)            let store = ASCredentialIdentityStore.shared            guard await store.state().isEnabled else { return }            let passkeys: [ASCredentialIdentity] = keychain.items(rpId: nil).compactMap { item in                guard let credential = PasskeyAuthenticator.fromBase64url(item.credentialId),                    let handle = PasskeyAuthenticator.fromBase64url(item.userHandle)                else { return nil }                return ASPasskeyCredentialIdentity(                    relyingPartyIdentifier: item.rpId, userName: item.userName ?? "", credentialID: credential,                    userHandle: handle, recordIdentifier: item.credentialId                )            }            try? await store.replaceCredentialIdentities(passkeys + passwords.identities())        #endif    }}