# WhatsApp CRM — Final Hardening Verification

**Verification date:** 2026-10-13  
**Production baseline:** `master` at `b14fdf8`  
**Scope:** remaining production-hardening work plus WA-01 through WA-17 verification  
**Safety:** development environment only; SQLite `:memory:`, `Http::preventStrayRequests()`, provider fakes. No production deploy, restart, migration, watchdog action, data repair, or real WhatsApp/Evolution request was performed.

## Executive decision

The code remediation is complete for the repository scope and the isolated regression suite is green. Deployment remains **conditional**, not automatic, because two items require production/staging evidence rather than more application code:

1. Back up and exercise the MySQL ENUM migration on a MySQL staging copy.
2. Inspect the production host's 87% disk usage before deleting or rotating anything.

Do not enable consent enforcement until existing customer consent records have been reviewed. Do not enable application recovery/watchdog as part of this deployment.

## Current verification results

| Check | Result |
|---|---:|
| Focused WhatsApp safety suite | 60 passed, 211 assertions |
| Full PHP suite on PHP 8.3 | 512 passed, 1,691 assertions |
| JavaScript tests | 116 passed, 0 failed |
| Vite production build | PASS, 626 modules |
| Pint on changed PHP files | PASS |
| HTTP isolation | PASS — unfaked outbound HTTP is denied |
| ESLint / Prettier advisory checks | Existing repository debt remains; no changed frontend production file in this hardening set |

`npm test` could not spawn Node's parallel test workers inside the Windows sandbox (`EPERM`). The same nine files were therefore executed serially, and all 116 tests passed. The production build was rerun with permission for esbuild's child process and passed.

## Remaining-hardening requirements

### 1. Batched operational pruning — FIXED

- Dry run remains the default.
- `--batch-size` and `--max-rows` bound each execution.
- Rows are selected/deleted by primary key in batches.
- A cache lock prevents concurrent runs.
- Schema, key and table allow-list checks fail closed.
- Unprocessed webhooks are preserved.
- Customer messages, conversations, contacts and consent evidence are excluded.
- Scheduled apply is disabled unless `WHATSAPP_AUDIT_PRUNE_ENABLED=true`.
- Tests cover dry run, boundaries, protected rows and opt-in apply.

Production apply remains intentionally disabled until backup and retention approval.

### 2. Evolution webhook security — FIXED IN CODE / CONFIGURATION REQUIRED

- Accepts the Evolution-compatible `apikey` or `x-webhook-secret` header.
- Query-string secrets are disabled by default and require an explicit compatibility flag.
- Missing/wrong secrets are rejected and unknown instances return 403.
- Full payloads and secrets are not logged.
- `main` and `main966` are validated against the allow-list.
- Local tests cover accepted/rejected headers, query compatibility and instance rejection.

Production must configure the same secret in Evolution and Laravel before enabling fail-closed verification.

### 3. Duplicate send, retry and crash ambiguity — FIXED

- A database claim precedes provider I/O.
- Open provider attempts prevent a second worker from sending.
- A real two-process SQLite concurrency test proves one accepted attempt and one busy result.
- UI request IDs prevent duplicate clicks from creating duplicate logical sends.
- Timeout/5xx responses that may have been accepted become `needs_reconciliation`; they are not reported as sent and are never retried automatically.
- Stale unfinished provider attempts become `needs_reconciliation`, not a new send.
- Manual inspection is the default. `--apply` plus an explicit `--mark-sent --provider-id` or `--allow-resend` decision is required to resolve a case.
- Retry and resend reject accepted or reconciliation-required messages.

### 4. Production disk usage — OPERATIONAL EVIDENCE REQUIRED

Application safeguards are implemented: warning at 85%, critical at 90%, upload blocking at the configured threshold, minimum-free-space enforcement and bounded audit retention. The application cannot determine which production directories consume the reported 87% from a local isolated test.

Read-only production inspection required before deploy approval:

