# Your backend

## The proxy

Your page calls your backend, and your backend forwards those calls to Engine with the token of your key. Mount it **before** any body parser: it reads the body itself.

```js
// Your backend for the SDK path: the Engine proxy, so the browser carries no token. Node 20.3+.
// Mount it BEFORE any body parser:
//   const engine = engineProxyHandler({ session })
//   if (req.url.startsWith('/engine/')) return engine(req, res)
import { createTokenSource, createEngineProxy, ownsAll } from '@neurologyca/capture-server'
import { toNodeListener } from '@neurologyca/capture-server/node'

/**
 * YOUR app's session: signing in and both ownership checks are yours (ownsAll checks every id a route carries).
 * `req` is a Fetch `Request`, not an Express `req`: there is no `req.session`. Read your session cookie from
 * `req.headers.get('cookie')` and look it up in your session store.
 * @typedef {object} YourSession
 * @property {(req: Request) => Promise<boolean>} signedIn
 * @property {(req: Request, userProtocolId: string, protocolMechanicId: string | null) => Promise<boolean>} ownsEnrolment
 * @property {(req: Request, userId: string) => Promise<boolean>} isUser
 */

/** @param {{ engineBase?: string, apiKey?: string, session: YourSession, fetch?: typeof fetch }} opts */
export function engineProxyHandler({ engineBase = process.env.ENGINE_BASE, apiKey = process.env.ENGINE_API_KEY, session: yourSession, fetch: fetchImpl }) {
  if (!engineBase || !apiKey) throw new Error('Set ENGINE_BASE and ENGINE_API_KEY in your backend environment')
  const tokens = createTokenSource({ baseUrl: engineBase, apiKey, fetch: fetchImpl }) // the key lives here and only here
  return toNodeListener(createEngineProxy({
    baseUrl: engineBase,
    tokens,
    mountPath: '/engine',
    fetch: fetchImpl,
    authorize: async (req, route) => (await yourSession.signedIn(req)) && ownsAll(route, {
      userProtocol: async (up, pm) => yourSession.ownsEnrolment(req, up, pm),
      user: async (userId) => yourSession.isUser(req, userId),
    }),
  }))
}
```

`createTokenSource` mints and caches the token; `createEngineProxy` only forwards the routes the SDK calls (below) and asks `authorize` for each request; `ownsAll` checks **every** id the route carries, the enrolment and the person.

`createEngineProxy` caps the request body at `maxBodyBytes`: 16 MiB by default from `capture-server` 0.12.0 (8 MiB before), and a body over the cap is refused with `413` `E_BODY_TOO_LARGE` before it reaches Engine. From 0.34.0 the SDK sends at most 3 MB of frames per batch, so whatever sits in front of your proxy needs a body limit of at least 4.5 MB, or 10 MB in front of an SDK before 0.34.0. The limits per platform, serverless functions among them, are in [Proxy by hand](/docs/api/proxy/).

## The 13 routes

The proxy forwards exactly these, and answers `404` for unknown routes and `405` for a disallowed method:

| # | Name | Method | Route |
| --- | --- | --- | --- |
| 1 | `protocol` | GET | `/user-protocols/{up}` |
| 2 | `plan` | GET | `/user-protocols/{up}/mechanics/{pm}` |
| 3 | `sessions` | GET | `/user-protocols/{up}/{pm}/sessions` |
| 4 | `baseline-get` | GET | `/users/{userId}/baseline` |
| 5 | `baseline-post` | POST | `/users/{userId}/baseline` |
| 6 | `stream` | GET | `/stream/{up}` |
| 7 | `context` | POST | `/user-protocols/{up}/{pm}/context` |
| 8 | `query` | PATCH | `/user-protocols/{up}/{pm}/query` |
| 9 | `frames` | POST | `/process-kpn-emo` |
| 10 | `results` | GET | `/results/{up}/{pm}` |
| 11 | `analyze-stream` | POST | `/analyze/stream` |
| 12 | `analyze` | POST | `/analyze` |
| 13 | `cancel` | POST | `/user-protocols/{up}/{pm}/cancel` |

Since 0.10.0 the proxy forwards `?captureId=` on `cancel`, and only there: with it, SDK 0.29.0 cancels only its own capture when it releases a recording or a replay; if another capture holds the position, Engine answers `200` with `cancelled: false` and `reason: other_capture_open` (`other_capture_open`) and leaves it alone. It forwards exactly one lower-case UUID; a malformed or repeated `captureId` is a `400 E_BAD_REQUEST` that never reaches Engine, and every other query is dropped, on every route. A live session still cancels without it.

