SPB Git

Repository Public License

AppModel.swift 6.4 KB 141 lines swift

1// ORIX Secure2// File: App/Sources/Core/AppModel.swift3// Description: The app's state: device readings, security signals, the assessment built from them and from the user's answers,4//              the privacy audit and the storage overview. Views read it; engines do the work.5//6// Author: Simon-Pierre Boucher7// Contact: contact@spboucher.ai8import AVFoundation9import CoreLocation10import ORIXSecureEngines11import ORIXSecureModel12import Photos13import SwiftUI14import UIKit1516@Observable final class AppModel {17    let store: LocalStore18    let settings: AppSettings19    let router = Router()20    let lock: AppLock2122    private let deviceProbe: any DeviceProbing23    private let securityProbe: any SecurityProbing24    private let assessmentEngine = SecurityAssessmentEngine()25    private let privacyEngine = PrivacyAuditEngine()26    let storageEngine = StorageAnalysisEngine(locations: AppFolders.owned)27    let diagnosticsEngine = DeviceDiagnosticsEngine()28    let network = NetworkController()29    let photos = PhotoCleanupController()3031    private(set) var device: DeviceSnapshot32    private(set) var signals: SecuritySignals33    private(set) var assessment: SecurityAssessment34    private(set) var privacy: PrivacyAudit35    private(set) var storage: StorageOverview36    /// Findings from the last network diagnostics run; they join the security assessment.37    var networkFindings: [Finding] = [] { didSet { recompute() } }38    /// Cleanup candidates found by the last photo scan, for the dashboard. Nil until a scan has run.39    var photoOpportunity: CleanupOpportunity?40    private(set) var lastRefresh = Date()4142    init(store: LocalStore, settings: AppSettings, deviceProbe: any DeviceProbing = SystemDeviceProbe(), securityProbe: any SecurityProbing = SystemSecurityProbe()) {43        self.store = store44        self.settings = settings45        self.deviceProbe = deviceProbe46        self.securityProbe = securityProbe47        lock = AppLock(settings: settings)48        AppFolders.prepare()49        let device = deviceProbe.snapshot()50        let signals = securityProbe.signals(isSimulator: device.isSimulator, screenCaptured: Self.screenCaptured())51        let responses = store.responses()52        self.device = device53        self.signals = signals54        assessment = assessmentEngine.assess(device: device, signals: signals, responses: responses)55        privacy = privacyEngine.audit(permissions: Self.permissions(settings: settings, signals: signals), responses: responses)56        storage = storageEngine.overview(volume: device.volume)57        network.onFindings = { [weak self] in self?.networkFindings = $0 }58        network.startMonitoring()59    }6061    /// Reads the device again and rebuilds every assessment.62    func refresh() {63        device = deviceProbe.snapshot()64        signals = securityProbe.signals(isSimulator: device.isSimulator, screenCaptured: Self.screenCaptured())65        storage = storageEngine.overview(volume: device.volume)66        lastRefresh = Date()67        recompute()68    }6970    private func recompute() {71        let responses = store.responses()72        assessment = assessmentEngine.assess(device: device, signals: signals, responses: responses, contributed: networkFindings)73        privacy = privacyEngine.audit(permissions: Self.permissions(settings: settings, signals: signals), responses: responses)74    }7576    func answer(_ answer: ChecklistAnswer?, for itemID: String) {77        store.setAnswer(answer, for: itemID)78        recompute()79    }8081    func response(for itemID: String) -> ChecklistResponse? {82        store.responses().first { $0.itemID == itemID }83    }8485    /// Findings to act on across security, privacy, storage and device, most important first.86    var recommendedActions: [Finding] {87        (assessment.actions + privacy.all.filter { $0.state == .attention } + storage.findings.filter { $0.state == .attention }88            + diagnosticsEngine.findings(device).filter { $0.state == .attention }).prioritized()89    }9091    static func screenCaptured() -> Reading<Bool> {92        guard let scene = UIApplication.shared.connectedScenes.compactMap({ $0 as? UIWindowScene }).first else {93            return .unavailable(.notRequested, L("No window was active when this was checked."))94        }95        return .measured(scene.traitCollection.sceneCaptureState == .active)96    }9798    /// ORIX Secure's own permission states: the only ones an app can read.99    static func permissions(settings: AppSettings, signals: SecuritySignals) -> [AppPermission] {100        let photos: AppPermissionStatus = switch PHPhotoLibrary.authorizationStatus(for: .readWrite) {101        case .notDetermined: .notRequested102        case .authorized: .granted103        case .limited: .limited104        case .denied: .denied105        case .restricted: .restricted106        @unknown default: .unknown107        }108        let camera: AppPermissionStatus = switch AVCaptureDevice.authorizationStatus(for: .video) {109        case .notDetermined: .notRequested110        case .authorized: .granted111        case .denied: .denied112        case .restricted: .restricted113        @unknown default: .unknown114        }115        let location: AppPermissionStatus = switch CLLocationManager().authorizationStatus {116        case .notDetermined: .notRequested117        case .authorizedAlways, .authorizedWhenInUse: .granted118        case .denied: .denied119        case .restricted: .restricted120        @unknown default: .unknown121        }122        let faceID: AppPermissionStatus = signals.biometryEnrolled.unavailability?.kind == .permissionRequired ? .denied : (settings.appLockEnabled ? .granted : .notRequested)123        return [124            AppPermission(kind: .photos, status: photos, source: "PHPhotoLibrary.authorizationStatus(for: .readWrite)"),125            AppPermission(kind: .camera, status: camera, source: "AVCaptureDevice.authorizationStatus(for: .video)"),126            AppPermission(kind: .location, status: location, source: "CLLocationManager.authorizationStatus"),127            AppPermission(kind: .localNetwork, status: .unknown, source: "no public API"),128            AppPermission(kind: .faceID, status: faceID, source: "LAContext.canEvaluatePolicy"),129        ]130    }131}132133/// What the last photo scan found, summarised for the dashboard.134struct CleanupOpportunity: Hashable {135    var candidateCount: Int136    /// Sum of the measured sizes of the candidates. Nil when no size could be measured.137    var measuredBytes: Int64?138    var unmeasuredCount: Int139    var scannedAt: Date140}141
Files main
Menu

Theme