SPB Git

Repository Public

AppEnvironment.swift 5.5 KB 111 lines swift

1import AppKit2import Foundation3import MCCCore45/// Launch configuration. Release builds always talk to production with system passkeys and the Keychain; the6/// overrides below exist in Debug builds only (local backend, software authenticator, UI tests).7struct AppEnvironment: Sendable {8    enum SecureStoreKind: String, Sendable { case keychain, file, memory }910    var origin: URL = CoreConfiguration.productionOrigin11    var softwarePasskeys = false12    var secureStore: SecureStoreKind = .keychain13    var language: AppLanguage?14    var uiTesting = false15    var resetState = false16    /// Invitation token handed at launch (Debug, UI tests). Consumed once, never logged or stored.17    var setupToken: String?18    var stateDirectory: URL?1920    var isProduction: Bool { origin == CoreConfiguration.productionOrigin }2122    static func resolve(_ info: ProcessInfo = .processInfo) -> AppEnvironment {23        var env = AppEnvironment()24        #if DEBUG25        let e = info.environment26        if let s = e["MCC_BASE_URL"], let url = URL(string: s), url.host != nil { env.origin = url }27        env.softwarePasskeys = e["MCC_PASSKEY"] == "software"28        if let k = e["MCC_SECURE_STORE"].flatMap(SecureStoreKind.init(rawValue:)) { env.secureStore = k }29        env.language = e["MCC_LANGUAGE"].flatMap(AppLanguage.init(rawValue:))30        env.uiTesting = e["MCC_UITEST"] == "1"31        env.resetState = e["MCC_RESET"] == "1"32        env.setupToken = e["MCC_SETUP_TOKEN"].flatMap { $0.isEmpty ? nil : $0 }33        if let dir = e["MCC_STATE_DIR"], !dir.isEmpty { env.stateDirectory = URL(fileURLWithPath: dir, isDirectory: true) }34        #endif35        return env36    }3738    /// Where this build keeps its local, non-secret state (offline cache, Debug-only test material).39    var supportDirectory: URL {40        if let stateDirectory { return stateDirectory }41        let root = (try? FileManager.default.url(for: .applicationSupportDirectory, in: .userDomainMask, appropriateFor: nil, create: true))42            ?? FileManager.default.temporaryDirectory43        return root.appendingPathComponent(Bundle.main.bundleIdentifier ?? "ai.spboucher.clustr", isDirectory: true)44    }4546    /// DEBUG, UI tests: start from a clean local state (files and preferences of this build only).47    func resetLocalStateIfRequested() {48        #if DEBUG49        guard resetState else { return }50        try? FileManager.default.removeItem(at: supportDirectory)51        if let id = Bundle.main.bundleIdentifier { UserDefaults.standard.removePersistentDomain(forName: id) }52        #endif53    }5455    private var namespace: String { (origin.host() ?? "server") + (origin.port.map { "-\($0)" } ?? "") }5657    @MainActor58    func makeConfiguration() -> CoreConfiguration {59        let support = supportDirectory60        let passkeys: any PasskeyProvider61        let store: any SecureStore62        #if DEBUG63        if softwarePasskeys {64            var o = "\(origin.scheme ?? "http")://\(origin.host() ?? "localhost")"65            if let p = origin.port { o += ":\(p)" }66            passkeys = SoftwareAuthenticator(origin: o, storageURL: support.appendingPathComponent("debug-passkeys.json"))67        } else {68            passkeys = PlatformPasskeyProvider(relyingPartyID: isProduction ? CoreConfiguration.relyingPartyID : (origin.host() ?? "localhost")) { Self.keyWindow() }69        }70        switch secureStore {71        case .file: store = DebugFileSecureStore(directory: support.appendingPathComponent("debug-secrets", isDirectory: true))72        case .memory: store = InMemorySecureStore()73        case .keychain: store = Self.keychain()74        }75        #else76        passkeys = PlatformPasskeyProvider(relyingPartyID: CoreConfiguration.relyingPartyID) { Self.keyWindow() }77        store = Self.keychain()78        #endif79        return CoreConfiguration(origin: origin, secureStore: store, passkeys: passkeys,80                                 cacheDirectory: support.appendingPathComponent("OfflineCache", isDirectory: true).appendingPathComponent(namespace, isDirectory: true))81    }8283    /// The data-protection Keychain (accessible after first unlock, this device only, never synchronised) when the84    /// build carries an application identifier — which the provisioned Release build does. A locally signed Debug85    /// build has none and falls back to the login keychain.86    private static func keychain() -> KeychainSecureStore {87        let service = "ai.spboucher.clustr.session"88        if let group = Entitlements.keychainAccessGroup {89            return KeychainSecureStore(service: service, accessGroup: group, dataProtection: true)90        }91        return KeychainSecureStore(service: service, accessGroup: nil, dataProtection: Entitlements.applicationIdentifier != nil)92    }9394    @MainActor95    static func keyWindow() -> NSWindow? {96        NSApp.keyWindow ?? NSApp.mainWindow ?? NSApp.windows.first { $0.isVisible && $0.canBecomeKey }97    }98}99100/// Entitlements of the running binary (read from its own code signature).101enum Entitlements {102    private static func value(_ key: String) -> Any? {103        guard let task = SecTaskCreateFromSelf(nil) else { return nil }104        return SecTaskCopyValueForEntitlement(task, key as CFString, nil)105    }106    static var applicationIdentifier: String? { value("com.apple.application-identifier") as? String }107    static var keychainAccessGroup: String? { (value("keychain-access-groups") as? [String])?.first }108    static var apsEnvironment: String? { value("com.apple.developer.aps-environment") as? String }109    static var associatedDomains: [String] { value("com.apple.developer.associated-domains") as? [String] ?? [] }110}111
Files main
Menu

Theme