Repository Public
1<!--2ORIX Cosmos3File: Documentation/modules/CosmosDataPacks.md4Description: Data-pack manager: manifest schema v1, pack index, .orixpack archive format, store layout and precedence, atomic install and recovery, download, signatures, threat model with the mitigations actually tested, tooling and limitations.5Author: Simon-Pierre Boucher6Contact: contact@spboucher.ai7-->8# CosmosDataPacks910Manifests, integrity, storage, download and installation of data packs. Depends on `CosmosCore` and Apple11frameworks only (Foundation, CryptoKit, Compression). Nothing is ever downloaded on the module's own12initiative: the only network calls are `PackManager.refreshIndex()` and `PackManager.install(_:)`, both13explicit, and the index URL defaults to *none*.1415| File | Content |16|---|---|17| `PackManifest.swift` | `PackManifest` (schema v1), `SemanticVersion`, `LocalizedText`, `PackKind`, `Redistribution`, `PackFile`, `PackSource`, `PackDependency`, `PackSignatureInfo`, `PackPath` |18| `PackIndex.swift` | `PackIndex`, `PackIndexEntry`, `PackIndexLoader`, `PackURLPolicy` |19| `PackArchive.swift`, `PackExtractor.swift` | ustar reader/writer, bounded streaming gunzip, validating extraction and directory import |20| `PackStore.swift` | `PackStore` actor, configuration, quotas, inventory, usage, verification, install/upgrade, recovery, removal, export |21| `PackDownloader.swift` | `PackDownloader`, `PackDownloadRequest`, `PackDownloadPolicy`, `PackDownloadControl` |22| `PackSignature.swift` | `PackSignature`, `TrustedPackKey`, `PackSignatureState` |23| `PackManager.swift` | `PackManager` actor and `PackOffer`: the facade for the pack manager screen |24| `PackHash.swift`, `JSONValue.swift`, `PackError.swift` | streaming SHA-256, loss-free JSON tree, error type |2526## 1. Manifest schema version 1 (`manifest.json`)2728JSON Schema: `DataPipeline/packs/schema/pack-manifest.v1.schema.json` (a test checks that its keys are those29of the Swift model). The writer emits sorted keys, 2-space indentation, a trailing newline.3031| Key | Type | Req. | Meaning |32|---|---|---|---|33| `schemaVersion` | integer | yes | Must be `1`. Any other value is refused with `unsupportedSchemaVersion` (not "invalid"). |34| `id` | string | yes | `[a-z0-9][a-z0-9._-]{0,63}`; also the directory name of the installed pack. |35| `version` | string | yes | Semantic version 2.0.0 (`major.minor.patch[-pre][+build]`). |36| `kind` | string | yes | `ephemeris`, `catalogue`, `textures`, `sky-imagery`, `missions`, `satellites`, `time`, `other`. |37| `title` | object | yes | `{"en": …, "fr": …}`; `en` mandatory. |38| `description` | object | no | Same shape as `title`. |39| `installedSize` | integer | yes | Bytes; must equal the sum of `files[].size`. |40| `downloadSize` | integer | no | Archive size when the builder knows it. The pack index is authoritative. |41| `files` | array | yes | `path` (relative, `/`-separated), `size` (bytes), `sha256` (64 lower-case hex); optional `role`, `description`, `source` (id of a `sources[]` entry), `url` (upstream URL of that file). Other keys are preserved. |42| `sources` | array | no | `id`, `name`, `version`, `license` required; `url`, `retrieved` (ISO date), `citation`, `method` optional. Maps one-to-one onto `CosmosCore.Provenance` (`PackManifest.provenance`). No other key allowed. |43| `license` | string | no | Licence summary of the pack as a whole. |44| `coverage` | any JSON | no | Free-form structured coverage (time span, magnitude limit, object counts…). |45| `redistribution` | string | yes | `redistributable` or `localBuildOnly`. Only the former can be exported or listed in an index. |46| `dependencies` | array | no | `{ "id", "minimumVersion"? }`. |47| `minimumAppVersion` | string | no | Semantic version of the oldest application able to read the pack. |48| `signature` | object | no | `{ "algorithm": "ed25519", "keyID": …, "file": "manifest.sig" }` — announces the detached signature. |49| *anything else* | any | no | Extension keys (domain data such as `missions`, `file_format`) are kept verbatim in `PackManifest.extensions`. |5051**Path rules** (`PackPath.validate`, applied to the manifest, to archive entries and to directory imports):52not empty, ≤ 1024 bytes, components ≤ 255 bytes, no leading `/` or `~`, no `.`/`..`/empty component, no53backslash, no NUL or control character (C0, DEL, C1), no line separator or bidirectional control, no54component ending in a space or a dot, first component not starting with a dot (reserved for the store),55not `manifest.json`/`manifest.sig` in any letter case. Two paths may not be equal, differ only by case or56Unicode normalisation, or use one name both as a file and as a directory (`PackPath.checkCollisions`).5758**Legacy aliases accepted on read, never written:** `format` → `schemaVersion`, `licence` → `license`,59`total_bytes` → `installedSize`, `title` as a plain string → `title.en`; in `files[]`: `name` → `path`,60`bytes` → `size`, `provenance_id` → `source`; in `sources[]`: `licence` → `license`.6162## 2. Pack index (`PackIndex`, schema version 1)6364JSON Schema: `DataPipeline/packs/schema/pack-index.v1.schema.json`. `{ "schemaVersion": 1, "generated"?, "packs": [entry] }`65where an entry has `id`, `version`, `kind`, `title`, `description`?, `installedSize`, `archiveSize`, `license`,66`coverage`?, `redistribution`, `archiveURL` (absolute, or relative to the index), `archiveSHA256`,67`minimumAppVersion`?, `dependencies`, `signatureKeyID`?. Loaded from a `file:` URL or over HTTPS68(`PackIndexLoader`); the location is `PackManagerConfiguration.indexURL`, nil by default.69`PackManager.offers()` joins the index with the store: sizes, licence, version, coverage, free space,70remaining download bytes and the list of blockers (quota, disk, application version, missing dependencies)71are all available before a single byte of an archive is requested.7273## 3. Archive format (`.orixpack`)7475A POSIX **ustar** stream, optionally wrapped in **gzip** (detected by magic number):76771. `manifest.json` — always the first entry;782. `manifest.sig` — optional, second;793. the payload files, each exactly once, any order (the tools write manifest order);804. two zero blocks, then at most 1 MiB of zero padding.8182Why ustar: it is a sequence of 512-byte headers each followed by its data, so it is read strictly forward in831 MiB chunks without ever holding a pack in memory; with the manifest first, every entry is checked *before*84its first byte is written; the standard `tar`/`tarfile` tools can inspect an archive; and the Python standard85library can produce it, which keeps the pipeline free of dependencies. Packs are mostly incompressible86(JPEG/PNG textures, Chebyshev coefficients), so compression is optional: gzip is read through the system87`Compression` framework (`compression_stream`, raw DEFLATE) with two fixed 64 KiB buffers.88The writers are deterministic (mode 0644, uid/gid 0, mtime 0): `PackStore.exportArchive` and89`packtool.py build` give byte-identical archives for the same pack (tested).9091Restrictions: regular files only; no pax or GNU extensions (paths ≤ 100 bytes, or ≤ 255 with a `/` split92that fits the ustar prefix field); one file ≤ 8 GiB − 1; the gzip CRC-32 trailer is not checked (integrity93rests on the SHA-256 of the archive and of every file).9495## 4. Store9697```98<bundle>/Contents/Resources/Packs/<id>/… starter packs, read-only (PackStoreConfiguration.bundledRoot)99<Application Support>/<app>/Packs/<id>/… user packs (PackStoreConfiguration.userRoot)100 .staging/<uuid>/ extraction in progress101 .journal/<id>.json installation in flight102 .previous/<id>/ previous version (move-aside strategy only)103 .downloads/ partial and completed archives (*.part, *.part.json)104```105106Both roots are injected. `PackStoreConfiguration.defaultUserRoot(applicationDirectoryName:)` asks107`FileManager` for the user's Application Support directory (the container's one in a sandbox) and creates108nothing; no home path is hard-coded.109110**Precedence** for an id present in both places: the user copy is active when its version is ≥ the bundled111one; otherwise the bundled copy is active and the user copy is reported inactive with the suggestion112`.removeUserCopy`. `PackStore.url(forPack:file:)` resolves in the active copy, only for paths listed in the113manifest, and only to regular files.114115**Verification** (`verify`) re-hashes every listed file and walks the directory: `missing`, `modified`116(size, content, or no longer a regular file), `extra` (unlisted files, symbolic links included), signature117state, and repair suggestions (`reinstall`, `deleteExtraFiles`, `removeUserCopy`, `reinstallApplication`).118119**Quotas**: `PackQuotas(perPack:total:)` on the declared installed sizes of user packs; free space through120the injectable `PackEnvironment.freeSpace` plus `freeSpaceMargin` (256 MiB by default). All are checked after121the manifest is read and before any payload byte is written; `checkCapacity` exposes the same check to the UI.122123## 5. Atomic installation and recovery124125`staging directory (same volume) → validated extraction → journal → commit → cleanup`.126127* Commit of a first installation: one `rename(2)`.128* Commit of an upgrade: `renamex_np(RENAME_SWAP)` exchanges the staged and the installed directories in one129 step (the pack directory is never absent); when the volume refuses, the previous version is renamed to130 `.previous/<id>` and the new one renamed in — the journal covers that gap.131* The journal names the staging directory and a token file placed in the staged pack. At launch132 `PackStore.recover()` (`PackManager.start()`): token present in the live directory → the commit happened,133 leftovers are deleted; otherwise the previous version is put back if it had been moved, and the staging134 directory is deleted. Orphan staging directories are removed. The operation is idempotent.135* The previous version is not touched until the new one has passed every check.136* Files are `fsync`ed; the directory renames themselves are not followed by `F_FULLFSYNC` (see limitations).137138## 6. Download139140`PackDownloader` (URLSession with a delegate, ephemeral configuration, no cache, `Accept-Encoding: identity`):141142* HTTPS only; `http://127.0.0.1|localhost|::1` is accepted only with `allowInsecureLoopback` (tests).143 Redirects are subject to the same rule.144* Resume: partial file `<name>.part` + `<name>.part.json` (URL, ETag, Last-Modified, total). A later call145 sends `Range: bytes=N-` and `If-Range: <ETag or Last-Modified>`; `206` with the expected `Content-Range`146 appends, `200` restarts from zero (resource changed or server without range support), `416` discards the147 partial file. A partial file without validator is never resumed.148* The size limit (`maximumSize`, and the size announced by the index) is checked on the response headers149 and again on every chunk written.150* Retries: transient failures only (network errors, 408/425/429/5xx, short body), `maximumRetries` times151 with exponential backoff capped by `maximumBackoff`; each retry resumes.152* Pause/cancel: `PackDownloadControl.pause()` keeps the partial file (`PackError.paused`), `cancel()` or153 cancelling the Swift task deletes it (`PackError.cancelled`).154* The file reaches its destination only after its size and SHA-256 match the index. `PackError.offline`155 when the device has no connectivity or the host cannot be reached; nothing is installed.156157## 7. Signatures158159Ed25519 (`CryptoKit.Curve25519.Signing`) over the exact bytes of `manifest.json`; since the manifest lists160the SHA-256 of every file, the signature covers the whole pack. `manifest.sig` is161`{"algorithm": "ed25519", "keyID": …, "signature": base64}`; the default key id is the first 16 hex digits of162the SHA-256 of the raw public key. `PackSignatureState`: `trusted(keyID)`, `unsigned`, `untrustedKey(keyID)`,163`invalid(reason)`; it is recomputed at every enumeration and exposed on `InstalledPack.signature`164(`description` gives e.g. "unsigned – local/import").165166| Situation | Download (`requireTrusted`) | Local import (`allowUnsignedLocal`) |167|---|---|---|168| valid signature, trusted key | installed | installed |169| no signature | refused | installed, state `unsigned` |170| signature by an unknown key | refused | installed, state `untrustedKey` |171| signature does not verify / announced but absent / key id mismatch / unreadable | refused | refused |172173The trusted keys come from `PackStoreConfiguration.trustedKeys`; the module ships none.174175## 8. Threat model and tested mitigations176177The archive, the index, the server and an imported directory are untrusted. Each line is exercised by a test178with a hand-crafted input (`ArchiveSecurityTests`, `StoreTests`, `DownloadTests`).179180| Attack | Mitigation | Error |181|---|---|---|182| Absolute path, `..`, `.`, empty component | `PackPath.validate` on every entry before any write | `unsafePath` |183| Symbolic link, hard link, device, FIFO, directory, pax/GNU header | only regular-file entries are accepted; directory import uses `lstat` and `O_NOFOLLOW` | `unsupportedEntryType` |184| Entry not listed in the manifest | lookup in the manifest before writing | `unlistedEntry` |185| Duplicate entry, second `manifest.json`/`manifest.sig` | each listed file accepted once; files created with `O_EXCL` | `duplicateEntry` |186| Size or hash different from the manifest | header size compared before writing; SHA-256 computed while writing | `sizeMismatch`, `hashMismatch` |187| Missing file | checked at the end marker | `missingEntry` |188| Expansion bomb (in an entry, after the end marker, oversized manifest) | declared sizes bound every read; ≤ 1 MiB of trailing zeros; manifest ≤ 32 MiB | `sizeMismatch`, `malformedArchive`, `expansionLimitExceeded` |189| Size beyond quota or disk | checked on the manifest before the payload | `quotaExceeded`, `insufficientDiskSpace` |190| NUL (smuggled suffix), control characters, invalid UTF-8 in names | header fields must be NUL-padded only, valid UTF-8, no control character | `unsafePath` |191| Case / Unicode-normalisation collisions | collision key (NFD + lower case) on manifest and entries | `caseCollision`, `duplicateEntry` |192| Truncated or corrupt container, bad checksum, base-256 size, data after the end marker | strict reader | `malformedArchive` |193| Tampered or forged signature, stripped signature | see §7 | `signatureInvalid`, `signatureRequired` |194| Archive swapped on the server, wrong size, oversized, plain-HTTP redirect | SHA-256 and size from the index, streaming limit, URL policy | `archiveHashMismatch`, `sizeMismatch`, `downloadTooLarge`, `insecureURL` |195| Index entry pointing at another pack | id and version of the manifest must match the entry | `packMismatch` |196| Crash or full disk during installation | staging + journal + atomic rename; fault injection at every stage | (recovered at launch) |197198After every rejected archive the tests assert that no pack is installed, that the staging area is empty and199that no file exists outside the store.200201## 9. Tooling (`DataPipeline/packs/`)202203Python 3 standard library only, plus one Swift script because Ed25519 is not in the Python standard library.204205```206python3 DataPipeline/packs/packtool.py validate <pack dir>... # schema v1 + files on disk (hashes)207python3 DataPipeline/packs/packtool.py hash <pack dir> [--all] [--write] # recompute files[] and installedSize208python3 DataPipeline/packs/packtool.py announce-signature <pack dir> <key id>209python3 DataPipeline/packs/packtool.py build <pack dir> -o <archive> [--gzip]210python3 DataPipeline/packs/packtool.py index <archive>... -o index.json [--base-url URL] [--generated ISO]211swift DataPipeline/packs/packsign.swift keygen|public|sign|verify …212```213214`packsign.swift keygen` refuses to write a private key inside a git working tree and creates the file with215mode 0600. Order: `hash --write` → `announce-signature` → `packsign sign` → `build` → `index`. A test runs216this chain and installs the result with the library.217218## 10. Limitations219220* **No hosting exists.** The index URL is a configuration value that is nil; the download path is tested221 against a loopback server only.222* **No trusted key exists.** Until the owner generates a key pair and puts the public key in the application223 configuration, every pack is "unsigned – local/import" and nothing can be installed through the download224 path (by design). Key custody and rotation are owner decisions.225* The pipeline packs `core-ephemeris`, `missions`, `textures-starter`, `textures-hd` and `sky-imagery` were226 aligned on schema v1 at the source (their generators write it; `RepositoryPackTests` reads them through227 `PackStore` as the bundled root and verifies their integrity). All five are `localBuildOnly` for now, by a228 conservative reading of the recorded licence statements (reasons in each manifest's `redistributionNote`):229 they cannot be exported or listed in an index until the owner decides.230* Installation runs on the store actor: a multi-gigabyte install occupies it (cancellable, progress reported);231 two packs are not installed in parallel.232* Durability against power loss relies on APFS ordering: file contents are `fsync`ed, directory entries are not233 forced with `F_FULLFSYNC`. Crash injection in the tests is a simulated process death, not a power cut.234* The archive carries no per-file compression other than whole-stream gzip; no delta updates.235* `.DS_Store` files are skipped by directory import (and by the Python validator); any other unlisted file is an error.236* Quotas count declared payload sizes; `manifest.json` and file-system overhead are not counted (reported by `usage()`).237