// Where a passkey's private half lives on this phone: one item per credential// in the keychain group Cotton Keys shares with its credential provider.//// The item is DEVICE-LOCAL PLAINTEXT under the device's own protection// (`kSecAttrAccessibleAfterFirstUnlockThisDeviceOnly`, never synced, never// backed up off the phone); the row's `private_key_enc` is the synced copy,// sealed under the vault. The provider writes an item when it registers and// reads one to sign; the app reads one for the call that seals it into a row,// writes one for a row made on another device (`passkey.mirror`), and removes// the item of a row that is gone.//// The scalar is 32 bytes; the item's `generic` attribute carries what the// picker and the identity store need (site, site name, account, account id,// made) — never the key. Nothing here logs.importFoundationimportSecurity/// What a kept passkey says about itself, without its key.publicstructPasskeyKeychainItem: Codable, Equatable, Sendable {publicvar credentialId: Stringpublicvar rpId: Stringpublicvar rpName: String?publicvar userName: String?publicvar userHandle: Stringpublicvar createdAt: Stringpublicinit(credentialId: String, rpId: String, rpName: String?, userName: String?, userHandle: String, createdAt: String) {self.credentialId = credentialIdself.rpId = rpIdself.rpName = rpNameself.userName = userNameself.userHandle = userHandleself.createdAt = createdAt }privateenumCodingKeys: String, CodingKey {case credentialId = "credential_id"case rpId = "rp_id"case rpName = "rp_name"case userName = "user_name"case userHandle = "user_handle"case createdAt = "created_at" }}/// Why the keychain refused, by its OSStatus.structPasskeyKeychainError: Error, Equatable, Sendable {let status: OSStatus}/// Where passkey items are kept: the shared keychain group on a phone, a/// dictionary in a test.publicprotocolPasskeyKeys: Sendable {func save(_ item: PasskeyKeychainItem, scalar: Data) throwsfunc scalar(credentialId: String) -> Data?func items(rpId: String?) -> [PasskeyKeychainItem]func remove(credentialId: String)}/// The shared keychain group's passkey items.publicstructPasskeyKeychain: PasskeyKeys {/// The service every passkey item is filed under.publicstaticlet service = "cotton.keys.passkey"privatelet accessGroup: String?/// `accessGroup` nil files the item where the system does (a test, an/// unsigned build); a shipping build names the shared group.publicinit(accessGroup: String? = PasskeyKeychain.sharedGroup()) {self.accessGroup = accessGroup }/// The group the app and its provider share: this bundle's/// `CottonKeychainGroup`, when a signed build stamped it team-prefixed.publicstaticfunc sharedGroup(bundle: Bundle = .main) -> String? {guardlet group = bundle.object(forInfoDictionaryKey: "CottonKeychainGroup") as? String,let dot = group.firstIndex(of: "."), group.index(after: dot) < group.endIndexelse { returnnil }let team = group[..<dot]guard team.count == 10, team.allSatisfy({ $0.isASCII && ($0.isUppercase || $0.isNumber) }) else { returnnil }return group }privatefunc base() -> [String: Any] {var query: [String: Any] = [ kSecClass asString: kSecClassGenericPassword, kSecAttrService asString: Self.service, ]iflet accessGroup { query[kSecAttrAccessGroup asString] = accessGroup }return query }/// Keep `scalar` for `item`, replacing an item for the same credential.publicfunc save(_ item: PasskeyKeychainItem, scalar: Data) throws { remove(credentialId: item.credentialId)var query = base() query[kSecAttrAccount asString] = item.credentialId query[kSecAttrLabel asString] = item.rpId query[kSecAttrGeneric asString] = try JSONEncoder().encode(item) query[kSecValueData asString] = scalar query[kSecAttrAccessible asString] = kSecAttrAccessibleAfterFirstUnlockThisDeviceOnly query[kSecAttrSynchronizable asString] = falselet status = SecItemAdd(query as CFDictionary, nil)guard status == errSecSuccess else { throwPasskeyKeychainError(status: status) } }/// The scalar kept for this credential, or nil.publicfunc scalar(credentialId: String) -> Data? {var query = base() query[kSecAttrAccount asString] = credentialId query[kSecReturnData asString] = true query[kSecMatchLimit asString] = kSecMatchLimitOnevar found: CFTypeRef?guardSecItemCopyMatching(query as CFDictionary, &found) == errSecSuccess else { returnnil }return found as? Data }/// Every kept passkey, or those for one site — without their keys.publicfunc items(rpId: String? = nil) -> [PasskeyKeychainItem] {var query = base()iflet rpId { query[kSecAttrLabel asString] = rpId } query[kSecReturnAttributes asString] = true query[kSecMatchLimit asString] = kSecMatchLimitAllvar found: CFTypeRef?guardSecItemCopyMatching(query as CFDictionary, &found) == errSecSuccess,let rows = found as? [[String: Any]]else { return [] }return rows.compactMap { row inguardlet generic = row[kSecAttrGeneric asString] as? Dataelse { returnnil }returntry? JSONDecoder().decode(PasskeyKeychainItem.self, from: generic) } .sorted { ($0.rpId, $0.userName ?? "") < ($1.rpId, $1.userName ?? "") } }/// The item for one credential, without its key.publicfunc item(credentialId: String) -> PasskeyKeychainItem? { items().first { $0.credentialId == credentialId } }/// Forget one credential's item.publicfunc remove(credentialId: String) {var query = base() query[kSecAttrAccount asString] = credentialIdSecItemDelete(query as CFDictionary) }}