// 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.importCottonMailboximportFoundation#if os(iOS)importAuthenticationServices#endif/// One pass's outcome over passwords.publicstructPasswordPass: Equatable, Sendable {/// Saves still waiting for the vault.publicvar waiting: Int/// Rows written or changed by saves this pass.publicvar kept: Int}/// Cotton Keys' password drain and mirror.publicstructPasswordArrivals: Sendable {privatelet core: any CottonCallingprivatelet mailbox: PasswordMailboxprivatelet keychain: any PasswordKeysprivatelet pending: any PasswordKeys/// The codes after which an entry waits rather than going.staticlet waits: Set<String> = ["vault_locked", "vault_not_wrapped_yet", "vault_key_mismatch", "write_refused", "device_refused"]publicinit( core: any CottonCalling, mailbox: PasswordMailbox = PasswordMailbox(), keychain: any PasswordKeys = PasswordKeychain(), pending: any PasswordKeys = PasswordKeychain.pending() ) {self.core = coreself.mailbox = mailboxself.keychain = keychainself.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 = 0for entry in mailbox.drain() {switch entry.kind {casePasswordChannel.saved:switchawait save(entry, lent: lent) {case .done: kept += 1case .wait: back.append(entry)case .drop: break }casePasswordChannel.used:ifawait used(entry) == .wait { back.append(entry) }default:break// a kind this build does not know: a newer provider's, dropped } } mailbox.wait(back)returnPasswordPass(waiting: back.filter { $0.kind == PasswordChannel.saved }.count, kept: kept) }enumOutcome: Equatable { case done, wait, drop }privatefunc save(_ entry: PasswordEntry, lent: String?) async -> Outcome {guardlet pendingId = entry.pendingId, let site = entry.site,let data = pending.password(id: pendingId), let password = String(data: data, encoding: .utf8)else {iflet pendingId = entry.pendingId { pending.remove(id: pendingId) }return .drop }var request: [String: String] = ["site": site, "password": password]iflet username = entry.username, !username.isEmpty { request["username"] = username }iflet title = entry.title, !title.isEmpty { request["name"] = title }iflet lent { request["privateKey"] = lent }do { _ = tryawait core.callJSON(CottonMethod.passwordSave, request) pending.remove(id: pendingId)return .done } catchlet refusal asCottonCallErrorwhereSelf.waits.contains(refusal.code) {return .wait } catchisCottonCallError {// 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 } }privatefunc used(_ entry: PasswordEntry) async -> Outcome {guardlet id = entry.passwordId else { return .drop }var request = ["id": id]iflet usedAt = entry.usedAt { request["usedAt"] = usedAt }do { _ = tryawait core.callJSON(CottonMethod.passwordUsed, request)return .done } catchlet refusal asCottonCallErrorwhereSelf.waits.contains(refusal.code) {return .wait } catchisCottonCallError {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. @discardableResultfunc 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)]iflet lent { request["privateKey"] = .string(lent) }guardlet answer = try? await core.callJSON(CottonMethod.passwordMirror, request) else { returnfalse }for login in answer["passwords"]?.array ?? [] {guardlet 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}