# Self-Hosting & Private Channels

Any host that can serve four static files over HTTPS can be a Channel. This chapter covers what such a host must send, three ways to keep a Channel private with no code at all, one dynamic pattern for access you can revoke, and five setups that are guaranteed to fail.

## Why the system installer constrains private hosting

An update is not one download. It is three requests made by two different processes, and only the first of them is yours:

```text
Host App (its own HTTP client; can send headers)      GET  <channel>/feed.json
        |
        |  the user taps Update; the Host App opens
        |  itms-services://?action=download-manifest&url=<encoded manifest URL>
        v
iOS system installer (a separate process)
        GET  <manifest URL>          manifest.plist
        GET  <package URL>, with Range requests to resume   app-<build>.ipa
```

The system installer runs in its own sandbox. It sends **none** of the Host App's headers or cookies, shares no session with Safari or a web view, ignores the Host App's App Transport Security exceptions, and trusts only certificates from the system trust store. It also refuses to fetch from the device itself, so `127.0.0.1` and `localhost` never work.

So authentication can live in exactly two places: the Feed request, which the Host App makes; and the URLs themselves, which the system installer fetches bare. Everything below follows from that.

## Required response headers

| File | Status | `Content-Type` | `Cache-Control` | Also required |
| --- | --- | --- | --- | --- |
| `feed.json` | `200` | `application/json; charset=utf-8` | `no-store` | — |
| `manifest.plist` | `200` | `text/xml` | `no-store` | Serve the document directly; do not redirect. |
| `app-<build>.ipa` | `200`, or `206` for `Range` | `application/octet-stream` | `public, max-age=31536000, immutable` | Exact `Content-Length`, `Accept-Ranges: bytes`, and no transformation of the body. |
| `index.html` | `200` | `text/html; charset=utf-8` | `no-cache` | — |

Why each one matters:

- **`Cache-Control: no-store` on the Feed and the manifest.** A cached Feed hides the build you just published, and a cached manifest can point at a package that has since been removed. The Host App asks for a cacheless fetch itself, but a CDN in between does not know that.
- **`text/xml` for the manifest.** The system installer parses the manifest as an XML property list. Any other label is outside the documented contract, and a host that answers with an HTML page instead — a login page, for instance — fails outright.
- **Exact `Content-Length` and `Accept-Ranges: bytes` for the package.** The system installer shows download progress from `Content-Length` and resumes an interrupted download with a `Range` request. A host that omits the length or ignores ranges breaks both. Byte-range support means answering `Range: bytes=…` with `206 Partial Content` and a `Content-Range` header.
- **No transformation of the package.** Dynamic gzip or Brotli recompresses the body per request and removes the meaning of `Content-Length`; chunked transfer encoding removes the length altogether. Neither is compatible with resuming a download. The package filename is immutable, so caching it forever is safe and encouraged.

All four files are served over HTTPS with a certificate from a CA that iOS trusts by default, such as Let's Encrypt. TLS 1.2 or later with forward secrecy is required.

### Checking a host

`iosparkle verify` checks that the Feed, manifest, package size, and SHA-256 agree. It does not check MIME types or cache headers, so confirm those once per host:

```sh
BASE=https://ota.example.com/my-app-dev
curl -sS -o /dev/null -D - "$BASE/feed.json"            # 200 · application/json · Cache-Control: no-store
curl -sS -o /dev/null -D - "$BASE/manifest.plist"       # 200 · text/xml · Cache-Control: no-store
curl -sS -o /dev/null -D - -r 0-0 "$BASE/app-118.ipa"   # 206 · application/octet-stream · Accept-Ranges: bytes
```

The last command requests a single byte, so it also shows the full package size in `Content-Range`.

### nginx

Many static hosts do not know either extension, so map them explicitly. An empty `types { }` block makes a location ignore the global MIME table, after which `default_type` decides.

