SPB Git

Repository Public License

LocalStore.swift 8.6 KB 234 lines swift

1// ORIX Secure2// File: App/Sources/Core/LocalStore.swift3// Description: Local persistence (SwiftData): saved reports and history, checklist answers, user workflows. Everything stays in the4//              app's container under complete file protection; nothing is synced.5//6// Author: Simon-Pierre Boucher7// Contact: contact@spboucher.ai8import Foundation9import ORIXSecureEngines10import ORIXSecureModel11import SwiftData1213@Model final class StoredReport {14    @Attribute(.unique) var id: UUID15    var kindRaw: String16    var createdAt: Date17    var title: String18    var summary: String19    var attentionCount: Int20    /// The `ReportDocument`, JSON-encoded.21    @Attribute(.externalStorage) var payload: Data2223    init(id: UUID, kindRaw: String, createdAt: Date, title: String, summary: String, attentionCount: Int, payload: Data) {24        self.id = id25        self.kindRaw = kindRaw26        self.createdAt = createdAt27        self.title = title28        self.summary = summary29        self.attentionCount = attentionCount30        self.payload = payload31    }32}3334@Model final class StoredAnswer {35    @Attribute(.unique) var itemID: String36    var answerRaw: String37    var answeredAt: Date3839    init(itemID: String, answerRaw: String, answeredAt: Date) {40        self.itemID = itemID41        self.answerRaw = answerRaw42        self.answeredAt = answeredAt43    }44}4546@Model final class StoredWorkflow {47    @Attribute(.unique) var id: String48    var name: String49    var createdAt: Date50    /// The workflow definition, JSON-encoded.51    var payload: Data5253    init(id: String, name: String, createdAt: Date, payload: Data) {54        self.id = id55        self.name = name56        self.createdAt = createdAt57        self.payload = payload58    }59}6061/// A saved report as the UI lists it (the document is decoded on demand).62struct ReportSummary: Identifiable, Hashable {63    var id: UUID64    var kind: ReportDocument.Kind65    var createdAt: Date66    var title: String67    var summary: String68    var attentionCount: Int69}7071@Observable final class LocalStore {72    // SwiftData's ModelContext does not retain its container: keep it.73    private let container: ModelContainer74    private let context: ModelContext75    /// Bumped on every change so views that list reports refresh.76    private(set) var revision = 077    let isInMemory: Bool7879    static let schema = Schema([StoredReport.self, StoredAnswer.self, StoredWorkflow.self])8081    init(inMemory: Bool) throws {82        isInMemory = inMemory83        let configuration: ModelConfiguration84        if inMemory {85            configuration = ModelConfiguration(schema: Self.schema, isStoredInMemoryOnly: true)86        } else {87            let folder = AppFolders.database88            try FileManager.default.createDirectory(at: folder, withIntermediateDirectories: true,89                                                    attributes: [.protectionKey: FileProtectionType.complete])90            configuration = ModelConfiguration(schema: Self.schema, url: folder.appendingPathComponent("ORIXSecure.store"))91        }92        container = try ModelContainer(for: Self.schema, configurations: [configuration])93        context = ModelContext(container)94    }9596    private func commit() {97        try? context.save()98        revision += 199    }100101    // MARK: Reports102103    private static let encoder: JSONEncoder = {104        let encoder = JSONEncoder()105        encoder.dateEncodingStrategy = .iso8601106        return encoder107    }()108109    private static let decoder: JSONDecoder = {110        let decoder = JSONDecoder()111        decoder.dateDecodingStrategy = .iso8601112        return decoder113    }()114115    @discardableResult func save(_ report: ReportDocument) -> Bool {116        guard let payload = try? Self.encoder.encode(report) else { return false }117        let id = report.id118        if let existing = try? context.fetch(FetchDescriptor<StoredReport>(predicate: #Predicate { $0.id == id })).first {119            context.delete(existing)120        }121        context.insert(StoredReport(id: report.id, kindRaw: report.kind.rawValue, createdAt: report.createdAt, title: report.title, summary: report.summary,122                                    attentionCount: report.allFindings.count(.attention), payload: payload))123        commit()124        return true125    }126127    func reports(limit: Int? = nil) -> [ReportSummary] {128        _ = revision129        var descriptor = FetchDescriptor<StoredReport>(sortBy: [SortDescriptor(\.createdAt, order: .reverse)])130        if let limit { descriptor.fetchLimit = limit }131        let stored = (try? context.fetch(descriptor)) ?? []132        return stored.map {133            ReportSummary(id: $0.id, kind: ReportDocument.Kind(rawValue: $0.kindRaw) ?? .securityAssessment, createdAt: $0.createdAt, title: $0.title,134                          summary: $0.summary, attentionCount: $0.attentionCount)135        }136    }137138    func report(_ id: UUID) -> ReportDocument? {139        guard let stored = try? context.fetch(FetchDescriptor<StoredReport>(predicate: #Predicate { $0.id == id })).first else { return nil }140        return try? Self.decoder.decode(ReportDocument.self, from: stored.payload)141    }142143    func deleteReport(_ id: UUID) {144        guard let stored = try? context.fetch(FetchDescriptor<StoredReport>(predicate: #Predicate { $0.id == id })).first else { return }145        context.delete(stored)146        commit()147    }148149    func deleteAllReports() {150        try? context.delete(model: StoredReport.self)151        commit()152    }153154    // MARK: Checklist answers155156    func responses() -> [ChecklistResponse] {157        _ = revision158        let stored = (try? context.fetch(FetchDescriptor<StoredAnswer>())) ?? []159        return stored.compactMap { answer in160            ChecklistAnswer(rawValue: answer.answerRaw).map { ChecklistResponse(itemID: answer.itemID, answer: $0, answeredAt: answer.answeredAt) }161        }162    }163164    func setAnswer(_ answer: ChecklistAnswer?, for itemID: String, at date: Date = Date()) {165        if let existing = try? context.fetch(FetchDescriptor<StoredAnswer>(predicate: #Predicate { $0.itemID == itemID })).first {166            context.delete(existing)167        }168        if let answer {169            context.insert(StoredAnswer(itemID: itemID, answerRaw: answer.rawValue, answeredAt: date))170        }171        commit()172    }173174    func deleteAllAnswers() {175        try? context.delete(model: StoredAnswer.self)176        commit()177    }178179    // MARK: Workflows180181    func workflowPayloads() -> [Data] {182        _ = revision183        let stored = (try? context.fetch(FetchDescriptor<StoredWorkflow>(sortBy: [SortDescriptor(\.createdAt)]))) ?? []184        return stored.map(\.payload)185    }186187    func saveWorkflow(id: String, name: String, payload: Data) {188        if let existing = try? context.fetch(FetchDescriptor<StoredWorkflow>(predicate: #Predicate { $0.id == id })).first {189            context.delete(existing)190        }191        context.insert(StoredWorkflow(id: id, name: name, createdAt: Date(), payload: payload))192        commit()193    }194195    func deleteWorkflow(id: String) {196        guard let stored = try? context.fetch(FetchDescriptor<StoredWorkflow>(predicate: #Predicate { $0.id == id })).first else { return }197        context.delete(stored)198        commit()199    }200201    func deleteEverything() {202        try? context.delete(model: StoredReport.self)203        try? context.delete(model: StoredAnswer.self)204        try? context.delete(model: StoredWorkflow.self)205        commit()206    }207}208209/// Folders ORIX Secure owns inside its container.210enum AppFolders {211    private static var support: URL {212        (FileManager.default.urls(for: .applicationSupportDirectory, in: .userDomainMask).first ?? FileManager.default.temporaryDirectory)213            .appendingPathComponent("ORIXSecure", isDirectory: true)214    }215216    static var database: URL { support.appendingPathComponent("Database", isDirectory: true) }217    static var exports: URL { FileManager.default.temporaryDirectory.appendingPathComponent("ORIXSecureExports", isDirectory: true) }218    static var temporary: URL { FileManager.default.temporaryDirectory.appendingPathComponent("ORIXSecureWork", isDirectory: true) }219    static var caches: URL {220        (FileManager.default.urls(for: .cachesDirectory, in: .userDomainMask).first ?? FileManager.default.temporaryDirectory)221            .appendingPathComponent("ORIXSecure", isDirectory: true)222    }223224    static var owned: OwnedLocations {225        OwnedLocations(exports: exports, caches: caches, temporary: temporary, database: database)226    }227228    static func prepare() {229        for folder in [exports, temporary, caches] {230            try? FileManager.default.createDirectory(at: folder, withIntermediateDirectories: true, attributes: [.protectionKey: FileProtectionType.complete])231        }232    }233}234
Files main
Menu

Theme