// THIS DEVICE'S VAULT KEY — the X25519 private half that opens the passwords.//// The model is `crates/cotton-core/src/vault` and Cotton note "The vault — the honest sentence".//// A second key beside `DeviceKey`, and the two must never be confused. The// device key is Ed25519 and it SIGNS: it is who this phone is, the server// approves it, and every owner request carries it in a header. This one is// X25519 and it UNWRAPS: the server wraps the workspace's vault master key for// its public half, and holding the private half is what lets this phone open a// password without asking anybody. Neither can do the other's job — a signing// key is not a key-agreement key — which is why there are two rather than one// clever one.//// ## Three decisions, each with the failure it avoids//// **THE GUARD IS THE SCREEN'S, NOT THE ITEM'S (e2e rulings R7, R8, R9; 16 Nov// 2026).** Until then the item carried `kSecAccessControlUserPresence`, so// every READ was the Face ID sheet. Recovery needs the key read with nobody// asked: the first sign-in founds with no question (R8), a phone re-opens by// itself once another device approves it, a recovery code or a trusted// person's help opens a new phone, and the iCloud Keychain copy is made in the// background (R7). So the item is now plain, and the prompt moved to// ``VaultKeyring/privateKey()`` (`VaultPresence`, `LAContext`'s// `.deviceOwnerAuthentication`: Face ID, Touch ID or the passcode), which every// reveal, Approve, Allow and Show still goes through; the prompt-free paths// call ``VaultKeyring/quietPrivateKey()`` and nothing else. The data key that// opens every sealed table was already kept this way (`DataKey.swift`). A// phone with no passcode is never blocked (R7): the act runs, as on Android.//// **`AfterFirstUnlockThisDeviceOnly`.** `ThisDeviceOnly` is load-bearing for// the same reason it is on the device key: a restore onto another phone must// not carry the vault (a new iPhone opens through the iCloud Keychain copy// instead, `recovery.openPlatform`, which is a different item made for that).// `AfterFirstUnlock` because the re-open after an approval and the help poll// may run as the app comes back behind the lock screen.//// **A LOST ITEM IS NOT A DISASTER.** If the slot is gone the phone mints a new// key and publishes it (`vault.publishKey`), and another vault device that is// already approved wraps the VMK for it once its code is typed there// (`signin.approve`): the Worker// holds no VMK, so device approval is the only wrap path. So unlike the device key — where an unreadable slot is// a named refusal and never a re-mint, because minting over an identity is a// different phone — this store MAY replace what it cannot read. Nothing is lost// by doing so: the passwords are sealed under the workspace's key, not under// this one.//// ## The Keychain search-attribute trap//// `DeviceKey`'s own header names it and it applies here twice over. **A search// attribute FILTERS.** `kSecAttrAccessible` or `kSecAttrAccessControl` in a// MATCH query means "an item filed exactly this way", so a query carrying them// would not match an item written under any other value: the read answers// `errSecItemNotFound`, the app decides there is no key, mints a second one,// and the wrap the server already wrote is orphaned. So `matchQuery` carries// the class, the service and the account and NOTHING else, exactly as// `KeychainDeviceKeyStore` does, and the access control appears only in the// dictionary handed to `SecItemAdd`.//// ## Never on the main thread//// `SecItemCopyMatching` on a presence-guarded item BLOCKS while the system// draws the Face ID sheet. `CottonCore` is an actor and the reveal reads it// there.//// ## On the simulator//// A simulator with no passcode and no enrolled Face ID asks nothing: the key// is minted, read and used as on a phone with no passcode. Features → Face ID// → Enrolled puts the sheet in front of a reveal, an Approve and an Allow.importCryptoKitimportFoundationimportLocalAuthenticationimportSecurity/// Where this device's vault private key is kept.////// A protocol for the reason `DeviceKeyStore` is one: a simulator's Keychain is/// shared between test runs, and a test that mints into the real one is a test/// that passes once.publicprotocolVaultKeyStore: Sendable {/// The stored key, or `nil` when there is none yet.////// Throws when the store answered something that is not a secret — which,/// on a presence-guarded item, includes the person cancelling the prompt./// A cancel is a decision, not a fault, and the caller draws it as one.func read() throws -> String?/// Is there an item at all — **without reading it, and so without asking/// the person for their face.**////// This is the whole reason the protocol has three members rather than two./// A presence-guarded item prompts on every READ, so a launch that checked/// for a key by reading one would put a Face ID sheet in front of the app/// every time it opened. A match query that returns ATTRIBUTES and not/// DATA decrypts nothing and prompts for nothing, which is exactly the/// question "have I minted yet" needs.func exists() -> Bool/// Store a key unless one is already there — **without reading what is/// there.** `true` when this key was stored, `false` when another was/// already in the slot.////// It answers a Bool and not "the key that is actually there" on purpose:/// answering the key would mean READING a presence-guarded item, and the/// launch mints through here. The one caller that wants the key after a/// lost race (`VaultKey.key`, a reveal) reads it itself, where a prompt/// belongs.func add(_ key: String) throws -> Bool/// Forget it. Only ever from a deliberate act.func forget()}/// What the store said when it would not answer.publicenumVaultKeyError: Error, Equatable {/// The store answered, and the answer was not a secret.case storeUnreadable(OSStatus)/// A key could not be written.case notWritten(OSStatus)/// The system could not give random bytes.case noRandom/// The device cannot guard an item behind presence at all — no passcode and/// no enrolled biometry. On a phone this is a person with no passcode; on/// the simulator it is Features → Face ID → Enrolled, unticked.case noPresence/// The person cancelled the Face ID / passcode prompt. A decision, drawn as/// one, and never retried on its own.case cancelled/// The slot is present and its contents are not a 32-byte key.case slotUnreadable/// macOS, and this build is not the signed app.////// A Mac's items live in the legacy file-based keychain, where access is/// gated by the CODE SIGNATURE that created the item — so a `swift build`/// binary asking for one raises a SecurityAgent dialog that a launch with/// no session cannot draw, and the app waits for ever (`Keychain`'s own/// header, and design M8). An unpackaged build therefore does not ask, and/// this is the state the screen draws instead of a prompt nobody can see.case notPackaged}publicenumVaultKey {/// The service every item in this app is filed under.////// **Two spellings, because there are two apps.** On the phone it is the/// bundle id, beside the device key. On the Mac it is the Mac app's own/// service, so this key is the FOURTH item beside the three/// `CottonHost/Client/Keychain.swift` already keeps — which is load-bearing/// rather than tidy: the Mac's boot reads that item and hands the private/// half to the core at `cotton_open`, and these screens read the SAME item/// for a reveal. Two items would be two keys, one of them wrapped for and/// one of them not. `CottonHostTests` asserts the two spellings agree.////// The ACCOUNT is what separates this key from the device key, on both. #if os(macOS)publicstaticlet service = AppFlavor.current.macKeychainService #elsepublicstaticlet service = DeviceKey.service #endif/// The account name. `device-key` is the Ed25519 identity; this is the/// X25519 half that opens the passwords.publicstaticlet account = "vault-key"/// The keychain group the app shares with its Keys provider, as the/// build stamped it (`CottonKeychainGroup`:/// `$(AppIdentifierPrefix)$(COTTON_KEYCHAIN_GROUP)`); `nil` on the Mac,/// in a bundle that names none, and where the stamp did not resolve.publicstaticvar accessGroup: String? { #if os(macOS)returnnil #elseguardlet group = Bundle.main.object(forInfoDictionaryKey: "CottonKeychainGroup") as? Stringelse { returnnil }return teamPrefixed(group) #endif }/// `group` when it starts with a team prefix (ten capitals or digits and/// a dot) — what a signed build stamps. An unsigned build stamps/// `$(AppIdentifierPrefix)` as nothing, and then there is no group to/// name: the item stays where the system files it.staticfunc teamPrefixed(_ group: String) -> String? {guardlet dot = group.firstIndex(of: "."), group.index(after: dot) < group.endIndex else { returnnil }let team = group[..<dot]guard team.count == 10, team.allSatisfy({ $0.isASCII && ($0.isUppercase || $0.isNumber) }) else { returnnil }return group }/// The app's own keychain group, where an item minted before the shared/// group existed was filed: the same team prefix, the bundle id.publicstaticvar legacyGroup: String? {guardlet group = accessGroup, let bundle = Bundle.main.bundleIdentifier,let dot = group.firstIndex(of: ".") else { returnnil }returnString(group[...dot]) + bundle }/// An X25519 scalar, 32 bytes, base64url unpadded — 43 characters, the same/// spelling `DeviceKey` uses and the one Rust decodes.publicstaticlet keyBytes = 32publicstaticlet keyLength = 43/// The key, minting one the first time.////// **A slot that will not read is REPLACED**, unlike the device key's. See/// the header: nothing is lost by minting again, because the passwords are/// sealed under the workspace's key rather than under this one, and the/// server re-wraps for whatever this phone publishes.publicstaticfunc key(store: someVaultKeyStore) throws -> String {iflet existing = try store.read() {if isKey(existing) { return existing } store.forget() }let minted = try mint()iftry store.add(minted) { return minted }// Somebody won the race. Theirs is the one this install has — read on// the reveal path, which is where a prompt belongs.guardlet existing = try store.read(), isKey(existing) else {throwVaultKeyError.storeUnreadable(errSecDuplicateItem) }return existing }/// Mint a key IF there is none, and answer it — **only when it was just/// minted.**////// `nil` means "there was already one", which is the launch-time answer: it/// says the key exists without reading it, so nothing prompts. The caller/// publishes the public half of a freshly-minted key and, for one that was/// already there, publishes the half it cached at mint.////// **It never reads.** An `exists()` that answers no for an item that is/// there (a race, or a Keychain that will not say) ends in `add` finding/// the slot taken, and that is answered as "there was already one" — never/// by reading the item, which on the phone is the presence prompt at launch.publicstaticfunc mintIfAbsent(store: someVaultKeyStore) throws -> String? {if store.exists() { returnnil }let minted = try mint()returntry store.add(minted) ? minted : nil }/// Start this phone's vault over: a new key, published, re-wrapped.publicstaticfunc forget(store: someVaultKeyStore) { store.forget() }/// Is this what we wrote — 43 base64url characters decoding to 32 bytes?publicstaticfunc isKey(_ text: String) -> Bool {guard text.count == keyLength else { returnfalse }returnDeviceKey.decode(text)?.count == keyBytes }/// The PUBLIC half, which is what `vault.publishKey` and the join carry.////// Curve25519 key agreement, from CryptoKit: the public half of an X25519/// scalar, base64url, the spelling `cotton_core::vault::wrap` reads.publicstaticfunc publicHalf(of key: String) -> String? {guardlet bytes = DeviceKey.decode(key), bytes.count == keyBytes else { returnnil }guardlet secret = try? Curve25519.KeyAgreement.PrivateKey(rawRepresentation: bytes)else { returnnil }returnDeviceKey.encode(secret.publicKey.rawRepresentation) }staticfunc mint() throws -> String {var bytes = [UInt8](repeating: 0, count: keyBytes)guardSecRandomCopyBytes(kSecRandomDefault, bytes.count, &bytes) == errSecSuccess else {throwVaultKeyError.noRandom }// CLAMPED by X25519 itself on use — `cotton_core::vault::wrap` and// CryptoKit both do it — so 32 random bytes are a valid scalar and no// clamping is done here. Doing it in two places would be two opinions// about what the key IS.returnDeviceKey.encode(Data(bytes)) }}/// The real store.publicstructKeychainVaultKeyStore: VaultKeyStore {privatelet service: Stringprivatelet account: String/// What the prompt says above the Face ID sheet. Plain words: this is the/// one sentence a person reads with their thumb on the sensor.privatelet reason: String/// THE SHARED ACCESS GROUP (Cotton Keys, 8 Nov 2026): the keychain group/// the app shares with its Keys provider extension/// (`$(AppIdentifierPrefix)$(COTTON_KEYCHAIN_GROUP)`), so the provider/// opens the vault under the same presence check. `nil` on the Mac and in/// a build that names none: the item lives where the system files it.privatelet accessGroup: String?/// Where an item minted before the shared group was filed — the app's/// own group (`<prefix><bundle id>`). Read once, moved into/// `accessGroup` and deleted there, in that order (`read`).privatelet legacyGroup: String?/// Guarded by presence on the item itself. Never by default: the guard is/// the screen's (`VaultPresence`, see the header); `true` is kept only for/// a test that wants an item filed the old way.privatelet guarded: Boolpublicinit( service: String = VaultKey.service, account: String = VaultKey.account, reason: String = VaultPresence.reason, accessGroup: String? = VaultKey.accessGroup, legacyGroup: String? = VaultKey.legacyGroup, guarded: Bool = false ) {self.service = serviceself.account = accountself.reason = reasonself.accessGroup = accessGroupself.legacyGroup = accessGroup == nil ? nil : legacyGroupself.guarded = guarded }/// The key, from the shared group; an item still filed in the app's own/// group is moved there on the way (``moved(from:)``).publicfunc read() throws -> String? {// A build that does not hold the shared group (an entitlement that did// not land) reads nothing there, and keeps using the old item.let found: String?do { found = try read(in: accessGroup) } catchVaultKeyError.storeUnreadable(errSecMissingEntitlement) where legacyGroup != nil { found = nil }iflet found { return found }guardlet legacyGroup, let old = try read(in: legacyGroup) else { returnnil } moved(old, from: legacyGroup)return old }/// THE ONE MOVE: the old item has been READ (the prompt already shown);/// it is WRITTEN into the shared group, and only once that write landed/// (or the group already holds it) is the old one DELETED. Any failure/// leaves the old item where it was, and the next read tries again.privatefunc moved(_ key: String, from old: String) {guardlet accessGroup else { return }let added: Booldo { added = try add(key, in: accessGroup) || exists(in: accessGroup) } catch { return }guard added else { return }SecItemDelete(KeychainVaultKeyStore.matchQuery(service: service, account: account, group: old) as CFDictionary) }privatefunc read(in group: String?) throws -> String? {KeychainGate.check(service: service, account: account)iflet refusal = KeychainVaultKeyStore.unpackaged() { throw refusal }var query = KeychainVaultKeyStore.matchQuery(service: service, account: account, group: group) query[kSecReturnData asString] = true query[kSecMatchLimit asString] = kSecMatchLimitOne// The sentence the system draws. It is an OPERATION prompt, not a// search attribute, so it narrows nothing — see the trap in the header.// On the Mac the item carries no access control, so nothing is drawn// and this is simply ignored; the Touch ID prompt in front of a reveal// there is the SCREEN's (`VaultAccess`), not the item's. query[kSecUseOperationPrompt asString] = reasonvar found: CFTypeRef?let status = SecItemCopyMatching(query as CFDictionary, &found)if status == errSecItemNotFound { returnnil }if status == errSecUserCanceled || status == errSecAuthFailed {throwVaultKeyError.cancelled }guard status == errSecSuccess, let data = found as? Dataelse {throwVaultKeyError.storeUnreadable(status) }returnString(decoding: data, as: UTF8.self) }publicfunc exists() -> Bool { exists(in: accessGroup) || legacyGroup.map { exists(in: $0) } == true }privatefunc exists(in group: String?) -> Bool {KeychainGate.check(service: service, account: account)ifKeychainVaultKeyStore.unpackaged() != nil { returnfalse }var query = KeychainVaultKeyStore.matchQuery(service: service, account: account, group: group)// ATTRIBUTES, never DATA — see the protocol. Returning data would// decrypt the item and draw the Face ID sheet; returning attributes// answers "is it there" off the keychain's own index. query[kSecReturnAttributes asString] = true query[kSecMatchLimit asString] = kSecMatchLimitOne// And no UI, whatever the item asks: a context that may not interact// turns any authentication the query would need into// `errSecInteractionNotAllowed` — which still says the item is there.let context = LAContext() context.interactionNotAllowed = true query[kSecUseAuthenticationContext asString] = contextvar found: CFTypeRef?let status = SecItemCopyMatching(query as CFDictionary, &found)return status == errSecSuccess || status == errSecInteractionNotAllowed }publicfunc add(_ key: String) throws -> Bool {// A key filed in the old group is the one this install has: never a// second beside it in the new one.iflet legacyGroup, exists(in: legacyGroup) { returnfalse }returntry add(key, in: accessGroup) }privatefunc add(_ key: String, in group: String?) throws -> Bool {KeychainGate.check(service: service, account: account)iflet refusal = KeychainVaultKeyStore.unpackaged() { throw refusal }var attributes = KeychainVaultKeyStore.matchQuery(service: service, account: account, group: group) #if os(macOS)// NO ACCESS CONTROL, and `ThisDeviceOnly` in its place. The server// opens an assistant's API key with nobody at the keyboard and the// placement applier writes a file into a build nobody is watching;// an item that prompted would stop both. The login session is the// guard, and the reveal screen's Touch ID prompt is a courtesy the// screen performs — see the type's header, and spec §7.1.//// The attribute is written the way `CottonHost`'s own three items// are, because that file puts `kSecAttrAccessible` in its MATCH// query: an item written without it would be filed as plain// `WhenUnlocked` and the Mac's boot would not find it. attributes[kSecAttrAccessible asString] = kSecAttrAccessibleWhenUnlockedThisDeviceOnly #elseif guarded {guardlet control = KeychainVaultKeyStore.presence() else {throwVaultKeyError.noPresence } attributes[kSecAttrAccessControl asString] = control } else { attributes[kSecAttrAccessible asString] = kSecAttrAccessibleAfterFirstUnlockThisDeviceOnly } #endif attributes[kSecValueData asString] = Data(key.utf8)let status = SecItemAdd(attributes as CFDictionary, nil)// Somebody won the race: theirs is the one this install has, and it is// NOT read here (see the protocol).if status == errSecDuplicateItem { returnfalse }guard status == errSecSuccess else { throwVaultKeyError.notWritten(status) }returntrue }publicfunc forget() {KeychainGate.check(service: service, account: account)for group in [accessGroup, legacyGroup] where group != nil || accessGroup == nil {SecItemDelete(KeychainVaultKeyStore.matchQuery(service: service, account: account, group: group) as CFDictionary ) } }/// `nil` on the phone, and on a packaged Mac app: both may ask the/// Keychain. A `swift build` Mac binary may NOT — see/// ``VaultKeyError/notPackaged``.staticfunc unpackaged() -> VaultKeyError? { #if os(macOS)returnBundle.main.bundleIdentifier == nil ? .notPackaged : nil #elsereturnnil #endif }/// Face ID, Touch ID, or the passcode — re-asked on every read.////// `nil` when the device can guard nothing behind presence: no passcode and/// no enrolled biometry, which is a simulator out of the box. The caller/// turns that into `VaultKeyError.noPresence`, a line on the screen.staticfunc presence() -> SecAccessControl? {SecAccessControlCreateWithFlags(nil, kSecAttrAccessibleWhenUnlockedThisDeviceOnly, .userPresence,nil ) }/// How the item is FOUND — class, service, account, and DELIBERATELY no/// accessibility and no access control.////// **A search attribute filters**, so either of those in a match query/// would mean "an item filed exactly this way" and would miss an item/// written under any other value — the read answers not-found, the app/// mints a second key, and the wrap the server already wrote is orphaned./// `KeychainDeviceKeyStore.matchQuery` carries the same three keys for the/// same reason.////// The access GROUP is the one filter added, and on purpose: it is what/// tells the shared group's item from one still filed in the app's own.staticfunc matchQuery(service: String, account: String, group: String? = nil) -> [String: Any] {var query: [String: Any] = [ kSecClass asString: kSecClassGenericPassword, kSecAttrService asString: service, kSecAttrAccount asString: account, ]iflet group { query[kSecAttrAccessGroup asString] = group }return query }}/// A store in memory — what every `VaultKey` test drives, and the only way to/// reproduce a cancelled prompt or a device with no passcode without a phone.publicfinalclassInMemoryVaultKeyStore: VaultKeyStore, @unchecked Sendable {privatelet lock = NSLock()privatevar stored: String?privatevar failure: VaultKeyError?privatelet indexed: Boolpublicprivate(set) var mintCount = 0/// Every read of the stored key — on the phone, every one is the presence/// prompt. What the launch guards count.publicprivate(set) var readCount = 0/// `indexed: false` is a store whose `exists()` answers no while a key IS/// there — a Keychain that would not say, or a race lost between the/// question and the write.publicinit(seeded: String? = nil, failing: VaultKeyError? = nil, indexed: Bool = true) { stored = seeded failure = failingself.indexed = indexed }publicfunc read() throws -> String? { lock.lock()defer { lock.unlock() } readCount += 1iflet failure { throw failure }return stored }publicfunc exists() -> Bool { lock.lock()defer { lock.unlock() }return indexed && stored != nil }publicfunc add(_ key: String) throws -> Bool { lock.lock()defer { lock.unlock() }iflet failure { throw failure }if stored != nil { returnfalse } stored = key mintCount += 1returntrue }publicfunc forget() { lock.lock()defer { lock.unlock() } stored = nil }}