# CLI & App Store Audit

The `iosparkle` command-line tool turns the publishing workflow into four commands:

| Command | Purpose |
| --- | --- |
| [`next-build`](#iosparkle-next-build) | Read the Channel and print the next build number. |
| [`publish`](#iosparkle-publish) | Validate an IPA and write or upload the four Channel files. |
| [`verify`](#iosparkle-verify) | Check a published Channel end to end. |
| [`audit-appstore`](#iosparkle-audit-appstore) | Prove an App Store archive contains no iOSparkle residue. |

It is a standalone Swift package in `cli/`, built only on macOS system frameworks, with no third-party dependencies.

## Install

Release builds of this repository publish a signed and notarized universal binary (`iosparkle-macos-universal.tar.gz`, with a `SHA256SUMS` file) on GitHub Releases. From a source checkout, build it yourself; it needs Swift 6 and macOS 13 or later.

```sh
swift build -c release --package-path cli
alias iosparkle="$PWD/cli/.build/release/iosparkle"
```

`swift run --package-path cli iosparkle --help` works too, without a separate build step.

## Conventions

- **Usage** is `iosparkle <command> [options]`. `iosparkle --help` lists the commands, `iosparkle <command> --help` prints the exact usage line, and `iosparkle --version` prints the tool's version.
- **Options** take a value as `--option value` or `--option=value`. `--header` and `--ssh-option` may be repeated; any other option may be given once. `--notes` always takes the next argument as literal text, even when it starts with `-`.
- **`--json`** prints a machine-readable result on standard output. On failure, the JSON error object goes to standard output and a human-readable line to standard error.
- **Exit codes.** `0` on success, `64` for a usage error, `1` for every other failure. On failure nothing is written to the Channel and no success output is printed, so a script can trust the exit code alone.
- **Fail closed.** A Channel that cannot be read, a Feed that is invalid, a package that cannot be installed over the air: each is an error, never a default.
- **`--channel-url`** is absolute. `publish` requires `https`; `next-build` and `verify` also accept `http`, so a local test host can be checked. A trailing slash is added if missing. A URL with a user name or password is rejected.
- **`--header "Key: Value"`** adds a request header. Repeatable. Headers are sent with the `feed.json` request only, which mirrors what the Host App can do.
- **`--timeout <seconds>`** is the per-request timeout, `10` by default.
- **Redirects are never followed.** A `3xx` is reported as an error, so a login page is never mistaken for a missing Feed.

## `iosparkle next-build`

```text
Usage: iosparkle next-build --channel-url <url> [--header "Key: Value"]... [--timeout <seconds>] [--json]
```

Reads the Channel's `feed.json` without any cache and prints the build number to use for the next build. It is how a CI job gets a monotonically increasing `CFBundleVersion` without storing state anywhere else.

| `feed.json` response | Printed | Exit code |
| --- | --- | --- |
| `200` with a valid Feed | the Feed's `build` plus one | `0` |
| `404` — the Channel does not exist yet | `1` | `0` |
| Anything else: `401`, `403`, `5xx`, a redirect, a timeout, an invalid Feed, or a Feed written for a newer schema | nothing; an error on standard error | non-zero |

Only a direct `404` counts as a new Channel. Every other unexpected outcome fails the command, so a credentials problem or an outage can never quietly reset your build numbers.

```sh
BUILD=$(iosparkle next-build --channel-url https://ota.example.com/my-app-dev --header "Authorization: Bearer $FEED_TOKEN")
```

With `--json`:

```json
{"channelURL":"https://ota.example.com/my-app-dev/","currentBuild":118,"nextBuild":119,"status":"ok"}
```

## `iosparkle publish`

```text
Usage: iosparkle publish --ipa <path> --channel-url <url> (--out <dir> | --ssh <[user@]host:/remote/dir>)
       [--ipa-url <url>] [--manifest-url <url>] [--commit <sha>] [--notes <text> | --notes-file <path>]
       [--keep-builds <N>] [--ssh-port <port>] [--ssh-option <opt>]... [--force] [--json]
```

Takes a device-signed IPA and produces a complete Channel directory: `app-<build>.ipa`, `manifest.plist`, `feed.json`, and `index.html`.

```sh
iosparkle publish --ipa build/MyAppDev.ipa --channel-url https://ota.example.com/my-app-dev \
  --out ./channel --commit "$GIT_COMMIT" --notes-file notes.txt
```

```text
Published com.example.myapp.dev 1.4.0 (118) to /path/to/channel
```

### What it checks before writing anything

Every check happens on your Mac, on a private copy of the IPA. The destination is only ever a place to put files.

**The IPA**

- It is a regular file and a ZIP archive with exactly one app directory, `Payload/<Name>.app`.
- `Info.plist` has a non-empty `CFBundleIdentifier` and `CFBundleShortVersionString`, and a `CFBundleVersion` that is a positive integer.
- `embedded.mobileprovision` is present and can be decoded, and its profile permits over-the-air installation: it lists devices (`ProvisionedDevices`), or `ProvisionsAllDevices` is true, or `get-task-allow` is true. An App Store export has none of these and is refused with:

  ```text
  An App Store Distribution profile cannot be installed over itms-services://. Sign the IPA with Development or Ad Hoc provisioning.
  ```

**The existing Channel**, unless `--force` is given

- If a `feed.json` is already there, it must be valid, its `bundleId` must equal the IPA's, and the IPA's build must be strictly greater than its `build`:

  ```text
  IPA build 119 must be greater than Channel build 119. Use --force to override.
  ```

  `--force` overrides all three checks at once. Use it to republish a corrected build or to move a Channel to a different bundle identifier — never to skip signing.

### What it writes

- `app-<build>.ipa`: the IPA byte for byte, as a world-readable copy (mode `0644`) even if your archive was owner-only.
- `manifest.plist` and `feed.json`: built from the IPA's `Info.plist`. `version`, `build`, `bundleId`, and `minimumOSVersion` come from `CFBundleShortVersionString`, `CFBundleVersion`, `CFBundleIdentifier`, and `MinimumOSVersion`. `sizeBytes` and `sha256` are computed from the same copy. `publishedAt` is the current UTC time.
- `index.html`: a self-contained install page in light and dark mode, with the title, bundle identifier, version and build, size, publication time, release notes, an inline SVG QR code of the Channel URL, and the install link. The title is `CFBundleDisplayName`, or else `CFBundleName`, or else the bundle identifier.

Then the previous packages are pruned to the number you asked to keep, and unrelated files in the directory are left alone.

### Options

| Option | Meaning |
| --- | --- |
| `--ipa <path>` | The IPA to publish. Required. |
| `--channel-url <url>` | The Channel's HTTPS URL; written into the Feed and the install page. Required. |
| `--out <dir>` | Write the Channel into a local directory. |
| `--ssh <[user@]host:/remote/dir>` | Upload the Channel to a remote directory over SSH. Exactly one of `--out` and `--ssh`. |
| `--ipa-url <url>` | Absolute HTTPS URL to use for the package in `manifest.plist`, instead of `<channel URL>/app-<build>.ipa`. For a package on a CDN or in a bucket. |
| `--manifest-url <url>` | Absolute HTTPS URL written as the Feed's `manifestURL`, instead of `manifest.plist` in the Channel directory. For a manifest served by a gate in front of the Channel. |
| `--commit <sha>` | Written to the Feed as `commit`. |
| `--notes <text>` or `--notes-file <path>` | Written to the Feed as `releaseNotes`, as plain text. Exactly one of the two. |
| `--keep-builds <N>` | How many packages to keep, including the new one. Default `2`. A positive integer. |
| `--ssh-port <port>` | SSH port for `--ssh`. `1` to `65535`. |
| `--ssh-option <opt>` | Extra `ssh` option, passed as `-o`. Repeatable; only with `--ssh`. |
| `--force` | Skip the checks against the existing Channel. |
| `--json` | Print the result as JSON. |

With `--json`:

```json
{"build":118,"bundleId":"com.example.myapp.dev","channelURL":"https://ota.example.com/my-app-dev/","destination":"/path/to/channel","sha256":"…","sizeBytes":2222,"status":"ok","version":"1.4.0"}
```

### Atomic publication, with no software on the destination

Whichever destination you choose, a reader never sees a half-published Channel, and a failed publish leaves the previous one intact.

**`--out`** builds the new directory beside the target and swaps it in with a single atomic rename. Packages to retain are hard-linked, so they cost nothing twice. A lock directory next to the target prevents two publishes from interleaving.

**`--ssh`** uses the system `ssh` and `scp` in batch mode, so it needs key authentication and never prompts. It uploads the four files into a staging directory on the same filesystem as the target, hard-links the packages to retain (copying if the filesystem refuses), and switches the Channel path to the new release directory with `mv`. From then on the Channel path is a symbolic link to the current release directory, which web roots follow by default. If anything fails before the switch, the staging directory is removed and the Channel stays as it was. The remote host needs nothing but a POSIX shell: no Python, no `plutil`, no script to keep in step with your local version.

```sh
iosparkle publish --ipa build/MyAppDev.ipa --channel-url https://ota.example.com/my-app-dev \
  --ssh deploy@ota.example.com:/var/www/ota/my-app-dev
```

## `iosparkle verify`

```text
Usage: iosparkle verify --channel-url <url> [--ipa <local.ipa>] [--header "Key: Value"]... [--timeout <seconds>] [--json]
```

Fetches a published Channel exactly the way the Host App and the system installer will, and checks that every piece agrees with every other.

```sh
iosparkle verify --channel-url https://ota.example.com/my-app-dev --ipa build/MyAppDev.ipa
```

```text
Verified com.example.myapp.dev 1.4.0 (118), 2222 bytes, SHA-256 db4929592b16fb031d1f5261902a741611fd18d995fdc75dc5d85d85da3eb530
```

In order:

1. **Feed.** `GET feed.json`, with your `--header` values. Must answer `200` with a valid Feed.
2. **Manifest.** `GET` the manifest URL — the Feed's `manifestURL`, or `manifest.plist` in the Channel. It must be an XML property list whose `bundle-identifier` equals the Feed's `bundleId`, whose `bundle-version` is the Feed's `version` or its `build`, and that has one `software-package` asset with an absolute HTTPS URL.
3. **Package.** One streamed `GET`, with `Accept-Encoding: identity`. The response must be `200` with a positive `Content-Length` equal to the Feed's `sizeBytes` when present; the number of bytes received must equal `Content-Length`; and the SHA-256 computed while streaming must equal the Feed's `sha256` when present.
4. **Local IPA**, with `--ipa`. The local file's size and SHA-256 must equal those of the download.

The package is fetched with `GET` and never `HEAD`. A SigV4 presigned URL is signed for one method, and `HEAD` against a `GET`-presigned URL answers `403`; a plain `GET` works for static and presigned packages alike. This is also why `verify` is safe to run against a Channel with a dynamic presigner.

With `--json`:

```json
{"bundleId":"com.example.myapp.dev","build":118,"channelURL":"https://ota.example.com/my-app-dev/","sha256":"…","sizeBytes":2222,"status":"ok","version":"1.4.0"}
```

`verify` does not check MIME types or cache headers. [Self-Hosting & Private Channels](self-hosting.md) has the three `curl` commands for those.

## `iosparkle audit-appstore`

```text
Usage: iosparkle audit-appstore <archive-or-ipa-path> [--json]
       iosparkle audit-appstore --path <path> [--json]

Accepts an .xcarchive, .ipa, or .app. Use -- before a positional path starting with '-'.
```

The **App Store Audit** proves that the artifact you are about to submit contains no self-update code and no metadata that could reveal it. It runs five checks against the `.app` bundle inside the artifact, and exits `0` only when none of them fails.

```text
App Store Audit passed — /path/to/build/MyApp.xcarchive
✓ Bundle tree [pass]
✓ Info.plist hygiene [pass]
✓ Mach-O raw bytes [pass]
✓ dSYM symbols [pass]
✓ Provisioning profiles [pass]
```

A failure prints each finding under its check, with the path inside the artifact:

```text
App Store Audit failed — /path/to/build/MyAppDev.xcarchive
✓ Bundle tree [pass]
✓ Info.plist hygiene [pass]
✗ Mach-O raw bytes [fail]
  MyAppDev: Found 34 raw byte match(es) for iosparkle. Remove the OTA code or strings and rebuild.
  MyAppDev: Found 1 raw byte match(es) for itms-services. Remove the OTA code or strings and rebuild.
  MyAppDev: Found 1 raw byte match(es) for download-manifest. Remove the OTA code or strings and rebuild.
✗ dSYM symbols [fail]
  dSYMs/MyAppDev.app.dSYM/Contents/Resources/DWARF/MyAppDev: Found iOSparkle symbol '…'. Remove iOSparkle from the App Store target.
✓ Provisioning profiles [pass]
```

### The five checks

1. **Bundle tree.** No entry anywhere in the `.app` directory may have `iosparkle` in its name — not a framework, a resource bundle, an app extension, or a file. The comparison ignores case, diacritics, and full-width forms, so `IoSparkle.framework` and `ｉＯＳｐａｒｋｌｅ.bundle` are caught too. Every symbolic link is examined: its destination text must not contain `iosparkle`, and it must resolve to a location strictly inside the bundle. Dangling, looping, and escaping links fail. The versioned links inside a framework (`Versions/Current`) are fine.

2. **Info.plist hygiene.** Every `Info.plist` in the bundle — the app's and each extension's, framework's, and resource bundle's — is read, binary or XML. Neither `LSApplicationQueriesSchemes` nor `CFBundleURLTypes/CFBundleURLSchemes` may declare `itms-services`, in any letter case. A missing or corrupt `Info.plist` fails rather than being skipped. iOSparkle needs no such declaration, because it opens the install URL directly instead of querying the scheme, so a clean project passes with nothing to remove.

3. **Mach-O raw bytes.** Every regular file whose header identifies it as Mach-O — thin or fat, either endianness, every slice — is read as raw bytes and searched, case-insensitively, for `iosparkle`, `itms-services`, and `download-manifest`. Each must occur zero times. Reading raw bytes is what makes the check honest: Xcode strips local symbols when archiving, so `nm` on the shipped binary reports nothing even while the `itms-services://?action=download-manifest&url=` string literal sits in the `__TEXT,__cstring` section. Files that merely share a magic number with Mach-O, such as Java class files, are recognized and skipped.

4. **dSYM symbols.** Every DWARF file in the archive's `dSYMs` directory is read with `xcrun nm -a -j -arch all` and demangled with `xcrun swift-demangle --compact`. Any symbol in the `iOSparkle.` namespace fails, whether it is found in its demangled form or in its mangled form (`9iOSparkle`). An `.xcarchive` with no dSYM bundles fails, with a reminder to set *Debug Information Format* to *DWARF with dSYM File*. For a bare `.ipa` or `.app`, companion dSYM bundles are looked for inside the artifact and beside it, by exact name, and scanned if present; when there are none the check reports an advisory and passes. That is the reason to audit the `.xcarchive` in CI: only it carries the symbols.

5. **Provisioning profiles.** Every `embedded.mobileprovision` in the bundle — the app's and each extension's — is decoded with `security cms -D`. The check fails when the profile lists devices (`ProvisionedDevices`), covers all devices (`ProvisionsAllDevices`), or allows debugging (`get-task-allow`): a Development, Ad Hoc, or In-House build was submitted for audit instead of an App Store build. An archive without a profile passes.

### Exit code and JSON

The exit code is `0` when no check failed and `1` otherwise. Each check has a status of `pass`, `fail`, or `advisory`; only `fail` affects the exit code.

With `--json`:

```json
{
  "advisories": [],
  "artifactPath": "/path/to/build/MyApp.xcarchive",
  "artifactType": "xcarchive",
  "checks": {
    "bundleTree": { "findings": [], "passed": true, "status": "pass" },
    "dsymSymbols": { "findings": [], "passed": true, "status": "pass" },
    "infoPlist": { "findings": [], "passed": true, "status": "pass" },
    "machOBytes": { "findings": [], "passed": true, "status": "pass" },
    "provisioningProfile": { "findings": [], "passed": true, "status": "pass" }
  },
  "passed": true
}
```

`artifactType` is `xcarchive`, `ipa`, or `app`. A finding is `{ "path", "message" }`, plus `marker` and `hitCount` for Mach-O byte matches. `advisories` repeats the message of every advisory finding.

### Producing an archive worth auditing

The audit can only vouch for the artifact it is given, so build that artifact adversarially: the development archive first, and the shipping archive beside it in one products directory. Xcode normally gives each archive its own products directory, which would hide the `iOSparkle.swiftmodule` the development variant left behind; with one shared directory the shipping archive compiles right beside it, where a bare `canImport` misfires. `scripts/ci-verify-audit.sh` in this repository runs exactly this gate on the example projects.

```sh
DD="$(pwd)/build/DerivedData"                  # absolute: package build steps run from the package's own directory
PRODUCTS="$DD/Build/Products/iphoneos"         # one products directory for every archive
archive() {
  xcodebuild -quiet -project MyApp.xcodeproj -scheme "$1" -configuration Release \
    -destination 'generic/platform=iOS' -derivedDataPath "$DD" -archivePath "build/$1.xcarchive" \
    CONFIGURATION_BUILD_DIR="$PRODUCTS" \
    'DWARF_DSYM_FOLDER_PATH=$(BUILD_DIR)/$(CONFIGURATION)$(EFFECTIVE_PLATFORM_NAME)' \
    CODE_SIGNING_ALLOWED=NO archive
}
rm -rf build/*.xcarchive                       # never audit a stale artifact

archive MyAppDev                               # leaves iOSparkle.swiftmodule and iOSparkle.o in $PRODUCTS
archive MyApp                                  # compiles beside them

iosparkle audit-appstore build/MyApp.xcarchive        # must exit 0
iosparkle audit-appstore build/MyAppDev.xcarchive     # positive control: must exit non-zero
```

Five rules make the result meaningful:

- **Both archives must exit `0` before anything is audited.** A failed link step leaves an incomplete bundle behind, and an audit of that leftover passes for the wrong reason.
- **Delete stale archives first**, and audit the `.xcarchive` rather than an exported `.ipa`, so the dSYM symbol check runs. The `DWARF_DSYM_FOLDER_PATH` line keeps each archive's dSYMs collectable even with the shared products directory.
- **Keep the positive control.** Auditing the development archive must fail. If it passes, the audit is blind, and a passing shipping audit proves nothing.
- **Share the products directory, with an absolute path.** `CONFIGURATION_BUILD_DIR` is what makes the gate honest: without it each archive compiles in its own directory and never sees the leftover module. The path must be absolute, because a local package's build steps run from the package's own directory and would resolve a relative path against it.
- **Audit archives, not a bare `.app`.** An archive's binary is stripped and its dSYMs are present, so all five checks run. An unstripped `.app` from a plain build still carries debug paths, and a checkout directory whose name contains `iosparkle` would trip the raw-byte check on harmless strings.

### In CI

```sh
set -eu
CHANNEL=https://ota.example.com/my-app-dev
DD="$(pwd)/build/DerivedData"                  # absolute: CONFIGURATION_BUILD_DIR below must be too
X="xcodebuild -project MyApp.xcodeproj -derivedDataPath $DD"
BUILD=$(iosparkle next-build --channel-url "$CHANNEL")

# Publish the development build.
$X -scheme MyAppDev -configuration Release archive -archivePath build/MyAppDev.xcarchive CURRENT_PROJECT_VERSION="$BUILD"
xcodebuild -archivePath build/MyAppDev.xcarchive -exportPath build/MyAppDev \
  -exportOptionsPlist ExportOptions-development.plist exportArchive
iosparkle publish --ipa build/MyAppDev/MyAppDev.ipa --channel-url "$CHANNEL" \
  --out ./channel --commit "$GITHUB_SHA" --notes-file notes.txt
# upload ./channel/* to the Channel, then:
iosparkle verify --channel-url "$CHANNEL" --ipa build/MyAppDev/MyAppDev.ipa

# Gate the App Store build: both archives in one products directory, development first.
PRODUCTS="$DD/Build/Products/iphoneos"
archive() {
  xcodebuild -quiet -project MyApp.xcodeproj -scheme "$1" -configuration Release -derivedDataPath "$DD" \
    -destination 'generic/platform=iOS' -archivePath "build/$2.xcarchive" CONFIGURATION_BUILD_DIR="$PRODUCTS" \
    'DWARF_DSYM_FOLDER_PATH=$(BUILD_DIR)/$(CONFIGURATION)$(EFFECTIVE_PLATFORM_NAME)' CODE_SIGNING_ALLOWED=NO archive
}
rm -rf build/MyApp.xcarchive build/MyAppDev-gate.xcarchive
archive MyAppDev MyAppDev-gate
archive MyApp MyApp
iosparkle audit-appstore build/MyApp.xcarchive                              # must exit 0
iosparkle audit-appstore build/MyAppDev-gate.xcarchive && exit 1 || true    # positive control: must fail
```

The two directions of the check belong together and run on every pull request: the shipping archive must pass, and the development archive must fail. `scripts/ci-verify-audit.sh` does this for the two example projects in `Examples/`.
