// The data key sealed tables open with (sealing plan §2.1, §2.4), kept on// this phone so a background pull opens sealed rows.//// It is NOT the vault key. The vault key opens passwords and is guarded by// presence: reading it draws Face ID. The data key opens messages and mail,// and a pull that runs while the phone sits in a pocket must open them with// nobody looking, so its item carries no access control and is readable// after the first unlock since boot (`AfterFirstUnlockThisDeviceOnly`), never// restored onto another phone. Losing it costs nothing: the next vault open// takes it again from the object's `seal_key` row.//// One item per database (account `data-key:<database id>`), the base64url// text the core hands over (`seal.heldKey`) and takes back (`seal.useKey`).importFoundationimportSecurity/// Where this phone keeps each database's data key.publicprotocolDataKeyKeeping: Sendable {func read(database: String) -> String? @discardableResult func write(_ key: String, database: String) -> Boolfunc forget(database: String)}/// The Keychain's data keys: no presence, after first unlock, this device only.publicstructDataKeychain: DataKeyKeeping {privatelet service: Stringpublicinit(service: String = DeviceKey.service) {self.service = service }staticfunc account(_ database: String) -> String { "data-key:\(database)" }publicfunc read(database: String) -> String? {var query = base(database) query[kSecReturnData asString] = true query[kSecMatchLimit asString] = kSecMatchLimitOnevar found: CFTypeRef?guardSecItemCopyMatching(query as CFDictionary, &found) == errSecSuccess, let data = found as? Dataelse { returnnil }let text = String(decoding: data, as: UTF8.self)return text.isEmpty ? nil : text } @discardableResult publicfunc write(_ key: String, database: String) -> Bool {SecItemDelete(base(database) as CFDictionary)var attributes = base(database) attributes[kSecValueData asString] = Data(key.utf8)// Set on the add only: a search attribute filters, so a read never names it. attributes[kSecAttrAccessible asString] = kSecAttrAccessibleAfterFirstUnlockThisDeviceOnlyreturnSecItemAdd(attributes as CFDictionary, nil) == errSecSuccess }publicfunc forget(database: String) {SecItemDelete(base(database) as CFDictionary) }privatefunc base(_ database: String) -> [String: Any] { [ kSecClass asString: kSecClassGenericPassword, kSecAttrService asString: service, kSecAttrAccount asString: Self.account(database), ] }}/// A keeper in memory, for tests.finalclassInMemoryDataKeys: DataKeyKeeping, @unchecked Sendable {privatelet lock = NSLock()privatevar keys: [String: String] = [:]publicinit() {}publicfunc read(database: String) -> String? { lock.withLock { keys[database] } } @discardableResult publicfunc write(_ key: String, database: String) -> Bool { lock.withLock { keys[database] = key }; returntrue }publicfunc forget(database: String) { _ = lock.withLock { keys.removeValue(forKey: database) } }}