SPB Git

Repository Public License

overview.md 15.0 KB 260 lines markdown

1<!--2ORIX Secure3File: docs/architecture/overview.md4Description: Module map, result vocabulary, localization, persistence, concurrency, navigation and local data architecture.5Author: Simon-Pierre Boucher6Contact: contact@spboucher.ai7-->89# ORIX Secure — Architecture overview1011ORIX Secure is an iOS/iPadOS 18+ app (Swift 6 language mode, strict concurrency `complete`, SwiftUI) built from12eight local Swift packages, one app target and one share extension. The project is generated by XcodeGen from13`project.yml`. There is no third-party dependency and no server.1415Companion documents: [security-engine.md](security-engine.md), [diagnostics.md](diagnostics.md),16[storage.md](storage.md), [network.md](network.md), [privacy.md](privacy.md).1718## 1. Module map1920An arrow `A --> B` reads "A depends on B".2122```mermaid23graph TD24    subgraph Targets25        APP["ORIXSecure (app)<br/>App/Sources: Core, Features, Platform, Debug"]26        EXT["ORIXSecureShare (share extension)<br/>ShareExtension/Sources"]27        UIT["ORIXSecureUITests"]28    end29    subgraph Packages30        MODEL["ORIXSecureModel<br/>Reading, Finding, ReportDocument, L()"]31        ENG["ORIXSecureEngines<br/>probes, assessment, checklist, privacy,<br/>storage, diagnostics, investigations"]32        URL["ORIXURLRisk<br/>URL parser, risk analyzer, QR classifier"]33        FILE["ORIXFileInspection<br/>file inspector, duplicates, large files, remover"]34        NET["ORIXNetworkLab<br/>path, interfaces, DNS, TCP, TLS, HTTPS, Bonjour, Wi-Fi"]35        MEDIA["ORIXMediaCleanup<br/>fingerprints, analyzer, plan, Photos adaptors"]36        REP["ORIXReporting<br/>PDF / Markdown / JSON / text, redaction"]37        WF["ORIXWorkflow<br/>(second target of the ORIXReporting package)"]38        DES["ORIXDesign<br/>tokens, components, haptics"]39    end40    ENG --> MODEL41    URL --> MODEL42    FILE --> MODEL43    NET --> MODEL44    MEDIA --> MODEL45    REP --> MODEL46    WF --> MODEL47    APP --> ENG48    APP --> URL49    APP --> FILE50    APP --> NET51    APP --> MEDIA52    APP --> REP53    APP --> WF54    APP --> DES55    APP --> MODEL56    APP -. embeds .-> EXT57    EXT --> URL58    EXT --> DES59    EXT --> MODEL60    UIT -. tests .-> APP61```6263Facts taken from the `Package.swift` files and `project.yml`:6465- Every engine package depends on `ORIXSecureModel` only. No engine package depends on another engine package.66- `ORIXDesign` depends on nothing and is the only package that imports SwiftUI.67- All packages declare `platforms: [.iOS(.v18), .macOS(.v15)]` and `swiftLanguageModes: [.v6]`, so the package68  tests run on a Mac with `swift test`.69- `ORIXReporting` (renderers) and `ORIXWorkflow` (workflow runner) are two independent targets of one package;70  neither imports the other.71- The share extension links `ORIXDesign`, `ORIXSecureModel` and `ORIXURLRisk` only.7273### Rule: diagnostics never import SwiftUI7475No file under `Packages/*/Sources` other than `ORIXDesign` imports SwiftUI. Engines return value types76(`Finding`, `Reading`, reports); views live in `App/Sources/Features`. Two engine files import UIKit behind77`#if canImport(UIKit)`, because the data they read exists only there:7879| File | UIKit use |80|---|---|81| `ORIXSecureEngines/SystemDeviceProbe.swift` | `UIDevice` (model, system name, idiom, battery), `UIScreen` via the first `UIWindowScene` |82| `ORIXMediaCleanup/PhotoLibraryScanner.swift` | `UIImage.cgImage` of the thumbnail returned by `PHImageManager` (AppKit on macOS) |8384## 2. Result vocabulary (`ORIXSecureModel`)8586| Type | Role |87|---|---|88| `Reading<Value>` | `.measured(Value)` or `.unavailable(Unavailability)`. `Unavailability.Kind`: `notExposedByiOS`, `permissionRequired`, `entitlementRequired`, `unsupportedOnDevice`, `simulator`, `failed`, `notRequested`, plus a localized `detail`. |89| `Finding` | One assessed item: `id`, `category`, `title`, `state`, `severity`, `confidence`, `verification`, `evidence`, `explanation`, `recommendation`, `notInspected`, `assessedAt`. |90| `AssessmentState` | `verified`, `attention`, `userConfirmed`, `userConfirmationRequired`, `notAvailable`, `notAssessed`. There is no "secure" or "safe" case. |91| `Severity` | `none` < `low` < `moderate` < `high` (`Comparable`). |92| `Confidence` | `measured`, `heuristic`, `userReported`, `none`. |93| `VerificationMethod` | `publicAPI`, `parsedData`, `heuristic`, `userConfirmed`, `notVerifiable`. |94| `Evidence` | `label`, `value`, optional technical `source` (an API name, `"user"`, `"URL parsing"`); the source is not localized. |95| `FindingCategory` | `device`, `authentication`, `appIntegrity`, `network`, `privacy`, `storage`, `url`, `file`, `account`, `configuration`, `performance`. |96| `ReportDocument` | Format-neutral report: `kind`, `title`, `summary`, `sections` (paragraphs, facts, findings, bullets), `unavailable`, `generator`. |9798Why `Reading` exists: iOS withholds many values (battery cycles, other apps' data, Wi-Fi details without99permission). A field that can be missing is typed `Reading<T>`, so an engine cannot return a default in place100of a value it did not obtain; the reason travels with the absence and is shown to the user. Engines turn an101`.unavailable` reading into a `notAvailable` finding whose explanation is the `detail`102(`SecurityAssessmentEngine.passcodeFinding` is the pattern).103104`userConfirmed` is distinct from `verified`: it is produced only by `SecurityChecklistEngine` for a setting105the app cannot read and the user reported as being in the expected condition, with106`confidence: .userReported` and `verification: .userConfirmed`.107108Helpers on `Sequence<Finding>`: `prioritized()` (attention first, then awaiting confirmation, then the rest;109by descending severity, then title), `count(_:)`, `highestSeverity` (over `attention` findings only).110111## 3. Localization flow1121131. Engines write English source text through `L(_ key: String.LocalizationValue)` in114   `ORIXSecureModel/Localization.swift`; interpolations become format arguments.1152. `L` resolves the key with `String(localized:bundle:)` against `ORIXLocalization.bundle`116   (and `ORIXLocalization.locale` when set). Both are `nonisolated(unsafe)` statics.1173. `ORIXSecureApp.init` sets `ORIXLocalization.bundle = .main` before any engine runs; the app's string118   catalog is `App/Resources/Localizable.xcstrings`. The share extension also sets `.main`, which there is119   the extension bundle; `project.yml` adds the same `Localizable.xcstrings` to the extension target's120   sources so engine text is translated there too. `InfoPlist.xcstrings` files localize the Info.plist strings.1214. In package tests no catalog is loaded and `L` returns the English source text.1225. `Scripts/localize.py` is written to refresh the catalog from the compiler's extracted strings and merge123   French (Canada) translations from `Scripts/translations-fr.json`.124125State of the resources: the catalog's source language is `en`; it holds 2111 keys, of which 2103 are126translated to `fr-CA` and 8 are marked not translatable. `Scripts/translations-fr.json` holds the 2103127translations. The Xcode project's known regions are `Base`, `en` and `fr-CA`. `Scripts/localize.py` exits128with code 1 when a translatable key lacks a French translation.129130View text uses SwiftUI `LocalizedStringKey` / `String(localized:)` directly; technical evidence sources and131brand names (`"Face ID"`, `"App Attest"`) are not localized.132133## 4. Persistence134135### SwiftData (`App/Sources/Core/LocalStore.swift`)136137| Model | Unique key | Fields | Content |138|---|---|---|---|139| `StoredReport` | `id: UUID` | `kindRaw`, `createdAt`, `title`, `summary`, `attentionCount`, `payload` (`@Attribute(.externalStorage)`) | The `ReportDocument`, JSON-encoded with ISO 8601 dates. |140| `StoredAnswer` | `itemID: String` | `answerRaw`, `answeredAt` | One checklist answer per item; `setAnswer` deletes the previous row. |141| `StoredWorkflow` | `id: String` | `name`, `createdAt`, `payload` | A user workflow definition, JSON-encoded. |142143`LocalStore` owns one `ModelContainer` and one `ModelContext`, keeps a `revision` counter that observing144views read, and saves with `try? context.save()` after every mutation. If the on-disk store cannot be opened,145`ORIXSecureApp.init` falls back to an in-memory store so the diagnostics stay usable. UI tests146(`-ORIXUITest YES`) always use the in-memory configuration and a separate `UserDefaults` suite.147148### Folders (`AppFolders`)149150| Folder | Location | Use |151|---|---|---|152| `database` | `Application Support/ORIXSecure/Database` | `ORIXSecure.store` (SwiftData). |153| `caches` | `Caches/ORIXSecure` | `orix-media-fingerprints.cache` (photo fingerprint cache). |154| `exports` | `tmp/ORIXSecureExports` | Files rendered for the share sheet. |155| `temporary` | `tmp/ORIXSecureWork` | Working files. |156157Saved reports have no folder of their own: they are rows of the SwiftData store.158159File protection: `AppFolders.prepare()` (exports, temporary, caches) and `LocalStore.init` (database) create160these directories with the attribute161`.protectionKey: FileProtectionType.complete`. The code sets the attribute on the directories; it does not set162a protection option on each file write (`ReportGenerator.export` writes with `.withoutOverwriting` only) and163the entitlements file declares no data-protection entitlement. The protection class effectively applied to a164new file in the container is measured at run time by `SystemSecurityProbe.fileProtection` and reported as the165`app.dataProtection` finding (not available in the Simulator).166167### UserDefaults (`AppSettings`)168169`appLockEnabled` (default off), `keepLinkHistory` (default off), `redactExports` (default on), `appearance`,170`hasSeenWelcome`.171172## 5. Concurrency model173174- App and extension targets set `SWIFT_DEFAULT_ACTOR_ISOLATION: MainActor`. `AppModel`, `LocalStore`,175  `Router`, `AppLock`, `AppSettings`, `NetworkController`, `PhotoCleanupController` are `@Observable`176  classes isolated to the main actor by that default.177- Packages have no default isolation. Engines are `Sendable` structs or caseless enums. Pure evaluators178  (`SecurityAssessmentEngine.assess`, `DeviceDiagnosticsEngine`, `URLRiskAnalyzer.analyze`,179  `NetworkAssessment.findings`, `TLSAssessment.findings`) are synchronous; I/O is `async`180  (`DNSProbe.resolve`, `LatencyProbe.measure`, `TLSInspector.inspect`, `HTTPSProbe.head`,181  `CleanupPipeline.run`, `FileInspector.inspect`, `DuplicateFinder.findDuplicates`).182- `DeviceProbing.snapshot()` is the one engine entry point marked `@MainActor` (it touches UIKit).183- Actors: `PhotoLibraryScanner`, `WorkflowRunner`, `WorkflowContext`.184- Lock-protected `@unchecked Sendable` classes bridge callback APIs: `ConnectivityMonitor`, `OneShot`185  (resume-once continuation), `PendingRequest` (Photos requests), the Bonjour `BrowseSession`.186- Opt-outs in the app target: `nonisolated enum ReportBuilder`, `nonisolated static QRImageReader.payloads`,187  `nonisolated` `CLLocationManagerDelegate` callback that hops back with `Task { @MainActor in … }`.188- Engine progress callbacks are `@Sendable`; views re-enter the main actor with `Task { @MainActor in … }`.189- Cancellation: long operations check `Task.isCancelled` / `Task.checkCancellation()`; a cancelled photo scan190  saves the fingerprint cache before throwing.191192## 6. Navigation193194`Router.swift` defines one `Destination` enum (16 cases: `dashboard`, `securityAudit`, `checklist`, `privacy`,195`investigations`, `storage`, `photoCleanup`, `fileCleanup`, `linkAnalyzer`, `fileScanner`, `network`,196`device`, `battery`, `reports`, `actions`, `settings`) and `DestinationView` maps each case to its screen.197198| Layout | Condition in `RootView` | Structure |199|---|---|---|200| `TabLayout` | `horizontalSizeClass != .regular` (iPhone, and iPad in a compact width) | `TabView` over `AppTab` (`overview`, `security`, `storage`, `tools`, `reports`), one `NavigationStack` per tab bound to `Router.paths[tab]`. The Tools tab root is `ToolsHubView`, which is not a `Destination`. |201| `SidebarLayout` | `horizontalSizeClass == .regular` | `NavigationSplitView`; sidebar list grouped as Security / Storage / Tools / Results, selection `Router.sidebar`, detail stack `Router.sidebarPath`. |202203`Router.open(_:)` updates both layouts at once (sidebar selection, tab, tab path). `Router.push(_:)` appends204a `Route` (`.destination`, `.investigation(Symptom)`, `.report(UUID)`) to both stacks. Incoming items are205parked in `pendingLink`, `pendingFile`, `pendingFolder` and consumed by the target screen:206207- `orixsecure://analyze?url=<link>` opens the link analyser (`ORIXSecureApp.handle` checks the scheme208  `orixsecure`, the host `analyze` and the `url` query item; anything else is ignored);209- a file URL (document type `public.data`, role Viewer, `LSSupportsOpeningDocumentsInPlace` false) opens the210  file scanner.211212## 7. Local data architecture213214```mermaid215graph LR216    subgraph Device["On the device"]217        subgraph Container["App container"]218            DB[("SwiftData store<br/>StoredReport, StoredAnswer, StoredWorkflow<br/>Application Support/ORIXSecure/Database")]219            UD[("UserDefaults<br/>5 preference keys")]220            CACHE[("Caches/ORIXSecure<br/>fingerprint cache: hashes, no images")]221            TMP[("tmp/ORIXSecureExports<br/>rendered export files")]222        end223        MEM["In memory only<br/>device snapshot, security signals,<br/>network change log (200 entries),<br/>probe results, cleanup analysis"]224        PHOTOS[("Photo library<br/>read through PhotoKit")]225        FILES[("Files the user picks<br/>security-scoped URLs")]226    end227    SHEET["System share sheet<br/>UIActivityViewController"]228    HOSTS["Hosts the user typed<br/>DNS, TCP, TLS, HEAD"]229    LAN["Local network<br/>Bonjour browse"]230231    MEM -->|"Save as report"| DB232    PHOTOS -->|"thumbnails, never stored"| MEM233    PHOTOS -->|"fingerprints"| CACHE234    FILES -->|"bytes read, not copied"| MEM235    DB -->|"export, optionally redacted"| TMP236    TMP -->|"user action only"| SHEET237    MEM -.->|"probe packets, no user data"| HOSTS238    MEM -.->|"mDNS queries"| LAN239```240241- Stored: reports the user saved (or that a workflow, a file cleanup or the link history setting saved),242  checklist answers, workflows, preferences, photo fingerprints.243- Never stored: photo pixels, file contents, the device name or serial number (`ReportBuilder.deviceFacts`244  writes the model identifier and system version only), the user's location.245- Leaves the device only through the share sheet: an exported report file (`ReportsView.export` →246  `ActivityView`). There is no other upload path in the code.247- Network traffic the app originates is limited to the probes described in [network.md](network.md); they248  carry no user data beyond the host name being tested.249250## 8. Verification status251252- This document was written from a reading of the sources listed above; the test suites were not re-run for it.253- Package test targets exist for every package except `ORIXDesign`; `UITests/ORIXSecureUITests.swift` drives254  the app in the Simulator.255- Data Protection, App Attest, battery readings, the Wi-Fi reading and the integrity checks return256  `.unavailable(.simulator, …)` or are skipped in the Simulator, so the corresponding paths have not been257  exercised on hardware. Photos, camera and Wi-Fi features were run in the Simulator or compiled only.258- The French (Canada) catalog is complete by key count (section 3); its rendering in the running app was259  not checked here.260
Files main
Menu

Theme