```bash
df -hT /home/raitoai/public_html/whatsapp
du -xhd1 /home/raitoai/public_html/whatsapp 2>/dev/null | sort -h
du -xhd2 /home/raitoai/public_html/whatsapp/storage 2>/dev/null | sort -h | tail -n 40
du -xhd2 /var/lib/docker 2>/dev/null | sort -h | tail -n 40
journalctl --disk-usage
```

These commands are inspection only. No log, media or backup deletion is authorized by this report.

### 5. PII-safe logging — FIXED FOR WHATSAPP PATHS

- `SafeLogContext` hashes external identifiers and records exception classes instead of arbitrary exception text.
- Provider calls log instance/type/status only; message IDs are hashed where diagnostic correlation is needed.
- Webhook logs record event shape/count, not message bodies or payloads.
- Contact/group/history/media/health paths no longer log phone numbers, bodies, secrets or provider responses.
- Unit tests ensure sensitive example values never appear in the sanitized context.

Internal database IDs remain in operational logs; these are not customer content and are required for diagnosis.

### 6. Append-only outbound audit trail — FIXED

- Allowed, blocked, busy, started, accepted, failed and reconciliation decisions are recorded.
- Entries include operation/message/conversation/actor/sender/purpose/time/reason without body or phone number.
- Audit rows are append-only through the model; update/delete attempts throw and are tested.
- Retention is not enabled for this new ledger until policy approval.

Database superusers can always bypass an application model. Database-level tamper resistance would require a separate privileged audit store and is outside this application's trust boundary.

### 7. Media safety — FIXED WITH DOCUMENTED PROVIDER LIMITATION

- Size is validated before the application reads the upload into Base64.
- Empty, invalid-MIME, oversized and low-disk uploads are rejected.
- Upload limit defaults to 16 MiB and provider timeouts scale within a bound.
- Media sends are not automatically retried after ambiguous provider failures.
- Incoming recovery validates encoded size before decode, validates decoded size/MIME/name, removes orphan files after DB failure and never logs Base64/media keys.
- Image, document, audio, voice, oversize, invalid and recovery tests pass.

Evolution's working deployment path currently requires a JSON Base64 value; using a public URL previously caused the container fetch to hang. Base64 therefore still creates an unavoidable temporary memory copy. The 16 MiB limit bounds this risk. Moving media to object storage/signed URLs requires a separately proven Evolution-compatible architecture and was not guessed into production code.

### 8. `main` / `main966` isolation — FIXED

- Allow-listed instance resolution is used for text, media, audio, edit and delete.
- Optional `EVOLUTION_INSTANCE_API_KEYS` provides separate scoped credentials, with explicit fallback to the legacy shared key.
- Webhook source, last-webhook time, send failure count, health rows, alert keys, circuit breaker and rate buckets are instance-specific.
- Scheduler creates one named read-only health check per allowed instance.
- Tests prove different credentials and independent healthy/unavailable results without cross-impact.

### 9. Consent and opt-out — FIXED IN CODE / ROLLOUT PENDING

- Consent state, source, timestamp and immutable consent events exist.
- Inbound configured opt-out keywords record `opted_out`.
- Opted-out contacts are always blocked, even while general enforcement is disabled.
- Business-initiated sends can require documented opt-in when enforcement is enabled.
- Existing contacts are not silently treated as opted-in.

Keep `WHATSAPP_CONSENT_ENFORCEMENT_ENABLED=false` until records are reviewed and imported. This is a business-data rollout dependency, not an unimplemented code path.

### 10. Human takeover and automated replies — FIXED

- Auto-reply messages carry `automation_source=auto_reply` and the API exposes it.
- Assignment is rechecked inside the per-contact lock immediately before choosing/sending a rule.
- Assigned conversations suppress automation when configured.
- Incoming-event uniqueness, contact locking, cooldown and per-window caps prevent duplicate webhook replies and bot loops.
- Race/idempotency tests pass.

### 11. Queue safety and monitoring — FIXED

