# bitcoinrouter.ai HTTP API

The API behind the site, at `https://bitcoinrouter.ai/api`. It does
everything the site does, with no browser, and the docs' "For agents"
section walks through the flow. Request and response bodies are JSON,
except the CSV exports and the Lexe wallet's callback.

## Conventions

- **Session**: signup and login set an `HttpOnly`, `SameSite=Lax`, `Secure`
  cookie named `__Host-br_session`, and logout clears it. Over plain http,
  as in dev, it is `br_session` and not `Secure`. Both also return the
  token as `session`, which works as `Authorization: Bearer <session>` and
  takes precedence over the cookie. Endpoints marked *auth* return 401
  without a session, or with an `Authorization` header that isn't a valid
  bearer.
- **Errors**: `{"error": "<message>"}` with a 4xx or 5xx status. A 403's or
  409's `error` is a stable machine-readable code instead of prose, listed
  per endpoint. 429 means rate limited.
- **Secrets** travel in JSON bodies, never in a path or query string, which
  servers and proxies log. So an endpoint that names one, such as a wallet
  login's `flow_id`, is a POST even if it only reads.
- **Money**: USD fields are JSON numbers in dollars (`1.25`), converted from
  micro-dollars. Sats are integers.
- **Time**: milliseconds since the UNIX epoch, as integers.

## Accounts

On staging, every signup, the wallet one included, needs the
`X-Gate-Email` header, else it is 403 `gate_sign_in_required`. The staging
gate (`nix/nixosModules/lexe-gate.nix`) sets it to whoever it let through,
and the account keeps it, trimmed, as its `gate_email` (see "Admin").
Logging in needs none, but a login, by any method, whose header is an
`@lexe.app` address, ignoring case, connects the account to it, unless the
account's `gate_email` is one already. Elsewhere the header is ignored.

An account logs in with a password, with any number of wallets (see
"Wallet login"), or both; one with neither logs in with its account code.
On an account with a password or a wallet, adding or removing a login
method needs a session that a login created in the past ten minutes, else
the request is 409 `reauth_required`: log in again, by any method, and
retry with the new session. A code account's first password or wallet
needs no recent login. Every such change logs out the account's other
sessions and revokes its chat keys in the background.

### `POST /api/signup`

```json
{ "username": "alice" | null, "password": "..." }
```

201 `{ "account_id": 42, "session": "..." }`, and sets the session cookie.
400 unless a given username, lowercased, is `[a-z0-9_]{3,32}` with at
least one letter, and the password has no leading or trailing whitespace,
is 10 to 128 bytes, and reaches zxcvbn score 3. 409 `username_taken`.

### `POST /api/signup/code`

Any body is ignored. Creates an account with no username or password,
whose only login is a generated account code: 20 characters of lowercase
base32 in groups of four. 201
`{ "account_id": 42, "login_code": "k7mq-3xzp-wq2n-7hd4-vt6s", "session": "..." }`,
and sets the session cookie. A lost code can't be recovered, so the account
is lost with it. Shares the signup rate limit. 409 `logged_in` with a valid
session.

A code account is deleted once it is a week old if it never paid, meaning
it has no password, wallet, key or ledger entry (such as an admin credit),
no payment that ever settled, and none made in the past week, unless it is
a sponsor (see "Sponsors").

### `POST /api/login`

```json
{ "identifier": "alice" | "42" | "alice@example.com", "password": "..." }
```

`identifier` is a username, an account id or an address (see "Email"),
ignoring case and surrounding whitespace. `password` is the account's
password or, while it has none, its account code, ignoring case, dashes and
whitespace. 200 `{ "account_id": 42, "session": "..." }`, and sets the
cookie. 401 on any failure, without saying which, nor whether `identifier`
names an account: a password is checked as long either way. Rate limited
per IP and per `identifier` (429), whether or not it names an account.

### `POST /api/logout` *auth*

204, ends the request's session and clears the cookie.

### `GET /api/me` *auth*

```json
{
  "account_id": 42,
  "username": "alice" | null,
  "email": "alice@example.com" | null,
  "login_code": null | "k7mq-3xzp-wq2n-7hd4-vt6s",
  "has_password": true,
  "linking_keys": [ {            // wallet logins
    "pubkey": "02c3b844...0c9362",
    "name": null | "Phone",
    "created_at": 1760000000000,
    "last_used_at": 1760000000000
  } ],
  "created_at": 1760000000000,
  "authenticated_at": 1760000000000, // when this session logged in
  "expires_at": null | 1760604800000,
  "admin": false,
  "paused_at": null | 1760000000000,
  "balance_usd": -0.40,
  "credit_usd": 1.00,
  "max_credit_usd": 1.00,
  "credit_full_at_usd": 20.00,
  "lifetime_paid_usd": 25.00,
  "lifetime_spent_usd": 25.40,
  "headroom_usd": 0.60,
  "reserve_usd": 0.00,
  "target_usd": 4.00,
  "refill_target_usd": null | 10.0,
  "refundable_usd": 0.00,
  "funding": [ {                 // in draw order
    "id": 3,
    "kind": "lexe" | "nwc",
    "name": "Lexe",
    "status": "active" | "needs_attention" | "unresponsive",
    "detail": null | "Credential revoked",
    "expires_at": null | 1790000000000,
    "created_at": 1760000000000,
    "refundable_usd": 0.00,
    "receives": true
  } ],
  "wallet_debts": [ { "account_id": 7, "funding_id": 3, "owed_usd": 3.20 } ],
  "keys": [ KeyInfo ],           // live, both kinds
  "payments": [ PaymentInfo ],   // newest first, last 20
  "refunds": [ RefundInfo ],     // newest first, last 20
  "events": [ EventInfo ]        // newest first, last 30 days
}
```

`email` is the account's address, which it proved it receives mail at (see
"Email"). `login_code` is the account code, or `null` once the account has
another login method. `has_password` says whether it has a password, and
`linking_keys` lists its wallet logins: each wallet's public key as hex,
which names it in the `/api/me/linking-keys/{pubkey}` endpoints, its
optional name, and when it last logged in, or was linked.

`expires_at` is when staging deletes the account, a week after it was
made, unless staging keeps it: connected to a Lexe person's sign-in (see
"Accounts"), an admin, or a kept sponsor's sponsored account. A sponsored
account's is its sponsor's. `null` for an account kept, and off staging.
See DESIGN.md "Environments".

`admin` says whether the account may use the admin API.

`paused_at` is when the account was paused, or `null` while it isn't. While
paused, `credit_usd` and `reserve_usd` are zero. See "Pausing and refunds".

`target_usd` is the larger of `refill_target_usd` and the largest default
target across the providers of the account's keys (zero without keys), at
most $100. `credit_usd` is 5% of `lifetime_spent_usd`, everything ever
charged for usage, up to `max_credit_usd`. `max_credit_usd` is the largest
credit cap across the same providers, and `credit_full_at_usd` is the
lifetime spend at which credit reaches it. See DESIGN.md "Money".

