> ## Documentation Index
> Fetch the complete documentation index at: https://docs.switchbord.ai/llms.txt
> Use this file to discover all available pages before exploring further.

# Audit Logging & Monitoring

> Switchbord's audit trail for security-relevant operations, observability stack, account alerts, and planned breach detection and notification capabilities.

## Audit Log Architecture

Switchbord maintains an `audit_logs` table that records security-relevant operations performed within each workspace. The audit trail is designed to answer: *who did what, to which object, in which workspace, and when.*

### Schema

```sql theme={null}
CREATE TABLE audit_logs (
  id            uuid PRIMARY KEY DEFAULT gen_random_uuid(),
  workspace_id  uuid NOT NULL REFERENCES workspaces(id),
  actor_user_id uuid REFERENCES auth.users(id),  -- null for system-initiated actions
  entity_type   text NOT NULL,  -- e.g. 'contact', 'workspace_member', 'api_key', 'secret'
  entity_id     text NOT NULL,  -- ID of the affected entity
  action        text NOT NULL,  -- e.g. 'gdpr_erasure', 'member_removed', 'secret_updated'
  metadata      jsonb,          -- action-specific context (sanitized, no PII values)
  created_at    timestamptz NOT NULL DEFAULT now()
);
```

All audit log queries are filtered by `workspace_id`, ensuring workspace isolation extends to the audit trail itself.

## What Is Logged

### Currently Implemented

| Event                     | Entity Type        | Action                     | Triggered By                                            |
| ------------------------- | ------------------ | -------------------------- | ------------------------------------------------------- |
| Workspace member removed  | `workspace_member` | `member_removed`           | Admin/owner removing a member                           |
| GDPR erasure requested    | `contact`          | `gdpr_erasure`             | Erasure endpoint `DELETE /api/contacts/[id]/gdpr`       |
| GDPR data export          | `contact`          | `gdpr_export`              | Export endpoint `GET /api/contacts/[id]/gdpr`           |
| Secret created/updated    | `secret`           | `secret_updated`           | Workspace admin updating Vault secret                   |
| Secret validation failure | `secret`           | `secret_validation_failed` | Invalid or malformed secret rejected on write           |
| API key created           | `api_key`          | `api_key_created`          | Developer creating a new API key                        |
| API key revoked           | `api_key`          | `api_key_revoked`          | Developer/admin revoking a key                          |
| Channel settings updated  | `channel_settings` | `channel_settings_updated` | Workspace admin modifying WhatsApp channel config       |
| Consent event (opt-in)    | `consent`          | `consent_opt_in`           | Contact opts in via WhatsApp                            |
| Consent event (opt-out)   | `consent`          | `consent_opt_out`          | Contact opts out via WhatsApp                           |
| Account alert triggered   | `account_alert`    | `alert_triggered`          | System detecting threshold breach or anomaly (BORD-189) |

### Writing an Audit Log Entry

```typescript theme={null}
await writeAuditLog({
  workspaceId: string,
  actorUserId: string | null,
  entityType: 'contact' | 'workspace_member' | 'api_key' | 'secret' | 'channel_settings' | 'consent' | 'account_alert',
  entityId: string,
  action: string,
  metadata?: Record<string, unknown>, // never include raw PII values
});
```

<Note>
  Audit log entries are written synchronously within the same database transaction as the operation they record where possible. This ensures the audit trail reflects actual operations, not just attempted ones.
</Note>

## Planned Audit Log Enhancements

### Read-Access Logging (BORD-168)

Currently, only write operations (mutations, deletions) are logged. Planned work includes logging read access to PII tables — specifically tracking which users accessed which contact records and when. This is required for full HIPAA §164.312(b) compliance.

### Tamper-Evident Hash Chain (BORD-168)

Each audit log entry will include a cryptographic hash of the previous entry in the workspace's log chain. This creates a tamper-evident structure where modification of any past entry invalidates all subsequent hashes. Planned implementation uses SHA-256 chaining.

```
entry_n.hash = SHA256(entry_(n-1).hash || entry_n.data)
```

### Immutable Export to Object Storage (BORD-168)

Audit logs will be periodically exported to write-once object storage (e.g., Supabase Storage with immutable bucket policy) to provide a backup that cannot be modified even by database administrators.

## Observability Stack