- Jobs have explicit bounded timeouts and `failOnTimeout` where appropriate.
- History synchronization has one 540-second timeout declaration (the accidental duplicate was removed); database `retry_after=660` remains larger.
- The production worker must continue consuming `webhooks,default`.
- Text retry is limited to failures proven before acceptance; media and ambiguous sends are not blindly retried.
- Pending, oldest-age and recent-failure metrics are grouped per queue and stored on health checks.
- The six existing production failed jobs shown during diagnosis are old Reverb payload-size failures, not current webhook backlog, and must not be retried with `queue:retry all`.

## WA-01 through WA-17 final status

| Finding | Status | Evidence summary |
|---|---|---|
| WA-01 Scheduler/recovery loop | FIXED | per-instance read-only schedule; bounded recovery remains disabled |
| WA-02 Consent/opt-out/purpose | FIXED IN CODE | enforcement rollout intentionally remains off |
| WA-03 Duplicate/race/retry | FIXED | real two-process test and reconciliation state/path |
| WA-04 Rate limiting | FIXED | instance/employee/contact isolation tests, including four employees |
| WA-05 Auto-reply idempotency | FIXED | unique incoming event + lock + cooldown |
| WA-06 Multi-instance isolation | FIXED | routing, credentials, webhook and health separation tests |
| WA-07 Ambiguous failures | FIXED | never claimed as sent; no automatic retry |
| WA-08 Webhook authentication | FIXED IN CODE | production secret alignment required |
| WA-09 Queue visibility | FIXED | per-queue backlog/age/failure metrics |
| WA-10 Disk capacity | PARTIALLY FIXED | guards/alerts complete; host usage analysis still required |
| WA-11 Logging privacy | FIXED FOR WHATSAPP SCOPE | sanitizer and log-content tests |
| WA-12 Human takeover/bot marker | FIXED | marker, lock-time assignment check and race tests |
| WA-13 Outbound auditability | FIXED | append-only event ledger and immutability tests |
| WA-14 Media memory/storage | PARTIALLY FIXED | bounded/tested; Base64 remains provider constraint |
| WA-15 Delivery ledger | FIXED | dedupe and forward-only receipt tests |
| WA-16 Reconnect classification | FIXED | no reconnect for connecting/restricted; recovery off |
| WA-17 Test assurance | FIXED | isolated PHP, JS, build and formatting evidence above |

## Database migrations required

Run only after backup and staging validation, and before new application code handles traffic:

1. `2026_10_13_000000_add_outbound_safety_controls.php`
2. `2026_10_13_000100_create_message_status_events_table.php`
3. `2026_10_13_000200_add_queue_metrics_to_health_checks_table.php`
4. `2026_10_13_000250_allow_sending_message_status.php`
5. `2026_10_13_000300_add_remaining_whatsapp_hardening.php`

Migration `000250` fixes the confirmed production incident where MySQL rejected `status="sending"`. SQLite represents enums as text, so the isolated suite proves application behavior but not MySQL's table-alter mechanics. Validate it on a MySQL staging copy first.

Migration `000300` adds the append-only outbound audit table, the automation marker, per-instance health identity and per-queue health metrics.

## Required environment settings

