# The cas.run API

`/api/v1` is what the `cas` CLI talks to, and anything else that wants to.
It is JSON over HTTPS at the instance's endpoint (`https://cas.run`).
`internal/api` implements this document; `internal/client` is the Go
client. A change to a route is a change here first. The JSON examples
below are checked against the real types by a test, so they are current.

Every example uses a token in `$CAS_TOKEN`. Get one with
`ssh -p 2222 cas.run token`, or from your settings page.

## Authentication

Two credentials are accepted, checked in this order:

- `Authorization: Bearer cas_...` — a CLI token. Get one with
  `ssh -p 2222 cas.run token | sh`, which writes it to
  `~/.config/cas/config.json`. Tokens start with `cas_` and are shown once.
- The `cas_session` cookie — a web login. A state-changing request on a
  cookie must come from this origin (the `Origin` or `Referer` header must
  match the host); a bearer token needs no such check, since no page in a
  browser can set that header on your behalf.

Without a valid credential every route but `/status` answers `401` with
`WWW-Authenticate: Bearer realm="cas.run"`.

### Who is an admin

An account is an admin when its role is `admin` (another admin sets that
on the web) or its login is named in the operator's `-admin` flag. Both
see the admin routes and may act on someone else's services with
`?login=`, and `whoami` says `admin: true` for both. The exemptions from
what units allow (the limits, `userns: host`, a custom domain without a
paid unit) go by the role alone.

## Shape

- Requests with a body are `application/json`. Unknown fields are refused.
- Every response is `application/json` with `Cache-Control: no-store`,
  except a service's logs, which are `text/plain`. That holds off the
  happy path too: an unknown path under `/api/` is a JSON `404`, and a
  known path with the wrong method is a JSON `405` with an `Allow` header
  listing the methods it takes.
- An error is `{"error": "a sentence for a person"}` with a status:

