diff --git a/docs/CHATWOOT_PARITY_DEVELOPMENT_PLAN.md b/docs/CHATWOOT_PARITY_DEVELOPMENT_PLAN.md index f6d87be0..7f8988e3 100644 --- a/docs/CHATWOOT_PARITY_DEVELOPMENT_PLAN.md +++ b/docs/CHATWOOT_PARITY_DEVELOPMENT_PLAN.md @@ -16,10 +16,10 @@ Build GoChat as a Go backend that can directly reuse the frontend from `referenc ## Current Baseline -- Current tracking checkpoint: 2026-06-05 after `af9e1eb feat(inboxes): align whatsapp health endpoints`, with this implementation checkpoint prepared as `feat(inboxes): queue template sync jobs`. -- Latest implementation checkpoint: this checkpoint, prepared as `feat(inboxes): queue template sync jobs`. +- Current tracking checkpoint: 2026-06-05 after `9db1336 feat(inboxes): queue template sync jobs`, with this implementation checkpoint prepared as `feat(auth): align password reset flows`. +- Latest implementation checkpoint: this checkpoint, prepared as `feat(auth): align password reset flows`. - Latest documentation-only checkpoint: `2923aae docs: land parity execution tracker`; this document is now the active follow-up plan and supersedes `.hermes/plans/*`. -- Worktree status at this implementation checkpoint: B11.1a aligns Captain assistant CRUD/tools/inbox bindings; B11.1b aligns Captain scenarios and custom tools; B11.1c aligns Captain documents, assistant responses, bulk actions, and custom-tool test payloads; B11.2 aligns Copilot thread/message create/list/get/delete payloads, account/user scoping, and no-LLM fallback persistence; B11.3a aligns Captain preferences show/update payloads and account-level model/feature storage; B11.3b aligns Captain playground request/response payloads, account scoping, v2 history handling, and no-LLM fallback; B11.3c adds the fakeable Captain document sync backend gate with disabled, failed, and fake-success states; B11.3d aligns Captain task request/response payloads, no-provider disabled states, follow-up context, suggestion persistence, and Copilot message tool-call key validation; B11.3e aligns Captain stream DTOs/disabled SSE fallbacks and Copilot push-event payload shapes; B12.1 adds the reusable GoChat server/seed entrypoint plus a Meilisearch-first reused Chatwoot frontend smoke harness and report; B12.2a adds API smoke assertions for auth/profile, inbox, conversation/messages, contact/company, widget config/message, and public CSAT; B12.2b adds a zero-dependency Chrome DevTools browser smoke that loads the reused Chatwoot login and dashboard entrypoints through Vite and checks browser auth/dashboard API requests; B12.3a adds enterprise API smoke assertions for SLA reports/download, CSAT reports/download, automation/macros, audit/custom roles, capacity, Captain, and Copilot; B12.3b adds reused-frontend enterprise browser route navigation for SLA, CSAT, automation, macros, audit logs, custom roles, capacity, Captain, and Copilot request coverage; P5.1 adds the PostgreSQL-backed durable `background_jobs` model/migration plus WorkerPool enqueue, schedule, retry/backoff, dead-letter, idempotency, stale-lock recovery, and focused tests; P5.2 wires `channel.Dispatcher` and `dispatch.EventDispatcher` async paths into durable event jobs with worker replay tests; P5.3 queues Meilisearch write-side index/delete jobs for conversations, messages, contacts, companies, and articles while keeping search reads Meilisearch-first; P5.4 queues automation webhook and email transcript side effects as durable jobs while preserving fakeable delivery boundaries; P5.5 queues Chatwoot-style macro execute fan-out through durable `automation:macro_execution` jobs; P5.6 queues resolve-triggered CSAT survey sends and WhatsApp/Twilio CSAT template creation through durable jobs; P5.7 queues Chatwoot enterprise SLA account scans and applied-SLA evaluation jobs through the durable worker; P5.8 queues Chatwoot-style contact export artifact generation through durable `contact:export` jobs; P5.9 queues normalized provider inbound message persistence/dispatch through durable `webhook:incoming_message_persist` jobs; P5.10 queues Chatwoot `SendReplyJob`-style outbound message delivery through durable `message:send_reply` jobs and provider delivery-status/read-receipt updates through durable webhook status jobs; P5.11 queues Captain document sync, crawl/parser, schedule-sync, response-builder, embedding-update, Copilot response, and Captain conversation response-builder work through durable jobs; P5.12 queues scheduled item fan-out, one-off campaigns, snoozed conversation reopening, account auto-resolution, widget/public message status updates, and account conversation bulk actions through durable jobs; P5.13a replaces the live report, bot report, conversation summary, inbox-label matrix, first-response distribution, and outgoing-message placeholder responses with persisted conversation/message/reporting-event aggregations; P5.13b routes `GET /reports` to Chatwoot-style metric timeseries, adds lazy rollup freshness/idempotency, registers durable `reporting:rollup_day` jobs, and makes rollup replacement hard-delete soft-deleted rows before recompute; B9.3 verifies the current reference exposes no delayed automation action params, preserves scheduled-item coverage under P5.12, and completes remaining automation action side effects by queueing `send_email_to_team` plus applying enterprise `add_sla`; Phase 2/3 drift audit now aligns account notifications with Chatwoot `NotificationFinder` list envelopes, `includes` filters, unread counts, primary-actor `read_all`, raw action responses, and `destroy_all` read/all semantics; P6.5 now aligns WhatsApp Cloud inbox health/register-webhook endpoints with Chatwoot raw payloads, Cloud-only guards, Graph health fields, default callback URL construction, and no-body register behavior; P6.5 also aligns `sync_templates` with Chatwoot's async low-priority template sync job and `{ message: "Template sync initiated successfully" }` response. Next active implementation slice is continued Phase 6 placeholder audit, followed by further Phase 2/3 drift from smoke/reference evidence. +- Worktree status at this implementation checkpoint: B11.1a aligns Captain assistant CRUD/tools/inbox bindings; B11.1b aligns Captain scenarios and custom tools; B11.1c aligns Captain documents, assistant responses, bulk actions, and custom-tool test payloads; B11.2 aligns Copilot thread/message create/list/get/delete payloads, account/user scoping, and no-LLM fallback persistence; B11.3a aligns Captain preferences show/update payloads and account-level model/feature storage; B11.3b aligns Captain playground request/response payloads, account scoping, v2 history handling, and no-LLM fallback; B11.3c adds the fakeable Captain document sync backend gate with disabled, failed, and fake-success states; B11.3d aligns Captain task request/response payloads, no-provider disabled states, follow-up context, suggestion persistence, and Copilot message tool-call key validation; B11.3e aligns Captain stream DTOs/disabled SSE fallbacks and Copilot push-event payload shapes; B12.1 adds the reusable GoChat server/seed entrypoint plus a Meilisearch-first reused Chatwoot frontend smoke harness and report; B12.2a adds API smoke assertions for auth/profile, inbox, conversation/messages, contact/company, widget config/message, and public CSAT; B12.2b adds a zero-dependency Chrome DevTools browser smoke that loads the reused Chatwoot login and dashboard entrypoints through Vite and checks browser auth/dashboard API requests; B12.3a adds enterprise API smoke assertions for SLA reports/download, CSAT reports/download, automation/macros, audit/custom roles, capacity, Captain, and Copilot; B12.3b adds reused-frontend enterprise browser route navigation for SLA, CSAT, automation, macros, audit logs, custom roles, capacity, Captain, and Copilot request coverage; P5.1 adds the PostgreSQL-backed durable `background_jobs` model/migration plus WorkerPool enqueue, schedule, retry/backoff, dead-letter, idempotency, stale-lock recovery, and focused tests; P5.2 wires `channel.Dispatcher` and `dispatch.EventDispatcher` async paths into durable event jobs with worker replay tests; P5.3 queues Meilisearch write-side index/delete jobs for conversations, messages, contacts, companies, and articles while keeping search reads Meilisearch-first; P5.4 queues automation webhook and email transcript side effects as durable jobs while preserving fakeable delivery boundaries; P5.5 queues Chatwoot-style macro execute fan-out through durable `automation:macro_execution` jobs; P5.6 queues resolve-triggered CSAT survey sends and WhatsApp/Twilio CSAT template creation through durable jobs; P5.7 queues Chatwoot enterprise SLA account scans and applied-SLA evaluation jobs through the durable worker; P5.8 queues Chatwoot-style contact export artifact generation through durable `contact:export` jobs; P5.9 queues normalized provider inbound message persistence/dispatch through durable `webhook:incoming_message_persist` jobs; P5.10 queues Chatwoot `SendReplyJob`-style outbound message delivery through durable `message:send_reply` jobs and provider delivery-status/read-receipt updates through durable webhook status jobs; P5.11 queues Captain document sync, crawl/parser, schedule-sync, response-builder, embedding-update, Copilot response, and Captain conversation response-builder work through durable jobs; P5.12 queues scheduled item fan-out, one-off campaigns, snoozed conversation reopening, account auto-resolution, widget/public message status updates, and account conversation bulk actions through durable jobs; P5.13a replaces the live report, bot report, conversation summary, inbox-label matrix, first-response distribution, and outgoing-message placeholder responses with persisted conversation/message/reporting-event aggregations; P5.13b routes `GET /reports` to Chatwoot-style metric timeseries, adds lazy rollup freshness/idempotency, registers durable `reporting:rollup_day` jobs, and makes rollup replacement hard-delete soft-deleted rows before recompute; B9.3 verifies the current reference exposes no delayed automation action params, preserves scheduled-item coverage under P5.12, and completes remaining automation action side effects by queueing `send_email_to_team` plus applying enterprise `add_sla`; Phase 2/3 drift audit now aligns account notifications with Chatwoot `NotificationFinder` list envelopes, `includes` filters, unread counts, primary-actor `read_all`, raw action responses, and `destroy_all` read/all semantics; P6.5 now aligns WhatsApp Cloud inbox health/register-webhook endpoints with Chatwoot raw payloads, Cloud-only guards, Graph health fields, default callback URL construction, and no-body register behavior; P6.5 also aligns `sync_templates` with Chatwoot's async low-priority template sync job and `{ message: "Template sync initiated successfully" }` response; Phase 2/3 auth now aligns Chatwoot Devise password reset/confirmation token columns, `POST/PUT /auth/password`, and `POST /auth/confirmation` payload/auth-header behavior. Next active implementation slice is continued Phase 6 placeholder audit, followed by further Phase 2/3 drift from smoke/reference evidence. - `go test ./...` passes. - Route dump succeeds with `TOTAL: 833` after adding `GET /api/v1/accounts/:account_id/reports` for the Chatwoot reports index path. - Route parity artifacts now exist under `docs/parity/` and are generated by `cmd/route_parity`. @@ -87,7 +87,7 @@ This table is the shortest authoritative handoff view. If an older lower section | Priority | Workstream | Current state | Next checkpoint | Commit close rule | | --- | --- | --- | --- | --- | -| 1 | Phase 2/3 drift | Tracked route parity is 0 missing for the current critical set; notification list/action serializers now match Chatwoot's frontend contract; broader serializer fixtures remain partial. | Expand route/serializer fixtures when smoke or reference inspection exposes drift. | Regenerate parity artifacts when routes change and add endpoint-family fixture tests. | +| 1 | Phase 2/3 drift | Tracked route parity is 0 missing for the current critical set; notification list/action serializers and Devise password reset/confirmation payloads now match Chatwoot's frontend contract; broader serializer fixtures remain partial. | Expand route/serializer fixtures when smoke or reference inspection exposes drift. | Regenerate parity artifacts when routes change and add endpoint-family fixture tests. | | 2 | Phase 6 placeholder audit | Widget/public/webhook critical placeholders are burned down; inbox WhatsApp health/register-webhook and sync-template drift are closed; account/contact/conversation/message/inbox audit remains broad. | Continue fresh placeholder audit and assign every frontend-reachable stub to a tracked owner. | `rg` placeholder audit is recorded and no reused-frontend blocker is ownerless. | | 3 | B12 optional live smoke | API/browser/enterprise smoke commands are checked in; live runs need PostgreSQL, Redis, Meilisearch, Vite, and Chrome. | Run full live smoke when environment is available and map failures to the board. | `docs/parity/frontend_smoke_report.md` records pass/fail and linked owners. | | 4 | B9.3 delayed automation actions | Current reference exposes no delayed automation action params; scheduled-item work is already P5.12; `send_email_to_team` is durable and `add_sla` mutates conversation/applied SLA state. | Keep automation drift closed if future reference/smoke exposes delayed params or unsupported action shapes. | Automation worker/action fixtures verify queued team email replay, retry visibility through worker jobs, and SLA action idempotency. | @@ -139,6 +139,7 @@ This ledger records the committed parity checkpoints that future slices should b | Commit | Scope | Verification summary | Follow-up state | | --- | --- | --- | --- | +| `feat(auth): align password reset flows` | Advances Phase 2/3 auth/session parity by replacing the password reset and confirmation placeholders with Chatwoot Devise-compatible token columns and frontend routes. `POST /auth/password` now returns Chatwoot's reset request message while storing a reset token digest; `PUT /auth/password` validates `reset_password_token`, updates and confirms the user password, clears reset/confirmation tokens, emits Devise auth headers, and returns `{ data: profile }`; `POST /auth/confirmation` confirms by `confirmation_token`, clears it, emits auth headers, and returns `{ data: profile }`. | `go test ./internal/service -run AuthService -count=1`; `go test ./internal/handler/api/v1 -run ChatwootAuth -count=1`; `go test ./...`; `git diff --check`. | Auth/session/profile remains Done for current reused frontend flow; future auth drift should come from B12 smoke or reference evidence. | | `feat(inboxes): queue template sync jobs` | Advances P6.5 inbox API parity by aligning `POST /inboxes/:id/sync_templates` with `Api::V1::Accounts::Concerns::WhatsappHealthManagement#sync_templates`. The endpoint no longer blocks on live provider template fetches or returns a local `templates` envelope; it validates WhatsApp inboxes, queues durable low-priority `inbox:sync_templates` jobs, replays the existing WhatsApp template fetch/update path in the worker, and returns Chatwoot `{ message: "Template sync initiated successfully" }`. | `go test ./internal/service -run 'InboxService.*SyncTemplates\|InboxService.*Health\|InboxService.*RegisterWebhook' -count=1`; `go test ./internal/handler/api/v1 -run InboxSyncTemplates -count=1`; `go test ./internal/app -count=1`; `go test ./...`; `git diff --check`. | P6.5 remains Doing for broader inbox/channel settings parity; continue Phase 6 placeholder audit across account/contact/conversation/message/inbox surfaces. | | `feat(inboxes): align whatsapp health endpoints` | Advances P6.5 inbox API parity by replacing the generic inbox health result with Chatwoot's WhatsApp Cloud-only `health` contract and aligning `register_webhook` with the reference concern. Health now returns raw Graph phone-number fields plus `expected_webhook_url` and `business_id`; non-WhatsApp/non-Cloud inboxes return the Chatwoot `400` error; register webhook accepts an empty body, builds the default callback from `FRONTEND_URL`, and returns `Webhook registered successfully`. WhatsApp Graph health reads now use `WHATSAPP_API_VERSION` default `v22.0`. | `go test ./internal/channel/whatsapp -count=1`; `go test ./internal/service -run InboxService -count=1`; `go test ./internal/handler/api/v1 -run Inbox -count=1`; `go test ./...`; `git diff --check`. | P6.5 remains Doing for broader inbox/channel settings parity; continue Phase 6 placeholder audit across account/contact/conversation/message/inbox surfaces. | | `feat(notifications): align chatwoot notification payloads` | Advances Phase 2/3 drift by aligning the account notifications API with `reference/chatwoot/app/controllers/api/v1/accounts/notifications_controller.rb`, `NotificationFinder`, `index.json.jbuilder`, and the reused frontend `notifications.js` client. Notification index now returns Chatwoot `{ data: { meta, payload } }`, supports `includes[]=read/snoozed`, fixed unread/count metadata, raw notification action responses, primary-actor-scoped `read_all`, raw unread count, and `destroy_all` read/all semantics from query or JSON body. | `go test ./internal/handler/api/v1 -run Notification -count=1`; `go test ./internal/service -run Notification -count=1`; `go test ./internal/handler/api/v1 ./internal/service -count=1`; `go test ./...`; `git diff --check`. | Notification serializer/action drift moves to Review; continue Phase 6 placeholder audit, then further Phase 2/3 drift from smoke/reference evidence. | @@ -1536,7 +1537,7 @@ Frontend-critical API groups to audit first: | ID | Area | Scope | Status | | --- | --- | --- | --- | -| P3.1 | Auth/session/profile | Login, logout, current user, profile, availability, notification settings. | Done | +| P3.1 | Auth/session/profile | Login, logout, current user, profile, availability, notification settings, Devise password reset, and confirmation. | Done | | P3.2 | Accounts/users/teams | Account settings, users, agents, teams, invitations, roles, permissions. | Todo | | P3.3 | Inboxes/channels | Inbox CRUD, assignable agents, avatars, channel config, business hours, widget config. | Done | | P3.4 | Conversations/messages | List filters, status changes, assignment, labels, private notes, attachments, drafts, typing/read events. | Review | @@ -2051,6 +2052,7 @@ Verification milestone gates: ## Progress Log +- 2026-06-05: Phase 2/3 auth drift checkpoint prepared as `feat(auth): align password reset flows`; audited Chatwoot `DeviseOverrides::PasswordsController`, `DeviseOverrides::ConfirmationsController`, `Auth::ResendConfirmationsController`, and the reused v3 auth frontend. Added Chatwoot user token columns/migration, replaced password reset confirmation placeholders, aligned `POST /auth/password` reset request message, added `PUT /auth/password` reset-token password update with auth headers and `{ data: profile }`, and added `POST /auth/confirmation` confirmation-token sign-in behavior. Focused auth service/handler tests, full `go test ./...`, and `git diff --check` passed; continue Phase 6 placeholder audit next. - 2026-06-05: P6.5 inbox sync-template checkpoint prepared as `feat(inboxes): queue template sync jobs`; audited Chatwoot `WhatsappHealthManagement#sync_templates`, `Channels::Whatsapp::TemplatesSyncJob`, and the reused frontend inbox API/store action. `POST /inboxes/:id/sync_templates` now validates WhatsApp inboxes, enqueues durable low-priority `inbox:sync_templates` jobs instead of synchronously fetching provider templates, replays the existing WhatsApp template fetch/update path in the worker, and returns Chatwoot `{ message: "Template sync initiated successfully" }` without a local `templates` envelope. Focused inbox service/handler/app tests, full `go test ./...`, and `git diff --check` passed; continue Phase 6 placeholder audit next. - 2026-06-05: P6.5 inbox placeholder/drift checkpoint prepared as `feat(inboxes): align whatsapp health endpoints`; audited `reference/chatwoot/app/controllers/api/v1/accounts/concerns/whatsapp_health_management.rb`, `Whatsapp::HealthService`, `Whatsapp::WebhookSetupService`, and the reused frontend inbox health client/component. `GET /inboxes/:id/health` now returns the raw WhatsApp Cloud Graph health payload with `expected_webhook_url` and `business_id`, rejects non-WhatsApp/non-Cloud inboxes with Chatwoot's `400` error, and drops the generic `healthy/status/details` placeholder shape. `POST /inboxes/:id/register_webhook` now accepts an empty body, builds the default callback from `FRONTEND_URL`, returns `Webhook registered successfully`, and uses the same Cloud-only guard. Focused WhatsApp, inbox service, inbox handler tests, full `go test ./...`, and `git diff --check` passed; continue Phase 6 placeholder audit next. - 2026-06-05: Phase 2/3 notification drift checkpoint prepared as `feat(notifications): align chatwoot notification payloads`; audited `reference/chatwoot` notifications controller, `NotificationFinder`, index Jbuilder, and dashboard notifications API/store consumers. Account notifications index now returns Chatwoot `{ data: { meta, payload } }`, filters read/snoozed items with `includes[]=read/snoozed`, reports `count/current_page/unread_count`, serializes frontend-required notification fields, marks all notifications or a primary actor as read, returns raw update/unread/snooze notification payloads, returns unread count as a raw number, and honors `destroy_all` `type=read` from query or JSON body. Focused notification handler/service tests, combined handler/service tests, full `go test ./...`, and `git diff --check` passed; continue Phase 6 placeholder audit next. diff --git a/internal/handler/api/v1/auth_handler.go b/internal/handler/api/v1/auth_handler.go index 99c2bc67..0adb4f1c 100644 --- a/internal/handler/api/v1/auth_handler.go +++ b/internal/handler/api/v1/auth_handler.go @@ -83,6 +83,16 @@ type ResetPasswordRequest struct { Email string `json:"email" binding:"required,email"` } +type ConfirmResetPasswordRequest struct { + ResetPasswordToken string `json:"reset_password_token" binding:"required"` + Password string `json:"password" binding:"required,min=6"` + PasswordConfirmation string `json:"password_confirmation" binding:"required,min=6"` +} + +type ConfirmEmailRequest struct { + ConfirmationToken string `json:"confirmation_token" binding:"required"` +} + // OAuthCallbackRequest is the JSON body for OAuth callback. type OAuthCallbackRequest struct { Provider string `json:"provider" binding:"required"` @@ -358,9 +368,35 @@ func (h *AuthHandler) ResetPassword(c *gin.Context) { Email: req.Email, }) - response.OK(c, gin.H{ - "message": "If the email exists, a reset link has been sent.", + c.JSON(http.StatusOK, gin.H{"message": service.ChatwootPasswordResetMessage}) +} + +// ConfirmResetPassword completes Chatwoot's Devise-compatible password reset. +// PUT /auth/password +func (h *AuthHandler) ConfirmResetPassword(c *gin.Context) { + var req ConfirmResetPasswordRequest + if err := c.ShouldBindJSON(&req); err != nil { + response.AbortWithStatusError(c, http.StatusBadRequest, response.ErrValidation, err.Error()) + return + } + + output, err := h.authService.ConfirmResetPassword(c.Request.Context(), &service.ConfirmResetPasswordInput{ + Token: req.ResetPasswordToken, + Password: req.Password, + PasswordConfirmation: req.PasswordConfirmation, }) + if err != nil { + c.JSON(http.StatusUnprocessableEntity, gin.H{"message": err.Error(), "redirect_url": "/"}) + return + } + + h.setChatwootAuthHeaders(c, output) + data, err := h.chatwootUserPayload(c, output.User.ID, output.AccountID) + if err != nil { + handleServiceError(c, err) + return + } + c.JSON(http.StatusOK, gin.H{"data": data}) } // ConfirmEmail verifies email confirmation token. @@ -372,7 +408,7 @@ func (h *AuthHandler) ConfirmEmail(c *gin.Context) { return } - user, err := h.authService.ConfirmEmail(c.Request.Context(), &service.ConfirmEmailInput{ + output, err := h.authService.ConfirmEmail(c.Request.Context(), &service.ConfirmEmailInput{ Token: token, }) if err != nil { @@ -381,11 +417,35 @@ func (h *AuthHandler) ConfirmEmail(c *gin.Context) { } response.OK(c, gin.H{ - "user": user, + "user": output.User, "message": "Email confirmed successfully.", }) } +// ChatwootConfirmEmail verifies the confirmation token from the reused frontend. +// POST /auth/confirmation +func (h *AuthHandler) ChatwootConfirmEmail(c *gin.Context) { + var req ConfirmEmailRequest + if err := c.ShouldBindJSON(&req); err != nil { + response.AbortWithStatusError(c, http.StatusBadRequest, response.ErrValidation, err.Error()) + return + } + + output, err := h.authService.ConfirmEmail(c.Request.Context(), &service.ConfirmEmailInput{Token: req.ConfirmationToken}) + if err != nil { + c.JSON(http.StatusUnprocessableEntity, gin.H{"message": err.Error(), "redirect_url": "/"}) + return + } + + h.setChatwootAuthHeaders(c, output) + data, err := h.chatwootUserPayload(c, output.User.ID, output.AccountID) + if err != nil { + handleServiceError(c, err) + return + } + c.JSON(http.StatusOK, gin.H{"data": data}) +} + // OAuthCallback handles OAuth2 provider callback. // POST /api/v1/auth/oauth/callback // Receives provider + code from frontend (frontend handles redirect flow). @@ -470,6 +530,7 @@ func RegisterAuthRoutes(rg *gin.RouterGroup, handler *AuthHandler) { // Password & email authGroup.POST("/reset_password", handler.ResetPassword) + authGroup.PUT("/reset_password", handler.ConfirmResetPassword) authGroup.GET("/confirm_email", handler.ConfirmEmail) // OAuth @@ -484,6 +545,8 @@ func RegisterChatwootAuthRoutes(rg *gin.RouterGroup, handler *AuthHandler) { rg.DELETE("/sign_out", handler.ChatwootSignOut) rg.GET("/validate_token", handler.ChatwootValidateToken) rg.POST("/password", handler.ResetPassword) + rg.PUT("/password", handler.ConfirmResetPassword) + rg.POST("/confirmation", handler.ChatwootConfirmEmail) } func (h *AuthHandler) chatwootUserPayload(c *gin.Context, userID uint, accountID uint) (any, error) { diff --git a/internal/handler/api/v1/auth_handler_test.go b/internal/handler/api/v1/auth_handler_test.go index 2858aa56..5c731b88 100644 --- a/internal/handler/api/v1/auth_handler_test.go +++ b/internal/handler/api/v1/auth_handler_test.go @@ -22,7 +22,7 @@ import ( "github.com/gochat/gochat/pkg/crypto" ) -func setupChatwootAuthTest(t *testing.T) (*gin.Engine, *model.User) { +func setupChatwootAuthTest(t *testing.T) (*gin.Engine, *gorm.DB, *model.User) { t.Helper() gin.SetMode(gin.TestMode) @@ -60,11 +60,11 @@ func setupChatwootAuthTest(t *testing.T) (*gin.Engine, *model.User) { router := gin.New() RegisterChatwootAuthRoutes(router.Group("/auth"), handler) - return router, user + return router, db, user } func TestChatwootAuthSignInReturnsDeviseHeadersAndUserPayload(t *testing.T) { - router, _ := setupChatwootAuthTest(t) + router, _, _ := setupChatwootAuthTest(t) body, _ := json.Marshal(map[string]string{"email": " AUTH@example.com ", "password": "password123"}) req, _ := http.NewRequest(http.MethodPost, "/auth/sign_in", bytes.NewReader(body)) req.Header.Set("Content-Type", "application/json") @@ -93,7 +93,7 @@ func TestChatwootAuthSignInReturnsDeviseHeadersAndUserPayload(t *testing.T) { } func TestChatwootAuthValidateTokenReturnsPayloadData(t *testing.T) { - router, _ := setupChatwootAuthTest(t) + router, _, _ := setupChatwootAuthTest(t) token := signInAndReturnAccessToken(t, router) req, _ := http.NewRequest(http.MethodGet, "/auth/validate_token", nil) req.Header.Set("access-token", token) @@ -111,7 +111,7 @@ func TestChatwootAuthValidateTokenReturnsPayloadData(t *testing.T) { } func TestChatwootAuthSignOutRevokesRefreshSession(t *testing.T) { - router, _ := setupChatwootAuthTest(t) + router, _, _ := setupChatwootAuthTest(t) token := signInAndReturnAccessToken(t, router) req, _ := http.NewRequest(http.MethodDelete, "/auth/sign_out", nil) req.Header.Set("access-token", token) @@ -125,6 +125,74 @@ func TestChatwootAuthSignOutRevokesRefreshSession(t *testing.T) { require.Equal(t, true, body["success"]) } +func TestChatwootAuthResetPasswordReturnsReferenceMessage(t *testing.T) { + router, db, user := setupChatwootAuthTest(t) + body, _ := json.Marshal(map[string]string{"email": "auth@example.com"}) + req, _ := http.NewRequest(http.MethodPost, "/auth/password", bytes.NewReader(body)) + req.Header.Set("Content-Type", "application/json") + w := httptest.NewRecorder() + + router.ServeHTTP(w, req) + + require.Equal(t, http.StatusOK, w.Code) + var resp map[string]any + require.NoError(t, json.Unmarshal(w.Body.Bytes(), &resp)) + require.Equal(t, service.ChatwootPasswordResetMessage, resp["message"]) + var updated model.User + require.NoError(t, db.First(&updated, user.ID).Error) + require.NotEmpty(t, updated.ResetPasswordToken) +} + +func TestChatwootAuthConfirmResetPasswordReturnsAuthPayload(t *testing.T) { + router, db, user := setupChatwootAuthTest(t) + require.NoError(t, db.Model(user).Updates(map[string]interface{}{ + "reset_password_token": "raw-reset-token", + "reset_password_sent_at": time.Now().UTC(), + }).Error) + body, _ := json.Marshal(map[string]string{ + "reset_password_token": "raw-reset-token", + "password": "newpassword", + "password_confirmation": "newpassword", + }) + req, _ := http.NewRequest(http.MethodPut, "/auth/password", bytes.NewReader(body)) + req.Header.Set("Content-Type", "application/json") + w := httptest.NewRecorder() + + router.ServeHTTP(w, req) + + require.Equal(t, http.StatusOK, w.Code, w.Body.String()) + require.NotEmpty(t, w.Header().Get("access-token")) + var resp map[string]any + require.NoError(t, json.Unmarshal(w.Body.Bytes(), &resp)) + data := resp["data"].(map[string]any) + require.Equal(t, "auth@example.com", data["email"]) + var updated model.User + require.NoError(t, db.First(&updated, user.ID).Error) + require.True(t, crypto.CheckPassword("newpassword", updated.PasswordDigest)) + require.Empty(t, updated.ResetPasswordToken) +} + +func TestChatwootAuthConfirmationReturnsAuthPayload(t *testing.T) { + router, db, user := setupChatwootAuthTest(t) + require.NoError(t, db.Model(user).Updates(map[string]interface{}{ + "confirmation_token": "raw-confirm-token", + "confirmed_at": nil, + }).Error) + body, _ := json.Marshal(map[string]string{"confirmation_token": "raw-confirm-token"}) + req, _ := http.NewRequest(http.MethodPost, "/auth/confirmation", bytes.NewReader(body)) + req.Header.Set("Content-Type", "application/json") + w := httptest.NewRecorder() + + router.ServeHTTP(w, req) + + require.Equal(t, http.StatusOK, w.Code, w.Body.String()) + require.NotEmpty(t, w.Header().Get("access-token")) + var updated model.User + require.NoError(t, db.First(&updated, user.ID).Error) + require.NotNil(t, updated.ConfirmedAt) + require.Empty(t, updated.ConfirmationToken) +} + func signInAndReturnAccessToken(t *testing.T, router *gin.Engine) string { t.Helper() body, _ := json.Marshal(map[string]string{"email": "auth@example.com", "password": "password123"}) diff --git a/internal/model/user.go b/internal/model/user.go index 2329156d..a4190563 100644 --- a/internal/model/user.go +++ b/internal/model/user.go @@ -12,30 +12,34 @@ import ( // User represents an agent/admin user in the system. type User struct { Base - AccountID uint `gorm:"index;not null" json:"account_id"` - Name string `gorm:"size:255;not null" json:"name"` - Email string `gorm:"size:255;uniqueIndex;not null" json:"email"` - Password string `gorm:"size:255;not null" json:"-"` // hashed password (bcrypt) - PasswordDigest string `gorm:"size:255" json:"-"` // alias used by auth service - Provider string `gorm:"size:50;default:email" json:"provider"` // email, google, saml - UID string `gorm:"size:255" json:"uid,omitempty"` // external ID for OAuth providers - AvatarURL string `gorm:"size:512" json:"avatar_url"` - DisplayName string `gorm:"size:255" json:"display_name"` - MessageSignature string `gorm:"type:text" json:"message_signature"` - PubsubToken string `gorm:"size:255;uniqueIndex" json:"pubsub_token"` - UISettings datatypes.JSON `gorm:"type:jsonb;default:'{}'" json:"ui_settings"` - CustomAttributes datatypes.JSON `gorm:"type:jsonb;default:'{}'" json:"custom_attributes,omitempty"` - Role string `gorm:"size:50;default:agent" json:"role"` // agent, admin - Type string `gorm:"size:50;default:user" json:"type"` - Active bool `gorm:"default:true" json:"active"` - Available bool `gorm:"default:false" json:"available"` - TOTPSecret string `gorm:"size:255" json:"totp_secret,omitempty"` - TOTPEnabled bool `gorm:"default:false" json:"totp_enabled"` - CustomRoleID *uint `gorm:"index" json:"custom_role_id,omitempty"` - SignInCount int `gorm:"default:0" json:"sign_in_count"` - ConfirmedAt *time.Time `json:"confirmed_at,omitempty"` - LastSignInAt *time.Time `json:"last_sign_in_at,omitempty"` - CurrentSignInAt *time.Time `json:"current_sign_in_at,omitempty"` + AccountID uint `gorm:"index;not null" json:"account_id"` + Name string `gorm:"size:255;not null" json:"name"` + Email string `gorm:"size:255;uniqueIndex;not null" json:"email"` + Password string `gorm:"size:255;not null" json:"-"` // hashed password (bcrypt) + PasswordDigest string `gorm:"size:255" json:"-"` // alias used by auth service + Provider string `gorm:"size:50;default:email" json:"provider"` // email, google, saml + UID string `gorm:"size:255" json:"uid,omitempty"` // external ID for OAuth providers + AvatarURL string `gorm:"size:512" json:"avatar_url"` + DisplayName string `gorm:"size:255" json:"display_name"` + MessageSignature string `gorm:"type:text" json:"message_signature"` + PubsubToken string `gorm:"size:255;uniqueIndex" json:"pubsub_token"` + UISettings datatypes.JSON `gorm:"type:jsonb;default:'{}'" json:"ui_settings"` + CustomAttributes datatypes.JSON `gorm:"type:jsonb;default:'{}'" json:"custom_attributes,omitempty"` + Role string `gorm:"size:50;default:agent" json:"role"` // agent, admin + Type string `gorm:"size:50;default:user" json:"type"` + Active bool `gorm:"default:true" json:"active"` + Available bool `gorm:"default:false" json:"available"` + TOTPSecret string `gorm:"size:255" json:"totp_secret,omitempty"` + TOTPEnabled bool `gorm:"default:false" json:"totp_enabled"` + CustomRoleID *uint `gorm:"index" json:"custom_role_id,omitempty"` + SignInCount int `gorm:"default:0" json:"sign_in_count"` + ResetPasswordToken string `gorm:"size:255;index" json:"-"` + ResetPasswordSentAt *time.Time `json:"-"` + ConfirmationToken string `gorm:"size:255;index" json:"-"` + ConfirmationSentAt *time.Time `json:"-"` + ConfirmedAt *time.Time `json:"confirmed_at,omitempty"` + LastSignInAt *time.Time `json:"last_sign_in_at,omitempty"` + CurrentSignInAt *time.Time `json:"current_sign_in_at,omitempty"` } func (User) TableName() string { return "users" } diff --git a/internal/service/auth_service.go b/internal/service/auth_service.go index 90e0f517..25356407 100644 --- a/internal/service/auth_service.go +++ b/internal/service/auth_service.go @@ -2,6 +2,9 @@ package service import ( "context" + "crypto/rand" + "crypto/sha256" + "encoding/hex" "fmt" "strings" "time" @@ -10,9 +13,11 @@ import ( "github.com/gochat/gochat/internal/auth" "github.com/gochat/gochat/internal/model" - "github.com/gochat/gochat/pkg/crypto" + pkgcrypto "github.com/gochat/gochat/pkg/crypto" ) +const ChatwootPasswordResetMessage = "Request for password reset is successful. A email with instructions will be sent to your email if it exists." + // Reference: P2E ยง1 โ€” Auth business logic service // Encapsulates all authentication business logic so handlers remain thin wrappers. // Pattern follows Chatwoot's service_object pattern (app/services/). @@ -85,7 +90,7 @@ func (s *AuthService) Login(ctx context.Context, input *LoginInput) (*LoginOutpu return nil, fmt.Errorf("this account uses %s authentication, please login via that provider", user.Provider) } - if !crypto.CheckPassword(input.Password, user.PasswordDigest) && !crypto.CheckPassword(input.Password, user.Password) { + if !pkgcrypto.CheckPassword(input.Password, user.PasswordDigest) && !pkgcrypto.CheckPassword(input.Password, user.Password) { return nil, fmt.Errorf("invalid email or password") } @@ -225,7 +230,7 @@ func (s *AuthService) Register(ctx context.Context, input *RegisterInput) (*mode } // Hash password - passwordDigest, err := crypto.HashPassword(input.Password) + passwordDigest, err := pkgcrypto.HashPassword(input.Password) if err != nil { return nil, fmt.Errorf("failed to hash password: %w", err) } @@ -382,26 +387,75 @@ type ResetPasswordInput struct { // Generates a reset token stored in Redis, sends email with reset link. func (s *AuthService) ResetPassword(ctx context.Context, input *ResetPasswordInput) error { var user model.User - if err := s.db.Where("email = ?", input.Email).First(&user).Error; err != nil { + email := strings.TrimSpace(strings.ToLower(input.Email)) + if err := s.db.WithContext(ctx).Where("email = ?", email).First(&user).Error; err != nil { // Don't reveal whether email exists โ€” security best practice return nil } - // Production note: reset token should be generated, stored in Redis with TTL, and emailed via worker. - // Placeholder for development - return nil + token, err := generateAuthToken() + if err != nil { + return fmt.Errorf("failed to generate reset token: %w", err) + } + now := time.Now().UTC() + return s.db.WithContext(ctx).Model(&user).Updates(map[string]interface{}{ + "reset_password_token": digestAuthToken(token), + "reset_password_sent_at": now, + }).Error } // ConfirmResetPasswordInput holds password reset confirmation parameters. type ConfirmResetPasswordInput struct { - Token string - Password string + Token string + Password string + PasswordConfirmation string } // ConfirmResetPassword completes password reset by verifying token and updating password. -func (s *AuthService) ConfirmResetPassword(ctx context.Context, input *ConfirmResetPasswordInput) error { - // Production note: reset token must be verified from Redis before password update. - return fmt.Errorf("password reset confirmation not yet implemented") +func (s *AuthService) ConfirmResetPassword(ctx context.Context, input *ConfirmResetPasswordInput) (*LoginOutput, error) { + token := strings.TrimSpace(input.Token) + if token == "" { + return nil, fmt.Errorf("Invalid token") + } + if input.Password == "" || input.Password != input.PasswordConfirmation { + return nil, fmt.Errorf("invalid password confirmation") + } + + var user model.User + digest := digestAuthToken(token) + if err := s.db.WithContext(ctx).Where("reset_password_token IN ?", []string{digest, token}).First(&user).Error; err != nil { + return nil, fmt.Errorf("Invalid token") + } + if user.ResetPasswordSentAt != nil && time.Since(*user.ResetPasswordSentAt) > 6*time.Hour { + return nil, fmt.Errorf("Invalid token") + } + + passwordDigest, err := pkgcrypto.HashPassword(input.Password) + if err != nil { + return nil, fmt.Errorf("failed to hash password: %w", err) + } + now := time.Now().UTC() + updates := map[string]interface{}{ + "password": passwordDigest, + "password_digest": passwordDigest, + "reset_password_token": "", + "reset_password_sent_at": nil, + "confirmation_token": "", + } + if user.ConfirmedAt == nil { + updates["confirmed_at"] = now + user.ConfirmedAt = &now + } + if err := s.db.WithContext(ctx).Model(&user).Updates(updates).Error; err != nil { + return nil, err + } + user.Password = passwordDigest + user.PasswordDigest = passwordDigest + user.ResetPasswordToken = "" + user.ResetPasswordSentAt = nil + user.ConfirmationToken = "" + + return s.issueLoginOutput(ctx, &user) } // --- Email Confirmation --- @@ -412,10 +466,30 @@ type ConfirmEmailInput struct { } // ConfirmEmail verifies a confirmation token and marks user email as confirmed. -func (s *AuthService) ConfirmEmail(ctx context.Context, input *ConfirmEmailInput) (*model.User, error) { - // Production note: confirmation token must be verified from Redis before marking confirmed. - // Placeholder โ€” in development mode, users are auto-confirmed during registration - return nil, fmt.Errorf("email confirmation not yet implemented (auto-confirmed in dev mode)") +func (s *AuthService) ConfirmEmail(ctx context.Context, input *ConfirmEmailInput) (*LoginOutput, error) { + token := strings.TrimSpace(input.Token) + if token == "" { + return nil, fmt.Errorf("Invalid token") + } + + var user model.User + if err := s.db.WithContext(ctx).Where("confirmation_token = ?", token).First(&user).Error; err != nil { + return nil, fmt.Errorf("Invalid token") + } + if user.ConfirmedAt != nil { + return nil, fmt.Errorf("Already confirmed") + } + now := time.Now().UTC() + if err := s.db.WithContext(ctx).Model(&user).Updates(map[string]interface{}{ + "confirmed_at": now, + "confirmation_token": "", + }).Error; err != nil { + return nil, err + } + user.ConfirmedAt = &now + user.ConfirmationToken = "" + + return s.issueLoginOutput(ctx, &user) } // --- OAuth2 Login --- @@ -513,6 +587,41 @@ func (s *AuthService) getUserDefaultAccount(user *model.User) (uint, string, err return accountUser.AccountID, accountUser.Role, nil } +func (s *AuthService) issueLoginOutput(ctx context.Context, user *model.User) (*LoginOutput, error) { + accountID, role, err := s.getUserDefaultAccount(user) + if err != nil { + return nil, fmt.Errorf("failed to get user account: %w", err) + } + tokenPair, err := s.jwtService.GenerateTokenPair(user, accountID, role) + if err != nil { + return nil, fmt.Errorf("failed to generate tokens: %w", err) + } + if err := s.refreshStore.Store(ctx, user.ID, tokenPair.RefreshToken); err != nil { + return nil, fmt.Errorf("failed to store refresh token: %w", err) + } + now := time.Now().UTC() + user.SignInCount++ + user.LastSignInAt = user.CurrentSignInAt + user.CurrentSignInAt = &now + if err := s.db.WithContext(ctx).Save(user).Error; err != nil { + return nil, err + } + return &LoginOutput{User: user, TokenPair: tokenPair, AccountID: accountID, Role: role}, nil +} + +func generateAuthToken() (string, error) { + b := make([]byte, 32) + if _, err := rand.Read(b); err != nil { + return "", err + } + return hex.EncodeToString(b), nil +} + +func digestAuthToken(token string) string { + sum := sha256.Sum256([]byte(token)) + return hex.EncodeToString(sum[:]) +} + // createDefaultAccount creates a personal account for a new user. func (s *AuthService) createDefaultAccount(user *model.User) (uint, string, error) { // Create account diff --git a/internal/service/auth_service_test.go b/internal/service/auth_service_test.go new file mode 100644 index 00000000..dc51b63e --- /dev/null +++ b/internal/service/auth_service_test.go @@ -0,0 +1,83 @@ +package service + +import ( + "context" + "testing" + "time" + + "github.com/stretchr/testify/require" + "gorm.io/driver/sqlite" + "gorm.io/gorm" + "gorm.io/gorm/logger" + + "github.com/gochat/gochat/internal/auth" + "github.com/gochat/gochat/internal/config" + "github.com/gochat/gochat/internal/model" + "github.com/gochat/gochat/pkg/crypto" +) + +func setupAuthServiceTest(t *testing.T) (*AuthService, *gorm.DB, *model.User) { + t.Helper() + db, err := gorm.Open(sqlite.Open("file:"+t.Name()+"?mode=memory&cache=private"), &gorm.Config{Logger: logger.Default.LogMode(logger.Silent)}) + require.NoError(t, err) + require.NoError(t, db.AutoMigrate(&model.Account{}, &model.User{}, &model.AccountUser{})) + account := &model.Account{Name: "Auth Service", Status: "active"} + require.NoError(t, db.Create(account).Error) + passwordDigest, err := crypto.HashPassword("oldpassword") + require.NoError(t, err) + user := &model.User{AccountID: account.ID, Name: "Auth User", Email: "auth-service@example.com", Password: passwordDigest, PasswordDigest: passwordDigest, Provider: "email", Active: true} + require.NoError(t, db.Create(user).Error) + require.NoError(t, db.Create(&model.AccountUser{AccountID: account.ID, UserID: user.ID, Role: "administrator"}).Error) + jwtCfg := &config.JWTConfig{Secret: "auth-service-secret", ExpiryHours: 1, RefreshExpiryHours: 24} + return NewAuthService(db, auth.NewJWTService(jwtCfg), auth.NewRefreshTokenStore(nil, jwtCfg), nil, nil), db, user +} + +func TestAuthService_ResetPasswordStoresDigestToken(t *testing.T) { + svc, db, user := setupAuthServiceTest(t) + + require.NoError(t, svc.ResetPassword(context.Background(), &ResetPasswordInput{Email: " AUTH-SERVICE@example.com "})) + + var updated model.User + require.NoError(t, db.First(&updated, user.ID).Error) + require.NotEmpty(t, updated.ResetPasswordToken) + require.NotEqual(t, updated.ResetPasswordToken, "AUTH-SERVICE@example.com") + require.NotNil(t, updated.ResetPasswordSentAt) +} + +func TestAuthService_ConfirmResetPasswordUpdatesPasswordAndIssuesTokens(t *testing.T) { + svc, db, user := setupAuthServiceTest(t) + rawToken := "reset-token-123" + sentAt := time.Now().UTC() + require.NoError(t, db.Model(user).Updates(map[string]interface{}{ + "reset_password_token": digestAuthToken(rawToken), + "reset_password_sent_at": sentAt, + }).Error) + + output, err := svc.ConfirmResetPassword(context.Background(), &ConfirmResetPasswordInput{Token: rawToken, Password: "newpassword", PasswordConfirmation: "newpassword"}) + require.NoError(t, err) + require.NotEmpty(t, output.TokenPair.AccessToken) + + var updated model.User + require.NoError(t, db.First(&updated, user.ID).Error) + require.True(t, crypto.CheckPassword("newpassword", updated.PasswordDigest)) + require.Empty(t, updated.ResetPasswordToken) + require.Nil(t, updated.ResetPasswordSentAt) + require.NotNil(t, updated.ConfirmedAt) +} + +func TestAuthService_ConfirmEmailConfirmsAndIssuesTokens(t *testing.T) { + svc, db, user := setupAuthServiceTest(t) + require.NoError(t, db.Model(user).Updates(map[string]interface{}{ + "confirmation_token": "confirm-token-123", + "confirmed_at": nil, + }).Error) + + output, err := svc.ConfirmEmail(context.Background(), &ConfirmEmailInput{Token: "confirm-token-123"}) + require.NoError(t, err) + require.NotEmpty(t, output.TokenPair.AccessToken) + + var updated model.User + require.NoError(t, db.First(&updated, user.ID).Error) + require.NotNil(t, updated.ConfirmedAt) + require.Empty(t, updated.ConfirmationToken) +} diff --git a/migrations/000027_add_user_auth_tokens.down.sql b/migrations/000027_add_user_auth_tokens.down.sql new file mode 100644 index 00000000..3978a9eb --- /dev/null +++ b/migrations/000027_add_user_auth_tokens.down.sql @@ -0,0 +1,7 @@ +DROP INDEX IF EXISTS idx_users_confirmation_token; +DROP INDEX IF EXISTS idx_users_reset_password_token; + +ALTER TABLE users DROP COLUMN IF EXISTS confirmation_sent_at; +ALTER TABLE users DROP COLUMN IF EXISTS confirmation_token; +ALTER TABLE users DROP COLUMN IF EXISTS reset_password_sent_at; +ALTER TABLE users DROP COLUMN IF EXISTS reset_password_token; diff --git a/migrations/000027_add_user_auth_tokens.up.sql b/migrations/000027_add_user_auth_tokens.up.sql new file mode 100644 index 00000000..4ae64cdf --- /dev/null +++ b/migrations/000027_add_user_auth_tokens.up.sql @@ -0,0 +1,7 @@ +ALTER TABLE users ADD COLUMN IF NOT EXISTS reset_password_token VARCHAR(255); +ALTER TABLE users ADD COLUMN IF NOT EXISTS reset_password_sent_at TIMESTAMP WITH TIME ZONE; +ALTER TABLE users ADD COLUMN IF NOT EXISTS confirmation_token VARCHAR(255); +ALTER TABLE users ADD COLUMN IF NOT EXISTS confirmation_sent_at TIMESTAMP WITH TIME ZONE; + +CREATE UNIQUE INDEX IF NOT EXISTS idx_users_reset_password_token ON users(reset_password_token) WHERE reset_password_token IS NOT NULL AND reset_password_token <> ''; +CREATE INDEX IF NOT EXISTS idx_users_confirmation_token ON users(confirmation_token) WHERE confirmation_token IS NOT NULL AND confirmation_token <> '';