### Error Monitoring: Sentry

Switchbord integrates with Sentry for real-time error monitoring across all application surfaces. Sentry captures:

* Unhandled exceptions in API routes
* Worker job failures
* Frontend JavaScript errors

Error reports are scrubbed to avoid capturing PII in stack traces. Configured via `packages/observability`.

### Log Aggregation: Better Stack

Application logs from Vercel and Railway are aggregated in Better Stack (formerly Logtail). Structured logs include request IDs for correlation across services.

### Health Monitoring

The `/api/health` and `/api/ready` endpoints are publicly accessible and monitored by uptime services to detect availability degradation.

### Account Alerts (BORD-189)

Switchbord ships real-time account-level alerts that surface operational and security-relevant events to workspace operators:

* **WhatsApp API health alerts** — notifications when the Meta API returns elevated error rates, rate-limit responses, or webhook delivery failures for a workspace's phone numbers
* **Secret expiry alerts** — warnings when Vault-stored tokens or API keys are approaching expiration
* **Consent threshold alerts** — notifications when a workspace's opt-out rate exceeds a configurable threshold, indicating potential compliance risk
* **Usage anomaly alerts** — flags for unusual message volume spikes, bulk contact operations, or API key usage patterns

Alerts are delivered via the in-app notification feed and can be forwarded to Slack or webhook endpoints. All alert events are recorded in the `audit_logs` table under the `account_alert` entity type.

## Planned: Security Incident Detection (BORD-166)

The following capabilities are planned as part of BORD-166:

* **Anomaly detection:** Flag unusual patterns such as bulk contact exports, high API key usage volume, or access from unexpected IP ranges
* **Security event monitoring:** Dedicated alerting for security-relevant events (failed auth bursts, concurrent session anomalies, privilege escalation attempts)
* **Alerting integration:** Webhook-based alerts to Slack, PagerDuty, or operator-configured endpoints

## Planned: Breach Notification Workflow (BORD-166)

GDPR Art.33 requires notification to the supervisory authority within **72 hours** of becoming aware of a personal data breach. Art.34 may require notification to affected data subjects.

Planned capabilities to support this obligation:

1. **Incident detection triggers** that create an incident record with timestamp of detection
2. **Breach assessment workflow** — guided questions to determine notification scope
3. **Notification draft generation** — pre-populated templates for DPA submission
4. **72-hour countdown timer** — visible in the admin UI once an incident is declared
5. **Affected workspace and contact scoping** — identify which contacts' data may have been involved

<Warning>
  The 72-hour breach notification workflow is currently **planned** (BORD-166). Organizations with immediate compliance requirements should establish a manual incident response procedure until this capability is implemented.
</Warning>

## Retention of Audit Logs

Audit logs are retained for the workspace's configured `data_retention_days` period, with a minimum retention of **365 days** regardless of the workspace setting. This ensures that audit trails remain available for post-incident investigation and compliance audits.

GDPR erasure requests do **not** delete audit log entries. Entries recording the fact of an erasure are themselves retained as evidence of compliance.

## Compliance Mapping

| Standard  | Control                                               | Implementation                                                          |
| --------- | ----------------------------------------------------- | ----------------------------------------------------------------------- |
| ISO 27001 | A.12.4.1 — Event logging                              | `audit_logs` table for write operations (shipped BORD-158)              |
| ISO 27001 | A.12.4.2 — Protection of log information              | Workspace-scoped, admin-read-only (tamper-evident chain planned)        |
| ISO 27001 | A.12.4.3 — Administrator and operator logs            | Member removal, secret changes, channel settings, consent events logged |
| HIPAA     | §164.312(b) — Audit controls                          | Write-operation audit trail; read-access logging planned BORD-168       |
| GDPR      | Art.33 — Breach notification to supervisory authority | 72h workflow planned BORD-166                                           |
| GDPR      | Art.34 — Breach notification to data subjects         | Scope assessment planned BORD-166                                       |
| SOC 2     | CC7.1 — System monitoring                             | Sentry, Better Stack, health endpoints, account alerts (BORD-189)       |
| SOC 2     | CC7.2 — Anomalous activity evaluation                 | Anomaly detection planned BORD-166                                      |

<Tip>
  For the full compliance control mapping, see the [Compliance Matrix](/security/compliance-matrix).
</Tip>
