# Live sessions (https://orgasm.dev/docs/guides/live-sessions)

A live session is one person's camera stream, analysed as it arrives. Three parties take part: **your server**, which holds the secret key; **the person's device**, which films them and publishes; and **orgasm.dev**, which analyses the stream in an enclave and sends events.

```mermaid
sequenceDiagram
  participant Device as Device
  participant Server as Your server
  participant API as orgasm.dev
  participant Enclave as Enclave
  Device->>Device: capability = 32 random bytes
  Device->>Server: SHA-256(capability)
  Server->>API: POST /v1/live-sessions {consent, capabilityHash, inputs}
  API-->>Server: session: ingest, results.clientToken
  Server-->>Device: ingest, clientToken
  Device->>Enclave: GET attestation, check policy
  Device->>Enclave: WHIP offer, sealed with the capability
  Enclave-->>Device: answer, signed by the enclave
  Device->>Enclave: camera + microphone (WebRTC)
  API-->>Device: events (stream, clientToken)
  API-->>Server: events (stream or webhooks)
  Server->>API: DELETE /v1/live-sessions/{id}
```

## 1. On the device: a capability [#1-on-the-device-a-capability]

The device generates a secret only it will hold, and sends your server its hash.

```ts title="device.ts"
const bytes = crypto.getRandomValues(new Uint8Array(32));
const capability = btoa(String.fromCharCode(...bytes)).replace(/\+/g, '-').replace(/\//g, '_').replace(/=+$/, '');
const digest = await crypto.subtle.digest('SHA-256', bytes);
const capabilityHash = [...new Uint8Array(digest)].map((b) => b.toString(16).padStart(2, '0')).join('');
// keep `capability` on the device; send `capabilityHash` to your server
```

## 2. On your server: create the session [#2-on-your-server-create-the-session]

```ts title="server.ts"
const response = await fetch('https://orgasm.dev/v1/live-sessions', {
  method: 'POST',
  headers: {
    Authorization: `Bearer ${process.env.ORGASM_KEY}`,
    'Content-Type': 'application/json',
    'Idempotency-Key': crypto.randomUUID(),
  },
  body: JSON.stringify({
    consent: {
      subjectIsAdult: true, // only when your product verified it
      subjectConsented: true, // only when the person agreed to this analysis
      ageVerification: 'third_party_service',
      consentedAt: user.consentedAt,
      consentRecordId: user.consentRecordId,
    },
    capabilityHash, // from the device
    inputs: { audio: true, body: false },
    maxDurationS: 3600,
    retentionDays: 7,
    userReference, // your pseudonymous id for the person, never their email
    clientReferenceId: `booking_${booking.id}`,
  }),
});
const session = await response.json();
// hand session.ingest and session.results.clientToken to the device
```

`capabilityHash` is required with live keys. `subjectHint` (`woman` or `man`) is optional: give it only when the person told you ([subject](/docs/concepts/subject)).

`userReference` and `clientReferenceId` are optional too: your own pseudonymous id for the person and your id for the session. They come back on the session and on each of its charges, so your finance team sees what each user and session cost ([cost attribution](/docs/credits#cost-attribution)), and [`listLiveSessions`](/docs/api/live-sessions/listLiveSessions) filters by either.

The session starts in `starting` while analysis capacity is prepared. That takes a few minutes when none is warm; `503 capacity_unavailable` means none is free, and `Retry-After` says when to try again.

## 3. On the device: verify, then publish [#3-on-the-device-verify-then-publish]

The device checks the enclave before sending it anything, then publishes its front camera and microphone over WHIP:

1. `GET ingest.attestationUrl`, and check the token against the [attestation policy](/docs/api/trust/getAttestationPolicy).
2. Create an `RTCPeerConnection` with the camera and microphone tracks, using `ingest.iceServersUrl` on strict networks.
3. `POST` the SDP offer to `ingest.url`, sealed with the capability (`ingest.seal`).
4. Verify the enclave's signature on the answer, then apply it.

The device SDK does all four, and its [source is public](https://github.com/Orgasm-dev/device-sdk) (Apache-2.0). Each release on npm is built from that repository with provenance, which `npm audit signatures` checks:

```sh title="Terminal"
npm install @orgasm-dev/device
npm audit signatures
```

```ts title="device.ts"
import { publishLiveSession } from '@orgasm-dev/device';
import { requestCapture } from '@orgasm-dev/device/capture';

const { stream } = await requestCapture(); // from a click: the front camera and the microphone
const live = await publishLiveSession({ session, capability, stream }); // throws AttestationRefused, sending nothing, if the enclave does not verify
```

Ask for the camera after explaining why: `<orgasm-capture-primer>` says what is measured, why the camera and why the microphone, and who receives the readings, then asks, and names any refusal with what to do about it ([camera and microphone](/docs/guides/capture)).

Video must be H.264 or H.265; see [inputs](/docs/concepts/inputs) for framing. With `inputs.body`, publish the body view to `ingest.bodyUrl` the same way.

## 4. Read the events [#4-read-the-events]

Anywhere that suits you; all carry the same events ([realtime](/docs/guides/realtime)):

- **On the device**: `live.subscribe({ onEvent })`, which reads the stream with the client token in a header. The client token reads this session only, and stops working five minutes after it ends. [Show the HUD](/docs/guides/hud) to the person with the same events.
- **On another screen**: a read-only view token from [`createViewToken`](/docs/api/live-sessions/createViewToken), one per screen.
- **On your server**: the stream with the secret key, [webhooks](/docs/guides/webhooks), or `listLiveSessionEvents` with `wait`.

If your product controls stimulation, report each change with `reportStimulation` (from your server or, with the client token, from the device), or `live.reportStimulation`, which sends it over the session's WebSocket. With the device's level, channels and mode in the report, every reader receives them as `stimulation.updated`, and the HUD shows the device ([reporting the device](/docs/guides/realtime#reporting-the-device)).

## 5. End it [#5-end-it]

```ts
await fetch(`https://orgasm.dev/v1/live-sessions/${session.id}`, { method: 'DELETE', headers: { Authorization: `Bearer ${process.env.ORGASM_KEY}` } });
```

A final `session.status` with `status: ended` closes every stream. The events stay readable until `resultsExpireAt`; `purgeLiveSession` deletes them now.

## Status [#status]

```mermaid
stateDiagram-v2
  [*] --> starting
  starting --> ready: capacity is up
  ready --> calibrating: media arrives
  calibrating --> analyzing: baseline in (about a minute)
  analyzing --> ended
  calibrating --> ended
  ready --> ended
  starting --> ended
  ended --> [*]
```

`endedReason` says why it ended: `client_ended`, `media_ended` (the device hung up), `media_timeout`, `max_duration`, `interrupted` (capacity was lost; create a new session), `policy` or `error`. `degraded` is true while a declared input is missing or the face is out of view; the open `input.warning` events say which, and `session.status` reports each change.
