# Customer centre: account tools, scoped knowledge, tickets and PII masking (CC)

Research date: 13 November 2026. Code read on `track/UI-components` at `2b316fbc`. Anything not confirmed in code or on a source is marked [unverified]. **Approved (owner delegated, my recommendation, 2026-11-14).**

## Summary

- **Fix before building.** (1) Any tool name the model returns is executed, not only the tools exposed in that request; the admin assistant's `change_settings` handler sits on the same filter without a capability check. (2) Chat history is read and continued by `session_id` alone, without checking the stored `user_id`, and the session cookie survives logout. (3) Password-protected posts are indexed in full, and `wp_search_posts` returns them to any logged-in user. Members-only posts carry no access information in the index.
- **Recommendation.** Fixes and access scoping first (CC-2 to CC-7), then a read-only customer tool framework with WooCommerce orders, then memberships, PII masking and helpdesk tickets. Write actions and real-time live chat need a separate decision.
- **Principle.** Identity comes only from the WordPress session of the REST request; the model never supplies a user ID or email.

## 1. What exists today

| Seed item | Today | Files |
|---|---|---|
| Logged-in identity | `wp_rest` nonce only for logged-in visitors, sent as `X-WP-Nonce`, so cookie auth sets the current user on `/kimaai/v1/chatbot` (`__return_true`). Rows store `get_current_user_id()` | `app/ChatBot/ChatbotAssets.php` (l. 187-201), `src/chatbot/adapters/wp/wpTransport.js`, `app/ChatBot/ChatBot.php`, `app/Ai/AiService.php` (l. 436) |
| Tool execution | `ChatbotToolRegistry` filters what is exposed, but `executeTool()` runs any returned name via `kimaai_chatbot_tool_call`; `ToolRouter::call()` falls back to any enabled custom function; `AdminAssistantSettingsTools` answers `change_settings` there without `current_user_can()` | `app/ChatBot/Tools/ToolCallOrchestrator.php` (l. 317), `premium/app/FunctionCall/ToolRouter.php` (l. 70-110), `app/AdminAssistant/AdminAssistantSettingsTools.php` (l. 33-75) |
| Tool results | Callbacks get only `$args`. Results are stored in the chat row (`tool_calls_trace`) and streamed as SSE `tool` events | `app/Ai/AiService.php` (l. 401-410), `app/ChatBot/ChatbotStreamingRequestRunner.php` (l. 256) |
| `UserTools`, WooCommerce | `UserTools`: admin PHP functions via `eval()`, no user context. WooCommerce: product tools only. Nothing for orders, subscriptions, memberships, LMS or helpdesks | `premium/app/FunctionCall/UserTools.php`, `premium/app/Integrations/WooCommerce/*` |
| Index visibility | Only `publish` (attachments `inherit`) is indexed; no `post_password` check, so protected posts are embedded in full. Chunk metadata has `post_id`, `post_type`, `lang` and others, no access field | `premium/app/Embedding/EmbeddingQueue.php` (l. 47, 178), `Embedding.php` (l. 494-510), `ContentProcessor.php` (l. 85-92) |
| Query-time filter | `MetaFilter` translates `field => value or list` (AND) for Pinecone and Qdrant; `buildMetaFilter()` sets only `lang` and `post_type` | `premium/app/Embedding/MetaFilter.php`, `ToolRouter.php` (l. 560-604) |
| Other retrieval paths | Keyword leg excludes protected posts. `wp_search_posts` has no password check (WordPress adds one only for logged-out searches). Content awareness takes `postId` from the client and ignores membership rules | `KeywordSearch/AbstractWpQueryProvider.php` (l. 105), `ToolRouter.php` (l. 412), `app/ChatBot/ChatbotContentAwareness.php` (l. 59) |
| Sessions | `/chatbot/history?session_id=` returns any session's rows; `sessionId` in the POST body continues any session | `app/ChatBot/ChatBot.php` (l. 156-166), `ChatbotRequestPreparer.php` (l. 102), `app/Models/ChatModel.php` (l. 124) |
| Handoff | On negative-feedback threshold or ungrounded answer: plain transcript once per session by email and/or webhook, then `kimaai_chatbot_handoff`. No visitor-initiated handoff, no reference for the visitor | `premium/app/ChatBot/HumanHandoff.php`, settings in `app/Admin/config/chatbot.php` (l. 1584-1660) |
| PII | `PiiRedactor` (email, IPv4, phone) is used only for MCP output and audit. Nothing is masked before the model call | `premium/app/Mcp/Redaction/PiiRedactor.php`, `premium/app/Mcp/Audit/AuditLogger.php` |
| Rate limits, audit | Daily per-IP message limit (HMAC key). Audit table exists only for MCP | `app/ChatBot/ChatbotRateLimiter.php`, `premium/app/Mcp/Audit/McpAuditModel.php` |