```nginx
server {
    listen 443 ssl;
    server_name ota.example.com;
    ssl_certificate     /etc/letsencrypt/live/ota.example.com/fullchain.pem;
    ssl_certificate_key /etc/letsencrypt/live/ota.example.com/privkey.pem;
    root /var/www/ota;

    location ~ \.json$  { types { } default_type application/json;         add_header Cache-Control "no-store" always; }
    location ~ \.plist$ { types { } default_type text/xml;                 add_header Cache-Control "no-store" always; }
    location ~ \.ipa$   { types { } default_type application/octet-stream; add_header Cache-Control "public, max-age=31536000, immutable" always; gzip off; }
    location ~ \.html$  { types { } default_type text/html;                add_header Cache-Control "no-cache" always; }
}
```

nginx adds `Accept-Ranges: bytes` to static files by itself and serves the file's real length, so nothing else is needed for the package. `gzip off` inside the `.ipa` location overrides a global `gzip on`.

### Caddy

```caddyfile
ota.example.com {
    root * /var/www/ota
    @plist path *.plist
    header @plist Content-Type "text/xml"
    header @plist Cache-Control "no-store"
    @feed path */feed.json
    header @feed Cache-Control "no-store"
    @ipa path *.ipa
    header @ipa Content-Type "application/octet-stream"
    header @ipa Cache-Control "public, max-age=31536000, immutable"
    file_server
}
```

### Object storage and CDNs

S3, Cloudflare R2, and CDNs in front of them satisfy the length and range requirements for static objects. Set two metadata items per object at upload time and nothing else is needed:

| Object | `Content-Type` | `Cache-Control` |
| --- | --- | --- |
| `feed.json` | `application/json` | `no-store` |
| `manifest.plist` | `text/xml` | `no-store` |
| `app-<build>.ipa` | `application/octet-stream` | `public, max-age=31536000, immutable` |
| `index.html` | `text/html` | `no-cache` |

Keep the bucket's own compression off for the package. The default compressible content-type lists of common CDNs do not include `application/octet-stream`, which is one more reason to label it exactly that way.

## Tier 1: zero-code static

Three ways to keep a Channel to yourself without writing any code. Each serves the plain four-file directory.

### Tailscale Serve

Tailscale Serve publishes a directory, or a local port, on your tailnet under a Let's Encrypt certificate that is issued and renewed for you. Only devices in your tailnet can reach it.

```sh
tailscale serve --bg /var/www/ota        # a directory
tailscale serve --bg 8080                # or a port your static host listens on
```

The Channel is then `https://<machine>.<tailnet>.ts.net/my-app-dev/`. Requirements:

- MagicDNS and HTTPS enabled for the tailnet; the Tailscale app connected on the iPhone.
- `iosparkle publish --out /var/www/ota/my-app-dev` run on that machine, or `--ssh <user>@<machine>:/var/www/ota/my-app-dev` from your build machine.

The certificate is valid for any client, but the hostname is published in Certificate Transparency logs; the content stays reachable only inside the tailnet. Serve's built-in file serving takes content types from the host's MIME database, so run the three checks above; if `.ipa` is not `application/octet-stream`, put nginx or Caddy in front and point `tailscale serve` at its port.

### Own domain over a tunnel with a DNS-01 certificate

When the Channel must live on your own domain but its host is reachable only through a tunnel — WireGuard, Surge Ponte, a private network — the certificate must be publicly trusted even though no port is open to the internet. An ACME client in **DNS-01** mode proves control of the name through a DNS TXT record instead of an inbound HTTP request, so ports 80 and 443 never have to be reachable, and the certificate it obtains — from Let's Encrypt by default — is trusted by iOS like any other. Caddy with the Cloudflare DNS module does it in a few lines:

