// Somebody else's credential, kept on this phone and nowhere else. // // Two screens held one: the AI page's provider API keys (gone with that page on // 2026-09-14) and `/settings#code-hosting`'s per-host access tokens. Both say the same thing // about custody, and both are the SAME mechanism — the Keychain, one slot per // name — so they are one seam here rather than two. // // **This is deliberately NOT `DeviceKey`.** That file holds this phone's own // identity: minted once, never rotated, never overwritten, and a slot that will // not read is a named refusal rather than a re-mint, because minting over an // identity is a different phone. A provider key is the opposite in every one of // those respects — it is replaced when the person types a new one, deleted when // they tap Remove, and an unreadable slot is simply a key that is not there. // Sharing one type between the two would mean one set of rules for two things // that need different ones. // // **The two custody stories the screens tell are different and stay different.** // An AI key is kept here AND sent to the server for an encrypted copy in the // person's own file, because background filing runs while the phone is asleep // and has no request to read a header from. A code-hosting // token is kept here and nowhere else, because nothing on Cotton's side ever // reads a repo on the owner's behalf. The copy is a property of the SCREEN's // write path, not of this store. // // **The Keychain cannot be enumerated**, which is why code hosting keeps an // index slot naming the hosts it holds a token for: without it the only hosts // Cotton could ask about are the ones a project happens to name today, and a // token saved for any other host would sit on the device unseen and // unremovable. The index holds host names only, never a token. That index is // the screen's own shape; what is here is the slot it lives in. // // Never on the main thread. `SecItemCopyMatching` blocks on a SecurityAgent // prompt whenever the binary's signature has changed since the item was // written, which is every rebuild during development. import Foundation import Security /// Where a credential is kept. /// /// A protocol for the reason `DeviceKeyStore` is one: a simulator's Keychain is /// shared between test runs, so a test that writes into the real one is a test /// that passes once. public protocol SecretStore: Sendable { /// What is in the slot, or `nil` when there is nothing. /// /// An unreadable slot answers `nil` rather than throwing. That is the /// TypeScript's behaviour, written down where it is made /// (`getByokCredential`): *"An unreadable entry is a dead entry — treat as /// absent; the settings screen will simply show no key saved."* It is safe /// here and would not be in `DeviceKey`, because the way out of a dead slot /// is to type the key again. func read(_ slot: String) -> String? /// Put a value in, replacing whatever was there. /// /// Answers whether it landed. A screen that showed "Key saved" over a write /// the Keychain refused would be telling the person their key is on this /// phone when it is not. @discardableResult func write(_ value: String, to slot: String) -> Bool /// Take it out. A slot that was already empty is a success. func forget(_ slot: String) } /// The real store. public struct KeychainSecretStore: SecretStore { private let service: String /// The same service every item in this app is filed under — the bundle id. /// The ACCOUNT is what separates one credential from another. public init(service: String = DeviceKey.service) { self.service = service } public func read(_ slot: String) -> String? { KeychainGate.check(service: service, account: slot) var query = baseQuery(slot) query[kSecReturnData as String] = true query[kSecMatchLimit as String] = kSecMatchLimitOne var found: CFTypeRef? let status = SecItemCopyMatching(query as CFDictionary, &found) guard status == errSecSuccess, let data = found as? Data else { return nil } let text = String(decoding: data, as: UTF8.self) return text.isEmpty ? nil : text } @discardableResult public func write(_ value: String, to slot: String) -> Bool { KeychainGate.check(service: service, account: slot) // Delete-then-add rather than `SecItemUpdate`: an update against a slot // that does not exist answers `errSecItemNotFound`, so the update path // would need the add path anyway and both orders would be live. // // **The delete is what makes a failed add destructive**, and that is the // hazard this reads the old value first for. `expo-secure-store` has the // same delete-then-add shape and the same hole: the add fails, the // screen says "Something went wrong", and the key the person HAD is // gone with the one they typed. So the previous value is put back, and // the answer is still `false` — a screen that showed "Key saved" over a // write the Keychain refused would be telling somebody their key is on // this phone when it is not. let previous = read(slot) SecItemDelete(baseQuery(slot) as CFDictionary) var attributes = baseQuery(slot) attributes[kSecValueData as String] = Data(value.utf8) if SecItemAdd(attributes as CFDictionary, nil) == errSecSuccess { return true } if let previous { var restore = baseQuery(slot) restore[kSecValueData as String] = Data(previous.utf8) // Best effort by necessity: if the Keychain will not take the new // value it may not take the old one either, and there is nothing // further to try. The failure is already being reported. SecItemAdd(restore as CFDictionary, nil) } return false } public func forget(_ slot: String) { KeychainGate.check(service: service, account: slot) SecItemDelete(baseQuery(slot) as CFDictionary) } private func baseQuery(_ slot: String) -> [String: Any] { [ kSecClass as String: kSecClassGenericPassword, kSecAttrService as String: service, kSecAttrAccount as String: slot, // Never restored onto another phone. A restored phone is a new // device; somebody else's credential does not travel with a backup. kSecAttrAccessible as String: kSecAttrAccessibleWhenUnlockedThisDeviceOnly, ] } } /// A store in memory — the double every test drives. public final class InMemorySecretStore: SecretStore, @unchecked Sendable { private let lock = NSLock() private var slots: [String: String] /// Slots this store refuses to write, so a screen's "that did not save" /// path is reachable without a Keychain that will not fail on demand. public var refusing: Set = [] public init(_ slots: [String: String] = [:]) { self.slots = slots } public func read(_ slot: String) -> String? { lock.lock() defer { lock.unlock() } return slots[slot] } @discardableResult public func write(_ value: String, to slot: String) -> Bool { lock.lock() defer { lock.unlock() } if refusing.contains(slot) { return false } slots[slot] = value return true } public func forget(_ slot: String) { lock.lock() defer { lock.unlock() } slots[slot] = nil } /// Every slot that holds something — a TEST's question, never the app's: /// the real Keychain cannot answer it, which is the whole reason code /// hosting keeps an index of its own. public var occupied: [String] { lock.lock() defer { lock.unlock() } return slots.keys.sorted() } }