Whether a provider can be made to call an undeclared tool name is [unverified]; it is a missing server-side check either way. Whether MemberPress or PMPro return full text or a teaser from `the_content` during cron indexing is [unverified].

## 2. How others do it

- **Intercom Fin.** Data connectors call your API with a configured token. Intercom "strongly recommends" JWT user authentication against impersonation and warns Fin "could accidentally share information from another user when parameter passing". Sensitive connectors can be limited to workflows; logs kept 14 days. Audiences (person and company attributes) decide which content and connectors each group gets.
- **Chatbase.** Server-signed JWT identity; contact data reachable only in actions that reference contact fields.
- **AI Engine Woo Basics** lists order tracking; its customer verification is not documented [unverified]. **Tidio Lyro** asks for email plus order number, weaker than a session.
- **Kapa.** Source groups scope a deployment, chosen by a client-side widget attribute: deployment scoping, not per-user security.
- **OWASP LLM Top 10 (2025).** Excessive agency (LLM06) and vector weaknesses (LLM08): least-privilege tools, permission-aware vector stores, enforcement outside the prompt.
- **Helpdesk APIs.** Zendesk: Requests API for end users, Tickets API with a requester. Freshdesk: `POST /api/v2/tickets`, API key. Help Scout: `POST /v2/conversations`, OAuth 2.0. FluentSupport: `POST /wp-json/fluent-support/v2/customer-portal/tickets` as the logged-in customer.

## 3. Design

### 3.1 Security model (applies to every item)

1. **Identity from the request only.** `CustomerContext` comes from `get_current_user_id()` after cookie and nonce validation and is passed by the router. No tool schema has a user ID, email or customer ID parameter; an order number is checked against the context and a mismatch answers "not found".
2. **Exposure equals permission.** Customer tools are exposed only to logged-in users with an allowed role; only names in this request's `tools` list run (CC-2).
3. **Minimal output.** A field allowlist per tool: no addresses, phone, full email or payment data. Results flagged `sensitive` are stored as name, status and record count only, and left out of SSE events.
4. **Read-only first.** Later write actions: the model proposes, a confirmation card runs the existing server-side `command: callback` path.
5. **Limits and audit.** Per user and tool rate limit (default 30 per hour) on `ChatbotRateLimitModel`; table `kimaai_tool_audit` (time, user, session, tool, redacted arguments, outcome), pruned with session retention.
6. **Session binding.** Rows with `user_id > 0` are readable or continuable only by that user; the session cookie is cleared on `wp_logout` and rotated on `wp_login`.
7. **Nonce expiry.** On `rest_cookie_invalid_nonce` the widget refreshes the nonce once, then continues anonymously with a notice.

### 3.2 Knowledge scoped by access

