// 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.importCottonMailboximportFoundation#if os(iOS)importAuthenticationServices#endif/// One pass's outcome, for the line the app shows.publicstructPasskeyPass: Equatable, Sendable {/// Registrations still waiting for the vault.publicvar waiting: Int/// Rows written this pass.publicvar kept: Int/// Saved passwords still waiting for the vault.publicvar passwordsWaiting: Int = 0}/// Cotton Keys' passkey drain, mirror and identity store.publicstructPasskeyArrivals: Sendable {privatelet core: any CottonCallingprivatelet mailbox: PasskeyMailboxprivatelet keychain: any PasskeyKeysprivatelet keyring: VaultKeyringprivatelet 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.staticlet waits: Set<String> = ["vault_locked", "vault_not_wrapped_yet", "vault_key_mismatch", "passkey_not_found", "write_refused", "device_refused"]publicinit( core: any CottonCalling, mailbox: PasskeyMailbox = PasskeyMailbox(), keychain: any PasskeyKeys = PasskeyKeychain(), keyring: VaultKeyring = VaultKeyring(), passwords: PasswordArrivals? = nil ) {self.core = coreself.mailbox = mailboxself.keychain = keychainself.keyring = keyringself.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. @discardableResultpublicfunc 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.waitingreturn 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 = 0for entry in entries {switch entry.kind {casePasskeyChannel.registered:switchawait register(entry, lent: lent) {case .done: kept += 1case .wait: back.append(entry)case .drop: break }casePasskeyChannel.used:if back.contains(where: { $0.credentialId == entry.credentialId }) { back.append(entry)continue }ifawait used(entry) == .wait { back.append(entry) }default:break// a kind this build does not know: a newer provider's, dropped } } mailbox.wait(back)returnPasskeyPass(waiting: back.filter { $0.kind == PasskeyChannel.registered }.count, kept: kept) }enumOutcome: Equatable { case done, wait, drop }privatefunc 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.guardlet scalar = keychain.scalar(credentialId: entry.credentialId) else { return .drop }var request: [String: String] = entry.arguments request["privateScalar"] = PasskeyAuthenticator.base64url(scalar)iflet lent { request["privateKey"] = lent }do { _ = tryawait core.callJSON(CottonMethod.passkeyRegister, request)return .done } catchlet refusal asCottonCallErrorwhereSelf.waits.contains(refusal.code) {return .wait } catchisCottonCallError {// 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 } }privatefunc used(_ entry: PasskeyEntry) async -> Outcome {do { _ = tryawait core.callJSON(CottonMethod.passkeyUsed, entry.arguments)return .done } catchlet refusal asCottonCallErrorwhereSelf.waits.contains(refusal.code) {return .wait } catchisCottonCallError {return .drop } catch {return .wait } }/// This device's vault key, read once after the presence prompt; nil on/// cancel or with no key.privatefunc vaultKey() async -> String? {let keyring = self.keyringreturnawaitTask.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 {guardlet 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) })]iflet lent { request["privateKey"] = .string(lent) }iflet answer = try? await core.callJSON(CottonMethod.passkeyMirror, request), let keys = answer["keys"]?.array {for key in keys {guardlet 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.sharedguardawait store.state().isEnabled else { return }let passkeys: [ASCredentialIdentity] = keychain.items(rpId: nil).compactMap { item inguardlet credential = PasskeyAuthenticator.fromBase64url(item.credentialId),let handle = PasskeyAuthenticator.fromBase64url(item.userHandle)else { returnnil }return ASPasskeyCredentialIdentity( relyingPartyIdentifier: item.rpId, userName: item.userName ?? "", credentialID: credential, userHandle: handle, recordIdentifier: item.credentialId ) }try? await store.replaceCredentialIdentities(passkeys + passwords.identities()) #endif }}