diff --git a/cmd/route_parity/main.go b/cmd/route_parity/main.go index 23b24533..ef773d5e 100644 --- a/cmd/route_parity/main.go +++ b/cmd/route_parity/main.go @@ -239,6 +239,7 @@ var criticalRoutes = []route{ {Method: "POST", Path: "/api/v1/accounts/:account_id/instagram/authorization", Controller: "api/v1/accounts/instagram/authorizations#create", Source: "routes.rb:327"}, {Method: "POST", Path: "/api/v1/accounts/:account_id/tiktok/authorization", Controller: "api/v1/accounts/tiktok/authorizations#create", Source: "routes.rb:331"}, {Method: "POST", Path: "/api/v1/accounts/:account_id/notion/authorization", Controller: "api/v1/accounts/notion/authorizations#create", Source: "routes.rb:335"}, + {Method: "POST", Path: "/api/v1/accounts/:account_id/whatsapp/authorization", Controller: "api/v1/accounts/whatsapp/authorizations#create", Source: "routes.rb:339"}, {Method: "DELETE", Path: "/api/v1/accounts/:account_id/integrations/shopify", Controller: "api/v1/accounts/integrations/shopify#destroy", Source: "routes.rb:361"}, {Method: "POST", Path: "/api/v1/accounts/:account_id/integrations/shopify/auth", Controller: "api/v1/accounts/integrations/shopify#auth", Source: "routes.rb:363"}, {Method: "GET", Path: "/api/v1/accounts/:account_id/integrations/shopify/orders", Controller: "api/v1/accounts/integrations/shopify#orders", Source: "routes.rb:364"}, diff --git a/docs/CHATWOOT_PARITY_DEVELOPMENT_PLAN.md b/docs/CHATWOOT_PARITY_DEVELOPMENT_PLAN.md index d6930e10..2d522adb 100644 --- a/docs/CHATWOOT_PARITY_DEVELOPMENT_PLAN.md +++ b/docs/CHATWOOT_PARITY_DEVELOPMENT_PLAN.md @@ -49,16 +49,16 @@ Hermes task landing checklist: ## Current Baseline -- Current tracking checkpoint: 2026-06-06 Instagram/TikTok authorization parity checkpoint, prepared as `feat(channels): align social authorization`. -- Latest implementation checkpoint: this checkpoint, prepared as `feat(channels): align social authorization`. +- Current tracking checkpoint: 2026-06-06 WhatsApp embedded signup authorization parity checkpoint, prepared as `feat(channels): align whatsapp authorization`. +- Latest implementation checkpoint: this checkpoint, prepared as `feat(channels): align whatsapp authorization`. - Latest documentation/tooling checkpoint: this tracker update for P3.24 plus the landed parity tracker history; this document is the active follow-up plan and supersedes `.hermes/plans/*`. - Plan landing status: complete for the current known Hermes plans and user-confirmed scope. Future work should update this file directly instead of opening a parallel tracker. -- Worktree status at this implementation checkpoint: Instagram and TikTok account authorization from `reference/chatwoot/config/routes.rb:327/331`, `Api::V1::Accounts::Instagram::AuthorizationsController`, `Api::V1::Accounts::Tiktok::AuthorizationsController`, their request specs, callback return hints, and reused dashboard `instagramClient.js`/`tiktokClient.js` are implemented. GoChat now exposes administrator-gated `POST /api/v1/accounts/:account_id/instagram/authorization` and `POST /api/v1/accounts/:account_id/tiktok/authorization`, returns Chatwoot `{ success: true, url }` payloads, builds provider authorize URLs with Chatwoot scopes/redirects/provider parameters, signs account callback state with optional `return_to`, and keeps previously aligned Twitter/Google/Microsoft/Notion behavior intact. Live API/browser/enterprise smoke still needs the full PostgreSQL/Redis/Meilisearch/GoChat/Vite/Chrome stack. +- Worktree status at this implementation checkpoint: WhatsApp embedded signup authorization from `reference/chatwoot/config/routes.rb:339`, `Api::V1::Accounts::Whatsapp::AuthorizationsController`, `Whatsapp::EmbeddedSignupService`, channel creation/reauthorization/token/phone validation services, request specs, and reused dashboard `whatsappChannel.js` are implemented. GoChat now exposes authenticated-agent/admin `POST /api/v1/accounts/:account_id/whatsapp/authorization`, validates `code/business_id/waba_id`, creates WhatsApp Cloud inboxes, supports inbox reauthorization, returns Chatwoot `{ success, id, name, channel_type, message? }` payloads, and keeps the previously aligned Twitter/Google/Microsoft/Instagram/TikTok/Notion behavior intact. Live API/browser/enterprise smoke still needs the full PostgreSQL/Redis/Meilisearch/GoChat/Vite/Chrome stack. - Next executable implementation checkpoint: continue Phase 2/3 drift audit, Phase 6 placeholder audit, or B12 live smoke from fresh reference/smoke evidence. - `go test ./...` passes when run outside the restricted socket sandbox; focused Shopify handler/service tests pass in the sandbox. -- Route dump succeeds with `947` registered routes after Instagram/TikTok authorization tracking. +- Route dump succeeds with `948` registered routes after WhatsApp authorization tracking. - Route parity artifacts now exist under `docs/parity/` and are generated by `cmd/route_parity`. -- Tracked frontend-critical route audit covers 410 Chatwoot routes: 397 exact, 0 method-compatible, 13 parameter-compatible, 0 missing. The 13 parameter-compatible routes are Gin-internal parameter-name differences for nested AgentCapacityPolicy users/inbox limits, dashboard app member `:id` names, plus the public article `.md`/`.png` suffixes served through the same external article route dispatcher. +- Tracked frontend-critical route audit covers 411 Chatwoot routes: 398 exact, 0 method-compatible, 13 parameter-compatible, 0 missing. The 13 parameter-compatible routes are Gin-internal parameter-name differences for nested AgentCapacityPolicy users/inbox limits, dashboard app member `:id` names, plus the public article `.md`/`.png` suffixes served through the same external article route dispatcher. - `/api/v1/widget` stubs are burned down and public inbox/contact/conversation/message core flows are backed by real handlers. - Handler test stability fixes are committed into the baseline before feature parity work continues. - `.codegraph/` is generated indexing output and is not part of tracked product code. @@ -140,6 +140,7 @@ This table is the shortest authoritative handoff view. If an older lower section | Priority | Workstream | Current state | Next checkpoint | Commit close rule | | --- | --- | --- | --- | --- | +| 0 | P3.32 WhatsApp authorization parity | Implemented for reused dashboard WhatsApp embedded signup and reauthorization flow: `POST /api/v1/accounts/:account_id/whatsapp/authorization` is registered and tracked from `routes.rb:339`, authenticated agents and administrators can call it like Chatwoot's controller, missing `code`, `business_id`, and `waba_id` return `422 { success: false, error }`, new authorization exchanges the Meta embedded-signup code, fetches WABA phone info, validates token WABA access, creates a WhatsApp Cloud channel/inbox with embedded-signup provider config, sets up the webhook URL, and returns raw `{ success: true, id, name, channel_type: "whatsapp" }`; reauthorization validates the same phone number, refreshes provider config/access token/phone ID, clears `reauthorization_required`, updates inbox channel config/name, and returns the same raw payload plus the reauthorization success message. | Keep in Review; reopen only if live WhatsApp embedded-signup smoke exposes Meta API version/config-source drift, Graph API error-body wording drift, webhook setup side-effect drift, health-check reauthorization prompting drift, or frontend payload drift beyond the inspected controller/spec/service/frontend contract. | Focused WhatsApp authorization service tests, handler/router/route-parity tests, route dump/parity regeneration (`948` routes; `398 exact`, `13 parameter-compatible`, `0 missing out of 411`), full `go test ./...`, and `git diff --check` must pass before commit. | | 0 | P3.31 Instagram/TikTok authorization parity | Implemented for reused dashboard Instagram and TikTok connect/reauthorization flows: `POST /api/v1/accounts/:account_id/instagram/authorization` and `POST /api/v1/accounts/:account_id/tiktok/authorization` are registered and tracked from `routes.rb:327/331`, both routes are administrator-gated like Chatwoot's shared OAuth authorization controller, responses return raw `{ success: true, url }`, Instagram authorize URLs target `https://api.instagram.com/oauth/authorize` with Chatwoot's required Instagram business scopes, `enable_fb_login=0`, and `force_authentication=1`, TikTok authorize URLs target `https://www.tiktok.com/v2/auth/authorize` with Chatwoot's required TikTok business scopes and `client_key`, and both sign account callback state with optional `return_to`. | Keep in Review; reopen only if live Instagram/TikTok OAuth smoke exposes GlobalID state compatibility requirements beyond signed callback state, provider config-source drift, onboarding return routing drift, or frontend payload drift beyond the inspected authorization controllers/specs/frontend clients. | Focused social authorization handler/router/route tests, route dump/parity regeneration (`947` routes; `397 exact`, `13 parameter-compatible`, `0 missing out of 410`), full `go test ./...`, and `git diff --check` must pass before commit. | | 0 | P3.30 Google/Microsoft authorization parity | Implemented for reused dashboard Gmail/Outlook connect and reauthorization flows: `POST /api/v1/accounts/:account_id/google/authorization` and `POST /api/v1/accounts/:account_id/microsoft/authorization` are registered and tracked from `routes.rb:319/323`, both routes are administrator-gated like Chatwoot's shared OAuth authorization controller, responses return raw `{ success: true, url }`, Google authorize URLs target `https://accounts.google.com/o/oauth2/auth` with `email profile https://mail.google.com/`, `prompt=consent`, and `access_type=offline`, Microsoft authorize URLs target `https://login.microsoftonline.com/common/oauth2/v2.0/authorize` with Chatwoot's IMAP/SMTP/openid/profile/email scope and no prompt, and both sign account callback state for existing email OAuth callbacks. | Keep in Review; reopen only if live Gmail/Outlook OAuth smoke exposes GlobalID state compatibility requirements beyond signed callback state, provider config-source drift, onboarding return routing drift, or frontend payload drift beyond the inspected authorization controllers/specs/frontend clients. | Focused email OAuth authorization handler/router/route tests, route dump/parity regeneration (`945` routes; `395 exact`, `13 parameter-compatible`, `0 missing out of 408`), full `go test ./...`, and `git diff --check` must pass before commit. | | 0 | P3.29 Twitter authorization parity | Implemented for reused dashboard Twitter connect flow: `POST /api/v1/accounts/:account_id/twitter/authorization` is registered and tracked from `routes.rb:315`, the route is administrator-gated like Chatwoot's controller, the response returns raw `{ success: true, url }`, the request-token call uses Twitter OAuth1 signing with configured consumer key/secret and frontend `/twitter/callback?state=...`, and the returned URL targets `/oauth/authorize?oauth_token=...`. | Keep in Review; reopen only if live Twitter OAuth smoke exposes request-token signing/header drift, Redis request-token mapping requirements beyond signed callback state, provider base URL drift, or frontend payload drift beyond the inspected authorization controller/spec/frontend contract. | Focused Twitter authorization handler/router/route tests, route dump/parity regeneration (`943` routes; `393 exact`, `13 parameter-compatible`, `0 missing out of 406`), full `go test ./...`, and `git diff --check` must pass before commit. | @@ -150,7 +151,7 @@ This table is the shortest authoritative handoff view. If an older lower section | 0 | P3.24 Slack integration parity | Implemented for reused dashboard Slack settings flow: no-trailing and trailing singleton routes are registered for create/update/delete, `PUT` and `PATCH` update both work, create accepts frontend `code` and exchanges it for a Slack access token, hooks are persisted with `app_id: slack` and disabled status, update accepts frontend `reference_id`, fetches real private/public Slack channels with pagination, joins public channels, persists `reference_id/settings.channel_name/status`, create/update return raw Chatwoot app payloads with hooks, list-all returns raw channel arrays, invalid channels return Chatwoot's `422 { error }`, and delete returns empty `200 OK`. | Keep in Review; reopen only if live Slack OAuth/channel smoke exposes OAuth redirect, provider error, app serializer, or Slack channel pagination drift beyond the inspected controller/builder/spec/frontend contract. | Focused Slack handler/service tests, route dump/parity regeneration, sandbox focused `go test`, escalated full `go test ./...`, and `git diff --check` passed. | | 0 | P3.23 nested contact inbox creation API | Implemented for Chatwoot nested contact inbox creation: raw JSON/form/query params are accepted, contact and inbox are account-scoped, missing source IDs are generated through Chatwoot channel rules, duplicate contact+inbox+source rows are returned idempotently, `hmac_verified` is persisted on creation, and the response is raw `{ source_id, inbox }` rather than the local model/envelope. | Keep in Review; reopen only if live CRM/new-conversation smoke exposes inbox access-policy, unsupported channel, or serializer drift beyond the inspected controller/builder/Jbuilder contract. | Focused nested ContactInbox handler/service/repository tests, route parity check, full `go test ./...`, and `git diff --check` passed. | | 1 | P3.2a invitation/confirmation mail parity | Implemented for current non-SSO reference behavior: profile resend is no longer a TODO-only log, new invited agents and unconfirmed invited profile resends generate reset-password invitation links, normal unconfirmed profile resends generate confirmation links, `users.unconfirmed_email` is modeled for email-update routing, and fakeable/environment SMTP mailers keep default tests offline. | Keep in Review; reopen only if reused frontend smoke or fresh reference evidence exposes additional Devise confirmation states outside excluded SSO/SAML/LDAP/OIDC variants. | Focused profile and agent invitation tests, combined handler/service/repository/router/migrate/app tests, full `go test ./...`, and `git diff --check` passed. | -| 2 | Phase 2/3 drift | Tracked route parity is 0 missing for the current 410-route critical set; dashboard `/app` shell routes from `routes.rb:19-20`, `.well-known` app association and custom-domain challenge routes from `routes.rb:657-660`, Twilio callback routes from `routes.rb:639-640`, enterprise Twilio voice routes from `routes.rb:643-646`, root Linear/Shopify/Notion OAuth callback routes from `routes.rb:630/634/654`, root Twitter/Google/Microsoft/Instagram/TikTok callback routes from `routes.rb:626/649-652`, assignment policy routes from `routes.rb:306-313`, help-center portal/category/article routes from `routes.rb:385-404`, public help-center portal/sitemap/article/category/search/article-detail routes from `routes.rb:590-601`, enterprise contact outbound voice call from `routes.rb:216`, account agent-bot routes from `routes.rb:94-97`, account webhook routes from `routes.rb:342`, account integration app/hook routes from `routes.rb:345-348`, account Slack routes from `routes.rb:350-352`, account Dyte routes from `routes.rb:357-358`, account Shopify routes from `routes.rb:361-364`, account Linear routes from `routes.rb:365-373`, account Notion authorization/destroy routes from `routes.rb:335/379`, account Twitter/Google/Microsoft/Instagram/TikTok authorization routes from `routes.rb:315/319/323/327/331`, dashboard app routes from `routes.rb:130`, canned response routes from `routes.rb:114`, notification subscription routes from `routes.rb:440`, team/team-member routes from `routes.rb:296-300`, conversation participant routes from `routes.rb:150`, conversation direct upload route from `routes.rb:151`, conversation draft message routes from `routes.rb:152`, conversation inbox assistant route from `routes.rb:165`, conversation reporting events route from `routes.rb:166`, and account reporting events route from `routes.rb:234` are now explicitly tracked. Notification list/action serializers, user notification-settings raw payloads, campaigns raw payload/display-id routes, Devise password reset/confirmation payloads, CRM shared attachment payloads plus fixed 100-row attachment pagination, account/settings payloads, assignable-agent payloads, agent index full-list behavior, agent create/update/delete defaults/errors/scope, account agent-bot route/payload/mutation behavior, account webhook payload/mutation behavior, integration app/hook payload behavior, account Slack OAuth/channel payload behavior, account Dyte create/join payload behavior, account Shopify customer-order payload behavior, account Linear GraphQL issue payload behavior, account Notion authorization/destroy behavior, account Twitter/Google/Microsoft/Instagram/TikTok authorization behavior, dashboard app raw payload/serializer behavior, canned response raw payload/search/delete behavior, notification subscription payload behavior, team update/frontend route behavior, conversation participant route/payload/final-set update behavior, conversation direct upload ActiveStorage behavior, conversation draft message Redis-key-equivalent behavior, conversation inbox assistant Copilot payload behavior, conversation reporting-event raw array behavior, account reporting-events payload/filter/pagination behavior, label CRUD payloads, custom filters, custom attribute definitions, contact outbound voice calls, assignment policy CRUD and inbox binding payloads, Twilio inbound/status callbacks, enterprise Twilio voice callbacks, Linear/Shopify/Notion root integration callbacks, Shopify OAuth auth redirects, root channel OAuth callbacks, help-center portal/category/article payloads, dashboard app shell route behavior, app association JSON payloads, Cloudflare custom hostname verification, public widget popular-article lists, public help-center category list/show payloads, public portal show/default-locale payloads, public portal search payloads, public article show/markdown/tracking routes, and public sitemap XML now match the inspected Chatwoot contract. | Continue the next evidence-backed route/controller/serializer drift after Instagram/TikTok authorization parity or from B12 findings. | Regenerate parity artifacts when routes change and add endpoint-family fixture tests. | +| 2 | Phase 2/3 drift | Tracked route parity is 0 missing for the current 411-route critical set; dashboard `/app` shell routes from `routes.rb:19-20`, `.well-known` app association and custom-domain challenge routes from `routes.rb:657-660`, Twilio callback routes from `routes.rb:639-640`, enterprise Twilio voice routes from `routes.rb:643-646`, root Linear/Shopify/Notion OAuth callback routes from `routes.rb:630/634/654`, root Twitter/Google/Microsoft/Instagram/TikTok callback routes from `routes.rb:626/649-652`, assignment policy routes from `routes.rb:306-313`, help-center portal/category/article routes from `routes.rb:385-404`, public help-center portal/sitemap/article/category/search/article-detail routes from `routes.rb:590-601`, enterprise contact outbound voice call from `routes.rb:216`, account agent-bot routes from `routes.rb:94-97`, account webhook routes from `routes.rb:342`, account integration app/hook routes from `routes.rb:345-348`, account Slack routes from `routes.rb:350-352`, account Dyte routes from `routes.rb:357-358`, account Shopify routes from `routes.rb:361-364`, account Linear routes from `routes.rb:365-373`, account Notion authorization/destroy routes from `routes.rb:335/379`, account Twitter/Google/Microsoft/Instagram/TikTok authorization routes from `routes.rb:315/319/323/327/331`, account WhatsApp authorization route from `routes.rb:339`, dashboard app routes from `routes.rb:130`, canned response routes from `routes.rb:114`, notification subscription routes from `routes.rb:440`, team/team-member routes from `routes.rb:296-300`, conversation participant routes from `routes.rb:150`, conversation direct upload route from `routes.rb:151`, conversation draft message routes from `routes.rb:152`, conversation inbox assistant route from `routes.rb:165`, conversation reporting events route from `routes.rb:166`, and account reporting events route from `routes.rb:234` are now explicitly tracked. Notification list/action serializers, user notification-settings raw payloads, campaigns raw payload/display-id routes, Devise password reset/confirmation payloads, CRM shared attachment payloads plus fixed 100-row attachment pagination, account/settings payloads, assignable-agent payloads, agent index full-list behavior, agent create/update/delete defaults/errors/scope, account agent-bot route/payload/mutation behavior, account webhook payload/mutation behavior, integration app/hook payload behavior, account Slack OAuth/channel payload behavior, account Dyte create/join payload behavior, account Shopify customer-order payload behavior, account Linear GraphQL issue payload behavior, account Notion authorization/destroy behavior, account Twitter/Google/Microsoft/Instagram/TikTok authorization behavior, account WhatsApp embedded-signup creation and reauthorization behavior, dashboard app raw payload/serializer behavior, canned response raw payload/search/delete behavior, notification subscription payload behavior, team update/frontend route behavior, conversation participant route/payload/final-set update behavior, conversation direct upload ActiveStorage behavior, conversation draft message Redis-key-equivalent behavior, conversation inbox assistant Copilot payload behavior, conversation reporting-event raw array behavior, account reporting-events payload/filter/pagination behavior, label CRUD payloads, custom filters, custom attribute definitions, contact outbound voice calls, assignment policy CRUD and inbox binding payloads, Twilio inbound/status callbacks, enterprise Twilio voice callbacks, Linear/Shopify/Notion root integration callbacks, Shopify OAuth auth redirects, root channel OAuth callbacks, help-center portal/category/article payloads, dashboard app shell route behavior, app association JSON payloads, Cloudflare custom hostname verification, public widget popular-article lists, public help-center category list/show payloads, public portal show/default-locale payloads, public portal search payloads, public article show/markdown/tracking routes, and public sitemap XML now match the inspected Chatwoot contract. | Continue the next evidence-backed route/controller/serializer drift after WhatsApp authorization parity or from B12 findings. | Regenerate parity artifacts when routes change and add endpoint-family fixture tests. | | 3 | Phase 6 placeholder audit | Widget/public/webhook critical placeholders are burned down; inbox WhatsApp health/register-webhook and sync-template drift are closed; refreshed `docs/parity/placeholder_audit.md` shows only webhook nil-handler fallbacks still call `chatwootParityStub`; dashboard conversation transcript/custom-attribute response drift and message retry status drift are closed. | Keep in Review; reopen only if fresh `rg`, route smoke, or B12 finds a frontend-reachable placeholder/stub in account/contact/conversation/message/inbox/widget/public paths. | `rg` placeholder audit and `scripts/parity_frontend_smoke.sh --check` are recorded; no reused-frontend blocker is ownerless. | | 4 | P3.9 account agent-bot API | Implemented for the reused dashboard AgentBots settings route with no-trailing-slash routes, PATCH update, raw Jbuilder-style payloads, account mutation scope, system-bot show/list visibility, empty `200 OK` delete, and full reset/avatar action payloads. | Keep in Review; reopen only if live settings smoke exposes avatar upload storage or administrator-secret gating drift. | Focused AgentBot handler tests, service/router focused tests, route dump/parity regeneration, full `go test ./...`, and `git diff --check` passed. | | 5 | P3.10 account webhooks API | Implemented for the reused dashboard Webhooks settings route with PATCH update, Chatwoot `{ payload }` list/mutation serializers, nested `{ webhook: ... }` bodies, generated secret, account-scoped mutations, URL/subscription validation, optional inbox serialization, and empty `200 OK` delete. | Keep in Review; reopen only if live settings smoke exposes audit writer or delivery-signature drift beyond the existing delivery service boundary. | Focused webhook handler/service/router tests, migration test, route dump/parity regeneration, full `go test ./...`, and `git diff --check` passed. | @@ -177,6 +178,7 @@ These rows are the executable development plan from this point forward. A checkp | ID | Owner files | Reference files | Work to land | Exit gate | | --- | --- | --- | --- | --- | +| P3.32 WhatsApp authorization parity | `internal/service/whatsapp_authorization_service.go`, `internal/handler/api/v1/inbox_handler.go`, `internal/router/router.go`, `cmd/route_parity/main.go`, WhatsApp authorization service tests | `reference/chatwoot/config/routes.rb:338-339`, `reference/chatwoot/app/controllers/api/v1/accounts/whatsapp/authorizations_controller.rb`, `reference/chatwoot/spec/controllers/api/v1/accounts/whatsapp/authorizations_controller_spec.rb`, `reference/chatwoot/app/services/whatsapp/embedded_signup_service.rb`, `reference/chatwoot/app/services/whatsapp/channel_creation_service.rb`, `reference/chatwoot/app/services/whatsapp/reauthorization_service.rb`, `reference/chatwoot/app/services/whatsapp/token_exchange_service.rb`, `reference/chatwoot/app/services/whatsapp/phone_info_service.rb`, `reference/chatwoot/app/services/whatsapp/token_validation_service.rb`, `reference/chatwoot/app/javascript/dashboard/api/channel/whatsappChannel.js` | Done. WhatsApp embedded signup now matches the reused dashboard boundary: the account route is tracked and registered; authenticated agents/admins can create or reauthorize; missing required params return Chatwoot-shaped `422` errors; Meta code exchange, phone info, and token WABA-access checks run through a fakeable HTTP boundary; new channels create WhatsApp Cloud inboxes with embedded-signup provider config and webhook setup; reauthorization validates phone-number continuity, refreshes access token/phone/provider config, clears `reauthorization_required`, updates inbox channel config/name, and returns raw `{ success, id, name, channel_type, message? }` payloads. | Review by `feat(channels): align whatsapp authorization`; focused WhatsApp authorization service tests cover create, reauthorize, validation, and provider failures; handler/router/route-parity focused tests pass; route dump/parity regenerated to `TOTAL: 948` and `398 exact, 13 parameter-compatible, 0 missing out of 411`; full `go test ./...` and `git diff --check` must pass. | | P3.24 Slack integration parity | `internal/handler/api/v1/slack_integration_handler.go`, `internal/service/slack_integration_service.go`, `internal/repository/integration_hook_repo.go`, `internal/handler/api/v1/integration_hook_handler.go`, `cmd/route_parity/main.go`, Slack handler/service tests | `reference/chatwoot/config/routes.rb:350-352`, `reference/chatwoot/app/controllers/api/v1/accounts/integrations/slack_controller.rb`, `reference/chatwoot/lib/integrations/slack/hook_builder.rb`, `reference/chatwoot/lib/integrations/slack/channel_builder.rb`, `reference/chatwoot/app/views/api/v1/accounts/integrations/slack/create.json.jbuilder`, `reference/chatwoot/app/views/api/v1/accounts/integrations/slack/update.json.jbuilder`, `reference/chatwoot/app/views/api/v1/models/_app.json.jbuilder`, `reference/chatwoot/app/views/api/v1/models/_hook.json.jbuilder`, `reference/chatwoot/spec/requests/api/v1/accounts/integrations/slack_request_spec.rb`, `reference/chatwoot/app/javascript/dashboard/api/integrations.js`, `reference/chatwoot/app/javascript/dashboard/store/modules/integrations.js` | Done. Chatwoot Slack singleton behavior is implemented for the reused dashboard flow: frontend no-trailing `POST/PATCH/DELETE` routes and Rails `PUT` update are registered alongside trailing aliases; create accepts `code`/`inbox_id`, exchanges OAuth against Slack, persists disabled `app_id: slack` hooks with access tokens; update accepts `reference_id`, fetches private/public Slack channels with cursor pagination, joins public channels, persists `reference_id`, `settings.channel_name`, and enabled status only when the channel exists; create/update return the raw app partial with hooks; list-all returns raw Slack channel arrays; invalid channel returns `422 { error: "Invalid slack channel. Please try again" }`; delete returns empty `200 OK`. | Review by `feat(integrations): align slack parity`; focused handler tests cover no-trailing create raw app payload, empty delete, and PUT route availability; service tests cover OAuth exchange redirect/body, disabled hook creation, channel fetch/update/join, invalid/not-found, and raw channel lists through a fake Slack client; route parity is `379 exact, 13 parameter-compatible, 0 missing out of 392`; escalated full `go test ./...` and `git diff --check` passed. | | P3.23 nested contact inbox creation parity | `internal/handler/api/v1/contact_handler.go`, `internal/service/contact_inbox_service.go`, `internal/repository/contact_inbox_repo.go`, `internal/handler/api/v1/crm_serializer.go`, `internal/router/router.go`, `cmd/route_parity/main.go`, nested contact inbox handler/service/repository tests | `reference/chatwoot/config/routes.rb:212`, `reference/chatwoot/app/controllers/api/v1/accounts/contacts/contact_inboxes_controller.rb`, `reference/chatwoot/app/controllers/concerns/hmac_concern.rb`, `reference/chatwoot/app/builders/contact_inbox_builder.rb`, `reference/chatwoot/app/views/api/v1/accounts/contacts/contact_inboxes/create.json.jbuilder`, `reference/chatwoot/app/views/api/v1/models/_contact_inbox.json.jbuilder`, `reference/chatwoot/spec/controllers/api/v1/accounts/contacts/contact_inboxes_controller_spec.rb` | Done. Chatwoot `ContactInboxBuilder` behavior is implemented for `POST /api/v1/accounts/:account_id/contacts/:contact_id/contact_inboxes`: raw JSON/form/query params provide `inbox_id`, optional `source_id`, and `hmac_verified`; contact and inbox resolution is account-scoped; missing source IDs are generated by supported channel (`api`/`web_widget` UUID, email, sms phone, whatsapp phone without `+`, twilio sms/whatsapp medium); existing contact+inbox+source rows are returned idempotently; `hmac_verified` is set on creation; tokens are generated; inbox is preloaded; and the response is only `{ source_id, inbox: inbox_slim }`. | Review by `feat(contacts): align contact inbox creation`; focused handler tests cover raw payload shape, HMAC creation, generated source IDs, email idempotency, cross-account inbox rejection, and missing-phone Twilio failure; service tests cover WhatsApp/Twilio generation and idempotency; repository tests cover contact+inbox+source lookup; route parity, full `go test ./...`, and `git diff --check` passed. | | P3.2a invitation/confirmation mail parity | `internal/service/profile_service.go`, `internal/service/profile_confirmation_mailer.go`, `internal/handler/api/v1/profile_handler.go`, `internal/service/agent_service.go`, `internal/repository/agent_repo.go`, `internal/model/user.go`, `migrations/000032_add_users_unconfirmed_email.*`, profile/agent handler tests | `reference/chatwoot/app/controllers/api/v1/accounts/agents_controller.rb`, `reference/chatwoot/app/builders/agent_builder.rb`, `reference/chatwoot/app/views/devise/mailer/confirmation_instructions.html.erb`, `reference/chatwoot/spec/mailers/confirmation_instructions_spec.rb`, `reference/chatwoot/spec/enterprise/mailers/devise_mailer_spec.rb` for non-SAML invitation wording only | Done. A shared fakeable confirmation mailer builds Chatwoot-shaped confirmation/invitation payloads; profile resend persists confirmation/reset tokens and delivers no-op/confirmation/invitation states; newly created invited agents get workspace invitation mail; `unconfirmed_email` is modeled for email-update branch routing; environment SMTP remains a no-op when not configured. SSO/SAML/LDAP/OIDC mail variants stay excluded. | Review by `feat(profile): send confirmation invitations`; focused tests cover confirmed no-op, normal confirmation mail, invited workspace invitation mail, agent creation/inviter context, hashed reset-token persistence, and no network in default tests; full `go test ./...` and `git diff --check` passed. | @@ -246,6 +248,7 @@ This ledger records the committed parity checkpoints that future slices should b | Commit | Scope | Verification summary | Follow-up state | | --- | --- | --- | --- | +| `feat(channels): align whatsapp authorization` | Advances P3.32 WhatsApp embedded signup authorization parity by matching Chatwoot `Api::V1::Accounts::Whatsapp::AuthorizationsController#create`, `Whatsapp::EmbeddedSignupService`, channel creation/reauthorization/token/phone validation services, route `339`, request specs, and reused dashboard `whatsappChannel.js`. GoChat now exposes authenticated-agent/admin `POST /api/v1/accounts/:account_id/whatsapp/authorization`, returns raw `{ success, id, name, channel_type, message? }` payloads, creates WhatsApp Cloud inboxes from embedded signup, validates token access to the requested WABA, and reauthorizes existing WhatsApp Cloud inboxes by refreshing provider config and clearing `reauthorization_required`. | `go test ./internal/service -run 'WhatsAppAuthorization' -count=1`; `go test ./internal/handler/api/v1 ./internal/router ./cmd/route_parity -run 'WhatsAppAuthorization\|Router\|RouteParity' -count=1`; `go run ./cmd/dump_routes > docs/parity/gochat_routes.txt`; `go run ./cmd/route_parity`; full `go test ./...`; `git diff --check`. Route dump is `TOTAL: 948`; tracked route parity is `398 exact, 0 method-compatible, 13 parameter-compatible, 0 missing out of 411`. | P3.32 moves to Review for current WhatsApp embedded-signup evidence; continue Phase 2/3 drift audit, Phase 6 placeholder audit, B12 live smoke, or fresh reference/smoke drift. | | `feat(channels): align social authorization` | Advances P3.31 Instagram/TikTok authorization parity by matching Chatwoot `Api::V1::Accounts::Instagram::AuthorizationsController#create`, `Api::V1::Accounts::Tiktok::AuthorizationsController#create`, shared OAuth authorization behavior, routes `327/331`, request specs, callback return hints, and reused dashboard `instagramClient.js`/`tiktokClient.js`. GoChat now exposes administrator-gated `POST /api/v1/accounts/:account_id/instagram/authorization` and `POST /api/v1/accounts/:account_id/tiktok/authorization`, returns raw `{ success: true, url }`, builds Chatwoot-scoped provider authorize URLs with frontend callback redirects, and signs account state with optional `return_to` for the existing social callback paths. | `go test ./internal/handler/api/v1 -run 'InstagramAuthorization\|TikTokAuthorization\|SocialAuthorization' -count=1`; `go test ./internal/router ./cmd/route_parity -run 'Router\|RouteParity' -count=1`; `go run ./cmd/dump_routes > docs/parity/gochat_routes.txt`; `go run ./cmd/route_parity`; full `go test ./...`; `git diff --check`. Route dump is `TOTAL: 947`; tracked route parity is `397 exact, 0 method-compatible, 13 parameter-compatible, 0 missing out of 410`. | P3.31 moves to Review for current Instagram/TikTok authorization evidence; continue Phase 2/3 drift audit, Phase 6 placeholder audit, B12 live smoke, or fresh reference/smoke drift. | | `feat(channels): align email oauth authorization` | Advances P3.30 Google/Microsoft authorization parity by matching Chatwoot `Api::V1::Accounts::Google::AuthorizationsController#create`, `Api::V1::Accounts::Microsoft::AuthorizationsController#create`, shared `OauthAuthorizationController`, routes `319/323`, request specs, email OAuth callbacks, and reused dashboard `googleClient.js`/`microsoftClient.js`. GoChat now exposes administrator-gated `POST /api/v1/accounts/:account_id/google/authorization` and `POST /api/v1/accounts/:account_id/microsoft/authorization`, returns raw `{ success: true, url }`, builds Chatwoot-scoped provider authorize URLs with frontend callback redirects, and signs callback state for the existing email OAuth callback paths. | `go test ./internal/handler/api/v1 -run 'GoogleAuthorization\|MicrosoftAuthorization\|EmailOAuthAuthorization' -count=1`; `go test ./cmd/route_parity ./internal/router -run 'RouteParity\|Router' -count=1`; `go run ./cmd/dump_routes > docs/parity/gochat_routes.txt`; `go run ./cmd/route_parity`; full `go test ./...`; `git diff --check`. Route dump is `TOTAL: 945`; tracked route parity is `395 exact, 0 method-compatible, 13 parameter-compatible, 0 missing out of 408`. | P3.30 moves to Review for current Google/Microsoft authorization evidence; continue Phase 2/3 drift audit, Phase 6 placeholder audit, B12 live smoke, or fresh reference/smoke drift. | | `feat(channels): align twitter authorization` | Advances P3.29 Twitter authorization parity by matching Chatwoot `Api::V1::Accounts::Twitter::AuthorizationsController#create`, route `315`, request specs, callback expectations, and reused dashboard `twitterClient.js`. GoChat now exposes administrator-gated `POST /api/v1/accounts/:account_id/twitter/authorization`, requests a Twitter OAuth1 token through a fakeable signed request-token client, returns raw `{ success: true, url }`, and signs callback state for the existing Twitter callback path. | `go test ./internal/handler/api/v1 ./internal/router ./cmd/route_parity -run 'TwitterAuthorization\|Router\|RouteParity' -count=1`; `go run ./cmd/dump_routes > docs/parity/gochat_routes.txt`; `go run ./cmd/route_parity`; full `go test ./...`; `git diff --check`. Route dump is `TOTAL: 943`; tracked route parity is `393 exact, 0 method-compatible, 13 parameter-compatible, 0 missing out of 406`. | P3.29 moves to Review for current Twitter authorization evidence; continue Phase 2/3 drift audit, Phase 6 placeholder audit, B12 live smoke, or fresh reference/smoke drift. | @@ -2458,3 +2461,4 @@ Verification milestone gates: - 2026-06-06: P3.29 Twitter authorization checkpoint prepared as `feat(channels): align twitter authorization`; audited Chatwoot Twitter account authorization controller/specs, route `315`, Twitter callback behavior, and reused dashboard `twitterClient.js`. GoChat now exposes administrator-gated `POST /api/v1/accounts/:account_id/twitter/authorization`, signs and sends the OAuth1 request-token call through a fakeable client, returns raw `{ success: true, url }`, builds `/oauth/authorize?oauth_token=...` URLs, signs callback state for the existing Twitter callback, and tracks the account authorization route in route parity. Focused Twitter authorization handler/router tests, route dump/parity regeneration (`943` routes; `393 exact`, `13 parameter-compatible`, `0 missing out of 406`), full `go test ./...`, and `git diff --check` passed; continue Phase 2/3 drift audit, Phase 6 placeholder audit, or B12 live smoke. - 2026-06-06: P3.30 Google/Microsoft authorization checkpoint prepared as `feat(channels): align email oauth authorization`; audited Chatwoot Google and Microsoft account authorization controllers/specs, shared OAuth authorization controller, routes `319/323`, email callback behavior, and reused dashboard `googleClient.js`/`microsoftClient.js`. GoChat now exposes administrator-gated `POST /api/v1/accounts/:account_id/google/authorization` and `POST /api/v1/accounts/:account_id/microsoft/authorization`, returns raw `{ success: true, url }`, builds Chatwoot provider authorize URLs with exact frontend callback redirects and scopes, includes Google `prompt=consent` plus `access_type=offline`, omits Microsoft prompt, signs account callback state for the existing email OAuth callbacks, and tracks both account authorization routes in route parity. Focused email authorization handler/router tests, route dump/parity regeneration (`945` routes; `395 exact`, `13 parameter-compatible`, `0 missing out of 408`), full `go test ./...`, and `git diff --check` passed; continue Phase 2/3 drift audit, Phase 6 placeholder audit, or B12 live smoke. - 2026-06-06: P3.31 Instagram/TikTok authorization checkpoint prepared as `feat(channels): align social authorization`; audited Chatwoot Instagram and TikTok account authorization controllers/specs, shared OAuth authorization behavior, routes `327/331`, callback return hints, and reused dashboard `instagramClient.js`/`tiktokClient.js`. GoChat now exposes administrator-gated `POST /api/v1/accounts/:account_id/instagram/authorization` and `POST /api/v1/accounts/:account_id/tiktok/authorization`, returns raw `{ success: true, url }`, builds Chatwoot provider authorize URLs with exact frontend callback redirects and required social scopes, includes Instagram `enable_fb_login=0` plus `force_authentication=1`, includes TikTok `client_key`, signs account callback state with optional `return_to`, and tracks both account authorization routes in route parity. Focused social authorization handler/router tests, route dump/parity regeneration (`947` routes; `397 exact`, `13 parameter-compatible`, `0 missing out of 410`), full `go test ./...`, and `git diff --check` passed; continue Phase 2/3 drift audit, Phase 6 placeholder audit, or B12 live smoke. +- 2026-06-06: P3.32 WhatsApp authorization checkpoint prepared as `feat(channels): align whatsapp authorization`; audited Chatwoot WhatsApp authorization controller/specs, embedded signup/channel creation/reauthorization/token/phone validation services, route `339`, and reused dashboard `whatsappChannel.js`. GoChat now exposes authenticated-agent/admin `POST /api/v1/accounts/:account_id/whatsapp/authorization`, validates embedded signup params, exchanges Meta codes, fetches phone info, validates WABA token access, creates WhatsApp Cloud inboxes with embedded-signup provider config, reauthorizes existing inboxes with same-phone validation and `reauthorization_required` clearing, and returns raw `{ success, id, name, channel_type, message? }`. Focused WhatsApp authorization service tests, handler/router/route-parity tests, route dump/parity regeneration (`948` routes; `398 exact`, `13 parameter-compatible`, `0 missing out of 411`), full `go test ./...`, and `git diff --check` passed; continue Phase 2/3 drift audit, Phase 6 placeholder audit, or B12 live smoke. diff --git a/docs/parity/gochat_routes.txt b/docs/parity/gochat_routes.txt index 8dd7d355..777dfce5 100644 --- a/docs/parity/gochat_routes.txt +++ b/docs/parity/gochat_routes.txt @@ -768,6 +768,7 @@ POST /api/v1/accounts/:account_id/update_active_at POST /api/v1/accounts/:account_id/upload POST /api/v1/accounts/:account_id/users POST /api/v1/accounts/:account_id/webhooks +POST /api/v1/accounts/:account_id/whatsapp/authorization POST /api/v1/auth/login POST /api/v1/auth/login/mfa POST /api/v1/auth/mfa/backup_codes @@ -945,4 +946,4 @@ PUT /public/api/v1/csat_survey/:id PUT /public/api/v1/inboxes/:inbox_id/contacts/:contact_id PUT /public/api/v1/inboxes/:inbox_id/contacts/:contact_id/conversations/:conversation_id/messages/:message_id PUT /widget/direct_uploads/:upload_uuid -TOTAL: 947 +TOTAL: 948 diff --git a/docs/parity/route_parity.md b/docs/parity/route_parity.md index 46d3385d..27e44fbf 100644 --- a/docs/parity/route_parity.md +++ b/docs/parity/route_parity.md @@ -7,7 +7,7 @@ Generated from: This report covers tracked frontend-critical Chatwoot routes from `reference/chatwoot/config/routes.rb`, including API v1 account routes, Captain/Copilot, assignment policies, widget/public APIs, and API v2 reports. Ruby is not installed in the workspace, so Chatwoot routes are sourced from static route declarations instead of `bin/rails routes`. -Summary: 397 exact, 0 method-compatible, 13 parameter-compatible, 0 missing out of 410 tracked critical routes. +Summary: 398 exact, 0 method-compatible, 13 parameter-compatible, 0 missing out of 411 tracked critical routes. ## Missing Critical Routes @@ -379,6 +379,7 @@ These routes exist with equivalent method and path shape but different parameter | POST | `/api/v1/accounts/:account_id/twitter/authorization` | `/api/v1/accounts/:account_id/twitter/authorization` | `api/v1/accounts/twitter/authorizations#create` | `routes.rb:315` | exact | | POST | `/api/v1/accounts/:account_id/update_active_at` | `/api/v1/accounts/:account_id/update_active_at` | `api/v1/accounts#update_active_at` | `routes.rb:49` | exact | | POST | `/api/v1/accounts/:account_id/webhooks` | `/api/v1/accounts/:account_id/webhooks` | `api/v1/accounts/webhooks#create` | `routes.rb:342` | exact | +| POST | `/api/v1/accounts/:account_id/whatsapp/authorization` | `/api/v1/accounts/:account_id/whatsapp/authorization` | `api/v1/accounts/whatsapp/authorizations#create` | `routes.rb:339` | exact | | POST | `/api/v1/notification_subscriptions` | `/api/v1/notification_subscriptions` | `api/v1/notification_subscriptions#create` | `routes.rb:440` | exact | | POST | `/api/v1/widget/config` | `/api/v1/widget/config` | `api/v1/widget/config#create` | `routes.rb:444` | exact | | POST | `/api/v1/widget/contact/destroy_custom_attributes` | `/api/v1/widget/contact/destroy_custom_attributes` | `api/v1/widget/contact#destroy_custom_attributes` | `routes.rb:460` | exact | diff --git a/internal/handler/api/v1/inbox_handler.go b/internal/handler/api/v1/inbox_handler.go index 59467116..d4bafc60 100644 --- a/internal/handler/api/v1/inbox_handler.go +++ b/internal/handler/api/v1/inbox_handler.go @@ -153,6 +153,44 @@ func (h *InboxHandler) Create(c *gin.Context) { c.JSON(http.StatusOK, serializeInbox(inbox)) } +// WhatsAppAuthorization handles Chatwoot's embedded signup callback for +// WhatsApp Cloud channel creation and reauthorization. +// POST /api/v1/accounts/:account_id/whatsapp/authorization +func (h *InboxHandler) WhatsAppAuthorization(c *gin.Context) { + accountID, err := parseUintParam(c, "account_id") + if err != nil { + response.AbortWithStatusError(c, http.StatusBadRequest, response.ErrBadRequest, "invalid account_id") + return + } + + var req service.WhatsAppAuthorizationRequest + if err := c.ShouldBind(&req); err != nil { + c.JSON(http.StatusUnprocessableEntity, gin.H{"success": false, "error": err.Error()}) + return + } + + result, svcErr := h.svc.AuthorizeWhatsAppEmbeddedSignup(c.Request.Context(), accountID, req) + if svcErr != nil { + status := http.StatusUnprocessableEntity + if req.InboxID != nil && strings.Contains(strings.ToLower(svcErr.Error()), "record not found") { + status = http.StatusNotFound + } + c.JSON(status, gin.H{"success": false, "error": svcErr.Error()}) + return + } + + payload := gin.H{ + "success": true, + "id": result.Inbox.ID, + "name": result.Inbox.Name, + "channel_type": "whatsapp", + } + if result.Message != "" { + payload["message"] = result.Message + } + c.JSON(http.StatusOK, payload) +} + // @Summary Update an inbox // @Description Updates an existing inbox's configuration // @Tags Inboxes diff --git a/internal/router/router.go b/internal/router/router.go index 44a34584..cb49de31 100644 --- a/internal/router/router.go +++ b/internal/router/router.go @@ -1586,6 +1586,7 @@ func registerV1Routes(g *gin.RouterGroup, h *Handlers) { accountScoped.POST("/google/authorization", middleware.RoleCheck("administrator"), h.GoogleChannel.ChatwootAuthorization) accountScoped.POST("/instagram/authorization", middleware.RoleCheck("administrator"), h.InstagramChannel.ChatwootAuthorization) accountScoped.POST("/tiktok/authorization", middleware.RoleCheck("administrator"), h.TikTokChannel.ChatwootAuthorization) + accountScoped.POST("/whatsapp/authorization", h.Inbox.WhatsAppAuthorization) // G16: Third-party Integrations — IntegrationHook CRUD + Slack/Shopify/Linear/Notion // Reference: Chatwoot namespace :integrations under :account diff --git a/internal/service/whatsapp_authorization_service.go b/internal/service/whatsapp_authorization_service.go new file mode 100644 index 00000000..facb23a4 --- /dev/null +++ b/internal/service/whatsapp_authorization_service.go @@ -0,0 +1,326 @@ +package service + +import ( + "context" + "encoding/json" + "fmt" + "io" + "net/http" + "net/url" + "os" + "strings" + + "github.com/gochat/gochat/internal/model" + channelmodel "github.com/gochat/gochat/internal/model/channel" +) + +var whatsappAuthorizationHTTPClient = http.DefaultClient + +type WhatsAppAuthorizationRequest struct { + Code string `json:"code" form:"code"` + BusinessID string `json:"business_id" form:"business_id"` + WabaID string `json:"waba_id" form:"waba_id"` + PhoneNumberID string `json:"phone_number_id" form:"phone_number_id"` + InboxID *uint `json:"inbox_id" form:"inbox_id"` +} + +type WhatsAppAuthorizationResult struct { + Inbox *model.Inbox + Message string +} + +type whatsappPhoneInfo struct { + PhoneNumberID string + PhoneNumber string + BusinessName string +} + +// AuthorizeWhatsAppEmbeddedSignup implements Chatwoot's WhatsApp embedded signup +// callback endpoint for both new channel creation and reauthorization. +func (s *InboxService) AuthorizeWhatsAppEmbeddedSignup(ctx context.Context, accountID uint, req WhatsAppAuthorizationRequest) (*WhatsAppAuthorizationResult, error) { + if err := validateWhatsAppAuthorizationParams(req); err != nil { + return nil, err + } + if s == nil || s.repo == nil || s.whatsappRepo == nil { + return nil, fmt.Errorf("WhatsApp authorization service is not configured") + } + if req.InboxID != nil && *req.InboxID > 0 { + if _, err := s.repo.FindByAccountAndID(ctx, accountID, *req.InboxID); err != nil { + return nil, err + } + } + + accessToken, err := exchangeWhatsAppAuthorizationCode(ctx, req.Code) + if err != nil { + return nil, err + } + phoneInfo, err := fetchWhatsAppPhoneInfo(ctx, req.WabaID, req.PhoneNumberID, accessToken) + if err != nil { + return nil, err + } + if err := validateWhatsAppTokenAccess(ctx, accessToken, req.WabaID); err != nil { + return nil, err + } + + if req.InboxID != nil && *req.InboxID > 0 { + return s.reauthorizeWhatsAppInbox(ctx, accountID, *req.InboxID, req, accessToken, phoneInfo) + } + return s.createWhatsAppEmbeddedSignupInbox(ctx, accountID, req, accessToken, phoneInfo) +} + +func validateWhatsAppAuthorizationParams(req WhatsAppAuthorizationRequest) error { + missing := make([]string, 0, 3) + if strings.TrimSpace(req.Code) == "" { + missing = append(missing, "code") + } + if strings.TrimSpace(req.BusinessID) == "" { + missing = append(missing, "business_id") + } + if strings.TrimSpace(req.WabaID) == "" { + missing = append(missing, "waba_id") + } + if len(missing) > 0 { + return fmt.Errorf("Required parameters are missing: %s", strings.Join(missing, ", ")) + } + return nil +} + +func (s *InboxService) createWhatsAppEmbeddedSignupInbox(ctx context.Context, accountID uint, req WhatsAppAuthorizationRequest, accessToken string, phoneInfo whatsappPhoneInfo) (*WhatsAppAuthorizationResult, error) { + if err := s.EnsureCanCreateInbox(ctx, accountID); err != nil { + return nil, err + } + var count int64 + if err := s.repo.DB().WithContext(ctx).Model(&channelmodel.ChannelWhatsApp{}).Where("phone_number = ?", phoneInfo.PhoneNumber).Count(&count).Error; err != nil { + return nil, err + } + if count > 0 { + return nil, fmt.Errorf("Channel already exists") + } + + inboxName := strings.TrimSpace(phoneInfo.BusinessName) + if inboxName == "" { + inboxName = "WhatsApp" + } else { + inboxName += " WhatsApp" + } + inbox := &model.Inbox{AccountID: accountID, Name: inboxName, ChannelType: "whatsapp", Enabled: true, EnableEmailCollect: true, AllowMessagesAfterResolved: true, SenderNameType: "friendly_name", Timezone: "UTC"} + if err := s.repo.Create(ctx, inbox); err != nil { + return nil, err + } + + channel := &channelmodel.ChannelWhatsApp{ + AccountID: accountID, + InboxID: inbox.ID, + PhoneNumber: phoneInfo.PhoneNumber, + PhoneNumberID: firstNonEmpty(phoneInfo.PhoneNumberID, req.PhoneNumberID), + BusinessAccountID: req.WabaID, + WhatsAppAccountName: phoneInfo.BusinessName, + AccessToken: accessToken, + Provider: "whatsapp_cloud", + ProviderConfig: marshalInboxJSON(whatsappEmbeddedProviderConfig(accessToken, firstNonEmpty(phoneInfo.PhoneNumberID, req.PhoneNumberID), req.WabaID)), + WebhookVerifyToken: generateInboxSecret(), + AutoCreateContact: true, + } + if err := s.whatsappRepo.Create(ctx, channel); err != nil { + return nil, err + } + inbox.ChannelID = channel.ID + inbox.ChannelConfig = marshalInboxJSON(whatsappInboxChannelConfig(channel)) + if err := s.repo.Update(ctx, inbox); err != nil { + return nil, err + } + _ = s.setupWhatsAppWebhook(ctx, channel, whatsappWebhookCallbackURL(channel.PhoneNumber)) + return &WhatsAppAuthorizationResult{Inbox: inbox}, nil +} + +func (s *InboxService) reauthorizeWhatsAppInbox(ctx context.Context, accountID, inboxID uint, req WhatsAppAuthorizationRequest, accessToken string, phoneInfo whatsappPhoneInfo) (*WhatsAppAuthorizationResult, error) { + inbox, err := s.repo.FindByAccountAndID(ctx, accountID, inboxID) + if err != nil { + return nil, err + } + channel, err := s.whatsappRepo.GetByInboxID(ctx, inbox.ID) + if err != nil || channel.Provider != "whatsapp_cloud" { + return nil, fmt.Errorf("WhatsApp channel not found") + } + if phoneInfo.PhoneNumber != "" && channel.PhoneNumber != "" && phoneInfo.PhoneNumber != channel.PhoneNumber { + return nil, fmt.Errorf("Phone number mismatch. Expected %s, got %s", channel.PhoneNumber, phoneInfo.PhoneNumber) + } + + channel.AccessToken = accessToken + channel.PhoneNumberID = firstNonEmpty(phoneInfo.PhoneNumberID, req.PhoneNumberID) + channel.BusinessAccountID = req.BusinessID + channel.ProviderConfig = marshalInboxJSON(whatsappEmbeddedProviderConfig(accessToken, channel.PhoneNumberID, req.BusinessID)) + channel.ReauthorizationRequired = false + if phoneInfo.BusinessName != "" { + channel.WhatsAppAccountName = phoneInfo.BusinessName + inbox.Name = phoneInfo.BusinessName + } + if err := s.whatsappRepo.Update(ctx, channel); err != nil { + return nil, err + } + inbox.ChannelConfig = marshalInboxJSON(whatsappInboxChannelConfig(channel)) + if err := s.repo.Update(ctx, inbox); err != nil { + return nil, err + } + _ = s.setupWhatsAppWebhook(ctx, channel, whatsappWebhookCallbackURL(channel.PhoneNumber)) + return &WhatsAppAuthorizationResult{Inbox: inbox, Message: "Inbox reauthorized successfully"}, nil +} + +func whatsappEmbeddedProviderConfig(accessToken, phoneNumberID, businessAccountID string) map[string]any { + return map[string]any{"api_key": accessToken, "phone_number_id": phoneNumberID, "business_account_id": businessAccountID, "source": "embedded_signup"} +} + +func whatsappInboxChannelConfig(channel *channelmodel.ChannelWhatsApp) map[string]any { + providerConfig := parseJSONMap(channel.ProviderConfig) + return map[string]any{ + "phone_number": channel.PhoneNumber, + "provider": channel.Provider, + "provider_config": providerConfig, + "message_templates": []any{}, + "reauthorization_required": channel.ReauthorizationRequired, + "webhook_verify_token": channel.WebhookVerifyToken, + } +} + +func whatsappWebhookCallbackURL(phoneNumber string) string { + return strings.TrimRight(envOrDefaultService("FRONTEND_URL", "http://localhost:3000"), "/") + "/webhooks/whatsapp/" + url.PathEscape(phoneNumber) +} + +func exchangeWhatsAppAuthorizationCode(ctx context.Context, code string) (string, error) { + endpoint := whatsappGraphAPIBase() + "/" + whatsappAPIVersion() + "/oauth/access_token" + params := url.Values{} + params.Set("client_id", os.Getenv("WHATSAPP_APP_ID")) + params.Set("client_secret", os.Getenv("WHATSAPP_APP_SECRET")) + params.Set("code", code) + body, err := whatsappGET(ctx, endpoint, params, "Token exchange failed") + if err != nil { + return "", err + } + accessToken, _ := body["access_token"].(string) + if accessToken == "" { + return "", fmt.Errorf("No access token in response") + } + return accessToken, nil +} + +func fetchWhatsAppPhoneInfo(ctx context.Context, wabaID, requestedPhoneNumberID, accessToken string) (whatsappPhoneInfo, error) { + endpoint := whatsappGraphAPIBase() + "/" + whatsappAPIVersion() + "/" + url.PathEscape(wabaID) + "/phone_numbers" + params := url.Values{"access_token": []string{accessToken}} + body, err := whatsappGET(ctx, endpoint, params, "WABA phone numbers fetch failed") + if err != nil { + return whatsappPhoneInfo{}, err + } + items, _ := body["data"].([]any) + for _, item := range items { + phone, _ := item.(map[string]any) + if len(phone) == 0 { + continue + } + if requestedPhoneNumberID == "" || whatsappStringMapValue(phone, "id") == requestedPhoneNumberID { + return buildWhatsAppPhoneInfo(phone), nil + } + } + if len(items) > 0 { + if phone, _ := items[0].(map[string]any); len(phone) > 0 { + return buildWhatsAppPhoneInfo(phone), nil + } + } + return whatsappPhoneInfo{}, fmt.Errorf("No phone numbers found for WABA %s", wabaID) +} + +func validateWhatsAppTokenAccess(ctx context.Context, accessToken, wabaID string) error { + endpoint := whatsappGraphAPIBase() + "/" + whatsappAPIVersion() + "/debug_token" + params := url.Values{} + params.Set("input_token", accessToken) + params.Set("access_token", os.Getenv("WHATSAPP_APP_ID")+"|"+os.Getenv("WHATSAPP_APP_SECRET")) + body, err := whatsappGET(ctx, endpoint, params, "Token validation failed") + if err != nil { + return err + } + data, _ := body["data"].(map[string]any) + scopes, _ := data["granular_scopes"].([]any) + for _, item := range scopes { + scope, _ := item.(map[string]any) + if whatsappStringMapValue(scope, "scope") != "whatsapp_business_management" { + continue + } + for _, id := range anySlice(scope["target_ids"]) { + if fmt.Sprint(id) == wabaID { + return nil + } + } + return fmt.Errorf("Token does not have access to WABA %s", wabaID) + } + return fmt.Errorf("No WABA scope found in token") +} + +func whatsappGET(ctx context.Context, endpoint string, params url.Values, errorPrefix string) (map[string]any, error) { + if len(params) > 0 { + endpoint += "?" + params.Encode() + } + req, err := http.NewRequestWithContext(ctx, http.MethodGet, endpoint, nil) + if err != nil { + return nil, err + } + resp, err := whatsappAuthorizationHTTPClient.Do(req) + if err != nil { + return nil, err + } + defer resp.Body.Close() + body, _ := io.ReadAll(resp.Body) + if resp.StatusCode < http.StatusOK || resp.StatusCode >= http.StatusMultipleChoices { + return nil, fmt.Errorf("%s: %s", errorPrefix, string(body)) + } + var parsed map[string]any + if err := json.Unmarshal(body, &parsed); err != nil { + return nil, err + } + return parsed, nil +} + +func buildWhatsAppPhoneInfo(phone map[string]any) whatsappPhoneInfo { + display := sanitizeWhatsAppPhoneNumber(whatsappStringMapValue(phone, "display_phone_number")) + name := firstNonEmpty(whatsappStringMapValue(phone, "verified_name"), whatsappStringMapValue(phone, "display_phone_number")) + return whatsappPhoneInfo{PhoneNumberID: whatsappStringMapValue(phone, "id"), PhoneNumber: "+" + display, BusinessName: name} +} + +func sanitizeWhatsAppPhoneNumber(phone string) string { + replacer := strings.NewReplacer(" ", "", "-", "", "(", "", ")", "", ".", "", "+", "") + return strings.TrimSpace(replacer.Replace(phone)) +} + +func whatsappGraphAPIBase() string { + return strings.TrimRight(envOrDefaultService("WHATSAPP_GRAPH_API_BASE", "https://graph.facebook.com"), "/") +} +func whatsappAPIVersion() string { + return strings.Trim(strings.TrimSpace(envOrDefaultService("WHATSAPP_API_VERSION", "v22.0")), "/") +} + +func envOrDefaultService(key string, fallback string) string { + if value := strings.TrimSpace(os.Getenv(key)); value != "" { + return value + } + return fallback +} + +func parseJSONMap(raw string) map[string]any { + var out map[string]any + if err := json.Unmarshal([]byte(raw), &out); err != nil || out == nil { + return map[string]any{} + } + return out +} + +func whatsappStringMapValue(values map[string]any, key string) string { + if values == nil || values[key] == nil { + return "" + } + return fmt.Sprint(values[key]) +} + +func anySlice(value any) []any { + if items, ok := value.([]any); ok { + return items + } + return nil +} diff --git a/internal/service/whatsapp_authorization_service_test.go b/internal/service/whatsapp_authorization_service_test.go new file mode 100644 index 00000000..c036b71d --- /dev/null +++ b/internal/service/whatsapp_authorization_service_test.go @@ -0,0 +1,202 @@ +package service + +import ( + "context" + "encoding/json" + "io" + "net/http" + "strings" + "testing" + + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" + "gorm.io/driver/sqlite" + "gorm.io/gorm" + + whatsapp "github.com/gochat/gochat/internal/channel/whatsapp" + "github.com/gochat/gochat/internal/model" + channelmodel "github.com/gochat/gochat/internal/model/channel" + "github.com/gochat/gochat/internal/repository" +) + +type fakeWhatsAppAuthorizationChannelService struct { + webhookURL string +} + +func (f *fakeWhatsAppAuthorizationChannelService) FetchMessageTemplates(context.Context, *channelmodel.ChannelWhatsApp) ([]interface{}, error) { + return nil, nil +} + +func (f *fakeWhatsAppAuthorizationChannelService) FetchHealthStatus(context.Context, *channelmodel.ChannelWhatsApp) (map[string]interface{}, error) { + return map[string]interface{}{}, nil +} + +func (f *fakeWhatsAppAuthorizationChannelService) SetupWebhook(_ context.Context, _ *channelmodel.ChannelWhatsApp, webhookURL string) error { + f.webhookURL = webhookURL + return nil +} + +func setupWhatsAppAuthorizationService(t *testing.T) (*InboxService, *gorm.DB, *fakeWhatsAppAuthorizationChannelService) { + t.Helper() + db, err := gorm.Open(sqlite.Open("file::memory:?cache=shared"), &gorm.Config{}) + require.NoError(t, err) + require.NoError(t, db.AutoMigrate(&model.Account{}, &model.Inbox{}, &channelmodel.ChannelWhatsApp{})) + fake := &fakeWhatsAppAuthorizationChannelService{} + svc := NewInboxService(repository.NewInboxRepo(db), nil, nil, nil, nil, fake, whatsapp.NewRepository(db)) + return svc, db, fake +} + +func withWhatsAppAuthorizationHTTPClient(t *testing.T, fn func(*http.Request) (int, map[string]any)) { + t.Helper() + original := whatsappAuthorizationHTTPClient + whatsappAuthorizationHTTPClient = &http.Client{Transport: whatsappAuthorizationRoundTripFunc(func(req *http.Request) (*http.Response, error) { + status, payload := fn(req) + body, _ := json.Marshal(payload) + return &http.Response{StatusCode: status, Body: io.NopCloser(strings.NewReader(string(body))), Header: http.Header{}}, nil + })} + t.Cleanup(func() { whatsappAuthorizationHTTPClient = original }) +} + +func TestWhatsAppAuthorization_CreateEmbeddedSignupInbox(t *testing.T) { + t.Setenv("WHATSAPP_GRAPH_API_BASE", "https://graph.example.test") + t.Setenv("WHATSAPP_API_VERSION", "v22.0") + t.Setenv("WHATSAPP_APP_ID", "app-id") + t.Setenv("WHATSAPP_APP_SECRET", "app-secret") + t.Setenv("FRONTEND_URL", "https://app.example.test") + svc, db, fake := setupWhatsAppAuthorizationService(t) + account := &model.Account{Name: "Acme", Active: true} + require.NoError(t, db.Create(account).Error) + + withWhatsAppAuthorizationHTTPClient(t, func(req *http.Request) (int, map[string]any) { + switch req.URL.Path { + case "/v22.0/oauth/access_token": + assert.Equal(t, "app-id", req.URL.Query().Get("client_id")) + assert.Equal(t, "auth-code", req.URL.Query().Get("code")) + return http.StatusOK, map[string]any{"access_token": "access-token"} + case "/v22.0/waba-1/phone_numbers": + assert.Equal(t, "access-token", req.URL.Query().Get("access_token")) + return http.StatusOK, map[string]any{"data": []any{map[string]any{"id": "phone-1", "display_phone_number": "+1 (555) 010-000", "verified_name": "Acme Support", "code_verification_status": "VERIFIED"}}} + case "/v22.0/debug_token": + return http.StatusOK, map[string]any{ + "data": map[string]any{ + "granular_scopes": []any{ + map[string]any{ + "scope": "whatsapp_business_management", + "target_ids": []any{"waba-1"}, + }, + }, + }, + } + default: + t.Fatalf("unexpected request path %s", req.URL.Path) + return http.StatusNotFound, map[string]any{} + } + }) + + result, err := svc.AuthorizeWhatsAppEmbeddedSignup(context.Background(), account.ID, WhatsAppAuthorizationRequest{Code: "auth-code", BusinessID: "business-1", WabaID: "waba-1", PhoneNumberID: "phone-1"}) + require.NoError(t, err) + require.NotNil(t, result.Inbox) + assert.Equal(t, "Acme Support WhatsApp", result.Inbox.Name) + assert.Equal(t, "whatsapp", result.Inbox.ChannelType) + assert.Equal(t, "https://app.example.test/webhooks/whatsapp/+1555010000", fake.webhookURL) + + var channel channelmodel.ChannelWhatsApp + require.NoError(t, db.First(&channel, result.Inbox.ChannelID).Error) + assert.Equal(t, account.ID, channel.AccountID) + assert.Equal(t, result.Inbox.ID, channel.InboxID) + assert.Equal(t, "+1555010000", channel.PhoneNumber) + assert.Equal(t, "phone-1", channel.PhoneNumberID) + assert.Equal(t, "waba-1", channel.BusinessAccountID) + assert.Equal(t, "whatsapp_cloud", channel.Provider) + providerConfig := parseJSONMap(channel.ProviderConfig) + assert.Equal(t, "access-token", providerConfig["api_key"]) + assert.Equal(t, "embedded_signup", providerConfig["source"]) +} + +func TestWhatsAppAuthorization_ReauthorizesExistingInbox(t *testing.T) { + t.Setenv("WHATSAPP_GRAPH_API_BASE", "https://graph.example.test") + t.Setenv("FRONTEND_URL", "https://app.example.test") + svc, db, _ := setupWhatsAppAuthorizationService(t) + account := &model.Account{Name: "Acme", Active: true} + require.NoError(t, db.Create(account).Error) + inbox := &model.Inbox{AccountID: account.ID, Name: "Old WhatsApp", ChannelType: "whatsapp", Enabled: true} + require.NoError(t, db.Create(inbox).Error) + channel := &channelmodel.ChannelWhatsApp{AccountID: account.ID, InboxID: inbox.ID, PhoneNumber: "+1555010000", PhoneNumberID: "old-phone", BusinessAccountID: "old-waba", AccessToken: "old-token", Provider: "whatsapp_cloud", ReauthorizationRequired: true} + require.NoError(t, whatsapp.NewRepository(db).Create(context.Background(), channel)) + inbox.ChannelID = channel.ID + require.NoError(t, db.Save(inbox).Error) + + withWhatsAppAuthorizationHTTPClient(t, func(req *http.Request) (int, map[string]any) { + switch req.URL.Path { + case "/v22.0/oauth/access_token": + return http.StatusOK, map[string]any{"access_token": "new-token"} + case "/v22.0/waba-new/phone_numbers": + return http.StatusOK, map[string]any{"data": []any{map[string]any{"id": "phone-new", "display_phone_number": "+1 (555) 010-000", "verified_name": "New Name"}}} + case "/v22.0/debug_token": + return http.StatusOK, map[string]any{ + "data": map[string]any{ + "granular_scopes": []any{ + map[string]any{ + "scope": "whatsapp_business_management", + "target_ids": []any{"waba-new"}, + }, + }, + }, + } + default: + t.Fatalf("unexpected request path %s", req.URL.Path) + return http.StatusNotFound, map[string]any{} + } + }) + + result, err := svc.AuthorizeWhatsAppEmbeddedSignup(context.Background(), account.ID, WhatsAppAuthorizationRequest{Code: "code", BusinessID: "business-new", WabaID: "waba-new", PhoneNumberID: "phone-new", InboxID: &inbox.ID}) + require.NoError(t, err) + assert.Equal(t, "Inbox reauthorized successfully", result.Message) + + var updated channelmodel.ChannelWhatsApp + require.NoError(t, db.First(&updated, channel.ID).Error) + assert.Equal(t, "new-token", updated.AccessToken) + assert.Equal(t, "phone-new", updated.PhoneNumberID) + assert.Equal(t, "business-new", updated.BusinessAccountID) + assert.False(t, updated.ReauthorizationRequired) +} + +func TestWhatsAppAuthorization_ValidationAndProviderErrors(t *testing.T) { + svc, db, _ := setupWhatsAppAuthorizationService(t) + account := &model.Account{Name: "Acme", Active: true} + require.NoError(t, db.Create(account).Error) + + _, err := svc.AuthorizeWhatsAppEmbeddedSignup(context.Background(), account.ID, WhatsAppAuthorizationRequest{BusinessID: "business", WabaID: "waba"}) + require.Error(t, err) + assert.Contains(t, err.Error(), "code") + + t.Setenv("WHATSAPP_GRAPH_API_BASE", "https://graph.example.test") + withWhatsAppAuthorizationHTTPClient(t, func(req *http.Request) (int, map[string]any) { + return http.StatusUnprocessableEntity, map[string]any{"error": "bad code"} + }) + _, err = svc.AuthorizeWhatsAppEmbeddedSignup(context.Background(), account.ID, WhatsAppAuthorizationRequest{Code: "bad", BusinessID: "business", WabaID: "waba"}) + require.Error(t, err) + assert.Contains(t, err.Error(), "Token exchange failed") +} + +func TestWhatsAppAuthorization_MissingReauthorizationInboxStopsBeforeProviderCalls(t *testing.T) { + svc, db, _ := setupWhatsAppAuthorizationService(t) + account := &model.Account{Name: "Acme", Active: true} + require.NoError(t, db.Create(account).Error) + missingInboxID := uint(999) + + withWhatsAppAuthorizationHTTPClient(t, func(req *http.Request) (int, map[string]any) { + t.Fatalf("unexpected provider request path %s", req.URL.Path) + return http.StatusInternalServerError, map[string]any{} + }) + + _, err := svc.AuthorizeWhatsAppEmbeddedSignup(context.Background(), account.ID, WhatsAppAuthorizationRequest{Code: "code", BusinessID: "business", WabaID: "waba", InboxID: &missingInboxID}) + require.Error(t, err) + assert.Contains(t, err.Error(), "record not found") +} + +type whatsappAuthorizationRoundTripFunc func(*http.Request) (*http.Response, error) + +func (f whatsappAuthorizationRoundTripFunc) RoundTrip(req *http.Request) (*http.Response, error) { + return f(req) +}