Account-scoped stores, an explicit device-only library, and local permission boundaries. Source review complete; compilation and runtime gate pending.
Verified account/environment namespaces and a separately selectable device-only library. Existing unscoped stores are retained without guessed ownership or automatic upload.
Store-qualified family grants, duplicate-root guards, serialized final saves, idempotent teardown and fresh asynchronous delivery checks.
Share errors temporarily require verification; permanent denials target exact shares. Reinvitation and overlapping verification preserve unrelated access.
Source reviewed; runtime pending
Four independent source reviewers are clear after corrections. Strict lint and whitespace checks pass. Transit owns the shared build/test slot; new compilation, all 120 declared cases and both Debug builds remain unrun. Last executed passing gate: 79 cases/10 suites and both builds at 3286293. No remote publication or live-account operation.
working-tree Account/access source checkpoint Halo opens the library belonging to the verified account. Device-only memories stay separate and remain selectable after login. An account change locks the current view; existing files are not deliberately deleted.
Sharing changes are checked for each family. A failed share does not permanently revoke every other invitation. Actual account and device behavior remains a release test.
Production coordinates two stores per account/environment namespace. A lock signal spans account lookup and opening, then guards repository fetches and the save boundary. Extension grants include the family UUID and Private/Shared store; duplicate roots within either store fail closed.
Local permission reads use a short state lock. Saves, account invalidation and host permission updates share a serialization gate. Background results check access again before reaching UI/export callers.
The opening observer is armed before asynchronous identity resolution and store attachment. Host factory generations, terminal teardown and per-window load generations prevent stale completion reuse. Separate local library caching avoids retaining a no-account result as the Cloud host.
Share failures install a temporary verification marker and fetch exact CKShare metadata. Persistent denial keys include record and zone identity; verified read-only caps and explicit reinvitation generations retain causal intent. Pinned backup snapshots validate uniqueness once, use permission-only per-row checks, and revalidate delivery on the main actor.
These guards do not prove framework cache preservation, cross-process atomicity or CloudKit transport ordering. Actual lifecycle/offline tests, legacy owner-provenance recovery and production schema promotion remain release gates.
Halo Family/Halo Family/Persistence/PersistenceStack.swift
Why it matters. Keeps device data out of automatic Cloud upload and separates account caches.
What to look at. AccountOpeningGuard, verified factory, deviceLibrary and cached host generations.
Halo Family/Halo Family/Persistence/AccessPermissions.swift
Why it matters. A restored original identity cannot authorize another store or duplicate shared root.
What to look at. FamilyAccessID, scoped SQL, direct-reference duplicate guards and permission manifests.
Halo Family/Halo Family/Persistence/AccountScope.swift
Why it matters. Prevents an in-process invalidation or permission downgrade from racing the final save guard.
What to look at. Save/invalidation/update gate plus short permission read lock and post-await delivery checks.
Halo Family/Halo Family/Persistence/AccessPermissions.swift
Why it matters. Retains unrelated invitations and rejects stale revalidation overwriting explicit acceptance.
What to look at. Temporary shared verification marker, exact record/zone denials, writable caps and coalesced reruns.
Halo Family/Halo Family/ContentView.swift
Why it matters. Every window uses the selected library and its indicator reflects the loaded stack.
What to look at. Preference-change reopening, async load generation and explicit sharing refresh action.
Reversible privacy choice within the approved pack. Legacy recovery remains pending ownership evidence.
The short state lock remains available to readers while SQLite saves use a separate gate. Permission updates and invalidation may wait for an active save; runtime timing has not been measured.
Device-only libraries remain accessible after login. The existing backup/import workflow makes transfer deliberate.
| Severity | Area | Finding | Resolution |
|---|---|---|---|
| major | Opening lifecycle | Account observation started after store loading. | Arm a retained opening observer before account lookup; pass the same signal through loading and always schedule terminal teardown. |
| major | Permission identity | UUID grants could cross stores or duplicate Shared roots. | Qualify by owning store, exclude ambiguous roots before queries and reject direct references. |
| major | Save race | Final save guard raced invalidation and writable downgrades. | Serialize save, invalidation and host permission updates under one gate. |
| major | Extension concurrency | An older manifest read could overwrite a newer permission snapshot. | Read and check the manifest under the short state lock. |
| major | Stale completion | Old teardown or background delivery could affect a reopened/locked session. | Idempotent teardown and fresh post-await checks; clean rejected owned export output. |
| major | Share lifecycle | Broad permanent denials and stale cached metadata could block unrelated or successfully reinvited families. | Temporary verification, exact share denials, explicit acceptance generation and queued verification reruns. |
| major | Multi-window library | Another window could relabel a Cloud repository as device-only. | Observe preference changes in every window and label the actual stack. |
| major | Backup efficiency | Duplicate-root validation caused a root-count query per exported row. | Validate once in the pinned context and use permission-only row checks. |
Source: local run at 2026-10-07T04:05:36.582504+00:00 · snapshot 06b959ce1363b0aa13c73f6c5ce9ccbe94e09712 (dirty working tree)
Baseline: none
Execution: not run · JUnit: none · Coverage: none · Baseline: absent
Coverage scope: every test in the repository
scheduled build/test slot pending
Derived by declaration name, from the diff (no baseline run).
Files that import a changed file on the left, changed files in the centre, files a changed file imports on the right. Snapshot working-tree against base 06b959c.
30 files: 24 code · 6 docs. Click to expand.
diff --git a/Halo Family/Halo Family/ContentView.swift b/Halo Family/Halo Family/ContentView.swiftindex 1326a1b..541035f 100644--- a/Halo Family/Halo Family/ContentView.swift +++ b/Halo Family/Halo Family/ContentView.swift @@ -1,13 +1,25 @@+import CloudKit+import Combine import SwiftUI struct ContentView: View { @State private var repository: FamilyRepository? @State private var failure: String?+ @State private var loadGeneration = UUID()+ @AppStorage("deviceOnlyLibrary") private var deviceOnly = false private let invitations = ShareInvitations.shared var body: some View { Group {- if let repository {+ if let issue = repository?.stack.accessIssue {+ ContentUnavailableView {+ Label("Data session locked", systemImage: "lock.shield")+ } description: {+ Text(issue)+ } actions: {+ Button("Verify and reopen", action: reopen)+ }+ } else if let repository { FamilyWorkspaceView(repository: repository) } else if let failure { ContentUnavailableView {@@ -22,7 +34,22 @@ struct ContentView: View { } } .task { await load() }+ .onChange(of: deviceOnly) { reopen() }+ .onReceive(NotificationCenter.default.publisher(for: .CKAccountChanged).receive(on: DispatchQueue.main)) { _ in+ if !deviceOnly { reopen() }+ } .safeAreaInset(edge: .bottom) {+ Menu {+ Button("Account library") { selectLibrary(deviceOnly: false) }+ Button("On this device") { selectLibrary(deviceOnly: true) }+ if let stack = repository?.stack, stack.accountScope?.mirrorsCloud == true {+ Button("Refresh sharing permissions") { Task { await stack.revalidateSharedAccess() } }+ .disabled(stack.verifyingShares)+ }+ } label: {+ let local = repository.map { $0.stack.accountScope == .local } ?? deviceOnly+ Label(local ? "On this device" : "Account library", systemImage: local ? "internaldrive" : "icloud")+ }.padding(.vertical, 8) if let issue = invitations.issue { VStack { Text(issue)@@ -37,19 +64,42 @@ struct ContentView: View { private func load() async { guard repository == nil else { return }+ let generation = UUID()+ loadGeneration = generation+ let deviceOnly = deviceOnly do {+ let stack: PersistenceStack #if DEBUG if let directory = try SyntheticLaunch.directory() {- repository = FamilyRepository(stack: try PersistenceStack(directory: directory))+ stack = try PersistenceStack(directory: directory) } else {- repository = FamilyRepository(stack: try await .production())+ stack = try await openLibrary(deviceOnly: deviceOnly) } #else- repository = FamilyRepository(stack: try await .production())+ stack = try await openLibrary(deviceOnly: deviceOnly) #endif+ guard loadGeneration == generation else { return }+ repository = FamilyRepository(stack: stack) failure = nil } catch {+ guard loadGeneration == generation else { return } failure = error.localizedDescription } }++ private func reopen() {+ loadGeneration = UUID()+ repository = nil+ failure = nil+ Task { await load() }+ }++ private func selectLibrary(deviceOnly: Bool) {+ if self.deviceOnly == deviceOnly { reopen() } else { self.deviceOnly = deviceOnly }+ }++ private func openLibrary(deviceOnly: Bool) async throws -> PersistenceStack {+ if deviceOnly { return try await .deviceLibrary() }+ return try await .production()+ } }
diff --git a/Halo Family/Halo Family/FamilySharingView.swift b/Halo Family/Halo Family/FamilySharingView.swiftindex e039980..0bd1fc5 100644--- a/Halo Family/Halo Family/FamilySharingView.swift +++ b/Halo Family/Halo Family/FamilySharingView.swift @@ -40,6 +40,7 @@ struct FamilySharingView: UIViewControllerRepresentable { } func cloudSharingControllerDidStopSharing(_ controller: UICloudSharingController) {+ Task { await parent.sharing.stack.revalidateSharedAccess() } parent.onFailure("Sharing has stopped. The family’s access has changed.") } }@@ -95,6 +96,7 @@ struct FamilySharingView: NSViewRepresentable { } func sharingService(_ service: NSSharingService, didStopSharing share: CKShare) {+ Task { await parent.sharing.stack.revalidateSharedAccess() } parent.onFailure("Sharing has stopped. The family’s access has changed.") } }
diff --git a/Halo Family/Halo Family/FamilyWorkspaceView.swift b/Halo Family/Halo Family/FamilyWorkspaceView.swiftindex d174b34..1122fa9 100644--- a/Halo Family/Halo Family/FamilyWorkspaceView.swift +++ b/Halo Family/Halo Family/FamilyWorkspaceView.swift @@ -53,6 +53,7 @@ struct FamilyWorkspaceView: View { } .task { reload() } .safeAreaInset(edge: .bottom) {+ if let notice = repository.stack.storageNotice { Text(notice).padding().background(.regularMaterial) } if let issue = repository.stack.issue { VStack { Text(issue)@@ -61,13 +62,18 @@ struct FamilyWorkspaceView: View { .padding().background(.regularMaterial) } if let issue = repository.stack.syncIssue {- Label(issue, systemImage: "icloud.slash").padding().background(.regularMaterial)+ VStack {+ Label(issue, systemImage: "icloud.slash")+ Button("Verify shared access") { Task { await repository.stack.revalidateSharedAccess() } }+ }.padding().background(.regularMaterial) } } .onReceive(NotificationCenter.default.publisher(for: .haloPersistenceDidRefresh, object: repository.stack.container) .receive(on: DispatchQueue.main)) { _ in reload() } .onChange(of: scenePhase) {- if scenePhase == .active { Task { await repository.stack.refreshHistory(); reload() } }+ if scenePhase == .active {+ Task { await repository.stack.verifyAccount(); await repository.stack.refreshHistory(); reload() }+ } } .sheet(isPresented: $managingFamily, onDismiss: reload) { FamilyManagerView(repository: repository, selectedFamilyID: $selectedFamilyID)
diff --git a/Halo Family/Halo Family/Persistence/AccessPermissions.swift b/Halo Family/Halo Family/Persistence/AccessPermissions.swiftnew file mode 100644index 0000000..de40257--- /dev/null+++ b/Halo Family/Halo Family/Persistence/AccessPermissions.swift @@ -0,0 +1,206 @@+import CloudKit+import CoreData+import Foundation++nonisolated extension StoreAccess {+ static func ambiguousFamilies(in context: NSManagedObjectContext) throws -> Set<FamilyAccessID> {+ var seen = Set<FamilyAccessID>(), repeated = Set<FamilyAccessID>()+ for root in try context.fetch(NSFetchRequest<NSManagedObject>(entityName: "FamilySpace")) {+ guard let id = root.value(forKey: "id") as? UUID,+ let filename = root.objectID.persistentStore?.url?.lastPathComponent else { continue }+ let key = FamilyAccessID(family: id, shared: filename == "Shared.sqlite")+ if !seen.insert(key).inserted { repeated.insert(key) }+ }+ return repeated+ }++ static func identity(_ object: NSManagedObject, checkingDuplicates: Bool = true) throws -> FamilyAccessID {+ let family = object.entity.name == "FamilySpace" ? object : object.value(forKey: "familySpace") as? NSManagedObject+ guard let family, let id = family.value(forKey: "id") as? UUID,+ let filename = family.objectID.persistentStore?.url?.lastPathComponent,+ ["Private.sqlite", "Shared.sqlite"].contains(filename) else { throw GraphError.invalidReference }+ if checkingDuplicates {+ guard let context = family.managedObjectContext else { throw GraphError.invalidReference }+ let request = NSFetchRequest<NSManagedObject>(entityName: "FamilySpace")+ request.predicate = NSPredicate(format: "id == %@", id as NSUUID)+ request.affectedStores = family.objectID.persistentStore.map { [$0] }+ guard try context.count(for: request) == 1 else { throw AccessError.familyUnavailable }+ }+ return FamilyAccessID(family: id, shared: filename == "Shared.sqlite")+ }++ func check(_ object: NSManagedObject, writing: Bool = false) throws {+ try check()+ let id = try Self.identity(object)+ try check(family: id.family, shared: id.shared, writing: writing)+ }+}++/// Records a revoked share separately from Core Data, where a framework import may remove its rows.+/// Only an explicit successful invitation for that share can remove this denial.+nonisolated struct ShareDenials: Codable {+ var shares: Set<String> = []+ var permissions: [String: Bool] = [:]++ static func key(_ id: CKRecord.ID) -> String {+ [id.recordName, id.zoneID.zoneName, id.zoneID.ownerName].joined(separator: "\n")+ }++ static func read(in directory: URL) throws -> ShareDenials {+ let file = directory.appendingPathComponent("ShareDenials.json")+ let handle: FileHandle+ do { handle = try FileHandle(forReadingFrom: file) } catch let error as CocoaError where error.code == .fileReadNoSuchFile {+ return ShareDenials()+ }+ defer { try? handle.close() }+ var data = Data()+ while let chunk = try handle.read(upToCount: 65_536), !chunk.isEmpty {+ data.append(chunk)+ guard data.count <= 1_000_000 else { throw AccessError.familyUnavailable }+ }+ return try JSONDecoder().decode(Self.self, from: data)+ }++ func save(in directory: URL) throws {+ let data = try JSONEncoder().encode(self)+ guard data.count <= 1_000_000 else { throw AccessError.familyUnavailable }+ try data.write(to: directory.appendingPathComponent("ShareDenials.json"), options: .atomic)+ }+}++@MainActor+extension PersistenceStack {+ func fetch(_ request: NSFetchRequest<NSManagedObject>) throws -> [NSManagedObject] {+ guard let permissions = try access.readableFamilies() else { return try container.viewContext.fetch(request) }+ let allowed = try permissions.subtracting(StoreAccess.ambiguousFamilies(in: container.viewContext))+ var rows: [NSManagedObject] = []+ for (store, shared) in [(privateStore, false), (sharedStore, true)] {+ guard request.affectedStores == nil || request.affectedStores?.contains(store) == true else { continue }+ let ids = allowed.filter { $0.shared == shared }.map(\.family)+ guard !ids.isEmpty else { continue }+ guard let scoped = request.copy() as? NSFetchRequest<NSManagedObject> else { throw GraphError.invalidReference }+ let path = request.entityName == "FamilySpace" ? "id" : "familySpace.id"+ let permission = NSPredicate(format: "%K IN %@", path, ids)+ scoped.predicate = request.predicate.map { NSCompoundPredicate(andPredicateWithSubpredicates: [$0, permission]) } ?? permission+ scoped.affectedStores = [store]+ scoped.fetchOffset = 0; scoped.fetchLimit = 0+ rows += try container.viewContext.fetch(scoped)+ }+ rows.sort { left, right in+ for descriptor in request.sortDescriptors ?? [] {+ let order = descriptor.compare(left, to: right)+ if order != .orderedSame { return order == .orderedAscending }+ }+ return false+ }+ let result = Array(rows.dropFirst(request.fetchOffset))+ return request.fetchLimit == 0 ? result : Array(result.prefix(request.fetchLimit))+ }++ func refreshAccess() throws {+ try access.check()+ guard let accountScope, let directory = privateStore.url?.deletingLastPathComponent(), role == .host else { return }+ let request = NSFetchRequest<NSManagedObject>(entityName: "FamilySpace")+ let families = try container.viewContext.fetch(request)+ let ambiguous = try StoreAccess.ambiguousFamilies(in: container.viewContext)+ var readable = Set<FamilyAccessID>()+ var writable = Set<FamilyAccessID>()+ let denials = try ShareDenials.read(in: directory)+ let verificationNeeded = FileManager.default.fileExists(atPath: directory.appendingPathComponent("SharedVerificationRequired").path)+ let cloud = container as? NSPersistentCloudKitContainer+ let sharedIDs = families.filter { $0.objectID.persistentStore == sharedStore }.map(\.objectID)+ let shares = sharedIDs.isEmpty ? [:] : try cloud?.fetchShares(matching: sharedIDs) ?? [:]+ for family in families {+ guard let uuid = family.value(forKey: "id") as? UUID else { continue }+ let key = FamilyAccessID(family: uuid, shared: family.objectID.persistentStore == sharedStore)+ guard !ambiguous.contains(key) else { continue }+ let id = key+ if family.objectID.persistentStore == privateStore {+ readable.insert(id); writable.insert(id)+ } else if !verificationNeeded, let share = shares[family.objectID], let participant = share.currentUserParticipant {+ let key = ShareDenials.key(share.recordID)+ guard participant.acceptanceStatus == .accepted, participant.permission != .none,+ !denials.shares.contains(key) else { continue }+ readable.insert(id)+ if participant.permission == .readWrite, denials.permissions[key] != false,+ cloud?.canUpdateRecord(forManagedObjectWith: family.objectID) == true {+ writable.insert(id)+ }+ }+ }+ let value = ExtensionAccess(version: 1, namespace: accountScope.namespace,+ readable: readable, writable: writable, locked: false)+ try value.save(in: directory)+ access.update(readable: readable, writable: writable)+ }++ func didAcceptInvitation(_ shareID: CKRecord.ID) throws {+ try access.check()+ shareVerificationGeneration = UUID()+ guard let directory = privateStore.url?.deletingLastPathComponent() else { throw PersistenceError.storesUnavailable }+ var denials = try ShareDenials.read(in: directory)+ denials.shares.remove(ShareDenials.key(shareID))+ denials.permissions.removeValue(forKey: ShareDenials.key(shareID))+ try denials.save(in: directory)+ try refreshAccess()+ }++ func revalidateSharedAccess(ifRequired: Bool = false) async {+ guard role == .host, accountScope?.mirrorsCloud == true, let directory = privateStore.url?.deletingLastPathComponent(),+ let cloud = container as? NSPersistentCloudKitContainer else { return }+ let marker = directory.appendingPathComponent("SharedVerificationRequired")+ if ifRequired && !FileManager.default.fileExists(atPath: marker.path) { return }+ do {+ try access.check()+ if !ifRequired {+ shareVerificationGeneration = UUID()+ try Data().write(to: marker, options: .atomic)+ try refreshAccess()+ NotificationCenter.default.post(name: .haloPersistenceDidRefresh, object: container)+ }+ guard !verifyingShares else { verifySharesAgain = true; return }+ verifyingShares = true+ defer {+ verifyingShares = false+ if verifySharesAgain {+ verifySharesAgain = false+ Task { @MainActor [weak self] in await self?.revalidateSharedAccess(ifRequired: true) }+ }+ }+ let generation = shareVerificationGeneration+ let request = NSFetchRequest<NSManagedObject>(entityName: "FamilySpace")+ request.affectedStores = [sharedStore]+ let ids = try container.viewContext.fetch(request).map(\.objectID)+ var denials = try ShareDenials.read(in: directory)+ let cached = ids.isEmpty ? [:] : try cloud.fetchShares(matching: ids)+ let shares = Set(cached.values.map(\.recordID))+ let database = CKContainer(identifier: StoreConfiguration.cloudContainer).sharedCloudDatabase+ for shareID in shares {+ let key = ShareDenials.key(shareID)+ do {+ let record = try await database.record(for: shareID)+ try access.check()+ guard let share = record as? CKShare, let participant = share.currentUserParticipant,+ participant.acceptanceStatus == .accepted, participant.permission != .none else {+ denials.shares.insert(key)+ continue+ }+ denials.permissions[key] = participant.permission == .readWrite+ // A previous confirmed removal stays denied until explicit successful reinvitation.+ } catch {+ try access.check()+ if CloudAccessFailure.removesAccess(error) || (error as? CKError)?.code == .unknownItem {+ denials.shares.insert(key)+ } else { throw error }+ }+ }+ try access.check()+ guard generation == shareVerificationGeneration else { throw AccessError.familyUnavailable }+ try denials.save(in: directory)+ if FileManager.default.fileExists(atPath: marker.path) { try FileManager.default.removeItem(at: marker) }+ try refreshAccess()+ shareVerificationSucceeded()+ NotificationCenter.default.post(name: .haloPersistenceDidRefresh, object: container)+ } catch { shareVerificationFailed(error) }+ }+}
diff --git a/Halo Family/Halo Family/Persistence/AccountScope.swift b/Halo Family/Halo Family/Persistence/AccountScope.swiftnew file mode 100644index 0000000..35ae6fb--- /dev/null+++ b/Halo Family/Halo Family/Persistence/AccountScope.swift @@ -0,0 +1,153 @@+import CloudKit+import CryptoKit+import Foundation++nonisolated enum AccountScope: Equatable, Sendable {+ case local+ case cloud(String)++ var namespace: String {+ switch self {+ case .local: "local"+ case .cloud(let hash): "account-" + hash+ }+ }++ var mirrorsCloud: Bool { if case .cloud = self { return true }; return false }++ static func verifiedCloud(userRecordName: String, environment: String = environment) throws -> AccountScope {+ guard !userRecordName.isEmpty else { throw AccessError.unverifiedAccount }+ let input = [StoreConfiguration.cloudContainer, environment, userRecordName].joined(separator: "\n")+ return .cloud(SHA256.hash(data: Data(input.utf8)).map { String(format: "%02x", $0) }.joined())+ }++ static var environment: String {+ #if DEBUG+ "development"+ #else+ "production"+ #endif+ }++ func directory(in root: URL) -> URL { root.appendingPathComponent("Accounts/" + namespace, isDirectory: true) }++ static func current(container: CKContainer = CKContainer(identifier: StoreConfiguration.cloudContainer)) async throws -> AccountScope {+ switch try await container.accountStatus() {+ case .noAccount: return .local+ case .available:+ let user = try await container.userRecordID()+ return try verifiedCloud(userRecordName: user.recordName)+ case .restricted, .couldNotDetermine, .temporarilyUnavailable: throw AccessError.unverifiedAccount+ @unknown default: throw AccessError.unverifiedAccount+ }+ }+}++nonisolated enum AccessError: LocalizedError {+ case unverifiedAccount+ case accountChanged+ case familyUnavailable+ case readOnlyFamily++ var errorDescription: String? {+ switch self {+ case .unverifiedAccount:+ "Your iCloud account could not be verified. Saved account data stays locked. Try again when verification is available."+ case .accountChanged: "Account access changed. Reopen Halo Family to verify the current account."+ case .familyUnavailable:+ "Access to this family is unavailable. Its saved cache stays locked; ask the owner for a new invitation."+ case .readOnlyFamily: "This family is currently read-only."+ }+ }+}++/// This signal can lock a session directly from an arbitrary account-notification queue.+/// It is checked again by background writers at their save boundary.+nonisolated final class StoreAccess: @unchecked Sendable {+ private let lock = NSLock()+ private let saveLock = NSLock()+ private var locked = false+ private var readable: Set<FamilyAccessID>?+ private var writable: Set<FamilyAccessID>?+ private var extensionSource: (directory: URL, namespace: String)?++ @discardableResult+ func invalidate() -> Bool {+ saveLock.withLock {+ lock.withLock {+ guard !locked else { return false }+ locked = true+ return true+ }+ }+ }+ func update(readable: Set<FamilyAccessID>, writable: Set<FamilyAccessID>) {+ saveLock.withLock {+ lock.withLock { self.readable = readable; self.writable = writable }+ }+ }++ func watchExtensionAccess(directory: URL, namespace: String) {+ lock.withLock { extensionSource = (directory, namespace) }+ }++ /// Called while holding the lock so an older read cannot overwrite a newer permission snapshot.+ private func refreshExtensionAccess() throws {+ guard let source = extensionSource else { return }+ let value = try ExtensionAccess.read(in: source.directory, namespace: source.namespace)+ readable = value.readable+ writable = value.writable+ }++ func check(family: UUID? = nil, shared: Bool = false, writing: Bool = false) throws {+ try lock.withLock {+ try refreshExtensionAccess()+ guard !locked else { throw AccessError.accountChanged }+ guard let family else { return }+ let family = FamilyAccessID(family: family, shared: shared)+ if let readable, !readable.contains(family) { throw AccessError.familyUnavailable }+ if writing, let writable, !writable.contains(family) { throw AccessError.readOnlyFamily }+ }+ }++ func readableFamilies() throws -> Set<FamilyAccessID>? {+ try lock.withLock {+ try refreshExtensionAccess()+ guard !locked else { throw AccessError.accountChanged }+ return readable+ }+ }++ /// Linearizes permission validation and the SQLite save against this process's invalidation signal.+ /// Other processes and framework mirroring still require the account/device release gate.+ func save(families: Set<FamilyAccessID>, _ operation: () throws -> Void) throws {+ try saveLock.withLock {+ try lock.withLock {+ try refreshExtensionAccess()+ guard !locked else { throw AccessError.accountChanged }+ for family in families {+ if let readable, !readable.contains(family) { throw AccessError.familyUnavailable }+ if let writable, !writable.contains(family) { throw AccessError.readOnlyFamily }+ }+ }+ try operation()+ }+ }+}++/// Arm the signal before the first asynchronous identity lookup or store attachment.+nonisolated final class AccountOpeningGuard: @unchecked Sendable {+ let container = CKContainer(identifier: StoreConfiguration.cloudContainer)+ let access: StoreAccess+ private let token: NSObjectProtocol++ init() {+ let access = StoreAccess()+ self.access = access+ token = NotificationCenter.default.addObserver(forName: .CKAccountChanged, object: nil, queue: nil) { _ in+ access.invalidate()+ }+ }++ deinit { NotificationCenter.default.removeObserver(token) }+}
diff --git a/Halo Family/Halo Family/Persistence/AssetRepository.swift b/Halo Family/Halo Family/Persistence/AssetRepository.swiftindex c45c162..cabe427 100644--- a/Halo Family/Halo Family/Persistence/AssetRepository.swift +++ b/Halo Family/Halo Family/Persistence/AssetRepository.swift @@ -10,6 +10,8 @@ final class AssetRepository { init(stack: PersistenceStack) { self.stack = stack } func save(data: Data, familyID: NSManagedObjectID, replacing assetID: NSManagedObjectID? = nil) async throws -> NSManagedObjectID {+ try stack.access.check()+ let access = stack.access guard stack.role != .widget else { throw GraphError.readOnly } let cloud = stack.container as? NSPersistentCloudKitContainer let context = stack.container.newBackgroundContext()@@ -17,6 +19,7 @@ final class AssetRepository { let result = try await context.perform { guard familyID.entity.name == "FamilySpace", !familyID.isTemporaryID else { throw GraphError.invalidReference } let family = try context.existingObject(with: familyID)+ try access.check(family, writing: true) guard let store = family.objectID.persistentStore else { throw GraphError.invalidReference } try Self.requireEditable(family, cloud: cloud) let asset: NSManagedObject@@ -38,10 +41,11 @@ final class AssetRepository { if asset.entity.attributesByName["contentRevision"] != nil { asset.setValue(UUID(), forKey: "contentRevision") } let inserted = Array(context.insertedObjects) let updated = Array(context.updatedObjects)- try context.save()+ let identity = try StoreAccess.identity(family)+ try access.save(families: [identity]) { try context.save() } return (asset.objectID, inserted.map(\.objectID), updated.map(\.objectID)) }- publish(inserted: result.1, updated: result.2)+ try publish(inserted: result.1, updated: result.2) return result.0 } @@ -62,6 +66,8 @@ final class AssetRepository { } private func importAsset(_ prepared: PreparedAsset, ownerID: NSManagedObjectID, photo: Bool) async throws -> NSManagedObjectID {+ try stack.access.check()+ let access = stack.access guard stack.role != .widget else { throw GraphError.readOnly } try Task.checkCancellation() let cloud = stack.container as? NSPersistentCloudKitContainer@@ -70,6 +76,7 @@ final class AssetRepository { let result = try await context.perform { guard ownerID.entity.name == (photo ? "Person" : "Event"), !ownerID.isTemporaryID else { throw GraphError.invalidReference } let owner = try context.existingObject(with: ownerID)+ try access.check(owner, writing: true) try Self.requireEditable(owner, cloud: cloud) if photo, owner.value(forKey: "mergedInto") != nil { throw MergeError.changed } guard let family = owner.value(forKey: "familySpace") as? NSManagedObject,@@ -106,14 +113,16 @@ final class AssetRepository { let inserted = Array(context.insertedObjects) let updated = Array(context.updatedObjects) try Task.checkCancellation()- try context.save()+ let identity = try StoreAccess.identity(family)+ try access.save(families: [identity]) { try context.save() } return (asset.objectID, inserted.map(\.objectID), updated.map(\.objectID)) }- publish(inserted: result.1, updated: result.2)+ try publish(inserted: result.1, updated: result.2) return result.0 } - private func publish(inserted: [NSManagedObjectID], updated: [NSManagedObjectID]) {+ private func publish(inserted: [NSManagedObjectID], updated: [NSManagedObjectID]) throws {+ try stack.access.check() NSManagedObjectContext.mergeChanges(fromRemoteContextSave: [NSInsertedObjectsKey: inserted, NSUpdatedObjectsKey: updated], into: [stack.container.viewContext]) NotificationCenter.default.post(name: .haloPersistenceDidRefresh, object: stack.container)@@ -121,9 +130,12 @@ final class AssetRepository { /// Fetch metadata alone so a cached thumbnail does not first materialize the full binary payload. func revision(for assetID: NSManagedObjectID) async throws -> String {+ try stack.access.check()+ let access = stack.access let context = stack.container.newBackgroundContext()- return try await context.perform {+ let value = try await context.perform { guard assetID.entity.name == "Asset", !assetID.isTemporaryID else { throw GraphError.invalidReference }+ try access.check(context.existingObject(with: assetID)) let request = NSFetchRequest<NSDictionary>(entityName: "Asset") request.resultType = .dictionaryResultType request.predicate = NSPredicate(format: "SELF == %@", assetID)@@ -132,6 +144,8 @@ final class AssetRepository { guard let metadata = try context.fetch(request).first else { throw GraphError.invalidReference } return "\(assetID.uriRepresentation().absoluteString)|\(metadata["contentRevision"] ?? "legacy")|\(metadata["modifiedAt"] ?? "")" }+ _ = try FamilyRepository(stack: stack).readable(assetID, entity: "Asset")+ return value } nonisolated private static func requireEditable(_ object: NSManagedObject, cloud: NSPersistentCloudKitContainer?) throws {@@ -142,12 +156,17 @@ final class AssetRepository { } func data(for assetID: NSManagedObjectID) async throws -> Data {+ try stack.access.check()+ let access = stack.access let context = stack.container.newBackgroundContext()- return try await context.perform {+ let value = try await context.perform { guard assetID.entity.name == "Asset", !assetID.isTemporaryID else { throw GraphError.invalidReference } let asset = try context.existingObject(with: assetID)+ try access.check(asset) guard let data = asset.value(forKey: "data") as? Data else { throw GraphError.invalidReference } return data }+ _ = try FamilyRepository(stack: stack).readable(assetID, entity: "Asset")+ return value } }
diff --git a/Halo Family/Halo Family/Persistence/BackupRepository.swift b/Halo Family/Halo Family/Persistence/BackupRepository.swiftindex a4dfb1f..3b1e1bf 100644--- a/Halo Family/Halo Family/Persistence/BackupRepository.swift +++ b/Halo Family/Halo Family/Persistence/BackupRepository.swift @@ -24,15 +24,19 @@ final class BackupRepository { init(stack: PersistenceStack) { self.stack = stack } func export(familyID: NSManagedObjectID, readable: Bool = true) async throws -> URL {+ try stack.access.check()+ let access = stack.access guard stack.role == .host else { throw GraphError.readOnly } let context = stack.container.newBackgroundContext() let model = stack.container.managedObjectModel let cancellation = BackupCancellation()- return try await withTaskCancellationHandler { try await context.perform {+ let archive = try await withTaskCancellationHandler { try await context.perform { try cancellation.check() try context.setQueryGenerationFrom(.current) guard familyID.entity.name == "FamilySpace", !familyID.isTemporaryID else { throw GraphError.invalidReference } let family = try context.existingObject(with: familyID)+ let identity = try StoreAccess.identity(family)+ try access.check(family: identity.family, shared: identity.shared) guard let uuid = family.value(forKey: "id") as? UUID else { throw BackupError.missingIdentity } let folder = FileManager.default.temporaryDirectory.appendingPathComponent(UUID().uuidString, isDirectory: true) try FileManager.default.createDirectory(at: folder, withIntermediateDirectories: true)@@ -48,6 +52,7 @@ final class BackupRepository { request.predicate = NSPredicate(format: "familySpace == %@", familyID) } else { continue } for object in try context.fetch(request) {+ try access.check(family: identity.family, shared: identity.shared) try cancellation.check() guard let id = object.value(forKey: "id") as? UUID else { throw BackupError.missingIdentity } let record = try PortableGraph.record(object) { key, data in@@ -78,12 +83,21 @@ final class BackupRepository { let archive = folder.appendingPathComponent("Halo Family Backup.zip") try cancellation.check() try BackupArchive.write(files, to: archive, check: cancellation.check)+ try access.check(family) try cancellation.check() for file in files { try? FileManager.default.removeItem(at: file.url) } delivered = true return archive } } onCancel: { cancellation.cancel() }+ do {+ try Task.checkCancellation()+ _ = try FamilyRepository(stack: stack).readable(familyID, entity: "FamilySpace")+ return archive+ } catch {+ try? FileManager.default.removeItem(at: archive.deletingLastPathComponent())+ throw error+ } } func preview(_ archive: URL) async throws -> BackupPreview {@@ -114,6 +128,8 @@ final class BackupRepository { } func restore(_ preview: BackupPreview, asNewCopy: Bool) async throws -> NSManagedObjectID {+ try stack.access.check()+ let access = stack.access guard stack.role == .host else { throw GraphError.readOnly } guard !stack.importingBackup else { throw BackupError.importing } // A single atomic context save avoids exposing a partially imported family. Bound its payload memory.@@ -165,11 +181,13 @@ final class BackupRepository { throw BackupError.changed } try cancellation.check()- try context.save()+ try access.save(families: []) { try context.save() } return (root.objectID, inserted.map(\.objectID)) } } onCancel: { cancellation.cancel() }+ try access.check() NSManagedObjectContext.mergeChanges(fromRemoteContextSave: [NSInsertedObjectsKey: result.1], into: [container.viewContext])+ do { try stack.refreshAccess() } catch { stack.lockSession() } NotificationCenter.default.post(name: .haloPersistenceDidRefresh, object: container) return result.0 }
diff --git a/Halo Family/Halo Family/Persistence/CloudAccessFailure.swift b/Halo Family/Halo Family/Persistence/CloudAccessFailure.swiftnew file mode 100644index 0000000..af96689--- /dev/null+++ b/Halo Family/Halo Family/Persistence/CloudAccessFailure.swift @@ -0,0 +1,16 @@+import CloudKit+import Foundation++nonisolated enum CloudAccessFailure {+ static func removesAccess(_ error: Error?, depth: Int = 0) -> Bool {+ guard let error, depth < 8 else { return false }+ let value = error as NSError+ if value.domain == CKErrorDomain,+ [CKError.permissionFailure.rawValue, CKError.zoneNotFound.rawValue, CKError.userDeletedZone.rawValue].contains(value.code) {+ return true+ }+ if removesAccess(value.userInfo[NSUnderlyingErrorKey] as? Error, depth: depth + 1) { return true }+ let partial = value.userInfo[CKPartialErrorsByItemIDKey] as? [AnyHashable: Error] ?? [:]+ return partial.values.contains { removesAccess($0, depth: depth + 1) }+ }+}
diff --git a/Halo Family/Halo Family/Persistence/ContextCategoryRepository.swift b/Halo Family/Halo Family/Persistence/ContextCategoryRepository.swiftindex 0c0e425..3e538c1 100644--- a/Halo Family/Halo Family/Persistence/ContextCategoryRepository.swift +++ b/Halo Family/Halo Family/Persistence/ContextCategoryRepository.swift @@ -36,7 +36,7 @@ extension FamilyRepository { let request = NSFetchRequest<NSManagedObject>(entityName: "ContextCategory") request.predicate = NSPredicate(format: "familySpace == %@", familyID) request.sortDescriptors = [NSSortDescriptor(key: "name", ascending: true)]- return try stack.container.viewContext.fetch(request).map(categoryRow)+ return try stack.fetch(request).map(categoryRow) } func createCategory(name: String, familyID: NSManagedObjectID) throws -> NSManagedObjectID {
diff --git a/Halo Family/Halo Family/Persistence/EventMemoryRepository.swift b/Halo Family/Halo Family/Persistence/EventMemoryRepository.swiftindex 74a5e93..bcc3885 100644--- a/Halo Family/Halo Family/Persistence/EventMemoryRepository.swift +++ b/Halo Family/Halo Family/Persistence/EventMemoryRepository.swift @@ -144,7 +144,7 @@ extension FamilyRepository { let request = NSFetchRequest<NSManagedObject>(entityName: "EventPerson") request.predicate = NSPredicate(format: "event == %@", eventID) request.sortDescriptors = [NSSortDescriptor(key: "person.displayName", ascending: true)]- return try stack.container.viewContext.fetch(request).compactMap(participantRow)+ return try stack.fetch(request).compactMap(participantRow) } private func participantRow(_ object: NSManagedObject) -> ParticipantRow? {@@ -211,7 +211,7 @@ extension FamilyRepository { func gifts(_ eventID: NSManagedObjectID) throws -> [GiftRow] { let request = NSFetchRequest<NSManagedObject>(entityName: "GiftRecord") request.predicate = NSPredicate(format: "event == %@", eventID)- return try stack.container.viewContext.fetch(request).map(giftRow)+ return try stack.fetch(request).map(giftRow) } private func giftRow(_ gift: NSManagedObject) -> GiftRow {@@ -227,7 +227,7 @@ extension FamilyRepository { func attachments(_ eventID: NSManagedObjectID) throws -> [AttachmentRow] { let request = NSFetchRequest<NSManagedObject>(entityName: "EventAttachment") request.predicate = NSPredicate(format: "event == %@", eventID)- return try stack.container.viewContext.fetch(request).compactMap {+ return try stack.fetch(request).compactMap { guard let asset = $0.value(forKey: "asset") as? NSManagedObject else { return nil } return AttachmentRow(id: $0.objectID, assetID: asset.objectID, title: $0.value(forKey: "title") as? String ?? "Attachment",@@ -242,7 +242,7 @@ extension FamilyRepository { participation.predicate = NSPredicate(format: "person == %@", personID) let gifts = NSFetchRequest<NSManagedObject>(entityName: "GiftRecord") gifts.predicate = NSPredicate(format: "ANY givers == %@ OR ANY recipients == %@", personID, personID)- let related = try stack.container.viewContext.fetch(participation) + stack.container.viewContext.fetch(gifts)+ let related = try stack.fetch(participation) + stack.fetch(gifts) let eventIDs = Set(related.compactMap { ($0.value(forKey: "event") as? NSManagedObject)?.objectID }) return try events(in: family.objectID).filter { $0.subjectID == personID || eventIDs.contains($0.id) } }
diff --git a/Halo Family/Halo Family/Persistence/ExtensionAccess.swift b/Halo Family/Halo Family/Persistence/ExtensionAccess.swiftnew file mode 100644index 0000000..298d8ee--- /dev/null+++ b/Halo Family/Halo Family/Persistence/ExtensionAccess.swift @@ -0,0 +1,38 @@+import Foundation++nonisolated struct FamilyAccessID: Codable, Hashable, Sendable {+ let family: UUID+ let shared: Bool+}++nonisolated struct ExtensionAccess: Codable, Equatable, Sendable {+ let version: Int+ let namespace: String+ let readable: Set<FamilyAccessID>+ let writable: Set<FamilyAccessID>+ let locked: Bool++ static func read(in directory: URL, namespace: String) throws -> ExtensionAccess {+ guard !FileManager.default.fileExists(atPath: directory.appendingPathComponent("AccessLocked").path) else {+ throw AccessError.accountChanged+ }+ let file = directory.appendingPathComponent("ExtensionAccess.json")+ let handle = try FileHandle(forReadingFrom: file)+ defer { try? handle.close() }+ var data = Data()+ while let chunk = try handle.read(upToCount: 65_536), !chunk.isEmpty {+ data.append(chunk)+ guard data.count <= 1_000_000 else { throw AccessError.accountChanged }+ }+ guard let value = try? JSONDecoder().decode(Self.self, from: data), value.version == 1,+ value.namespace == namespace, !value.locked,+ value.writable.isSubset(of: value.readable) else { throw AccessError.accountChanged }+ return value+ }++ func save(in directory: URL) throws {+ let data = try JSONEncoder().encode(self)+ guard data.count <= 1_000_000 else { throw BackupError.tooLarge }+ try data.write(to: directory.appendingPathComponent("ExtensionAccess.json"), options: .atomic)+ }+}
diff --git a/Halo Family/Halo Family/Persistence/FamilyMemoryRepository.swift b/Halo Family/Halo Family/Persistence/FamilyMemoryRepository.swiftindex 4f5d1fe..5c6f701 100644--- a/Halo Family/Halo Family/Persistence/FamilyMemoryRepository.swift +++ b/Halo Family/Halo Family/Persistence/FamilyMemoryRepository.swift @@ -154,7 +154,7 @@ extension FamilyRepository { let pair = NSPredicate(format: "source == %@ OR target == %@", personID, personID) request.predicate = modern && !includeArchived ? NSCompoundPredicate(andPredicateWithSubpredicates: [pair, NSPredicate(format: "archivedAt == nil")]) : pair- return try stack.container.viewContext.fetch(request).compactMap { fact -> FamilyFactRow? in+ return try stack.fetch(request).compactMap { fact -> FamilyFactRow? in guard let source = fact.value(forKey: "source") as? NSManagedObject, let target = fact.value(forKey: "target") as? NSManagedObject else { return nil } let asserted = entity == "RelationshipAssertion"@@ -224,7 +224,7 @@ extension FamilyRepository { func groupMembers(_ groupID: NSManagedObjectID) throws -> [GroupMemberRow] { let request = NSFetchRequest<NSManagedObject>(entityName: "GroupMembership") request.predicate = NSPredicate(format: "group == %@", groupID)- return try stack.container.viewContext.fetch(request).compactMap { link in+ return try stack.fetch(request).compactMap { link in guard let person = link.value(forKey: "person") as? NSManagedObject else { return nil } return GroupMemberRow(id: link.objectID, personID: person.objectID, name: person.value(forKey: "displayName") as? String ?? "Unnamed",@@ -268,7 +268,7 @@ extension FamilyRepository { func addressLabels(for personID: NSManagedObjectID) throws -> [AddressLabelRow] { let request = NSFetchRequest<NSManagedObject>(entityName: "AddressLabel") request.predicate = NSPredicate(format: "target == %@", personID)- return try stack.container.viewContext.fetch(request).map(addressLabelRow)+ return try stack.fetch(request).map(addressLabelRow) } private func addressLabelRow(_ object: NSManagedObject) -> AddressLabelRow {
diff --git a/Halo Family/Halo Family/Persistence/FamilyRepository.swift b/Halo Family/Halo Family/Persistence/FamilyRepository.swiftindex 92d75b1..5b04488 100644--- a/Halo Family/Halo Family/Persistence/FamilyRepository.swift +++ b/Halo Family/Halo Family/Persistence/FamilyRepository.swift @@ -85,6 +85,7 @@ final class FamilyRepository { } func createFamily(name: String) throws -> NSManagedObjectID {+ guard stack.role == .host else { throw GraphError.readOnly } let name = try validated(name) return try write { context in let family = insert("FamilySpace", in: context, store: stack.privateStore)@@ -137,6 +138,7 @@ final class FamilyRepository { } func write(_ operation: (NSManagedObjectContext) throws -> NSManagedObject) throws -> NSManagedObjectID {+ try stack.access.check() guard stack.role != .widget else { throw GraphError.readOnly } let context = NSManagedObjectContext(concurrencyType: .mainQueueConcurrencyType) context.persistentStoreCoordinator = stack.container.persistentStoreCoordinator@@ -145,12 +147,24 @@ final class FamilyRepository { let inserted = Array(context.insertedObjects) let updated = Array(context.updatedObjects) let deleted = Array(context.deletedObjects)- try context.save()+ let newFamilies = Set(inserted.filter { $0.entity.name == "FamilySpace" }.map(\.objectID))+ var permittedFamilies = Set<FamilyAccessID>()+ let ambiguous = try StoreAccess.ambiguousFamilies(in: context)+ for object in inserted + updated + deleted {+ let family = object.entity.name == "FamilySpace" ? object : object.value(forKey: "familySpace") as? NSManagedObject+ if let family, newFamilies.contains(family.objectID), stack.role == .host,+ family.objectID.persistentStore == stack.privateStore { continue }+ let identity = try StoreAccess.identity(object, checkingDuplicates: false)+ guard !ambiguous.contains(identity) else { throw AccessError.familyUnavailable }+ permittedFamilies.insert(identity)+ }+ try stack.access.save(families: permittedFamilies) { try context.save() } // Repository callers can immediately refetch already registered objects after a local save. NSManagedObjectContext.mergeChanges(fromRemoteContextSave: [ NSInsertedObjectsKey: inserted.map(\.objectID), NSUpdatedObjectsKey: updated.map(\.objectID), NSDeletedObjectsKey: deleted.map(\.objectID), ], into: [stack.container.viewContext])+ do { try stack.refreshAccess() } catch { stack.lockSession() } NotificationCenter.default.post(name: .haloPersistenceDidRefresh, object: stack.container) return result.objectID }@@ -159,17 +173,19 @@ final class FamilyRepository { let request = NSFetchRequest<NSManagedObject>(entityName: entity) request.predicate = predicate request.sortDescriptors = [NSSortDescriptor(key: nameKey, ascending: true)]- return try stack.container.viewContext.fetch(request).map {+ return try stack.fetch(request).map { GraphRow(id: $0.objectID, name: $0.value(forKeyPath: nameKey) as? String ?? "Unnamed") } } func record(_ id: NSManagedObjectID, entity: String, in context: NSManagedObjectContext) throws -> NSManagedObject {+ try stack.access.check() guard !id.isTemporaryID, id.entity.name == entity, let store = id.persistentStore, stack.container.persistentStoreCoordinator.persistentStores.contains(store) else { throw GraphError.invalidReference } let object = try context.existingObject(with: id) guard !object.isDeleted else { throw GraphError.invalidReference }+ try stack.access.check(object, writing: true) if ["Person", "Connection", "ChildProfile"].contains(entity), object.entity.relationshipsByName["mergedInto"] != nil, object.value(forKey: "mergedInto") != nil { throw MergeError.changed }
diff --git a/Halo Family/Halo Family/Persistence/FamilySharing.swift b/Halo Family/Halo Family/Persistence/FamilySharing.swiftindex 5d0199b..2d3896c 100644--- a/Halo Family/Halo Family/Persistence/FamilySharing.swift +++ b/Halo Family/Halo Family/Persistence/FamilySharing.swift @@ -75,6 +75,8 @@ final class FamilySharing { if let error { continuation.resume(throwing: error) } else { continuation.resume() } } }+ try stack.access.check()+ try stack.refreshAccess() } func accept(_ metadata: CKShare.Metadata) async throws {@@ -88,11 +90,13 @@ final class FamilySharing { } } // Acceptance finishes before the graph necessarily downloads. Remote history handles later imports.+ try stack.didAcceptInvitation(metadata.share.recordID) await stack.refreshHistory() NotificationCenter.default.post(name: .haloPersistenceDidRefresh, object: stack.container) } private func cloudContainer() throws -> NSPersistentCloudKitContainer {+ try stack.access.check() guard stack.role == .host, let cloud = stack.container as? NSPersistentCloudKitContainer else { throw SharingError.hostRequired }
diff --git a/Halo Family/Halo Family/Persistence/HistoryProcessor.swift b/Halo Family/Halo Family/Persistence/HistoryProcessor.swiftindex 55dc025..ead1a10 100644--- a/Halo Family/Halo Family/Persistence/HistoryProcessor.swift +++ b/Halo Family/Halo Family/Persistence/HistoryProcessor.swift @@ -17,18 +17,21 @@ final class HistoryProcessor { private let container: NSPersistentContainer private let directory: URL private let consumer: String+ private let access: StoreAccess private var processing = false private var needsAnotherPass = false - init(container: NSPersistentContainer, directory: URL, consumer: String) {+ init(container: NSPersistentContainer, directory: URL, consumer: String, access: StoreAccess = StoreAccess()) { self.container = container self.directory = directory self.consumer = consumer+ self.access = access } /// Overlapping notifications coalesce, while writes arriving during a pass request another pass. @discardableResult func process() async throws -> Int {+ try access.check() if processing { needsAnotherPass = true return 0@@ -67,6 +70,7 @@ final class HistoryProcessor { } } let batch = try await fetch(store: store, token: token)+ try access.check() if reset || batch.recovered { container.viewContext.refreshAllObjects() }
diff --git a/Halo Family/Halo Family/Persistence/KinshipQueries.swift b/Halo Family/Halo Family/Persistence/KinshipQueries.swiftindex ebe396e..d9e6e28 100644--- a/Halo Family/Halo Family/Persistence/KinshipQueries.swift +++ b/Halo Family/Halo Family/Persistence/KinshipQueries.swift @@ -20,7 +20,7 @@ extension FamilyRepository { family, date as NSDate, date as NSDate) request.predicate = modern ? NSCompoundPredicate(andPredicateWithSubpredicates: [active, NSPredicate(format: "archivedAt == nil")]) : active- let facts = try stack.container.viewContext.fetch(request)+ let facts = try stack.fetch(request) var parents: [NSManagedObjectID: Set<NSManagedObjectID>] = [:] var siblings: [NSManagedObjectID: Set<NSManagedObjectID>] = [:] for fact in facts {
diff --git a/Halo Family/Halo Family/Persistence/OriginRepository.swift b/Halo Family/Halo Family/Persistence/OriginRepository.swiftindex 8a63319..9eefe8d 100644--- a/Halo Family/Halo Family/Persistence/OriginRepository.swift +++ b/Halo Family/Halo Family/Persistence/OriginRepository.swift @@ -37,7 +37,7 @@ extension FamilyRepository { let request = NSFetchRequest<NSManagedObject>(entityName: "OriginProposal") request.predicate = NSPredicate(format: "connection == %@", connectionID) request.sortDescriptors = [NSSortDescriptor(key: "createdAt", ascending: false)]- return try stack.container.viewContext.fetch(request).map { try proposalRow($0) }+ return try stack.fetch(request).map { try proposalRow($0) } } func conflictingOriginConnections(in familyID: NSManagedObjectID) throws -> Set<NSManagedObjectID> {@@ -45,7 +45,7 @@ extension FamilyRepository { let request = NSFetchRequest<NSManagedObject>(entityName: "OriginProposal") request.predicate = NSPredicate(format: "familySpace == %@", familyID) request.relationshipKeyPathsForPrefetching = ["connection", "predecessors", "familySpace"]- let proposals = try stack.container.viewContext.fetch(request)+ let proposals = try stack.fetch(request) let grouped = Dictionary(grouping: proposals) { ($0.value(forKey: "connection") as? NSManagedObject)?.objectID ?? $0.objectID }
diff --git a/Halo Family/Halo Family/Persistence/PeopleSearch.swift b/Halo Family/Halo Family/Persistence/PeopleSearch.swiftindex e0c9706..2a578b3 100644--- a/Halo Family/Halo Family/Persistence/PeopleSearch.swift +++ b/Halo Family/Halo Family/Persistence/PeopleSearch.swift @@ -45,14 +45,14 @@ extension FamilyRepository { let request = NSFetchRequest<NSManagedObject>(entityName: "ConnectionContext") request.predicate = NSPredicate(format: "familySpace == %@ AND context IN %@", familyID, contexts.map(\.id)) request.relationshipKeyPathsForPrefetching = ["connection.person"]- let ids = Set(try stack.container.viewContext.fetch(request).compactMap {+ let ids = Set(try stack.fetch(request).compactMap { ($0.value(forKeyPath: "connection.person") as? NSManagedObject)?.objectID }) predicates.append(NSPredicate(format: "SELF IN %@", Array(ids))) let roles = NSFetchRequest<NSManagedObject>(entityName: "ContextPerson") roles.predicate = NSPredicate(format: "familySpace == %@ AND context IN %@", familyID, contexts.map(\.id)) roles.relationshipKeyPathsForPrefetching = ["person"]- let people = Set(try stack.container.viewContext.fetch(roles).compactMap {+ let people = Set(try stack.fetch(roles).compactMap { ($0.value(forKey: "person") as? NSManagedObject)?.objectID }) predicates.append(NSPredicate(format: "SELF IN %@", Array(people)))@@ -66,7 +66,7 @@ extension FamilyRepository { let request = NSFetchRequest<NSManagedObject>(entityName: "ContextPerson") request.predicate = NSPredicate(format: "person == %@", personID) request.relationshipKeyPathsForPrefetching = ["context", "person"]- return try stack.container.viewContext.fetch(request).compactMap { row in+ return try stack.fetch(request).compactMap { row in guard let context = row.value(forKey: "context") as? NSManagedObject else { return nil } let association = ContextPersonRow(id: row.objectID, contextID: context.objectID, personID: personID, name: row.value(forKeyPath: "person.displayName") as? String ?? "Unnamed", role: row.value(forKey: "role") as? String ?? "",
diff --git a/Halo Family/Halo Family/Persistence/PersistenceStack.swift b/Halo Family/Halo Family/Persistence/PersistenceStack.swiftindex f96d5fa..521a27e 100644--- a/Halo Family/Halo Family/Persistence/PersistenceStack.swift +++ b/Halo Family/Halo Family/Persistence/PersistenceStack.swift @@ -1,3 +1,4 @@+import CloudKit import CoreData import Foundation import Observation@@ -7,23 +8,39 @@ import OSLog @Observable final class PersistenceStack { private static var hostTask: Task<PersistenceStack, Error>?+ private static var hostGeneration: UUID?+ private static weak var hostStack: PersistenceStack?+ private static var deviceTask: Task<PersistenceStack, Error>?+ private static weak var deviceStack: PersistenceStack? let container: NSPersistentContainer let privateStore: NSPersistentStore let sharedStore: NSPersistentStore let role: PersistenceRole let nativeContactsEnabled: Bool+ let accountScope: AccountScope?+ @ObservationIgnored let access: StoreAccess+ @ObservationIgnored private let accountContainer: CKContainer?+ private(set) var accessIssue: String?+ private(set) var storageNotice: String? @ObservationIgnored var importingBackup = false+ @ObservationIgnored var verifyingShares = false+ @ObservationIgnored var verifySharesAgain = false+ @ObservationIgnored var shareVerificationGeneration = UUID() private(set) var issue: String? private(set) var syncIssue: String? @ObservationIgnored private var history: HistoryProcessor? @ObservationIgnored private var observation: PersistenceObservation? @ObservationIgnored private var contactLinks: LocalContactLinks?+ @ObservationIgnored private var accountObservation: PersistenceObservation? @ObservationIgnored private let logger = Logger(subsystem: "me.nore.ig.halo-family", category: "Persistence") /// Test/local coordinators never mirror CloudKit. Production uses the async factory below. init(directory: URL, model: NSManagedObjectModel? = nil, role: PersistenceRole = .host) throws { try FileManager.default.createDirectory(at: directory, withIntermediateDirectories: true) self.role = role+ accountScope = nil+ access = StoreAccess()+ accountContainer = nil nativeContactsEnabled = false container = NSPersistentContainer(name: "HaloModel", managedObjectModel: try model ?? Self.loadModel()) let coordinator = container.persistentStoreCoordinator@@ -42,35 +59,121 @@ final class PersistenceStack { configureViewContext() } - private init(container: NSPersistentContainer, configuration: StoreConfiguration) throws {+ private init(container: NSPersistentContainer, configuration: StoreConfiguration, access: StoreAccess) throws { let coordinator = container.persistentStoreCoordinator guard let owned = coordinator.persistentStore(for: configuration.directory.appendingPathComponent("Private.sqlite")), let shared = coordinator.persistentStore(for: configuration.directory.appendingPathComponent("Shared.sqlite")) else { throw PersistenceError.storesUnavailable } self.container = container+ self.access = access privateStore = owned sharedStore = shared role = configuration.role+ accountScope = configuration.accountScope+ accountContainer = configuration.accountScope == nil ? nil : CKContainer(identifier: StoreConfiguration.cloudContainer) nativeContactsEnabled = configuration.role == .host configureViewContext() } static func production(role: PersistenceRole = .host) async throws -> PersistenceStack {- guard role == .host else { return try await open(configuration: .production(role: role)) }+ guard role == .host else { return try await openProduction(role: role) } // Multiple windows share one host coordinator and one mirroring owner.- if let hostTask { return try await hostTask.value }- let task = Task { @MainActor in try await open(configuration: .production(role: .host)) }+ if let hostTask {+ let stack = try await hostTask.value+ try stack.access.check()+ return stack+ }+ let generation = UUID()+ let task = Task { @MainActor in+ let stack = try await openProduction(role: .host)+ if stack.accountScope?.mirrorsCloud == true { hostStack = stack }+ return stack+ }+ hostGeneration = generation hostTask = task do {- return try await task.value+ let stack = try await task.value+ if stack.accountScope == .local, hostGeneration == generation { hostTask = nil; hostGeneration = nil }+ return stack+ } catch {+ if hostGeneration == generation { hostTask = nil; hostGeneration = nil }+ throw error+ }+ }++ private static func openProduction(role: PersistenceRole) async throws -> PersistenceStack {+ let opening = AccountOpeningGuard()+ let scope = try await AccountScope.current(container: opening.container)+ try opening.access.check()+ if scope == .local { return try await deviceLibrary(role: role) }+ let configuration = try StoreConfiguration.production(role: role, scope: scope)+ if role != .host { _ = try ExtensionAccess.read(in: configuration.directory, namespace: scope.namespace) }+ let stack = try await open(configuration: configuration, access: opening.access)+ stack.observeAccount(directory: configuration.directory)+ do {+ guard try await AccountScope.current(container: opening.container) == scope else { throw AccessError.accountChanged }+ try stack.access.check()+ if role == .host {+ let marker = configuration.directory.appendingPathComponent("AccessLocked")+ if FileManager.default.fileExists(atPath: marker.path) { try FileManager.default.removeItem(at: marker) }+ try stack.refreshAccess()+ stack.startHistory(directory: configuration.directory.appendingPathComponent("History", isDirectory: true))+ await stack.refreshHistory()+ let root = configuration.directory.deletingLastPathComponent().deletingLastPathComponent()+ if FileManager.default.fileExists(atPath: root.appendingPathComponent("Private.sqlite").path) {+ stack.storageNotice = "Earlier unscoped stores are retained separately. They were not attached to this account."+ } else if scope == .local {+ stack.storageNotice = "This library is stored only on this device. Signing in opens a separate iCloud library."+ }+ } else {+ stack.access.watchExtensionAccess(directory: configuration.directory, namespace: scope.namespace)+ try stack.access.check()+ }+ try stack.access.check()+ return stack } catch {- hostTask = nil+ stack.lockSession() throw error } } - static func open(configuration: StoreConfiguration) async throws -> PersistenceStack {+ static func deviceLibrary(role: PersistenceRole = .host) async throws -> PersistenceStack {+ if role != .host { return try await openDeviceLibrary(role: role) }+ if let deviceTask {+ let stack = try await deviceTask.value+ try stack.access.check()+ return stack+ }+ let task = Task { @MainActor in+ let stack = try await openDeviceLibrary(role: .host)+ deviceStack = stack+ return stack+ }+ deviceTask = task+ do { return try await task.value } catch { deviceTask = nil; throw error }+ }++ private static func openDeviceLibrary(role: PersistenceRole) async throws -> PersistenceStack {+ let configuration = try StoreConfiguration.production(role: role, scope: .local)+ if role != .host { _ = try ExtensionAccess.read(in: configuration.directory, namespace: "local") }+ let stack = try await open(configuration: configuration)+ if role == .host {+ let marker = configuration.directory.appendingPathComponent("AccessLocked")+ if FileManager.default.fileExists(atPath: marker.path) { try FileManager.default.removeItem(at: marker) }+ try stack.refreshAccess()+ stack.startHistory(directory: configuration.directory.appendingPathComponent("History", isDirectory: true))+ await stack.refreshHistory()+ stack.storageNotice = "This library stays on this device. Use backup/import to make an explicit copy into your iCloud library."+ } else {+ stack.access.watchExtensionAccess(directory: configuration.directory, namespace: "local")+ try stack.access.check()+ }+ return stack+ }++ static func open(configuration: StoreConfiguration, access: StoreAccess = StoreAccess()) async throws -> PersistenceStack {+ try access.check() if configuration.role == .host { try FileManager.default.createDirectory(at: configuration.directory, withIntermediateDirectories: true) } else {@@ -100,8 +203,12 @@ final class PersistenceStack { } } }- let stack = try PersistenceStack(container: container, configuration: configuration)- if configuration.role == .host {+ do { try access.check() } catch {+ for store in container.persistentStoreCoordinator.persistentStores { try? container.persistentStoreCoordinator.remove(store) }+ throw error+ }+ let stack = try PersistenceStack(container: container, configuration: configuration, access: access)+ if configuration.role == .host && configuration.accountScope == nil { stack.startHistory(directory: configuration.directory.appendingPathComponent("History", isDirectory: true)) await stack.refreshHistory() }@@ -110,7 +217,7 @@ final class PersistenceStack { func startHistory(directory: URL) { guard history == nil else { return }- history = HistoryProcessor(container: container, directory: directory, consumer: role.rawValue)+ history = HistoryProcessor(container: container, directory: directory, consumer: role.rawValue, access: access) let token = NotificationCenter.default.addObserver( forName: .NSPersistentStoreRemoteChange, object: container.persistentStoreCoordinator, queue: nil ) { [weak self] _ in@@ -127,10 +234,13 @@ final class PersistenceStack { Task { @MainActor [weak self] in if succeeded { self?.syncIssue = nil+ do { try self?.refreshAccess() } catch { self?.lockSession() } } else { self?.syncIssue = "iCloud sync is delayed: \(message ?? "Please try again later.")" self?.logger.error("CloudKit operation failed: \(message ?? "Unknown error", privacy: .public)") }+ if event.storeIdentifier == self?.sharedStore.identifier,+ CloudAccessFailure.removesAccess(event.error) { await self?.revalidateSharedAccess() } } } observation = PersistenceObservation(tokens: [token, cloudToken])@@ -139,7 +249,11 @@ final class PersistenceStack { func refreshHistory() async { guard let history else { return } do {+ try access.check() _ = try await history.process()+ try access.check()+ try refreshAccess()+ await revalidateSharedAccess(ifRequired: true) issue = nil } catch { issue = "Couldn’t refresh saved changes: \(error.localizedDescription)"@@ -148,6 +262,7 @@ final class PersistenceStack { } func localContactLinks() throws -> LocalContactLinks {+ try access.check() guard role == .host, let directory = privateStore.url?.deletingLastPathComponent() else { throw GraphError.readOnly } if let contactLinks { return contactLinks } let store = LocalContactLinks(file: directory.appendingPathComponent("DeviceLinks/contacts.json"))@@ -155,6 +270,60 @@ final class PersistenceStack { return store } + func verifyAccount() async {+ guard let accountScope, accountScope.mirrorsCloud else { return }+ do {+ guard let accountContainer,+ try await AccountScope.current(container: accountContainer) == accountScope else { throw AccessError.accountChanged }+ try access.check()+ try refreshAccess()+ await revalidateSharedAccess(ifRequired: true)+ } catch { lockSession() }+ }++ private func observeAccount(directory: URL) {+ let access = access+ let marker = directory.appendingPathComponent("AccessLocked")+ let token = NotificationCenter.default.addObserver(forName: .CKAccountChanged, object: nil, queue: nil) { [weak self] _ in+ if access.invalidate() { try? Data().write(to: marker, options: .atomic) }+ Task { @MainActor [weak self] in self?.lockSession() }+ }+ accountObservation = PersistenceObservation(tokens: [token])+ }++ func lockSession() {+ guard accessIssue == nil else { return }+ access.invalidate()+ accessIssue = AccessError.accountChanged.localizedDescription+ if accountScope != nil, let directory = privateStore.url?.deletingLastPathComponent() {+ try? Data().write(to: directory.appendingPathComponent("AccessLocked"), options: .atomic)+ }+ observation = nil+ accountObservation = nil+ container.viewContext.reset()+ // Detach; never destroy/reset SQLite files or another account's directory.+ for store in container.persistentStoreCoordinator.persistentStores {+ do { try container.persistentStoreCoordinator.remove(store) } catch {+ issue = "The previous data session could not be closed. Restart Halo Family before reopening."+ return+ }+ }+ if Self.hostStack === self {+ Self.hostStack = nil+ Self.hostTask = nil+ Self.hostGeneration = nil+ }+ if Self.deviceStack === self { Self.deviceStack = nil; Self.deviceTask = nil }+ }++ func shareVerificationFailed(_ error: Error) {+ syncIssue = "Shared-family access needs verification: \(error.localizedDescription)"+ }++ func shareVerificationSucceeded() {+ if syncIssue?.hasPrefix("Shared-family access needs verification:") == true { syncIssue = nil }+ }+ private func configureViewContext() { container.viewContext.transactionAuthor = role.rawValue container.viewContext.automaticallyMergesChangesFromParent = true
diff --git a/Halo Family/Halo Family/Persistence/PersonMergeHistory.swift b/Halo Family/Halo Family/Persistence/PersonMergeHistory.swiftindex e755105..86be035 100644--- a/Halo Family/Halo Family/Persistence/PersonMergeHistory.swift +++ b/Halo Family/Halo Family/Persistence/PersonMergeHistory.swift @@ -8,7 +8,7 @@ extension FamilyRepository { let request = NSFetchRequest<NSManagedObject>(entityName: "PersonMergeRecovery") request.predicate = NSPredicate(format: "familySpace == %@", familyID) request.sortDescriptors = [NSSortDescriptor(key: "createdAt", ascending: false)]- return try stack.container.viewContext.fetch(request).map {+ return try stack.fetch(request).map { try PersonMergeRecoveryRow(id: $0.objectID, createdAt: $0.value(forKey: "createdAt") as? Date, people: MergeSnapshot.decode($0.value(forKey: "beforeData") as? Data)) }
diff --git a/Halo Family/Halo Family/Persistence/RelationshipQueries.swift b/Halo Family/Halo Family/Persistence/RelationshipQueries.swiftindex 9daff96..6534f5a 100644--- a/Halo Family/Halo Family/Persistence/RelationshipQueries.swift +++ b/Halo Family/Halo Family/Persistence/RelationshipQueries.swift @@ -110,7 +110,7 @@ extension FamilyRepository { func contexts(in familyID: NSManagedObjectID, includeArchived: Bool = true) throws -> [ContextRow] { let request = NSFetchRequest<NSManagedObject>(entityName: "Context") request.predicate = NSPredicate(format: "familySpace == %@", familyID)- return try stack.container.viewContext.fetch(request).compactMap { object in+ return try stack.fetch(request).compactMap { object in let archived = object.value(forKey: "archivedAt") != nil guard includeArchived || !archived else { return nil } return ContextRow(id: object.objectID, name: object.value(forKey: "name") as? String ?? "Unnamed",@@ -121,7 +121,7 @@ extension FamilyRepository { func memberships(for connectionID: NSManagedObjectID) throws -> [MembershipRow] { let request = NSFetchRequest<NSManagedObject>(entityName: "ConnectionContext") request.predicate = NSPredicate(format: "connection == %@", connectionID)- return try stack.container.viewContext.fetch(request).compactMap { object in+ return try stack.fetch(request).compactMap { object in guard let source = object.value(forKey: "context") as? NSManagedObject else { return nil } return MembershipRow(id: object.objectID, contextID: source.objectID, name: contextPath(source), startedAt: object.value(forKey: "startedAt") as? Date,@@ -134,7 +134,7 @@ extension FamilyRepository { let request = NSFetchRequest<NSManagedObject>(entityName: "Event") request.predicate = NSPredicate(format: "familySpace == %@", familyID) request.sortDescriptors = [NSSortDescriptor(key: "date", ascending: false), NSSortDescriptor(key: "title", ascending: true)]- return try stack.container.viewContext.fetch(request).map(eventRow).filter { includeArchived || !$0.isArchived }+ return try stack.fetch(request).map(eventRow).filter { includeArchived || !$0.isArchived } } func contextConnections(_ contextID: NSManagedObjectID) throws -> [ContextConnectionRow] {@@ -142,7 +142,7 @@ extension FamilyRepository { request.predicate = NSPredicate(format: "context == %@", contextID) request.sortDescriptors = [NSSortDescriptor(key: "connection.person.displayName", ascending: true), NSSortDescriptor(key: "connection.child.person.displayName", ascending: true)]- return try stack.container.viewContext.fetch(request).compactMap { membership in+ return try stack.fetch(request).compactMap { membership in guard let connection = membership.value(forKey: "connection") as? NSManagedObject else { return nil } return ContextConnectionRow(id: membership.objectID, connectionID: connection.objectID, personName: connection.value(forKeyPath: "person.displayName") as? String ?? "Unnamed",@@ -157,7 +157,7 @@ extension FamilyRepository { request.predicate = NSPredicate(format: "context == %@", contextID) request.sortDescriptors = [NSSortDescriptor(key: "person.displayName", ascending: true), NSSortDescriptor(key: "role", ascending: true)]- return try stack.container.viewContext.fetch(request).compactMap { object in+ return try stack.fetch(request).compactMap { object in guard let person = object.value(forKey: "person") as? NSManagedObject, let source = object.value(forKey: "context") as? NSManagedObject else { return nil } return ContextPersonRow(id: object.objectID, contextID: source.objectID, personID: person.objectID,@@ -169,11 +169,13 @@ extension FamilyRepository { } func readable(_ id: NSManagedObjectID, entity: String) throws -> NSManagedObject {+ try stack.access.check() guard !id.isTemporaryID, id.entity.name == entity, let store = id.persistentStore, stack.container.persistentStoreCoordinator.persistentStores.contains(store) else { throw GraphError.invalidReference } let object = try stack.container.viewContext.existingObject(with: id) guard !object.isDeleted else { throw GraphError.invalidReference }+ try stack.access.check(object) return object }
diff --git a/Halo Family/Halo Family/Persistence/ReviewRepository.swift b/Halo Family/Halo Family/Persistence/ReviewRepository.swiftindex afdb95b..51518de 100644--- a/Halo Family/Halo Family/Persistence/ReviewRepository.swift +++ b/Halo Family/Halo Family/Persistence/ReviewRepository.swift @@ -20,7 +20,7 @@ extension FamilyRepository { request.sortDescriptors = [NSSortDescriptor(key: "person.displayName", ascending: true), NSSortDescriptor(key: "child.person.displayName", ascending: true)] request.relationshipKeyPathsForPrefetching = ["person", "child.person"]- let connections = try stack.container.viewContext.fetch(request)+ let connections = try stack.fetch(request) let states = try connectionStates(connections.map(\.objectID)) let origins = try conflictingOriginConnections(in: familyID) return connections.compactMap { connection in
diff --git a/Halo Family/Halo Family/Persistence/StoreConfiguration.swift b/Halo Family/Halo Family/Persistence/StoreConfiguration.swiftindex 1781e4e..95b14f5 100644--- a/Halo Family/Halo Family/Persistence/StoreConfiguration.swift +++ b/Halo Family/Halo Family/Persistence/StoreConfiguration.swift @@ -15,13 +15,15 @@ nonisolated struct StoreConfiguration: Sendable { let directory: URL let role: PersistenceRole let mirrorsCloud: Bool+ var accountScope: AccountScope? - static func production(role: PersistenceRole) throws -> StoreConfiguration {+ static func production(role: PersistenceRole, scope: AccountScope) throws -> StoreConfiguration { guard let group = FileManager.default.containerURL(forSecurityApplicationGroupIdentifier: appGroup) else { throw PersistenceError.appGroupUnavailable }- return StoreConfiguration(directory: group.appendingPathComponent("Persistence", isDirectory: true),- role: role, mirrorsCloud: role == .host)+ let root = group.appendingPathComponent("Persistence", isDirectory: true)+ return StoreConfiguration(directory: scope.directory(in: root), role: role,+ mirrorsCloud: role == .host && scope.mirrorsCloud, accountScope: scope) } func descriptions() -> [NSPersistentStoreDescription] {
diff --git a/Tests/HaloPersistenceTests/AccountAccessTests.swift b/Tests/HaloPersistenceTests/AccountAccessTests.swiftnew file mode 100644index 0000000..1adf135--- /dev/null+++ b/Tests/HaloPersistenceTests/AccountAccessTests.swift@@ -0,0 +1,265 @@+import CloudKit+import CoreData+import Testing+@testable import HaloPersistence++@MainActor+struct AccountAccessTests {+ private func directory() -> URL {+ FileManager.default.temporaryDirectory.appendingPathComponent(UUID().uuidString, isDirectory: true)+ }++ @Test func scopeHashesIdentityAndSeparatesCloudEnvironments() throws {+ let first = try AccountScope.verifiedCloud(userRecordName: "synthetic-owner-a", environment: "development")+ let same = try AccountScope.verifiedCloud(userRecordName: "synthetic-owner-a", environment: "development")+ let other = try AccountScope.verifiedCloud(userRecordName: "synthetic-owner-b", environment: "development")+ let release = try AccountScope.verifiedCloud(userRecordName: "synthetic-owner-a", environment: "production")+ #expect(first == same)+ #expect(first != other && first != release && first != .local)+ #expect(!first.namespace.contains("synthetic-owner"))+ #expect(first.namespace.count == 72)+ #expect(throws: AccessError.self) { try AccountScope.verifiedCloud(userRecordName: "") }+ }++ @Test func localAndAccountDirectoriesPreserveUnscopedFiles() throws {+ let root = directory()+ defer { try? FileManager.default.removeItem(at: root) }+ try FileManager.default.createDirectory(at: root, withIntermediateDirectories: true)+ let old = root.appendingPathComponent("Private.sqlite")+ let bytes = Data("unscoped synthetic sentinel".utf8)+ try bytes.write(to: old)+ let cloud = try AccountScope.verifiedCloud(userRecordName: "synthetic-owner")+ #expect(AccountScope.local.directory(in: root) != cloud.directory(in: root))+ #expect(!FileManager.default.fileExists(atPath: cloud.directory(in: root).path))+ #expect(try Data(contentsOf: old) == bytes)+ let local = StoreConfiguration(directory: AccountScope.local.directory(in: root), role: .host,+ mirrorsCloud: AccountScope.local.mirrorsCloud, accountScope: .local)+ #expect(local.descriptions().allSatisfy { $0.cloudKitContainerOptions == nil })+ }++ @Test func permissionsFilterListsAndRejectDirectReferences() throws {+ let root = directory()+ defer { try? FileManager.default.removeItem(at: root) }+ let stack = try PersistenceStack(directory: root)+ let graph = FamilyRepository(stack: stack)+ let allowed = try graph.createFamily(name: "Visible")+ let hidden = try graph.createFamily(name: "Locked")+ let child = try graph.addChild(name: "Synthetic child", familyID: hidden)+ let person = try graph.personID(for: graph.quickCapture(name: "Synthetic peer", childID: child))+ let id = try #require(stack.container.viewContext.existingObject(with: allowed).value(forKey: "id") as? UUID)+ stack.access.update(readable: [.init(family: id, shared: false)], writable: [.init(family: id, shared: false)])+ #expect(try graph.families().map(\.name) == ["Visible"])+ #expect(try graph.children(in: hidden).isEmpty)+ #expect(throws: AccessError.self) { try graph.person(person) }+ #expect(throws: AccessError.self) { try graph.quickCapture(name: "Denied", childID: child) }+ }++ @Test func readOnlyAllowsReadingButRejectsEveryChangedRow() throws {+ let root = directory()+ defer { try? FileManager.default.removeItem(at: root) }+ let stack = try PersistenceStack(directory: root)+ let graph = FamilyRepository(stack: stack)+ let family = try graph.createFamily(name: "Read only")+ let child = try graph.addChild(name: "Synthetic child", familyID: family)+ let id = try #require(stack.container.viewContext.existingObject(with: family).value(forKey: "id") as? UUID)+ stack.access.update(readable: [.init(family: id, shared: false)], writable: [])+ #expect(try graph.children(in: family).count == 1)+ #expect(throws: AccessError.self) { try graph.quickCapture(name: "Denied", childID: child) }+ #expect(throws: AccessError.self) {+ try graph.write { context in+ let root = try context.existingObject(with: family)+ root.setValue("Bypass attempt", forKey: "name")+ return root+ }+ }+ #expect(try graph.families().first?.name == "Read only")+ }++ @Test func invalidationAtSaveBoundaryDiscardsOnlyTheOperation() throws {+ let root = directory()+ defer { try? FileManager.default.removeItem(at: root) }+ let stack = try PersistenceStack(directory: root)+ let graph = FamilyRepository(stack: stack)+ let family = try graph.createFamily(name: "Preserved")+ #expect(throws: AccessError.self) {+ try graph.write { context in+ let object = try context.existingObject(with: family)+ object.setValue("Must not save", forKey: "name")+ stack.access.invalidate()+ return object+ }+ }+ let reopened = try PersistenceStack(directory: root)+ #expect(try FamilyRepository(stack: reopened).families().first?.name == "Preserved")+ #expect(throws: AccessError.self) { try graph.families() }+ }++ @Test func extensionManifestRejectsWrongAccountAndPropagatesRevocation() throws {+ let root = directory()+ defer { try? FileManager.default.removeItem(at: root) }+ try FileManager.default.createDirectory(at: root, withIntermediateDirectories: true)+ let family = UUID()+ let identity = FamilyAccessID(family: family, shared: false)+ let value = ExtensionAccess(version: 1, namespace: "synthetic-a", readable: [identity], writable: [identity], locked: false)+ try value.save(in: root)+ let access = StoreAccess()+ access.watchExtensionAccess(directory: root, namespace: "synthetic-a")+ try access.check(family: family, writing: true)+ #expect(throws: AccessError.self) { try ExtensionAccess.read(in: root, namespace: "synthetic-b") }+ try ExtensionAccess(version: 1, namespace: "synthetic-a", readable: [identity], writable: [], locked: false).save(in: root)+ try access.check(family: family)+ #expect(throws: AccessError.self) { try access.check(family: family, writing: true) }+ try Data().write(to: root.appendingPathComponent("AccessLocked"), options: .atomic)+ #expect(throws: AccessError.self) { try access.check(family: family) }+ }++ @Test func extensionManifestFailsClosedForInvalidAndOversizedData() throws {+ let root = directory()+ defer { try? FileManager.default.removeItem(at: root) }+ try FileManager.default.createDirectory(at: root, withIntermediateDirectories: true)+ let file = root.appendingPathComponent("ExtensionAccess.json")+ try Data("invalid".utf8).write(to: file)+ #expect(throws: AccessError.self) { try ExtensionAccess.read(in: root, namespace: "test") }+ try Data(repeating: 0, count: 1_000_001).write(to: file)+ #expect(throws: AccessError.self) { try ExtensionAccess.read(in: root, namespace: "test") }+ let invalid = ExtensionAccess(version: 1, namespace: "test", readable: [],+ writable: [.init(family: UUID(), shared: false)], locked: false)+ try invalid.save(in: root)+ #expect(throws: AccessError.self) { try ExtensionAccess.read(in: root, namespace: "test") }+ }++ @Test func lockedAssetsAndExportCannotReadSavedPayloads() async throws {+ let root = directory()+ defer { try? FileManager.default.removeItem(at: root) }+ let stack = try PersistenceStack(directory: root)+ let graph = FamilyRepository(stack: stack)+ let family = try graph.createFamily(name: "Synthetic")+ let assets = AssetRepository(stack: stack)+ let asset = try await assets.save(data: Data("synthetic payload".utf8), familyID: family)+ stack.access.invalidate()+ await #expect(throws: AccessError.self) { try await assets.data(for: asset) }+ await #expect(throws: AccessError.self) { try await assets.revision(for: asset) }+ await #expect(throws: AccessError.self) { try await BackupRepository(stack: stack).export(familyID: family) }+ await #expect(throws: AccessError.self) { try await assets.save(data: Data(), familyID: family) }+ }++ @Test func shareDenialsPersistExactShareAndClassifyWrappedRevocation() throws {+ let root = directory()+ defer { try? FileManager.default.removeItem(at: root) }+ try FileManager.default.createDirectory(at: root, withIntermediateDirectories: true)+ let first = CKRecord.ID(recordName: "synthetic-share-a", zoneID: .init(zoneName: "zone", ownerName: "owner"))+ let other = CKRecord.ID(recordName: "synthetic-share-b", zoneID: first.zoneID)+ var value = ShareDenials()+ value.shares.insert(ShareDenials.key(first))+ try value.save(in: root)+ #expect(try ShareDenials.read(in: root).shares.contains(ShareDenials.key(first)))+ #expect(try !ShareDenials.read(in: root).shares.contains(ShareDenials.key(other)))+ let denied = NSError(domain: CKErrorDomain, code: CKError.permissionFailure.rawValue)+ let wrapped = NSError(domain: NSCocoaErrorDomain, code: 1, userInfo: [NSUnderlyingErrorKey: denied])+ #expect(CloudAccessFailure.removesAccess(wrapped))+ #expect(!CloudAccessFailure.removesAccess(NSError(domain: CKErrorDomain, code: CKError.networkUnavailable.rawValue)))+ }++ @Test func privateGrantCannotAuthorizeSharedRootWithTheSameUUID() throws {+ let root = directory()+ defer { try? FileManager.default.removeItem(at: root) }+ let stack = try PersistenceStack(directory: root)+ let graph = FamilyRepository(stack: stack)+ let privateID = try graph.createFamily(name: "Private original")+ let context = stack.container.viewContext+ let uuid = try #require(context.existingObject(with: privateID).value(forKey: "id") as? UUID)+ let shared = NSEntityDescription.insertNewObject(forEntityName: "FamilySpace", into: context)+ context.assign(shared, to: stack.sharedStore)+ shared.setValue(uuid, forKey: "id")+ shared.setValue("Shared original", forKey: "name")+ try context.save()+ let child = try graph.addChild(name: "Synthetic child", familyID: shared.objectID)+ let privateKey = FamilyAccessID(family: uuid, shared: false)+ let sharedKey = FamilyAccessID(family: uuid, shared: true)+ stack.access.update(readable: [privateKey], writable: [privateKey])+ #expect(try graph.families().map(\.name) == ["Private original"])+ #expect(throws: AccessError.self) { try graph.readable(shared.objectID, entity: "FamilySpace") }+ stack.access.update(readable: [privateKey, sharedKey], writable: [privateKey])+ #expect(try graph.families().count == 2)+ #expect(throws: AccessError.self) { try graph.quickCapture(name: "Denied", childID: child) }+ #expect(try graph.addChild(name: "Allowed", familyID: privateID).persistentStore == stack.privateStore)+ }++ @Test func invalidatedOpeningSignalStopsBeforeCreatingStores() async throws {+ let root = directory()+ defer { try? FileManager.default.removeItem(at: root) }+ let access = StoreAccess()+ access.invalidate()+ await #expect(throws: AccessError.self) {+ try await PersistenceStack.open(configuration: StoreConfiguration(directory: root, role: .host, mirrorsCloud: false),+ access: access)+ }+ #expect(!FileManager.default.fileExists(atPath: root.path))+ }++ @Test func ambiguousSharedRootsCannotUseOneAnothersGrant() throws {+ let root = directory()+ defer { try? FileManager.default.removeItem(at: root) }+ let stack = try PersistenceStack(directory: root)+ let graph = FamilyRepository(stack: stack)+ let privateID = try graph.createFamily(name: "Unaffected private family")+ let context = stack.container.viewContext+ let privateUUID = try #require(context.existingObject(with: privateID).value(forKey: "id") as? UUID)+ let sharedUUID = UUID()+ var roots: [NSManagedObject] = []+ for name in ["Revoked share", "Allowed share"] {+ let family = NSEntityDescription.insertNewObject(forEntityName: "FamilySpace", into: context)+ context.assign(family, to: stack.sharedStore)+ family.setValue(sharedUUID, forKey: "id")+ family.setValue(name, forKey: "name")+ roots.append(family)+ }+ try context.save()+ let privateKey = FamilyAccessID(family: privateUUID, shared: false)+ let sharedKey = FamilyAccessID(family: sharedUUID, shared: true)+ stack.access.update(readable: [privateKey, sharedKey], writable: [privateKey, sharedKey])+ #expect(try graph.families().map(\.name) == ["Unaffected private family"])+ for family in roots {+ #expect(throws: AccessError.self) { try graph.readable(family.objectID, entity: "FamilySpace") }+ #expect(throws: AccessError.self) { try graph.addChild(name: "Denied", familyID: family.objectID) }+ }+ #expect(try graph.addChild(name: "Allowed", familyID: privateID).persistentStore == stack.privateStore)+ }++ @Test func repeatedTeardownCannotRelockAReopenedNamespace() async throws {+ let root = directory()+ defer { try? FileManager.default.removeItem(at: root) }+ let stack = try await PersistenceStack.open(+ configuration: StoreConfiguration(directory: root, role: .host, mirrorsCloud: false, accountScope: .local)+ )+ _ = try FamilyRepository(stack: stack).createFamily(name: "Retained")+ stack.lockSession()+ let marker = root.appendingPathComponent("AccessLocked")+ #expect(FileManager.default.fileExists(atPath: marker.path))+ try FileManager.default.removeItem(at: marker)+ stack.lockSession()+ #expect(!FileManager.default.fileExists(atPath: marker.path))+ let reopened = try PersistenceStack(directory: root)+ #expect(try FamilyRepository(stack: reopened).families().first?.name == "Retained")+ }++ @Test func explicitReinvitationClearsOnlyItsDenialWithoutCachedReinsertion() async throws {+ let root = directory()+ defer { try? FileManager.default.removeItem(at: root) }+ let stack = try await PersistenceStack.open(+ configuration: StoreConfiguration(directory: root, role: .host, mirrorsCloud: false, accountScope: .local)+ )+ let first = CKRecord.ID(recordName: "synthetic-reinvited")+ let other = CKRecord.ID(recordName: "synthetic-still-revoked")+ let firstKey = ShareDenials.key(first), otherKey = ShareDenials.key(other)+ var value = ShareDenials()+ value.shares = [firstKey, otherKey]+ value.permissions[firstKey] = false+ try value.save(in: root)+ try stack.didAcceptInvitation(first)+ try stack.refreshAccess()+ let retained = try ShareDenials.read(in: root)+ #expect(retained.shares == [otherKey])+ #expect(retained.permissions[firstKey] == nil)+ }+}
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex fd29831..af99a50 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -4,6 +4,15 @@ ### Added +- Verified account/environment store namespaces and an explicit device-only library;+ old unscoped stores remain unattached until owner provenance is established.+- Store-qualified family access, serialized save checks, idempotent account teardown,+ background publication guards and bounded cross-process extension manifests.+- Scoped server share verification, retained exact-share denials and reinvitation+ handling; unrelated shares are not permanently denied by one store-level error.+- Fourteen synthetic account/access cases: 120 declared tests/15 suites and strict+ lint 0/79 files; new compilation/runtime gates await the shared test slot.+ - Versioned family JSON/payload ZIP backup, optional readable summary and native preview with atomic absent-family or explicit fresh-identity copy import. - Guarded historical identity remapping, retained merge accounts, ownership-derived
diff --git a/docs/halo_family_design_pack/04-build-plan.md b/docs/halo_family_design_pack/04-build-plan.mdindex 2d1c1bf..771938c 100644--- a/docs/halo_family_design_pack/04-build-plan.md+++ b/docs/halo_family_design_pack/04-build-plan.md@@ -2,6 +2,18 @@ **Status:** Full application implementation in progress; release gates remain separate +### Account/access implementation — 2026-10-07 UTC++Account/environment-scoped stores, an explicit device-only library, opening/session+invalidation, store-qualified permission manifests, save/publication guards and+scoped share verification/reinvitation are implemented as source. Fourteen new+synthetic cases bring this checkout to **120 declared cases/15 suites**; strict+lint passes **0/79 files**. All new runtime/build gates remain pending the shared+slot. The last executed passing gate remains **3286293: 79 cases/10 suites and+both Debug builds**. Actual framework cache retention, account switching, share+revocation/reinvite/offline and legacy unscoped recovery remain release evidence+requirements. No production schema or actual account data operation ran.+ ### Backup, categories and search source checkpoint — 2026-10-07 UTC The source on verified V6 now adds versioned JSON plus payload ZIP export, an
diff --git a/docs/halo_family_design_pack/10-initial-implementation-results.md b/docs/halo_family_design_pack/10-initial-implementation-results.mdindex c830607..1e7fa0c 100644--- a/docs/halo_family_design_pack/10-initial-implementation-results.md+++ b/docs/halo_family_design_pack/10-initial-implementation-results.md@@ -1,5 +1,53 @@ # Implementation evidence +## Account/access source increment — 2026-10-07 UTC++Source now selects two stores under a SHA-256 account/environment namespace only+following account identity verification, with a separate explicitly selectable+on-device library that never mirrors CloudKit. Existing unscoped SQLite files are+left in place and are not attached to an unproven owner. Device-only memories+remain selectable after signing in; moving them to iCloud requires explicit+backup/import. The opening account-change signal is armed before identity lookup+and store attachment. A retained CKContainer receives account notifications.++Account changes invalidate reads and serialize final local saves against the+in-process signal. The UI hides locked sessions and teardown detaches stores+without deleting SQLite. Teardown is idempotent; background history/assets/import+results check access again before publication. Each grant contains both family+UUID and Private/Shared store identity, so an original-ID restored root cannot+lend permission to its later Shared counterpart. Multiple roots with the same+UUID within one store are also rejected at query/reference boundaries, including+before the next history refresh.++Extensions recheck a bounded host manifest under the permission lock. Shared+errors temporarily require server permission verification; permanent denials are+recorded only for the exact queried share. Read-only downgrades remain readable.+Explicit successful reinvitation clears only that share's denial; old cached+removed metadata does not recreate a permanent denial. Unrelated valid shares+can regain access following verification. Unknown/offline verification failures+leave shared access locked and Private data available.++Fourteen new synthetic cases are drafted: **120 declared tests/15 suites**,+strict lint **0/79 files**, with new test compilation and both builds pending the+shared Mac slot. The last executed passing gate is still **79 tests/10 suites**+and both Debug builds at **3286293**. Initial source reviewers identified startup,+save, manifest ordering, cross-store identity, stale teardown/publication and+reinvitation/revocation issues; fixes and regression source passed all four final read-only reviews.+Corrections also include duplicate roots within one store, library preference+changes in every window, overlapping share-verification retry, and avoiding a+root-count query per exported row. Permission updates and account invalidation+share a save gate; ordinary permission reads use a separate short lock.++No account status lookup, real store opening, CloudKit share fetch/update, native+Contacts call or real family backup was performed by this implementation task.+Actual no-account/restoration, account-change, revocation/reinvitation and offline+runtime gates remain unrun. Core Data may itself purge or alter cached content+before observer-driven detachment; retaining paths alone is not proof of retained+cache contents. Legacy unscoped recovery needs owner-provenance evidence before+those stores can be attached. CloudKit schema promotion and device/two-account+release validation remain separate blockers. Widget/intent product UX remains active.++ ## Backup, categories and search source checkpoint — 2026-10-07 UTC The source on verified V6 now adds versioned JSON plus payload ZIP export, an
diff --git a/docs/halo_family_design_pack/CHANGELOG.md b/docs/halo_family_design_pack/CHANGELOG.mdindex 3430fbb..beb58c3 100644--- a/docs/halo_family_design_pack/CHANGELOG.md+++ b/docs/halo_family_design_pack/CHANGELOG.md@@ -2,6 +2,10 @@ ## 7 October 2026 UTC +- Add account/access lifecycle source and fourteen synthetic regression cases;+ 120 declared cases/15 suites, strict lint 0/79 files. Keep test/build and actual+ account/share/cache-retention gates pending; preserve the prior verified evidence.+ - Add V6 duplicate/merge source, explicit previews, retained original records, guarded undo, late-account Review and conservative recovery of competing aliases. The V6 build/test gate passes: 79 cases/10 suites, strict lint 0/55 and both Debug builds.
diff --git a/docs/halo_family_design_pack/README.md b/docs/halo_family_design_pack/README.mdindex a0929d8..d703a6c 100644--- a/docs/halo_family_design_pack/README.md+++ b/docs/halo_family_design_pack/README.md@@ -40,7 +40,7 @@ The persistence spike concluded successfully enough to make a production decisio - persistent history + remote-store notifications for cross-process change delivery - binary assets with external storage enabled -The only deliberately deferred architecture validation is behaviour when **no iCloud account is available**, including later account restoration.+Account/access lifecycle is now implemented as source, including a separate device-only library. Actual no-account/restoration, account-change, share-removal/reinvite and framework cache-retention validation remain release gates; see [current implementation evidence](10-initial-implementation-results.md). ## Document policy
diff --git a/docs/halo_family_design_pack/decision_log.md b/docs/halo_family_design_pack/decision_log.mdindex a77ccad..5cd68a7 100644--- a/docs/halo_family_design_pack/decision_log.md+++ b/docs/halo_family_design_pack/decision_log.md@@ -10,6 +10,8 @@ | Q4 | 2026-10-07 UTC | Use Children, People, Contexts, Events and Review navigation, with a Mac sidebar and iOS tabs | Reversible implementation choice within the pack's UI direction. Keep per-window family selection and reset routes when changing family. Prioritize explicit closeness in child lists; lost contact can be included deliberately. | | Q5 | 2026-10-07 UTC | Retain source Connection accounts on archived records; transfer only late unseen/changed accounts as alternatives through Review | Implements the approved retention/review default. Keep original UUIDs, source histories and separate Event accounts; local snapshot checks do not claim a CloudKit compare-and-swap. | | Q6 | 2026-10-07 UTC | Recover competing merges by exposing separate identities while preserving current references and all earlier audits | Reversible conservative recovery avoids replaying old references over later edits. Current unsupported aliases remain visible; subsequent explicit merges acknowledge observed recovery UUIDs. Recovery is described separately from guarded undo. |+| Q7 | 2026-10-07 UTC | Separate verified account/environment stores from an explicitly selectable device-only library; retain unscoped stores without attaching them | Reversible privacy-preserving implementation of approved account lifecycle defaults. Never automatically upload device-only data or guess the owner of an old cache. Legacy recovery and framework retention still require evidence. |+| Q8 | 2026-10-07 UTC | Qualify permissions by family UUID plus owning store; temporarily lock ambiguous share errors and verify each exact share | Prevents an original-ID Private backup from granting access to a Shared counterpart, and avoids declaring unrelated invitations revoked. Confirmed denials require explicit reinvitation. | ## Decision 1: Retain competing first-meeting proposals for review
Run make test with coverage/JUnit, then make check sequentially after the parent grants the shared Mac slot. No runner was launched for this source increment.
Synthetic two-account/no-account/share/offline checks must establish framework behavior. Retained SQLite paths alone do not prove retained cache contents. Legacy unscoped ownership recovery and production schema/device validation remain pending.