Keys run while `headroom_usd` is above `reserve_usd`, and pause at it. With
an `active` wallet, `reserve_usd` is zero. Without one, the account is
prepaid, and there is no wallet to collect a last turn's overshoot from. So
`reserve_usd` is the largest prepaid reserve across the same providers
($0.05 on Tinfoil, $0.25 on TrustedRouter), or zero with no keys yet. The
reserve stays part of the account's balance, spent after the next payment.

`funding` lists the account's wallets, at most five. Automatic pulls draw
from the first that is `active` and not backing off after a failed payment.
A wallet's `status` is `needs_attention` once it refuses a payment or a
check, with `detail` saying why, and `unresponsive` while it doesn't answer
our liveness checks. Credit needs at least one `active` wallet.

`refundable_usd` is what `POST /api/refund` would send the wallets, before
the fee. It is the sum of each wallet's `refundable_usd`, the unspent part of
what was pulled from it. A wallet counts only while it's connected and
`receives` refunds. Every Lexe wallet does, and an NWC wallet only if it
offers `make_invoice`. Once removed, a Lexe wallet's pulls count again when
the same wallet reconnects, but an NWC connection's pulls stop counting.
Usage spends what came in otherwise (invoices, credits) first, then pulls no
wallet can take back. See DESIGN.md "Refunds".

`wallet_debts` lists the other accounts this account's wallets funded that
owe money, each with `owed_usd` and `funding_id`, the wallet that owes it.
While the list isn't empty, the account gets no credit and can't create
keys. `POST /api/funding/settle-debt` pays the debts.

### `DELETE /api/me` *auth*

On staging only, deletes the account, for good: 204, and every session of
it ends, the cookie cleared. From then on no login finds it (401, or 409
`unknown_wallet` for a wallet), its sponsor tokens stop, and nothing more
is minted for it or pulled for it. Its keys are revoked at their providers,
each charged a final reading, and then everything in it is deleted, its
sponsored accounts first if it is a sponsor. A provider that is down puts
that off, until the poller's next try. Its username and wallet logins stay
taken until then, but its address is free at once. Off staging, 404, as if
there were no such route.

### `PUT /api/me/settings` *auth*

```json
{ "refill_target_usd": null | 10.0 }
```

200 with the `GET /api/me` body. 400 if `refill_target_usd` is below the
default target or above $100.

### `PUT /api/me/password` *auth*

```json
{ "password": "...", "username": null | "alice" }
```

Set the account's password, or change it. A first password may come with
`username`; both are validated as at signup (400, 409 `username_taken`). A
code account's code is deleted: it now logs in with the password. A change
takes no `username` (400). Logs out the account's other sessions, and
revokes its chat keys in the background. 200 with the `GET /api/me` body.
409 `reauth_required` without a recent login, except for a first password
on an account without a wallet login. 404 if a change finds no password.

### `DELETE /api/me/password` *auth*

Remove the account's password, leaving its wallet logins. 200 with the
`GET /api/me` body. 404 if the account has no password; 409
`last_login_method` if it has no wallet login; 409 `reauth_required`
without a recent login. Logs out the account's other
sessions, and revokes its chat keys in the background.

### `PUT /api/me/username` *auth*

```json
{ "username": "alice" }
```

Set the username of an account with a password, or change it, validated
as at signup (400, 409 `username_taken`). The old name is free at once.
200 with the `GET /api/me` body; the current name again changes nothing.
409 `no_password` without a password, as a username logs in only with
one; 409 `reauth_required` without a recent login. Logs no one out: a
username is an identifier, not a credential.

### `DELETE /api/me/username` *auth*

Remove the account's username, so it logs in by its number or address.
200 with the `GET /api/me` body. 404 without a username; 409
`reauth_required` without a recent login. Logs no one out.

### `POST /api/me/login-code` *auth*

Replace the account code with a new one, log out the account's other
sessions, and revoke its chat keys in the background. 200
`{ "login_code": "..." }`. 409 `no_login_code` if the account has none: it
logs in with a password or a wallet.

### `POST /api/me/linking-keys` *auth*

```json
{ "flow_id": "...", "name": null | "Phone" }
```