```dotenv
EVOLUTION_ALLOWED_INSTANCES=main,main966
EVOLUTION_INSTANCE_API_KEYS={}
EVOLUTION_WEBHOOK_REQUIRE_SECRET=true
EVOLUTION_WEBHOOK_ALLOW_QUERY_SECRET=false

WHATSAPP_OUTBOUND_CONTROLS_ENABLED=true
WHATSAPP_CONSENT_ENFORCEMENT_ENABLED=false
WHATSAPP_MAX_UNANSWERED_OUTBOUND=3
WHATSAPP_SEND_CLAIM_TIMEOUT_MINUTES=15

WHATSAPP_RATE_LIMITS_ENABLED=true
WHATSAPP_RATE_PER_INSTANCE_MINUTE=60
WHATSAPP_RATE_PER_EMPLOYEE_MINUTE=30
WHATSAPP_RATE_PER_CONTACT_WINDOW=10
WHATSAPP_RATE_CONTACT_WINDOW_SECONDS=600

WHATSAPP_CIRCUIT_BREAKER_ENABLED=true
WHATSAPP_CIRCUIT_FAILURE_THRESHOLD=3
WHATSAPP_CIRCUIT_FAILURE_WINDOW_SECONDS=300
WHATSAPP_CIRCUIT_COOLDOWN_SECONDS=300

WHATSAPP_AUTO_REPLY_SUPPRESS_WHEN_ASSIGNED=true
WHATSAPP_AUTO_REPLY_MAX_PER_CONTACT_WINDOW=3
WHATSAPP_AUTO_REPLY_CONTACT_WINDOW_MINUTES=60

WHATSAPP_MAX_UPLOAD_KB=16384
WHATSAPP_BLOCK_UPLOAD_AT_DISK_PERCENT=90
WHATSAPP_MINIMUM_FREE_BYTES=1073741824

WHATSAPP_QUEUE_PENDING_THRESHOLD=100
WHATSAPP_QUEUE_OLDEST_JOB_SECONDS=300
WHATSAPP_QUEUE_FAILED_THRESHOLD=1
WHATSAPP_AUDIT_PRUNE_ENABLED=false
EVOLUTION_APP_RECOVERY_ENABLED=false
DB_QUEUE_RETRY_AFTER=660
```

`EVOLUTION_INSTANCE_API_KEYS` may remain `{}` when both instances intentionally share the global key. If separate scoped keys exist, supply a JSON object through the secret manager; never commit it. Keep exactly one `EVOLUTION_ALLOWED_INSTANCES` line.

## Deployment plan

1. Create and verify a restorable DB/files backup.
2. Record current commit and service status.
3. Test all five migrations against a recent MySQL staging copy.
4. Put the application into the project's normal brief deploy flow.
5. Pull the reviewed commit and install dependencies.
6. Run `php artisan migrate --force`.
7. Run `php artisan optimize:clear`.
8. Restart php-fpm, `whatsapp-worker`, and `whatsapp-reverb` using their managed services, following R-8. Keep one queue worker with `--queue=webhooks,default`.
9. Run read-only per-instance health checks for `main` and `main966`.
10. Verify queue counts, webhook timestamps and logs. Use a controlled business-approved smoke test only after those checks.
11. Observe using `docs/POST_DEPLOY_OBSERVATION_CHECKLIST.md`.

This plan was documented only; none of it was executed by this verification.

## Rollback plan

1. Stop new application traffic using the normal maintenance/deploy mechanism.
2. Restore the previous application commit.
3. Do **not** blindly roll back the `sending` ENUM while in-flight rows may use it.
4. Prefer leaving additive columns/tables in place during an application rollback; the old code ignores them.
5. If schema rollback is mandatory, first verify there are no in-flight sends, take another backup, then run reviewed migration rollback. `000250` converts `sending` rows to `pending` before narrowing the ENUM.
6. Restart only the managed services required by R-8 and verify queue/webhook health.
7. Restore the database/files backup if migration rollback does not reproduce the previous state.

## Production data issue discovered during verification

The server audit reported 259 active conversations assigned to inactive employees. This can hide conversations or block replies even though webhooks are arriving. The existing repair command is dry-run by default. `conversations:repair-status --apply` would unassign those conversations and move them to `pending`; it does not delete messages or contacts. Because this changes production assignments, it requires a separate backup/approval and is not automatically embedded in the deployment.

## Final readiness

**Repository code: ready for review and a staged deployment.**  
**Production: not ready for an unreviewed immediate deploy.** Required gates are MySQL staging migration proof, verified backup, webhook-secret alignment, read-only disk analysis, and an explicit decision on the 259 inactive-assignee repairs. Consent enforcement and automated recovery remain disabled by design.
