# Inbox — connecting

The live-chat inbox is a Socket.IO connection, not REST. It has its own origin,
separate from the REST gateway: the gateway proxies HTTP only and forwards no
WebSocket upgrade, so a handshake routed through it never completes.

```bash
npm install ab-ecosystem-cpass socket.io-client
```

`socket.io-client` is an optional peer dependency. The REST client never resolves
it — only the `/realtime` subpath does.

```ts
import { Inbox } from 'ab-ecosystem-cpass/realtime';

const inbox = new Inbox({
  url: 'https://inbox.example.com',
  clientId: process.env.CRM_CLIENT_ID!,
  token: () => session.accessToken,   // called on every connect
});

await inbox.ready();
```

## Client options

| Option | Type | Default | Notes |
|---|---|---|---|
| `url` | `string` | — | Required. The inbox socket's origin. |
| `clientId` | `string` | — | Required. Your ecosystem client id, as on every REST call. |
| `token` | `string \| () => string \| Promise<string>` | — | Required. Bearer token. |
| `path` | `string` | `/socket.io` | Only if the deployment moved it. |
| `timeout` | `number` | `20000` | How long a request waits for its acknowledgement, in ms. |
| `autoConnect` | `boolean` | `true` | Connect on construction. |
| `socketOptions` | `object` | — | Merged into the socket.io options last. |

**Pass `token` as a function.** It is resolved on every connect, so a reconnect
after an expiry picks up a fresh token. A string is captured once, and a socket
that drops after the token expires will retry forever with the dead one.

## How credentials travel

In `auth`, not in a header:

```ts
{ token: '<bearer token>', client_id: '<client id>' }
```

A browser cannot set headers on a WebSocket upgrade at all. A header-based
handshake only works while the connection is still on HTTP long-polling, and
breaks the moment a client sets `transports: ['websocket']`. The server still
accepts `authorization` and `client-id` headers for existing clients.

The handshake checks two things: the token verifies against the ecosystem JWKS
for the `client_id` sent, and the verified claims name that same client. There is
**no origin allowlist** — the credential is the boundary, not the page it came
from, which is also why a server-to-server client with no `Origin` at all
connects fine. A failure arrives as `connect_error` with the reason:

```ts
inbox.raw.on('connect_error', (err) => console.error(err.message));
```

## Requests and pushes

Two kinds of traffic, and the same event name can be both.

**Requests** are promises. Every emit carries an acknowledgement callback, so two
concurrent reads of different threads cannot be confused for one another:

```ts
const { contacts, nextPage } = await inbox.chats.list({ filter: { assignment: 'me' } });
```

**Pushes** are things that happened elsewhere — another agent archiving a chat, a
contact replying:

```ts
const off = inbox.on('chat.action', ({ action, id, chat }) => applyToList(action, id, chat));
off();  // unsubscribe
```

An archive you performed and an archive another agent performed arrive under the
same name with the same shape, so one handler per kind of change is enough.

| Push | Payload | When |
|---|---|---|
| `message.received` | `Message` | A message arrived, or one you sent now exists as a stored row. |
| `message.status` | `MessageStatusUpdate` | A delivery state moved: sent, delivered, read, failed. |
| `chat.action` | `ChatActionResult` | A chat changed: unread, assignment, automation, tags. |
| `contact.received` | stored document | A contact wrote in for the first time, so a chat row appeared. |
| `message.delete` | `MessageDeleteResult` | A message was removed from an open thread. |
| `message.retry_download` | `Message` | Media was re-fetched and its link changed. |
| `contact.done` | `ChatActionResult` | A chat was marked done. |
| `message.send` | stored document | Legacy. The same row as `message.received`, unmapped. |
| `error` | `InboxError` | An event was refused. Carries the failing event name. |

`message.send` as a *push* exists only because the inbox this replaced used one
name for both its own reply and the row that followed. Prefer
`message.received`: it is mapped (`id`, ISO `createdAt`), where `message.send`
carries `_id` and `user` as the database holds them.

Each push is delivered **once** per socket even when you are in two rooms it
targets — your account's room and the thread you have open.

## Subscriptions

A socket starts subscribed to the account, so every account-wide change reaches
it. Thread-level pushes need the thread: calling `chats.get(id)` or
`messages.list(id)` subscribes to that conversation, and typing notices and new
messages for it arrive from then on without asking again.

## Errors

A refused request rejects with `CrmApiError`, carrying the same `status` and
`code` the REST API would have returned — one error path covers both transports.

```ts
import { CrmApiError } from 'ab-ecosystem-cpass';

try {
  await inbox.chats.transfer(chatId, memberId);
} catch (err) {
  if (err instanceof CrmApiError && err.status === 403) {
    // not allowed to reassign this chat
  }
}
```

| `status` | `code` | Means |
|---|---|---|
| 401 | `unauthorized` | The handshake's token did not verify. |
| 403 | `forbidden` | The action is beyond this member's permissions. |
| 403 | `A403` | The role does not hold the permission the action needs. |
| 403 | `E403` | The account's plan does not include the feature. `details.feature` names it. |
| 404 | `not_found` | No such chat or message **for this account**. |
| 422 | `validation_failed` | Payload rejected. `details` names the fields. |
| 500 | `internal_error` | Server fault. Nothing further is disclosed. |
| 504 | `timeout` | No acknowledgement inside `timeout` ms. |

An unknown event name is ignored rather than refused, so a client emitting its
own lifecycle events gets no spurious errors.

## Scoping

Every read and write is scoped to the account the token identifies, the same way
the REST contact endpoints are. Quoting another account's chat or message id
produces `404`, not that account's data.

Which account that is depends on who signed in. The token's `act` claim says:

