wacrm/src/app/api/whatsapp/templates/sync
Arnas Donauskas 242ecdf2c5
fix(whatsapp): require a write role on the WhatsApp write routes
The five write handlers under /api/whatsapp resolved the caller's
account_id straight off their profile row, which only proves account
membership — never a role. Every other write surface in the app
(account/, ai/, automations/, flows/, quick-replies/) already goes
through requireRole(); this family was missed.

RLS did not backstop it, because each of these routes calls Meta
*before* it persists anything:

  - broadcast: makes no database write at all, so there was no policy
    involved on any path
  - send / react: the Meta call precedes the insert, so the outbound
    message or reaction reached the customer and only the local mirror
    was refused
  - templates/submit, templates/sync: push to Meta before upserting the
    local catalog

Gate each handler at the role its data class already implies, matching
lib/auth/roles and the migration 017 policies:

  - send, react, broadcast  -> 'agent'  (canSendMessages)
  - templates/submit, sync  -> 'admin'  (canEditSettings, and the
                                        message_templates_insert/update
                                        policies)

Also switches these handlers to toErrorResponse so an authorization
failure returns 401/403 instead of being folded into a generic 500. The
two template routes keep their existing message-surfacing 500 for
non-auth errors, so a Meta failure still reports its own reason.

Adds role-enforcement coverage to the send route's test: a viewer is
refused with 403 and sendTemplateMessage is never called, while an agent
passes through.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
2026-07-29 23:02:03 +03:00
..
route.ts fix(whatsapp): require a write role on the WhatsApp write routes 2026-07-29 23:02:03 +03:00