| status | when |
|---|---|
| 400 | bad JSON, a field that fails validation (`image is required`, `env "X" is not KEY=value`, `http_port must be 0, or 1-65535`), an invalid name or volume, a domain that is not a hostname or is under `cas.run` |
| 401 | no credential, or one that does not resolve |
| 403 | a disabled account; a cookie POST from another origin; an admin route from a plain account (`admin only`); `userns: host` from an account without the admin role |
| 404 | no such service or token (yours, that is: other people's are 404 too); a path that is not a route |
| 405 | a route reached with a method it does not take; `Allow` lists the ones it does |
| 409 | you already have a service with that name; the name would share a hostname with another account's service; a custom domain attached to another service |
| 422 | the account's units are used up (services or memory), memory above the per-service cap, or a custom domain without a unit beyond the free one |
| 500 | something broke on our side; the detail is in casd's log, not in the answer |
| 502 | box did not answer for the logs or the stats of a service; the message says what it said |

### Names

A service name is 1 to 32 characters of `a-z`, `0-9` and `-`, not starting
or ending with a dash. It is unique per account and is the first part of
the service's hostname, `<name>-<login>.cas.run`.

### A service

```json
{
  "id": 7,
  "login": "alice",
  "name": "web",
  "image": "nginx:alpine",
  "command": ["nginx", "-g", "daemon off;"],
  "env": ["TZ=Australia/Brisbane"],
  "http_port": 80,
  "memory_mb": 64,
  "cpu_weight": 10,
  "pids": 64,
  "restart": "always",
  "userns": "private",
  "volumes": [{"name": "data", "path": "/data"}],
  "disk_bytes": 114688,
  "desired": "running",
  "box_id": "0f2c7d1e9a4b",
  "ip": "172.30.0.9",
  "status": "running",
  "created_at": "2026-10-19T03:04:05Z",
  "updated_at": "2026-10-19T03:04:11Z",
  "started_at": "2026-10-19T03:04:11Z",
  "host": "web-alice.cas.run",
  "url": "https://web-alice.cas.run"
}
```

`desired` is what you asked for: `running` or `stopped`. `status` is what
the reconciler last saw: `pending` (not yet started), `pulling`, `running`,
`exited`, `stopped`, `error` (a start failed; `last_error` says why) or
`crashloop` (parked after ten failures in a row). A service parked by its
own exits waits for your restart. One parked by failed starts, a pull that
could not reach the registry for instance, tries again on its own: `parked_at`
says when it was parked and `retry_at` when the next attempt comes (fifteen
minutes, then thirty, then hourly, for a day); after the day `retry_at` is
absent and `last_error` says it gave up. A `running` service whose port
answered nothing when the web proxied to it carries the proxy's complaint
in `proxy_error`, until a response gets through or the container is
recreated.

`last_output` is the last 200 lines the container printed before it last
exited, kept before the container is removed; it is empty while the
service runs, so it always says what the last exit said.

`host` and `url` are present only when `http_port` is set. `cpu_weight`
is read-only: every service gets the same share, so one account cannot
starve the rest. Fields that are empty or zero are left out, so a service
that has never failed has no `exit_code`, `last_error`, `failures` or
`last_output`, and one that is not running has no `box_id`, `ip` or
`started_at`.

## Routes

### `GET /api/v1/status` — public

```sh
curl https://cas.run/api/v1/status
```

```json
{"version": "v0.1.0@abc1234", "accounts": 12, "services": 9, "running": 7,
 "backup": {"enabled": true, "last_ok": "2026-10-24T17:00:41Z", "last_error": ""},
 "billing": {"enabled": true, "mode": "live", "paid_units": 5, "past_due": 0}}
```

`backup` is the host's own backup (docs/OPERATIONS.md): whether a
repository is configured, when it last succeeded (`null` if never), and
the last failure as one word: `""` when the last run worked,
`"unreachable"` when the network or the repository could not be reached,
`"failed"` for anything else. The line itself stays with the operator.
`billing` says whether units are for sale and in which Stripe mode
(`off`, `test` or `live`), how many units are paid for across every
account, and how many accounts have a failed payment Stripe is retrying.

While the operator has a site notice up for everyone there is also a
`notice`; a notice meant only for accounts is never here, since this
endpoint has no caller:

```json
"notice": {"text": "Maintenance on Saturday from 10:00 UTC.", "level": "warning",
           "audience": "everyone", "until": "2026-11-28T00:00:00Z"}
```

`level` is `info`, `warning` or `error`; `audience` is `everyone` or
`signed-in`; `until`, in UTC, is when it stops being shown, and is absent
for a notice with no end. The same object is on the site's pages as a
banner and on the SSH door's stderr.

### `GET /api/v1/whoami`

```sh
curl -H "Authorization: Bearer $CAS_TOKEN" https://cas.run/api/v1/whoami
```

```json
{
  "login": "alice", "role": "user", "admin": false,
  "limits": {"units": 1, "services": 1, "memory_mb": 64, "max_memory_mb": 256, "disk_mb": 1024},
  "usage": {"services": 1, "memory_mb": 64, "disk_mb": 3}
}
```

`limits` is what the account's units allow: `units` how many (the free
ones plus the paid ones, or what an admin set; `paid` says how many are
paid for), `services` how many services, `memory_mb` the pool they share, `max_memory_mb` the most
one may take, `disk_mb` what they may hold on disk between them (what
they write and their logs; a service's own share is its `disk_bytes`,
measured every few minutes, and over the allowance the account's largest
running service is stopped with the reason in `last_error`). An account
whose numbers an admin set by hand has `overridden: true`. `usage` is what
the account's services take now, running or stopped.

Once the account has bought units there is also a `subscription`, what
Stripe last said about it, and it stays after the subscription ends:

```json
"subscription": {"id": "sub_1Q2w3e", "customer": "cus_R4t5y6", "status": "active", "quantity": 2,
                 "interval": "month", "price": "price_7u8i9o", "period_end": "2026-11-24T03:00:00Z",
                 "cancel_at_period_end": false, "updated_at": "2026-10-24T06:01:00Z"}
```

