# 13 — Security, privacy and compliance

**Status:** Draft. Written 2026-11-07. Legal statements are engineering summaries of secondary
sources and must be reviewed by counsel in each country before launch. Everything marked
**[VERIFY]** is a research item, not a decision.

## 1. Security controls (parity with Keiki's published posture, plus additions)

| Area | Control |
|---|---|
| Encryption at rest | All secrets (BYOK keys, developer/personal secrets, channel tokens, MCP headers, OAuth client secrets, webhook signing secrets) AES-256-GCM with per-value nonce and tag; data key from KMS (envelope), never in DB or source. Database volumes encrypted by provider. |
| Encryption in transit | TLS 1.2+ everywhere; HSTS; cookies `HttpOnly`, `Secure`, `SameSite=Lax`. |
| Credentials | API keys and OAuth tokens stored hashed (argon2id); shown once; scopable, expirable, rotatable, revocable. Passwords (if any) argon2id. Secrets write-only. |
| Keys out of the model | Secrets substituted host-side; placeholders in sandbox; stripped from prompts, transcripts, traces, tool args and errors; prefix-based redaction of pasted keys. Platform provider keys never reach sandboxes or generated code. |
| Tenant isolation | Server-side org scoping on every request; Postgres RLS as second layer; per-agent sandboxes; eval/playground never co-located with live turns; Mastra resource/thread ids carry org prefix; per-region databases. |
| Outbound safety | Webhooks, MCP endpoints, OpenAPI specs: HTTPS only, DNS-resolved and checked against private/link-local ranges at call time, no redirects followed, per-call timeouts, response size caps. |
| Inbound safety | Signature verification on Meta (`X-Hub-Signature-256`), Telegram (secret token), Twilio, Resend, Stripe/Mercado Pago webhooks; replay protection with timestamps; idempotency on provider ids. |
| Access | Roles owner/admin/member/viewer enforced in API and MCP (`403 viewer_read_only`); rate-limited sign-in without enumeration; server-side session expiry; SSO (Later). |
| Audit | Append-only audit log of dashboard, API and MCP changes (app role without `UPDATE`/`DELETE`, and a trigger that refuses them for every role); diffs redacted before insert; page `/[org]/settings/audit` and `GET /api/v1/audit`, CSV export on Max+ (T-145); staff console allowlisted and secret-redacting. |
| Prompt security | Prompt-injection detector annotates flagged inbound; tool results treated as untrusted input; approval gates on side effects; unsupported-claim guard on outputs. |
| Supply chain | Pinned dependencies, lockfile, Dependabot with monthly Mastra upgrades, SBOM, `npm audit` in CI, signed container images. |
| Backups | Daily snapshots + PITR on Postgres; object store versioning; quarterly restore test. |
| Incident response | Runbook with 72 h notification path (GDPR/LGPD), status page, on-call. |

Certifications: SOC 2 Type II and ISO 27001 are Later roadmap items driven by enterprise sales;
HIPAA is not a target. **[DECISION NEEDED]** on timing.

## 2. Data inventory and retention

| Data | Default retention | Configurable | Deletion path |
|---|---|---|---|
| Conversation messages | 365 days | 30–unlimited per org | Per conversation, per contact (DSAR), per org |
| Attachments | 90 days | 7–365 | With conversation; expiry job |
| Workflow state (stage and variables) | With the messages (idle time) | Follows `messages` | With conversation (close, DSAR); expiry job |
| Traces and spans | 14 days | 7–90 | Expiry job |
| Raw inbound events | 30 days | fixed | Expiry job |
| Signals | 90 days | fixed | Expiry job |
| Webhook delivery history | 30 days | fixed | Expiry job |
| Memory facts (working memory) | With contact | — | DSAR erase deletes Mastra resource |
| Audit log | 2 years | — | Org deletion after legal hold |
| Billing records | 10 years (tax law BR/MX/ES) | — | — |

Erasing a contact deletes messages, attachments, memory, identity cache, signals, workflow
states and presentation intents, and writes a non-authorising tombstone (external id hash) so a recycled
number cannot inherit history. Consent events are anonymised, not deleted (proof of the
opt-out); billing usage keeps its amounts without the turn, and payment requests keep their
amounts without the conversation or the agent's description. The export package lists the
contact's payment requests (amount in minor units, currency, status, dates, refunded amount,
description) without provider references, checkout links or connection secrets. Export packages
are deleted 24 h after they are built. Details: [06](06-domain-model.md) §2.7 (T-142).

