# Security and privacy

> Isolation, CSP, what the widget stores and sends.

What the widget does with data. How it isolates itself from your
page. How to make it work with strict CSPs. GDPR + compliance notes.

---

## TL;DR

- **No cookies or fingerprinting.** The default adapter uses `localStorage`; a
  custom synchronous adapter can replace it. Anonymous allowlisted usage events
  use 1×1 pixel requests by default; `tracking.enabled: false`, GPC, or DNT
  disables them.
- **CSP-compatible.** Small set of directives needed; shown below.
- **Shadow DOM isolated.** Your site's CSS can't break the widget and
  vice versa.
- **Optional iframe isolation** for strict threat models.
- **GDPR-ready.** Your DPA with Help AI covers processing terms.
- **SOC 2 Type II** certified (contact for report).
- **No `eval`, no `innerHTML`, no dynamic code.** Source-available so
  you can audit.

---

## What data the widget collects

On every mount + every message, the widget sends to the Help AI API:

| Field                  | Required? | Example                                                                      |
| ---------------------- | --------- | ---------------------------------------------------------------------------- |
| `visitorId`            | Auto      | `visitor_7a8f2b...`                                                          |
| `conversationId`       | Auto      | `chat_abc123...`                                                             |
| `userPrefs`            | Auto      | `{ locale: "fr", soundMuted: false, themeMode: "dark", textSize: "normal" }` |
| `messages` (user text) | On send   | `[{ role: "user", text: "Hello" }]`                                          |
| `attachments` (if any) | On send   | Upload URLs + metadata                                                       |
| `userContext` (if set) | Optional  | `{ id, email, name, ...custom }` — informational only                        |
| `pageContext`          | Auto      | `{ url, ...host area/path/title/custom }` — `url` auto-filled                |
| `locale`               | Auto      | `"en-US"`                                                                    |

When built-in usage tracking is enabled (the default), meaningful widget events
also send an anonymous 1×1 pixel request to the configured data collector. Each
request contains an allowlisted event name and scalar dimensions: anonymous
visitor/conversation and deployment identifiers, page origin + path, referrer
origin, screen/viewport values, language, timezone, presentation mode, theme,
and event-specific counts or outcomes. Message text, form values, attachment
contents, query strings, hashes, and host-provided user identity are not
included. The host-controlled pathname is included and may itself contain
identifiers; keep sensitive values out of paths or disable tracking. Set
`tracking.enabled: false` to stop client-side hits; GPC and DNT override all
configuration. See Anonymous usage tracking.

On every receive (from the backend):

- Streaming text responses.
- Tool calls + results.
- File references.

The widget does **not** collect:

