Repository Public
1// Author: Simon-Pierre Boucher — contact@spboucher.ai2// File: Packages/LocalChatUI/Sources/Features/Settings/SyncController.swift3// Description: Optional end-to-end encrypted synchronization: mode (off / folder / Mac node), passphrase setup, master key in the Keychain, status.4import Foundation5import Observation6import LocalChatCore7import LocalChatSecurity8import LocalChatSync910@MainActor @Observable11public final class SyncController {12 @ObservationIgnored unowned let app: AppModel1314 public enum Mode: String, Codable, Sendable, CaseIterable, Identifiable {15 case off, folder, node16 public var id: String { rawValue }17 public var title: String { switch self { case .off: "Off (this device only)"; case .folder: "Folder"; case .node: "Mac node" } }18 }1920 struct Config: Codable {21 var mode: Mode = .off22 var folderBookmark: Data?23 var folderPath: String?24 var nodeBaseURL: String?25 var nodeName: String?26 var allowInsecureHTTP = false27 }2829 public private(set) var mode: Mode = .off30 public var isEnabled = false31 public private(set) var status: SyncStatus = .localOnly32 public private(set) var lastSummary: SyncSummary?33 public private(set) var lastError: String?34 public private(set) var isBusy = false35 public private(set) var destination: String? // folder path or node URL, for display3637 @ObservationIgnored private var config = Config()38 @ObservationIgnored private let engine: SyncEngine39 @ObservationIgnored private var statusTask: Task<Void, Never>?40 @ObservationIgnored private var restored = false41 @ObservationIgnored private var scopedFolder: URL?42 static let masterKeyAccount = "sync.masterKey"43 static let nodeKeyAccount = "sync.nodeKey"44 private var configURL: URL { app.paths.root.appendingPathComponent("sync-config.json") }4546 init(app: AppModel) {47 self.app = app48 engine = SyncEngine(store: app.store, stateURL: app.paths.root.appendingPathComponent("sync-state.json"))49 if let data = try? Data(contentsOf: app.paths.root.appendingPathComponent("sync-config.json")), let c = try? JSONDecoder().decode(Config.self, from: data) { config = c }50 mode = config.mode; isEnabled = config.mode != .off51 destination = config.mode == .folder ? config.folderPath : config.mode == .node ? config.nodeBaseURL : nil52 let engine = engine53 statusTask = Task { [weak self] in54 for await s in await engine.statusUpdates() {55 guard let self else { return }56 self.status = s57 if case .idle(let last) = s, let last { self.lastSummary = last }58 }59 }60 }6162 private func persist() { try? JSONEncoder().encode(config).write(to: configURL, options: .atomic) }6364 // MARK: Transport6566 private func makeTransport() throws -> any SyncTransport {67 switch config.mode {68 case .off: throw SyncError.notConfigured69 case .folder:70 guard let bookmark = config.folderBookmark else { throw SyncError.notConfigured }71 var stale = false72 #if os(macOS)73 let options: URL.BookmarkResolutionOptions = [.withSecurityScope]74 #else75 let options: URL.BookmarkResolutionOptions = []76 #endif77 let url = try URL(resolvingBookmarkData: bookmark, options: options, relativeTo: nil, bookmarkDataIsStale: &stale)78 if scopedFolder != url { scopedFolder?.stopAccessingSecurityScopedResource(); _ = url.startAccessingSecurityScopedResource(); scopedFolder = url }79 return FolderSyncTransport(folder: url)80 case .node:81 guard let text = config.nodeBaseURL, let url = URL(string: text) else { throw SyncError.notConfigured }82 let key = (try? app.keychain.string(for: Self.nodeKeyAccount)) ?? ""83 return try NodeSyncTransport(baseURL: url, apiKey: key, allowInsecureHTTP: config.allowInsecureHTTP)84 }85 }8687 /// The server root a `RemoteNode` syncs with (its inference URL without the trailing /v1).88 public static func serverRoot(of baseURL: String) -> String {89 var s = baseURL.trimmingCharacters(in: .whitespacesAndNewlines)90 while s.hasSuffix("/") { s.removeLast() }91 if s.hasSuffix("/v1") { s.removeLast(3) }92 return s93 }9495 // MARK: Setup9697 public func generatePassphrase() -> String { PairingCode.generate() }9899 /// nil when the passphrase is acceptable, otherwise why it is not.100 public func passphraseProblem(_ text: String) -> String? {101 let t = text.trimmingCharacters(in: .whitespacesAndNewlines)102 if t.isEmpty { return "Enter the sync passphrase." }103 if PairingCode.isValid(t) { return nil }104 if t.count < 12 { return "Use a generated code, or a passphrase of at least 12 characters." }105 return nil106 }107108 public func enableFolder(_ folder: URL, passphrase: String) async {109 let scoped = folder.startAccessingSecurityScopedResource()110 defer { if scoped { folder.stopAccessingSecurityScopedResource() } }111 #if os(macOS)112 let options: URL.BookmarkCreationOptions = [.withSecurityScope]113 #else114 let options: URL.BookmarkCreationOptions = []115 #endif116 guard let bookmark = try? folder.bookmarkData(options: options, includingResourceValuesForKeys: nil, relativeTo: nil) else {117 lastError = "Local Chat could not keep access to this folder."; return118 }119 var c = Config(); c.mode = .folder; c.folderBookmark = bookmark; c.folderPath = folder.path120 await enable(c, passphrase: passphrase)121 }122123 public func enableNode(baseURL: String, name: String?, apiKey: String, allowInsecureHTTP: Bool, passphrase: String) async {124 var c = Config(); c.mode = .node; c.nodeBaseURL = Self.serverRoot(of: baseURL); c.nodeName = name; c.allowInsecureHTTP = allowInsecureHTTP125 do { try app.keychain.set(apiKey, for: Self.nodeKeyAccount) } catch { lastError = "The node key could not be saved in the Keychain: \(error.localizedDescription)"; return }126 await enable(c, passphrase: passphrase)127 }128129 private func enable(_ new: Config, passphrase: String) async {130 if let problem = passphraseProblem(passphrase) { lastError = problem; return }131 isBusy = true; defer { isBusy = false }132 lastError = nil133 let previous = config134 config = new135 let secret = PairingCode.isValid(passphrase) ? PairingCode.canonical(passphrase) : passphrase.trimmingCharacters(in: .whitespacesAndNewlines)136 do {137 let transport = try makeTransport()138 let master = try await engine.configure(transport: transport, passphrase: secret)139 try app.keychain.set(master, for: Self.masterKeyAccount)140 persist(); restored = true141 mode = new.mode; isEnabled = true142 destination = new.mode == .folder ? new.folderPath : new.nodeBaseURL143 await syncNow()144 } catch {145 config = previous146 lastError = describe(error)147 }148 }149150 private func restoreIfNeeded() async -> Bool {151 if restored { return true }152 guard config.mode != .off else { return false }153 do {154 guard let master = try app.keychain.data(for: Self.masterKeyAccount) else {155 lastError = "The sync key is missing from the Keychain. Turn sync off and set it up again with your passphrase."; return false156 }157 try await engine.configure(transport: try makeTransport(), masterKey: master)158 restored = true; return true159 } catch { lastError = describe(error); return false }160 }161162 // MARK: Running163164 /// Runs one synchronization pass when sync is configured (called at launch, on foreground and after changes).165 public func syncIfEnabled() async {166 guard isEnabled, !isBusy else { return }167 await syncNow()168 }169170 public func syncNow() async {171 guard isEnabled else { return }172 guard await restoreIfNeeded() else { return }173 do {174 lastSummary = try await engine.sync(); lastError = nil175 app.reloadLists()176 } catch SyncError.alreadySyncing { }177 catch { lastError = describe(error) }178 }179180 public func disable(forgetProgress: Bool) async {181 await engine.disable(forgetProgress: forgetProgress)182 _ = try? app.keychain.delete(Self.masterKeyAccount)183 _ = try? app.keychain.delete(Self.nodeKeyAccount)184 scopedFolder?.stopAccessingSecurityScopedResource(); scopedFolder = nil185 config = Config(); persist()186 mode = .off; isEnabled = false; restored = false; destination = nil; lastError = nil; status = .localOnly187 if forgetProgress { lastSummary = nil }188 }189190 private func describe(_ error: Error) -> String {191 if let e = error as? SyncError {192 switch e {193 case .wrongPassphrase: return "Wrong passphrase: this destination was set up with a different one. Nothing was changed."194 case .insecureURL: return "Plain HTTP is only accepted for a Mac on your private network. Use https, or allow insecure HTTP explicitly."195 case .unauthorized: return "The Mac refused the API key."196 default: return e.errorDescription ?? "Sync failed."197 }198 }199 return error.localizedDescription200 }201}202