**Retention jobs (T-141).** The daily `prune` maintenance task (03:00 UTC, one run at a time
under the Redis lock `prune:attachments`) applies this table per org with
`organizations.settings.retentionDays` (`messages` ≥ 30 or `null` for unlimited, `attachments`
7–365, `traces` 7–90; out-of-range values fall back to the default per key). In batches of 500
with `FOR UPDATE SKIP LOCKED`, it deletes: messages past their days, together with their
attachments (object and row), Mastra's memory copy (`mastra_messages` of the org's
conversations) and the workflow states that have not changed in that time
(`conversation_workflow_states`, T-162); the Mastra spans of the org's turns past `traces`; `inbound_events` older than 30
days; and attachments past `expires_at`. The `webhook-sweep` deletes webhook delivery history
after 30 days. Consent events and newer replies that pointed to a deleted message keep their row
with the reference set to null. Mastra's `storage.prune()` is not used: it takes one `maxAge` per
table for every tenant, so it can honour neither per-org days nor a legal hold.

`organizations.legal_hold = true` excludes the org from every retention delete until it is
lifted. It is a column, not a setting, so the org cannot lift it itself. `audit_log` and billing
records are never touched by these jobs. Each org that lost data gets one `audit_log` row
`retention.prune` with the counts per type (never content), and `charla_retention_deleted_total
{kind}` counts the rows on `/internal/metrics`. Signals get their 90-day job when their table
exists.

## 3. Jurisdictions

### 3.1 Brazil — LGPD (Lei 13.709/2018), ANPD
- Legal basis per processing purpose recorded per org (consent, contract performance,
  legitimate interest). Consent events per contact ([06](06-domain-model.md) §2.7).
- Privacy notice must state that AI is used in customer service and what the conversation
  collects; the agent's **disclosure line** covers the in-conversation part.
- Art. 20: right to review automated decisions → governed actions and handoffs give a human path;
  DSAR export includes action records.
- RIPD (impact report) template for tenants in regulated sectors **[VERIFY]**.
- International transfer: model providers in the US → SCC-equivalent clauses (ANPD standard
  clauses, Resolução CD/ANPD 19/2024) **[VERIFY]**; offer `br` data region for storage.
- ANPD lists AI as a 2026–2027 enforcement priority; PL 2338/2023 (AI framework) pending.
- Named encarregado (DPO) contact in Settings → Compliance.

### 3.2 Mexico — LFPDPPP (new law in force 2025-03-21), Secretaría Anticorrupción y Buen Gobierno
- Aviso de privacidad (short form in the first message or via link) per tenant; purpose-bound
  consent; **express consent** for sensitive and financial data and cross-border transfer
  **[VERIFY exact scope]**.
- ARCO rights → DSAR tooling.
- Stronger penalties; review internal AI policies (Baker McKenzie guidance).

### 3.3 Colombia — Ley 1581/2012, Decreto 1377/2013, SIC
- Prior informed authorisation; published treatment policy; RNBD registration thresholds
  **[VERIFY current thresholds and any 2026 SIC guidance on AI/chatbots]**.

### 3.4 Argentina — Ley 25.326 (in force), AAIP; reform bills 3397-D-2026, 1751-D-2026 pending
- Database registration with AAIP; EU adequacy status; watch the reform.

### 3.5 Spain and Portugal / EU — GDPR + LOPDGDD (ES) and Lei 58/2019 (PT); AEPD, CNPD; EU AI Act
- DPA with each tenant (we are processor; tenant is controller); sub-processor list (model
  providers, STT, hosting, Meta, **the WhatsApp BSP**); SCCs for US transfers; `eu` data
  region. If the primary BSP (Kapso) is not EU-based or lacks an EU DPA **[VERIFY]**, Spanish
  and Portuguese tenants are offered 360dialog (Berlin) as provider.
- Portugal: same GDPR regime under CNPD; no chatbot-specific CNPD guidance found **[VERIFY]**;
  pt-PT disclosure and consent texts.
- **EU AI Act Article 50 (in force 2026-08-02)**: people must be told they are interacting with
  an AI unless obvious. The agent's disclosure line on first contact is **on by default and
  cannot be disabled for EU-region orgs**; tenants deploying our agents are also "providers" of
  the chatbot in some readings, so the dashboard shows the obligation. Penalties up to €15M or
  3% turnover.
- Not high-risk under Annex III for ordinary customer service; verticals (credit, employment,
  health triage) may be — flag in template metadata **[VERIFY]**.

### 3.6 United States (Hispanic market)
- TCPA consent for outbound SMS/voice; 10DLC registration; state privacy laws (CCPA etc.);
  WhatsApp itself is not SMS but marketing templates still need documented opt-in.

