import Foundation import CloudKit import CryptoKit import Security /// What the Mac shares with the iPhone: the workspace (accounts, categories, rules, budgets), recent /// transactions with their edits, and a year of balances. Keys and tokens never travel. public struct Snapshot: Codable, Sendable { public var sharedAt: Date public var workspace: Workspace public var transactions: [Transaction] public var edits: [TransactionEdit] public var balances: [BalancePoint] } /// Two-way iCloud sync in the user's private CloudKit database, with no server: /// - the Mac writes one `Snapshot` record (a CKAsset) after each bank sync or edit; /// - both devices write one `Edit` record per edited transaction (reviewed, category, note, …) and /// read the other's through zone changes. The newer edit wins field by field, and an edit always /// wins over bank data because it is stored apart from it; /// - the iPhone writes a `WalletImport` record with its Apple Wallet (FinanceKit) data, which the /// Mac files under an Apple Wallet connection. public actor CloudSync { public static let containerID = "iCloud.com.protomota.bucksley" static let zone = CKRecordZone.ID(zoneName: "Bucksley", ownerName: CKCurrentUserDefaultName) static let snapshotID = CKRecord.ID(recordName: "mac-snapshot", zoneID: zone) static let walletID = CKRecord.ID(recordName: "wallet-import", zoneID: zone) static let subscriptionID = "bucksley-zone-changes" let containerID: String /// Nil without the iCloud entitlement (unsigned dev builds): CloudKit traps instead of throwing /// there, so sync reports itself unavailable and the rest of the app keeps working. let database: CKDatabase? let stateURL: URL public init(store: WorkspaceStore, containerID: String = CloudSync.containerID) { self.containerID = containerID stateURL = store.folder.appendingPathComponent("sync-state.json") database = Self.hasCloudKitEntitlement ? CKContainer(identifier: containerID).privateCloudDatabase : nil } public nonisolated var isAvailable: Bool { database != nil } public func accountReady() async -> Bool { guard isAvailable else { return false } return (try? await CKContainer(identifier: containerID).accountStatus()) == .available } // MARK: Snapshot (Mac → iPhone) public static func snapshot(from store: WorkspaceStore, days: Int = 180) throws -> Snapshot { var ws = try store.load() ws.agentLog = [] let cutoff = DayKey.adding(-days, to: DayKey.today) let txs = try store.transactions().filter { $0.day >= cutoff } let ids = Set(txs.map(\.id)) return Snapshot(sharedAt: .now, workspace: ws, transactions: txs, edits: try store.edits().values.filter { ids.contains($0.transactionID) }, balances: try store.balances().filter { $0.day >= DayKey.adding(-370, to: DayKey.today) }) } public func pushSnapshot(_ snapshot: Snapshot) async throws { let database = try requireDatabase() try await ensureZone() let file = FileManager.default.temporaryDirectory.appendingPathComponent("bucksley-snapshot-\(UUID().uuidString).json") try JSONEncoder.bucksley.encode(snapshot).write(to: file) defer { try? FileManager.default.removeItem(at: file) } let record = (try? await database.record(for: Self.snapshotID)) ?? CKRecord(recordType: "Snapshot", recordID: Self.snapshotID) record["sharedAt"] = snapshot.sharedAt as NSDate record["payload"] = CKAsset(fileURL: file) _ = try await database.modifyRecords(saving: [record], deleting: [], savePolicy: .changedKeys) } public func pullSnapshot() async throws -> Snapshot? { let database = try requireDatabase() do { let record = try await database.record(for: Self.snapshotID) guard let url = (record["payload"] as? CKAsset)?.fileURL else { return nil } return try JSONDecoder.bucksley.decode(Snapshot.self, from: Data(contentsOf: url)) } catch let e as CKError where e.code == .unknownItem || e.code == .zoneNotFound { return nil } } // MARK: Edits (both ways) static func editRecordID(_ transactionID: String) -> CKRecord.ID { let hash = SHA256.hash(data: Data(transactionID.utf8)).map { String(format: "%02x", $0) }.joined() return CKRecord.ID(recordName: "edit-" + hash, zoneID: zone) } /// Sends this device's edits made since the last push. @discardableResult public func pushEdits(from store: WorkspaceStore) async throws -> Int { let database = try requireDatabase() try await ensureZone() var state = loadState() let since = state.lastEditPush ?? .distantPast let pending = try store.edits().values.filter { $0.updatedAt > since } guard !pending.isEmpty else { return 0 } for chunk in stride(from: 0, to: pending.count, by: 300).map({ Array(pending[$0.. CKRecord in let record = CKRecord(recordType: "Edit", recordID: Self.editRecordID(edit.transactionID)) record["transactionID"] = edit.transactionID as NSString record["updatedAt"] = edit.updatedAt as NSDate record["payload"] = String(decoding: try JSONEncoder.bucksley.encode(edit), as: UTF8.self) as NSString return record } _ = try await database.modifyRecords(saving: records, deleting: [], savePolicy: .allKeys, atomically: false) } state.lastEditPush = pending.map(\.updatedAt).max() saveState(state) return pending.count } /// Reads edits (and an Apple Wallet import) that changed since the last pull and merges the edits /// into the store. Returns the number of edits merged and any wallet import found. public func pullChanges(into store: WorkspaceStore) async throws -> (edits: Int, wallet: BankPull?, snapshotChanged: Bool) { let database = try requireDatabase() var state = loadState() var token = state.zoneToken.flatMap { try? NSKeyedUnarchiver.unarchivedObject(ofClass: CKServerChangeToken.self, from: $0) } var edits: [TransactionEdit] = [], wallet: BankPull?, snapshotChanged = false var more = true do { while more { let changes = try await database.recordZoneChanges(inZoneWith: Self.zone, since: token) for (_, result) in changes.modificationResultsByID { guard case .success(let modification) = result else { continue } let record = modification.record switch record.recordType { case "Edit": if let text = record["payload"] as? String, let edit = try? JSONDecoder.bucksley.decode(TransactionEdit.self, from: Data(text.utf8)) { edits.append(edit) } case "WalletImport": if let url = (record["payload"] as? CKAsset)?.fileURL, let data = try? Data(contentsOf: url) { wallet = try? JSONDecoder.bucksley.decode(WalletPayload.self, from: data).pull.pull } case "Snapshot": snapshotChanged = true default: break } } token = changes.changeToken more = changes.moreComing } } catch let e as CKError where e.code == .zoneNotFound { return (0, nil, false) } catch let e as CKError where e.code == .changeTokenExpired { state.zoneToken = nil; saveState(state) return try await pullChanges(into: store) } let merged = try store.mergeEdits(edits) state.zoneToken = token.flatMap { try? NSKeyedArchiver.archivedData(withRootObject: $0, requiringSecureCoding: true) } saveState(state) return (merged, wallet, snapshotChanged) } // MARK: Apple Wallet (iPhone → Mac) struct WalletPayload: Codable { var importedAt: Date; var pull: BankPullCodable } public func pushWallet(_ pull: BankPull) async throws { let database = try requireDatabase() try await ensureZone() let file = FileManager.default.temporaryDirectory.appendingPathComponent("bucksley-wallet-\(UUID().uuidString).json") try JSONEncoder.bucksley.encode(WalletPayload(importedAt: .now, pull: BankPullCodable(pull))).write(to: file) defer { try? FileManager.default.removeItem(at: file) } let record = (try? await database.record(for: Self.walletID)) ?? CKRecord(recordType: "WalletImport", recordID: Self.walletID) record["importedAt"] = Date.now as NSDate record["payload"] = CKAsset(fileURL: file) _ = try await database.modifyRecords(saving: [record], deleting: [], savePolicy: .changedKeys) } // MARK: Push notifications /// Silent push on any change in the zone, so the other device refreshes right away. public func subscribe() async throws { let database = try requireDatabase() try await ensureZone() let sub = CKRecordZoneSubscription(zoneID: Self.zone, subscriptionID: Self.subscriptionID) let info = CKSubscription.NotificationInfo(); info.shouldSendContentAvailable = true sub.notificationInfo = info _ = try await database.modifySubscriptions(saving: [sub], deleting: []) } // MARK: Plumbing struct State: Codable { var zoneToken: Data?; var lastEditPush: Date? } func loadState() -> State { (try? JSONDecoder.bucksley.decode(State.self, from: Data(contentsOf: stateURL))) ?? State() } func saveState(_ state: State) { try? JSONEncoder.bucksley.encode(state).write(to: stateURL, options: .atomic) } private var zoneReady = false private func ensureZone() async throws { guard !zoneReady else { return } _ = try await requireDatabase().modifyRecordZones(saving: [CKRecordZone(zoneID: Self.zone)], deleting: []) zoneReady = true } private func requireDatabase() throws -> CKDatabase { guard let database else { throw BucksleyError.notAllowed("iCloud sync needs a signed build with the iCloud entitlement.") } return database } /// macOS can read its own entitlements. iOS can't, but an iOS app only runs signed with the /// entitlements from project.yml, so it is assumed there (except in the simulator test host). static var hasCloudKitEntitlement: Bool { if ProcessInfo.processInfo.environment["BUCKSLEY_NO_ICLOUD"] != nil { return false } #if os(macOS) guard let task = SecTaskCreateFromSelf(nil), let value = SecTaskCopyValueForEntitlement(task, "com.apple.developer.icloud-services" as CFString, nil) else { return false } return (value as? [String])?.contains("CloudKit") ?? false #else return true #endif } } /// BankPull as Codable for the Apple Wallet hand-off. struct BankPullCodable: Codable { var accounts: [Account] var transactions: [Transaction] init(_ pull: BankPull) { accounts = pull.accounts; transactions = pull.transactions } var pull: BankPull { var p = BankPull(); p.accounts = accounts; p.transactions = transactions; return p } } public extension WorkspaceStore { /// iPhone: replaces its cache with the Mac's snapshot, then lays the Mac's edits under its own. func adopt(_ snapshot: Snapshot) throws { try update { ws in let log = ws.agentLog ws = snapshot.workspace; ws.agentLog = log } try removeTransactions { _ in true } try upsert(snapshot.transactions) try replaceBalances(snapshot.balances) try mergeEdits(snapshot.edits) } }