Link the wallet that answered the login flow `flow_id` (see "Wallet
login") to the account, so it logs in to it from now on, named `name` if
given (trimmed, at most 40 characters). A code account's code is deleted.
Logs out the account's other sessions, and revokes its chat keys in the
background. 200 with the `GET /api/me` body. 404 if the flow is unknown,
expired or used; 409 `flow_pending` if no wallet has answered it yet; 409
`wallet_taken` if the wallet logs in to another account; 409
`already_linked` if it is this account's; 409 `reauth_required` without a
recent login, on an account that already has a password or a wallet.

### `PATCH /api/me/linking-keys/{pubkey}` *auth*

```json
{ "name": "Phone" }
```

Rename the wallet login `pubkey`, as listed in `GET /api/me`. A blank name
clears it. 200 with the `GET /api/me` body. 404 if the account has no such
wallet; 400 if `pubkey` isn't 33 bytes of hex, here and below.

### `DELETE /api/me/linking-keys/{pubkey}` *auth*

Unlink the wallet `pubkey`. 200 with the `GET /api/me` body. 404 if the
account has no such wallet; 409 `last_login_method` if it is the account's
only login; 409 `reauth_required` without a recent login. Logs out the
account's other sessions, and revokes its chat keys in the background.

## Email

An account may have an address, which it logs in by as by a username, and
which resets its password. It gets one only by proving that it receives
mail there: a *start* mails a code, and the browser sends the code back
with the `flow` the start answered. A code is 8 characters of lowercase
base32 in two groups of four (`k7mq-3xzp`), checked ignoring case, dashes
and whitespace. It works for 10 minutes, once, and only at its own
endpoint, and five wrong codes end its flow.

None of these says who has an account. A start answers the same 200
`{ "flow": "..." }`, after the same work, whether or not the address has
one, and mails in the background: a code, or in its place a note (see each
start). Every failure to redeem a code, whether its flow is unknown,
expired, another endpoint's or out of tries, or the code is wrong, is the
same 409 `invalid_code`, which says nothing of the tries left.

Each mail is in the words of the brand of the origin the request was made
to, and from `noreply` at its domain, which takes no mail:
`bitcoinrouter.ai <noreply@bitcoinrouter.ai>` or
`lexerouter.ai <noreply@lexerouter.ai>`.

A start's `email` is trimmed and lowercased, and is 400 `That doesn't look
like an email address` unless it is at most 254 bytes: a local part of 1 to
64 bytes of `a-z`, `0-9` and ``!#$%&'*+/=?^_`{|}~-.``, with no dot at either
end or beside another; `@`; and a domain of two labels or more, each 1 to 63
bytes of `a-z`, `0-9` and `-`, with no `-` at either end, the last not all
digits. Non-ASCII is refused.

Starts are rate limited per IP (5 a minute), overall, and per mailbox (5,
then one every 15 minutes; an address's `+tag` doesn't make another mailbox,
nor at Gmail do its dots), and redeems per IP (10 a minute), each limit
shared by every endpoint of its kind (429). Where nothing sends mail
(`GET /api/status`'s `mail` is `null`), these endpoints are 404.

### `POST /api/signup/email/start`

```json
{ "email": "alice@example.com" }
```

200 `{ "flow": "..." }`. Mails a signup code, or if the address has an
account, links to log in or set a new password, and no code.

### `POST /api/signup/email`

```json
{ "flow": "...", "code": "k7mq-3xzp", "password": "..." }
```

Create an account with the flow's address and `password`, and no username.
201 `{ "account_id": 42, "session": "..." }`, and sets the cookie, like
`POST /api/signup`. Needs the staging gate's header on staging, as every
signup does. 400 unless the password passes the rules of
`POST /api/signup`, with the address's local part and its domain's first
label counting against its strength: only a right code gets that far, and
it stays usable. 409 `invalid_code`; `email_taken` if the address got an
account since the start; `logged_in` with a valid session.

### `POST /api/password-reset/start`

```json
{ "email": "alice@example.com" }
```

200 `{ "flow": "..." }`. Mails a reset code if an account has the address,
and nothing otherwise.

### `POST /api/password-reset`

```json
{ "flow": "...", "code": "k7mq-3xzp", "password": "..." }
```

Give the account that has the flow's address `password`, in place of its
password or account code, end all its sessions, revoke its chat keys in the
background, and log in. 200 `{ "account_id": 42, "session": "..." }`, and
sets the cookie, like `POST /api/login`. 400 as for `POST /api/signup/email`.
409 `invalid_code`, also if no account has the address any more.

### `POST /api/me/email/start` *auth*

```json
{ "email": "alice@example.com" }
```

200 `{ "flow": "..." }`. Mails a code to add the address to the account, or
if another account has it, how to move it, and no code. 400 if it is the
account's already.

### `PUT /api/me/email` *auth*

```json
{ "flow": "...", "code": "k7mq-3xzp" }
```

Set the flow's address on the account, in place of any it had. The flow is
only this account's. 200 with the `GET /api/me` body. 409 `invalid_code`;
`email_taken` if another account got the address since the start. The
address it replaces is mailed a notice, which doesn't name the new one.

### `DELETE /api/me/email` *auth*

Remove the account's address, which then logs nobody in, and is free for
another account; the account logs in by its id or username. 200 with the
`GET /api/me` body. 404 if it has none. Works where nothing sends mail;
elsewhere the address is mailed a notice.

These three need a session that a login created in the past ten minutes,
else 409 `reauth_required`, unless the account logs in with its account
code. Each change logs out the account's other sessions, and revokes its
chat keys in the background.

## Wallet login

A Lightning wallet logs in by LNURL-auth (LUD-04): the site shows a code,
the wallet signs the challenge in it, and the wallet's key for our domain
identifies the account. A flow has two identifiers. `k1`, the challenge,
is in the code and so public; the wallet sends it back. `flow_id` is the
browser's secret, returned once by `start` and sent only in JSON bodies:
whoever holds it claims the flow's result, so it never goes in a URL or in
storage. Flows live ten minutes, in memory, so a restart means a new code.

The wallet's answer serves whichever of `login`, `signup` or
`POST /api/me/linking-keys` the browser then calls, whatever `action` the
code was started with, so a user who scanned on the wrong page needn't
scan again. The callback is always on `LEXE_ROUTER_LNURL_AUTH_ORIGIN`
(default: the first `LEXE_ROUTER_BASE_URL`), as wallets derive their key
from its domain.

### `POST /api/auth/lnurl/start`

```json
{ "action": "login" | "register" | "link" }
```

200 `{ "flow_id": "...", "lnurl": "LNURL1..." }`. `lnurl` is the bech32
LNURL, uppercase for a QR code; a link is `lightning:` and it. `action` is
what the wallet tells the user it is approving. Rate limited per IP and
overall (429).

### `GET /api/auth/lnurl/callback?tag=login&k1=<hex>&action=<action>&sig=<hex>&key=<hex>`

The wallet's answer: `sig`, a DER ECDSA signature over `k1` by `key`, its
secp256k1 public key for our domain. Always 200, with LUD-04's body:
`{ "status": "OK" }`, or `{ "status": "ERROR", "reason": "..." }` for a
missing parameter, an unknown or expired `k1`, an invalid signature, a
`k1` another wallet already answered, or too many invalid answers. The
same wallet may answer again. Serves `Access-Control-Allow-Origin: *`, for
wallets that run in a browser.

### `POST /api/auth/lnurl/status`

```json
{ "flow_id": "..." }
```

200 `{ "state": "pending" }` while no wallet has answered; `{ "state":
"expired" }`; `{ "state": "known", "account_id": 42, "created_at":
1760000000000, "pubkey": "02c3b844...0c9362" }` once a wallet that logs in to
an account has, naming the account, when it was created, and the wallet's
key, as `GET /api/me` lists it; or `{ "state": "unknown_wallet", "pubkey":
"..." }` once a wallet with no account has. 404 if the flow is unknown or was used. Reads
only, so it is safe to poll, and never sets a cookie.

### `POST /api/auth/lnurl/login`

```json
{ "flow_id": "..." }
```

Log in to the account of the wallet that answered the flow. 200
`{ "account_id": 42, "session": "..." }`, and sets the session cookie,
like `POST /api/login`. 404 if the flow is unknown, expired or used; 409
`flow_pending` if no wallet has answered yet; 409 `unknown_wallet` if the
wallet has no account (see `signup`).

### `POST /api/auth/lnurl/signup`

```json
{ "flow_id": "...", "name": null | "Phone" }
```

Create an account whose login is the wallet that answered the flow, named
`name` if given (trimmed, at most 40 characters). 201
`{ "account_id": 42, "session": "..." }`, and sets the cookie, like
`POST /api/signup`. Needs the staging gate's header on staging and shares
the signup rate limit, as the other signups do. 404 and 409
`flow_pending` as for `login`; 409 `wallet_taken` if the wallet already
logs in to an account; 409 `logged_in` with a valid session.

## Providers

### `GET /api/providers`

```json
[ {
  "id": "tinfoil",
  "name": "Tinfoil",
  "tier": "private" | "standard",
  "base_url": "https://inference.tinfoil.sh/v1",
  "docs_url": "https://docs.tinfoil.sh",
  "privacy_note": "Models run in a secure enclave. Nobody, including us or Tinfoil, can read your prompts.",
  "premium_percent": 7.0,
  "max_credit_usd": 1.00,
  "max_turn_cost_usd": 1.00,
  "concurrency": 1,
  "target_usd": 1.00,
  "start_usd": 1.00
} ]
```

`start_usd` is what an account must have paid in total, or hold now, before
it may have a key at this provider. `target_usd` is what a wallet is topped
up to. With the default `concurrency` of 1, it is also the largest single
request a topped-up account can make.
`max_credit_usd` caps the credit line earned at this provider.
`premium_percent` is our markup over the provider's price.

## Funding

Each connect adds a wallet, named:

- `Lexe` for a Lexe wallet.
- For NWC, after the `wallet` picked: `Coinos`, `Alby`, `Alby Go`, `Zeus` or
  `Primal`.
- For `other`, or a pasted string without `wallet`, after its first relay's
  host (`Coinos`, `Alby` or `Primal`), else `NWC wallet`.

If another wallet has that name, the new one gets ` 2`, ` 3` and so on. A
new Lexe wallet goes first in the draw order, and any other last.

Reconnecting a Lexe wallet that is already connected replaces it, keeping
its place and name. An NWC connection has no identity, so connecting one
always adds a wallet.

The site may be served at several origins (`LEXE_ROUTER_BASE_URL`). A flow
returns the user to the one its start request was made to, by its `Host`
header, or to the first configured if `Host` names none of them. The wallet
names the connection after that origin's brand, `bitcoinrouter.ai` or
`lexerouter.ai`, and our payments from it and refunds to it are noted with
the same name, wherever they are made (see DESIGN.md "Brands").

At five wallets, the start endpoints and `POST /api/funding/nwc` answer 409
`too_many_wallets`. A Lexe start while a Lexe wallet is connected may be a
reconnect, so it is exempt. A flow that completes at the limit anyway is
rejected unless it reconnects a wallet.

### `POST /api/funding/lexe/start` *auth*

```json
{ "delivery": "post" | "redirect" }
```

200 `{ "flow_id": "...", "connection_string": "https://lexe.app/connect?..." }`

The frontend renders the string as a QR code and an "Open in Lexe" link,
then polls the flow. Flows expire after ten minutes. `delivery` sets where
the wallet sends its response:

- `post` (desktop): the wallet POSTs it to the callback below.
- `redirect` (iOS, iPadOS, Android): the wallet opens
  `/connect/return?flow=...&response=...` on this site, which relays it to
  the redirect endpoint below, so the user ends up back here.

The request asks the wallet for `read_info`, `read_payments` and `spend`,
or under fake payments for `read_info` alone (see [Fake money](#fake-money)).

### `GET /api/funding/lexe/flows/{flow_id}` *auth*

200 `{ "state": "pending" | "granted" | "rejected" | "expired", "detail": null | "..." }`,
or 404 for an unknown flow. On `granted`, the wallet is already added, so
refetch `/api/me`.

### `POST /api/funding/lexe/callback/{flow_id}`

The Lexe wallet calls this for `post` flows, by LexeConnect `post_url`
delivery. The body is the opaque response blob. 200 on accept, 400
otherwise.

### `POST /api/funding/lexe/redirect/{flow_id}`

```json
{ "url": "https://bitcoinrouter.ai/connect/return?flow=...&response=..." }
```

The `/connect/return` page calls this for `redirect` flows with the URL the
wallet opened, by LexeConnect `redirect_uri` delivery. The response only
decrypts with the flow's key, so no session is needed, and this works in
whichever browser the phone opens. 200 with the flow's final
`{ "state", "detail" }`, as from `GET /api/funding/lexe/flows/{flow_id}`.
400 if the response is invalid or the flow already finished, 404 if it
expired or is unknown.

### `POST /api/funding/settle-debt` *auth*

```json
{ "account_id": 7, "funding_id": null | 3 }
```

Pay what one of the account's wallets owes on account 7, crediting
account 7. The payment comes from the wallet `funding_id`, by default the
one that owes it (the debt's `funding_id`). The amount is the debt, clamped
to ten cents to $100. So a debt under ten cents is slightly overpaid,
leaving account 7 a small positive balance, and a larger one takes several
payments.

202 `{ "payment_id": 12 }`, then poll `GET /api/payments/{id}`. 409
`no_funding` without a wallet. 404 if account 7 isn't in `wallet_debts` or
`funding_id` isn't one of the account's wallets. 409 `payment_pending`
while account 7 has a pull in flight, 409 `funding_changed` if the wallet
was removed meanwhile.

### `POST /api/funding/nwc` *auth*

`{ "uri": "nostr+walletconnect://...", "wallet": "zeus" }`: connect a
pasted NWC connection string. The string may omit the `//`, and has one or
more `relay` params. The optional `wallet` takes any value `start` does,
and names the wallet. We fetch the wallet's info event, require NIP-44
(`nip44_v2`), and call `get_info`, which must allow `pay_invoice` on
mainnet, or under fake payments need only answer (see
[Fake money](#fake-money)). 204 once added. 400 with a plain message for a
malformed string, a NIP-04-only or unreachable wallet, no `pay_invoice`, a
relay that isn't `wss://`, or any other field in the body. Shares the
LexeConnect start rate limit.

### `POST /api/funding/nwc/start` *auth*

`{ "wallet": "coinos" | "alby" | "alby_go" | "zeus" | "primal" | "other" }`:
start a one-click NWC-08 flow. We generate the connection's key and keep it.
Flows expire after ten minutes. 400 for any other field in the body.

- `coinos`, `alby`: 200 `{ "flow_id": "...", "url": "https://coinos.io/apps/new?..." }`.
  Open `url` in a tab with no opener, which the wallet's page could
  otherwise navigate. On approval, that page redirects its tab to
  `/connect/nwc/return?flow=<id>` with the wallet's pubkey and relay as
  query params (`wallet_pubkey` and `relay_url` per NWC-08, `pubkey` and
  `relay` from Alby): report them with `complete`. A decline tells us
  nothing, so poll the flow until it expires.
- any other wallet: 200 `{ "flow_id": "...", "uri": "nostr+walletauth://..." }`.
  Show `uri` as a QR code and a link. The wallet answers on our relay, so
  poll the flow.

### `GET /api/funding/nwc/flows/{flow_id}` *auth*

As `GET /api/funding/lexe/flows/{flow_id}`.

### `POST /api/funding/nwc/flows/{flow_id}/complete` *auth*

`{ "wallet_pubkey": "<hex>", "relay_url": "wss://...", "state": "..." | null }`:
report the HTTP flow's approval. `state` must match when present. Coinos and
Alby omit it. We verify the wallet as `POST /api/funding/nwc` does, then
store it. 200 with the flow's `{ "state", "detail" }`, `granted` or
`rejected`. A repeated report gets the flow's current state. 400 for a wrong
`state` or a malformed body, 404 for an unknown or expired flow.

### `PATCH /api/funding/{id}` *auth*

`{ "name": "Savings" }`: rename a wallet. Trimmed, 1 to 40 characters, else
400. 204, or 404 if it isn't one of the account's wallets.

### `PUT /api/funding/order` *auth*

`{ "ids": [3, 1, 4] }`: set the draw order, first to pull from first. 204.
409 `funding_changed` unless `ids` lists each of the account's wallets
exactly once. After a 409, refetch `/api/me`.

### `DELETE /api/funding/{id}` *auth*

Remove a wallet. 204, or 404 if it isn't one of the account's wallets. 409
`payment_pending` while a payment draws from it, including one for another
account's debt. 409 `debt_outstanding` if the account balance is negative
and this is its only `active` wallet. An inactive wallet can always go.

Removing the last `active` wallet ends credit, so keys are capped at current
usage. The wallet's `refundable_usd` stops being refundable, for good if
it's NWC, or until the same wallet reconnects if it's Lexe.

## Top-ups, invoices and payments

A payment is a pull, which one of the account's wallets pays when we ask
it, or an invoice, which we show the user to pay from any wallet. Unpaid
invoices cost nobody anything, so they never hold up a pull.

### `POST /api/topup` *auth*

```json
{ "provider": null | "tinfoil", "funding_id": null | 3 }
```

Pull from the wallet `funding_id`, by default the first `active` one, else
the first. The pull brings headroom up to the target, counting `provider`
(the provider of a key about to be minted) toward it. Settling the pull
reactivates the paying wallet, so it also counts the credit the account
will have then.

400 if headroom is already at the target, unless the wallet isn't `active`,
in which case the pull is ten cents, to reactivate it. The user never picks
the amount, so sending `amount_usd` is 400 "Payments are sized to your
buffer", and 400 if `provider` isn't enabled. 202 `{ "payment_id": 7 }`.
409 `account_paused` while paused, 409 `no_funding` without a wallet, 404
if `funding_id` isn't one of the account's wallets, 409 `payment_pending`
while another pull is in flight, 409 `funding_changed` if the wallet was
removed meanwhile.

### `POST /api/invoices` *auth*

```json
{ "amount_usd": null | 1.0, "provider": null | "tinfoil" }
```

Create an invoice for the user to pay from any Lightning wallet, noted
with the name of the brand of the origin the request was made to. A `null`
amount means whatever brings headroom up to the provider's `start_usd`,
while the account has neither paid nor holds that much, and otherwise up to
the target with `provider` counted, at least ten cents. So an account that
has paid nothing gets the provider's start. Unlike a pull, paying an
invoice reactivates no wallet, so this counts only the credit the account
has now.

400 if the amount is outside ten cents to $1,000, or `provider` isn't
enabled. 409 `balance_cap` if paying it, on top of the account's other
unpaid, unexpired invoices, would take the balance past $1,000, counting a
debt as zero. A `null` amount stops short of that instead, and is 409 once
under ten cents of room is left.

```json
InvoiceInfo = {
  "payment_id": 7,
  "number": 1,
  "invoice": "lnbc...",
  "amount_usd": 1.00,
  "amount_sats": 893,
  "expires_at": 1760000600000
}
```

201 with a new invoice, or 200 with a pending one for the same amount that
has at least two minutes left, so a double click doesn't make two. 409
`too_many_invoices` while the account has three unexpired pending ones.
Invoices expire after ten minutes. We credit an invoice within seconds of
payment, so poll `GET /api/payments/{id}` until it leaves `pending`. What an
invoice pays is non-refundable.

### `GET /api/payments/{id}` *auth*

One of the account's payments, or one its wallet made to settle another
account's debt.

```json
{
  "id": 7,
  "number": 3,
  "kind": "pull" | "invoice",
  "amount_usd": 4.00,
  "amount_sats": 3571,
  "state": "pending" | "settled" | "failed" | "expired",
  "error": null | "...",
  "invoice": "lnbc...",
  "wallet_name": null | "Lexe",
  "created_at": 1760000000000,
  "expires_at": 1760000600000,
  "settled_at": null | 1760000030000
}
```

404 unless the payment is the account's, or one its wallet made for another
account's debt. `number` counts the account's payments from 1, and the
payment's invoice says "Payment 3". `wallet_name` is the wallet it was drawn
from, removed ones included. It is `null` for an invoice, and for a payment
from another account's wallet settling this account's debt. `expires_at` is
when its invoice expires. An unpaid invoice turns `expired` some minutes
later.

### `DELETE /api/payments/{id}` *auth*

Cancel one of the account's unpaid invoices, so it stops counting toward
the prepaid cap. 204. 404 unless it is the account's, pending and
unexpired. The invoice stays payable on our node until it expires, and a
payment that lands anyway still credits the account.

## Pausing and refunds

What we pull from a wallet is a prepayment for inference, not a balance to
withdraw. While the account is paused, the unspent part can go back to the
wallets it came from, all of it at once. What an invoice or a credit paid
can't. See DESIGN.md "Refunds".

### `POST /api/pause` *auth*

Pause the account. While it is paused:

- Every key is capped at its usage and paused, with `paused_reason`
  `account_paused`.
- There is no credit.
- Nothing is pulled but debt, which is pulled right away.
- Creating keys and `POST /api/topup` answer 409 `account_paused`.
- Invoices, wallet changes and refunds work as usual.

204, also if already paused.

### `POST /api/resume` *auth*

Lift the pause. The keys resume, credit returns, and a refill is pulled if
headroom is below half the target. 204, also if not paused. 409
`refund_pending` while a refund is in flight.

### `POST /api/refund` *auth*

Refund the paused account. This first takes a final usage reading of every
key, as revoking one does, so a turn in flight is charged first. If a
provider can't be read, the request fails, to be retried. Then each wallet
with a `refundable_usd` gets one payment of that amount, in sats at today's
rate, less our node's Lightning fee. A wallet with under a cent to refund is
skipped, and that amount stays spendable.

```json
{
  "refunds": [ RefundInfo ],     // pending, paid in the background
  "errors": [ { "funding_id": 3, "wallet_name": "Coinos", "error": "..." } ]
}
```

202. `errors` lists the wallets that couldn't say where to send their
refund. They get no refund, and each gets a `refund_failed` event.

409 `not_paused`, and 409 `refund_pending` while a refund is in flight. A
pull in flight would settle after the refund was sized, so it is 409
`payment_pending`. 409 `nothing_to_refund` if there is nothing to refund.

Poll `GET /api/refunds/{id}` until it leaves `pending`, which it does once
our node says whether it was sent. If our node never accepts it, it is tried
again for up to an hour, then fails with the reason. A failed refund changes
nothing, so the user can try again.

Usage charged while a refund is in flight still spends what it is sending,
so the balance may end a little negative. That is debt, pulled as any other.

### `GET /api/refunds/{id}` *auth*

One of the account's refunds, else 404.

```json
RefundInfo = {
  "id": 2,
  "number": 1,
  "wallet_name": null | "Lexe",
  "amount_usd": 4.20,
  "amount_sats": 4179,
  "fee_sats": 21,
  "state": "pending" | "settled" | "failed",
  "error": null | "Payment failed",
  "created_at": 1760000000000,
  "settled_at": null | 1760000030000
}
```

`number` counts the account's refunds from 1, and the wallet shows
"Refund 1". `amount_usd` comes off the balance when the refund settles.
`amount_sats` is what the wallet receives, after `fee_sats`. `wallet_name`
is the wallet refunded to, removed ones included.

## Keys

A key is of one of two kinds, counted apart:

- `api`: created by the user on the dashboard, which shows its secret once.
  It may have a name. At most ten live across providers, or one without a
  wallet.
- `chat`: minted by a logged-in browser for the Chat page, one per browser
  and provider. Never shown or named. At most five live per provider, or one
  without a wallet. A new one first revokes the account's least recently
  used chat keys at its provider to make room. A chat key is revoked 90
  days after it was minted, and when the account's login changes
  (`PUT /api/me/password`, `POST /api/me/login-code`), in the background.
  The browser then mints a new one when its next message is refused.

Both kinds are capped, metered, paused and resumed alike.

### `POST /api/keys` *auth*

```json
{ "provider": "tinfoil", "name": null | "laptop", "kind": "api" | "chat" }
```

201 `{ "key": KeyInfo, "secret": "tk_..." }`. The secret is returned exactly
once. `kind` defaults to `api`. `name` is an optional label of up to 40
characters, for an `api` key only. 400 if `provider` isn't enabled, or with
a `name` for a `chat` key. 429 past ten `chat` keys a minute. The
preconditions are checked in this order, each a 409:

1. `sponsor` for a sponsor, whose users' keys come from the sponsor API.
   See "Sponsors".
2. `account_paused` while the account is paused. See "Pausing and refunds".
3. `wallet_has_debt` while another account funded by one of its wallets
   owes money. See `wallet_debts`.
4. `key_limit` for an `api` key, at the limit above. A `chat` key makes
   room instead, and the request fails if revoking one does.
5. `topup_required` unless headroom is above `reserve_usd`, and the
   account has paid the provider's `start_usd` in total or holds it now.
   The frontend then offers `POST /api/topup`, or `POST /api/invoices`
   without a wallet.

`reserve_usd` and the target here count the key's provider. The key is
capped at what headroom allows above the reserve, and a wallet account is
reconciled right away, so a refill to a higher target starts at once.

```json
KeyInfo = {
  "id": 3,
  "kind": "api" | "chat",
  "name": null | "laptop",
  "provider": "tinfoil",
  "provider_name": "Tinfoil",
  "tier": "private",
  "base_url": "https://inference.tinfoil.sh/v1",
  "cap_usd": 4.00,
  "usage_usd": 0.12,
  "paused_reason": null | "exhausted" | "account_paused" | "provider_error",
  "created_at": 1760000000000
}
```

`cap_usd` and `usage_usd` include the premium, so they are in the same
dollars as `balance_usd` and `headroom_usd`. `paused_reason` is:

- `exhausted` while headroom is at or below `reserve_usd`. Pair it with the
  `funding` statuses to choose the hint.
- `account_paused` while the account is paused.
- `provider_error` once the provider has rejected the key for good. A key
  paused already keeps the reason it has.
- `held`, only for a sponsored account's key, as admins see it, while its
  sponsor holds the account (see "Sponsors").
- `usage_backwards`, only for a sponsored account's key, once its usage
  went backwards at the provider: frozen at its usage until an admin
  looks.

### `GET /api/keys/quote?provider=<id>&kind=<kind>` *auth*

200 `{ "payment_usd": 0.30, "pull_usd": 0.0 }`, which the frontend shows
before the user commits.

- `payment_usd`: what `POST /api/keys` at `provider` needs paid first, or 0
  if nothing. With a wallet, this is the `POST /api/topup` refill with
  `provider` counted. Without one, it is what `POST /api/invoices` without
  an amount invoices: up to `start_usd` if the account never paid that
  much, else up to the target.
- `pull_usd`: 0 if `payment_usd` isn't. Otherwise what minting the key pulls
  from the wallet right after: up to the target with `provider` counted, if
  headroom is below half of it. 0 while paused, without an `active` wallet,
  while `wallet_debts` isn't empty, or while a pull is pending.

`kind` defaults to `api`. 400 if the provider is not enabled. 409
`key_limit` if the account can't create another `api` key, as for
`POST /api/keys`. A `chat` quote is never 409 `key_limit`.

### `PATCH /api/keys/{id}` *auth*

`{ "name": "laptop" | null }`: rename an `api` key. Trimmed, at most 40
characters, else 400. Blank or null clears the name. 204, or 404 if it
isn't one of the account's live `api` keys.

### `DELETE /api/keys/{id}` *auth*

Revoke a key of either kind at the provider and locally. A browser revokes
its own chat keys this way when the user signs out. First the key's cap is
frozen and a final usage reading taken, so nothing used since the last poll
goes unbilled. 204. 404 unless it's one of the account's live keys. 5xx,
with the key left live, if the provider can't be reached.

## Events

```json
EventInfo = {
  "id": 11,
  "kind": "pull_failed" | "funding_revoked" | "key_paused" | "key_resumed"
        | "overshoot_debt" | "wallet_reused" | "payment_settled"
        | "funding_unresponsive" | "funding_restored" | "wallet_debt_paid"
        | "account_paused" | "account_resumed" | "refund_settled"
        | "refund_failed" | "sponsor_updated" | "wallet_login_added"
        | "wallet_login_removed" | "password_added" | "password_changed"
        | "password_removed" | "password_reset" | "email_set"
        | "email_removed" | "username_set" | "username_removed",
  "detail": "...",
  "wallet_name": null | "Coinos",
  "created_at": 1760000000000
}
```

The frontend maps each `kind` to a fixed remediation hint.

`pull_failed` and `funding_revoked` go to the account whose wallet failed
to pay, even when the payment was for another account's debt. A payment of
another account's debt is also recorded there, as `wallet_debt_paid`.
`payment_settled` goes to the account credited.

`wallet_name` names the wallet the event concerns, removed ones included.
It is set for `pull_failed`, `funding_revoked`, `funding_unresponsive`,
`funding_restored`, `wallet_debt_paid`, `wallet_reused`, `refund_settled`
and `refund_failed`, and `null` otherwise.

`refund_settled`'s `detail` reads "Refunded $4.20", and `refund_failed`'s is
the error. `account_paused` and `account_resumed` say what the change
means for the keys. `sponsor_updated` goes to an account an admin makes a
sponsor, or whose name or limits it changes, and its `detail` says what
they are.

`wallet_login_added`, `wallet_login_removed`, `password_added`,
`password_changed`, `password_removed`, `password_reset`, `email_set`,
`email_removed`, `username_set` and `username_removed` record changes to
the account's logins, so an owner notices a stranger's.
`detail` names the wallet login, or says what happened to the password,
address or username, never naming the address or username.

## History

Full history, newest first, a page at a time. Pass a page's `next_before`
as `before` to get the next one. `next_before` is set whenever the page is
full, so the next page may be empty. `null` means there is no more. `limit`
is clamped to 1 to its maximum.

```json
Page<T, C> = { "items": [ T ], "next_before": null | C }
```

### `GET /api/payments?before=<id>&limit=<n>` *auth*

200 `Page<PaymentInfo, id>`: payments in all states, with ids below
`before`. `limit` defaults to 50, at most 200.

### `GET /api/usage?before=<day>&limit=<n>` *auth*

200 `Page<UsageInfo, day>`: usage charges summed per UTC day and key. A page
covers the `limit` latest days with usage before `before` (`YYYY-MM-DD`),
by key within a day. `limit` counts days, defaulting to 30, at most 365.
400 on a malformed `before`.

```json
UsageInfo = {
  "day": "2026-10-17",
  "key_id": 3,
  "key_name": null | "laptop",
  "provider": "tinfoil",
  "charged_usd": 0.04
}
```

`charged_usd` includes the premium, like `balance_usd`. Revoked keys are
included. A `chat` key's `key_name` is `"Chat"`, here and in the CSV.

### `GET /api/events?before=<id>&limit=<n>` *auth*

200 `Page<EventInfo, id>`: events with ids below `before`, kept for a year.
`limit` defaults to 50, at most 200.

### `GET /api/payments.csv` and `GET /api/usage.csv` *auth*

200 `text/csv` with `Content-Disposition: attachment`: the full history,
unpaginated, in the same order, with a header row. Timestamps are ISO 8601
in UTC. The files are `<brand>-payments.csv` and `<brand>-usage.csv`, by
the brand of the origin the request was made to: `bitcoinrouter` or
`lexerouter`.

```
id,created_at_iso,amount_usd,amount_sats,state,settled_at_iso,error,wallet_name,number
day,key_id,key_name,provider,charged_usd
```

## Sponsors

A sponsor is an account that creates accounts for its own users and is
charged for their usage, as lexe.bot does for its users. An admin makes
an account a sponsor (see "Admin"). A sponsored account has no login,
wallet or funding of its own: nobody but its sponsor acts on it, through
the routes below. See DESIGN.md "Sponsors".

- **Auth**: a sponsor token, `Authorization: Bearer lrs_...`, or the
  sponsor's own session. 401 without either, or with a token that is
  unknown or revoked. 404 to any other account, as the admin routes are,
  and for an account or key the caller doesn't sponsor. 429 past 1,200
  calls a minute.
- **Money**: integer micro-dollars (`*_micro`), at list price: what we
  would charge a user, our premium included. Unlike the float dollars
  elsewhere, they add up exactly in a sponsor's books.
- **Postpaid**: the usage of a sponsored account's keys is charged to its
  sponsor's ledger, in full, whatever the sponsor's balance, which may go
  below zero. Nothing is pulled from a wallet, and nothing of the prepaid
  money logic (start, target, credit, reserve, debt, refunds, pauses for
  balance) applies to a sponsor or its accounts. A sponsor has no keys of
  its own, and sponsors an account for itself instead. So its session is
  409 `sponsor` on every route that funds, tops up, invoices, pauses,
  resumes, refunds or mints for itself: `POST /api/keys`, `/api/topup`,
  `/api/invoices`, `/api/funding/lexe/start`, `/api/funding/nwc`,
  `/api/funding/nwc/start`, `/api/funding/nwc/flows/{flow_id}/complete`,
  `/api/funding/settle-debt`, `/api/funding/fake`, `/api/pause`,
  `/api/resume` and `/api/refund`.
- **Limits**: what a sponsor's keys may still spend is bounded twice, by
  limits an admin sets per sponsor. What a key has open is what its
  provider lets it spend beyond its usage: the cap the provider enforces,
  after its rounding and floor, at list price, rounded up, less its usage.
  At Tinfoil, which takes caps in cents, that cap is rounded up to the
  cent, and at least a cent; a held key's is its usage, rounded so. Until
  the provider takes a new cap, the one it took last counts, if larger. A
  key may have at most `key_open_limit_usd` open (default $100), and the
  sponsor's live keys at most `open_limit_usd` in all (default $1,000). A
  mint, a cap change or a release that would raise what's open past either
  is 409 `sponsor_limit`; one that lowers it always passes. What can
  raise what's open is checked one at a time per sponsor, and a mint at
  the provider counts until its key is in; nothing else, a lowering, a
  hold or a revocation included, waits for another account's changes.
- **503** `provider_unavailable`: the provider couldn't be reached. What
  was asked is stored, and the sweep pushes it within a minute.

### Tokens

With the sponsor's session only, which a token can't stand in for (401),
so that a token can't make more. They share the sponsor's rate limit.

- `POST /api/sponsor/tokens` `{ "name": "prod" }`: 201
  `{ "token": SponsorToken, "secret": "lrs_<64 hex>" }`. The secret is
  returned once, and stored as its sha256. 400 for a blank name or one
  over 40 characters, 409 `token_limit` at ten live tokens.
- `GET /api/sponsor/tokens`: 200 `[ SponsorToken ]`, the live ones, oldest
  first.
- `DELETE /api/sponsor/tokens/{id}`: 204, after which the token is 401. 404
  unless it is one of the sponsor's live tokens.

```json
SponsorToken = {
  "id": 1,
  "name": "prod",
  "created_at": 1760000000000,
  "last_used_at": null | 1760000000000   // to the minute
}
```

### `POST /api/sponsor/accounts`

```json
{ "reference": "42" }
```

The account the sponsor names `reference`, its own name for it, such as
its account number: 1 to 64 of `A-Z`, `a-z`, `0-9`, `_`, `.` and `-`, else
400. 201 with a new account, or 200 with the one the sponsor already has,
so a retry is safe. 409 `account_deleted` once the sponsor has deleted
it, or while it is deleting it: a reference is never reused.

```json
SponsoredAccount = {
  "reference": "42",
  "account_id": 1234,                 // ours
  "held_at": null | 1760000000000,
  "deleting_at": null | 1760000000000,
  "created_at": 1760000000000,
  "keys": [ SponsoredKey ]            // live, oldest first
}
```

### `GET /api/sponsor/accounts/{reference}`

200 `SponsoredAccount`.

### `PUT /api/sponsor/accounts/{reference}/hold`

`{ "hold": true }` holds the account: each key of it is capped at its
usage, and marked `held`, and minting is 409 `account_held`. The cap stays
where it froze, though requests admitted before take the usage past it,
and a push that fails retries it, until a release thaws the key. A second
hold keeps the first's `held_at`. `{ "hold": false }` releases it, and its
keys' caps are the sponsor's again, but a revoking key's, unless that
raises what's open past the sponsor's limits: 409 `sponsor_limit`, or the
account is being deleted: 409 `account_deleting`. 200 `SponsoredAccount`,
once the provider has every cap, or no longer has the key. 503
`provider_unavailable` while a provider can't be reached or isn't enabled
here, with the hold stored and pushed by the sweep. A cap change while
held is kept for the release. A hold that lands while a mint is at the
provider waits for it, then caps the new key.

A hold bites as a cap change does (below).

### `DELETE /api/sponsor/accounts/{reference}`

Holds the account, sets `deleting_at`, and revokes each key of it as
`DELETE /api/sponsor/accounts/{reference}/keys/{id}` does. 202
`SponsoredAccount`. Once the last key is gone, by default about 30 minutes
after the delete, the account is deleted, and 404 to every route here.
Until then it shows as it is, minting and releasing it are 409
`account_deleting`, and deleting it again changes nothing. Its usage stays
in the feed. 503 `provider_unavailable` if a cap couldn't be pushed,
as for a hold.

### `POST /api/sponsor/accounts/{reference}/keys`

```json
{ "provider": "tinfoil", "name": "cloud", "cap_micro": 5000000 }
```

Mints a key, `name`d 1 to 40 characters, unique among the account's
live keys. 201 `{ "key": SponsoredKey, "secret": "tk_..." }`. The secret
is returned once. Our name for it at the provider is `br-<account_id>-<ms>`:
neither the reference nor the key's name reaches the provider. 400 if the
provider isn't enabled, for a blank or long name, or a cap under the
provider's least (below). The preconditions are checked in this order,
each a 409: `account_deleting`, `account_held`, `key_exists` (a live key
has the name, revoking ones included), `key_limit` (ten live keys), and
`sponsor_limit`.

```json
SponsoredKey = {
  "id": 7,
  "name": "cloud",
  "provider": "tinfoil",
  "base_url": null | "https://inference.tinfoil.sh/v1",
  "cap_micro": 5000000,
  "enforced_cap_micro": 5000000,     // the cap the provider enforces
  "usage_micro": 1070000,            // as of its last reading
  "state": "live" | "held" | "revoking" | "provider_error" | "provider_off",
  "created_at": 1760000000000
}
```

`cap_micro` is the most the key may spend over its life, at list price:
to give a user what they have left, set it to `usage_micro` plus that.
It is at least the provider's least cap, at list price: 10700 at Tinfoil,
a cent and our 7%. Under it is 400, the message naming the least cap.
The provider stops the key there. Caps are per key, as the provider
keeps them: a user with several keys can spend what they have left once
at each, unless the sponsor splits it between them or lowers the caps as
the feed comes in.

`enforced_cap_micro` is the cap the provider enforces for the key, at
list price, as the sponsor's limits count it: `cap_micro` after the
provider's rounding and floor (at Tinfoil, up to the cent, and at least a
cent), or while the key is held or revoking, where it froze. Until the
provider takes a new cap, as while it can't be reached, it is the larger
of that and the cap the provider took last. So the key may still spend
`enforced_cap_micro` less `usage_micro`, give or take the softness below.

The cap is soft, as the provider's is:

- Tinfoil admits a request while the key's recorded usage is under its
  cap, so a request in flight when the cap is reached finishes and is
  charged in full: a key overshoots by what its concurrent requests cost.
- Tinfoil takes caps in cents, rounded up, and reads 0 as no cap, so
  it is never sent less than a cent. Thus a key may spend under a cent
  past its cap, and a held key that has spent nothing can spend a cent.
- The request that sets a cap returns once Tinfoil has taken it, which
  took 0.3 seconds on staging, and a hold of five keys at Tinfoil and
  TrustedRouter 0.47. How soon Tinfoil then refuses a request
  isn't measured yet; it documents that its check against the cap trails
  its usage counter by a few seconds.

`state` is `held` while the account is held; `revoking` once the sponsor
revoked it; `provider_error` once the provider rejected the key for good,
or no longer has it, or its usage there went backwards, when the usage
we last read stands and the key is frozen at it until an admin looks; and
`provider_off` while its provider isn't enabled here, when nothing caps
it, reads its usage or revokes it, `base_url` is `null` and `usage_micro`
is at cost. A view lists every live key, whatever its state.

### `PUT /api/sponsor/accounts/{reference}/keys/{id}/cap`

`{ "cap_micro": 2000000 }`: raises or lowers the key's cap, below its
usage too, which refuses it. 200 `SponsoredKey`, once the provider has
it. 400 for a cap under the provider's least, 409 `sponsor_limit`, and
409 `key_revoking` once the key is revoking.

### `DELETE /api/sponsor/accounts/{reference}/keys/{id}`

Revokes the key. At once, it is `revoking`, and capped at its usage, so
that the provider admits nothing new; nothing raises or releases it
again. Requests admitted before go on, and the provider books each only
once it ends, so the key stays at the provider, read at least every
minute, for `LEXE_ROUTER_SPONSOR_REVOKE_SETTLE_SECS` (default 30
minutes). Then, at the next minute's sweep, a final reading is charged
and the key is deleted at the provider. So the usage the provider books
within the settle time of the revoking is charged, and nothing it books
after: a request still running then is never charged. As the frozen cap
admits nothing new, what goes uncharged is at most what requests
admitted before the revoking can cost. Neither Tinfoil nor TrustedRouter
publishes a limit on how long a request may run. 202 `SponsoredKey`;
revoking it again changes nothing, nor its time. 503
`provider_unavailable` if its cap couldn't be pushed, which the sweep
does, still revoking. Tinfoil may go on serving a deleted key for a
while, and what it spends past the final reading is never charged; the
cap, frozen 30 minutes before, admits nothing by then.

### `GET /api/sponsor/usage?after=<id>&limit=<n>`

The usage feed, which the sponsor converts into its own users' credits:
its usage charges for its accounts' keys after the entry `after`
(default 0), oldest first, at most `limit` (default and at most 1,000,
clamped to at least 1).

```json
{
  "entries": [ {
    "id": 81,                        // the ledger entry's
    "reference": "42",
    "key_id": 7,
    "key_name": "cloud",
    "provider": "tinfoil",
    "charged_micro": 1070,           // positive: a charge
    "at": 1760000000000
  } ],
  "next_after": 81
}
```

`next_after` is the last entry's id, or `after` if there is none: pass it
as the next call's `after`. Ids increase in the order entries commit, as
the database has one writer at a time, so paging this way repeats and
skips no entry, however many are written between calls.

An entry appears when we read the key's usage at the provider, which we do
for all of a provider's sponsored keys at once, every minute. Tinfoil
counts a request within a few seconds of its end, so an entry trails the
request it charges by up to about 70 seconds. How far
behind never changes what a key may spend, which its cap bounds.