| `act` | The account | Who you are |
|---|---|---|
| `owner` (or absent) | your own `psuid` | the account holder |
| `member` | the `accountId` claim | someone the holder granted access to |

A member works inside the owner's account — the owner's chats, contacts and
channels, counted against the owner's plan. How much of it they see is the
role's `data_scope`:

| `data_scope` | Sees |
|---|---|
| `own` (or absent) | the chats and contacts assigned to them |
| `all` | everything in the account |

Absent means `own`: a role the server could not read narrows rather than opens.
Nothing distinguishes an owner from a member in a request — the same events, the
same payloads — and a chat nobody assigned you simply is not there. A chat
assigned to nobody at all is the account's, not everybody's, so an `own`-scoped
member does not see it either; `live_chat.unassigned.*` below is how that is
granted.

## Permissions

Visibility inside an account is gated on inbox permissions, not API scopes. An
owner or a manager is never gated; a team member needs the permission named.

| Permission | Grants |
|---|---|
| `live_chat.unassigned.ALL` | See every chat in the account, assigned or not. |
| `live_chat.unassigned.NEW` | See chats nobody has answered yet. |
| `live_chat.send.AS_OTHER` | Attribute an outgoing message to another member. |

A team member without these is narrowed to their own chats rather than refused —
and the reply says so. See [chats.md](https://github.com/udghatan-dev/crm-sdk/blob/main/packages/sdk-js/docs/inbox/chats.md#the-applied-filter).

The token carries a `roleId` rather than a list of permissions. The server
resolves it against the SSO at connect — once per role version, cached — and the
grants it returns are what the table above is checked against. A role that
grants none of these names leaves the member in the narrow case: their assigned
chats, no unassigned queue, no sending as somebody else. So does a role the SSO
cannot be asked about, which is deliberate — an SSO outage narrows a member, it
never opens an account.

Permissions are read once, at connect. A role edited mid-session takes effect on
the next reconnect, the same way an upgraded plan does. A member's `role` is
`team_member` unless the token says `manager`.

### Permission keys, per event

`CRM.CHAT` governs the inbox, and every event names a verb of it. There is no
router here, so the check runs in the dispatcher in the position route
middleware would occupy — before the handler, after the payload is validated.

| Event | Key |
| --- | --- |
| `contact.list`, `ctwa.list` | `CRM.CHAT.LIST` |
| `contact.fetch`, `chat_session.list`, `message.list`, `message.fetch`, `message.retry_download` | `CRM.CHAT.READ` |
| `message.send` | `CRM.CHAT.SEND` |
| `message.delete` | `CRM.CHAT.DELETE` |
| `contact.update`, `contact.done`, `contact.bot_assign` | `CRM.CHAT.UPDATE` |
| `chat.action` | **depends on the action** |
| `ping` | none — it is a liveness probe |

`chat.action` carries thirteen actions under one event name, and they are not one
capability: `transfer` and `bulk_transfer` need `CRM.CHAT.TRANSFER`, `delete`
needs `CRM.CHAT.DELETE`, and the state changes — archive, unarchive, close, done,
block, mark read/unread, pause/resume automation, pause timer — need
`CRM.CHAT.UPDATE`. The key is resolved from the validated payload, so a client
that may archive but not delete gets `A403` on the second and nothing changes.

`contact.bot_assign` is `UPDATE`, not `ASSIGN`: it hands a conversation to
automation rather than to a colleague, and the catalogue's `ASSIGN` implies
`TEAM.LIST` because choosing a person means seeing the team.

A refusal arrives as the same `A403` / `E403` the REST API returns, in the
acknowledgement callback and as an `error` emit.

### `live_chat.*` is a separate, older vocabulary

The three permissions in the table above this section are **not in the SSO's
catalogue**. A role can only grant what the catalogue publishes, so nothing can
currently grant `live_chat.unassigned.ALL` — the way to give a member the whole
account's inbox is `data_scope: all` on their role, which `CRM.CHAT` is marked
**scopable** for. The three names are kept because the inbox still checks them.

### Two different refusals

Beyond the inbox's own visibility rules, an action can be refused for either of
two reasons, and the codes are distinct because the answers are:

- **`A403`** — the role does not hold the permission. Ask the account owner.
- **`E403`** — the account's plan does not cover the feature. Upgrade.
  `details.feature` names the feature, so the client can say which.

An owner is never refused for `A403` — there is no role to check them against —
but an owner *is* refused for `E403`: a feature outside the plan is outside it
for everybody on the account.

## Modules

| Page | Actions |
|---|---|
| [chats.md](https://github.com/udghatan-dev/crm-sdk/blob/main/packages/sdk-js/docs/inbox/chats.md) | `list` `get` `delete` `transfer` `bulkTransfer` `archive` `unarchive` `block` `markAsRead` `markAsUnread` `pauseAutomation` `resumeAutomation` `close` `done` `pauseTimer` `updateTags` `update` `assignBot` |
| [messages.md](https://github.com/udghatan-dev/crm-sdk/blob/main/packages/sdk-js/docs/inbox/messages.md) | `list` `get` `send` `sendMedia` `delete` `retryDownload` |
| [media.md](https://github.com/udghatan-dev/crm-sdk/blob/main/packages/sdk-js/docs/inbox/media.md) | `sendMedia` · `crm.inboxMedia.upload` `createUpload` |
| [referrals.md](https://github.com/udghatan-dev/crm-sdk/blob/main/packages/sdk-js/docs/inbox/referrals.md) | `referrals` |
| [sessions.md](https://github.com/udghatan-dev/crm-sdk/blob/main/packages/sdk-js/docs/inbox/sessions.md) | `sessions` |
