# Authentication

## API key and token

Your team has an API key. Your backend exchanges it for a **token** with `POST /token`, and sends the token as `Authorization: Bearer <token>` on every other request.

```bash
curl -s -X POST "$ENGINE/token" \
  -H "Content-Type: application/json" \
  -d '{"apiKey":"<your-api-key>"}'
```

```json
{ "token": "<jwt>", "expiresIn": 3600 }
```

`expiresIn` is in seconds. Read it from the response instead of assuming a value.

## With the SDK: no token in the browser

The recommended path: your page talks to your backend, and your backend's proxy adds the token. The browser never carries a key or a token, and your page creates the client without `getToken`. The token source mints with your key, caches the token and mints once more after a `401`; it reads the key when it is created, so after a rotation restart your backend. Build the proxy in [Your backend](/docs/sdk/backend/).

```js
import { createTokenSource } from '@neurologyca/capture-server'

const tokens = createTokenSource({ baseUrl: process.env.ENGINE_BASE, apiKey: process.env.ENGINE_API_KEY })
const { token, expiresAt } = await tokens.get() // what the proxy puts in Authorization; never send it to the page
```

## Keep the key on your server

- Anyone with the key can mint tokens for your organization. Treat the token as a secret too: it is not limited to one user or one capture (a [capture token](#a-token-for-one-capture) is).
- Without `@neurologyca/capture-server` (the HTTP API, or a proxy of your own), your backend mints the token, keeps it and puts it in the `Authorization` of its own calls to Engine, behind your own authentication; never hand it to the page. See [Proxy by hand](/docs/api/proxy/).

```js
// Your backend without @neurologyca/capture-server: it mints Engine's token with your key and keeps it on the server.
// The token goes in the Authorization of your proxy's calls to Engine, never to the page.
const ENGINE = process.env.ENGINE_BASE // the Engine URL of your kit
let cached = null // { token, expiresAt }
let minting = null // the request in flight: calls that arrive meanwhile share it instead of minting another token

export function engineToken(now = Date.now()) {
  if (cached && cached.expiresAt - 60_000 > now) return Promise.resolve(cached.token) // reuse it until a minute before it expires
  minting ??= mint(now).finally(() => { minting = null })
  return minting
}

async function mint(now) {
  const r = await fetch(`${ENGINE}/token`, {
    method: 'POST',
    headers: { 'content-type': 'application/json' },
    body: JSON.stringify({ apiKey: process.env.ENGINE_API_KEY }),
  })
  if (!r.ok) throw new Error(`POST /token answered ${r.status}`) // 401: the key is wrong, revoked or expired
  const { token, expiresIn } = await r.json()
  cached = { token, expiresAt: now + expiresIn * 1000 }
  return token
}
```

## Cache and renew

- `POST /token` is rate limited per client IP. Mint once and reuse the token until shortly before it expires; do not mint one per request.
- There is no refresh endpoint: when the token is about to expire, call `POST /token` again.

## Rotation and revocation

When a key is rotated or revoked, it stops minting new tokens at once, and a token minted from it is refused on its next request (`401`). Mint a new token with the new key. See [Keys: rotation, revocation and expiry](/docs/access/keys/) and the [access model](/docs/access/model/).

## Scopes

Each key has a scope, `admin` or `read_all`. A `read_all` key only reaches the users it created: their captures, results, interpretations, events and management (enrol, block, delete). It still lists and edits every user of the organization. See [Access model](/docs/access/model/).

## A token for one capture

`POST /token/capture` returns a token limited to one capture, for whoever sends a recording without needing your token: for example, the [processing service](/docs/sdk/processing/#the-token-url). Your backend calls it with its regular token (`Authorization: Bearer`) and the capture's three ids:

```json
{
  "userProtocolId": "00000000-0000-4000-8000-9ca46ec3ea86",
  "protocolMechanicId": "00000000-0000-4000-8000-c9d097234e8d",
  "captureId": "00000000-0000-4000-8000-07f0d35d38d2"
}
```

- It lasts 30 minutes (`expiresIn: 1800`). When it expires, request another one.
- It only allows sending that capture (`captureId`) of that mechanic: `POST …/context`, `POST /process-kpn-emo`, `GET …/sessions`, `POST …/cancel`, `GET /results/{userProtocolId}/{protocolMechanicId}`, `GET /user-protocols/{userProtocolId}`, `GET /user-protocols/{userProtocolId}/mechanics/{protocolMechanicId}`, `GET /user-protocols/{userProtocolId}/schema` and `GET /stream/{userProtocolId}`. On `POST …/context` and `POST …/cancel` you can leave `captureId` out: the token's is used. `POST /process-kpn-emo` must carry it, so pass the SDK the same `captureId`. With it, the stream only carries that mechanic's events and closes with `stream.end` and `reason: "token_expired"` when the token expires.
- Any other route, mechanic or capture, `POST /analyze` among them, answers `403` with `reason: "CAPTURE_TOKEN_SCOPE"`. A capture token cannot request another one. Rotating, revoking or deleting your key invalidates it at once.
- Its requests are limited per capture and per minute: 15 for `GET …/schema` and `POST …/context` together, 30 for `POST /process-kpn-emo` and 60 for the rest. Above that it answers `429` with `reason: "CAPTURE_TOKEN_RATE_LIMIT"` and a `Retry-After` header: nothing was processed, wait those seconds and repeat. A new token for the same `captureId` keeps the count. Your regular token has no such limit. Since `@neurologyca/capture` 0.37.0 the SDK waits that `Retry-After` and sends the same request again (at most 2 minutes at a time and 5 times in a row), with the warning `transport.rate-limited`; `cancel` does not wait. Earlier versions fail the capture.
- For everything else, your backend keeps using its regular token.

Today only the test environment's Engine has this route; production does not yet.

## Errors

| Status | When | Body |
| --- | --- | --- |
| `401` on `/token` | The key is malformed, unknown, revoked or expired, or your organization is suspended (the same answer in every case) | `{ "code": 401, "message": "Invalid credentials." }` |
| `401` elsewhere | Missing, expired or invalid token, or its key was rotated, revoked or has expired | Empty body, with a `WWW-Authenticate: Bearer` header |
| `429` on `/token` | Too many token requests from your IP | Empty body |

## In DevLab

- Your team's key is in [Your account](/account). Revealing it asks for your password, is limited to 5 times per hour and is recorded.
- The playground never asks for a token from the browser: `POST /token` and `POST /token/capture` don't go through DevLab. Your backend mints tokens.