```caddyfile
ota.example.com {
    tls {
        dns cloudflare {env.CF_API_TOKEN}
    }
    root * /var/www/ota
    @plist path *.plist
    header @plist Content-Type "text/xml"
    header @plist Cache-Control "no-store"
    @feed path */feed.json
    header @feed Cache-Control "no-store"
    @ipa path *.ipa
    header @ipa Content-Type "application/octet-stream"
    header @ipa Cache-Control "public, max-age=31536000, immutable"
    file_server
}
```

certbot (`certonly --dns-cloudflare`), acme.sh (`--dns`), and lego work the same way with nginx. The iPhone resolves `ota.example.com` through the tunnel, so configure the tunnel's DNS to answer for that name; the system installer uses the same system resolver. A good first test is Safari on the device: if it can open the Feed URL, the system installer can too.

### Capability URL

The simplest private Channel is unguessable rather than authenticated. Put a 256-bit secret in the path:

```sh
SECRET=$(openssl rand -hex 32)       # 64 hex characters
# Channel: https://ota.example.com/<SECRET>/my-app-dev/
```

Any static host works: an R2 or S3 bucket behind a custom domain, Cloudflare Pages, an nginx host. The rules:

- Disable directory listing, so the secret cannot be enumerated from a parent page.
- Send `X-Robots-Tag: noindex` and `Referrer-Policy: no-referrer`, and keep the URL out of public repositories and shared logs.
- To revoke access, publish to a new prefix and ship a new Host App build that points at it.
- The provisioning profile remains the hard gate: even with the URL, a package installs only on a device the profile lists.

This never expires, needs no code, and is the right default for personal and small-team Channels.

## Tier 2: a dynamic presigner

When access must be revocable per person without rebuilding the app, protect the one request the Host App makes, and give the system installer URLs that are unguessable and short-lived:

1. The Host App sends `Authorization: Bearer <token>` with every Feed request, through `Configuration.feedHeaders`.
2. A small gate in front of the Channel checks the token and returns the Feed with a `manifestURL` that carries its own credential: an expiry and an HMAC signature.
3. When the system installer fetches that `manifestURL` with no headers, the gate validates it, renders `manifest.plist`, and puts a freshly minted, one-hour package URL in it.
4. The package sits in a private bucket, reachable only through that presigned URL.

The gate keeps no state beyond its secrets. The Feed and the packages are stored exactly as in a static Channel.

### A complete presigner for Cloudflare Workers

This Worker is dependency-free, about sixty lines of logic, and typechecks under `strict` TypeScript with `@cloudflare/workers-types`. It binds to the Channel's hostname, reads the Feed that `iosparkle publish --out` produced from a private R2 bucket, and mints SigV4 presigned package URLs itself.

```ts
// iOSparkle private Channel: a stateless presigner (Cloudflare Workers, zero dependencies).
// Publish with `iosparkle publish --channel-url https://ota.example.com/my-app-dev --out channel`,
// then upload `channel/` into the private bucket under the key prefix `my-app-dev/`.
interface Feed {
  schemaVersion: number;
  bundleId: string;
  version: string;
  build: number;
  manifestURL?: string; // present in what this Worker serves; never usable in what it stores
  [key: string]: unknown; // publishedAt, commit, minimumOSVersion, releaseNotes, sizeBytes, sha256, …
}

interface Env {
  FEED_TOKEN: string; // secret: Bearer token the Host App sends through Configuration.feedHeaders
  SIGNING_SECRET: string; // secret: HMAC-SHA-256 key for short-lived manifest.plist links
  S3_ACCESS_KEY_ID: string; // secret: R2 S3 API token
  S3_SECRET_ACCESS_KEY: string; // secret: R2 S3 API token
  S3_ENDPOINT: string; // var: "https://<ACCOUNT_ID>.r2.cloudflarestorage.com"
  S3_REGION: string; // var: "auto"
  BUCKET_NAME: string; // var: bucket name as the S3 API sees it
  CHANNEL_PATH: string; // var: "/my-app-dev"
  APP_TITLE: string; // var: title shown in the iOS install dialog
  BUCKET: R2Bucket; // binding: private bucket holding my-app-dev/feed.json and my-app-dev/app-<build>.ipa
}