- Cookies (it doesn't set any).
- Explicit client IP or geolocation fields. The analytics collector may derive
  coarse location from the request IP and then discard the IP.
- Keystroke telemetry.
- Mouse movements.
- Page content outside what the user types.

---

## Where data goes

```
┌─────────────────┐
│  Visitor's      │      HTTPS + TLS 1.3
│  browser        │ ────────────────────────→  help.ai
│  (widget)       │
└─────────────────┘
                                              │
                                              ↓
                                    ┌─────────────────────┐
                                    │   Help AI backend   │
                                    │   ↓                 │
                                    │   Your deployment's │
                                    │   configured model  │
                                    │   provider          │
                                    └─────────────────────┘
```

- **Every deployment**: data flows to `help.ai` (the `/api/agent` and `/api/data` modules) and is processed in
  US-based infrastructure.
- **Self-hosted**: enterprise customers can route via a bring-your-own
  API endpoint (`baseUrl` option).

---

## Persistence

### What the widget stores client-side by default

The default adapter stores values in `localStorage` using three scopes. In the
patterns below, `[.deploymentId]` is omitted when absent and `[.vN]` appears only
after a handshake-provided storage version takes effect on the next load.

| Scope               | Key pattern                                                     |
| ------------------- | --------------------------------------------------------------- |
| Reset lever         | `helpai.storageVersion` (stable and never versioned)            |
| Anonymous visitor   | `helpai[.vN].visitorId` (shared by every widget and deployment) |
| Widget + deployment | `helpai.<widgetId>[.deploymentId][.vN].<suffix>`                |

Complete `ClientStorage` adapter-managed suffix inventory:

| Suffix                   | Value                                                               | Lifetime / behavior                            |
| ------------------------ | ------------------------------------------------------------------- | ---------------------------------------------- |
| `conversationId`         | Active UUIDv7                                                       | Pointer removed by "New conversation"          |
| `draft.<conversationId>` | Exact unsent textarea text                                          | Removed when accepted/emptied; no built-in TTL |
| `userPrefs`              | JSON: `locale`, `widgetSize`, `soundMuted`, `themeMode`, `textSize` | Cached locally; synchronized to the backend    |
| `panelOpen`              | `"0"` / `"1"`                                                       | Per-device                                     |
| `panelSize`              | `normal` / `expanded` / `fullscreen`                                | Per-device                                     |
| `calloutDismissed`       | Exact dismissed callout text                                        | Per-device                                     |
| `sidebarCollapsed`       | `"0"` / `"1"`                                                       | Per-device, page mode                          |
| `activeModule`           | Messenger module id                                                 | Per-device                                     |
| `historyCount`           | Last loaded conversation-row count                                  | Per-device skeleton sizing                     |
| `formsDone`              | JSON map of form id to completion epoch milliseconds                | Per-device; survives "New conversation"        |

`helpai.storageVersion` stores the next namespace version. A changed value
abandons the prior versioned namespace on the following load; it does not
migrate or delete old keys.

The runtime logger is separate from `ClientStorage`: explicitly changing the
debug level persists the brand-global `helpai.debug` key directly in
`localStorage` so diagnostics survive reloads. The default warning level does
not create that key. A custom storage adapter does not intercept it.

Adapter-managed persistence does not use `Conversation`, `IndexedDB`, `Cache`
storage, or a `ServiceWorker`. It sets no cookies.

The default adapter stores unsent draft text as plaintext readable by other
same-origin scripts. The widget does not include that text in Help AI network
requests until the visitor sends it, and it applies no draft TTL. Customers with
stricter requirements should pass an encrypted or in-memory adapter; an
in-memory adapter intentionally gives up draft restoration after reload.

### Default-adapter scope

| Data                   | Per-device                  | Cross-device                                                |
| ---------------------- | --------------------------- | ----------------------------------------------------------- |
| `visitorId`            | ✓ (minted once per browser) |
| `conversationId`       | ✓                           |                                                             |
| Unsent text draft      | ✓                           |                                                             |
| Messages               |                             | ✓ (server is authoritative; `loadConversation` re-hydrates) |
| Locale preference      |                             | ✓ (via `userPrefs`)                                         |
| Theme preference       |                             | ✓                                                           |
| Sound mute state       |                             | ✓                                                           |
| Text size preference   |                             | ✓                                                           |
| Drag-resized size      |                             | ✓                                                           |
| Panel open / closed    | ✓                           |                                                             |
| Panel size tier        | ✓                           |                                                             |
| Hint dismissed         | ✓                           |                                                             |
| Sidebar state          | ✓                           |                                                             |
| Active module          | ✓                           |                                                             |
| History skeleton count | ✓                           |                                                             |
| One-time form markers  | ✓                           |                                                             |

Cross-device sync uses the same `visitorId` — so if the user has the
widget on multiple tabs of the same browser, they sync. Across
different browsers / devices, the visitor is separate. `userContext.id`
is informational only — it does not tie conversations together server-side.

### Custom storage

You can swap `localStorage` for any synchronous adapter:

```ts
const storage = {
  get: (key: string) => sessionStorage.getItem(key),
  set: (key: string, value: string) => sessionStorage.setItem(key, value),
  remove: (key: string) => sessionStorage.removeItem(key),
};

init({
  publicKey: '...',
  aiAgentDeploymentId: '01900000-0000-7000-8000-000000000000',
  storage,
});
```

Custom adapters receive the dynamic `draft.<conversationId>` keys and exact
unsent text values in addition to identity and UI state, so adapter code owns
their storage destination, retention, and privacy behavior. Use cases include
encrypted `localStorage`, `sessionStorage`, and in-memory consent fallbacks.

[Recipes § Custom storage](/sdk/recipes#custom-storage-adapter).

---

## Shadow DOM + iframe

### Shadow DOM (always on)

Every widget renders inside an open shadow root attached to a custom
element (`<helpai-chat-host>` or `<web-ai-chat>`). Consequences:

- **Your CSS can't reach in.** `body * { ... !important }` won't
  style the widget's internals.
- **The widget's CSS can't leak out.** We don't pollute your `<body>`.
- **Events bubble through** (by W3C spec). Your `document.addEventListener('click', ...)`
  handlers still see clicks that happen inside the widget — useful
  for analytics, doesn't affect isolation.

The widget sets `all: initial` on the shadow host element to neutralize
inherited styles from hostile host pages.

### Iframe isolation (opt-in)

For host pages with aggressive JS (monkey-patching `window.fetch`,
replacing `console.log`, etc.):

```ts
init({ publicKey: '...', aiAgentDeploymentId: '01900000-0000-7000-8000-000000000000', presentation: { iframe: true } });
```

This wraps the widget in a same-origin iframe. The widget's JS runs
in the iframe's realm — parent-page globals don't affect it.

Composes with every `presentation.mode`:

- `presentation: { mode: "floating", iframe: true }` → floating iframe in the corner.
- `presentation: { mode: "inline", iframe: true }` → iframe fills your container.
- `presentation: { mode: "standalone", iframe: true }` → fullscreen iframe.

When to enable:

- Host page monkey-patches `window.fetch` or `XMLHttpRequest`.
- Host page attaches listeners that swallow widget events.
- Compliance review requires "no access to parent page globals".
- You embed the widget on pages you don't fully control.

Not needed for 95% of deployments — shadow DOM alone is sufficient.

### In-widget content iframe sandbox (messenger modules)

This is a **different** iframe from the runtime-isolation wrapper above.
When the messenger renders remote help articles, status pages, or any
`iframe`-action / `embed` block, it shows that remote URL inside a
**heavily sandboxed iframe within the widget** (`src/ui/iframe-view.tsx`):

- **Article / status drill-ins** (`IframeView`):
  ```
  sandbox="allow-scripts allow-forms allow-popups allow-popups-to-escape-sandbox allow-downloads"
  referrerpolicy="no-referrer"
  ```
- **`embed` blocks** use a **narrower** sandbox — the same set **minus**
  `allow-downloads`.

The critical omission in both is `allow-same-origin`. Without it, a
sandboxed page is forced into an opaque origin and **cannot script the
embedder, read its DOM, or touch its storage** — even if the remote URL
happens to be same-origin with the host. `referrerpolicy="no-referrer"`
also strips the referrer from those requests.

**Article / status bodies are never fetched or inlined.** The widget only
ever renders them as sandboxed _remote URLs_ — it does not download HTML
and inject it. (Rich text that the backend controls travels as a content row's
markdown `content` and is rendered DOM-safely, never via `innerHTML`.) A row
opens as an iframe only when it has a `url`; otherwise its markdown renders in
the native reader. See the content model.

---

## Content Security Policy

The widget needs these directives to run under a strict CSP:

```
default-src 'self';
script-src 'self' https://cdn.help.ai;
connect-src 'self' https://help.ai;
style-src 'self' 'unsafe-inline';
img-src 'self' data: blob: https:;
font-src 'self' https:;
media-src 'self' blob:;
```

### Why each is needed

- `script-src https://cdn.help.ai` — the widget JS is hosted on
  our CDN. If you self-host, use `'self'` or your CDN.
- `connect-src https://help.ai` — the widget fetches from our API
  (`/api/agent` + `/api/data` on the main origin).
- `style-src 'unsafe-inline'` — the widget's CSS is adopted via
  constructable stylesheets + an inline fallback. `'unsafe-inline'`
  is safe when scoped inside shadow DOM — host pages can't inject
  new styles there.
- `img-src data: blob: https:` — inline SVG icons (`data:`), uploaded
  attachment previews (`blob:`), and avatar / attachment URLs.
- `font-src https:` — if you use a custom `fontFamily` that loads
  web fonts.
- `media-src blob:` — voice recording uses `MediaRecorder` + `blob:`
  URLs.

### Strict CSP + nonces

If your CSP uses nonces, the widget's shadow DOM CSS doesn't need one
(it's not injected into the main document). But the bootstrap
`<script>` tag does:

```html
<script src="https://cdn.help.ai/sdk/js/elements/latest/elements.js" data-public-key="agent_pk_..." data-ai-agent-deployment-id="01900000-0000-7000-8000-000000000000" nonce="{{ csp_nonce }}" defer></script>
```

Adjust `script-src` to allow the nonce instead of `'unsafe-inline'`.

### CSP report-only testing

Before enforcing:

```
Content-Security-Policy-Report-Only: default-src 'self'; script-src 'self' https://cdn.help.ai; ...
```

Reports land in your DevTools console + your `report-uri` endpoint
without blocking anything.

---

## Subresource Integrity (SRI)

Pin the bundle to a specific hash:

```html
<script src="https://cdn.help.ai/v1.2.0/elements.js" integrity="sha384-..." crossorigin="anonymous" data-public-key="agent_pk_..." data-ai-agent-deployment-id="01900000-0000-7000-8000-000000000000" defer></script>
```

We publish SRI hashes with each release in the
[changelog](https://github.com/help-ai/elements/releases). Only
the pinned version URL (`/v1.2.0/`) supports SRI — the floating URL
(`/elements.js`) doesn't, by design.

---

## Authentication

Browser access is scoped by `aiAgentDeploymentId`; a `publicKey` adds
workspace authorization. Visitors are anonymous unless your server signs a
[user token](#verified-users-usertoken) for your logged-in user.

### public key (default)

```ts
init({ publicKey: 'agent_pk_...', aiAgentDeploymentId: '01900000-0000-7000-8000-000000000000' });
```

Sent as the `x-public-key` header. Your public key authorizes access
to your **public** widget configuration — it's designed to be safe to
expose client-side. Think of it like a Stripe publishable key
(`pk_live_...`).

What your public key does NOT grant:

- Access to other customers' data.
- Write access to your deployment's config (that's gated by your
  dashboard conversation).
- Server-side admin APIs.

### guest

Omit `publicKey` but keep `aiAgentDeploymentId`; the widget connects to
that public deployment as a guest without an auth header.

### Verified users (`userToken`)

To show a logged-in user their own conversations on any device, and to let the AI rely on who they are, your
server signs a short-lived JWT for them with the deployment's **secret key** (on the deployment's Install page;
never put it in the browser):

| Claim   | Required | What it is                                                 |
| ------- | -------- | ---------------------------------------------------------- |
| `sub`   | yes      | Your own id for the user (a string, up to 255 characters)  |
| `exp`   | yes      | Expiry, in seconds since the epoch; keep it short (1 hour) |
| `name`  | no       | Their name, given to the AI as a verified fact             |
| `email` | no       | Their email, given to the AI as a verified fact            |

Sign it with HS256:

```js
// Node (jose)
import { SignJWT } from 'jose';

const secret = new TextEncoder().encode(process.env.HELPAI_SECRET_KEY);
const userToken = await new SignJWT({ name: user.name, email: user.email }).setProtectedHeader({ alg: 'HS256' }).setSubject(String(user.id)).setExpirationTime('1h').sign(secret);
```

```python
# Python (PyJWT)
import os, time, jwt

user_token = jwt.encode({"sub": str(user.id), "exp": int(time.time()) + 3600, "name": user.name, "email": user.email}, os.environ["HELPAI_SECRET_KEY"], algorithm="HS256")
```

```php
// PHP (firebase/php-jwt)
use Firebase\JWT\JWT;

$userToken = JWT::encode(['sub' => (string) $user->id, 'exp' => time() + 3600, 'name' => $user->name, 'email' => $user->email], getenv('HELPAI_SECRET_KEY'), 'HS256');
```

Serve it from an endpoint only your signed-in user can reach, and hand the widget a function that fetches it:

```ts
const userToken = () => fetch('/api/help-ai-token').then((res) => res.text());

init({ publicKey: 'agent_pk_...', aiAgentDeploymentId: '01900000-0000-7000-8000-000000000000', userToken }); // signed in at load
chat.login(userToken); // or after your sign-in (`HelpAI('login', userToken)`, `<HelpAI userToken={userToken} />`)
chat.reset(); // on sign-out (`HelpAI('reset')`)
```

- The widget sends the token only to the agent API, as the `x-user-token` header. The function is called when a token
  is first needed and again when the server answers `401 USER_TOKEN_INVALID` (expired or rejected); the request is
  then sent once more. A fixed string can't be refreshed, so an expired one fails until you call `login()` again.
- A token the server can't verify is refused; it never falls back to an anonymous visitor.
- Signing in moves the visitor's conversations on that browser to the user. From then on they reach them on any device
  where they're signed in, and nobody else does, the signed-out browser included.
- Signing out (`reset()`, or dropping the token) or switching to another user starts over as a new visitor: nothing of
  the previous user stays in the browser.
- Keep the function's identity stable for one user (a module function, or `useCallback` keyed on your user id): a
  different function counts as a different user.

### user / page context is NOT auth

```ts
init({
  publicKey: 'agent_pk_...',
  aiAgentDeploymentId: '01900000-0000-7000-8000-000000000000',
  userContext: { id: '42', email: 'jane@help.ai', name: 'Jane' },
  pageContext: { area: 'support' },
});
```

`userContext` and `pageContext` are **untrusted, host-asserted
information for the AI** — never an authentication credential. The
backend does not register or authenticate these end users. The `id`
field is a string you provide, not a cryptographic identity. Both
objects are sanitized client-side before they leave the page (reserved
auth-like keys such as `jwt` / `token` / `authorization` / `password`
are stripped). Use them for personalization and context only.

#### Trust zones

```mermaid
flowchart TB
  subgraph Host["Host site — example.com (untrusted by backend)"]
    direction TB
    H1["Asserts userContext / pageContext<br/>(who/where the visitor is)"]
    H2["Has its OWN auth — some sites log users in,<br/>some are guest-only"]
  end

  subgraph Widget["Widget — runs in the visitor's browser"]
    direction TB
    W1["Mints + owns anonymous visitorId / conversationId"]
    W2["Sanitizes context client-side<br/>(strips jwt/token/password/…)"]
    W3["Encodes the context field<br/>base64url({ user, page }) on every request"]
    W4["Authenticates to backend via<br/>x-public-key + x-ai-agent-deployment-id"]
  end

  subgraph Backend["Help AI backend"]
    direction TB
    B1["Authenticates the HOST's agent deployment<br/>(NOT the end user)"]
    B2["Treats userContext / pageContext as<br/>informational + untrusted"]
    B3["Never registers end users; verifies a signed userToken when the host sends one"]
  end

  Host -->|"context (untrusted)"| Widget
  Widget -->|"HTTPS/TLS + headers + context field"| Backend

  note["publicKey + aiAgentDeploymentId auth the host's agent; only a userToken signed by the host's server identifies the end user."]
  Backend -.-> note
```

#### The `context` field — base64url, obfuscation not encryption

`userContext` + `pageContext` ride **every** request as one `context` field
= `base64url(JSON.stringify({ user, page }))` (JSON body for POSTs, form field
for multipart POSTs, `?context=` for GETs) — alongside the required `visitorId`
/ `conversationId` identity. base64url keeps PII (email / phone) out of plaintext server
access logs, the devtools network tab, and analytics proxies — but it is
**obfuscation, not encryption**: TLS already protects the bytes in transit,
and anyone can base64url-decode it. Never put a secret in context.

### Key rotation

The dashboard has no key rotation today.

- **public key** — public by design: it only names the deployment. Limit where it works with the deployment's
  **Allowed websites**.
- **secret key** — keep it on your server. If it leaks, create a new deployment (it gets new keys), move your embed
  and your token signing to it, and delete the old one. User tokens signed with the old key stop verifying, so every
  verified user is signed out until your server signs new ones.

---

## GDPR + regional compliance

### Data processing agreement (DPA)

Help AI is the data processor; you are the data controller. Our DPA
is available on request and covers:

- Processing purposes.
- Sub-processor list.
- Data transfer mechanisms (SCCs).
- Deletion / return on contract termination.

### Consent management

The widget doesn't set cookies, but depending on your jurisdiction +
how you use `userContext`, you may need consent. Common patterns:

#### Pattern A — only mount after consent

```ts
window.addEventListener('consent-accepted', () => {
  init({ publicKey: '...', aiAgentDeploymentId: '01900000-0000-7000-8000-000000000000' });
});
```

No chat available until consent. Simple, strict.

#### Pattern B — memory-only without consent

```ts
const memoryAdapter = /* see recipes */;

init({
  publicKey: '...',
  aiAgentDeploymentId: "01900000-0000-7000-8000-000000000000",
  storage: consentGiven ? undefined : memoryAdapter,
});
```

Widget works without consent but state evaporates on tab close.

#### Pattern C — annotate visitors as consented

```ts
init({
  publicKey: '...',
  aiAgentDeploymentId: '01900000-0000-7000-8000-000000000000',
  userContext: consentGiven ? { id: userId } : undefined,
});
```

Anonymous (no user context) when no consent; context attached with
consent.

### Data subject requests

- **Access**: visitors can view their chat thread in the widget
  itself. For server-side exports, contact [support@help.ai](mailto:support@help.ai)
  with the `visitorId` or `userContext.id`.
- **Deletion**: clicking "New conversation" orphans the old thread
  from the client. For permanent deletion: contact support.
- **Portability**: export via server-side API. See dashboard → API docs.

### Region

Every deployment uses one data plane: `help.ai`, in the US (AWS us-east-1, us-west-2).

---

## Security audits

- **SOC 2 Type II** — annual. Report available on request
  (NDA required).
- **Pen testing** — quarterly external pen tests.
- **Dependency audit** — `bun audit` on every CI run. No
  high-severity vulns allowed in releases.
- **Bug bounty** — [help.ai/security](https://help.ai/security) — up
  to $10,000 for critical reports.

---

## What the widget can / can't do on your page

**Can do:**

- Render UI in its own shadow root.
- Listen to its own keyboard + pointer events.
- Store data under `helpai.*` localStorage keys.
- Fetch from the configured `baseUrl`.
- Record audio (with user permission) for voice input.
- Upload files the user attaches.

**Can't do:**

- Read or set cookies.
- Modify your page's DOM outside its own shadow root.
- Read your localStorage keys that don't start with `helpai.`.
- Intercept your form submissions.
- Mine cryptocurrency / run unrelated scripts.
- Navigate your page.
- Access `iframe` content across origins.

The source is available for audit — `dist/help-ai/elements.js`
is the production bundle; `src/*` is the un-minified source.

---

## Supply chain

- **Bundled runtime dependencies** are pinned in `package.json` and `bun.lock`.
- **No third-party analytics** in the widget itself. Anything you
  wire via hooks is your choice.
- **No CDN tracking**. We don't use CloudFlare Workers, Google
  Tag Manager, or any third-party on our CDN path. Direct from our
  infrastructure.

---

## Outage + incident response

- **Status page**: [help.ai/status](https://help.ai/status).
- **Incident notifications**: subscribe via the status page.
- **Degraded mode**: if the API is down, the widget still renders
  (the bundle is cached). Attempting to send shows an error. Cached
  chats remain viewable.

---

## Reporting a security issue

Please don't file public issues for vulnerabilities. Email
[security@help.ai](mailto:security@help.ai) with:

- The affected version.
- Steps to reproduce.
- The potential impact.
- PGP key: `0xCAFEBABE...` (download from
  [help.ai/.well-known/security.asc](https://help.ai/.well-known/security.asc)).

We respond within 24 hours and coordinate disclosure on your schedule.
