# Client tokens

> Mint short-lived pmfa_ct_ credentials and enforce session, recipient, action, origin, and rate rules.

Use a short-lived client token to make requests from a browser or mobile app.
Each token is limited to one session and the actions you permit. A
[Customer-scoped token](#customer-scoped-tokens) instead covers the numbers one
Customer owns.

Client tokens work with the Messaging API only. The
[Graph API](https://docs.polymorfa.com/api/graph) rejects them; call it from your server with a
team key or project token.

## Mint

Call `POST /platform/client-tokens` with a project or team key that has all of
`sessions:manage`, `messages:write`, `contacts:read`, `presence:read`,
`presence:observe`, and `mcp`. Updating session rules requires the same
permissions. Each token records its mint-time action ceiling. Effective access
is limited by that ceiling and live session rules. To add actions beyond the
ceiling, update the rules and mint a new token. The issuing key must cover every
action it delegates.

```json JSON
{
  "session": "739182640518203",
  "ephemeralId": "user_42",
  "ttlSeconds": 900
}
```

```typescript TypeScript
const minted = await messaging.clientTokens.mint({
  session: "<number-id>",
  ephemeralId: "user_42",
  ttlSeconds: 900,
});

// Return the token to your signed-in browser client. Do not log it.
const browserResponse = Response.json(
  { token: minted.data.data.token, expiresAt: minted.data.data.expiresAt },
  { headers: { "Cache-Control": "no-store" } },
);
```

Mint the token on your server and send only the token to the browser. The
response contains the token and its expiry:

```json
{
  "success": true,
  "data": {
    "token": "pmfa_ct_…",
    "expiresAt": "2030-01-01T00:15:00.000Z"
  }
}
```

*TypeScript:*

Read and change the [session rules](#session-rules) with
`clientTokens.retrieveRules` and `clientTokens.updateRules`.

`ttlSeconds` must be within the bounds documented for the endpoint. The token is
limited to its team, session, ephemeral ID, and expiry.

Session `allow` requires enrollment in the action-ceilings beta. Until that
beta is enabled, session `allow` requests are refused and omission retains the
existing rule-based token format. Existing sealed ceilings remain enforced if
new ceiling issuance is disabled.

`allow` also accepts an explicit ceiling for a session token, including `mcp`
and `voip_*` actions. An empty session `allow` grants no API actions. Customer `allow` must contain
at least one action. Set the rules before minting. A token with no permitted
actions needs reissuing after you configure its rules.

The action names `chats_read`, `chats_manage`, `contact_write`, and
`contact_delete` are reserved for enrolled regional beta access. Including a
reserved action does not enable regional Contacts or Chats. Regional ceilings
also require the corresponding `chats:read`, `chats:manage`, or `contacts:manage`
issuer scope. These permissions do not authorize legacy WhatsApp chat routes. `read_contact`
continues to cover its documented contact lookups; it grants no unrestricted
access to a retained contact directory. Existing tokens cannot gain these
reserved actions through a rule edit.

## Session rules

Rules are managed independently:

```http
GET    /platform/sessions/{session}/client-rules
PUT    /platform/sessions/{session}/client-rules
DELETE /platform/sessions/{session}/client-rules
```

```json
{
  "recipientMode": "conversation",
  "allowedActions": "send_message,send_seen,send_typing",
  "rateLimit": 30,
  "maxDaily": 500,
  "allowedOrigins": "https://app.example.com",
  "conversationTtlSeconds": 86400,
  "enabled": true
}
```

`PUT` replaces the whole rule set. Omitted optional fields return to their
defaults. Rules stay in effect until you replace or delete them, and deleting a
session also deletes its rules.

`recipientMode` is one of `conversation`, `any`, or `none`. Unknown modes fail
closed. `allowedActions` is a comma-separated list containing only these
values:

```text
mcp                     send_message            send_reaction
send_typing             send_seen               read_presence
subscribe_presence      read_contact            voip_place
voip_answer             voip_signal
```

### Conversation window

In `conversation` mode, a client token can send only to a contact who messaged
the session within the conversation window. The window starts again with each
new message from that contact.

`conversationTtlSeconds` sets the window, in seconds:

| Value | Window |
| --- | --- |
| `86400` (default) | 24 hours |
| `300` (minimum) | 5 minutes |
| `604800` (maximum) | 7 days |

Values outside this range return `400`. A window without an expiry is not
available: a contact who has not messaged the session for more than 7 days
must message it again before a client token can reply.
The `voip_*` actions permit calling. `allowedNumber` restricts the numbers a
client token can call or invite (a comma-separated list of E.164 numbers).
Client tokens have the same call limits as your API keys; see
[Call limits](https://docs.polymorfa.com/calls/how-calls-work#limits). `maxSetupsPerMinute` and
`maxConcurrency` are deprecated and have no effect.

Client tokens never pair numbers. Use a [QuickLink](https://docs.polymorfa.com/numbers/quicklink)
to connect a number from a browser or phone.

The `mcp` action permits the protocol handshake. Each MCP tool still passes
through its ordinary session, recipient, action, origin, and rate rules.

## Customer-scoped tokens

> **Note**
>
> Customer-scoped tokens are a beta. When the beta is offered to your team, a
> team owner or admin joins it in [Opt-in features](https://docs.polymorfa.com/teams/opt-in-features) and accepts the terms. Until the team has joined, minting with `customer`
> returns `403`.

When a Customer owns several numbers, mint one token for the Customer instead
of one per session. Pass the Polymorfa Customer ID in `customer` instead of
`session`:

```json
{
  "customer": "0190f0b6-7c1e-7a55-9d1a-2f0c6b1e4a10",
  "ephemeralId": "user_42",
  "allow": ["send_message", "read_presence"],
  "ttlSeconds": 900
}
```

- Send exactly one of `session` or `customer`.
- `customer` is the Customer's Polymorfa ID. Look up a Customer by your own
  external ID on your server first; tokens never accept an external ID.
- The issuing key also needs `customers:read`. A project token can mint only
  for Customers in its project. A team key can mint for any Customer in the
  team. A Customer outside the key's team or project returns `404`.
- The Customer must be active and own at least one number, and the project
  must have Customers enabled. A token covers at most 64 numbers; minting for
  a Customer with more returns `400`.

The token covers the numbers the Customer owns at the moment you mint it. Each
request is also checked against the Customer's current numbers:

| After minting | Effect on the token |
|---|---|
| A number moves to another Customer | Requests for that number return `403` immediately. |
| A number moves to this Customer | Not covered. Mint a new token to include it. |
| The Customer is archived, or Customers are turned off for the project | Every request returns `403`. |
| The team withdraws from the beta | Every request returns `403`. |

Call the usual session routes with the number's session ID in the path, for
example `POST /messaging/{session}/messages/send`. Each request must also pass
that session's [rules](#session-rules): a Customer-scoped token never allows
more than the session's rules do.

`allow` narrows the token further. It accepts `send_message`,
`send_reaction`, `send_typing`, `send_seen`, `read_presence`,
`subscribe_presence`, and `read_contact`. Omit it for a Customer to use that
original action set. For a session, omission snapshots the configured actions
at mint time; missing rules produce a token with no actions. A Customer-scoped token can't use calling (`voip_*`) or MCP; mint a
session token for those.

## Security behavior

Revoking or regenerating the issuing team key or project token stops its client
tokens on the next request. A signed-in human's client tokens also depend on
their live session, team membership and role. Test-key clients stay restricted
to test numbers.

- Client tokens cannot mint other tokens, including Customer-scoped tokens.
- Rules, recipient/conversation state, origin constraints, and rate limits are
  checked after the token authenticates.
- Delete or disable the session rules to stop permitted effects before all
  issued tokens expire.
- Each rule change appears in [Audit history](https://docs.polymorfa.com/teams/audit-history) as
  `clientToken.rulesCreated`, `clientToken.rulesUpdated`, or
  `clientToken.rulesDeleted`. The entry records which fields changed, the
  recipient mode, the limits, and the conversation window. It records how many
  origins and numbers are allowed, not the origins or numbers themselves.
- If a `PUT` or `DELETE` returns `503` with code `service_unavailable`, Polymorfa
  stored the change but could not confirm that client tokens use it. Repeat the
  same request after the `Retry-After` delay.

## Temporary unavailability

Client tokens fail closed. If Polymorfa cannot check a request's rules, the
request is refused instead of being allowed without checks:

- `503` with code `credential_verification_unavailable` when the session rules
  cannot be loaded. The token is still valid; retry the request.
- `503` with code `service_unavailable` and a `Retry-After` header when a
  per-minute `rateLimit` or the `conversation` window cannot be checked. Retry
  after the stated number of seconds.

See [Mint a client token](https://docs.polymorfa.com/api/client-tokens/mint-client-token) and
[Session rules](https://docs.polymorfa.com/api/client-tokens/get-client-rules) in the Platform API reference.
