# Transport & authentication
## Endpoints
One endpoint per environment (NOT per account):
| | |
|---|---|
| HTTP | `POST {base}/graphql` — e.g. `https://panel.chatfuel.com/graphql` |
| WebSocket | `wss://{host}/graphql` — same path, TLS |
| WS subprotocol | **`graphql-transport-ws`** (the `graphql-ws` npm library; NOT the legacy `subscriptions-transport-ws`) |
| REST | `{base}/api/...` (file uploads, see `references/files-tasks.md`) |
Optional but useful: append `?op=<OperationName>` to the HTTP URL so requests are easy to tell apart in your own traces (the server ignores it; the operation still travels in the POST body).
## Authentication
- **HTTP**: header `Authorization: Bearer <token>`.
- **WebSocket**: browsers can't set headers on WS, so the token goes in the `connection_init` payload:
```json
{ "authToken": "Bearer <token>" }
```
(key `authToken`, value **including** the `Bearer ` prefix). With the `graphql-ws` client this is `connectionParams: () => ({ authToken: `Bearer ${token}` })`.
**That snippet belongs on your backend, on your backend's own socket to the API.** A browser running it is a browser holding a full-account credential, which is the one thing the proxy exists to prevent — a browser client connects to *your* WebSocket endpoint with *your* session, and your backend builds this payload on the socket it opens upstream. See `references/cors-proxy.md`.
- **REST**: same `Authorization: Bearer <token>` header.
### Token lifecycle
- The credential is a **dashboard user token**, generated by the account owner at `https://panel.chatfuel.com/integration/auth/token`. Do not assume a shape or a lifetime — treat it as an opaque secret that can be regenerated at any time.
- The bot "API token" (`bot.apiToken`) authenticates the separate REST APIs (broadcasting, contact import) — **it is not a GraphQL credential**, and it is not the dashboard token either. It is a working credential of its own: scoped to one bot, outliving the session, and reaching Chatfuel with no proxy in front of it. Reading it once out of the GraphQL schema is a permanent way around anything a proxy does, which is why the proxy's gate refuses a selection that reaches it (`BOT_SCOPE_DENIED` in `queryAnalysis.ts`).
- Once a token stops working every request returns an `Unauthorized` error — surface a clear "token needs rotation" message rather than retrying.
- An auth attempt may return `AuthResultRedirectToOldDashboard` instead of `AuthResultRegular` — handle both result types; the redirect one is not a session and nothing downstream works with it.
### Permissions
Fine-grained per-bot roles (`Admin | Editor | Agent | Custom`) with `(object, action)` permission pairs. Relevant objects: `Inbox` (live chat view/edit), `People` (contacts), `ContactsAssignedToOthers` / `ContactsUnassigned` (visibility restrictions — a restricted agent receives `UnavailableContact` stubs), `Configure`, `Broadcasting`, `Flows`, `Workspaces`, `Pro` (paid features), `Roles`. Check what the token can do with the `MyBotRole` operation (`examples/operations.graphql`) before building UI that assumes edit rights.
## WebSocket client behavior
- **One lazy connection** per token/instance: connect on first subscription, share it for all subscriptions.
- Send a keepAlive ping every ~10 s; treat a missing pong within ~15 s as a dead socket and close with code 4408 so the client reconnects.
- Reconnect with exponential backoff + jitter (e.g. `min(5s * 2^attempt, 60s) * (0.5 + rand*0.5)`), and immediately on network-online events.
- Do NOT retry on these close codes: 4400 BadRequest, 4401 Unauthorized, 4403 Forbidden, 4406 SubprotocolNotAcceptable, 4409 SubscriberAlreadyExists, 4429 TooManyInitialisationRequests.
- **On reconnect, refetch** the queries backing every live view (chat list, open thread, counters). The server does not replay events missed while disconnected; the socket only guarantees "from now on".
## Request hygiene
- **Strip `__typename` from variables.** If you round-trip fetched objects into mutation inputs, remove `__typename` recursively first — the server rejects unknown input fields.
- Timestamps are the `Time` scalar (RFC3339 strings).
- **The API rate-limits per token.** Batch reads sensibly; back off on 429-style errors.
- Query size guards exist — the operations in `examples/` are well inside them.
## Error envelope
GraphQL errors carry machine-readable codes in `extensions`:
```json
{
"errors": [
{
"message": "...",
"path": ["bot", "conversation"],
"extensions": { "code": "NotEnoughPermissions", "service": "...", "traceId": "..." }
}
]
}
```
Rules:
1. Codes come from the `DefinedErrorCode` enum: global `Unauthorized`, `NotEnoughPermissions`, `InternalServerError` plus per-domain codes (`FileTooBig`, `FileDoesNotExist`, `FileContentTypeNotSupported`, `EnabledTriggerIsImmutable`, …). Which codes a given mutation can return is **not** in `references/schema.graphql` — the bundle carries no descriptions. Take them from the module guide covering that surface, and treat the enum as vocabulary rather than a contract: switch on the raw `extensions.code` string with a fallback branch, because a code you have never seen is a normal outcome, not a bug.
2. **A 401-equivalent can arrive inside an HTTP-200 response**: the API may return 200 with `errors[]` containing an `Unauthorized` code. Always scan `errors[].extensions.code`, not just HTTP status — and one level deeper: a relayed failure carries a generic message at the top and the real entries (code, traceId) in `extensions.errors[]`.
3. Partial data is possible: `data` and `errors` can coexist. Decide per-view whether partial render is acceptable.
4. WhatsApp delivery failures do NOT come back as GraphQL errors — they appear later as `Message.errors[]` (`MessageError { code, originalErrCode, originalErrMessage }`) via `messageUpdated`.
5. `include traceId` from the error extensions when reporting problems to the Chatfuel team.