# Push notifications

`crm.notifications` — `/v1/audience/devices`

Which browsers and apps a user wants notifications delivered to. A subscription
is one device — one browser profile, one app installation — held against the
acting user, and the only party who can see or revoke it is that user.

| Action | Route | Scope |
| --- | --- | --- |
| [`subscribe`](#subscribe) | `POST /v1/audience/devices` | `devices:write` |
| [`unsubscribe`](#unsubscribe) | `POST /v1/audience/devices/unregister` | `devices:write` |
| [`devices`](#devices) | `GET /v1/audience/devices` | `devices:read` |

**Permissions** — `CRM.DEVICE`: `LIST`, `CREATE` to register, `DELETE` to
unregister. Every device row belongs to the acting person rather than the
account, so a caller only ever sees and changes their own whatever the key says.

## What the SDK does, and what you do

A push subscription has two halves and only one of them is an API call.

**In the browser**, which this SDK deliberately does not wrap:

```js
const permission = await Notification.requestPermission(); // 'granted' | 'denied' | 'default'
const token = await getToken(messaging, { vapidKey });     // firebase/messaging
```

Wrapping those two would mean a hard dependency on `firebase/*` — in a package
that also runs on Node — to pass arguments that come from your own Firebase
project.

**Here**, which is the part that is an API call:

```ts
if (permission === 'granted') {
  await crm.notifications.subscribe({ token });
}
```

## Where the subscription lives

On the platform, against the acting user, **in this product** — not in the core
platform. Core owns identity and the agency's Firebase credentials; messages
arrive here, so the tokens and the sending live here too, and core is never on
the delivery path.

Nothing you send names a Firebase project. The platform resolves it from the
client the call arrives on and stamps it onto the row, because a registration
token is only sendable through the project that minted it and nothing in the
token itself says which. That resolution is a cached read, so it costs nothing in
steady state — but it is why `subscribe` is the one method here that can answer
`503`.

## The device object

```ts
interface Device {
  id: string;
  platform: 'web' | 'android' | 'ios';
  label: string;          // what you sent as device_label; '' when you sent none
  clientId: string | null; // the reseller frontend it registered from
  lastSeenAt: string;     // ISO; last successful send, or last subscribe
  createdAt: string;
}
```

The **registration token is never returned**. It is a send credential: anything
holding one can push to that browser through the agency's Firebase project. The
list exists so a user can recognise and revoke their own devices, which needs the
label and the last-seen time and nothing more.

---

## subscribe

```ts
crm.notifications.subscribe(input: SubscribeNotificationsInput): Promise<Device>
```

`POST /v1/audience/devices` · `devices:write` · **201**

### Payload

| Field | Type | Required | Notes |
| --- | --- | --- | --- |
| `token` | string | yes | The FCM registration token for this instance, from `getToken()`. 20–4096 characters — a sanity check, not a format; Google publishes no shape for these. Trimmed. |
| `platform` | `'web' \| 'android' \| 'ios'` | defaulted | `'web'` when the SDK can see a DOM. Required otherwise — see below. |
| `device_label` | string | no | Up to 200 characters; longer is trimmed, not refused. Defaults to something like `Chrome on Windows`, derived from the user agent. Cosmetic, never matched on. |
| `tpc_id` | string | no | The reseller client (`tpc_…`) this frontend belongs to. Rarely needed. |

What goes on the wire, with everything defaulted:

```http
POST /v1/audience/devices
authorization: Bearer <ecosystem token>
client-id: tpc_8Kd3mXp7qR2wL9zB
content-type: application/json

{
  "token": "fNx8…:APA91bH…",
  "platform": "web",
  "device_label": "Chrome on Windows"
}
```

```ts
const device = await crm.notifications.subscribe({ token });
// → { id: '…', platform: 'web', label: 'Chrome on Windows', clientId: 'tpc_…', … }
```

There is **no user field**, and that is deliberate: the acting user comes from
the verified token the client was constructed with. A body that could name its
own user would let any caller point someone else's notifications at their own
browser.

### Call it on every app load, not once

It is an idempotent upsert keyed on the token, so re-sending one the platform
already holds costs a single indexed update. That is the intended usage, because
two things change underneath you:

- FCM rotates registration tokens on its own schedule, and the old one stops
  being delivered to without anyone being told.
- A device unseen for **60 days** is pruned, and "seen" means a successful send
  or a call to this method. Someone who receives no notifications for two months
  would otherwise quietly fall off the list.

Re-subscribing a token already on file against **another** user moves it rather
than duplicating it. One browser has one person signed in, and the previous
owner's notifications have to stop reaching it the moment someone else logs in
there.

### `platform` off-browser

The SDK defaults it from `document`, not from `navigator` — which is the
distinction that matters. React Native defines a `navigator` and no `document`,
so a navigator-based guess would register every phone as a browser, and the send
path would fill in the `webpush` block instead of `android`/`apns`: a
notification FCM accepts and the device never shows. Outside a browser the SDK
asks instead of guessing:

```ts
await crm.notifications.subscribe({ token, platform: 'android' });
```

### `tpc_id`

Only ever a confirmation. The `clientId` the `CrmClient` already sends is
verified by the gateway and wins; this field says which reseller frontend is
registering, which decides whose Firebase project and which deep-link host apply.
A value that contradicts the verified client is refused with `403` rather than
ignored — the two disagreeing means either a frontend bug or an attempt to file a
device under another tenant, and silently preferring one would hide the first and
partially succeed at the second. The white-label frontend has no client and sends
nothing.

### Errors

| Status | Code | Meaning |
| --- | --- | --- |
| 400 | `validation_failed` | Token missing or implausible, or `platform` could not be defaulted. Thrown by the SDK before a request is made. |
| 403 | `forbidden` | `tpc_id` names a different client than the token was issued for. |
| 503 | `push_not_configured` | The agency has no Firebase notification resource. Nothing the caller can fix; push is simply off for this account. |
| 503 | `push_unavailable` | The platform could not read the configuration from core. Transient. |

Both `503`s want the same handling as success: try again on the next app load,
which the advice above means you are doing anyway.

---

## unsubscribe

```ts
crm.notifications.unsubscribe(token: string): Promise<void>
```

`POST /v1/audience/devices/unregister` · `devices:write` · **204**

```ts
await crm.notifications.unsubscribe(token);
```

### Payload

| Field | Type | Required | Notes |
| --- | --- | --- | --- |
| `token` | string | yes | The same registration token. Trimmed. |

`204` with no body **whether or not a row went** — you are asking for a
guarantee about the future, and a token that is already gone provides it. So this
is safe to call unconditionally on logout without first checking whether the
device was ever subscribed.

Scoped to the caller's own devices. A token identifies a browser rather than a
person, so by the time one user logs out the row may already belong to whoever
logged in after them; an unscoped delete would cut off the person now holding it.

A `POST` with the token in the body rather than `DELETE /devices/:token`: a
registration token is hundreds of characters and may contain `:` and `/`, and
putting one in a path invites proxy length limits and writes a live send
credential into every access log along the way.

### Also delete it on the device

This withdraws the platform's permission to send to that token. If the user is
turning notifications **off** — rather than logging out — also drop the token in
the browser, or the next `getToken()` hands back the same one and the
subscription can come back by accident:

```ts
await crm.notifications.unsubscribe(token);
await deleteToken(messaging); // firebase/messaging
```

---

## devices

```ts
crm.notifications.devices(query?: Partial<ListDevicesQuery>): Promise<Paginated<Device>>
```

`GET /v1/audience/devices` · `devices:read` · **200**

### Query

| Field | Type | Default | Notes |
| --- | --- | --- | --- |
| `page` | number | `1` | 1-based. |
| `rows` | number | `25` | 1–100. |

Sorted by `lastSeenAt` descending. This is what a "notification settings" screen
lists.

```ts
const { data } = await crm.notifications.devices();
data.map((d) => `${d.label || 'This device'} · last seen ${d.lastSeenAt}`);
```

No `search`: the endpoint shares the common list query so the server would accept
one, but the service does not apply it — a device list is one person's handful of
rows. It is left out of the SDK type rather than accepted and silently dropped.

Only ever the acting user's own devices. There is no account-wide view and no
device id in the path: a device is one person's browser.

Worth knowing: a notification is sent to the **20 most recently seen** devices
of a user. A longer list is itself the answer to "why did my old laptop stop
buzzing".

### Telling whether *this* browser is subscribed

You can't, from here — tokens are not returned, by design. Decide it locally
instead. The browser knows its own `Notification.permission` and its own token,
and because `subscribe` is an idempotent upsert, the cheap and correct answer to
"am I still subscribed?" is to subscribe again:

```ts
if (Notification.permission === 'granted') {
  await crm.notifications.subscribe({ token: await getToken(messaging, { vapidKey }) });
}
```

That also repairs the two cases a stored flag gets wrong: a rotated token, and a
row pruned for staleness.

---

## What a device actually receives

Subscribing is only half the story. This is what arrives, so a frontend can
render it and an app can deep-link from it.

Today one thing notifies: **a message on a chat the device's owner is
responsible for.** The payload is FCM's, with the application's own keys under
`data`:

```json
{
  "notification": { "title": "Priya", "body": "Is this still available?" },
  "data": {
    "chat": "68f1c2a39b4e5d6f70812345",
    "action_title": "View In Chat Panel",
    "link": "https://app.acme.com/products/crmv2/chat/68f1c2a39b4e5d6f70812345",
    "click_action": "https://app.acme.com/products/crmv2/chat/68f1c2a39b4e5d6f70812345",
    "icon": "https://cdn.acme.com/push-192.png",
    "badge": "https://cdn.acme.com/push-192.png"
  },
  "webpush": {
    "notification": { "icon": "https://cdn.acme.com/push-192.png" },
    "fcmOptions": { "link": "https://app.acme.com/products/crmv2/chat/68f1c2a39b4e5d6f70812345" }
  }
}
```

| Key | What it is |
| --- | --- |
| `notification.title` | Who wrote — the contact's first name, or `New User`. Not the agency's sender name, which is what every other notification would use. |
| `notification.body` | The message text, cut to 180 characters. A non-text message is named by its type instead: `Image Message`, `Location Message`. |
| `data.chat` | The chat id. The same id the inbox endpoints take. |
| `data.click_action` | **Web:** the absolute panel URL. **Android/iOS:** the bare chat id, because an app resolves a record rather than opening a URL. |
| `data.link` | Always the absolute URL, on every platform, so a native client can open the panel if it would rather. |
| `data.image` | An image message's media URL, for a preview. Absent otherwise. |
| `data.icon`, `data.badge` | The agency's notification icon, for a client drawing the notification itself. |
| `webpush.fcmOptions.link` | What a **browser** opens on click. This is the mechanism, not `click_action`. |

The host in every URL is the one configured for that device's surface, so the
same notification deep-links to `app.acme.com` for one reseller's user and
`portal.other.com` for another's.

### Which messages notify

| The message | Notifies |
| --- | --- |
| A contact wrote in | yes |
| Somebody replied from the WhatsApp Business app | yes |
| An agent replied from the panel | no |
| A bot replied | no |
| A campaign sent | no |
| An API send | no |
| A delivery receipt moved to delivered or read | no |

A tick changing on a screen is not worth interrupting anyone for, and nobody
needs telling about a message they just sent themselves.

### Who it reaches

The chat's **assigned agent**, or the **account owner** while it is unassigned
— one person, not the team. An unassigned chat belongs to whoever is minding
the queue.

There is no presence check: an agent with the conversation open on screen still
gets the push on their phone. That is the behaviour the panel has always had, and
changing it is a product decision rather than a detail of delivery.

A person is matched under **either of their two ids**. A request carries the
ecosystem's `psuid`, which is what `subscribe()` files a device under; the inbox
trigger reads its recipient off a chat row the legacy stack wrote, so the id it
holds is a legacy one. Registration records both, and the lookup matches the one
id it is given against either field — so it resolves one person under two
names, and never returns a colleague's devices.

The practical consequence: a device registered before this existed is still
reachable by `psuid` exactly as before, and the next `subscribe()` call — which
the frontend makes on every app load — fills in the second id.

A **team member's** device records only their `psuid`. The legacy id on a member
token belongs to the account holder, not to the member, so filling it in would
make the member's phone answer notifications addressed to the owner — and the
owner's answer theirs. The consequence is narrow and worth knowing: a member is
reachable by `psuid`, and a chat assigned to them notifies them because the chat
row names them.

### Rendering it in a browser

If the payload carries a `notification` block, FCM displays it and opens
`webpush.fcmOptions.link` on click with no code from you — which is the
default worth keeping. A service worker that wants to draw its own instead
should read the `data` keys above:

```js
messaging.onBackgroundMessage((payload) => {
  self.registration.showNotification(payload.notification.title, {
    body: payload.notification.body,
    icon: payload.data.icon,
    image: payload.data.image,
    data: { url: payload.data.link },
  });
});

self.addEventListener('notificationclick', (event) => {
  event.notification.close();
  event.waitUntil(clients.openWindow(event.notification.data.url));
});
```

Two things to know if you are porting the existing worker. A notification FCM
displayed itself nests the payload under `notification.data.FCM_MSG`, so reading
`event.notification.data.click_action` off it finds nothing — take the link
from your own `showNotification` call, as above. And `localStorage` does not
exist in a service worker: a gate written against it throws, and the handler
around it never runs.