### 3.7 Meta platform policies
- WhatsApp Business Messaging Policy and Commerce Policy: opt-in before business-initiated
  messages, prohibited verticals, 24 h window, template categories, quality rating. Our
  dashboard enforces opt-in evidence for marketing templates and blocks prohibited categories
  at template creation.

### 3.8 Italy — GDPR + Codice Privacy (D.Lgs. 196/2003), Garante; EU AI Act; AGCM
- Same GDPR processor obligations as Spain and Portugal; `eu` data region; Italian DPA
  template and privacy notice.
- The Garante has no chatbot-specific rule as of late 2026 but lists AI processing in its 2026
  inspection plan and fined Character.AI in July 2026 **[VERIFY against garanteprivacy.it]**;
  expect scrutiny of training-data use (we do not train on tenant conversations; state it in the
  DPA) and of transparency.
- Competition-law context (AGCM interim measures against Meta's WhatsApp AI terms) affects cost
  and availability of AI replies on WhatsApp in Italy, not our privacy posture.

### 3.9 Rest of Latin America (Tier B footprint)
Summary table in [03 §8](03-market-and-channels-latam.md). Engineering consequences are the same
everywhere: consent ledger, disclosure, DSAR, retention, regional storage. Country counsel review
is sequenced with the Tier B promotion schedule. Highlights to track: Chile's Ley 21.719 enters
into force on 2026-12-01 with a new agency; Uruguay and Argentina hold EU adequacy; Ecuador's
LOPDP requires impact assessments; Costa Rica (PRODHAB), Panama (ANTAI), Dominican Republic
(Ley 172-13) and Nicaragua (Ley 787) have registration or notice duties **[VERIFY each]**;
Bolivia, Venezuela, Guatemala and Honduras lack comprehensive laws **[VERIFY]**; El Salvador
passed a law in 2024 **[VERIFY]**. Cuba is excluded for sanctions reasons; Venezuela payments
are limited by sanctions and FX rules.

## 4. Product controls that implement the above

1. **AI disclosure**: per agent, default on, localised ("Soy un asistente virtual de {{org}}…"),
   sent in the first reply of a conversation and after 30 days of silence; mandatory for `eu`.
2. **Consent ledger** with locale keyword sets, provider events, operator changes; exposed via
   webhooks and API.
3. **Data region** per org (`us`, `eu`, `br` all at GA, since Brazil is a launch market and
   resourcing is not a constraint) covering Postgres, object store, runtime workers and Redis. Model providers remain where they are; the tenant chooses provider
   and region via BYOK when needed.
4. **Retention settings** per org with hard floors for billing/audit.
5. **DSAR tooling**: export (JSON + media) and erase per contact, with webhook notification and
   audit entry; API endpoints in [10](10-api-reference.md) §2.5.
6. **Sub-processor registry** page and DPA generator (es/pt/en). T-144: the registry is
   `docs/legal/subprocessors.json`, public at `/legal/subprocessors`; `Settings → Compliance`
   generates each tenant's privacy notice (HTML and PDF) from per-country templates (MX, BR, AR,
   CO, CL, PE, ES, PT, IT, generic es-419) in `apps/web/src/server/privacy/templates.ts`. A
   template is published at the tenant's short link `/n/<slug>` only once its legal review is
   recorded there (`review.status = "reviewed"`); until then it downloads as a draft. The DPA
   generator is still pending.
7. **Sensitive-vertical templates** carry a compliance checklist (health, finance, legal).
8. **PII redaction** for traces and exporters (`redactInputs`), and in eval case creation from
   real conversations (anonymise before freezing).

## 5. Threat model highlights

| Threat | Mitigation |
|---|---|
| Prompt injection via inbound message or tool result leading to unauthorised tool call | Scopes from identity webhook, approval policy on writes, injection detector, untrusted-result processors |
| Model-supplied ids used for authorisation at the tenant | Documented rule: tenants must authorise by `context.principal`, never by `input` ids; SDK helpers enforce |
| Webhook spoofing to our ingress | Provider signatures, replay windows, idempotency |
| Our outbound webhooks replayed | Timestamped HMAC, 5-minute tolerance, `eventId` dedupe |
| SSRF via tenant-provided URLs | Resolution-time private-range checks, no redirects |
| Secret exfiltration through model output or sandbox | Host-side substitution, redaction processors, no network from codemode |
| Cross-tenant data access | RLS + org scoping + region separation; tests in CI that attempt cross-org reads |
| Account takeover of a WhatsApp number (SIM swap) | Identity webhook with DM evidence; `approvalProof: verified` for money; re-verification on number change `system` events |
| Runner replay executing a side effect twice | Idempotency keys on every send and tool call; action `executing` state |
