Repository Public License
1// ORIX Secure2// File: App/Sources/Features/Network/NetworkController.swift3// Description: Drives the Network Lab: live path monitoring while the app is active, the connection assessment, and the probes4// the user starts (DNS, latency, certificate, local network, Wi-Fi). Probes contact only the host shown on screen.5//6// Author: Simon-Pierre Boucher7// Contact: contact@spboucher.ai8import CoreLocation9import ORIXNetworkLab10import ORIXSecureModel11import SwiftUI1213@Observable final class NetworkController: NSObject, CLLocationManagerDelegate {14 private let monitor = ConnectivityMonitor()15 private let locationManager = CLLocationManager()16 private var monitorTask: Task<Void, Never>?1718 private(set) var snapshot: ConnectivitySnapshot?19 private(set) var changes: [NetworkChange] = []20 private(set) var input: NetworkAssessmentInput?21 private(set) var findings: [Finding] = []22 private(set) var dns: DNSResult?23 private(set) var latency: LatencyResult?24 private(set) var tls: TLSInspection?25 private(set) var https: HTTPSProbeResult?26 private(set) var bonjour: Reading<BonjourBrowseSummary>?27 private(set) var bonjourLive: [BonjourService] = []28 private(set) var running: Set<String> = []29 private(set) var probedHost: String?30 private(set) var locationStatus: CLAuthorizationStatus31 /// Called when the assessment findings change, so they can join the security assessment.32 var onFindings: (([Finding]) -> Void)?3334 override init() {35 locationStatus = locationManager.authorizationStatus36 super.init()37 locationManager.delegate = self38 }3940 var locationAuthorization: LocationAuthorization {41 switch locationStatus {42 case .notDetermined: .notDetermined43 case .denied: .denied44 case .restricted: .restricted45 case .authorizedAlways, .authorizedWhenInUse:46 locationManager.accuracyAuthorization == .fullAccuracy ? .authorizedPrecise : .authorizedReducedAccuracy47 @unknown default: .denied48 }49 }5051 func isRunning(_ key: String) -> Bool { running.contains(key) }5253 /// Starts path monitoring. It runs while the app is active (the dashboard shows the connection) and records changes.54 func startMonitoring() {55 guard monitorTask == nil else { return }56 monitor.start()57 monitorTask = Task { [weak self] in58 guard let stream = self?.monitor.snapshots() else { return }59 for await snapshot in stream {60 guard let self else { return }61 self.snapshot = snapshot62 self.changes = self.monitor.changeLog.reversed()63 }64 }65 }6667 func stopMonitoring() {68 monitorTask?.cancel()69 monitorTask = nil70 monitor.stop()71 }7273 /// Reads the connection, interfaces, proxy, VPN indicator and Wi-Fi details, and derives the findings.74 func assess() async {75 running.insert("assess")76 defer { running.remove("assess") }77 let collected = await NetworkAssessment.collect(locationAuthorization: locationAuthorization, monitor: monitor)78 input = collected79 if let value = collected.snapshot.value { snapshot = value }80 findings = NetworkAssessment.findings(for: collected)81 onFindings?(findings)82 }8384 func requestLocationForWiFi() {85 locationManager.requestWhenInUseAuthorization()86 }8788 nonisolated func locationManagerDidChangeAuthorization(_ manager: CLLocationManager) {89 let status = manager.authorizationStatus90 Task { @MainActor in91 self.locationStatus = status92 await self.assess()93 }94 }9596 /// Normalises what the user typed ("https://example.com/path" → "example.com").97 static func host(from text: String) -> String? {98 let trimmed = text.trimmingCharacters(in: .whitespacesAndNewlines)99 guard !trimmed.isEmpty else { return nil }100 if let url = URL(string: trimmed), let host = url.host(), url.scheme != nil { return host }101 let candidate = trimmed.split(separator: "/").first.map(String.init) ?? trimmed102 return TLSEndpoint(parsing: candidate)?.host103 }104105 func runProbes(on text: String) async {106 guard let host = Self.host(from: text) else { return }107 probedHost = host108 dns = nil109 latency = nil110 tls = nil111 https = nil112 running.formUnion(["dns", "latency", "tls"])113 async let dnsResult = DNSProbe.resolve(host)114 async let latencyResult = LatencyProbe.measure(host: host)115 async let tlsResult = TLSInspector.inspect(TLSEndpoint(host: host))116 dns = await dnsResult117 running.remove("dns")118 latency = await latencyResult119 running.remove("latency")120 tls = await tlsResult121 running.remove("tls")122 }123124 /// Sends one HEAD request to the host. Asked for separately because it is an actual web request.125 func runHTTPSProbe() async {126 guard let host = probedHost, let url = URL(string: "https://\(host)/") else { return }127 running.insert("https")128 https = await HTTPSProbe.head(url)129 running.remove("https")130 }131132 func browseLocalNetwork() async {133 running.insert("bonjour")134 bonjourLive = []135 bonjour = nil136 for await event in LocalNetworkBrowser.browse(duration: .seconds(6)) {137 switch event {138 case .found(let service): if !bonjourLive.contains(service) { bonjourLive.append(service) }139 case .lost(let service): bonjourLive.removeAll { $0 == service }140 case .finished(let summary): bonjour = summary141 }142 }143 running.remove("bonjour")144 }145146 func report() -> ReportDocument? {147 guard let input else { return nil }148 var report = NetworkAssessment.report(input: input, dns: dns.map { [$0] } ?? [], latency: latency.map { [$0] } ?? [], tls: tls.map { [$0] } ?? [])149 if let summary = bonjour?.value {150 report.sections.append(.init(title: L("Services announced on the local network"),151 facts: summary.services.map { .init($0.name, LocalNetworkBrowser.label(forServiceType: $0.type)) }, bullets: summary.notInspected))152 }153 report.generator = ReportBuilder.generator154 return report155 }156}157158/// One line describing the current connection, for the dashboard.159struct ConnectivitySummaryText: View {160 @Environment(AppModel.self) private var model161 var body: some View {162 if let snapshot = model.network.snapshot {163 let kinds = snapshot.interfaceKinds.filter { $0 != .loopback }.map(\.title).joined(separator: ", ")164 Text(verbatim: snapshot.status == .satisfied ? (kinds.isEmpty ? snapshot.status.title : kinds) : snapshot.status.title)165 } else {166 Text("Connection not read yet")167 }168 }169}170