The units count while `status` is `active` or `past_due` (a failed card
keeps them through Stripe's retries) and not once it is `canceled` or
`unpaid`. `period_end` is the next charge, or when the units stop if
`cancel_at_period_end` is true. Buying and managing a subscription is
done on the web (the settings page sends the browser to Stripe); there
is no API for it.

While there is a site notice the caller may see, whatever its audience,
whoami carries it as the same `notice` object `status` has.

### `GET /api/v1/services`

```sh
curl -H "Authorization: Bearer $CAS_TOKEN" https://cas.run/api/v1/services
```

Your services, by name, as a JSON array (empty: `[]`).

### `POST /api/v1/services`

```sh
curl -X POST -H "Authorization: Bearer $CAS_TOKEN" -H "Content-Type: application/json" \
  -d '{"name": "web", "image": "nginx:alpine", "http_port": 80}' https://cas.run/api/v1/services
```

```json
{
  "name": "web",
  "image": "nginx:alpine",
  "command": ["nginx", "-g", "daemon off;"],
  "env": ["TZ=Australia/Brisbane"],
  "http_port": 80,
  "memory_mb": 64,
  "pids": 64,
  "restart": "always",
  "userns": "host",
  "domain": "app.example.com",
  "volumes": [{"name": "data", "path": "/data"}]
}
```

Only `name` and `image` are required. The image must be public: box has
no registry credentials. `http_port` is the port the hostname proxies
to; left out or `0`, the service is not exposed and has no `host` or
`url`. `memory_mb` and `pids` default to the instance's settings;
`memory_mb` above the per-service cap, or more than the account's pool
has left, is `422`, as is one service more than its units allow; `pids`
above the instance default is lowered to it, and the CPU share is the
same for every service and not settable (it comes back as `cpu_weight`).
`userns` is `private` (the default) or `host`; `host` is a real root in
the container and needs the admin role (`403` otherwise). `restart` is
`always` (the default) or `no`; `env` entries are `KEY=value`, stored and
shown back as given. `volumes` (up to four) are directories of the
service's own, mounted at `path`, kept across restarts and re-creates,
counted against the account's disk, and deleted with the service.
`domain` attaches a hostname of your own (see `PUT .../domain`) at
creation. Answers `201` with the service in the `pending` state. It
starts within a few seconds; poll `GET` or watch `cas ps`.

### `GET /api/v1/services/{name}`

```sh
curl -H "Authorization: Bearer $CAS_TOKEN" https://cas.run/api/v1/services/web
```

The service. `404` if it is not yours.

### `PATCH /api/v1/services/{name}`

```sh
curl -X PATCH -H "Authorization: Bearer $CAS_TOKEN" -H "Content-Type: application/json" \
  -d '{"image": "nginx:1.27-alpine"}' https://cas.run/api/v1/services/web
```

```json
{"image": "nginx:1.27-alpine", "http_port": 8080, "memory_mb": 128, "env": ["TZ=UTC"], "command": [], "restart": "no"}
```

Changes a service in place (DESIGN §14.19). Every field is optional and
a field left out, or given as `null`, keeps what is there (this is not
RFC 7396: `null` does not clear). `command` and `env` given as `[]` clear
them, and `env` given at all replaces the whole list. `http_port: 0`
stops exposing the service. The checks are `POST`'s: `memory_mb` above
the cap or beyond the pool is `422`, a bad `env`, `restart` or
`http_port` is `400`. The name, `userns` and the volumes cannot change; a
volume is only lost with the service. A running service is recreated with
the change (so it re-pulls the image, as every start does) and a stopped
one picks it up when it next starts. Answers `200` with the service,
which is `pending` when it was running: the container that answers from
here on is the new one.

### `DELETE /api/v1/services/{name}`

```sh
curl -X DELETE -H "Authorization: Bearer $CAS_TOKEN" https://cas.run/api/v1/services/web
```

Removes the container, the volumes and the record. `{"deleted": "web"}`.

### `POST /api/v1/services/{name}/start`
### `POST /api/v1/services/{name}/stop`
### `POST /api/v1/services/{name}/restart`

```sh
curl -X POST -H "Authorization: Bearer $CAS_TOKEN" https://cas.run/api/v1/services/web/restart
```

Change what the service should be doing and answer with it as it now
stands (`desired` has changed; `status` follows within seconds). `restart`
removes the container and runs a fresh one, which also clears a
`crashloop`. A `start` or `restart` of a service that has no container
(one in `error`, `exited` or `crashloop`) answers `pending` with
`last_error`, `proxy_error` and `failures` cleared: what you read from
then on is this attempt's. `stop` keeps the service and its settings; its
container and that container's logs go. A container that exits on its own
leaves its last lines in `last_output`.

### `GET /api/v1/services/{name}/logs[?follow=1][&tail=N]`

```sh
curl -N -H "Authorization: Bearer $CAS_TOKEN" "https://cas.run/api/v1/services/web/logs?follow=1&tail=100"
```

`text/plain`, the container's output. Without `follow` it is everything
box has kept; with `follow=1` (or `true`) the response streams, flushed
as lines arrive, until the container exits or you close the connection.
`tail=N` keeps only the last N lines (N above 10000 is read as 10000; 0
or absent means everything); with `follow` those lines come first and the
stream continues from there. A service that has never run answers an
empty body. A `restart` or a `PATCH` replaces the container, which ends a
follow; `cas logs -f` reconnects, a script of your own should too.

### `GET /api/v1/services/{name}/stats`

```sh
curl -H "Authorization: Bearer $CAS_TOKEN" https://cas.run/api/v1/services/web/stats
```

```json
{"id": "0f2c7d1e9a4b", "name": "alice--web", "memory": "12.3MiB", "memory_limit": "64MiB",
 "memory_bytes": 12897484, "memory_limit_bytes": 67108864, "memory_pct": 19.2,
 "pids": 3, "cpu_seconds": 4.81}
```

A running service's resource use, as box measures it, at this moment.
`memory_limit` is `unlimited` and `memory_limit_bytes` `0` when there is
no cap. A service that is not running answers
`409 {"error":"service is not running"}`; box not answering is `502`.

### `PUT /api/v1/services/{name}/domain`

```sh
curl -X PUT -H "Authorization: Bearer $CAS_TOKEN" -H "Content-Type: application/json" \
  -d '{"domain": "app.example.com"}' https://cas.run/api/v1/services/web/domain
```

```json
{"domain": "app.example.com"}
```

Attaches a hostname of your own to the service, or detaches it with `""`.
Needs a unit beyond the free one (`422` without one); a name that is not a
hostname, or is under the instance's own domain, is `400`; one attached
to another service is `409`. Answers the service: `domain_status` is
`pending` until the certificate is in hand, then `ready`, or `error` with
`domain_error` saying what the name points at instead. The name must
resolve to the instance (a CNAME to the service's hostname, or A and AAAA
records to the instance's addresses) before the certificate is ordered;
it is checked every few minutes.

### Acting for someone else

An administrator may add `?login=<login>` to any route under
`/api/v1/services` to list, create, read, change, start, stop, restart,
delete or read the logs and stats of another account's services, and to
attach a domain for them. Anyone else gets `404` for that. Tokens are
always the caller's own.

### `GET /api/v1/tokens`

```sh
curl -H "Authorization: Bearer $CAS_TOKEN" https://cas.run/api/v1/tokens
```

```json
[{"id": 3, "label": "laptop", "prefix": "cas_k3Jd9sLq", "created_at": "2026-10-19T03:00:00Z", "last_used_at": "2026-10-24T08:15:02Z"},
 {"id": 4, "label": "ci", "prefix": "cas_p0Qr7tWx", "created_at": "2026-10-24T09:00:00Z"}]
```

The secret is never returned here. `prefix` is the first twelve
characters, enough to tell tokens apart. `last_used_at` is absent until
the token has authenticated a request.

### `POST /api/v1/tokens`

```sh
curl -X POST -H "Authorization: Bearer $CAS_TOKEN" -H "Content-Type: application/json" \
  -d '{"label": "laptop"}' https://cas.run/api/v1/tokens
```

`{"label": "laptop"}` (optional, 64 characters at most). Answers `201`:

```json
{"token": {"id": 4, "label": "laptop", "prefix": "cas_p0Qr7tWx", "created_at": "2026-10-24T09:00:00Z"}, "secret": "cas_p0Qr7tWxExampleSecretNotReal"}
```

`secret` is shown here and nowhere else.

### `DELETE /api/v1/tokens/{id}`

```sh
curl -X DELETE -H "Authorization: Bearer $CAS_TOKEN" https://cas.run/api/v1/tokens/4
```

`{"revoked": 4}`. A token not yours is `404`.

## Admin routes

Two read-only lists for the operator and a metrics scrape, `403
{"error":"admin only"}` for anyone else. The lists are what `cas admin
accounts` and `cas admin ps` print.

### `GET /api/v1/admin/accounts`

```sh
curl -H "Authorization: Bearer $CAS_TOKEN" https://cas.run/api/v1/admin/accounts
```

Every account with its limits and what it holds:

```json
[{"id": 1, "login": "alice", "role": "user", "admin": false,
  "created_at": "2026-10-19T03:00:00Z", "seen_at": "2026-10-24T08:15:02Z",
  "limits": {"units": 1, "services": 1, "memory_mb": 64, "max_memory_mb": 64, "disk_mb": 1024},
  "usage": {"services": 1, "memory_mb": 64, "disk_mb": 12}}]
```

`admin` is true by role or by the operator's flag. An account that has
bought units carries its `subscription` as `whoami` does.

### `GET /api/v1/admin/services`

```sh
curl -H "Authorization: Bearer $CAS_TOKEN" https://cas.run/api/v1/admin/services
```

Every service on the instance, in the shape of `GET /api/v1/services`,
each with its owner's `login`. The fields the web proxy decides a `503`
by are all there: a service is served when it has an `http_port`, its
`status` is `running` and it has an `ip`; otherwise the hostname answers
the "not running" page, and `last_error` usually says why. A served
service whose port answered nothing carries the proxy's complaint in
`proxy_error` (on the owner's own `GET /api/v1/services` too); the next
response that gets through clears it, as does a fresh container.

A running service also carries `memory_used_mb`, what its container
holds right now in whole MB (rounded up) from box's stats, beside its
`memory_mb` ceiling:

```json
[{"id": 1, "login": "alice", "name": "web", "image": "nginx:alpine",
  "status": "running", "ip": "172.30.0.9", "http_port": 80,
  "memory_mb": 64, "memory_used_mb": 22,
  "host": "web-alice.cas.run", "url": "https://web-alice.cas.run"}]
```

The stats of every running container are read at once with a three
second limit, so the list never waits on one slow container. A service
that is not running, or whose stats did not come back in time, has no
`memory_used_mb` at all, and the list still answers.

### `GET /metrics`

```sh
curl -H "Authorization: Bearer $CAS_TOKEN" https://cas.run/metrics
```

The Prometheus text exposition (format 0.0.4), not JSON, and at the
root rather than under `/api/v1`, because that is where scrapers look.
It takes the same credentials as the admin lists and answers their
`401` and `403` to anyone else; a tenant hostname never reaches it.
`Content-Type: text/plain; version=0.0.4; charset=utf-8`. Every series
is prefixed `casd_`; `docs/OPERATIONS.md` under "Metrics" lists them
with a scrape config.

## What is not here

More than one exposed port, TCP ports, image pushes, private registries,
token expiry and scopes, webhooks, machine-readable error codes and
pagination are not in this version. Buying units is on the web, not here.
See DESIGN.md §11 and §14.21.