const MANIFEST_TTL_SECONDS = 3600;
const IPA_TTL_SECONDS = 3600;
const encoder = new TextEncoder();
const hmac = (key: BufferSource, text: string) =>
  crypto.subtle.importKey("raw", key, { name: "HMAC", hash: "SHA-256" }, false, ["sign"])
    .then((imported) => crypto.subtle.sign("HMAC", imported, encoder.encode(text)));
const sha256 = (text: string) => crypto.subtle.digest("SHA-256", encoder.encode(text));
const hex = (bytes: ArrayBuffer) => [...new Uint8Array(bytes)].map((b) => b.toString(16).padStart(2, "0")).join("");
const escapes: Record<string, string> = { "&": "amp", "<": "lt", ">": "gt", '"': "quot", "'": "apos" };
const xml = (text: string) => text.replace(/[&<>"']/g, (c) => `&${escapes[c]};`);
function equal(a: string, b: string) {
  // Compares every byte; never returns early on the first difference.
  const [x, y] = [encoder.encode(a), encoder.encode(b)];
  let difference = x.length ^ y.length;
  for (let i = 0; i < Math.max(x.length, y.length); i++) difference |= (x[i] ?? 0) ^ (y[i] ?? 0);
  return difference === 0;
}
async function manifestSignature(env: Env, expires: number) {
  return hex(await hmac(encoder.encode(env.SIGNING_SECRET), `${env.CHANNEL_PATH}/manifest.plist|${expires}`));
}

/** A fresh SigV4 GetObject URL, minted only when iOS asks for manifest.plist, so X-Amz-Expires stays short. */
export async function presignedGetObject(env: Env, key: string, ttlSeconds: number, now = new Date()) {
  const amzDate = now.toISOString().replace(/[:-]|\.\d{3}/g, "");
  const scope = `${amzDate.slice(0, 8)}/${env.S3_REGION}/s3/aws4_request`;
  const query = new URLSearchParams({
    "X-Amz-Algorithm": "AWS4-HMAC-SHA256",
    "X-Amz-Credential": `${env.S3_ACCESS_KEY_ID}/${scope}`,
    "X-Amz-Date": amzDate,
    "X-Amz-Expires": String(ttlSeconds),
    "X-Amz-SignedHeaders": "host",
  });
  const path = `/${env.BUCKET_NAME}/${key.split("/").map(encodeURIComponent).join("/")}`;
  const canonicalRequest = ["GET", path, query.toString(), `host:${new URL(env.S3_ENDPOINT).host}\n`, "host", "UNSIGNED-PAYLOAD"].join("\n");
  let signingKey: ArrayBuffer = await hmac(encoder.encode(`AWS4${env.S3_SECRET_ACCESS_KEY}`), amzDate.slice(0, 8));
  for (const part of [env.S3_REGION, "s3", "aws4_request"]) signingKey = await hmac(signingKey, part);
  const stringToSign = ["AWS4-HMAC-SHA256", amzDate, scope, hex(await sha256(canonicalRequest))].join("\n");
  query.set("X-Amz-Signature", hex(await hmac(signingKey, stringToSign)));
  return `${env.S3_ENDPOINT}${path}?${query}`;
}

function manifest(feed: Feed, ipaURL: string, title: string) {
  return `<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0"><dict><key>items</key><array><dict>
  <key>assets</key><array><dict><key>kind</key><string>software-package</string><key>url</key><string>${xml(ipaURL)}</string></dict></array>
  <key>metadata</key><dict><key>bundle-identifier</key><string>${xml(feed.bundleId)}</string><key>bundle-version</key><string>${xml(feed.version)}</string><key>kind</key><string>software</string><key>platform-identifier</key><string>com.apple.platform.iphoneos</string><key>title</key><string>${xml(title)}</string></dict>
</dict></array></dict></plist>`;
}

export default {
  async fetch(request: Request, env: Env): Promise<Response> {
    const url = new URL(request.url);
    const prefix = env.CHANNEL_PATH.replace(/\/$/, "");
    const noStore = { "Cache-Control": "no-store" };
    const storedFeed = async () => (await env.BUCKET.get(`${prefix.slice(1)}/feed.json`))?.json<Feed>();
    if (url.pathname === `${prefix}/feed.json`) {
      // Stage 1: the Host App's URLSession, which is the only client that can send a header.
      if (!equal(request.headers.get("Authorization") ?? "", `Bearer ${env.FEED_TOKEN}`)) return new Response("Unauthorized", { status: 401, headers: noStore });
      const feed = await storedFeed();
      if (!feed) return new Response("Not found", { status: 404, headers: noStore });
      delete feed.manifestURL; // the stored Feed carries no usable link; this Worker mints a fresh one
      const expires = Math.floor(Date.now() / 1000) + MANIFEST_TTL_SECONDS;
      const signature = await manifestSignature(env, expires);
      return Response.json({ ...feed, manifestURL: `${url.origin}${prefix}/manifest.plist?expires=${expires}&signature=${signature}` }, {
        headers: { ...noStore, "Content-Type": "application/json; charset=utf-8" },
      });
    }
    if (url.pathname === `${prefix}/manifest.plist`) {
      // Stage 2: itunesstored, which sends no headers: the URL itself must be the credential.
      const expires = Number(url.searchParams.get("expires"));
      if (!(expires > Date.now() / 1000) || !equal(url.searchParams.get("signature") ?? "", await manifestSignature(env, expires)))
        return new Response("Forbidden", { status: 403, headers: noStore });
      const feed = await storedFeed();
      if (!feed) return new Response("Not found", { status: 404, headers: noStore });
      // Stage 3: the presigned .ipa URL is created here, one hour at a time — never stored in a file.
      const ipaURL = await presignedGetObject(env, `${prefix.slice(1)}/app-${feed.build}.ipa`, IPA_TTL_SECONDS);
      return new Response(manifest(feed, ipaURL, env.APP_TITLE), { headers: { ...noStore, "Content-Type": "text/xml" } });
    }
    return new Response("Not found", { status: 404, headers: noStore });
  },
};
```

Publish to it with the usual command, then upload the output to the private bucket under the Channel's key prefix:

```sh
iosparkle publish --ipa MyAppDev.ipa --channel-url https://ota.example.com/my-app-dev --out ./channel
# upload ./channel/* to the bucket as my-app-dev/feed.json, my-app-dev/app-118.ipa, …
iosparkle verify --channel-url https://ota.example.com/my-app-dev --ipa MyAppDev.ipa \
  --header "Authorization: Bearer $FEED_TOKEN"
```

`wrangler.jsonc`:

```jsonc
{
  "name": "iosparkle-channel",
  "main": "src/worker.ts",
  "compatibility_date": "2026-01-01",
  // Bind the Worker to the Channel's hostname so that https://ota.example.com/my-app-dev/* reaches it.
  "r2_buckets": [{ "binding": "BUCKET", "bucket_name": "my-app-private" }],
  "vars": {
    "S3_ENDPOINT": "https://<ACCOUNT_ID>.r2.cloudflarestorage.com",
    "S3_REGION": "auto",
    "BUCKET_NAME": "my-app-private",
    "CHANNEL_PATH": "/my-app-dev",
    "APP_TITLE": "MyApp Dev"
  }
  // Secrets, one `wrangler secret put <NAME>` each:
  //   FEED_TOKEN, SIGNING_SECRET, S3_ACCESS_KEY_ID, S3_SECRET_ACCESS_KEY
}
```

The S3 credentials are an R2 API token, created under *R2 ▸ Manage R2 API Tokens*. Generate the two secrets with `openssl rand -hex 32`.

In the Host App:

```swift
#if IOSPARKLE_ENABLED
import iOSparkle

@MainActor
enum Updates {
    static let updater = IOSparkleUpdater(
        channelURL: URL(string: "https://ota.example.com/my-app-dev")!,
        configuration: .init(feedHeaders: ["Authorization": "Bearer <FEED_TOKEN>"])
    )
}
#endif
```

What to know about this pattern:

- **Lifetime.** The manifest link lasts an hour. That must exceed the longest gap between a Feed refresh and the user tapping **Update**; it is far more than the usual few seconds. The package URL lasts an hour from the moment iOS requests the manifest.
- **Why presign at manifest time.** A SigV4 presigned URL expires after at most seven days (`X-Amz-Expires` ≤ `604800`). One written into a static `manifest.plist` is a time bomb: after a week without a publish, every device fails with `403`. A URL minted when the manifest is requested never has to outlive a download.
- **R2 hosts.** The presigned URL uses `<ACCOUNT_ID>.r2.cloudflarestorage.com`. R2 custom domains do not validate SigV4 parameters.
- **`GET` only.** A SigV4 signature is bound to one HTTP method. `iosparkle verify` uses `GET`, so it works; a monitor that probes presigned URLs with `HEAD` gets `403 SignatureDoesNotMatch`.
- **First install.** Safari cannot send the bearer token, and the Worker answers `404` everywhere outside the two routes. Install the first build from Xcode; the app updates itself from then on. The **Open Channel Page** button in the Developer Updates screen has nothing to show for such a Channel.
- **Other runtimes.** The Worker needs only standard Web APIs (`Request`, `Response`, `crypto.subtle`), so the same functions run on Deno, Node, and most edge platforms; on S3, set `S3_REGION` to the bucket's region and `S3_ENDPOINT` to its regional host.

## Five guaranteed failures

Each of these fails at the system installer stage. None of them produces an error in the Host App, which is what makes them hard to diagnose.

1. **Encoding the manifest URL with a permissive character set.** `&`, `=`, and `+` left bare truncate the manifest URL at the first `&`; a `+` that a gateway reads as a space corrupts a token. Swift's `CharacterSet.urlQueryAllowed` does exactly this. Use an encoder that keeps only `A-Z a-z 0-9 - . _ ~` ([Static Feed & Channel Spec](channel-and-feed-spec.md)).
2. **A presigned package URL stored in a static manifest.** It expires — after a week at most — and then no device can update until the next publish. Mint package URLs when the manifest is requested.
3. **Expecting the system installer to inherit the Host App's authentication.** Headers, cookies, an `NSAppTransportSecurity` exception, or a self-signed certificate trusted by the app: none of it reaches the installer. Protect the Feed with a header; protect everything else with URLs and a publicly trusted certificate.
4. **Probing a presigned package URL with `HEAD`.** The method is part of the signature; the answer is `403`. Use `GET`, or a ranged `GET` as `iosparkle verify` and the checks above do.
5. **Overwriting a fixed `app.ipa` in place.** A device resuming an interrupted download with `Range` receives bytes from two different builds, and the install fails with a checksum or archive error. Publish under a new `app-<build>.ipa` name and leave the previous one in place.

## Choosing

| Situation | Use |
| --- | --- |
| Personal devices or a small team, no code | [Capability URL](#capability-url) |
| Same, but only reachable over your own network | [Tailscale Serve](#tailscale-serve) or [own domain over a tunnel](#own-domain-over-a-tunnel-with-a-dns-01-certificate) |
| Revoke a tester's access without rebuilding; packages in a private bucket | [Dynamic presigner](#tier-2-a-dynamic-presigner) |
| Public test distribution | Any static host with the [required headers](#required-response-headers) |