Without `capture-server`, the same routes by hand: [Proxy by hand](/docs/api/proxy/).

## Your session in front of the proxy

`authorize` receives a Fetch `Request`: read your session cookie from `req.headers.get('cookie')`. No session: return `false`, and the proxy answers `403`. Use a cookie with `SameSite=Lax` or `Strict`; the proxy refuses a `Content-Type` or a `Sec-Fetch-Site` that does not fit. Serve the proxy on the page's origin when you can. On another origin it takes both halves: `cors: { origins: ['https://app.example.com'], credentials: true }` in `createEngineProxy` and `credentials: 'include'` in the client (since `@neurologyca/capture` 0.45.0; `capture-server` 0.20.1 also exposes `Retry-After` to that page): [A proxy on another origin](/docs/api/proxy/#a-proxy-on-another-origin).

## People and enrolments: createEngineAdmin

Your backend creates the person and enrols them, and keeps the pair (`userProtocolId`, `protocolMechanicId`) that the page needs:

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

const admin = createEngineAdmin({ baseUrl: process.env.ENGINE_BASE, apiKey: process.env.ENGINE_API_KEY })
const { externalId } = await admin.createUser({ name: 'your-user', narrative: { language: 'es' } }) // opaque UUID; narrative.language sets the interpretation language (default 'en')
const { userProtocolId } = await admin.enrol(externalId, protocolPid)
const next = await admin.getNextPosition(userProtocolId) // { userProtocolId, protocolMechanicId, … } or null
```

The proxy only accepts a `userId` that matches `^[A-Za-z0-9_-]{1,128}$`, so an email used as `externalId` gets a 404 on the baseline routes: keep the generated UUID. `createUser` refuses an `externalId` you pass that is not a UUID; to keep an identifier scheme you already have, opt in with `allowNonUuidExternalId: true`, and make it opaque (never an email or a name) and within that pattern.

`createEngineAdmin` is the same HTTP API from Node: each method is one documented Engine call. `deleteUser` is physical and irreversible.

The **interpretation's language** is set on the person, with `narrative.language` (default `en`) — not on `transcribe` (that only changes the transcript) and not on `/analyze`. Pass the UI language when you create or update the person (`createUser`/`updateUser`), or a capture in Spanish comes back interpreted in English. `audience` lives on the person too; see `narrative` and `CreateUserInput` in the [SDK reference](/docs/sdk/reference/).

**A protocol's kit in your backend.** `admin.buildTenantKit(protocolPid)` builds it (`kind`, `config`, `env`, `pending`, `notices`). Since `capture-server` 0.20.0 it covers Measurement too: a protocol whose catalogue entry says `interpreted: false` gets `kind: 'measurement'`, with `config` `{ engineBaseUrl, taxonomy: { contextId: MEASUREMENT_CONTEXT_ID } }` (`MEASUREMENT_CONTEXT_ID` is `'measurement'`, a filler the SDK does not send once Engine reports the protocol is not interpreted), `pending` with only the optional `env.ROLE`, and a notice saying there will be no interpretation: capture it with `triggerAnalysis: false`. Every other kit carries `kind: 'context'`. Branch on `kit.kind`, and resolve the kit before `admin.enrol`, so a kit that fails leaves no enrolment behind. `listProtocolLibrary()` says it too: `ProtocolSummary.interpreted` (the protocol's value, else its group's `group.interpreted`; `null` when the catalogue does not say). Against an Engine whose catalogue does not publish `interpreted`, Measurement still throws `E_KIT_NO_CONTEXT`: there, use the fixed configuration the console's Measurement kit carries ([Measurement](/docs/guides/measurement/#what-is-not-there-yet)). With `capture-server` 0.19.0 and earlier, `buildTenantKit` always throws `E_KIT_NO_CONTEXT` for Measurement.

## The upload receiver

For deferred, your backend also receives the recordings: `createUploadReceiver` with a storage (`localDiskStorage` on disk, or your own), `authorize`, `checkManifest` and `onComplete`. It has two handlers, both mounted before any body parser: `receiver.handler` for the uploads and `receiver.mediaHandler` for `/media/<captureId>/video`, the signed video the processing service downloads (without it, the service gets a 404 and the job fails with `E_DOWNLOAD_FAILED`, which is not retried). The example is in [Deferred (server-side)](/docs/sdk/deferred/#your-receiver). The retention of confirmed uploads is yours: `sweep` only deletes abandoned ones. The receiver starts no timers, so call `receiver.sweep()` yourself (for example every hour from your scheduler): it deletes unconfirmed uploads left untouched for `abandonedAfterMs` (72 h by default). `receiver.remove(captureId)` deletes a confirmed video once its job ends; a confirmed video never expires on its own ([Privacy](/docs/resources/privacy/)).

## Startup reports (optional)

With `startup.report.url` in the client ([On-device](/docs/sdk/on-device/#the-startup-screen)), the page sends a report of each startup: its stages and times, the device checks and how it ended. Without that option nothing leaves the page, and **DevLab mounts no receiver**: this section is only for your backend. Since `capture-server` 0.18.0, `createStartupReportReceiver` receives, validates and stores them, and `localDiskStartupReports` (from `@neurologyca/capture-server/node`) keeps them on a local disk, one process per directory; for several processes, implement `StartupReportStorage` on your own store. With capture 0.43.0 use `capture-server` 0.19.0 or later: the page sends schema 2 reports when they carry something schema 1 does not admit (mostly with `keepPrepared`: `prepared` on a baseline, `prepared.origin`, `kept`), and since 0.19.0 the receiver validates them as strictly as schema 1 and answers `400` to one that breaks the rules; before, it stored them marked `unvalidated`.

```js
// Your backend, optional (Node 20.3+): the receiver of the startup reports the page sends with startup.report.url.
// It stores data of the person's browser (stages, times, device checks and, by default, the user agent): your consent and
// privacy notice cover it. Mount it BEFORE any body parser:
//   if (req.url === '/startup-reports') return startupReports(req, res)
import { createStartupReportReceiver } from '@neurologyca/capture-server'
import { localDiskStartupReports, toNodeListener } from '@neurologyca/capture-server/node'