- **Access resolver** (`app/Access/AccessResolver.php`, free, because free content awareness needs `canView()`): `tokensForPost()` and `canView($post_id, $user_id)`, adapters for core, MemberPress (`current_user_can('mepr-active', ...)` [unverified API]), PMPro (`pmpro_has_membership_access()`), LearnDash (`sfwd_lms_has_access()`) and a filter `kimaai_content_access_tokens`. Tokens: `public`, `role:<slug>`, `mepr:<id>`, `pmpro:<level>`, `ld_course:<id>`, `deny`.
- **Indexing.** Protected and non-public posts are never indexed. `public` only if every adapter lets user 0 view; unmappable restrictions get `deny`. Members-only posts are indexed only with "Include members-only content" on, tokens in an `access` list per chunk. Attachments inherit the parent's tokens.
- **Query time.** `buildMetaFilter()` always adds `access IN tokensForUser()` (anonymous: `public`), so chunks without `access` never match (default deny). A metadata-only backfill fills existing vectors [unverified in current SDK wrappers]. Each hit is rechecked with `canView()` with a small over-fetch; the same check guards `wp_get_post`, `wp_search_posts`, the keyword leg and content awareness. Scope never comes from the client or the model.

### 3.3 Session-bound customer tools

`AbstractCustomerTool` (premium) registers through `kimaai_tools_registry` with `requiresUser: true` and an output allowlist. First tools, all read-only:

| Tool | Source | Returns |
|---|---|---|
| `my_orders` (status filter, limit 5) | `wc_get_orders(['customer_id' => ctx])` | number, date, status label, total, item names and quantities, My Account link |
| `my_order` (order number) | `wc_get_order()`, checks `get_customer_id()` | as above plus shipping method and tracking if a supported plugin stores it [unverified] |
| `my_subscriptions` | `wcs_get_users_subscriptions(ctx)` | status, product, next payment date, link |
| `my_memberships` | MemberPress, PMPro | membership or level name, status, expiry, account link |
| `my_courses` | `learndash_user_get_enrolled_courses()` [unverified signature] | course, progress, next lesson link |

### 3.4 Tickets and handoff

