# Hosting the policy (/policy/hosting)

The policy is a static JSON file that every install downloads. You don't need a server for it: the
[CLI](/docs/reference/cli) publishes it to GitHub, or you can serve it from anything that speaks
HTTPS.

## Publish with the CLI [#publish-with-the-cli]

Keep `upwell/policy.json` (and `upwell/releases.json`) in your app's repo, review changes in pull
requests, and publish with one command:

```bash
npx @upwell/cli publish
```

The first run creates a **public GitHub gist** with both files, prints their URLs, and records the
gist in `upwell.json`. Pass the policy URL to your app:

```tsx
<UpwellProvider policy="https://gist.githubusercontent.com/acme/aa5a315d61ae9438b18d/raw/policy.json">
```

The URL never changes. Later runs update the same gist: they show the diff against what's live
first, and changes that affect installs already out there (raising `minimum`, lowering `latest`,
changing the OTA runtime) need `--confirm`. `npx @upwell/cli status` shows whether the published
copy matches your local files.

### A public repo instead of a gist [#a-public-repo-instead-of-a-gist]

```bash
npx @upwell/cli publish --repo acme/app-updates [--branch main] [--path upwell]
```

This commits both files to the repo (one commit per changed file) and serves them from
`https://raw.githubusercontent.com/acme/app-updates/main/upwell/policy.json`. The repo must be
**public**: raw URLs of private repos need a token, which can't ship inside an app. That's why
publishing doesn't use your app's own repo, which is usually private.

### Authentication [#authentication]

`publish` uses `GITHUB_TOKEN` or `GH_TOKEN` when set (CI), otherwise the GitHub CLI's login
(`gh auth login --scopes gist`). Gists need the `gist` scope; a repo target needs `contents: write`
on that repo. Upwell has no account or credentials of its own, and nothing passes through Upwell's
servers.

### Caching [#caching]

Gists and raw repo files are served with `Cache-Control: max-age=300`, so a published change
reaches devices within about 5 minutes. Don't use URLs pinned to a revision (they never change), and
don't put jsDelivr in front of GitHub for this: its cache for branch URLs is much longer.

### History and rollback [#history-and-rollback]

Gists and repos keep every revision, and `publish` prints the revision it created. To roll back,
publish an older version of the file:

```bash
git checkout <commit> -- upwell/policy.json
npx @upwell/cli publish --confirm
```

<Callout title="Published files are public">
  Anyone with the link can read them, and they always were: every install of your app downloads
  them. Never put secrets in the policy or the release notes.
</Callout>

## Host it yourself [#host-it-yourself]

Anything that serves HTTPS works, and Upwell never needs an account:

| Host | Notes |
| --- | --- |
| A CDN (CloudFront, Cloudflare, Fastly) | Set a short cache TTL (e.g. 60 s), so a change reaches devices quickly |
| S3, R2, GCS bucket | Make the object public, or use `headers` for auth |
| GitHub Pages | Easy to review policy changes in pull requests. Pages caches for about 10 minutes |
| Your API | Return the JSON from any endpoint. You can generate it, e.g. from your release pipeline |
| Firebase Remote Config, LaunchDarkly, … | Use a [custom source](/docs/guides/custom-sources-and-adapters) |

Check a self-hosted URL the way a device sees it with
`npx @upwell/cli doctor --policy-url <url>`: HTTPS, reachable, valid, and cached for 5 minutes or
less.

## Fetching [#fetching]

Pass a URL and Upwell uses `jsonUrl()` under the hood:

```tsx
<UpwellProvider policy="https://cdn.example.com/upwell/policy.json">
```

Or configure it:

```tsx
import { jsonUrl } from 'upwell';

<UpwellProvider
  policy={jsonUrl('https://api.example.com/upwell/policy', {
    headers: { Authorization: `Bearer ${token}` },
    cacheBust: true,
  })}
/>
```

| `jsonUrl` option | Default | |
| --- | --- | --- |
| `headers` | — | Extra request headers |
| `cacheBust` | `false` | Appends `?_=<timestamp>` to skip CDN caches. Off by default because it breaks signed URLs |
| `fetch` | global `fetch` | A custom fetch implementation |

Requests always send `Cache-Control: no-cache`, so the HTTP cache on the device doesn't serve stale
copies. They time out after `timeoutMs` (default 10 s).

## Last known good [#last-known-good]

Every valid policy is cached on the device. When a fetch fails (offline, timeout, HTTP error) or
returns an invalid policy:

1. Upwell uses the cached copy and decides normally.
2. `state.policyError` holds the reason, and the trace says `using last known good`.
3. Only when there's no cached copy either, *and* nothing else to do (such as an OTA update), is the
   decision `error`.

So a CDN outage never blocks your users, and a broken policy edit doesn't take effect.

<Callout type="warn" title="A valid but wrong policy does take effect">
  Validation catches typos and impossible values (like `minimum` above `latest`), but not a
  `minimum` you raised by mistake. Review policy changes like code, and check them with
  [simulation](/docs/guides/testing-and-simulation) or [`explain()`](/docs/reference/core#explain) first.
</Callout>

## Bundling a fallback [#bundling-a-fallback]

To have a policy before the first fetch ever succeeds, bundle one and fall back to it:

```ts
import { jsonUrl, type PolicySource } from 'upwell';
import bundled from './policy.json';

const remote = jsonUrl('https://cdn.example.com/upwell/policy.json');

const policy: PolicySource = {
  async fetch(signal) {
    try {
      return await remote.fetch(signal);
    } catch {
      return bundled as never;
    }
  },
};
```

Because the source then succeeds even when the network fails, the bundled copy wins over the
cached one in that case. Keep it conservative, for example only a `minimum` you're sure about.

## One file or many [#one-file-or-many]

One file with an `android` and an `ios` section is the simplest. If you prefer separate files per
platform or environment, pick the URL at runtime:

```tsx
const env = __DEV__ ? 'staging' : 'production';

<UpwellProvider policy={`https://cdn.example.com/upwell/${env}/policy.json`} />;
```

## Release checklist [#release-checklist]

1. Ship the new build to the store and wait until it's live (and rolled out, on Play).
2. Update `latest` (with `releasedAt`) in the policy:
   `npx @upwell/cli policy set latest --platform android --version 3.5.0 --build 350 --released-at today`
3. Once the first OTA update for the new runtime is published, update `ota.latestRuntimeVersion`:
   `npx @upwell/cli policy set ota-runtime 3.5.0`
4. Raise `minimum` only when you really need to block older builds.
5. Publish: `npx @upwell/cli publish` (with `--confirm` for steps 3 and 4).
