# Signed-in website chat visitors

> Verify who is signed in on the website chat: a signing key, a token your server signs, the widget's identify call, when an email counts as verified, verified visitors only, and mobile apps.

A site or app that knows who is signed in can have Onbox verify that person in the website chat.
The company's server signs a short-lived token for its user with a signing key of the chat, and the page hands the token to the widget.
Onbox checks the signature when the chat session starts.

Without a token, `Onbox('identify', { userId, email, name, details })` still tells Onbox who the page says the visitor is.
The team and Onbox see that as a claim, never as a sign-in.

## What it changes

- Onbox knows who the customer is.
  The agent and its guards treat the signed user ID as proven, and the email too when the token says `email_verified: true`.
- Onbox can look up the customer's own account.
  A record it finds by the signed user ID or the verified email is theirs.
- Their conversations follow them.
  They belong to the user, not to the browser: every device where the user signs in shows them, and a logout does not lose them.
- Their messages come from one contact, named as signed.
  When a user is first verified, a verified email links them to the contact that already has that address.

It never gives access to anyone else's data: a user ID or an email the customer types in a message is still only a claim.

## 1. Create a signing key

An admin creates the key in Web chat settings, or you call `update_inbox` with `websiteChat.createSigningKey: true`, alone in its call.
The result's `signingKey.secret` (`onbox_wsk_...`) is shown this once.
Give it to the person to store as a server secret, such as an `ONBOX_SIGNING_SECRET` environment variable.
Never put it in front-end code, a repository, the brain or a message.

A chat has at most two active keys, so the server can move to a new key before the old one goes.
To rotate: create a second key and switch the server to it.
An hour later, once every token the old key signed has expired, revoke it with `websiteChat.revokeSigningKey` and its id from `list_inboxes`.
Revoking takes effect at once: tokens it signed stop verifying, and every session it verified becomes unverified.
Revoke at once only a key that leaked.

## 2. Sign a token on the server

Sign with HS256, using the secret as text.
Onbox reads these claims and ignores the others:

| Claim            | Required | Value                                                                                |
| ---------------- | -------- | ------------------------------------------------------------------------------------ |
| `sub`            | yes      | The company's own user ID: up to 256 letters, digits and `. _ ~ : @ + = \| -`.       |
| `exp`            | yes      | At most 1 hour ahead; a few minutes is enough.                                       |
| `email`          | no       | The user's email.                                                                    |
| `email_verified` | no       | `true` only when the company confirmed the user owns `email` (below). Default false. |
| `name`           | no       | The user's name.                                                                     |
| `details`        | no       | Up to 20 string values (plan, company), keys up to 40 characters, values up to 200.  |

Node, with `jsonwebtoken`, behind the app's own sign-in:

```js
import jwt from 'jsonwebtoken'

app.get('/onbox-token', requireSignedIn, (req, res) => {
  const user = req.user
  const claims = { sub: String(user.id) }
  if (user.name?.trim()) claims.name = user.name.trim()
  if (user.email) {
    claims.email = user.email
    claims.email_verified = user.emailConfirmed === true
  }
  const token = jwt.sign(claims, process.env.ONBOX_SIGNING_SECRET, {
    algorithm: 'HS256',
    expiresIn: '10m'
  })
  res.type('text/plain').send(token)
})
```

Python, with PyJWT:

```python
import os, time, jwt

def onbox_token(user):
    claims = {"sub": str(user.id), "exp": int(time.time()) + 600}
    if user.name and user.name.strip():
        claims["name"] = user.name.strip()
    if user.email:
        claims["email"] = user.email
        claims["email_verified"] = user.email_confirmed is True
    return jwt.encode(claims, os.environ["ONBOX_SIGNING_SECRET"], algorithm="HS256")
```

Leave out a claim you do not have: Onbox refuses `null`, and text with spaces at either end.

## 3. Pass it to the widget

Call `identify` once the user is known, with the token or a function that fetches one:

```js
// A function, called when a chat session starts or resumes (recommended).
Onbox('identify', {
  userId: String(user.id),
  jwt: () => fetch('/onbox-token', { credentials: 'include' }).then((r) => (r.ok ? r.text() : ''))
})

// Or the token itself, signed when the server rendered the page.
Onbox('identify', { userId: String(user.id), jwt: 'eyJhbGciOiJIUzI1NiJ9...' })
```