- `HelpdeskAdapterInterface`: `createTicket(TicketDraft): TicketRef`, optional `listMyTickets()`. Adapters: FluentSupport (internal `rest_do_request` to the customer-portal route as the current user [unverified]), Zendesk, Freshdesk, Help Scout. The requester comes from the WordPress user; anonymous visitors may type an email only to create a ticket, never for lookups.
- Ticket body: masked transcript, page URL, reason; the visitor sees a card with the reference.
- A `request_human` tool and a "Talk to a person" button create a ticket (fallback: today's email or webhook); `HumanHandoff::escalate()` uses the same channel.
- As built (CC-14 to CC-16): helpdesk tickets only for logged-in users; visitors are handed over by email or webhook with a `KA-` reference. An email field for visitors' helpdesk tickets is not built yet.
- Real-time live chat in the widget is a separate decision (own agent inbox or handover to an existing chat tool), not in this track.
- API tokens in settings, overridable by `wp-config.php` constants; there is no encryption helper today.

### 3.5 PII masking before the model call

- Move `PiiRedactor` to `app/Privacy/`, keep the MCP use, add IBAN and Luhn-checked card numbers.
- Apply it to the message and history before `AiService` builds the provider input, and to tool output outside a tool's allowlist. Cards and IBANs are always masked, also in storage; email and phone masking is a setting. Names are not detected (documented limit).

### 3.6 Free and premium

Free: CC-2, CC-3, the password and status fix in free code, PII masking (privacy baseline). Premium: access-scoped retrieval (needs embeddings), customer tools, helpdesk adapters, visitor handoff.

### 3.7 Settings

New section `customerCentre` in `app/Admin/config/chatbot.php`, same schema style (`section`, `type`, `default`, `component`, `props.onlyPremium`, `condition`): `ccToolsEnabled` (false), `ccAllowedRoles` (`['customer','subscriber']`), per-tool toggles, `ccToolRateLimit` (30). In `embedding.php`: `indexMembersOnly` (false). In the handoff section: `handoffChannel` (`email|webhook|fluentsupport|zendesk|freshdesk|helpscout`), per-adapter credentials, `handoffVisitorButton` (false). Privacy: `piiMaskInput` (true), `piiMaskEmailPhone` (false).

### 3.8 Tests

- PHPUnit with fakes: faked current user, fake order store, fake access and helpdesk adapters, `MetaFilter` with `access` for both providers, orchestrator refusing unexposed names.
- Integration: WooCommerce orders for two users; A asking for B's order number gets "not found".
- Playwright in Playground (`tests/e2e/playground.json` plus a WooCommerce step): customer sees own orders; a logged-out visitor gets no customer tools and no members-only answer; logout clears the conversation. Model calls stubbed.

### 3.9 Manual helpdesk checks

The adapters are tested against fakes only. Before a release, check each once on a test account of the service, with "Human handoff" on and the channel selected, logged in as a customer, by asking the chatbot for a person.

- **FluentSupport.** The customer portal route answers an internal request as the logged-in customer with `ticket.id` [unverified]. Expect a ticket in Fluent Support → Tickets from that customer, its title "Your conversation with the … assistant", the transcript with card numbers and IBANs masked, and the reference `#<id>` on the widget's ticket card.
- **Zendesk.** Settings or `KIMAAI_ZENDESK_SUBDOMAIN`, `KIMAAI_ZENDESK_EMAIL` and `KIMAAI_ZENDESK_API_TOKEN` (an agent's API token, Admin Center → Apps and integrations → Zendesk API). Expect a ticket in Views → Unsolved tickets with the customer's WordPress email as requester (a new end user when unknown) and the reference `#<id>` on the card. A wrong token shows `HTTP 401` in the KimaAI log and the conversation goes by email instead.
- **Freshdesk.** Settings or `KIMAAI_FRESHDESK_DOMAIN` and `KIMAAI_FRESHDESK_API_KEY` (Profile settings → View API key). Expect an open ticket, priority low, from the customer's WordPress email (a new contact when unknown), and `#<id>` on the card.
- **Help Scout.** Settings or `KIMAAI_HELPSCOUT_APP_ID`, `KIMAAI_HELPSCOUT_APP_SECRET` and `KIMAAI_HELPSCOUT_MAILBOX_ID` (Your profile → My Apps; the mailbox ID from the mailbox URL). Expect an active conversation in that mailbox from the customer's WordPress email, and `#<id>` on the card (the ID from the `Resource-ID` header, not the conversation number) [unverified].
- **For every helpdesk.** Export the settings without secrets and check that the token, key or app secret is blank; check that the API calls go out from the server only (none in the browser's network tab).

## 4. Items

Each item is one commit with its tests.

| Item | Title | Acceptance criteria |
|---|---|---|
| CC-2 | Only exposed tools run | Orchestrator rejects a call whose name is not in the request's `tools` with "Unknown tool"; `AdminAssistantSettingsTools` returns null unless `current_user_can('manage_options')`; unit tests for both |
| CC-3 | Conversations bound to their user | History and continuation of a session with `user_id > 0` refused for another user or a visitor (403, no rows); cookie cleared on logout and rotated on login; e2e logout test |
| CC-4 | Password-protected and non-public posts out of every answer path | Indexing skips `post_password`; a purge removes existing protected chunks; `wp_search_posts` and content awareness exclude them for all users; tests per path |
| CC-5 | Access resolver with membership adapters | `canView()` and `tokensForPost()` for core, MemberPress, PMPro, LearnDash and the filter; unknown restriction yields `deny`; content awareness, `wp_get_post` and the keyword leg use `canView()` |
| CC-6 | Access tokens in the index | Every new chunk has `access`; metadata-only backfill job for existing vectors; members-only posts indexed only with the setting on; index health counts chunks without `access` |
| CC-7 | Retrieval scoped to the visitor at query time | `access IN user tokens` always applied (Pinecone and Qdrant); results rechecked with `canView()`; anonymous e2e never receives a members-only snippet; setting changes need no re-embed |
| CC-8 | Customer tool framework | `CustomerContext`, `AbstractCustomerTool`, role setting, per-user rate limit, `kimaai_tool_audit` table with migration, sensitive results kept out of the stored trace and SSE |
| CC-9 | WooCommerce: my orders | `my_orders` and `my_order` read-only; foreign or unknown order gives "not found"; output allowlist test; Playground e2e with two customers |
| CC-10 | WooCommerce Subscriptions | `my_subscriptions`, exposed only when the plugin is active |
| CC-11 | Memberships: MemberPress and PMPro | `my_memberships` per active plugin; tests with fakes |
| CC-12 | LearnDash courses | `my_courses` with progress and next lesson link |
| CC-13 | PII masking before the model call | Shared redactor with IBAN and Luhn card detection; input and tool output masked; settings; MCP unchanged; tests on fixtures |
| CC-14 | Helpdesk adapters and FluentSupport | Interface, FluentSupport adapter creating a ticket as the current user, masked transcript, ticket card in the widget |
| CC-15 | Zendesk, Freshdesk and Help Scout adapters | Ticket created with server-side requester; credentials via settings or constants; HTTP faked in tests, documented manual check per service |
| CC-16 | Visitor-requested handoff | `request_human` tool and button; `HumanHandoff` uses the selected channel; once per session; reference shown to the visitor |

## Decisions (owner delegated, my recommendation, 2026-11-14)

1. **PII masking is free.** Protecting visitors' data is not an upsell.
2. **Customer tools default to the `customer` and `subscriber` roles**; a setting widens them. Least privilege first.
3. **Live chat inside the widget** waits until CC-16 ships; it is listed under "Later" in the roadmap.
4. **CC-2 and CC-3 first.** CC-2 shipped with SEC (#421, SEC-1 and SEC-2), as did most of CC-4 (SEC-3: indexing, reconcile purge, `wp_get_post`, `wp_search_posts`, knowledge search). CC-3 is the first item of this track; CC-4 covers only what SEC left open.
5. **Chunks without access tokens stay searchable** (2026-11-14). Until the backfill has run, the vector filter is "access IN user tokens OR access missing" (Pinecone `$or` with `$exists: false`, Qdrant `should` with `is_empty`); the `canView()` check of every hit drops what the visitor may not see. This replaces the default deny in 3.2, so an upgrade does not empty knowledge search.

## Sources

- Intercom Fin, data connectors: <https://fin.ai/help/en/articles/13975792-create-data-connectors-for-fin>
- Intercom Fin, audiences and targeting: <https://fin.ai/help/en/articles/10903029-manage-audiences-and-targeting-for-fin> and <https://www.intercom.com/help/en/articles/9357948-manage-knowledge-audiences-and-content-targeting-for-fin>
- Chatbase identity verification: <https://www.chatbase.co/docs/developer-guides/identity-verification> ; client-side custom actions: <https://www.chatbase.co/docs/developer-guides/website-integration/client-side-custom-actions>
- AI Engine Woo Basics: <https://meowapps.com/products/mwai-woo-basics/>
- Tidio, order status from Shopify: <https://www.tidio.com/integrations/get-order-status-from-shopify/>
- Kapa source groups: <https://docs.kapa.ai/knowledge-sources/use-source-groups>
- OWASP Top 10 for LLM applications 2025 (secondary summary; official page not retrieved [source missing]): <https://blog.barracuda.com/2024/11/20/owasp-top-10-risks-large-language-models-2025-updates>
- Zendesk requests for end users: <https://developer.zendesk.com/documentation/ticketing/managing-tickets/creating-and-managing-requests/> ; tickets: <https://developer.zendesk.com/api-reference/ticketing/tickets/tickets/>
- Freshdesk API v2: <https://developers.freshdesk.com/api>
- Help Scout create conversation: <https://developer.helpscout.com/mailbox-api/endpoints/conversations/create/> ; authentication: <https://developer.helpscout.com/mailbox-api/overview/authentication>
- FluentSupport REST API: <https://fluentsupport.com/rest-api>
- WooCommerce `wc_get_orders()`: <https://developer.woocommerce.com/docs/features/orders/wc-get-orders/> ; Subscriptions functions: <https://woocommerce.com/document/subscriptions/develop/functions/>
- PMPro access filter: <https://www.paidmembershipspro.com/hook/pmpro_has_membership_access_filter/>
- MemberPress rule features (`mepr-active`): <https://memberpress.com/pt/docs/advanced-rule-features/>
- LearnDash `sfwd_lms_has_access`: <https://developers.learndash.com/hook/sfwd_lms_has_access/>
