# Let's Encrypt certificates (built-in ACME)

With a `tls.acme` block, `photon` gets its HTTPS certificate from Let's Encrypt (or another
ACME CA) by itself, keeps it in a folder next to the config, and renews it in the background
before it expires. There is no certbot, no PKCS#12 file, no password and no deploy hook. The
same certificate serves HTTPS and HTTP/3, and a renewal swaps it in without a restart.

```json
{
  "host": "0.0.0.0",
  "port": 80,
  "root": "Public",
  "tls": {
    "port": 443,
    "acme": {
      "email": "admin@example.com",
      "domains": ["example.com", "www.example.com"],
      "directory": "letsencrypt-staging",
      "agreeToTerms": true,
      "redirectHTTP": true
    }
  },
  "http3": true
}
```

[`Root/http-config.acme.json`](https://github.com/brennanMKE/PhotonHTTP/blob/main/Root/http-config.acme.json) is the same example, with
the names taken from `hosts`.

The built-in client uses the HTTP-01 challenge. It is the simplest way to run one Mac with
its own public names. [When to use certbot instead](#when-to-use-certbot-instead) covers the
cases it does not handle.

## Requirements

- **Public DNS.** Every name in `domains` must resolve (A and/or AAAA) to an address that
  reaches this Mac. Let's Encrypt checks each name from several places on the internet.
- **Port 80, from the internet.** The CA fetches
  `http://NAME/.well-known/acme-challenge/TOKEN` on port 80, and nothing else will do: there
  is no way to tell it another port. The server answers on its cleartext `port`, so:
  - set `"port": 80` with `"host": "0.0.0.0"` (or `"::"`). A normal user can bind
    ports below 1024 on the wildcard address ([Ports 80 and 443 without
    root](https://photon-http.sstools.co/docs/running-on-a-mac.md#ports-80-and-443-without-root)); or
  - forward the router's port 80 to the Mac's cleartext port (for example 80 → 8080).
  Open port 80 in every firewall in front of the Mac. Redirects to HTTPS are fine for
  everything else ([Redirect](#redirect-http-to-https)): challenge requests are never
  redirected.
- **Port 443** (TCP, and UDP for HTTP/3) for HTTPS itself, the same way.
- **No wildcard names.** `*.example.com` needs DNS-01, which the built-in client does not
  do; list each name, or use certbot (below).
- **Agree to the terms.** `"agreeToTerms": true` says that you have read the CA's terms of
  service ([Let's Encrypt](https://letsencrypt.org/repository/)). `photon check` refuses
  the config without it.

The first time an unsigned binary listens on a public address, macOS may ask whether it may
accept incoming connections ([Binding to all interfaces and the firewall
prompt](https://photon-http.sstools.co/docs/running-on-a-mac.md#binding-to-all-interfaces-and-the-firewall-prompt)).

## Staging first

Start with `"directory": "letsencrypt-staging"`. Staging issues certificates from an
untrusted test root, so browsers warn, but its rate limits are generous. Production's are
strict, and a misconfigured port 80 can use them up in a few failed tries. Once staging
issues a certificate (`photon cert status` shows `issuer: … (STAGING) …`), switch to
`"letsencrypt"` and reload. Changing the directory starts a new order. The state folder
keeps one account per CA, so the staging account is not reused.

`directory` takes:

| Value | CA |
|---|---|
| `"letsencrypt"` (default) | Let's Encrypt production, `https://acme-v02.api.letsencrypt.org/directory` |
| `"letsencrypt-staging"` | Let's Encrypt staging, `https://acme-staging-v02.api.letsencrypt.org/directory` |
| an `https://` URL | Any RFC 8555 CA: ZeroSSL, Google Trust Services (both need [EAB](#other-cas)), a private CA, or Pebble |

## Rate limits

Let's Encrypt limits, among other things, certificates per registered domain per week,
duplicate certificates (the same set of names), new orders and failed validations per
account and name per hour. See [Rate limits](https://letsencrypt.org/docs/rate-limits/). The
server stays well inside them:

- It orders only when there is no certificate, the names changed, or a renewal is due. A
  restart that finds a valid stored certificate for the names sends nothing.
- After a failure it keeps the current certificate and retries after 1 min, 2, 4, … up to
  6 h (with jitter). A `Retry-After` from the CA is honoured, up to 7 days.
- After a `rateLimited` error, even `photon cert renew --force` waits until the CA's
  `Retry-After`.

Avoid loops that defeat this: don't delete the state folder to "start over", and don't
force renewals in a script. Test on staging.

## The state directory

Keys, the certificate and the account live in `stateDirectory` (default `acme`, relative to
the config file's folder, even when `--root` is given):

| File | Contents |
|---|---|
| `account-key.pem` | The ACME account's P-256 key (PKCS#8). Losing it loses the account, not the certificate |
| `certificate-key.pem` | The certificate's private key |
| `certificate.pem` | The chain as the CA sent it (leaf first) |
| `metadata.json` | Directory URL, account URL, names, profile, issue and last-success times |

The folder is created `0700` and every file is written `0600`: to a temporary file, then
`fsync` and `rename`, so a crash never leaves half a key. The folder is tightened back to
`0700` at every start. Nothing goes into the keychain, and no PKCS#12 file is written: the
identity is built in memory. Back the folder up like any private key. Do not commit it; the
repository's `.gitignore` covers `Root/acme/`.

To move it, set `stateDirectory` and move the folder while the server is stopped. To use
another account, point at an empty folder. Never share one folder between two running
servers.

## Startup

At startup the server loads the state folder (no network):

- **A valid stored certificate** for the configured names is served at once. Restarts and
  reboots don't touch the CA.
- **None yet, expired, or not covering the names:** the order starts in the background once the
  listeners are up, and `startup` decides what HTTPS does meanwhile:

| `startup` | Until the first certificate is issued |
|---|---|
| `"placeholder"` (default) | HTTPS and HTTP/3 serve a self-signed certificate for the names (issuer `PhotonHTTP placeholder`), which browsers reject. The real one replaces it as soon as it is issued, with no restart |
| `"wait"` | Only the cleartext port listens (answering challenges, and serving or redirecting the site). Once the certificate is issued, a [graceful restart](https://photon-http.sstools.co/docs/running-on-a-mac.md#graceful-restart) adds the HTTPS and HTTP/3 listeners and prints their `listening … (https)` lines. No client ever sees the placeholder |

Issuance usually takes a few seconds. The cleartext port never waits for it, so the CA can
always reach the challenge.

## Redirect HTTP to HTTPS

`"redirectHTTP": true` answers every cleartext request with `308 Permanent Redirect` to
`https://HOST/PATH?QUERY` on port 443. Give a number (`"redirectHTTP": 8443`) when HTTPS is
reached on another port. Requests to `/.well-known/acme-challenge/` are never redirected.
Requests arriving over TLS or QUIC pass through. Without `redirectHTTP` (the default), the
cleartext port serves the site too.

To also tell browsers to stay on HTTPS, add HSTS ([TLS → HSTS](https://photon-http.sstools.co/docs/tls.md#hsts)) once the real
certificate works.

## Renewal

The renewal loop runs inside the server and stops with it:

- **ARI (RFC 9773).** When the CA offers renewal information (Let's Encrypt does), the server
  asks for the CA's suggested window and renews at a random time inside it. It checks the
  window again as the CA's `Retry-After` says (default every 6 h). This is how Let's Encrypt
  asks clients to renew early, for example before a mass revocation. The renewal order names
  the certificate it replaces.
- **Otherwise**, when one third of the lifetime remains (about 30 days before expiry for a
  90-day certificate), minus up to 2 % of the lifetime at random.
- **Profiles.** `"profile": "shortlived"` asks Let's Encrypt for its short-lived (about
  6-day) certificates. Renewal follows the same rules, so it happens every few days.
- Failures keep the current certificate and back off as in [Rate limits](#rate-limits).
- The loop wakes at least hourly, so a Mac that slept past the renewal time renews when it
  wakes.

Each renewal swaps the certificate into the running HTTPS and HTTP/3 listeners. New
handshakes get it; open connections keep the one they negotiated. Every step goes to stderr,
for example:

```
photon: acme: requesting a certificate for example.com,www.example.com from https://acme-v02.api.letsencrypt.org/directory
photon: acme: certificate for example.com,www.example.com issued, expires 2027-03-02T12:00:00Z (issuer R11, Let's Encrypt)
photon: acme: renewal window for example.com,www.example.com from the CA: 2027-01-31T… to 2027-02-02T…; renewing at 2027-02-01T…
photon: acme: certificate for example.com,www.example.com failed (attempt 1): …; keeping the current certificate (expires …); retrying at …
```

## Commands

```
photon cert status [--config FILE] [--json]
photon cert renew  [--force] [--config FILE] [--timeout SECONDS]
```

Like the other [control commands](https://photon-http.sstools.co/docs/running-on-a-mac.md#control-commands), these find the
server through its status file (`statusFile`, default `run/status.json`) and signal its pid.
There is no control socket.

- `photon cert status` prints the names, the served certificate's names, issuer, serial,
  validity, next renewal and why then, the CA's renewal window, last success, the last error
  with the number of failed attempts, directory and profile, state folder, and the last
  `cert renew` outcome. `--json` prints the record from the status file.
- `photon cert renew` asks the server to renew if a renewal is due and prints
  `not due: next renewal …` otherwise. `--force` renews now (unless the CA's rate-limit
  `Retry-After` is still running). It waits up to `--timeout` seconds (default 120) for the
  outcome: `renewed: certificate for … renewed, expires …` (exit 0), or `renewal failed, the
  current certificate stays: …` (exit 1). The request travels as a `cert-renew` file next to
  the status file plus SIGUSR1.
- `photon status` adds one line: `certificate: example.com,www.example.com from R11, Let's
  Encrypt, expires …, next renewal …`.
- `photon check` validates the block without touching the network or the state folder. It
  reads the `caCertificates` file and checks the EAB variable, and it says which CA the
  certificate comes from.

## Reload and restart

| Change | Takes effect |
|---|---|
| `domains` (or the `hosts` names it defaults to), `directory`, `email`/`contact`, `profile`, `externalAccountBinding`, `caCertificates`, `stateDirectory` | **Reload.** The server makes a new certificate manager and orders a certificate if the stored one does not cover the new names or comes from another CA. The current certificate keeps serving until then. `photon check` reports `can hot-reload: tls.acme changed` |
| `redirectHTTP` | Reload (it is part of the request chain) |
| `startup` | Only at startup |
| `tls.port` | Restart, as with `tls.identity` |
| Switching between `tls.identity` and `tls.acme`, or adding or removing `tls` | **Restart** (`photon restart`), like adding or removing `tls`. A server that started without `tls.acme` cannot add it in a graceful restart: stop and start it (`launchctl kickstart -k …`) |

## Other CAs

- **External account binding.** ZeroSSL, Google Trust Services and many commercial CAs tie
  the ACME account to an account with them. Copy the key ID and HMAC key they show:
  `"externalAccountBinding": {"keyID": "…", "hmacKeyEnv": "ACME_EAB_KEY"}`. Prefer
  `hmacKeyEnv` (an environment variable) over an inline `"hmacKey"`, so the secret stays out
  of the file.
- **A private CA or Pebble.** `"caCertificates": "ca.pem"` trusts the roots in that PEM file,
  in memory only, for the directory's HTTPS. Without it the system's roots are used. The
  certificate the CA issues is served as is; clients must trust that CA.

## Reference

| Key | Type | Default | Meaning |
|---|---|---|---|
| `tls.acme` | object | – | Get the certificate over ACME. Not together with `tls.identity` / `tls.password` / `tls.passwordEnv` |
| `tls.acme.email` | string or array | none | Contact address(es), sent as `mailto:` URLs. Optional (Let's Encrypt no longer sends expiry emails) |
| `tls.acme.contact` | array | none | Contact URLs (`mailto:` only), in addition to `email` |
| `tls.acme.domains` | array of strings | names in `hosts` | Names (or IP addresses) on the certificate. No wildcards |
| `tls.acme.directory` | string | `"letsencrypt"` | `"letsencrypt"`, `"letsencrypt-staging"` or an `https://` directory URL |
| `tls.acme.agreeToTerms` | bool (required `true`) | `false` | Accept the CA's terms of service |
| `tls.acme.stateDirectory` | string | `"acme"` | Folder for keys, chain and metadata, relative to the config file |
| `tls.acme.profile` | string | none | ACME profile, e.g. `"shortlived"` |
| `tls.acme.redirectHTTP` | bool or port | `false` | Redirect cleartext requests to HTTPS (`true` = port 443) |
| `tls.acme.startup` | string | `"placeholder"` | `"placeholder"` or `"wait"` ([Startup](#startup)) |
| `tls.acme.externalAccountBinding` | object | none | `keyID` and `hmacKey` or `hmacKeyEnv` |
| `tls.acme.caCertificates` | string | system roots | PEM roots to trust for the CA's directory |

## Troubleshooting

Start with `photon cert status`. Its `last error` is the CA's problem document, which names
the failing name.

| Symptom | Cause and fix |
|---|---|
| `unauthorized` / `incorrectResponse`, `Invalid response from http://NAME/.well-known/acme-challenge/…` | The CA reached something else on port 80: a router forwarding to another machine, another web server, or a CDN. `curl -i http://NAME/.well-known/acme-challenge/test` from outside should give this server's `404` |
| `connection` / `Timeout during connect` | Port 80 is closed: router forwarding, a firewall, or an ISP that blocks inbound port 80 (then use certbot with DNS-01) |
| `dns` / `NXDOMAIN` / `No valid IP addresses found` | The name doesn't resolve publicly yet, or an AAAA record points to an address that doesn't reach the Mac. Remove a wrong AAAA record |
| `caa` | A CAA record on the domain forbids this CA. Add `letsencrypt.org` (or your CA) to it |
| `rateLimited` | Production limit reached. The server waits for the CA's `Retry-After` by itself; test on staging meanwhile |
| `externalAccountRequired` | The CA needs `externalAccountBinding` |
| HTTPS shows `PhotonHTTP placeholder` | No certificate yet: see `last error`. With `startup: "wait"`, HTTPS isn't listening yet instead |
| `"tls.acme.stateDirectory": cannot use …` at startup | The folder can't be created or read: wrong owner, or a file in its place |
| Browser warns `(STAGING)` | You are still on `letsencrypt-staging`. Switch `directory` and reload |

The server never retries faster than the backoff, so fix the cause and then run
`photon cert renew --force` (or reload) instead of restarting in a loop.

## When to use certbot instead

Use certbot (or lego, acme.sh) with
[`scripts/acme-deploy-hook.sh`](https://photon-http.sstools.co/docs/running-on-a-mac.md#a-real-certificate-lets-encrypt) and
`tls.identity` when:

- you need a **wildcard** certificate or **DNS-01**: port 80 isn't reachable, the ISP blocks
  it, or the Mac is on a private network;
- **several machines** or other software share the certificate;
- a reverse proxy, load balancer or CDN in front of the Mac terminates TLS or takes port 80;
- your organisation already runs certbot, or wants the certificate files in a standard place.

Switching between the two is a config edit and `photon restart`.