- A function suits most apps.
  The widget calls it only when a session starts or resumes and it holds no unexpired token, never on a timer.
- A string works while its `exp` has not passed.
  After that the widget sends no token and a new session is not verified, so use it only on pages that reload more often than tokens expire.
- Pass `userId` too: the widget then sees a change of user at once.
- A function that throws or returns nothing leaves the visitor unverified, and ends a session it had verified.
- On logout, call `Onbox('shutdown')`.
  It removes the chat and clears it on this device, so the next person starts clean.
  When someone signs in again without a page load, call `boot` again before `identify`.
- The token's `exp` only bounds the token, not the session.
  A session it verified stays verified for its life (up to 90 days) unless the key is revoked; `shutdown` drops it from the device.

A token Onbox cannot verify (bad signature, revoked key, a claim out of bounds) makes the chat unavailable, with the reason in the browser console (`visitor_jwt_invalid`).
Onbox never turns it into an anonymous visitor: fix the signer.

## When to set `email_verified`

Set it to `true` only when the company knows the user controls that address:

- a magic link sent to that address signed them in;
- they confirmed the address when they signed up;
- they signed in with Google, Google's ID token says `email_verified: true`, and the address is a Gmail address or the token has an `hd` claim (a Google Workspace domain).
  For other addresses, Google's flag can outlive the user's ownership of the mailbox.

Do not set it from Microsoft Entra ID's `email` claim: a tenant admin can set it to any address, including one they do not own (the "nOAuth" problem).
When unsure, leave it out.
The email then shows as a claim, and links no contact.

## Verified visitors only

"Verified visitors only" in Web chat settings, or `update_inbox` with `websiteChat.requireVerifiedVisitors: true`, refuses every visitor without a valid token.
It needs an active signing key.
Once Onbox has refused a visitor, the widget hides its launcher until `identify` gives it a token, and remembers that on the device for a day.
A new browser still shows the launcher until that first refusal, so boot the widget only on signed-in pages.
Turn it on only when the chat lives inside the signed-in app.
Revoking the last key while it is on closes the chat to everyone until a new key signs.

## Mobile apps

In a mobile app's WebView on the hosted chat page (`mobileChatUrl`), inject a token function through the app's JavaScript bridge before the page runs.
The page calls it when a session starts:

```swift
// iOS: tokenHandler is a WKScriptMessageHandlerWithReply that replies with a token
// from your server, or nil when signed out.
let controller = configuration.userContentController
controller.addScriptMessageHandler(tokenHandler, contentWorld: .page, name: "onboxToken")
controller.addUserScript(WKUserScript(
    source: """
    window.Onbox = window.Onbox || function () { (Onbox.q = Onbox.q || []).push(arguments) };
    Onbox('identify', { jwt: () => window.webkit.messageHandlers.onboxToken.postMessage(null) });
    """,
    injectionTime: .atDocumentStart, forMainFrameOnly: true, in: .page))
```

```kotlin
// Android: OnboxTokenBridge.token() asks your server for a token, or returns null.
if (WebViewFeature.isFeatureSupported(WebViewFeature.DOCUMENT_START_SCRIPT)) {
    webView.addJavascriptInterface(OnboxTokenBridge(), "OnboxTokenBridge")
    WebViewCompat.addDocumentStartJavaScript(webView, """
        window.Onbox = window.Onbox || function () { (Onbox.q = Onbox.q || []).push(arguments) };
        Onbox('identify', { jwt: async () => OnboxTokenBridge.token() });
    """, setOf("https://widget.onbox.ing"))
} // Else this WebView cannot verify: the chat opens unverified, and a verified-only chat refuses it.
```

React Native (`react-native-webview`) does the same with `injectedJavaScriptBeforeContentLoaded` and a `postMessage` round trip.
With the bridge, pass `userId`, `email` and `name` in that `identify` call instead of the page address.
Never put a long-lived token in a URL: the code that builds it can log it.
On app logout, load the page again without a token.

## Next

- [Every day](https://www.onbox.ing/docs/agents/everyday.md): adding a website chat, and the rest of the work after setup
- [API and CLI](https://www.onbox.ing/docs/agents/api-and-cli.md): the chat routes, to build your own chat with the same token
