// This phone's identity — an Ed25519 seed minted once, held in the Keychain,// never rotated, never shared. The PUBLIC half is the device id the server// approves, so a request carries its own key and the server needs no key// column.//// Swift owns the Keychain and nothing else of the identity (design P15, the// Mac's M8): the seed is read here, handed down at `cotton_open` as// `OpenConfig.deviceSecret`, and Rust derives the id and signs. Nothing under// `crates/` calls a Keychain API and nothing else in this app does// either — a second reader would be a second opinion about where this phone's// identity lives.//// Four rules, all of them the Mac's and all of them measured there://// * **A read is idempotent and never replaces what it finds.** A seed IS an// identity; minting a new one over an old one is not a recovery, it is a// different phone. So a read that FAILS is reported and never repaired.// * **`AfterFirstUnlockThisDeviceOnly`.** `ThisDeviceOnly` is the load-bearing// half: an iCloud or iTunes restore onto another phone carries no key, so a// restored phone is a NEW device and pairs again — the whole point of the// key being an identity rather than a setting, since two phones answering to// one device id is two writers on one approval.//// `AfterFirstUnlock` rather than `WhenUnlocked` because the app does not// only run when somebody is looking at it. A launch while the phone is// locked — a notification's background fetch, the app// resumed behind a lock screen — read `errSecInteractionNotAllowed` on the// stricter setting, which this app turns into `device_key_unreadable`: a// screen whose only button MINTS A NEW IDENTITY. A key that cannot be read// for a few seconds is not a key that is gone. After the first unlock since// boot the item is readable, which is every moment the app can actually run.// Guard: `DeviceKeyTests`.// * **A slot that exists and cannot be read is `device_key_unreadable`, NEVER// a second identity.** Minting over an unreadable slot would strand every// approval the first one holds, silently. The way out is deliberate:// ``DeviceKey/forget(store:)`` from the refusal screen's destructive pill.// * **Never on the main thread.** `SecItemCopyMatching` blocks on a// SecurityAgent prompt whenever the binary's signature has changed since the// item was written. `CottonCore` is an actor and the boot reads it there.//// **The previous app's slot is deliberately not read.** `cotton.device.key`// held a JSON envelope in a different secure store; this app writes a bare// base64url seed under its own account name. A phone upgrading from that build// therefore re-pairs as a NEW device, which is acceptable under// [i-m-the-only-cotton-user-the-app-carries-no-backward-compatibili] and is// written down in Cotton note "The phone and Mac app — how a screen is built". Reading the old slot would// mean carrying that envelope and its keychain service name into a build that// has neither.importFoundationimportSecurity/// Where the seed is kept. A protocol so `DeviceKey`'s rules are provable/// without a Keychain — a simulator's Keychain is shared between test runs and/// a test that mints into it is a test that passes once.publicprotocolDeviceKeyStore: Sendable {/// The stored seed, or `nil` when there is none yet. Throws only when the/// store itself answered something that is not a secret.func read() throws -> String?/// Store a seed. Refuses to overwrite: answers what is actually there.func writeIfAbsent(_ seed: String) throws -> String/// Forget it. Only ever from a deliberate act.func forget()/// Put `seed` in the slot, over whatever is there. Only ever a re-key's/// promotion (`DeviceKey.promote`), after the server answered the new key.func replace(_ seed: String) throws}/// What the store said when it would not answer.publicenumDeviceKeyError: Error, Equatable {/// The store answered, and the answer was not a secret.case storeUnreadable(OSStatus)/// A secret could not be written.case notWritten(OSStatus)/// The system could not give random bytes.case noRandom/// The slot is present and its contents are not a 32-byte seed. NOT "no/// key": this is the refusal the screen calls `device_key_unreadable`.case slotUnreadable}publicenumDeviceKey {/// The service every item is filed under. Stable for the life of the app:/// changing it is losing this phone's identity. Per flavor/// (`AppFlavor.phoneKeychainService`) — the real app's is its bundle id,/// `com.cottondb.cotton`, and Cotton Dev never names it.publicstaticlet service = AppFlavor.current.phoneKeychainService/// The account name. The previous build's was `cotton.device.key`; see/// above.publicstaticlet account = "device-key"/// Where "Re-key this device" keeps the NEW key while its approval is/// asked: beside the key in use, never over it, until the new key's row is/// live (`promote`). A second press finds the same successor here.publicstaticlet successorAccount = "device-key-successor"/// A 32-byte seed, base64url unpadded — 43 characters.publicstaticlet seedBytes = 32publicstaticlet seedLength = 43/// The seed, minting one the first time.////// Throws ``DeviceKeyError/slotUnreadable`` when the slot is present and/// unreadable, which is the one failure this function must never repair.publicstaticfunc seed(store: someDeviceKeyStore) throws -> String {iflet existing = try store.read() {guard isSeed(existing) else { throwDeviceKeyError.slotUnreadable }return existing }returntry store.writeIfAbsent(mint()) }/// Start this phone over: a NEW identity next time. The server will know it/// as a new device, to be paired again.publicstaticfunc forget(store: someDeviceKeyStore) { store.forget() }/// THE RE-KEY'S LAST STEP, once the server has answered the successor:/// the successor goes into the key's slot and only then leaves its own,/// so a process killed between the two finds the same key in both and a/// launch finishes it (`successorPending`). Answers whether anything moved. @discardableResultpublicstaticfunc promote(successor: someDeviceKeyStore, into current: someDeviceKeyStore) throws -> Bool {guardlet next = try successor.read() else { returnfalse }guard isSeed(next) else { throwDeviceKeyError.slotUnreadable }iftry current.read() != next { try current.replace(next) } successor.forget()returntrue }/// The successor a launch must still ask about: present and not already/// the key in use. One that IS the key in use is a promotion that was cut/// short after its first half, and is finished here.publicstaticfunc successorPending(successor: someDeviceKeyStore, current: someDeviceKeyStore) -> String? {guardlet next = try? successor.read(), isSeed(next) else { returnnil }if (try? current.read()) == next { successor.forget()returnnil }return next }/// Is this what we wrote — 43 base64url characters decoding to 32 bytes?publicstaticfunc isSeed(_ text: String) -> Bool {guard text.count == seedLength else { returnfalse }return decode(text)?.count == seedBytes }staticfunc mint() throws -> String {var bytes = [UInt8](repeating: 0, count: seedBytes)guardSecRandomCopyBytes(kSecRandomDefault, bytes.count, &bytes) == errSecSuccess else {throwDeviceKeyError.noRandom }return encode(Data(bytes)) }/// base64url, unpadded — what Rust decodes and what `x-cotton-device`/// carries.publicstaticfunc encode(_ data: Data) -> String { data.base64EncodedString() .replacingOccurrences(of: "+", with: "-") .replacingOccurrences(of: "/", with: "_") .replacingOccurrences(of: "=", with: "") }publicstaticfunc decode(_ text: String) -> Data? {var padded = text .replacingOccurrences(of: "-", with: "+") .replacingOccurrences(of: "_", with: "/")while padded.count % 4 != 0 { padded.append("=") }returnData(base64Encoded: padded) }}/// The real store — the Security framework's whole surface in this app.publicstructKeychainDeviceKeyStore: DeviceKeyStore {privatelet service: Stringprivatelet account: Stringpublicinit(service: String = DeviceKey.service, account: String = DeviceKey.account) {self.service = serviceself.account = account }publicfunc read() throws -> String? {KeychainGate.check(service: service, account: account)var query = KeychainDeviceKeyStore.matchQuery(service: service, account: account) query[kSecReturnData asString] = true query[kSecMatchLimit asString] = kSecMatchLimitOnevar found: CFTypeRef?let status = SecItemCopyMatching(query as CFDictionary, &found)if status == errSecItemNotFound { returnnil }guard status == errSecSuccess, let data = found as? Dataelse {throwDeviceKeyError.storeUnreadable(status) } migrateAccessibility()returnString(decoding: data, as: UTF8.self) }/// Move an item written by an earlier build onto/// `AfterFirstUnlockThisDeviceOnly`.////// **The phone in somebody's pocket already HAS a key**, written under/// `WhenUnlockedThisDeviceOnly`. Shipping the new attribute without this/// would leave that phone reading its old item for ever — and reading it/// only while unlocked, which is the failure being repaired. `SecItemUpdate`/// re-files the same bytes: the identity does not change, so no server/// re-approves anything.////// Best effort and never reported: the seed has already been read by here,/// and failing a launch because an accessibility attribute could not be/// updated would be worse than the thing it fixes. The next read tries/// again.privatefunc migrateAccessibility() {KeychainGate.check(service: service, account: account)let query = KeychainDeviceKeyStore.matchQuery(service: service, account: account)let attributes: [String: Any] = [ kSecAttrAccessible asString: KeychainDeviceKeyStore.accessibility ] _ = SecItemUpdate(query as CFDictionary, attributes as CFDictionary) }publicfunc replace(_ seed: String) throws {KeychainGate.check(service: service, account: account)let query = KeychainDeviceKeyStore.matchQuery(service: service, account: account)let status = SecItemUpdate(query as CFDictionary, [kSecValueData asString: Data(seed.utf8)] as CFDictionary)if status == errSecItemNotFound { _ = try writeIfAbsent(seed)return }guard status == errSecSuccess else { throwDeviceKeyError.notWritten(status) } }publicfunc writeIfAbsent(_ seed: String) throws -> String {KeychainGate.check(service: service, account: account)var attributes = KeychainDeviceKeyStore.addAttributes(service: service, account: account) attributes[kSecValueData asString] = Data(seed.utf8)let status = SecItemAdd(attributes as CFDictionary, nil)if status == errSecDuplicateItem {// Somebody won the race. Theirs is the one this install has.guardlet existing = try read() else {throwDeviceKeyError.storeUnreadable(status) }return existing }guard status == errSecSuccess else { throwDeviceKeyError.notWritten(status) }return seed }publicfunc forget() {KeychainGate.check(service: service, account: account)SecItemDelete(KeychainDeviceKeyStore.matchQuery(service: service, account: account) as CFDictionary ) }/// How the item is filed: readable after the first unlock since boot, and/// never carried onto another phone.////// One place, read by the ADD and by the migration, so the two cannot come/// to disagree about what this build writes.staticvar accessibility: CFString { kSecAttrAccessibleAfterFirstUnlockThisDeviceOnly }/// How the item is FOUND — class, service, account, and deliberately no/// accessibility.////// **A search attribute filters, and that is the trap.** `kSecAttrAccessible`/// in a match query means "an item filed THIS way", so a query carrying the/// new value would not match the item the last build wrote: the read would/// answer `errSecItemNotFound`, the app would treat it as a phone with no/// key, mint a second identity, and every approval the first one holds/// would be stranded — the exact failure `DeviceKey`'s own header refuses,/// arrived at by changing one line.staticfunc matchQuery(service: String, account: String) -> [String: Any] { [ kSecClass asString: kSecClassGenericPassword, kSecAttrService asString: service, kSecAttrAccount asString: account, ] }/// How the item is WRITTEN: the match query plus this build's/// accessibility.staticfunc addAttributes(service: String, account: String) -> [String: Any] {var attributes = matchQuery(service: service, account: account) attributes[kSecAttrAccessible asString] = accessibilityreturn attributes }}/// A store in memory — the double every `DeviceKey` test drives, and the one/// way to reproduce `device_key_unreadable` without corrupting a real Keychain.publicfinalclassInMemoryDeviceKeyStore: DeviceKeyStore, @unchecked Sendable {privatelet lock = NSLock()privatevar stored: String?publicprivate(set) var mintCount = 0publicinit(seeded: String? = nil) { stored = seeded }publicfunc read() throws -> String? { lock.lock()defer { lock.unlock() }return stored }publicfunc writeIfAbsent(_ seed: String) throws -> String { lock.lock()defer { lock.unlock() }iflet stored { return stored } stored = seed mintCount += 1return seed }publicfunc forget() { lock.lock()defer { lock.unlock() } stored = nil }publicfunc replace(_ seed: String) throws { lock.lock()defer { lock.unlock() } stored = seed }}