Repository Public
1// Author: Simon-Pierre Boucher — contact@spboucher.ai2// File: Packages/LocalChatUI/Sources/Features/Settings/ServerController.swift3// Description: Owns the Local API server on macOS (configuration, lifecycle, API keys, live request log). On iOS it only reports that the server is unavailable.4import Foundation5import Observation6import LocalAPIServer7import LocalChatCore8import LocalChatSync910@MainActor @Observable11public final class ServerController {12 @ObservationIgnored unowned let app: AppModel1314 public var isRunning = false15 public private(set) var port: UInt16?16 public private(set) var lastError: String?17 public private(set) var log: [RequestLogEntry] = []18 public private(set) var keys: [APIKeyRecord] = []19 /// The secret of the key that was just created. Shown once, then cleared by the UI.20 public var revealedSecret: String?21 public private(set) var configuration = ServerConfiguration()22 public private(set) var startAtLaunch = false23 public private(set) var isBusy = false2425 public static var isAvailable: Bool {26 #if os(macOS)27 true28 #else29 false30 #endif31 }32 public var baseURL: String? { port.map { "http://127.0.0.1:\($0)/v1" } }33 public var docsURL: URL? { port.flatMap { URL(string: "http://127.0.0.1:\($0)/docs") } }34 public var hasActiveKeys: Bool { keys.contains(where: \.isActive) }3536 private struct Persisted: Codable { var configuration: ServerConfiguration; var startAtLaunch: Bool }37 @ObservationIgnored private var settingsURL: URL { app.paths.root.appendingPathComponent("server-settings.json") }38 @ObservationIgnored private let keyStore: FileAPIKeyStore39 @ObservationIgnored private var server: LocalAPIServer?40 @ObservationIgnored private var logTask: Task<Void, Never>?41 static let logLimit = 3004243 init(app: AppModel) {44 self.app = app45 keyStore = FileAPIKeyStore(fileURL: app.paths.root.appendingPathComponent("api-keys.json"))46 if let data = try? Data(contentsOf: app.paths.root.appendingPathComponent("server-settings.json")),47 let saved = try? JSONDecoder().decode(Persisted.self, from: data) {48 configuration = saved.configuration; startAtLaunch = saved.startAtLaunch49 }50 Task { [weak self] in await self?.reloadKeys() }51 }5253 private func persist() {54 try? JSONEncoder().encode(Persisted(configuration: configuration, startAtLaunch: startAtLaunch)).write(to: settingsURL, options: .atomic)55 }5657 /// Starts the server when the user enabled "start at launch".58 public func startIfConfigured() async {59 guard Self.isAvailable, startAtLaunch, !isRunning else { return }60 await start()61 }6263 public func setStartAtLaunch(_ value: Bool) { startAtLaunch = value; persist() }6465 /// Saves a new configuration and restarts the server when it is running.66 public func apply(_ new: ServerConfiguration) async {67 guard new != configuration else { return }68 configuration = new; persist()69 if isRunning { await stop(); await start() }70 }7172 public func start() async {73 #if os(macOS)74 guard !isRunning, !isBusy else { return }75 isBusy = true; defer { isBusy = false }76 lastError = nil77 await reloadKeys()78 if configuration.exposeOnLAN && !hasActiveKeys {79 lastError = "Network access needs at least one active API key. Create a key first: the server never listens on the network without authentication."80 return81 }82 let relay = SyncRelay(directory: app.paths.root.appendingPathComponent("SyncRelay", isDirectory: true))83 let server = LocalAPIServer(configuration: configuration, service: app.engine, keys: keyStore, routes: [relay])84 do {85 port = try await server.start()86 self.server = server; isRunning = true87 logTask = Task { [weak self] in88 for await entry in await server.requestStream() {89 guard let self else { return }90 self.log.insert(entry, at: 0)91 if self.log.count > Self.logLimit { self.log.removeLast(self.log.count - Self.logLimit) }92 if entry.keyLabel != nil { await self.reloadKeys() }93 }94 }95 } catch let error as ServerError {96 if case .portInUse(let p) = error { lastError = "Port \(p) is already used by another program. Choose another port, or quit the program that uses it." }97 else { lastError = error.errorDescription ?? "The server could not start." }98 } catch { lastError = error.localizedDescription }99 #else100 lastError = "The Local API server runs on the Mac."101 #endif102 }103104 public func stop() async {105 logTask?.cancel(); logTask = nil106 await server?.stop(); server = nil107 isRunning = false; port = nil108 }109110 public func clearLog() { log.removeAll() }111112 // MARK: API keys113114 public func reloadKeys() async { keys = await keyStore.list() }115116 public func createKey(label: String) async {117 let name = label.trimmingCharacters(in: .whitespacesAndNewlines)118 do {119 let made = try await keyStore.create(label: name.isEmpty ? "Key" : name)120 revealedSecret = made.secret121 await reloadKeys()122 } catch { lastError = error.localizedDescription }123 }124 public func revokeKey(_ id: UUID) async { try? await keyStore.revoke(id: id); await reloadKeys(); await stopIfUnprotected() }125 public func deleteKey(_ id: UUID) async { try? await keyStore.delete(id: id); await reloadKeys(); await stopIfUnprotected() }126127 private func stopIfUnprotected() async {128 if isRunning, configuration.exposeOnLAN, !hasActiveKeys {129 await stop()130 lastError = "The server was stopped: it was reachable from the network and no active API key is left."131 }132 }133134 /// IPv4 addresses of this Mac on its local networks (what to type on the iPhone).135 public nonisolated static func lanAddresses() -> [String] {136 var out: [String] = []137 var list: UnsafeMutablePointer<ifaddrs>?138 guard getifaddrs(&list) == 0, let first = list else { return [] }139 defer { freeifaddrs(list) }140 var cursor: UnsafeMutablePointer<ifaddrs>? = first141 while let entry = cursor {142 defer { cursor = entry.pointee.ifa_next }143 let flags = Int32(entry.pointee.ifa_flags)144 guard let addr = entry.pointee.ifa_addr, addr.pointee.sa_family == UInt8(AF_INET), flags & IFF_UP != 0, flags & IFF_LOOPBACK == 0 else { continue }145 var host = [CChar](repeating: 0, count: Int(NI_MAXHOST))146 if getnameinfo(addr, socklen_t(addr.pointee.sa_len), &host, socklen_t(host.count), nil, 0, NI_NUMERICHOST) == 0 {147 let ip = String(decoding: host.prefix { $0 != 0 }.map { UInt8(bitPattern: $0) }, as: UTF8.self)148 if !ip.hasPrefix("169.254."), !out.contains(ip) { out.append(ip) }149 }150 }151 return out152 }153}154