/**
 * @param {object} o
 * @param {string} o.dir a private directory for the reports (one process per directory)
 * @param {string[]} o.origins the exact origins of your pages, such as 'https://app.example.com'
 */
export function startupReportsHandler(o) {
  const reports = createStartupReportReceiver({
    storage: localDiskStartupReports({ dir: o.dir }),
    allowedOrigins: o.origins, // anonymous by design (sendBeacon carries no credential): another or no Origin answers 403
    onError: (_error) => console.error('startup reports: receiver error'), // never the body
  })
  // reports.read({ since }) returns the stored reports, one per startup; call reports.sweep() from your scheduler
  return { reports, listener: toNodeListener(reports.handler) }
}
```

- It stores **data of the person's browser**: the stages, the device checks and, unless the client passes `startup.includeUserAgent: false`, the user agent, plus the `context` pairs you add. Your consent and your privacy notice must cover it; the SDK does not ask for it.
- It is anonymous by design, because `sendBeacon` carries no credential: it requires `allowedOrigins` (an exact `scheme://host[:port]`; another or no `Origin` answers `403`), and `authorize(req)` is an optional extra gate. It accepts only `POST` (`405` otherwise), validates each report strictly (`400`), and bounds the size (64 KiB, `413`) and the rate (600 a minute in all, 60 per `clientKey`, `429`).
- It stores the validated report and its `receivedAt`, never a header, an address or the client key; 14 days and 100 MiB by default (`retentionMs`, `maxBytes`; a full store answers `507`). `reports.read({ since, until })` returns one report per startup; call `reports.sweep()` from your scheduler.
- Put the URL in your CSP's `connect-src` (`'self'` covers it on your own origin).

## Rotating the key

`createTokenSource` reads the key when it is created: after a rotation, restart (or redeploy) your backend with the new key. It mints once more after a `401`. By default `createEngineAdmin` and `createTokenSource` keep separate token caches; to share one, pass your `tokens` to `createEngineAdmin`. There is no credential rotation inside the packages: rotate in DevLab ([Keys](/docs/access/keys/)).

## The token and its scope

The token the proxy adds is your organization's developer token: it can reach the whole organization. In short, the boundary is your `authorize` with `ownsAll`: never let a request through without both checks.
