GOWA - WhatsApp REST API with support for UI, Multi Account, Webhooks, and MCP, and Chatwoot. Built with Golang for efficient memory use.
Go botgogolanggolang-whatsappgolang-whatsapp-apirestrest-apiwhatsappwhatsapp-apiwhatsapp-api-gowhatsapp-multi-devicewhatsapp-web-multi-device
fix: chatwoot routing identity, exclusion, and message author checks (#922)
Aldino Kemal300820f8354e
diff --git a/docs/chatwoot.md b/docs/chatwoot.mdindex 23630668..906a4166 100644--- a/docs/chatwoot.md+++ b/docs/chatwoot.md@@ -623,6 +623,8 @@ Inbound replies and reactions are threaded onto the message they reference (agai```+An exact entry matches a chat under either of its addresses, so `111222333@lid` still excludes that contact after its LID resolves to a phone number, for live forwarding and history import alike. Wildcards match only the address a message is delivered under. Live forwarding checks the chat and the sender, so `@lid` excludes a chat whose LID has not resolved to a phone number and also a group message whose sender's LID has not resolved, although the chat is `@g.us`. History import checks only the stored chat address.+## Supported Features### Incoming Messages (WhatsApp → Chatwoot)diff --git a/docs/webhook-payload.md b/docs/webhook-payload.mdindex 07a03010..9e39630a 100644--- a/docs/webhook-payload.md+++ b/docs/webhook-payload.md@@ -456,9 +456,12 @@ another linked device is reported just like opening it on the phone. For these,| `device_id` | string | JID of the device that received this event || `timestamp` | string | RFC3339 formatted timestamp when the receipt was received || `payload.ids` | array | Array of message IDs that received the acknowledgment |-| `payload.chat_id` | string | Chat identifier (group or individual chat) |+| `payload.chat_id` | string | Chat identifier (group or individual chat). A LID chat whose phone number is known is reported as that phone JID, as on message events |+| `payload.chat_lid` | string | Original LID chat identifier when WhatsApp supplied a LID before normalization, or a 1:1 chat's LID taken from `recipient_alt` || `payload.from` | string | JID of the user who triggered the receipt || `payload.from_lid` | string | LID of the user (if available) |+| `payload.sender_alt` | string | The user's other address (phone or LID), when WhatsApp supplied one |+| `payload.recipient_alt` | string | The recipient's other address (phone or LID) in a 1:1 chat, when WhatsApp supplied one || `payload.sender_display_name` | string | Dynamic sender label when `payload.from` is non-empty || `payload.receipt_type` | string | Type of receipt: `"delivered"`, `"read"`, etc. || `payload.receipt_type_description` | string | Human-readable description of the receipt type |@@ -1410,8 +1413,10 @@ Triggered when a message is deleted for the current user (DeleteForMe event).| `payload.deleted_message_id` | string | ID of the deleted message || `payload.timestamp` | string | RFC3339 timestamp when the delete event occurred || `payload.from` | string | JID of the user who deleted the message |+| `payload.from_lid` | string | LID of the user who deleted the message, when the event named them by LID || `payload.sender_display_name` | string | Dynamic sender label when `payload.from` is non-empty || `payload.chat_id` | string | Chat identifier where the message was deleted |+| `payload.chat_lid` | string | Original LID chat identifier when the event named the chat by LID || `payload.original_content` | string | Original message content (if available from storage) || `payload.original_sender` | string | Original sender of the deleted message || `payload.original_timestamp` | string | Original message timestamp |diff --git a/src/domains/chatstorage/interfaces.go b/src/domains/chatstorage/interfaces.goindex 532691ea..a32364d0 100644--- a/src/domains/chatstorage/interfaces.go+++ b/src/domains/chatstorage/interfaces.go@@ -64,7 +64,11 @@ type IChatStorageRepository interface {// configID, when non-zero, further restricts the match to links written under// that device config: separate Chatwoot servers can collide on// (conversation_id, account_id), so per-device (forced-route) callers must- // scope by their own config.+ // scope by their own config. configID 0 does not mean "any server". Each+ // chatwoot_device_configs row is one server (URL + account + inbox). If the+ // matching links span more than one non-zero config, the lookup returns nil+ // so the shared webhook cannot pick the newest row from the wrong server.+ // Legacy config-id 0 rows are used only when they are the only matches.GetLatestChatwootMessageLinkByConversation(conversationID, accountID int, allowLegacyZero bool, configID int64) (*ChatwootMessageLink, error)GetLatestUnreadChatwootMessageLinkByChat(deviceID, waChatJID string) (*ChatwootMessageLink, error)CountChatwootMessageLinksByConfig(configID int64) (int, error)diff --git a/src/infrastructure/chatstorage/sqlite_repository.go b/src/infrastructure/chatstorage/sqlite_repository.goindex 456ededb..6bd16b6f 100644--- a/src/infrastructure/chatstorage/sqlite_repository.go+++ b/src/infrastructure/chatstorage/sqlite_repository.go@@ -1091,35 +1091,92 @@ func (r *SQLiteRepository) GetChatwootMessageLinkByChatwootID(deviceID string, creturn link, err}+// chatwootLinkLookupBeforeSelect runs inside the conversation-link transaction+// after the configuration count and before the final select. Production leaves+// it nil. Tests use it to insert another configuration on the same connection+// so the recount below observes it.+var chatwootLinkLookupBeforeSelect func(tx *sql.Tx)+func (r *SQLiteRepository) GetLatestChatwootMessageLinkByConversation(conversationID, accountID int, allowLegacyZero bool, configID int64) (*domainChatStorage.ChatwootMessageLink, error) {+ // Count and select share one transaction, so they cannot observe two+ // different pool connections. A second configuration committed on another+ // connection waits, and one inserted on this connection is counted again+ // before the select.+ tx, err := r.db.Begin()+ if err != nil {+ return nil, err+ }+ defer tx.Rollback()+ return r.latestChatwootMessageLinkTx(tx, conversationID, accountID, allowLegacyZero, configID)+}++func (r *SQLiteRepository) latestChatwootMessageLinkTx(tx *sql.Tx, conversationID, accountID int, allowLegacyZero bool, configID int64) (*domainChatStorage.ChatwootMessageLink, error) {// The legacy-zero wildcard is gated on allowLegacyZero (true only in legacy// single-account mode). The `? = 1` guard keeps this a single query: when the// flag is 0 the OR branch is never satisfied and the match is exact-account.- // The same trick scopes by config id when one is given (per-device callers):- // configID 0 leaves the match account-wide.+ // A non-zero configID pins one chatwoot_device_configs row. That row is the+ // server identity (URL + account + inbox): numeric account and conversation+ // ids are reused across Chatwoot servers. configID 0 is the shared webhook,+ // which has no server of its own — it may return a row only when every+ // non-zero config id in the match set is the same one. Legacy config-id 0+ // rows do not count as a second server, and they lose to a real config.+ legacyZero := 0+ if allowLegacyZero {+ legacyZero = 1+ }+ where := `chatwoot_conversation_id = ? AND (chatwoot_account_id = ? OR (? = 1 AND chatwoot_account_id = 0))`+ args := []any{conversationID, accountID, legacyZero}+ if configID != 0 {+ where += ` AND chatwoot_config_id = ?`+ args = append(args, configID)+ } else {+ configs, err := countDistinctChatwootConfigs(tx, where, args)+ if err != nil {+ return nil, err+ }+ // A test hook inserts on this same transaction. Recount so a second+ // configuration that is now visible suppresses the row.+ if chatwootLinkLookupBeforeSelect != nil {+ chatwootLinkLookupBeforeSelect(tx)+ configs, err = countDistinctChatwootConfigs(tx, where, args)+ if err != nil {+ return nil, err+ }+ }+ if configs > 1 {+ return nil, nil+ }+ if configs == 1 {+ where += ` AND chatwoot_config_id != 0`+ }+ }+query := `SELECT device_id, wa_message_id, wa_chat_jid, chatwoot_message_id,chatwoot_conversation_id, chatwoot_inbox_id,chatwoot_contact_inbox_source_id, source_id, direction,is_read, created_at, updated_at, chatwoot_config_id, chatwoot_account_idFROM chatwoot_message_links- WHERE chatwoot_conversation_id = ? AND (chatwoot_account_id = ? OR (? = 1 AND chatwoot_account_id = 0))- AND (? = 0 OR chatwoot_config_id = ?)+ WHERE ` + where + `ORDER BY updated_at DESC, created_at DESCLIMIT 1`-- legacyZero := 0- if allowLegacyZero {- legacyZero = 1- }- link, err := r.scanChatwootMessageLink(r.db.QueryRow(query, conversationID, accountID, legacyZero, configID, configID))+ link, err := r.scanChatwootMessageLink(tx.QueryRow(query, args...))if err == sql.ErrNoRows {return nil, nil}return link, err}+func countDistinctChatwootConfigs(tx *sql.Tx, where string, args []any) (int, error) {+ var configs int+ err := tx.QueryRow(`+ SELECT COUNT(DISTINCT chatwoot_config_id) FROM chatwoot_message_links+ WHERE `+where+` AND chatwoot_config_id != 0+ `, args...).Scan(&configs)+ return configs, err+}+// BackfillChatwootMessageLinkAccount stamps accountID onto links whose account id// is still 0 (pre-migration legacy links), returning the number of rows updated.// Idempotent: rows already carrying a non-zero account id are left untouched.@@ -2204,7 +2261,7 @@ func (r *SQLiteRepository) CreateMessage(ctx context.Context, evt *events.Messagsender := normalizedSender.ToNonAD().String()if revokedMessageID := extractRevokedMessageID(evt.Message); revokedMessageID != "" {- return r.DeleteMessageByDevice(deviceID, revokedMessageID, chatJID)+ return r.revokeMessageByAuthor(ctx, deviceID, chatJID, sender, evt, revokedMessageID)}// PushName belongs to the sender. For messages sent from this account, using@@ -2314,6 +2371,69 @@ func (r *SQLiteRepository) CreateMessage(ctx context.Context, evt *events.Messagreturn r.StoreMessage(message)}+// revokeMessageByAuthor deletes a stored message only when the revoke event+// was sent by its author, by a group admin, or by this account. A peer who+// names another message id must not remove that row. The decision is recorded+// for Chatwoot forwarding, which runs after the row is gone and would otherwise+// be unable to tell the two apart.+func (r *SQLiteRepository) revokeMessageByAuthor(ctx context.Context, deviceID, chatJID, sender string, evt *events.Message, revokedMessageID string) error {+ existing, err := r.getMessageByDeviceAndChatIDAndMessageID(deviceID, chatJID, revokedMessageID)+ if err != nil {+ return fmt.Errorf("failed to load message %s for revoke: %w", revokedMessageID, err)+ }+ eventID := ""+ rawSender := ""+ fromMe := false+ if evt != nil {+ eventID = evt.Info.ID+ rawSender = evt.Info.Sender.ToNonAD().String()+ fromMe = evt.Info.IsFromMe+ }+ // This account may revoke anything it sends, including a message it never+ // stored (a poll) or an admin delete made from the phone. A peer needs the+ // stored row to establish authorship or the admin delete of that author.+ authorized := fromMe+ if !authorized && existing != nil {+ authorized = whatsapp.MessageAuthorMatches(existing.Sender, existing.IsFromMe, sender, rawSender, fromMe) ||+ groupAdminRevoke(ctx, evt, existing.Sender)+ }+ if existing == nil && !authorized {+ // The row may already have been deleted by an authorized revoke whose+ // Chatwoot forward has not run. Do not replace that decision with false.+ whatsapp.NoteMessageRevokeAuthorization(deviceID, chatJID, revokedMessageID, false)+ whatsapp.NoteMessageEventAuthorization(deviceID, eventID, false)+ return nil+ }+ whatsapp.NoteMessageRevokeAuthorization(deviceID, chatJID, revokedMessageID, authorized)+ whatsapp.NoteMessageEventAuthorization(deviceID, eventID, authorized)+ if !authorized {+ logrus.Warnf("Ignoring revoke of message %s by %s: sender is not the author", revokedMessageID, sender)+ return nil+ }+ return r.DeleteMessageByDevice(deviceID, revokedMessageID, chatJID)+}++// isGroupAdmin asks WhatsApp whether a user currently administers a group.+// Tests replace it to answer without a connection.+var isGroupAdmin = whatsapp.IsGroupAdmin++// groupAdminRevoke reports a group admin deleting another member's message.+// WhatsApp marks it edit="8" and names the author as the key participant. The+// sender sets both, so the revoker's admin role is checked with WhatsApp.+func groupAdminRevoke(ctx context.Context, evt *events.Message, storedSender string) bool {+ if evt == nil || evt.Info.Chat.Server != types.GroupServer || evt.Info.Edit != types.EditAttributeAdminRevoke {+ return false+ }+ author, err := types.ParseJID(utils.UnwrapMessage(evt.Message).GetProtocolMessage().GetKey().GetParticipant())+ if err != nil {+ return false+ }+ client := whatsapp.ClientFromContext(ctx)+ normalizedAuthor := whatsapp.NormalizeJIDFromLID(ctx, author, client).ToNonAD().String()+ return whatsapp.MessageAuthorMatches(storedSender, false, normalizedAuthor, author.ToNonAD().String(), false) &&+ isGroupAdmin(ctx, client, evt.Info.Chat, evt.Info.Sender, evt.Info.SenderAlt)+}+func extractRevokedMessageID(msg *waE2E.Message) string {if msg == nil {return ""@@ -2329,7 +2449,7 @@ func extractEditedMessage(msg *waE2E.Message) *waE2E.Message {if msg == nil {return nil}- protocolMessage := msg.GetProtocolMessage()+ protocolMessage := utils.UnwrapMessage(msg).GetProtocolMessage()if protocolMessage == nil || protocolMessage.GetType() != waE2E.ProtocolMessage_MESSAGE_EDIT {return nil}@@ -2341,7 +2461,7 @@ func (r *SQLiteRepository) storeEditedMessage(ctx context.Context, evt *events.Mreturn nil}- protocolMessage := evt.Message.GetProtocolMessage()+ protocolMessage := utils.UnwrapMessage(evt.Message).GetProtocolMessage()if protocolMessage == nil {return nil}@@ -2360,6 +2480,13 @@ func (r *SQLiteRepository) storeEditedMessage(ctx context.Context, evt *events.M}messageExists := existingMessage != nil+ if !messageExists && !evt.Info.IsFromMe {+ // Without the original row a peer's authorship cannot be checked, and a+ // stub naming the editor as sender would authorize the editor's revoke.+ logrus.Warnf("Ignoring edit of message %s by %s: original message is not stored", originalMessageID, sender)+ whatsapp.NoteMessageEventAuthorization(deviceID, evt.Info.ID, false)+ return nil+ }currentMessage := existingMessagepreviousContent := ""@@ -2390,6 +2517,12 @@ func (r *SQLiteRepository) storeEditedMessage(ctx context.Context, evt *events.McurrentMessage.ContextMetadata = utils.ExtractContextMetadata(editedMessage)+ if messageExists && !whatsapp.MessageAuthorMatches(existingMessage.Sender, existingMessage.IsFromMe, sender, evt.Info.Sender.ToNonAD().String(), evt.Info.IsFromMe) {+ logrus.Warnf("Ignoring edit of message %s by %s: sender is not the author", originalMessageID, sender)+ whatsapp.NoteMessageEventAuthorization(deviceID, evt.Info.ID, false)+ return nil+ }+edit := &domainChatStorage.MessageEdit{OriginalMessageID: originalMessageID,EditEventID: evt.Info.ID,@@ -2435,7 +2568,11 @@ func (r *SQLiteRepository) storeEditedMessage(ctx context.Context, evt *events.Mreturn fmt.Errorf("failed to store edit history for %s: %w", originalMessageID, err)}- return tx.Commit()+ if err := tx.Commit(); err != nil {+ return err+ }+ whatsapp.NoteMessageEventAuthorization(deviceID, evt.Info.ID, true)+ return nil}func (r *SQLiteRepository) getMessageByDeviceAndChatIDAndMessageID(deviceID, chatJID, messageID string) (*domainChatStorage.Message, error) {diff --git a/src/infrastructure/chatstorage/sqlite_repository_chatwoot_config_test.go b/src/infrastructure/chatstorage/sqlite_repository_chatwoot_config_test.goindex 346efbee..5877b10e 100644--- a/src/infrastructure/chatstorage/sqlite_repository_chatwoot_config_test.go+++ b/src/infrastructure/chatstorage/sqlite_repository_chatwoot_config_test.go@@ -233,10 +233,75 @@ func TestSQLiteRepositoryConversationLookupIsConfigScoped(t *testing.T) {if err != nil || got == nil || got.DeviceID != "dev-b" {t.Fatalf("config-scoped lookup (20) = %+v err=%v, want dev-b", got, err)}- // configID 0 keeps the account-wide behavior (shared/legacy endpoint).+ // configID 0 is the shared webhook. Two configs means two servers that+ // reused account 1 / conversation 1; the newest row must not win.got, err = repo.GetLatestChatwootMessageLinkByConversation(1, 1, false, 0)- if err != nil || got == nil {- t.Fatalf("unscoped lookup: %v (%v)", err, got)+ if err != nil {+ t.Fatalf("ambiguous lookup: %v", err)+ }+ if got != nil {+ t.Fatalf("ambiguous servers must not resolve, got %+v", got)+ }+}++func TestSQLiteRepositoryConversationLookupUnscopedUsesSingleConfig(t *testing.T) {+ repo := newTestSQLiteRepository(t)+ for _, l := range []*domainChatStorage.ChatwootMessageLink{+ {DeviceID: "dev-a", WhatsAppMessageID: "old", WhatsAppChatJID: "[email protected]", ChatwootConversationID: 1, ChatwootAccountID: 1, ChatwootConfigID: 10, Direction: "incoming"},+ {DeviceID: "dev-a", WhatsAppMessageID: "new", WhatsAppChatJID: "[email protected]", ChatwootConversationID: 1, ChatwootAccountID: 1, ChatwootConfigID: 10, Direction: "incoming"},+ // A legacy zero-config row for the same conversation must not count as+ // a second server, and must not beat the real config.+ {DeviceID: "dev-stale", WhatsAppMessageID: "stale", WhatsAppChatJID: "[email protected]", ChatwootConversationID: 1, ChatwootAccountID: 1, ChatwootConfigID: 0, Direction: "incoming"},+ } {+ if err := repo.UpsertChatwootMessageLink(l); err != nil {+ t.Fatalf("upsert: %v", err)+ }+ }+ // The zero-config row is the newest. It must not beat the single real config.+ if _, err := repo.db.Exec(`UPDATE chatwoot_message_links SET updated_at = ? WHERE wa_message_id = ?`, time.Now().Add(2*time.Hour), "stale"); err != nil {+ t.Fatalf("touch stale: %v", err)+ }+ if _, err := repo.db.Exec(`UPDATE chatwoot_message_links SET updated_at = ? WHERE wa_message_id = ?`, time.Now().Add(time.Hour), "new"); err != nil {+ t.Fatalf("touch new: %v", err)+ }++ got, err := repo.GetLatestChatwootMessageLinkByConversation(1, 1, false, 0)+ if err != nil || got == nil || got.WhatsAppMessageID != "new" || got.DeviceID != "dev-a" {+ t.Fatalf("single-config lookup = %+v err=%v, want dev-a/new", got, err)+ }+}++func TestConversationLookupRecountsSecondConfigOnSameConnection(t *testing.T) {+ repo := newTestSQLiteRepository(t)+ if err := repo.UpsertChatwootMessageLink(&domainChatStorage.ChatwootMessageLink{+ DeviceID: "dev-a", WhatsAppMessageID: "a1", WhatsAppChatJID: "[email protected]",+ ChatwootConversationID: 1, ChatwootAccountID: 1, ChatwootConfigID: 10, Direction: "incoming",+ }); err != nil {+ t.Fatalf("upsert: %v", err)+ }++ prev := chatwootLinkLookupBeforeSelect+ chatwootLinkLookupBeforeSelect = func(tx *sql.Tx) {+ now := time.Now()+ if _, err := tx.Exec(`+ INSERT INTO chatwoot_message_links (+ device_id, wa_message_id, wa_chat_jid, chatwoot_message_id,+ chatwoot_conversation_id, chatwoot_inbox_id,+ chatwoot_contact_inbox_source_id, source_id, direction,+ is_read, created_at, updated_at, chatwoot_config_id, chatwoot_account_id+ ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)+ `, "dev-b", "b1", "[email protected]", 2, 1, 1, "", "", "incoming", false, now, now.Add(time.Hour), 20, 1); err != nil {+ t.Errorf("insert second config: %v", err)+ }+ }+ t.Cleanup(func() { chatwootLinkLookupBeforeSelect = prev })++ got, err := repo.GetLatestChatwootMessageLinkByConversation(1, 1, false, 0)+ if err != nil {+ t.Fatalf("lookup: %v", err)+ }+ if got != nil {+ t.Fatalf("second configuration visible in the transaction must return no row, got %+v", got)}}diff --git a/src/infrastructure/chatstorage/sqlite_repository_context_metadata_test.go b/src/infrastructure/chatstorage/sqlite_repository_context_metadata_test.goindex 9eb858e4..9488349c 100644--- a/src/infrastructure/chatstorage/sqlite_repository_context_metadata_test.go+++ b/src/infrastructure/chatstorage/sqlite_repository_context_metadata_test.go@@ -237,7 +237,12 @@ func TestContextMetadataEditCanSupplyMissingReply(t *testing.T) {t.Run(name, func(t *testing.T) {repo, ctx := orderTestRepo(t)if exists {- require.NoError(t, repo.StoreMessage(contextTestMessage(orderDevice, orderChatJID, orderMsgID, "")))+ // The edit is from this account. The stored row has to be that+ // author's, or the edit is refused.+ existing := contextTestMessage(orderDevice, orderChatJID, orderMsgID, "")+ existing.Sender = "[email protected]"+ existing.IsFromMe = true+ require.NoError(t, repo.StoreMessage(existing))}evt := editEvent(orderMsgID, "edited", time.Now())evt.Message.ProtocolMessage.EditedMessage = replyProto()diff --git a/src/infrastructure/chatstorage/sqlite_repository_delete_test.go b/src/infrastructure/chatstorage/sqlite_repository_delete_test.goindex 9e3a63f4..06adb557 100644--- a/src/infrastructure/chatstorage/sqlite_repository_delete_test.go+++ b/src/infrastructure/chatstorage/sqlite_repository_delete_test.go@@ -5,9 +5,11 @@ import ("testing""time"+ "github.com/aldinokemal/go-whatsapp-web-multidevice/config"domainChatStorage "github.com/aldinokemal/go-whatsapp-web-multidevice/domains/chatstorage""github.com/aldinokemal/go-whatsapp-web-multidevice/infrastructure/whatsapp""github.com/stretchr/testify/require"+ "go.mau.fi/whatsmeow""go.mau.fi/whatsmeow/proto/waCommon""go.mau.fi/whatsmeow/proto/waE2E""go.mau.fi/whatsmeow/types"@@ -24,6 +26,15 @@ func TestCreateMessageRevokeDeletesTargetForActiveDevice(t *testing.T) {seedChatMessage(t, repo, deviceID, chatJID, "message-1", "remove me", timestamp)seedChatMessage(t, repo, otherDeviceID, chatJID, "message-1", "keep me", timestamp)+ // The revoke sender is the author. seedChatMessage stores a different sender.+ require.NoError(t, repo.StoreMessage(&domainChatStorage.Message{+ ID: "message-1",+ ChatJID: chatJID,+ DeviceID: deviceID,+ Sender: "[email protected]",+ Content: "remove me",+ Timestamp: timestamp,+ }))ctx := whatsapp.ContextWithDevice(context.Background(), whatsapp.NewDeviceInstance(deviceID, nil, repo))revoke := &events.Message{@@ -164,3 +175,260 @@ func TestDeleteMessageRollsBackDependentDeletesWhenMessageDeleteFails(t *testing})}}++func TestCreateMessageRevokeIgnoresNonAuthor(t *testing.T) {+ repo := newTestSQLiteRepository(t)+ deviceID := authzDevice(t)+ chatJID := "[email protected]"+ timestamp := time.Date(2026, time.August, 22, 9, 0, 0, 0, time.UTC)+ seedChatMessage(t, repo, deviceID, chatJID, "message-foreign", "keep me", timestamp)++ ctx := whatsapp.ContextWithDevice(context.Background(), whatsapp.NewDeviceInstance(deviceID, nil, repo))+ revoke := &events.Message{+ Info: types.MessageInfo{+ MessageSource: types.MessageSource{+ Chat: types.NewJID("628123456789", types.DefaultUserServer),+ Sender: types.NewJID("628000000001", types.DefaultUserServer),+ },+ ID: "revoke-event-foreign",+ Timestamp: timestamp.Add(time.Minute),+ },+ Message: &waE2E.Message{ProtocolMessage: &waE2E.ProtocolMessage{+ Type: waE2E.ProtocolMessage_REVOKE.Enum(),+ Key: &waCommon.MessageKey{+ RemoteJID: proto.String(chatJID),+ ID: proto.String("message-foreign"),+ },+ }},+ }+ require.NoError(t, repo.CreateMessage(ctx, revoke))++ kept, err := repo.GetMessageByIDAndDevice(deviceID, "message-foreign")+ require.NoError(t, err)+ require.NotNil(t, kept)+ require.Equal(t, "keep me", kept.Content)++ authorized, ok := whatsapp.MessageRevokeAuthorized(deviceID, chatJID, "message-foreign")+ require.True(t, ok)+ require.False(t, authorized)+}++func TestRevokeAuthorizationSurvivesLaterMissingRow(t *testing.T) {+ repo := newTestSQLiteRepository(t)+ deviceID := authzDevice(t)+ chatJID := "[email protected]"+ timestamp := time.Date(2026, time.August, 22, 9, 0, 0, 0, time.UTC)+ require.NoError(t, repo.StoreMessage(&domainChatStorage.Message{+ ID: "message-1", ChatJID: chatJID, DeviceID: deviceID,+ Sender: "[email protected]", Content: "hello", Timestamp: timestamp,+ }))+ ctx := whatsapp.ContextWithDevice(context.Background(), whatsapp.NewDeviceInstance(deviceID, nil, repo))++ author := revokeEvent(chatJID, "revoke-ok", "628123456789", timestamp.Add(time.Minute))+ require.NoError(t, repo.CreateMessage(ctx, author))+ authorized, ok := whatsapp.MessageRevokeAuthorized(deviceID, chatJID, "message-1")+ require.True(t, ok)+ require.True(t, authorized)+ eventOK, ok := whatsapp.MessageEventAuthorized(deviceID, "revoke-ok")+ require.True(t, ok)+ require.True(t, eventOK)++ // The row is gone. A peer revoke of the same id must not flip the note.+ peer := revokeEvent(chatJID, "revoke-peer", "628000000001", timestamp.Add(2*time.Minute))+ require.NoError(t, repo.CreateMessage(ctx, peer))+ authorized, ok = whatsapp.MessageRevokeAuthorized(deviceID, chatJID, "message-1")+ require.True(t, ok)+ require.True(t, authorized, "missing-row revoke cleared an authorized decision")+ peerOK, ok := whatsapp.MessageEventAuthorized(deviceID, "revoke-peer")+ require.True(t, ok)+ require.False(t, peerOK)+}++func TestUnauthorizedRevokeDoesNotClearAuthorization(t *testing.T) {+ repo := newTestSQLiteRepository(t)+ deviceID := authzDevice(t)+ chatJID := "[email protected]"+ timestamp := time.Date(2026, time.August, 22, 9, 0, 0, 0, time.UTC)+ require.NoError(t, repo.StoreMessage(&domainChatStorage.Message{+ ID: "message-1", ChatJID: chatJID, DeviceID: deviceID,+ Sender: "[email protected]", Content: "hello", Timestamp: timestamp,+ }))+ whatsapp.NoteMessageRevokeAuthorization(deviceID, chatJID, "message-1", true)+ ctx := whatsapp.ContextWithDevice(context.Background(), whatsapp.NewDeviceInstance(deviceID, nil, repo))++ peer := revokeEvent(chatJID, "revoke-late", "628000000001", timestamp.Add(time.Minute))+ require.NoError(t, repo.CreateMessage(ctx, peer))++ kept, err := repo.GetMessageByIDAndDevice(deviceID, "message-1")+ require.NoError(t, err)+ require.NotNil(t, kept)+ authorized, ok := whatsapp.MessageRevokeAuthorized(deviceID, chatJID, "message-1")+ require.True(t, ok)+ require.True(t, authorized)+ eventOK, ok := whatsapp.MessageEventAuthorized(deviceID, "revoke-late")+ require.True(t, ok)+ require.False(t, eventOK)+}++func revokeEvent(chatJID, eventID, senderUser string, at time.Time) *events.Message {+ return &events.Message{+ Info: types.MessageInfo{+ MessageSource: types.MessageSource{+ Chat: types.NewJID("628123456789", types.DefaultUserServer),+ Sender: types.NewJID(senderUser, types.DefaultUserServer),+ },+ ID: eventID,+ Timestamp: at,+ },+ Message: &waE2E.Message{ProtocolMessage: &waE2E.ProtocolMessage{+ Type: waE2E.ProtocolMessage_REVOKE.Enum(),+ Key: &waCommon.MessageKey{+ RemoteJID: proto.String(chatJID),+ ID: proto.String("message-1"),+ },+ }},+ }+}++// authzDevice returns a device id unique to the running test, with Chatwoot+// enabled so CreateMessage records edit/revoke decisions. Both are undone at+// cleanup, so a -count or -shuffle run never reads another test's decision.+func authzDevice(t *testing.T) string {+ t.Helper()+ enabled := config.ChatwootEnabled+ config.ChatwootEnabled = true+ deviceID := t.Name()+ t.Cleanup(func() {+ config.ChatwootEnabled = enabled+ whatsapp.ForgetMessageAuthorizationsForTest(deviceID)+ })+ return deviceID+}++func TestCreateMessageGroupAdminRevoke(t *testing.T) {+ const (+ groupJID = "[email protected]"+ author = "[email protected]"+ revoker = "[email protected]"+ )+ for _, tc := range []struct {+ name string+ admin bool+ participant string+ authorized bool+ }{+ {"admin deletes the author message", true, author, true},+ {"non-admin peer is denied", false, author, false},+ {"admin naming another author is denied", true, revoker, false},+ } {+ t.Run(tc.name, func(t *testing.T) {+ repo := newTestSQLiteRepository(t)+ deviceID := authzDevice(t)+ var asked []string+ orig := isGroupAdmin+ isGroupAdmin = func(_ context.Context, _ *whatsmeow.Client, group types.JID, user ...types.JID) bool {+ asked = append(asked, group.String(), user[0].String())+ return tc.admin+ }+ t.Cleanup(func() { isGroupAdmin = orig })+ require.NoError(t, repo.StoreMessage(&domainChatStorage.Message{+ ID: "SPAM", ChatJID: groupJID, DeviceID: deviceID, Sender: author, Content: "spam", Timestamp: time.Now(),+ }))++ group, _ := types.ParseJID(groupJID)+ sender, _ := types.ParseJID(revoker)+ ctx := whatsapp.ContextWithDevice(context.Background(), whatsapp.NewDeviceInstance(deviceID, nil, repo))+ require.NoError(t, repo.CreateMessage(ctx, &events.Message{+ Info: types.MessageInfo{+ MessageSource: types.MessageSource{Chat: group, Sender: sender, IsGroup: true},+ ID: "REV-ADMIN",+ Edit: types.EditAttributeAdminRevoke,+ Timestamp: time.Now(),+ },+ Message: &waE2E.Message{ProtocolMessage: &waE2E.ProtocolMessage{+ Type: waE2E.ProtocolMessage_REVOKE.Enum(),+ Key: &waCommon.MessageKey{+ RemoteJID: proto.String(groupJID),+ ID: proto.String("SPAM"),+ FromMe: proto.Bool(false),+ Participant: proto.String(tc.participant),+ },+ }},+ }))++ kept, err := repo.GetMessageByIDAndDevice(deviceID, "SPAM")+ require.NoError(t, err)+ require.Equal(t, !tc.authorized, kept != nil)+ eventOK, ok := whatsapp.MessageEventAuthorized(deviceID, "REV-ADMIN")+ require.True(t, ok)+ require.Equal(t, tc.authorized, eventOK)+ if tc.authorized {+ require.Equal(t, []string{groupJID, revoker}, asked)+ }+ })+ }+}++func TestCreateMessageOwnRevokePurgesUnstoredPoll(t *testing.T) {+ repo := newTestSQLiteRepository(t)+ deviceID := authzDevice(t)+ chatJID := "[email protected]"+ require.NoError(t, repo.UpsertPollDefinition(&domainChatStorage.PollDefinition{+ DeviceID: deviceID, ChatJID: chatJID, PollMessageID: "POLL-OWN", Question: "lunch?",+ Options: []domainChatStorage.PollOption{{Name: "yes"}}, Version: "v3",+ }))+ seedReaction(t, repo, deviceID, chatJID, "POLL-OWN", "[email protected]")++ // Polls never get a messages row. The account's own revoke still counts.+ revoke := revokeEvent(chatJID, "REV-OWN-POLL", "628000000000", time.Now())+ revoke.Info.IsFromMe = true+ revoke.Message.ProtocolMessage.Key.ID = proto.String("POLL-OWN")+ ctx := whatsapp.ContextWithDevice(context.Background(), whatsapp.NewDeviceInstance(deviceID, nil, repo))+ require.NoError(t, repo.CreateMessage(ctx, revoke))++ poll, err := repo.GetPollDefinition(deviceID, chatJID, "POLL-OWN")+ require.NoError(t, err)+ require.Nil(t, poll)+ require.Zero(t, countMessageReactions(t, repo))+ eventOK, ok := whatsapp.MessageEventAuthorized(deviceID, "REV-OWN-POLL")+ require.True(t, ok)+ require.True(t, eventOK)+ authorized, ok := whatsapp.MessageRevokeAuthorized(deviceID, chatJID, "POLL-OWN")+ require.True(t, ok)+ require.True(t, authorized)+}++func TestCreateMessagePeerEditOfUnstoredMessageGrantsNoRevoke(t *testing.T) {+ repo := newTestSQLiteRepository(t)+ deviceID := authzDevice(t)+ chatJID := "[email protected]"+ require.NoError(t, repo.UpsertPollDefinition(&domainChatStorage.PollDefinition{+ DeviceID: deviceID, ChatJID: chatJID, PollMessageID: "POLL-A", Question: "lunch?",+ Options: []domainChatStorage.PollOption{{Name: "yes"}}, Version: "v3",+ }))+ ctx := whatsapp.ContextWithDevice(context.Background(), whatsapp.NewDeviceInstance(deviceID, nil, repo))++ edit := revokeEvent(chatJID, "EDIT-STUB", "628123456789", time.Now())+ edit.Message.ProtocolMessage = &waE2E.ProtocolMessage{+ Type: waE2E.ProtocolMessage_MESSAGE_EDIT.Enum(),+ Key: &waCommon.MessageKey{RemoteJID: proto.String(chatJID), ID: proto.String("POLL-A")},+ EditedMessage: &waE2E.Message{Conversation: proto.String("stub")},+ }+ require.NoError(t, repo.CreateMessage(ctx, edit))+ stub, err := repo.GetMessageByIDAndDevice(deviceID, "POLL-A")+ require.NoError(t, err)+ require.Nil(t, stub, "a peer edit of an unstored message created a row")+ editOK, ok := whatsapp.MessageEventAuthorized(deviceID, "EDIT-STUB")+ require.True(t, ok)+ require.False(t, editOK)++ revoke := revokeEvent(chatJID, "REV-STUB", "628123456789", time.Now())+ revoke.Message.ProtocolMessage.Key.ID = proto.String("POLL-A")+ require.NoError(t, repo.CreateMessage(ctx, revoke))+ poll, err := repo.GetPollDefinition(deviceID, chatJID, "POLL-A")+ require.NoError(t, err)+ require.NotNil(t, poll)+ revokeOK, ok := whatsapp.MessageEventAuthorized(deviceID, "REV-STUB")+ require.True(t, ok)+ require.False(t, revokeOK)+}diff --git a/src/infrastructure/chatstorage/sqlite_repository_edit_test.go b/src/infrastructure/chatstorage/sqlite_repository_edit_test.goindex 31d782d5..2b76bdea 100644--- a/src/infrastructure/chatstorage/sqlite_repository_edit_test.go+++ b/src/infrastructure/chatstorage/sqlite_repository_edit_test.go@@ -6,6 +6,7 @@ import ("testing""time"+ domainChatStorage "github.com/aldinokemal/go-whatsapp-web-multidevice/domains/chatstorage""github.com/aldinokemal/go-whatsapp-web-multidevice/infrastructure/whatsapp"_ "github.com/mattn/go-sqlite3""github.com/stretchr/testify/assert"@@ -140,6 +141,121 @@ func TestSQLiteRepositoryEditTestSuite(t *testing.T) {suite.Run(t, new(SQLiteRepositoryEditTestSuite))}+func TestCreateMessageEditRejectsOtherAuthor(t *testing.T) {+ db := openTestDB(t)+ repo := NewStorageRepository(db).(*SQLiteRepository)+ require.NoError(t, repo.InitializeSchema())+ deviceID := authzDevice(t)+ ctx := whatsapp.ContextWithDevice(context.Background(), whatsapp.NewDeviceInstance(deviceID, nil, nil))++ original := &events.Message{+ Info: types.MessageInfo{+ MessageSource: types.MessageSource{+ Chat: types.NewJID("123", types.DefaultUserServer),+ Sender: types.NewJID("123", types.DefaultUserServer),+ },+ ID: "MSG-1",+ Timestamp: time.Date(2026, time.May, 16, 10, 0, 0, 0, time.UTC),+ },+ Message: &waE2E.Message{Conversation: editProtoString("hello")},+ }+ require.NoError(t, repo.CreateMessage(ctx, original))++ edited := &events.Message{+ Info: types.MessageInfo{+ MessageSource: types.MessageSource{+ Chat: types.NewJID("123", types.DefaultUserServer),+ Sender: types.NewJID("999", types.DefaultUserServer),+ },+ ID: "EDIT-FOREIGN",+ Timestamp: time.Date(2026, time.May, 16, 10, 5, 0, 0, time.UTC),+ },+ Message: &waE2E.Message{ProtocolMessage: &waE2E.ProtocolMessage{+ Type: waE2E.ProtocolMessage_MESSAGE_EDIT.Enum(),+ Key: &waCommon.MessageKey{+ ID: editProtoString("MSG-1"),+ RemoteJID: editProtoString("[email protected]"),+ },+ EditedMessage: &waE2E.Message{Conversation: editProtoString("pwned")},+ }},+ }+ require.NoError(t, repo.CreateMessage(ctx, edited))++ got, err := repo.GetMessageByID("MSG-1")+ require.NoError(t, err)+ require.NotNil(t, got)+ assert.Equal(t, "hello", got.Content)+ authorized, ok := whatsapp.MessageEventAuthorized(deviceID, "EDIT-FOREIGN")+ require.True(t, ok)+ require.False(t, authorized)++ // whatsmeow strips each wrapper once, so a doubly wrapped edit still+ // arrives wrapped. It is the same edit and needs the same author check.+ wrapped := &events.Message{Info: edited.Info, Message: &waE2E.Message{+ EphemeralMessage: &waE2E.FutureProofMessage{Message: edited.Message},+ }}+ wrapped.Info.ID = "EDIT-FOREIGN-WRAPPED"+ require.NoError(t, repo.CreateMessage(ctx, wrapped))+ got, err = repo.GetMessageByID("MSG-1")+ require.NoError(t, err)+ assert.Equal(t, "hello", got.Content)+ authorized, ok = whatsapp.MessageEventAuthorized(deviceID, "EDIT-FOREIGN-WRAPPED")+ require.True(t, ok)+ require.False(t, authorized)++ var edits int+ require.NoError(t, db.QueryRow(`SELECT COUNT(*) FROM message_edits WHERE original_message_id = ?`, "MSG-1").Scan(&edits))+ assert.Zero(t, edits)+}++func TestCreateMessageEditAllowsOwnAccountAcrossSenderStrings(t *testing.T) {+ db := openTestDB(t)+ repo := NewStorageRepository(db).(*SQLiteRepository)+ require.NoError(t, repo.InitializeSchema())+ deviceID := authzDevice(t)+ ctx := whatsapp.ContextWithDevice(context.Background(), whatsapp.NewDeviceInstance(deviceID, nil, nil))++ require.NoError(t, repo.StoreMessage(&domainChatStorage.Message{+ ID: "MSG-OWN",+ ChatJID: "[email protected]",+ DeviceID: deviceID,+ Sender: "[email protected]",+ Content: "original",+ Timestamp: time.Date(2026, time.May, 16, 10, 0, 0, 0, time.UTC),+ IsFromMe: true,+ }))++ edited := &events.Message{+ Info: types.MessageInfo{+ MessageSource: types.MessageSource{+ Chat: types.NewJID("628123456789", types.DefaultUserServer),+ Sender: types.NewJID("628999999999", types.DefaultUserServer),+ IsFromMe: true,+ },+ ID: "EDIT-OWN",+ Timestamp: time.Date(2026, time.May, 16, 10, 5, 0, 0, time.UTC),+ },+ Message: &waE2E.Message{ProtocolMessage: &waE2E.ProtocolMessage{+ Type: waE2E.ProtocolMessage_MESSAGE_EDIT.Enum(),+ Key: &waCommon.MessageKey{+ ID: editProtoString("MSG-OWN"),+ RemoteJID: editProtoString("[email protected]"),+ FromMe: editProtoBool(true),+ },+ EditedMessage: &waE2E.Message{Conversation: editProtoString("edited by us")},+ }},+ }+ require.NoError(t, repo.CreateMessage(ctx, edited))++ got, err := repo.GetMessageByIDAndDevice(deviceID, "MSG-OWN")+ require.NoError(t, err)+ require.NotNil(t, got)+ assert.Equal(t, "edited by us", got.Content)+ authorized, ok := whatsapp.MessageEventAuthorized(deviceID, "EDIT-OWN")+ require.True(t, ok)+ require.True(t, authorized)+}+func openTestDB(t *testing.T) *sql.DB {t.Helper()diff --git a/src/infrastructure/chatwoot/client.go b/src/infrastructure/chatwoot/client.goindex 1c2da8e1..2288e959 100644--- a/src/infrastructure/chatwoot/client.go+++ b/src/infrastructure/chatwoot/client.go@@ -2,6 +2,7 @@ package chatwootimport ("bytes"+ "context""encoding/json""errors""fmt"@@ -210,12 +211,37 @@ func NewClient() *Client {// NewClientFromConfig builds a Chatwoot client for a specific (per-device)// destination from an operator-supplied config. The base URL is canonicalized-// (a stored, already-validated URL falls back to a trimmed value on error). The-// HTTP client is SSRF-guarded at connect time unless an explicit host allowlist-// is configured (CHATWOOT_ALLOWED_HOSTS), which is the operator's opt-in to-// trust specific hosts — including internal ones.+// (a stored, already-validated URL falls back to a trimmed value on error).+// The HTTP client is SSRF-guarded at connect time. When CHATWOOT_ALLOWED_HOSTS+// is set, the stored host is checked against that list again here — an operator+// can tighten the list after the row was saved — and every redirect is checked+// the same way. An allowlisted host may be private; that is the operator's+// explicit approval. An empty allowlist keeps the previous rule: public hosts+// are allowed and private addresses are refused, so a self-hosted Chatwoot is+// not suddenly blocked unless it was already blocked.func NewClientFromConfig(baseURL, apiToken string, accountID, inboxID int) *Client {- return newChatwootClient(baseURL, apiToken, accountID, inboxID, len(config.ChatwootAllowedHosts) == 0)+ if !perDeviceChatwootURLAllowed(baseURL) {+ return &Client{}+ }+ return newChatwootClient(baseURL, apiToken, accountID, inboxID, true)+}++// perDeviceChatwootURLAllowed reports whether baseURL may be used as a+// per-device Chatwoot destination under the current allowlist. An empty+// allowlist does not reject here; connect-time filtering still applies.+func perDeviceChatwootURLAllowed(baseURL string) bool {+ if len(config.ChatwootAllowedHosts) == 0 {+ return true+ }+ canonical, err := CanonicalizeChatwootURL(baseURL)+ if err != nil {+ return false+ }+ u, err := url.Parse(canonical)+ if err != nil || u.Hostname() == "" {+ return false+ }+ return chatwootHostAllowlisted(u.Hostname())}func newChatwootClient(baseURL, apiToken string, accountID, inboxID int, ssrfGuard bool) *Client {@@ -225,7 +251,8 @@ func newChatwootClient(baseURL, apiToken string, accountID, inboxID int, ssrfGua}httpClient := &http.Client{Timeout: 30 * time.Second}if ssrfGuard {- httpClient.Transport = ssrfGuardedTransport()+ httpClient.Transport = cappedBodyTransport{ssrfGuardedTransport()}+ httpClient.CheckRedirect = chatwootCheckRedirect}return &Client{BaseURL: canonical,@@ -236,30 +263,111 @@ func newChatwootClient(baseURL, apiToken string, accountID, inboxID int, ssrfGua}}-// ssrfGuardedTransport returns an HTTP transport whose dialer rejects, at-// connect time, any connection to a loopback/private/link-local/metadata-// address. Checking post-resolution (via Dialer.Control) closes the DNS-// rebinding window left open by validating the URL's host once up front.+// maxChatwootErrorBody is the most of an auto-decompressed Chatwoot error+// response that is kept. One extra byte is read so a larger body is rejected+// instead of being copied into the error string.+const maxChatwootErrorBody = 64 << 10++// maxChatwootResponseBody bounds every per-device response body after+// automatic decompression; a read past it fails with *http.MaxBytesError. It+// is generous for any Chatwoot API reply and keeps a small compressed body+// from an operator-supplied URL from expanding without limit in memory.+const maxChatwootResponseBody = 16 << 20++// cappedBodyTransport applies maxChatwootResponseBody to every response.+type cappedBodyTransport struct{ http.RoundTripper }++func (t cappedBodyTransport) RoundTrip(req *http.Request) (*http.Response, error) {+ resp, err := t.RoundTripper.RoundTrip(req)+ if err == nil {+ resp.Body = http.MaxBytesReader(nil, resp.Body, maxChatwootResponseBody)+ }+ return resp, err+}++// ssrfGuardedTransport returns an HTTP transport that refuses connections the+// operator has not approved.+//+// With an empty allowlist it rejects, at connect time, any loopback / private /+// link-local / metadata address. Checking post-resolution (via Dialer.Control)+// closes the DNS rebinding window left open by validating the URL's host once+// up front. Behind HTTP(S)_PROXY the dialed address is the proxy, so Proxy+// also refuses a request, redirects included, whose host is such an address+// written as a literal IP. A host name that resolves to one is not caught+// there: the proxy resolves it.+//+// With a non-empty allowlist the request's host must be on that list. Proxy+// checks it for every request, redirects included, before a connection is+// chosen; the dialed address is not checked because behind HTTP(S)_PROXY it+// is the proxy. An allowlisted host is dialed even when it is private — that+// host is the operator's explicit self-host exception.func ssrfGuardedTransport() *http.Transport {t := http.DefaultTransport.(*http.Transport).Clone()- dialer := &net.Dialer{+ t.Proxy = func(req *http.Request) (*url.URL, error) {+ if len(config.ChatwootAllowedHosts) > 0 && !chatwootHostAllowlisted(req.URL.Hostname()) {+ return nil, fmt.Errorf("chatwoot: host %q is not in the allowed hosts list", req.URL.Hostname())+ }+ if ip := net.ParseIP(req.URL.Hostname()); len(config.ChatwootAllowedHosts) == 0 && ip != nil && isDisallowedSSRFIP(ip) {+ return nil, fmt.Errorf("chatwoot: blocked request to disallowed address %s", req.URL.Hostname())+ }+ return http.ProxyFromEnvironment(req)+ }+ baseDialer := &net.Dialer{Timeout: 30 * time.Second,KeepAlive: 30 * time.Second,- Control: func(_, address string, _ syscall.RawConn) error {- host, _, err := net.SplitHostPort(address)- if err != nil {- host = address+ }+ t.DialContext = func(ctx context.Context, network, address string) (net.Conn, error) {+ if len(config.ChatwootAllowedHosts) > 0 {+ return baseDialer.DialContext(ctx, network, address)+ }+ guarded := *baseDialer+ guarded.Control = func(_, resolved string, _ syscall.RawConn) error {+ ipHost, _, splitErr := net.SplitHostPort(resolved)+ if splitErr != nil {+ ipHost = resolved}- if ip := net.ParseIP(host); ip != nil && isDisallowedSSRFIP(ip) {- return fmt.Errorf("chatwoot: blocked connection to disallowed address %s", address)+ if ip := net.ParseIP(ipHost); ip != nil && isDisallowedSSRFIP(ip) {+ return fmt.Errorf("chatwoot: blocked connection to disallowed address %s", resolved)}return nil- },+ }+ return guarded.DialContext(ctx, network, address)}- t.DialContext = dialer.DialContextreturn t}+// chatwootCheckRedirect applies the host allowlist to every redirect. An empty+// allowlist keeps the default follow-redirects behavior (the connect-time+// guard still blocks private addresses). A redirect to a different host or+// scheme drops the Chatwoot API token, with or without an allowlist, so+// credentials are not sent across origins.+func chatwootCheckRedirect(req *http.Request, via []*http.Request) error {+ if len(via) >= 10 {+ return errors.New("chatwoot: stopped after 10 redirects")+ }+ if len(via) > 0 && (!strings.EqualFold(via[0].URL.Hostname(), req.URL.Hostname()) || via[0].URL.Scheme != req.URL.Scheme) {+ req.Header.Del("api_access_token")+ }+ if len(config.ChatwootAllowedHosts) == 0 {+ return nil+ }+ if !chatwootHostAllowlisted(req.URL.Hostname()) {+ return fmt.Errorf("chatwoot: redirect host %q is not in the allowed hosts list", req.URL.Hostname())+ }+ return nil+}++func readChatwootErrorBody(r io.Reader) string {+ buf, err := io.ReadAll(io.LimitReader(r, maxChatwootErrorBody+1))+ if err != nil || len(buf) == 0 {+ return ""+ }+ if len(buf) > maxChatwootErrorBody {+ return fmt.Sprintf("response body exceeds %d bytes", maxChatwootErrorBody)+ }+ return string(buf)+}+func (c *Client) IsConfigured() bool {return c.BaseURL != "" && c.APIToken != "" && c.AccountID != 0 && c.InboxID != 0}@@ -290,8 +398,7 @@ func (c *Client) FindContactByIdentifier(identifier string, isGroup bool) (*Contdefer resp.Body.Close()if resp.StatusCode != http.StatusOK {- body, _ := io.ReadAll(resp.Body)- return nil, &HTTPStatusError{StatusCode: resp.StatusCode, Op: "search contact", Body: string(body)}+ return nil, &HTTPStatusError{StatusCode: resp.StatusCode, Op: "search contact", Body: readChatwootErrorBody(resp.Body)}}var result struct {diff --git a/src/infrastructure/chatwoot/client_registry.go b/src/infrastructure/chatwoot/client_registry.goindex a5ea9837..04fead87 100644--- a/src/infrastructure/chatwoot/client_registry.go+++ b/src/infrastructure/chatwoot/client_registry.go@@ -35,9 +35,10 @@ type ResolvedConfig struct {// back to the global env inbox — which would mis-deliver across accounts. The// env config is only used as a single "legacy" config while the table is empty.type ClientRegistry struct {- mu sync.RWMutex- cache map[string]*ResolvedConfig- repo domainChatStorage.IChatStorageRepository+ mu sync.Mutex+ cache map[string]*ResolvedConfig+ repo domainChatStorage.IChatStorageRepository+ generation uint64}func NewClientRegistry(repo domainChatStorage.IChatStorageRepository) *ClientRegistry {@@ -57,13 +58,32 @@ func (r *ClientRegistry) Resolve(identifier string) (*ResolvedConfig, error) {// a copy the cached key's bytes would silently mutate under the next request.identifier = strings.Clone(strings.TrimSpace(identifier))- r.mu.RLock()- if rc, ok := r.cache[identifier]; ok {- r.mu.RUnlock()- return rc, nil+ // Load outside the lock, then cache only if Invalidate has not run since+ // the load started. A result that lost that race is discarded and the+ // lookup is repeated so a disabled or replaced destination is not pinned.+ for attempt := 0; attempt < 2; attempt++ {+ r.mu.Lock()+ if rc, ok := r.cache[identifier]; ok {+ r.mu.Unlock()+ return rc, nil+ }+ gen := r.generation+ r.mu.Unlock()++ rc, err := r.loadResolved(identifier)+ if err != nil {+ return nil, err+ }+ if r.remember(identifier, gen, rc) {+ return rc, nil+ }}- r.mu.RUnlock()+ // Invalidation is still racing the load. Return the current row without+ // caching it; the next Resolve reads again.+ return r.loadResolved(identifier)+}+func (r *ClientRegistry) loadResolved(identifier string) (*ResolvedConfig, error) {if r.repo == nil {return nil, nil}@@ -77,13 +97,11 @@ func (r *ClientRegistry) Resolve(identifier string) (*ResolvedConfig, error) {// Explicitly disabled for this device: do not forward, do not fall back.return nil, nil}- rc := &ResolvedConfig{+ return &ResolvedConfig{ConfigID: cfg.ID,DeviceID: cfg.DeviceID,Client: NewClientFromConfig(cfg.ChatwootURL, cfg.APIToken, cfg.AccountID, cfg.InboxID),- }- r.store(identifier, rc)- return rc, nil+ }, nil}// No per-device row. Fall back to the env config ONLY while the table is@@ -93,13 +111,25 @@ func (r *ClientRegistry) Resolve(identifier string) (*ResolvedConfig, error) {return nil, err}if count == 0 {- rc := &ResolvedConfig{ConfigID: 0, DeviceID: identifier, Client: NewClient()}- r.store(identifier, rc)- return rc, nil+ return &ResolvedConfig{ConfigID: 0, DeviceID: identifier, Client: NewClient()}, nil}return nil, nil}+// remember caches rc when gen is still current. A nil rc is not cached.+// It reports false when Invalidate bumped the generation during the load.+func (r *ClientRegistry) remember(identifier string, gen uint64, rc *ResolvedConfig) bool {+ r.mu.Lock()+ defer r.mu.Unlock()+ if r.generation != gen {+ return false+ }+ if rc != nil {+ r.cache[identifier] = rc+ }+ return true+}+// ResolveByInbox maps a Chatwoot (account, inbox) to a device config. Used by// the reverse path for agent-initiated conversations. Returns nil when there is// no unambiguous match (the underlying repo returns nil on ambiguity).@@ -134,6 +164,9 @@ func (r *ClientRegistry) Invalidate(deviceID string) {deviceID = strings.TrimSpace(deviceID)r.mu.Lock()defer r.mu.Unlock()+ // Bump even when the cache is empty so a load already in flight cannot+ // insert the client it read before this invalidation.+ r.generation++for key, rc := range r.cache {if key == deviceID || rc == nil || rc.DeviceID == deviceID || rc.ConfigID == 0 {delete(r.cache, key)@@ -141,12 +174,6 @@ func (r *ClientRegistry) Invalidate(deviceID string) {}}-func (r *ClientRegistry) store(identifier string, rc *ResolvedConfig) {- r.mu.Lock()- r.cache[identifier] = rc- r.mu.Unlock()-}-// Package-global registry, initialized at boot from the chat storage repo.var (globalRegistry *ClientRegistrydiff --git a/src/infrastructure/chatwoot/client_registry_test.go b/src/infrastructure/chatwoot/client_registry_test.goindex 46fa4375..ec76af69 100644--- a/src/infrastructure/chatwoot/client_registry_test.go+++ b/src/infrastructure/chatwoot/client_registry_test.go@@ -1,6 +1,7 @@package chatwootimport (+ "sync""testing""github.com/aldinokemal/go-whatsapp-web-multidevice/config"@@ -185,6 +186,106 @@ func TestClientRegistryInvalidatePurgesEnvFallbackEntries(t *testing.T) {}}+type blockingConfigRepo struct {+ domainChatStorage.IChatStorageRepository+ mu sync.Mutex+ current *domainChatStorage.ChatwootDeviceConfig+ calls int+ entered chan struct{}+ release chan struct{}+ once sync.Once+}++func (b *blockingConfigRepo) GetChatwootDeviceConfigByIdentifier(string) (*domainChatStorage.ChatwootDeviceConfig, error) {+ b.mu.Lock()+ b.calls+++ call := b.calls+ cfg := b.current+ b.mu.Unlock()+ if call == 1 {+ b.once.Do(func() { close(b.entered) })+ <-b.release+ return cfg, nil+ }+ b.mu.Lock()+ defer b.mu.Unlock()+ return b.current, nil+}++func (b *blockingConfigRepo) CountChatwootDeviceConfigs() (int, error) { return 1, nil }++func TestClientRegistryDoesNotCacheClientInvalidatedDuringLoad(t *testing.T) {+ oldCfg := &domainChatStorage.ChatwootDeviceConfig{+ ID: 1, DeviceID: "d", ChatwootURL: "https://old.example.com", AccountID: 1, InboxID: 1, APIToken: "t", Enabled: true,+ }+ newCfg := &domainChatStorage.ChatwootDeviceConfig{+ ID: 1, DeviceID: "d", ChatwootURL: "https://new.example.com", AccountID: 1, InboxID: 9, APIToken: "t", Enabled: true,+ }+ repo := &blockingConfigRepo{current: oldCfg, entered: make(chan struct{}), release: make(chan struct{})}+ reg := NewClientRegistry(repo)++ type result struct {+ rc *ResolvedConfig+ err error+ }+ done := make(chan result, 1)+ go func() {+ rc, err := reg.Resolve("d")+ done <- result{rc, err}+ }()+ <-repo.entered+ repo.mu.Lock()+ repo.current = newCfg+ repo.mu.Unlock()+ reg.Invalidate("d")+ close(repo.release)++ got := <-done+ if got.err != nil {+ t.Fatalf("resolve: %v", got.err)+ }+ if got.rc == nil || got.rc.Client == nil || got.rc.Client.BaseURL != "https://new.example.com" || got.rc.Client.InboxID != 9 {+ t.Fatalf("in-flight resolve kept the pre-invalidation client: %+v", got.rc)+ }+ again, err := reg.Resolve("d")+ if err != nil || again == nil || again.Client == nil || again.Client.BaseURL != "https://new.example.com" {+ t.Fatalf("later resolve is stale: %+v err=%v", again, err)+ }+}++func TestClientRegistryDisabledDuringLoadIsNotCached(t *testing.T) {+ oldCfg := &domainChatStorage.ChatwootDeviceConfig{+ ID: 1, DeviceID: "d", ChatwootURL: "https://old.example.com", AccountID: 1, InboxID: 1, APIToken: "t", Enabled: true,+ }+ disabled := &domainChatStorage.ChatwootDeviceConfig{+ ID: 1, DeviceID: "d", ChatwootURL: "https://old.example.com", AccountID: 1, InboxID: 1, APIToken: "t", Enabled: false,+ }+ repo := &blockingConfigRepo{current: oldCfg, entered: make(chan struct{}), release: make(chan struct{})}+ reg := NewClientRegistry(repo)++ done := make(chan *ResolvedConfig, 1)+ go func() {+ rc, err := reg.Resolve("d")+ if err != nil {+ t.Errorf("resolve: %v", err)+ }+ done <- rc+ }()+ <-repo.entered+ repo.mu.Lock()+ repo.current = disabled+ repo.mu.Unlock()+ reg.Invalidate("d")+ close(repo.release)++ if rc := <-done; rc != nil {+ t.Fatalf("disabled config was returned: %+v", rc)+ }+ if rc, err := reg.Resolve("d"); err != nil || rc != nil {+ t.Fatalf("disabled config was cached: %+v err=%v", rc, err)+ }+}+func TestClientRegistryResolveByInbox(t *testing.T) {cfg := &domainChatStorage.ChatwootDeviceConfig{ID: 5, DeviceID: "d", ChatwootURL: "https://a.example.com", AccountID: 3, InboxID: 9, APIToken: "t", Enabled: true}repo := &fakeConfigRepo{byInbox: map[[2]int]*domainChatStorage.ChatwootDeviceConfig{{3, 9}: cfg}}diff --git a/src/infrastructure/chatwoot/pgimport/writer.go b/src/infrastructure/chatwoot/pgimport/writer.goindex 46a1e898..45159062 100644--- a/src/infrastructure/chatwoot/pgimport/writer.go+++ b/src/infrastructure/chatwoot/pgimport/writer.go@@ -445,22 +445,18 @@ func (i *Importer) insertMessage(sourceID := "WAID:" + msg.ID// Idempotency probe keyed to the inbox: Chatwoot's `index_messages_on_source_id`- // is plain (non-unique), but messages imported under the same inbox- // share a source_id iff they're the same WhatsApp message — whether- // they landed in a different conversation after a resolve/reopen cycle- // or not. Inbox-scoped lookup makes replays correctly skip duplicates.- var existingID, existingConvID int- err := tx.QueryRowContext(ctx, `- SELECT id, conversation_id FROM messages- WHERE inbox_id = $1 AND source_id = $2- LIMIT 1- `, i.inboxID, sourceID).Scan(&existingID, &existingConvID)- if err == nil {- return i.buildMessageLink(msg, existingConvID, existingID, sourceID, messageTypeForWA(msg.IsFromMe)), false, nil- }- if err != sql.ErrNoRows {+ // is plain (non-unique). A hit is the same WhatsApp message only when the+ // existing conversation belongs to this chat's contact — a resolve/reopen+ // cycle keeps the contact and changes the conversation id. An inbox-wide+ // source_id collision in some other contact's conversation must not become+ // a routing link for this chat.+ existingID, existingConvID, reuse, err := i.existingMessageForChat(ctx, tx, contactID, sourceID)+ if err != nil {return nil, false, err}+ if reuse {+ return i.buildMessageLink(msg, existingConvID, existingID, sourceID, messageTypeForWA(msg.IsFromMe)), false, nil+ }content := buildContent(msg, isGroup)// Skip entirely when there is nothing meaningful to show — no body, no@@ -536,6 +532,28 @@ func (i *Importer) insertMessage(return i.buildMessageLink(msg, convID, chatwootMessageID, sourceID, mType), true, nil}+// existingMessageForChat reports an inbox source_id hit in one of this chat+// contact's conversations. reuse is false when nothing matches or the only+// hits sit on other contacts' conversations; the caller then inserts instead+// of linking a foreign conversation. The contact filter runs before LIMIT 1,+// so another contact's copy of the source_id cannot hide this contact's row.+func (i *Importer) existingMessageForChat(ctx context.Context, tx *sql.Tx, contactID int, sourceID string) (existingID, existingConvID int, reuse bool, err error) {+ err = tx.QueryRowContext(ctx, `+ SELECT m.id, m.conversation_id FROM messages m+ JOIN conversations c ON c.id = m.conversation_id+ WHERE m.inbox_id = $1 AND m.source_id = $2+ AND c.account_id = $3 AND c.inbox_id = $1 AND c.contact_id = $4+ LIMIT 1+ `, i.inboxID, sourceID, i.accountID, contactID).Scan(&existingID, &existingConvID)+ if err == sql.ErrNoRows {+ return 0, 0, false, nil+ }+ if err != nil {+ return 0, 0, false, err+ }+ return existingID, existingConvID, true, nil+}+func (i *Importer) buildMessageLink(msg *domainChatStorage.Message, convID, chatwootMessageID int, sourceID string, messageType int) *domainChatStorage.ChatwootMessageLink {if msg == nil || msg.ID == "" || msg.DeviceID == "" || chatwootMessageID == 0 {return nildiff --git a/src/infrastructure/chatwoot/pgimport/writer_flow_test.go b/src/infrastructure/chatwoot/pgimport/writer_flow_test.goindex a0c10f02..92a0c8e4 100644--- a/src/infrastructure/chatwoot/pgimport/writer_flow_test.go+++ b/src/infrastructure/chatwoot/pgimport/writer_flow_test.go@@ -93,7 +93,7 @@ func TestImportChat_HappyPath(t *testing.T) {// msg1 — savepoint, probe miss, insert, release.mock.ExpectExec(regexp.QuoteMeta("SAVEPOINT cw_msg")).WillReturnResult(sqlmock.NewResult(0, 0))mock.ExpectQuery(regexp.QuoteMeta(idempotencyProbeSQL)).- WithArgs(imp.inboxID, "WAID:wa-1").+ WithArgs(imp.inboxID, "WAID:wa-1", imp.accountID, 100).WillReturnError(noRowsError())mock.ExpectQuery(`INSERT INTO messages`).WillReturnRows(sqlmock.NewRows([]string{"id"}).AddRow(1))mock.ExpectExec(regexp.QuoteMeta("RELEASE SAVEPOINT cw_msg")).WillReturnResult(sqlmock.NewResult(0, 0))@@ -101,7 +101,7 @@ func TestImportChat_HappyPath(t *testing.T) {// msg2 — same shape.mock.ExpectExec(regexp.QuoteMeta("SAVEPOINT cw_msg")).WillReturnResult(sqlmock.NewResult(0, 0))mock.ExpectQuery(regexp.QuoteMeta(idempotencyProbeSQL)).- WithArgs(imp.inboxID, "WAID:wa-2").+ WithArgs(imp.inboxID, "WAID:wa-2", imp.accountID, 100).WillReturnError(noRowsError())mock.ExpectQuery(`INSERT INTO messages`).WillReturnRows(sqlmock.NewRows([]string{"id"}).AddRow(1))mock.ExpectExec(regexp.QuoteMeta("RELEASE SAVEPOINT cw_msg")).WillReturnResult(sqlmock.NewResult(0, 0))@@ -166,7 +166,7 @@ func TestImportChat_HappyPathExistingContactFastPath(t *testing.T) {// single message written.mock.ExpectExec(regexp.QuoteMeta("SAVEPOINT cw_msg")).WillReturnResult(sqlmock.NewResult(0, 0))mock.ExpectQuery(regexp.QuoteMeta(idempotencyProbeSQL)).- WithArgs(imp.inboxID, "WAID:wa-1").+ WithArgs(imp.inboxID, "WAID:wa-1", imp.accountID, 100).WillReturnError(noRowsError())mock.ExpectQuery(`INSERT INTO messages`).WillReturnRows(sqlmock.NewRows([]string{"id"}).AddRow(1))mock.ExpectExec(regexp.QuoteMeta("RELEASE SAVEPOINT cw_msg")).WillReturnResult(sqlmock.NewResult(0, 0))@@ -217,7 +217,7 @@ func TestImportChat_IdempotentSkip(t *testing.T) {// Savepoint + probe HIT -> RELEASE, but no INSERT and no touchConversation.mock.ExpectExec(regexp.QuoteMeta("SAVEPOINT cw_msg")).WillReturnResult(sqlmock.NewResult(0, 0))mock.ExpectQuery(regexp.QuoteMeta(idempotencyProbeSQL)).- WithArgs(imp.inboxID, "WAID:wa-dup").+ WithArgs(imp.inboxID, "WAID:wa-dup", imp.accountID, 100).WillReturnRows(sqlmock.NewRows([]string{"id", "conversation_id"}).AddRow(1, 300))mock.ExpectExec(regexp.QuoteMeta("RELEASE SAVEPOINT cw_msg")).WillReturnResult(sqlmock.NewResult(0, 0))@@ -274,7 +274,7 @@ func TestImportChat_PerMessageFailureCountedNotFatal(t *testing.T) {// msg1 fails the INSERT -> ROLLBACK TO SAVEPOINT, not fatal.mock.ExpectExec(regexp.QuoteMeta("SAVEPOINT cw_msg")).WillReturnResult(sqlmock.NewResult(0, 0))mock.ExpectQuery(regexp.QuoteMeta(idempotencyProbeSQL)).- WithArgs(imp.inboxID, "WAID:wa-bad").+ WithArgs(imp.inboxID, "WAID:wa-bad", imp.accountID, 100).WillReturnError(noRowsError())mock.ExpectQuery(`INSERT INTO messages`).WillReturnError(errors.New("constraint boom"))mock.ExpectExec(regexp.QuoteMeta("ROLLBACK TO SAVEPOINT cw_msg")).WillReturnResult(sqlmock.NewResult(0, 0))@@ -282,7 +282,7 @@ func TestImportChat_PerMessageFailureCountedNotFatal(t *testing.T) {// msg2 succeeds.mock.ExpectExec(regexp.QuoteMeta("SAVEPOINT cw_msg")).WillReturnResult(sqlmock.NewResult(0, 0))mock.ExpectQuery(regexp.QuoteMeta(idempotencyProbeSQL)).- WithArgs(imp.inboxID, "WAID:wa-good").+ WithArgs(imp.inboxID, "WAID:wa-good", imp.accountID, 100).WillReturnError(noRowsError())mock.ExpectQuery(`INSERT INTO messages`).WillReturnRows(sqlmock.NewRows([]string{"id"}).AddRow(1))mock.ExpectExec(regexp.QuoteMeta("RELEASE SAVEPOINT cw_msg")).WillReturnResult(sqlmock.NewResult(0, 0))@@ -495,7 +495,7 @@ func TestImportChat_GroupSkipsTouchWhenAllZeroTimestampsFallBackToNow(t *testingmock.ExpectExec(regexp.QuoteMeta("SAVEPOINT cw_msg")).WillReturnResult(sqlmock.NewResult(0, 0))mock.ExpectQuery(regexp.QuoteMeta(idempotencyProbeSQL)).- WithArgs(imp.inboxID, "WAID:wa-1").+ WithArgs(imp.inboxID, "WAID:wa-1", imp.accountID, 100).WillReturnError(noRowsError())mock.ExpectQuery(`INSERT INTO messages`).WillReturnRows(sqlmock.NewRows([]string{"id"}).AddRow(1))mock.ExpectExec(regexp.QuoteMeta("RELEASE SAVEPOINT cw_msg")).WillReturnResult(sqlmock.NewResult(0, 0))diff --git a/src/infrastructure/chatwoot/pgimport/writer_test.go b/src/infrastructure/chatwoot/pgimport/writer_test.goindex 499956b5..efdef983 100644--- a/src/infrastructure/chatwoot/pgimport/writer_test.go+++ b/src/infrastructure/chatwoot/pgimport/writer_test.go@@ -84,13 +84,12 @@ func TestInsertMessage_SenderResolution(t *testing.T) {agentUserID: tc.agentUserID,}- // Idempotency probe must hit messages with (inbox_id, source_id).- // Returning ErrNoRows forces the writer to attempt the INSERT.+ // Idempotency probe must hit messages with (inbox_id, source_id)+ // in this contact's conversations. Returning ErrNoRows forces the+ // writer to attempt the INSERT.mock.ExpectBegin()- mock.ExpectQuery(regexp.QuoteMeta(`SELECT id, conversation_id FROM messages- WHERE inbox_id = $1 AND source_id = $2- LIMIT 1`)).- WithArgs(2, "WAID:"+tc.msg.ID).+ mock.ExpectQuery(regexp.QuoteMeta(idempotencyProbeSQL)).+ WithArgs(2, "WAID:"+tc.msg.ID, 1, contactID).WillReturnError(noRowsError())// The INSERT carries 12 args. Pin the WhatsApp timestamp becausediff --git a/src/infrastructure/chatwoot/pgimport/writer_units_test.go b/src/infrastructure/chatwoot/pgimport/writer_units_test.goindex ebc8ceec..e40d84a8 100644--- a/src/infrastructure/chatwoot/pgimport/writer_units_test.go+++ b/src/infrastructure/chatwoot/pgimport/writer_units_test.go@@ -63,8 +63,10 @@ const insertConversationSQL = ``const idempotencyProbeSQL = `- SELECT id, conversation_id FROM messages- WHERE inbox_id = $1 AND source_id = $2+ SELECT m.id, m.conversation_id FROM messages m+ JOIN conversations c ON c.id = m.conversation_id+ WHERE m.inbox_id = $1 AND m.source_id = $2+ AND c.account_id = $3 AND c.inbox_id = $1 AND c.contact_id = $4LIMIT 1`@@ -170,8 +172,10 @@ func TestInsertMessage_IdempotencyHitReturnsFalseNoInsert(t *testing.T) {defer cleanup()mock.ExpectBegin()+ // Conversation 300 is not the caller's conversation (10). The probe only+ // returns rows of this chat's contact (20), so it is a resolve/reopen.mock.ExpectQuery(regexp.QuoteMeta(idempotencyProbeSQL)).- WithArgs(imp.inboxID, "WAID:wa-dup").+ WithArgs(imp.inboxID, "WAID:wa-dup", imp.accountID, 20).WillReturnRows(sqlmock.NewRows([]string{"id", "conversation_id"}).AddRow(1, 300))tx, err := imp.db.BeginTx(context.Background(), nil)@@ -192,6 +196,62 @@ func TestInsertMessage_IdempotencyHitReturnsFalseNoInsert(t *testing.T) {}}+func TestInsertMessage_ForeignConversationIsNotLinked(t *testing.T) {+ imp, mock, cleanup := newUpsertContactTestImporter(t)+ defer cleanup()++ now := time.Date(2026, time.June, 6, 12, 0, 0, 0, time.UTC)+ msg := &domainChatStorage.Message{+ ID: "wa-foreign",+ DeviceID: "[email protected]",+ ChatJID: "[email protected]",+ Content: "this chat",+ Timestamp: now,+ }++ mock.ExpectBegin()+ // The source_id exists only in another contact's conversation, which the+ // contact filter in the probe leaves out.+ mock.ExpectQuery(regexp.QuoteMeta(idempotencyProbeSQL)).+ WithArgs(imp.inboxID, "WAID:wa-foreign", imp.accountID, 20).+ WillReturnError(sql.ErrNoRows)+ mock.ExpectQuery(`INSERT INTO messages`).+ WithArgs(+ "this chat",+ imp.accountID,+ imp.inboxID,+ 10,+ messageTypeIncoming,+ now,+ messageStatusDelivered,+ "WAID:wa-foreign",+ contentTypeText,+ "Contact",+ int64(20),+ sqlmock.AnyArg(),+ ).+ WillReturnRows(sqlmock.NewRows([]string{"id"}).AddRow(404))++ tx, err := imp.db.BeginTx(context.Background(), nil)+ if err != nil {+ t.Fatalf("BeginTx: %v", err)+ }+ link, wrote, err := imp.insertMessage(context.Background(), tx, 10, 20, msg, false)+ if err != nil {+ t.Fatalf("insertMessage: %v", err)+ }+ if !wrote {+ t.Fatal("wrote = false, want a new row in this chat's conversation")+ }+ if link == nil || link.ChatwootConversationID != 10 || link.WhatsAppChatJID != msg.ChatJID {+ t.Fatalf("foreign conversation was linked: %+v", link)+ }+ _ = tx.Rollback()+ if err := mock.ExpectationsWereMet(); err != nil {+ t.Errorf("unmet sqlmock expectations: %v", err)+ }+}+func TestInsertMessage_EmptyContentSkipsAfterProbeMiss(t *testing.T) {// Probe misses (ErrNoRows) but the computed content is empty (no body, no// media placeholder): insertMessage returns (false, nil) WITHOUT an INSERT@@ -205,7 +265,7 @@ func TestInsertMessage_EmptyContentSkipsAfterProbeMiss(t *testing.T) {mock.ExpectBegin()mock.ExpectQuery(regexp.QuoteMeta(idempotencyProbeSQL)).- WithArgs(imp.inboxID, "WAID:wa-empty").+ WithArgs(imp.inboxID, "WAID:wa-empty", imp.accountID, 20).WillReturnError(sql.ErrNoRows)tx, err := imp.db.BeginTx(context.Background(), nil)@@ -236,7 +296,7 @@ func TestInsertMessage_ProbeQueryErrorPropagates(t *testing.T) {probeErr := errors.New("probe boom")mock.ExpectBegin()mock.ExpectQuery(regexp.QuoteMeta(idempotencyProbeSQL)).- WithArgs(imp.inboxID, "WAID:wa-err").+ WithArgs(imp.inboxID, "WAID:wa-err", imp.accountID, 20).WillReturnError(probeErr)tx, err := imp.db.BeginTx(context.Background(), nil)@@ -272,7 +332,7 @@ func TestInsertMessage_ReturnsChatwootLinkForInsertedMessage(t *testing.T) {mock.ExpectBegin()mock.ExpectQuery(regexp.QuoteMeta(idempotencyProbeSQL)).- WithArgs(imp.inboxID, "WAID:wa-linked").+ WithArgs(imp.inboxID, "WAID:wa-linked", imp.accountID, 20).WillReturnError(sql.ErrNoRows)mock.ExpectQuery(`INSERT INTO messages`).WithArgs(@@ -332,7 +392,7 @@ func TestInsertMessage_GroupIncomingContentGetsSenderPrefix(t *testing.T) {mock.ExpectBegin()mock.ExpectQuery(regexp.QuoteMeta(idempotencyProbeSQL)).- WithArgs(imp.inboxID, "WAID:wa-grp").+ WithArgs(imp.inboxID, "WAID:wa-grp", imp.accountID, 77).WillReturnError(sql.ErrNoRows)mock.ExpectQuery(`INSERT INTO messages`).WithArgs(@@ -385,7 +445,7 @@ func TestInsertMessageSavepoint_Success(t *testing.T) {mock.ExpectExec(regexp.QuoteMeta("SAVEPOINT cw_msg")).WillReturnResult(sqlmock.NewResult(0, 0))mock.ExpectQuery(regexp.QuoteMeta(idempotencyProbeSQL)).- WithArgs(imp.inboxID, "WAID:sp-ok").+ WithArgs(imp.inboxID, "WAID:sp-ok", imp.accountID, 20).WillReturnError(sql.ErrNoRows)mock.ExpectQuery(`INSERT INTO messages`).WillReturnRows(sqlmock.NewRows([]string{"id"}).AddRow(1))@@ -423,7 +483,7 @@ func TestInsertMessageSavepoint_InsertErrorRollsBackToSavepoint(t *testing.T) {mock.ExpectExec(regexp.QuoteMeta("SAVEPOINT cw_msg")).WillReturnResult(sqlmock.NewResult(0, 0))mock.ExpectQuery(regexp.QuoteMeta(idempotencyProbeSQL)).- WithArgs(imp.inboxID, "WAID:sp-fail").+ WithArgs(imp.inboxID, "WAID:sp-fail", imp.accountID, 20).WillReturnError(sql.ErrNoRows)mock.ExpectQuery(`INSERT INTO messages`).WillReturnError(insertErr)@@ -501,7 +561,7 @@ func TestInsertMessageSavepoint_ReleaseErrorIsFatal(t *testing.T) {mock.ExpectExec(regexp.QuoteMeta("SAVEPOINT cw_msg")).WillReturnResult(sqlmock.NewResult(0, 0))mock.ExpectQuery(regexp.QuoteMeta(idempotencyProbeSQL)).- WithArgs(imp.inboxID, "WAID:sp-rel").+ WithArgs(imp.inboxID, "WAID:sp-rel", imp.accountID, 20).WillReturnError(sql.ErrNoRows)mock.ExpectQuery(`INSERT INTO messages`).WillReturnRows(sqlmock.NewRows([]string{"id"}).AddRow(1))@@ -544,7 +604,7 @@ func TestInsertMessageSavepoint_RollbackErrorBecomesFatal(t *testing.T) {mock.ExpectExec(regexp.QuoteMeta("SAVEPOINT cw_msg")).WillReturnResult(sqlmock.NewResult(0, 0))mock.ExpectQuery(regexp.QuoteMeta(idempotencyProbeSQL)).- WithArgs(imp.inboxID, "WAID:sp-rb").+ WithArgs(imp.inboxID, "WAID:sp-rb", imp.accountID, 20).WillReturnError(sql.ErrNoRows)mock.ExpectQuery(`INSERT INTO messages`).WillReturnError(insertErr)diff --git a/src/infrastructure/chatwoot/sync.go b/src/infrastructure/chatwoot/sync.goindex 3596ff56..dd109628 100644--- a/src/infrastructure/chatwoot/sync.go+++ b/src/infrastructure/chatwoot/sync.go@@ -229,6 +229,21 @@ func (s *SyncService) SyncHistory(ctx context.Context, deviceID string, waClientlogrus.Debugf("Chatwoot Sync: Skipping ignored chat %s", chat.JID)continue}+ // The stored JID is phone-normalized, but an ignore entry may name the+ // chat's LID (or the reverse), so the chat's other address counts too,+ // matched against exact entries as on the live path.+ if jid, err := types.ParseJID(chat.JID); err == nil && len(config.ChatwootIgnoreJids) > 0 {+ var other types.JID+ if jid.Server == types.HiddenUserServer {+ other = utils.ResolveLIDToPhone(ctx, jid, waClient)+ } else {+ other = utils.ResolvePhoneToLID(ctx, jid, waClient)+ }+ if utils.MatchesIgnoredAliasJID(other.String(), config.ChatwootIgnoreJids) {+ logrus.Debugf("Chatwoot Sync: Skipping ignored chat %s (%s)", chat.JID, other)+ continue+ }+ }progress.UpdateChat(chat.JID)diff --git a/src/infrastructure/chatwoot/sync_test.go b/src/infrastructure/chatwoot/sync_test.goindex c08d974c..4bfb6aac 100644--- a/src/infrastructure/chatwoot/sync_test.go+++ b/src/infrastructure/chatwoot/sync_test.go@@ -3,10 +3,17 @@ package chatwootimport ("context""fmt"+ "net/http"+ "net/http/httptest"+ "sync/atomic""testing""time""github.com/aldinokemal/go-whatsapp-web-multidevice/config"+ domainChatStorage "github.com/aldinokemal/go-whatsapp-web-multidevice/domains/chatstorage"+ "go.mau.fi/whatsmeow"+ "go.mau.fi/whatsmeow/store"+ "go.mau.fi/whatsmeow/types")// TestTriggerAutoSync_NoopWhenGated verifies the connect-path entrypoint is a@@ -299,3 +306,91 @@ func TestHTTPStatusError_Message(t *testing.T) {t.Errorf("got %q, want %q", got, want)}}++// syncChatsRepo serves a fixed chat list to SyncHistory.+type syncChatsRepo struct {+ domainChatStorage.IChatStorageRepository+ chats []*domainChatStorage.Chat+}++func (r syncChatsRepo) GetChats(*domainChatStorage.ChatFilter) ([]*domainChatStorage.Chat, error) {+ return r.chats, nil+}++// syncTestLIDs is a WhatsApp LID store holding phone JID -> LID mappings.+type syncTestLIDs struct {+ store.LIDStore+ pnToLID map[types.JID]types.JID+}++func (s syncTestLIDs) GetLIDForPN(_ context.Context, pn types.JID) (types.JID, error) {+ return s.pnToLID[pn], nil+}++func (s syncTestLIDs) GetPNForLID(_ context.Context, lid types.JID) (types.JID, error) {+ for pn, mapped := range s.pnToLID {+ if mapped == lid {+ return pn, nil+ }+ }+ return types.JID{}, nil+}++// TestSyncHistorySkipsChatIgnoredByOtherAddress: CHATWOOT_IGNORE_JIDS may name+// a chat by its LID while history stores the phone JID, or the reverse.+// Either form keeps the chat out of the import.+func TestSyncHistorySkipsChatIgnoredByOtherAddress(t *testing.T) {+ prevIgnore := config.ChatwootIgnoreJids+ t.Cleanup(func() { config.ChatwootIgnoreJids = prevIgnore })++ pn := types.NewJID("628111111111", types.DefaultUserServer)+ lid := types.NewJID("111111111111111", types.HiddenUserServer)+ waClient := &whatsmeow.Client{Store: &store.Device{LIDs: syncTestLIDs{pnToLID: map[types.JID]types.JID{pn: lid}}}}++ var requests atomic.Int32+ server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {+ requests.Add(1)+ w.WriteHeader(http.StatusNotFound)+ }))+ defer server.Close()++ for _, tt := range []struct{ stored, ignored types.JID }{{pn, lid}, {lid, pn}} {+ config.ChatwootIgnoreJids = []string{tt.ignored.String()}+ svc := NewSyncService(&Client{BaseURL: server.URL, APIToken: "t", AccountID: 1, InboxID: 2, HTTPClient: server.Client()},+ syncChatsRepo{chats: []*domainChatStorage.Chat{{JID: tt.stored.String()}}})+ progress, err := svc.SyncHistory(context.Background(), "[email protected]", waClient, SyncOptions{DaysLimit: 1})+ if err != nil {+ t.Fatalf("SyncHistory: %v", err)+ }+ if got := requests.Load(); got != 0 || progress.SyncedChats != 0 || progress.FailedChats != 0 {+ t.Errorf("chat %s ignored as %s: Chatwoot got %d requests, synced/failed %d/%d; want it skipped",+ tt.stored, tt.ignored, got, progress.SyncedChats, progress.FailedChats)+ }+ }+}++func TestSyncHistoryWildcardIgnoresOnlyStoredAddress(t *testing.T) {+ prevIgnore := config.ChatwootIgnoreJids+ t.Cleanup(func() { config.ChatwootIgnoreJids = prevIgnore })+ config.ChatwootIgnoreJids = []string{"@lid"}++ pn := types.NewJID("628111111111", types.DefaultUserServer)+ lid := types.NewJID("111111111111111", types.HiddenUserServer)+ waClient := &whatsmeow.Client{Store: &store.Device{LIDs: syncTestLIDs{pnToLID: map[types.JID]types.JID{pn: lid}}}}++ var requests atomic.Int32+ server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {+ requests.Add(1)+ w.WriteHeader(http.StatusNotFound)+ }))+ defer server.Close()++ svc := NewSyncService(&Client{BaseURL: server.URL, APIToken: "t", AccountID: 1, InboxID: 2, HTTPClient: server.Client()},+ syncChatsRepo{chats: []*domainChatStorage.Chat{{JID: pn.String()}}})+ if _, err := svc.SyncHistory(context.Background(), "[email protected]", waClient, SyncOptions{DaysLimit: 1}); err != nil {+ t.Fatalf("SyncHistory: %v", err)+ }+ if requests.Load() == 0 {+ t.Error("@lid skipped a phone-stored chat because of its LID alias")+ }+}diff --git a/src/infrastructure/chatwoot/url_validation_test.go b/src/infrastructure/chatwoot/url_validation_test.goindex 5b3d1968..0299d03e 100644--- a/src/infrastructure/chatwoot/url_validation_test.go+++ b/src/infrastructure/chatwoot/url_validation_test.go@@ -1,7 +1,12 @@package chatwootimport (+ "bytes"+ "compress/gzip"+ "context"+ "errors""fmt"+ "io""net""net/http""net/http/httptest"@@ -100,9 +105,10 @@ func TestValidateChatwootURL_SSRF(t *testing.T) {}}-// TestChatwootClientSSRFGuardWiring verifies per-device clients get the-// connect-time SSRF guard by default, the env client does not, and an explicit-// allowlist disables the guard (the operator opted into trusting those hosts).+// TestChatwootClientSSRFGuardWiring verifies per-device clients keep the+// connect-time guard whether or not an allowlist is set. The env client stays+// unguarded so a private self-host on CHATWOOT_URL keeps working. A stored URL+// that is no longer on the allowlist is not a usable client.func TestChatwootClientSSRFGuardWiring(t *testing.T) {origHosts := config.ChatwootAllowedHostst.Cleanup(func() { config.ChatwootAllowedHosts = origHosts })@@ -116,8 +122,16 @@ func TestChatwootClientSSRFGuardWiring(t *testing.T) {}config.ChatwootAllowedHosts = []string{"x.example.com"}- if c := NewClientFromConfig("https://x.example.com", "t", 1, 1); c.HTTPClient.Transport != nil {- t.Error("per-device client WITH allowlist should not be guarded (allowlist is the control)")+ allowed := NewClientFromConfig("https://x.example.com", "t", 1, 1)+ if allowed.HTTPClient == nil || allowed.HTTPClient.Transport == nil {+ t.Error("per-device client with allowlist should still filter connections")+ }+ if !allowed.IsConfigured() {+ t.Error("allowlisted stored URL should stay usable")+ }+ removed := NewClientFromConfig("https://old.example.net", "t", 1, 1)+ if removed.IsConfigured() {+ t.Error("stored URL removed from the allowlist must not be usable")}// Sanity: the guard transport is a real *http.Transport.@@ -126,6 +140,15 @@ func TestChatwootClientSSRFGuardWiring(t *testing.T) {}}+func getWithContext(t *testing.T, c *http.Client, target string) (*http.Response, error) {+ t.Helper()+ req, err := http.NewRequestWithContext(t.Context(), http.MethodGet, target, nil)+ if err != nil {+ t.Fatal(err)+ }+ return c.Do(req)+}+// TestChatwootClientSSRFGuardBlocksConnect exercises the Dialer.Control guard// end to end: a guarded client must refuse to actually connect to a loopback// address (the DNS-rebinding case a one-time URL validation can't catch),@@ -142,10 +165,14 @@ func TestChatwootClientSSRFGuardBlocksConnect(t *testing.T) {defer srv.Close() // listens on 127.0.0.1// Guarded per-device client: connect to the loopback server must be blocked.+ // It is named by host, since Proxy already refuses the literal IP.guarded := NewClientFromConfig(srv.URL, "t", 1, 1)- if _, err := guarded.HTTPClient.Get(srv.URL); err == nil {+ blockedResp, err := getWithContext(t, guarded.HTTPClient, strings.Replace(srv.URL, "127.0.0.1", "localhost", 1))+ if err == nil {+ blockedResp.Body.Close()t.Fatal("guarded client connected to a loopback address, want block")- } else if !strings.Contains(err.Error(), "disallowed address") {+ }+ if !strings.Contains(err.Error(), "disallowed address") {t.Fatalf("guarded client error = %v, want a disallowed-address block", err)}@@ -171,3 +198,199 @@ func TestValidateChatwootURL_Allowlist(t *testing.T) {t.Error("non-allowlisted host accepted, want rejection")}}++func TestChatwootAllowlistPermitsPrivateHostAndRejectsRedirect(t *testing.T) {+ origHosts := config.ChatwootAllowedHosts+ t.Cleanup(func() { config.ChatwootAllowedHosts = origHosts })+ config.ChatwootAllowedHosts = []string{"127.0.0.1"}++ okSrv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {+ w.WriteHeader(http.StatusOK)+ }))+ defer okSrv.Close()++ allowed := NewClientFromConfig(okSrv.URL, "t", 1, 1)+ resp, err := getWithContext(t, allowed.HTTPClient, okSrv.URL)+ if err != nil {+ t.Fatalf("allowlisted loopback should connect: %v", err)+ }+ resp.Body.Close()++ redirectSrv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {+ http.Redirect(w, r, "http://evil.example/steal", http.StatusFound)+ }))+ defer redirectSrv.Close()++ // CheckRedirect's own error: the transport would refuse the host too, but+ // with another message, so this fails if CheckRedirect is not wired.+ redirected := NewClientFromConfig(redirectSrv.URL, "t", 1, 1)+ redirectResp, err := getWithContext(t, redirected.HTTPClient, redirectSrv.URL+"/v1")+ if err == nil {+ redirectResp.Body.Close()+ }+ if err == nil || !strings.Contains(err.Error(), `redirect host "evil.example" is not in the allowed hosts list`) {+ t.Fatalf("redirect off the allowlist: err=%v", err)+ }+}++// TestChatwootRedirectToAnotherHostDropsToken: the API token is for the+// configured Chatwoot host only. A redirect to another host must not carry+// it, with or without an allowlist.+func TestChatwootRedirectToAnotherHostDropsToken(t *testing.T) {+ origHosts := config.ChatwootAllowedHosts+ t.Cleanup(func() { config.ChatwootAllowedHosts = origHosts })++ tokens := make(chan string, 1)+ target := httptest.NewServer(http.HandlerFunc(func(_ http.ResponseWriter, r *http.Request) {+ tokens <- r.Header.Get("api_access_token")+ }))+ defer target.Close()+ // The same listener under another host name.+ targetURL := strings.Replace(target.URL, "127.0.0.1", "localhost", 1)+ origin := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {+ http.Redirect(w, r, targetURL, http.StatusFound)+ }))+ defer origin.Close()++ for _, tt := range []struct {+ name string+ allowed []string+ client func() *http.Client+ }{+ // The guarded transport refuses loopback without an allowlist, so this+ // case runs the redirect policy on a plain transport.+ {"empty allowlist", nil, func() *http.Client { return &http.Client{CheckRedirect: chatwootCheckRedirect} }},+ {"both hosts allowlisted", []string{"127.0.0.1", "localhost"}, func() *http.Client { return NewClientFromConfig(origin.URL, "t", 1, 1).HTTPClient }},+ } {+ t.Run(tt.name, func(t *testing.T) {+ config.ChatwootAllowedHosts = tt.allowed+ req, err := http.NewRequest(http.MethodGet, origin.URL, nil)+ if err != nil {+ t.Fatal(err)+ }+ req.Header.Set("api_access_token", "secret-token")+ resp, err := tt.client().Do(req)+ if err != nil {+ t.Fatalf("redirect: %v", err)+ }+ resp.Body.Close()+ if got := <-tokens; got != "" {+ t.Fatalf("redirect target received api_access_token %q", got)+ }+ })+ }+}++// TestChatwootAllowlistChecksRequestHostNotDialedAddress: behind+// HTTP(S)_PROXY the dialed address is the proxy, which is not on the+// allowlist. The allowlist applies to the request's destination host.+func TestChatwootAllowlistChecksRequestHostNotDialedAddress(t *testing.T) {+ origHosts := config.ChatwootAllowedHosts+ t.Cleanup(func() { config.ChatwootAllowedHosts = origHosts })+ config.ChatwootAllowedHosts = []string{"chatwoot.example"}++ proxy := httptest.NewServer(http.HandlerFunc(func(http.ResponseWriter, *http.Request) {}))+ defer proxy.Close()++ tr := ssrfGuardedTransport()+ conn, err := tr.DialContext(context.Background(), "tcp", proxy.Listener.Addr().String())+ if err != nil {+ t.Fatalf("dialing a proxy that is not on the allowlist: %v", err)+ }+ conn.Close()++ for host, wantErr := range map[string]bool{"chatwoot.example": false, "evil.example": true} {+ req, err := http.NewRequest(http.MethodGet, "http://"+host+"/api/v1", nil)+ if err != nil {+ t.Fatal(err)+ }+ if _, err := tr.Proxy(req); (err != nil) != wantErr {+ t.Errorf("Proxy(%s) err = %v, want error=%v", host, err, wantErr)+ }+ }+}++// TestChatwootProxyRejectsLiteralPrivateIPWithoutAllowlist: behind+// HTTP(S)_PROXY the dial guard sees only the proxy, so a request or redirect+// to a literal private or metadata IP must fail in Proxy, before the+// environment's proxy is chosen.+func TestChatwootProxyRejectsLiteralPrivateIPWithoutAllowlist(t *testing.T) {+ origHosts := config.ChatwootAllowedHosts+ t.Cleanup(func() { config.ChatwootAllowedHosts = origHosts })+ config.ChatwootAllowedHosts = nil++ tr := ssrfGuardedTransport()+ for target, wantErr := range map[string]bool{+ "http://169.254.169.254/latest/meta-data/": true,+ "http://[fd00::1]/api/v1": true,+ "http://203.0.113.10/api/v1": false,+ "http://chatwoot.example/api/v1": false,+ } {+ req, err := http.NewRequest(http.MethodGet, target, nil)+ if err != nil {+ t.Fatal(err)+ }+ if _, err := tr.Proxy(req); (err != nil) != wantErr {+ t.Errorf("Proxy(%s) err = %v, want error=%v", target, err, wantErr)+ }+ }+}++// TestPerDeviceClientCapsDecompressedBody: a small gzip body from a+// per-device URL must not expand past maxChatwootResponseBody when read.+func TestPerDeviceClientCapsDecompressedBody(t *testing.T) {+ origHosts := config.ChatwootAllowedHosts+ t.Cleanup(func() { config.ChatwootAllowedHosts = origHosts })+ config.ChatwootAllowedHosts = []string{"127.0.0.1"}++ var compressed bytes.Buffer+ zw := gzip.NewWriter(&compressed)+ if _, err := zw.Write(make([]byte, maxChatwootResponseBody+1)); err != nil {+ t.Fatal(err)+ }+ if err := zw.Close(); err != nil {+ t.Fatal(err)+ }+ srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {+ w.Header().Set("Content-Encoding", "gzip")+ _, _ = w.Write(compressed.Bytes())+ }))+ defer srv.Close()++ resp, err := getWithContext(t, NewClientFromConfig(srv.URL, "t", 1, 1).HTTPClient, srv.URL)+ if err != nil {+ t.Fatalf("get: %v", err)+ }+ defer resp.Body.Close()+ var tooLarge *http.MaxBytesError+ if _, err := io.Copy(io.Discard, resp.Body); !errors.As(err, &tooLarge) {+ t.Fatalf("read err = %v, want the %d-byte response cap", err, maxChatwootResponseBody)+ }+}++func TestFindContactByIdentifierCapsErrorBody(t *testing.T) {+ const huge = 70 << 10+ srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {+ w.WriteHeader(http.StatusInternalServerError)+ _, _ = w.Write([]byte(strings.Repeat("A", huge)))+ }))+ defer srv.Close()++ c := &Client{+ BaseURL: srv.URL,+ APIToken: "t",+ AccountID: 1,+ InboxID: 1,+ HTTPClient: srv.Client(),+ }+ _, err := c.FindContactByIdentifier("628123456789", false)+ if err == nil {+ t.Fatal("expected search error")+ }+ if strings.Contains(err.Error(), strings.Repeat("A", 1024)) {+ t.Fatal("error included a large slice of the response body")+ }+ if !strings.Contains(err.Error(), "exceeds") {+ t.Fatalf("error = %v, want the size cap", err)+ }+}diff --git a/src/infrastructure/whatsapp/event_delete.go b/src/infrastructure/whatsapp/event_delete.goindex efd38d33..adcec111 100644--- a/src/infrastructure/whatsapp/event_delete.go+++ b/src/infrastructure/whatsapp/event_delete.go@@ -6,6 +6,7 @@ import (domainChatStorage "github.com/aldinokemal/go-whatsapp-web-multidevice/domains/chatstorage""go.mau.fi/whatsmeow"+ "go.mau.fi/whatsmeow/types""go.mau.fi/whatsmeow/types/events")@@ -31,6 +32,9 @@ func createDeletePayload(ctx context.Context, evt *events.DeleteForMe, message *normalizedSenderJID := NormalizeJIDFromLID(ctx, evt.SenderJID, client)payload["from"] = normalizedSenderJID.ToNonAD().String()addSenderDisplayName(ctx, client, payload, false, "")+ // The stored chat is often the phone. Keep the event's original LID and+ // any alt so an ignore entry for that LID still matches.+ addChatwootIdentityAliases(payload, evt.ChatJID, evt.SenderJID, types.EmptyJID, types.EmptyJID)// Include original message information if availableif message != nil {diff --git a/src/infrastructure/whatsapp/event_receipt.go b/src/infrastructure/whatsapp/event_receipt.goindex e6a96920..223f673c 100644--- a/src/infrastructure/whatsapp/event_receipt.go+++ b/src/infrastructure/whatsapp/event_receipt.go@@ -44,19 +44,26 @@ func createReceiptPayload(ctx context.Context, evt *events.Receipt, deviceID strpayload["ids"] = evt.MessageIDs}- // Add chat_id- payload["chat_id"] = evt.Chat.ToNonAD().String()+ // Add chat_id. A LID chat keeps its original id beside the phone it resolves to.+ chatJID := evt.Chat.ToNonAD()+ if chatJID.Server == types.HiddenUserServer {+ payload["chat_lid"] = chatJID.String()+ chatJID = NormalizeJIDFromLID(ctx, chatJID, client).ToNonAD()+ }+ payload["chat_id"] = chatJID.String()- // Build from/from_lid fields from sender+ // Build from/from_lid fields from sender. SenderAlt and RecipientAlt carry+ // the other address when the primary JID was already normalized to a phone.senderJID := evt.Sender- if senderJID.Server == "lid" {+ if senderJID.Server == types.HiddenUserServer {payload["from_lid"] = senderJID.ToNonAD().String()}// Resolve sender JID (convert LID to phone number if needed)normalizedSenderJID := NormalizeJIDFromLID(ctx, senderJID, client)payload["from"] = normalizedSenderJID.ToNonAD().String()+ addChatwootIdentityAliases(payload, evt.Chat, senderJID, evt.SenderAlt, evt.RecipientAlt)addSenderDisplayName(ctx, client, payload, false, "")// Receipt typediff --git a/src/infrastructure/whatsapp/webhook_forward.go b/src/infrastructure/whatsapp/webhook_forward.goindex 54c4731d..53bd6839 100644--- a/src/infrastructure/whatsapp/webhook_forward.go+++ b/src/infrastructure/whatsapp/webhook_forward.go@@ -3,11 +3,14 @@ package whatsappimport ("context""encoding/json"+ "errors""fmt""hash/fnv"+ "maps""slices""strings""sync"+ "sync/atomic""time""github.com/aldinokemal/go-whatsapp-web-multidevice/config"@@ -162,7 +165,13 @@ func getContactMutex(phone string) *sync.Mutex {// successful targets still receive the event.func forwardPayloadToConfiguredWebhooks(ctx context.Context, payload map[string]any, eventName string) error {deviceJID, _ := payload["device_id"].(string)- webhookConfig, err := getWebhookConfigForDevice(deviceJID)+ webhookConfig, err := webhookConfigForPayload(ctx, payload)+ if errors.Is(err, errAmbiguousWebhookDevice) {+ // Sibling companion slots share the bare account JID. Delivering with the+ // global policy would replace the originating slot's event filter.+ logrus.Warnf("Skipping event %s: %v (device_id=%s)", eventName, err, deviceJID)+ return nil+ }if err != nil {// A config lookup failure is not a delivery failure: fall back to the global// webhook config so the event still reaches the global targets and Chatwoot.@@ -272,6 +281,75 @@ func getDeviceRecordForTest(deviceJID string) (*domainChatStorage.DeviceRecord,return nil, nil}+// errAmbiguousWebhookDevice means the event's account JID is shared by more+// than one companion slot and the originating slot could not be selected.+var errAmbiguousWebhookDevice = errors.New("webhook device identity is ambiguous across companion slots")++// webhookConfigForPayload selects webhook policy for the originating device+// slot. payload["device_id"] stays the public account JID; policy uses the+// companion AD JID from the device context when that slot is known. A bare+// account JID that matches several in-memory slots does not fall back to the+// global filter.+func webhookConfigForPayload(ctx context.Context, payload map[string]any) (*domainChatStorage.DeviceWebhookConfig, error) {+ payloadID, _ := payload["device_id"].(string)+ if inst, ok := DeviceFromContext(ctx); ok && inst != nil {+ ad := strings.TrimSpace(inst.ADJID())+ if ad != "" && ad != payloadID {+ rec, err := getDeviceRecordForTest(ad)+ if err != nil {+ return nil, err+ }+ if rec != nil {+ return webhookConfigFromRecord(rec), nil+ }+ bare := inst.JID()+ if bare == "" {+ bare = payloadID+ }+ if siblingCompanionCount(bare) > 1 {+ return nil, errAmbiguousWebhookDevice+ }+ }+ }+ if siblingCompanionCount(payloadID) > 1 {+ return nil, errAmbiguousWebhookDevice+ }+ return getWebhookConfigForDevice(payloadID)+}++// siblingCompanionCount reports how many registered slots share a bare account+// JID. Zero means the manager is absent or the id is not a shared account JID.+func siblingCompanionCount(bareJID string) int {+ bareJID = strings.TrimSpace(bareJID)+ if bareJID == "" || !strings.Contains(bareJID, "@") {+ return 0+ }+ dm := GetDeviceManager()+ if dm == nil {+ return 0+ }+ n := 0+ for _, inst := range dm.ListDevices() {+ if inst != nil && inst.JID() == bareJID {+ n+++ }+ }+ return n+}++func webhookConfigFromRecord(record *domainChatStorage.DeviceRecord) *domainChatStorage.DeviceWebhookConfig {+ if record == nil || record.WebhookURL == nil || *record.WebhookURL == "" {+ return nil+ }+ logrus.Debugf("Using device-specific webhook config for %s", record.DeviceID)+ return &domainChatStorage.DeviceWebhookConfig{+ WebhookURL: record.WebhookURL,+ WebhookSecret: record.WebhookSecret,+ WebhookEvents: record.WebhookEvents,+ WebhookInsecureSkipVerify: record.WebhookInsecureSkipVerify,+ }+}+// getWebhookConfigForDevice returns the webhook configuration to use for a given device.// If the device has a custom webhook config, it returns that config.// Otherwise, it returns nil (caller should use global config).@@ -284,17 +362,7 @@ func getWebhookConfigForDevice(deviceJID string) (*domainChatStorage.DeviceWebhoif err != nil {return nil, fmt.Errorf("failed to get device record: %w", err)}- if record != nil && record.WebhookURL != nil && *record.WebhookURL != "" {- logrus.Debugf("Using device-specific webhook config for %s", deviceJID)- return &domainChatStorage.DeviceWebhookConfig{- WebhookURL: record.WebhookURL,- WebhookSecret: record.WebhookSecret,- WebhookEvents: record.WebhookEvents,- WebhookInsecureSkipVerify: record.WebhookInsecureSkipVerify,- }, nil- }-- return nil, nil+ return webhookConfigFromRecord(record), nil}// getWebhookURLsFromConfig extracts webhook URLs from the config.@@ -355,7 +423,7 @@ func shouldIgnoreWebhookJID(payload map[string]any) bool {if !ok {return false}- for _, key := range []string{"chat_id", "from", "chat_lid", "from_lid"} {+ for _, key := range payloadIdentityKeys {if jid, _ := data[key].(string); utils.MatchesIgnoredJID(jid, ignore) {return true}@@ -487,8 +555,11 @@ func extractChatwootContactInfo(ctx context.Context, data map[string]any) (*chat// Operator-configured ignore list (CHATWOOT_IGNORE_JIDS) on top of the// always-ignored system JIDs — supports exact JIDs and the "@g.us" /- // "@s.whatsapp.net" / "@lid" address-space wildcards.- if utils.MatchesIgnoredJID(chatID, config.ChatwootIgnoreJids) || utils.MatchesIgnoredJID(from, config.ChatwootIgnoreJids) {+ // "@s.whatsapp.net" / "@lid" address-space wildcards. Phone-normalized+ // chat_id/from are not enough: a resolved LID keeps its original id in+ // chat_lid/from_lid, and an exclusion written against that alias must+ // still match.+ if chatwootPayloadExcluded(data) {return nil, fmt.Errorf("skipping ignored JID chat=%s from=%s", chatID, from)}@@ -1017,7 +1088,278 @@ func deleteTargetMessageID(eventName string, data map[string]any) string {return ""}-func syncReadReceiptsToChatwoot(cw *chatwoot.Client, deviceID string, linkRepo domainChatStorage.IChatStorageRepository, data map[string]any) {+// payloadIdentityKeys are the original and normalized JIDs a webhook event can+// carry. An exclusion configured against a LID must still match after that LID+// is resolved to a phone JID and stored beside it. The first two are the+// addresses the event is delivered under; the rest are aliases.+var payloadIdentityKeys = []string{"chat_id", "from", "chat_lid", "from_lid", "sender_alt", "recipient_alt"}++// addChatwootIdentityAliases copies original LID chats and alt JIDs onto a+// webhook payload. chat_id/from may already be the phone; exclusion still has+// to see 111@lid when that is only the original chat or an alt address.+func addChatwootIdentityAliases(payload map[string]any, chat, sender, senderAlt, recipientAlt types.JID) {+ if payload == nil {+ return+ }+ setLID := func(key string, jid types.JID) {+ if jid.IsEmpty() || jid.Server != types.HiddenUserServer {+ return+ }+ if _, exists := payload[key]; exists {+ return+ }+ payload[key] = jid.ToNonAD().String()+ }+ setLID("chat_lid", chat)+ setLID("from_lid", sender)+ if !senderAlt.IsEmpty() {+ payload["sender_alt"] = senderAlt.ToNonAD().String()+ setLID("from_lid", senderAlt)+ }+ if !recipientAlt.IsEmpty() {+ payload["recipient_alt"] = recipientAlt.ToNonAD().String()+ // In a 1:1 chat the recipient alt is the chat's other address.+ setLID("chat_lid", recipientAlt)+ }+}++func chatwootPayloadExcluded(data map[string]any) bool {+ if len(config.ChatwootIgnoreJids) == 0 || data == nil {+ return false+ }+ for i, key := range payloadIdentityKeys {+ jid, _ := data[key].(string)+ // Wildcards such as "@lid" apply to chat_id and from, as before the+ // aliases were added; an alias matches exact entries only.+ if i < 2 && utils.MatchesIgnoredJID(jid, config.ChatwootIgnoreJids) ||+ i >= 2 && utils.MatchesIgnoredAliasJID(jid, config.ChatwootIgnoreJids) {+ return true+ }+ }+ return false+}++func chatwootJIDExcluded(jid string) bool {+ return utils.MatchesIgnoredJID(jid, config.ChatwootIgnoreJids)+}++// MessageAuthorMatches reports whether an edit or revoke was sent by the stored+// message's author. whatsmeow sets IsFromMe from the authenticated account, so+// the account may rewrite its own messages even when companion devices differ+// in the sender string. Otherwise the event sender — or the pre-normalization+// alias, when one was kept — must equal the stored sender.+func MessageAuthorMatches(storedSender string, storedFromMe bool, eventSender, eventAlias string, eventFromMe bool) bool {+ if storedFromMe && eventFromMe {+ return true+ }+ storedSender = strings.TrimSpace(storedSender)+ if storedSender == "" {+ return false+ }+ for _, candidate := range []string{eventSender, eventAlias} {+ if s := strings.TrimSpace(candidate); s != "" && s == storedSender {+ return true+ }+ }+ return false+}++// IsGroupAdmin reports whether any of one user's addresses (LID or phone) is+// currently an admin of group, asking WhatsApp as client. A failed lookup is+// not an admin.+func IsGroupAdmin(ctx context.Context, client *whatsmeow.Client, group types.JID, user ...types.JID) bool {+ if client == nil {+ return false+ }+ lookupCtx, cancel := context.WithTimeout(ctx, 10*time.Second)+ defer cancel()+ info, err := fetchGroupInfoFn(lookupCtx, client, group)+ if err != nil || info == nil {+ logrus.Warnf("Could not load admins of group %s: %v", group, err)+ return false+ }+ for _, p := range info.Participants {+ if !p.IsAdmin && !p.IsSuperAdmin {+ continue+ }+ for _, u := range user {+ u = u.ToNonAD()+ if !u.IsEmpty() && (u == p.JID.ToNonAD() || u == p.LID.ToNonAD() || u == p.PhoneNumber.ToNonAD()) {+ return true+ }+ }+ }+ return false+}++type revokeAuthRecord struct {+ authorized bool+ expires time.Time+}++// authNotesSweptAt is when expired decisions were last swept, in Unix nanoseconds.+var authNotesSweptAt atomic.Int64++// sweepAuthNotes drops expired decisions at most every five minutes. A read+// removes only the expired entry it looks up.+func sweepAuthNotes() {+ now := time.Now()+ last := authNotesSweptAt.Load()+ if now.UnixNano()-last < int64(5*time.Minute) || !authNotesSweptAt.CompareAndSwap(last, now.UnixNano()) {+ return+ }+ dropAuthNotes(func(_ string, rec revokeAuthRecord) bool { return now.After(rec.expires) })+}++// ForgetMessageAuthorizationsForTest drops every decision noted for deviceID,+// so tests in other packages can clean up the decisions CreateMessage records.+func ForgetMessageAuthorizationsForTest(deviceID string) {+ dropAuthNotes(func(key string, _ revokeAuthRecord) bool { return strings.HasPrefix(key, deviceID+"\n") })+}++func dropAuthNotes(drop func(key string, rec revokeAuthRecord) bool) {+ for _, notes := range []*sync.Map{&revokeAuthNotes, &messageEventAuthNotes} {+ notes.Range(func(key, value any) bool {+ k, _ := key.(string)+ if rec, _ := value.(revokeAuthRecord); drop(k, rec) {+ notes.CompareAndDelete(key, value)+ }+ return true+ })+ }+}++var revokeAuthNotes sync.Map++func revokeAuthKey(deviceID, chatJID, messageID string) string {+ return deviceID + "\n" + chatJID + "\n" + messageID+}++// NoteMessageRevokeAuthorization remembers whether a revoke was authorized+// against the stored author. Chatwoot forwarding runs after that row is+// deleted and would otherwise be unable to tell a real revoke from a forged one.+// A later missing-row or unauthorized attempt must not clear an authorization+// already recorded for this message: the forwarder may not have read it yet.+// Only Chatwoot forwarding reads it, so nothing is kept while Chatwoot is off.+func NoteMessageRevokeAuthorization(deviceID, chatJID, messageID string, authorized bool) {+ deviceID = strings.TrimSpace(deviceID)+ messageID = strings.TrimSpace(messageID)+ if !config.ChatwootEnabled || deviceID == "" || messageID == "" {+ return+ }+ if !authorized {+ if prev, ok := MessageRevokeAuthorized(deviceID, chatJID, messageID); ok && prev {+ return+ }+ }+ sweepAuthNotes()+ revokeAuthNotes.Store(revokeAuthKey(deviceID, chatJID, messageID), revokeAuthRecord{+ authorized: authorized,+ expires: time.Now().Add(24 * time.Hour),+ })+}++var messageEventAuthNotes sync.Map++func messageEventAuthKey(deviceID, eventID string) string {+ return deviceID + "\n" + eventID+}++// NoteMessageEventAuthorization records whether this protocol event was applied.+// Chatwoot forwarding is asynchronous and keys off the event id in the payload,+// so an unauthorized edit or revoke can be skipped without erasing an earlier+// authorization of the same target message.+func NoteMessageEventAuthorization(deviceID, eventID string, authorized bool) {+ deviceID = strings.TrimSpace(deviceID)+ eventID = strings.TrimSpace(eventID)+ if !config.ChatwootEnabled || deviceID == "" || eventID == "" {+ return+ }+ sweepAuthNotes()+ messageEventAuthNotes.Store(messageEventAuthKey(deviceID, eventID), revokeAuthRecord{+ authorized: authorized,+ expires: time.Now().Add(24 * time.Hour),+ })+}++// MessageEventAuthorized reports the decision recorded for one protocol event.+func MessageEventAuthorized(deviceID, eventID string) (authorized bool, ok bool) {+ key := messageEventAuthKey(strings.TrimSpace(deviceID), strings.TrimSpace(eventID))+ v, found := messageEventAuthNotes.Load(key)+ if !found {+ return false, false+ }+ rec, _ := v.(revokeAuthRecord)+ if time.Now().After(rec.expires) {+ messageEventAuthNotes.Delete(key)+ return false, false+ }+ return rec.authorized, true+}++// chatwootEventDenied reports whether an edit or revoke must not reach+// Chatwoot. Without a recorded decision (storage failed or never saw the+// event) only this account's own event passes: it may edit or revoke+// anything it sent.+func chatwootEventDenied(deviceID string, data map[string]any) bool {+ eventID, _ := data["id"].(string)+ authorized, ok := MessageEventAuthorized(deviceID, eventID)+ if !ok {+ isFromMe, _ := data["is_from_me"].(bool)+ return !isFromMe+ }+ return !authorized+}++// MessageRevokeAuthorized reports a previously recorded revoke decision.+func MessageRevokeAuthorized(deviceID, chatJID, messageID string) (authorized bool, ok bool) {+ key := revokeAuthKey(strings.TrimSpace(deviceID), chatJID, strings.TrimSpace(messageID))+ v, found := revokeAuthNotes.Load(key)+ if !found {+ return false, false+ }+ rec, _ := v.(revokeAuthRecord)+ if time.Now().After(rec.expires) {+ revokeAuthNotes.Delete(key)+ return false, false+ }+ return rec.authorized, true+}++func chatwootEventChatMatches(data map[string]any, chatJID string) bool {+ chatJID = strings.TrimSpace(chatJID)+ if chatJID == "" || data == nil {+ return false+ }+ for _, key := range []string{"chat_id", "chat_lid", "revoked_chat"} {+ if v, _ := data[key].(string); strings.TrimSpace(v) == chatJID {+ return true+ }+ }+ return false+}++func chatwootRevokeAuthorized(deviceID string, linkRepo domainChatStorage.IChatStorageRepository, data map[string]any, link *domainChatStorage.ChatwootMessageLink, targetID string) bool {+ if link == nil || !chatwootEventChatMatches(data, link.WhatsAppChatJID) {+ return false+ }+ if authorized, ok := MessageRevokeAuthorized(deviceID, link.WhatsAppChatJID, targetID); ok {+ return authorized+ }+ if linkRepo == nil {+ return false+ }+ msg, err := linkRepo.GetMessageByIDChatAndDevice(deviceID, link.WhatsAppChatJID, targetID)+ if err != nil || msg == nil {+ return false+ }+ from, _ := data["from"].(string)+ alias, _ := data["from_lid"].(string)+ isFromMe, _ := data["is_from_me"].(bool)+ return MessageAuthorMatches(msg.Sender, msg.IsFromMe, from, alias, isFromMe)+}++func syncReadReceiptsToChatwoot(cw *chatwoot.Client, deviceID string, linkRepo domainChatStorage.IChatStorageRepository, configID int64, data map[string]any) {receiptType, _ := data["receipt_type"].(string)if receiptType != string(types.ReceiptTypeRead) && receiptType != string(types.ReceiptTypeReadSelf) {return@@ -1026,6 +1368,10 @@ func syncReadReceiptsToChatwoot(cw *chatwoot.Client, deviceID string, linkRepo dlogrus.Warn("Chatwoot: Cannot sync read receipt without message-link storage")return}+ if chatwootPayloadExcluded(data) {+ logrus.Debugf("Chatwoot: skipping read receipt for excluded chat")+ return+ }for _, messageID := range extractReceiptMessageIDs(data) {link, err := linkRepo.GetChatwootMessageLinkByWhatsAppID(deviceID, messageID)@@ -1036,10 +1382,14 @@ func syncReadReceiptsToChatwoot(cw *chatwoot.Client, deviceID string, linkRepo dif link == nil || link.ChatwootConversationID == 0 {continue}- if !chatwootLinkMatchesClient(link, cw) {- // The link was written under a different Chatwoot account (e.g. before- // a delete-and-recreate rebind): its conversation id means nothing on- // the current destination.+ if !chatwootLinkMatchesClient(link, cw, configID) {+ // The link was written under a different Chatwoot account or server+ // (e.g. before a delete-and-recreate rebind): its conversation id+ // means nothing on the current destination.+ continue+ }+ if chatwootJIDExcluded(link.WhatsAppChatJID) {+ logrus.Debugf("Chatwoot: skipping read receipt for excluded chat %s", link.WhatsAppChatJID)continue}@@ -1062,10 +1412,14 @@ func syncReadReceiptsToChatwoot(cw *chatwoot.Client, deviceID string, linkRepo d}}-func deleteLinkedChatwootMessage(cw *chatwoot.Client, deviceID string, linkRepo domainChatStorage.IChatStorageRepository, eventName string, data map[string]any) bool {+func deleteLinkedChatwootMessage(cw *chatwoot.Client, deviceID string, linkRepo domainChatStorage.IChatStorageRepository, configID int64, eventName string, data map[string]any) bool {if !config.ChatwootMessageDelete || deviceID == "" || linkRepo == nil {return false}+ if chatwootPayloadExcluded(data) {+ logrus.Debugf("Chatwoot: skipping linked delete for excluded chat")+ return false+ }targetID := deleteTargetMessageID(eventName, data)if targetID == "" {@@ -1080,9 +1434,17 @@ func deleteLinkedChatwootMessage(cw *chatwoot.Client, deviceID string, linkRepoif link == nil || link.ChatwootConversationID == 0 || link.ChatwootMessageID == 0 {return false}- if !chatwootLinkMatchesClient(link, cw) {- // Cross-account link (pre-rebind): the (conversation, message) ids would- // address an unrelated message on the current destination.+ if !chatwootLinkMatchesClient(link, cw, configID) {+ // Cross-account or cross-server link (pre-rebind): the (conversation,+ // message) ids would address an unrelated message on the current destination.+ return false+ }+ if chatwootJIDExcluded(link.WhatsAppChatJID) {+ logrus.Debugf("Chatwoot: skipping linked delete for excluded chat %s", link.WhatsAppChatJID)+ return false+ }+ if eventName == "message.revoked" && !chatwootRevokeAuthorized(deviceID, linkRepo, data, link, targetID) {+ logrus.Warnf("Chatwoot: not deleting linked message %s; revoke is not authorized", targetID)return false}@@ -1094,14 +1456,20 @@ func deleteLinkedChatwootMessage(cw *chatwoot.Client, deviceID string, linkRepo}// chatwootLinkMatchesClient reports whether a stored message link belongs to-// the Chatwoot account the client is bound to. Links with account id 0-// (pre-migration legacy rows not yet backfilled) are accepted for-// compatibility; any other mismatch means the link predates a rebind and its-// Chatwoot ids must not be replayed against the current destination.-func chatwootLinkMatchesClient(link *domainChatStorage.ChatwootMessageLink, cw *chatwoot.Client) bool {+// the Chatwoot destination the client is bound to. Account numbers collide+// across servers, so a per-device client (configID != 0) must match the link's+// configuration id. The legacy env client (configID 0) accepts only legacy+// links, and then only when the account id matches or was never backfilled.+func chatwootLinkMatchesClient(link *domainChatStorage.ChatwootMessageLink, cw *chatwoot.Client, configID int64) bool {if link == nil || cw == nil {return false}+ if configID != 0 {+ return link.ChatwootConfigID == configID+ }+ if link.ChatwootConfigID != 0 {+ return false+ }return link.ChatwootAccountID == 0 || link.ChatwootAccountID == cw.AccountID}@@ -1154,6 +1522,9 @@ func isRetryableChatwootForwardEvent(eventName string) bool {}}+// queuedAuthorizationKey carries an edit or revoke decision in a queued payload.+const queuedAuthorizationKey = "chatwoot_authorized"+func enqueueChatwootForwardRetry(linkRepo domainChatStorage.IChatStorageRepository, deviceID, eventName string, payload map[string]any, syncErr error) bool {if !isRetryableChatwootForwardEvent(eventName) || linkRepo == nil || strings.TrimSpace(deviceID) == "" || !chatwoot.Retryable(syncErr) {return false@@ -1164,6 +1535,16 @@ func enqueueChatwootForwardRetry(linkRepo domainChatStorage.IChatStorageRepositoreturn false}+ // Edit and revoke decisions live in memory. Queue this one with the event,+ // on a copy so the live map is not changed. It follows the live rule, so this+ // account's own event without a recorded decision stays authorized.+ if eventName == "message.edited" || eventName == "message.revoked" {+ data, _ := payload["payload"].(map[string]any)+ authorized := !chatwootEventDenied(deviceID, data)+ payload = maps.Clone(payload)+ payload[queuedAuthorizationKey] = authorized+ }+payloadJSON, err := json.Marshal(payload)if err != nil {logrus.Errorf("Chatwoot: Failed to serialize retry payload for %s: %v", messageID, err)@@ -1211,12 +1592,34 @@ func syncPayloadToChatwoot(ctx context.Context, payload map[string]any, eventNamreturn nil}+ // An unauthorized edit or revoke is a storage no-op. Do not post the+ // "Edited" or "This message was deleted" note, and do not hard-delete.+ if (eventName == "message.edited" || eventName == "message.revoked") && chatwootEventDenied(deviceID, data) {+ logrus.Warnf("Chatwoot: skipping %s; sender is not the author", eventName)+ return nil+ }+ // Exclusion covers the normalized phone and every original or alt LID+ // carried on the payload. It runs before read receipts, hard deletes, and+ // tombstone notes.+ if chatwootPayloadExcluded(data) {+ logrus.Debugf("Chatwoot: skipping %s for excluded chat", eventName)+ return nil+ }+switch eventName {case "message.ack":- syncReadReceiptsToChatwoot(cw, deviceID, linkRepo, data)+ syncReadReceiptsToChatwoot(cw, deviceID, linkRepo, resolved.ConfigID, data)return nilcase "message.revoked", "message.deleted":- if deleteLinkedChatwootMessage(cw, deviceID, linkRepo, eventName, data) {+ // The stored chat may be excluded under an address this payload does not+ // carry (LID vs phone). Then skip both the hard delete and the tombstone.+ if targetID := deleteTargetMessageID(eventName, data); targetID != "" && linkRepo != nil {+ if link, err := linkRepo.GetChatwootMessageLinkByWhatsAppID(deviceID, targetID); err == nil && link != nil && chatwootJIDExcluded(link.WhatsAppChatJID) {+ logrus.Debugf("Chatwoot: skipping %s for excluded chat %s", eventName, link.WhatsAppChatJID)+ return nil+ }+ }+ if deleteLinkedChatwootMessage(cw, deviceID, linkRepo, resolved.ConfigID, eventName, data) {return nil}// The hard delete was attempted (or there was no link to delete). The@@ -1322,9 +1725,28 @@ func processChatwootForwardRetryEvent(repo domainChatStorage.IChatStorageReposit// fall back to the global default device — the wrong client in multi-device// deployments.ctx := context.Background()- if dm := GetDeviceManager(); dm != nil {- if instance, _, err := dm.ResolveDevice(event.DeviceID); err == nil && instance != nil {- ctx = ContextWithDevice(ctx, instance)+ dm := GetDeviceManager()+ if dm == nil {+ return fmt.Errorf("chatwoot retry: device manager unavailable, not replaying %s for device %s", event.EventName, event.DeviceID)+ }+ instance, _, err := dm.ResolveDevice(event.DeviceID)+ if err != nil || instance == nil {+ if err == nil {+ err = errors.New("device not found")+ }+ return fmt.Errorf("chatwoot retry: device %s is not available: %w", event.DeviceID, err)+ }+ ctx = ContextWithDevice(ctx, instance)+ if event.EventName == "message.edited" || event.EventName == "message.revoked" {+ // The in-memory decision may be gone after a restart or its TTL. Restore+ // the one queued with the event; a queued edit or revoke without one is denied.+ authorized, _ := payload[queuedAuthorizationKey].(bool)+ data, _ := payload["payload"].(map[string]any)+ eventID, _ := data["id"].(string)+ NoteMessageEventAuthorization(event.DeviceID, eventID, authorized)+ if event.EventName == "message.revoked" {+ chatJID, _ := data["chat_id"].(string)+ NoteMessageRevokeAuthorization(event.DeviceID, chatJID, deleteTargetMessageID(event.EventName, data), authorized)}}return syncPayloadToChatwoot(ctx, payload, event.EventName, event.DeviceID, repo)diff --git a/src/infrastructure/whatsapp/webhook_forward_authz_test.go b/src/infrastructure/whatsapp/webhook_forward_authz_test.gonew file mode 100644index 00000000..5ee78a95--- /dev/null+++ b/src/infrastructure/whatsapp/webhook_forward_authz_test.go@@ -0,0 +1,760 @@+package whatsapp++import (+ "context"+ "errors"+ "net/http"+ "net/http/httptest"+ "strings"+ "testing"+ "time"++ "github.com/aldinokemal/go-whatsapp-web-multidevice/config"+ "github.com/aldinokemal/go-whatsapp-web-multidevice/domains/chatstorage"+ "github.com/aldinokemal/go-whatsapp-web-multidevice/infrastructure/chatwoot"+ "go.mau.fi/whatsmeow"+ "go.mau.fi/whatsmeow/store"+ "go.mau.fi/whatsmeow/types"+ "go.mau.fi/whatsmeow/types/events"+)++func companionInstance(slot, user string, device uint8) *DeviceInstance {+ jid := types.NewADJID(user, 0, device)+ return NewDeviceInstance(slot, &whatsmeow.Client{Store: &store.Device{ID: &jid}}, nil)+}++func TestWebhookPolicyUsesCompanionSlot(t *testing.T) {+ origHooks := config.WhatsappWebhook+ origEvents := config.WhatsappWebhookEvents+ origStorage := webhookStorageForTest+ origSubmit := submitWebhookFn+ t.Cleanup(func() {+ config.WhatsappWebhook = origHooks+ config.WhatsappWebhookEvents = origEvents+ webhookStorageForTest = origStorage+ submitWebhookFn = origSubmit+ })++ slot := companionInstance("slot-a", "6281777000021", 28)+ bare := slot.JID()+ ad := slot.ADJID()+ slotURL := "https://slot.example/hook"+ config.WhatsappWebhook = []string{"https://global.example/hook"}+ config.WhatsappWebhookEvents = nil+ webhookStorageForTest = func(key string) (*chatstorage.DeviceRecord, error) {+ if key != ad {+ return nil, nil+ }+ return &chatstorage.DeviceRecord{+ DeviceID: "slot-a",+ JID: bare,+ ADJID: ad,+ WebhookURL: &slotURL,+ WebhookEvents: "message",+ }, nil+ }++ var urls []string+ submitWebhookFn = func(_ context.Context, _ map[string]any, url string, _ *chatstorage.DeviceWebhookConfig) error {+ urls = append(urls, url)+ return nil+ }++ ctx := ContextWithDevice(context.Background(), slot)+ payload := map[string]any{"device_id": bare, "payload": map[string]any{}}++ if err := forwardPayloadToConfiguredWebhooks(ctx, payload, "newsletter.joined"); err != nil {+ t.Fatalf("forward: %v", err)+ }+ if len(urls) != 0 {+ t.Fatalf("slot policy excludes newsletter.joined, delivered to %v", urls)+ }++ urls = nil+ if err := forwardPayloadToConfiguredWebhooks(ctx, payload, "message"); err != nil {+ t.Fatalf("forward message: %v", err)+ }+ if len(urls) != 1 || urls[0] != slotURL {+ t.Fatalf("message delivered to %v, want slot webhook", urls)+ }+}++func TestWebhookPolicyStopsWhenBareJIDIsAmbiguous(t *testing.T) {+ origHooks := config.WhatsappWebhook+ origDM := deviceManager+ origStorage := webhookStorageForTest+ origSubmit := submitWebhookFn+ t.Cleanup(func() {+ config.WhatsappWebhook = origHooks+ deviceManager = origDM+ webhookStorageForTest = origStorage+ submitWebhookFn = origSubmit+ })++ config.WhatsappWebhook = []string{"https://global.example/hook"}+ deviceManager = NewDeviceManager(nil, nil, nil)+ slotA := companionInstance("slot-a", "6281777000021", 28)+ deviceManager.AddDevice(slotA)+ deviceManager.AddDevice(companionInstance("slot-b", "6281777000021", 32))+ webhookStorageForTest = func(string) (*chatstorage.DeviceRecord, error) { return nil, nil }++ called := false+ submitWebhookFn = func(context.Context, map[string]any, string, *chatstorage.DeviceWebhookConfig) error {+ called = true+ return nil+ }++ err := forwardPayloadToConfiguredWebhooks(context.Background(), map[string]any{+ "device_id": slotA.JID(),+ "payload": map[string]any{},+ }, "newsletter.joined")+ if err != nil {+ t.Fatalf("ambiguous delivery should skip, not fail the caller: %v", err)+ }+ if called {+ t.Fatal("ambiguous bare account JID used the global webhook policy")+ }+}++func TestRetryFailsWhenQueuedDeviceIsGone(t *testing.T) {+ origDM := deviceManager+ origName := contactDisplayNameFn+ t.Cleanup(func() {+ deviceManager = origDM+ contactDisplayNameFn = origName+ })+ deviceManager = NewDeviceManager(nil, nil, nil)+ deviceManager.AddDevice(companionInstance("other", "6281999999999", 4))++ called := false+ contactDisplayNameFn = func(context.Context, string) string {+ called = true+ return "from the other account"+ }++ err := processChatwootForwardRetryEvent(&chatwootForwardQueueTestRepo{}, &chatstorage.ChatwootForwardEvent{+ ID: 1,+ DeviceID: "missing-slot",+ EventName: "message",+ PayloadJSON: `{"payload":{"id":"m1","from":"[email protected]","chat_id":"[email protected]","body":"hi"}}`,+ })+ if err == nil {+ t.Fatal("retry should fail when the queued device cannot be restored")+ }+ if called {+ t.Fatal("retry read a contact name without the queued device")+ }++ deviceManager = nil+ if err := processChatwootForwardRetryEvent(&chatwootForwardQueueTestRepo{}, &chatstorage.ChatwootForwardEvent{+ ID: 2,+ DeviceID: "missing-slot",+ EventName: "message",+ PayloadJSON: `{"payload":{"id":"m1"}}`,+ }); err == nil {+ t.Fatal("retry should fail when no device manager can restore the device")+ }+}++type authzLinkRepo struct {+ chatstorage.IChatStorageRepository+ link *chatstorage.ChatwootMessageLink+ msg *chatstorage.Message+}++func (r *authzLinkRepo) GetChatwootMessageLinkByWhatsAppID(deviceID, waMessageID string) (*chatstorage.ChatwootMessageLink, error) {+ if r.link != nil && r.link.DeviceID == deviceID && r.link.WhatsAppMessageID == waMessageID {+ cloned := *r.link+ return &cloned, nil+ }+ return nil, nil+}++func (r *authzLinkRepo) GetMessageByIDChatAndDevice(deviceID, chatJID, id string) (*chatstorage.Message, error) {+ if r.msg != nil && r.msg.DeviceID == deviceID && r.msg.ChatJID == chatJID && r.msg.ID == id {+ cloned := *r.msg+ return &cloned, nil+ }+ return nil, nil+}++func TestChatwootLinkRequiresConfigurationNotJustAccount(t *testing.T) {+ cw := &chatwoot.Client{AccountID: 1}+ sameAccountOtherServer := &chatstorage.ChatwootMessageLink{ChatwootAccountID: 1, ChatwootConfigID: 5}+ if chatwootLinkMatchesClient(sameAccountOtherServer, cw, 9) {+ t.Fatal("account number collision was treated as the same Chatwoot server")+ }+ if !chatwootLinkMatchesClient(sameAccountOtherServer, cw, 5) {+ t.Fatal("matching configuration was rejected")+ }+ legacy := &chatstorage.ChatwootMessageLink{ChatwootAccountID: 1, ChatwootConfigID: 0}+ if chatwootLinkMatchesClient(legacy, cw, 5) {+ t.Fatal("legacy link matched a per-device configuration")+ }+ if !chatwootLinkMatchesClient(legacy, cw, 0) {+ t.Fatal("legacy client should accept a legacy link for the same account")+ }+}++func TestChatwootExclusionRunsBeforeReceiptAndDelete(t *testing.T) {+ origIgnore := config.ChatwootIgnoreJids+ origDelete := config.ChatwootMessageDelete+ t.Cleanup(func() {+ config.ChatwootIgnoreJids = origIgnore+ config.ChatwootMessageDelete = origDelete+ })+ config.ChatwootIgnoreJids = []string{"111222333@lid", "[email protected]"}+ config.ChatwootMessageDelete = true++ _, err := extractChatwootContactInfo(context.Background(), map[string]any{+ "from": "[email protected]",+ "chat_id": "[email protected]",+ "from_lid": "111222333@lid",+ })+ if err == nil {+ t.Fatal("resolved phone JID bypassed an excluded LID alias")+ }++ hit := false+ srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {+ hit = true+ w.WriteHeader(http.StatusOK)+ }))+ defer srv.Close()+ cw := &chatwoot.Client{BaseURL: srv.URL, APIToken: "t", AccountID: 1, InboxID: 2, HTTPClient: srv.Client()}+ repo := &authzLinkRepo{link: &chatstorage.ChatwootMessageLink{+ DeviceID: "dev",+ WhatsAppMessageID: "m1",+ WhatsAppChatJID: "[email protected]",+ ChatwootMessageID: 8,+ ChatwootConversationID: 9,+ ChatwootContactInboxSourceID: "src",+ ChatwootConfigID: 3,+ ChatwootAccountID: 1,+ }}++ syncReadReceiptsToChatwoot(cw, "dev", repo, 3, map[string]any{+ "receipt_type": "read",+ "ids": []string{"m1"},+ "chat_id": "[email protected]",+ "chat_lid": "111222333@lid",+ })+ if hit {+ t.Fatal("read receipt updated an excluded chat")+ }++ hit = false+ repo.link.WhatsAppChatJID = "[email protected]"+ if deleteLinkedChatwootMessage(cw, "dev", repo, 3, "message.revoked", map[string]any{+ "revoked_message_id": "m1",+ "chat_id": "[email protected]",+ "from": "[email protected]",+ }) {+ t.Fatal("delete ran for an excluded chat")+ }+ if hit {+ t.Fatal("excluded chat was deleted in Chatwoot")+ }+}++func TestChatwootRevokeRequiresAuthor(t *testing.T) {+ origEnabled := config.ChatwootEnabled+ origDelete := config.ChatwootMessageDelete+ origIgnore := config.ChatwootIgnoreJids+ t.Cleanup(func() {+ config.ChatwootEnabled = origEnabled+ config.ChatwootMessageDelete = origDelete+ config.ChatwootIgnoreJids = origIgnore+ })+ config.ChatwootEnabled = true+ config.ChatwootMessageDelete = true+ config.ChatwootIgnoreJids = nil++ hit := false+ srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {+ hit = true+ w.WriteHeader(http.StatusOK)+ }))+ defer srv.Close()+ cw := &chatwoot.Client{BaseURL: srv.URL, APIToken: "t", AccountID: 1, InboxID: 2, HTTPClient: srv.Client()}+ chatJID := "[email protected]"+ repo := &authzLinkRepo{+ link: &chatstorage.ChatwootMessageLink{+ DeviceID: "dev",+ WhatsAppMessageID: "m1",+ WhatsAppChatJID: chatJID,+ ChatwootMessageID: 8,+ ChatwootConversationID: 9,+ ChatwootConfigID: 3,+ ChatwootAccountID: 1,+ },+ msg: &chatstorage.Message{+ ID: "m1", ChatJID: chatJID, DeviceID: "dev", Sender: "[email protected]",+ },+ }+ data := map[string]any{+ "revoked_message_id": "m1",+ "chat_id": chatJID,+ "from": "[email protected]",+ "is_from_me": false,+ }+ if deleteLinkedChatwootMessage(cw, "dev", repo, 3, "message.revoked", data) {+ t.Fatal("unauthorized revoke deleted the Chatwoot message")+ }+ if hit {+ t.Fatal("Chatwoot was called for an unauthorized revoke")+ }++ NoteMessageRevokeAuthorization("dev", chatJID, "m1", true)+ t.Cleanup(func() { revokeAuthNotes.Delete(revokeAuthKey("dev", chatJID, "m1")) })+ data["from"] = "[email protected]"+ if !deleteLinkedChatwootMessage(cw, "dev", repo, 3, "message.revoked", data) {+ t.Fatal("authorized revoke was not forwarded")+ }+ if !hit {+ t.Fatal("authorized revoke did not reach Chatwoot")+ }+}++func TestMessageAuthorMatchesRejectsEmptyStoredSender(t *testing.T) {+ if MessageAuthorMatches("", false, "[email protected]", "[email protected]", false) {+ t.Fatal("empty stored sender matched a peer")+ }+ if !MessageAuthorMatches("[email protected]", true, "[email protected]", "", true) {+ t.Fatal("same-account IsFromMe edit should match")+ }+}++func TestSyncPayloadSkipsUnauthorizedEditAndRevoke(t *testing.T) {+ origEnabled := config.ChatwootEnabled+ origEdit := config.ChatwootForwardEdits+ origDelete := config.ChatwootForwardDeletes+ origHard := config.ChatwootMessageDelete+ origClient := getChatwootClientFn+ t.Cleanup(func() {+ config.ChatwootEnabled = origEnabled+ config.ChatwootForwardEdits = origEdit+ config.ChatwootForwardDeletes = origDelete+ config.ChatwootMessageDelete = origHard+ getChatwootClientFn = origClient+ for _, id := range []string{"EDIT-FOREIGN", "REV-FOREIGN", "EDIT-OWN"} {+ messageEventAuthNotes.Delete(messageEventAuthKey("dev", id))+ }+ })+ config.ChatwootEnabled = true+ config.ChatwootForwardEdits = true+ config.ChatwootForwardDeletes = true+ config.ChatwootMessageDelete = true++ hit := false+ srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {+ hit = true+ w.WriteHeader(http.StatusOK)+ _, _ = w.Write([]byte(`{"payload":[]}`))+ }))+ defer srv.Close()+ getChatwootClientFn = func(string) (*chatwoot.ResolvedConfig, error) {+ return &chatwoot.ResolvedConfig{+ ConfigID: 3,+ Client: &chatwoot.Client{+ BaseURL: srv.URL, APIToken: "t", AccountID: 1, InboxID: 2, HTTPClient: srv.Client(),+ },+ }, nil+ }+ repo := &authzLinkRepo{link: &chatstorage.ChatwootMessageLink{+ DeviceID: "dev", WhatsAppMessageID: "m1", WhatsAppChatJID: "[email protected]",+ ChatwootMessageID: 8, ChatwootConversationID: 9, ChatwootConfigID: 3, ChatwootAccountID: 1,+ ChatwootContactInboxSourceID: "src",+ }}+ chatID := "[email protected]"++ NoteMessageEventAuthorization("dev", "EDIT-FOREIGN", false)+ err := syncPayloadToChatwoot(context.Background(), map[string]any{"payload": map[string]any{+ "id": "EDIT-FOREIGN", "original_message_id": "m1", "body": "pwned",+ "from": "[email protected]", "chat_id": chatID, "is_from_me": false,+ }}, "message.edited", "dev", repo)+ if err != nil {+ t.Fatalf("unauthorized edit: %v", err)+ }+ if hit {+ t.Fatal("unauthorized edit wrote to Chatwoot")+ }++ NoteMessageEventAuthorization("dev", "REV-FOREIGN", false)+ err = syncPayloadToChatwoot(context.Background(), map[string]any{"payload": map[string]any{+ "id": "REV-FOREIGN", "revoked_message_id": "m1",+ "from": "[email protected]", "chat_id": chatID, "is_from_me": false,+ }}, "message.revoked", "dev", repo)+ if err != nil {+ t.Fatalf("unauthorized revoke: %v", err)+ }+ if hit {+ t.Fatal("unauthorized revoke wrote to Chatwoot")+ }++ // No decision was recorded (storage failed or never saw the event): a+ // peer's edit or revoke is denied.+ for _, event := range []string{"message.edited", "message.revoked"} {+ err = syncPayloadToChatwoot(context.Background(), map[string]any{"payload": map[string]any{+ "id": "PEER-UNDECIDED", "original_message_id": "m1", "revoked_message_id": "m1", "body": "pwned",+ "from": "[email protected]", "chat_id": chatID, "is_from_me": false,+ }}, event, "dev", repo)+ if err != nil {+ t.Fatalf("undecided peer %s: %v", event, err)+ }+ if hit {+ t.Fatalf("undecided peer %s wrote to Chatwoot", event)+ }+ }++ NoteMessageEventAuthorization("dev", "EDIT-OWN", true)+ err = syncPayloadToChatwoot(context.Background(), map[string]any{"payload": map[string]any{+ "id": "EDIT-OWN", "original_message_id": "m1", "body": "edited by us",+ "from": "[email protected]", "chat_id": chatID, "is_from_me": true,+ }}, "message.edited", "dev", repo)+ if !hit {+ t.Fatalf("same-account edit was not forwarded (err=%v)", err)+ }++ // This account may edit or revoke what it sent without a recorded decision.+ for _, event := range []string{"message.edited", "message.revoked"} {+ hit = false+ err = syncPayloadToChatwoot(context.Background(), map[string]any{"payload": map[string]any{+ "id": "OWN-UNDECIDED", "original_message_id": "m1", "revoked_message_id": "m1", "body": "edited by us",+ "from": "[email protected]", "chat_id": chatID, "is_from_me": true,+ }}, event, "dev", repo)+ if !hit {+ t.Fatalf("undecided same-account %s was not forwarded (err=%v)", event, err)+ }+ }+}++func TestDeleteAndReceiptPayloadsCarryLIDForExclusion(t *testing.T) {+ origIgnore := config.ChatwootIgnoreJids+ origDelete := config.ChatwootMessageDelete+ origForward := config.ChatwootForwardDeletes+ origClient := getChatwootClientFn+ t.Cleanup(func() {+ config.ChatwootIgnoreJids = origIgnore+ config.ChatwootMessageDelete = origDelete+ config.ChatwootForwardDeletes = origForward+ getChatwootClientFn = origClient+ })+ config.ChatwootIgnoreJids = []string{"111@lid"}+ config.ChatwootMessageDelete = true+ config.ChatwootForwardDeletes = true++ phone := types.NewJID("1555121200", types.DefaultUserServer)+ lid := types.NewJID("111", types.HiddenUserServer)+ hit := false+ srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {+ hit = true+ w.WriteHeader(http.StatusOK)+ }))+ defer srv.Close()+ getChatwootClientFn = func(string) (*chatwoot.ResolvedConfig, error) {+ return &chatwoot.ResolvedConfig{+ ConfigID: 3,+ Client: &chatwoot.Client{+ BaseURL: srv.URL, APIToken: "t", AccountID: 1, InboxID: 2, HTTPClient: srv.Client(),+ },+ }, nil+ }+ repo := &authzLinkRepo{link: &chatstorage.ChatwootMessageLink{+ DeviceID: "dev", WhatsAppMessageID: "m1", WhatsAppChatJID: phone.String(),+ ChatwootMessageID: 8, ChatwootConversationID: 9, ChatwootConfigID: 3, ChatwootAccountID: 1,+ ChatwootContactInboxSourceID: "src",+ }}++ deleteBody, err := createDeletePayload(context.Background(), &events.DeleteForMe{+ ChatJID: lid, SenderJID: phone, MessageID: "m1", Timestamp: time.Now(),+ }, &chatstorage.Message{+ ChatJID: phone.String(), Sender: phone.String(), Content: "secret", Timestamp: time.Now(),+ }, "dev", nil)+ if err != nil {+ t.Fatalf("createDeletePayload: %v", err)+ }+ inner, _ := deleteBody["payload"].(map[string]any)+ if inner["chat_id"] != phone.String() || inner["chat_lid"] != "111@lid" {+ t.Fatalf("delete payload lost the original LID: %#v", inner)+ }+ if err := syncPayloadToChatwoot(context.Background(), deleteBody, "message.deleted", "dev", repo); err != nil {+ t.Fatalf("delete sync: %v", err)+ }+ if hit {+ t.Fatal("delete-for-me of an ignored LID updated Chatwoot")+ }++ receipt := createReceiptPayload(context.Background(), &events.Receipt{+ MessageSource: types.MessageSource{+ Chat: phone, Sender: phone, RecipientAlt: lid,+ },+ MessageIDs: []types.MessageID{"m1"},+ Type: types.ReceiptTypeRead,+ Timestamp: time.Now(),+ }, "dev", nil)+ inner, _ = receipt["payload"].(map[string]any)+ if inner["chat_id"] != phone.String() || inner["chat_lid"] != "111@lid" {+ t.Fatalf("receipt payload lost the alt LID: %#v", inner)+ }+ if err := syncPayloadToChatwoot(context.Background(), receipt, "message.ack", "dev", repo); err != nil {+ t.Fatalf("receipt sync: %v", err)+ }+ if hit {+ t.Fatal("read receipt for an ignored LID updated last seen")+ }+}++func TestIsGroupAdminMatchesLIDOrPhone(t *testing.T) {+ orig := fetchGroupInfoFn+ t.Cleanup(func() { fetchGroupInfoFn = orig })+ group := types.NewJID("120363000000000001", types.GroupServer)+ adminLID := types.NewJID("111", types.HiddenUserServer)+ adminPN := types.NewJID("628111", types.DefaultUserServer)+ memberLID := types.NewJID("222", types.HiddenUserServer)+ var lookupErr error+ fetchGroupInfoFn = func(_ context.Context, _ *whatsmeow.Client, jid types.JID) (*types.GroupInfo, error) {+ if lookupErr != nil || jid != group {+ return nil, lookupErr+ }+ return &types.GroupInfo{Participants: []types.GroupParticipant{+ {JID: adminLID, PhoneNumber: adminPN, IsAdmin: true},+ {JID: memberLID, PhoneNumber: types.NewJID("628222", types.DefaultUserServer)},+ }}, nil+ }+ ctx := context.Background()+ client := &whatsmeow.Client{}++ companion := adminLID+ companion.Device = 3+ if !IsGroupAdmin(ctx, client, group, companion) {+ t.Fatal("admin sending from a companion device was not recognized by LID")+ }+ if !IsGroupAdmin(ctx, client, group, adminPN, types.EmptyJID) {+ t.Fatal("admin addressed by phone in a LID group was not recognized")+ }+ if IsGroupAdmin(ctx, client, group, memberLID, types.EmptyJID) {+ t.Fatal("a member who is not an admin was treated as one")+ }+ if IsGroupAdmin(ctx, nil, group, adminLID) {+ t.Fatal("a missing client answered as admin")+ }+ lookupErr = errors.New("timeout")+ if IsGroupAdmin(ctx, client, group, adminLID) {+ t.Fatal("a failed group lookup was treated as admin")+ }+}++func TestAuthNotesNeedChatwootAndExpiredOnesAreSwept(t *testing.T) {+ origEnabled := config.ChatwootEnabled+ t.Cleanup(func() {+ config.ChatwootEnabled = origEnabled+ ForgetMessageAuthorizationsForTest("dev-sweep")+ })+ chatJID := "[email protected]"++ config.ChatwootEnabled = false+ NoteMessageEventAuthorization("dev-sweep", "EVT-OFF", false)+ NoteMessageRevokeAuthorization("dev-sweep", chatJID, "m-off", false)+ if _, ok := MessageEventAuthorized("dev-sweep", "EVT-OFF"); ok {+ t.Fatal("event decision kept while Chatwoot is disabled")+ }+ if _, ok := MessageRevokeAuthorized("dev-sweep", chatJID, "m-off"); ok {+ t.Fatal("revoke decision kept while Chatwoot is disabled")+ }++ config.ChatwootEnabled = true+ staleEvent := messageEventAuthKey("dev-sweep", "EVT-STALE")+ staleRevoke := revokeAuthKey("dev-sweep", chatJID, "m-stale")+ expired := revokeAuthRecord{expires: time.Now().Add(-time.Minute)}+ messageEventAuthNotes.Store(staleEvent, expired)+ revokeAuthNotes.Store(staleRevoke, expired)+ authNotesSweptAt.Store(0)+ NoteMessageEventAuthorization("dev-sweep", "EVT-NEW", true)+ if _, found := messageEventAuthNotes.Load(staleEvent); found {+ t.Fatal("expired event decision survived the sweep")+ }+ if _, found := revokeAuthNotes.Load(staleRevoke); found {+ t.Fatal("expired revoke decision survived the sweep")+ }+ if authorized, ok := MessageEventAuthorized("dev-sweep", "EVT-NEW"); !ok || !authorized {+ t.Fatal("the new decision was not kept")+ }+}++func TestQueuedRevokeKeepsItsAuthorization(t *testing.T) {+ origEnabled := config.ChatwootEnabled+ origHard := config.ChatwootMessageDelete+ origForward := config.ChatwootForwardDeletes+ origIgnore := config.ChatwootIgnoreJids+ origClient := getChatwootClientFn+ origDM := deviceManager+ t.Cleanup(func() {+ config.ChatwootEnabled = origEnabled+ config.ChatwootMessageDelete = origHard+ config.ChatwootForwardDeletes = origForward+ config.ChatwootIgnoreJids = origIgnore+ getChatwootClientFn = origClient+ deviceManager = origDM+ ForgetMessageAuthorizationsForTest("dev-retry")+ })+ config.ChatwootEnabled = true+ config.ChatwootMessageDelete = true+ config.ChatwootForwardDeletes = true+ config.ChatwootIgnoreJids = nil+ deviceManager = NewDeviceManager(nil, nil, nil)+ deviceManager.AddDevice(NewDeviceInstance("dev-retry", nil, nil))++ var requests []string+ srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {+ requests = append(requests, r.Method)+ w.WriteHeader(http.StatusOK)+ }))+ defer srv.Close()+ getChatwootClientFn = func(string) (*chatwoot.ResolvedConfig, error) {+ return &chatwoot.ResolvedConfig{+ ConfigID: 3,+ Client: &chatwoot.Client{+ BaseURL: srv.URL, APIToken: "t", AccountID: 1, InboxID: 2, HTTPClient: srv.Client(),+ },+ }, nil+ }+ chatJID := "[email protected]"+ repo := &authzLinkRepo{link: &chatstorage.ChatwootMessageLink{+ DeviceID: "dev-retry", WhatsAppMessageID: "m1", WhatsAppChatJID: chatJID,+ ChatwootMessageID: 8, ChatwootConversationID: 9, ChatwootConfigID: 3, ChatwootAccountID: 1,+ }}++ // The author's revoke was authorized and its row deleted, then Chatwoot failed.+ NoteMessageEventAuthorization("dev-retry", "REV-1", true)+ NoteMessageRevokeAuthorization("dev-retry", chatJID, "m1", true)+ payload := map[string]any{"event": "message.revoked", "payload": map[string]any{+ "id": "REV-1", "revoked_message_id": "m1", "chat_id": chatJID, "from": chatJID, "is_from_me": false,+ }}+ queue := &chatwootForwardQueueTestRepo{}+ if !enqueueChatwootForwardRetry(queue, "dev-retry", "message.revoked", payload, &chatwoot.HTTPStatusError{+ StatusCode: http.StatusInternalServerError, Op: "delete message",+ }) {+ t.Fatal("transient failure was not queued")+ }+ if _, stamped := payload[queuedAuthorizationKey]; stamped {+ t.Fatal("the decision was written into the live payload")+ }++ // A restart drops the in-memory decisions. The replay restores the queued one.+ ForgetMessageAuthorizationsForTest("dev-retry")+ if err := processChatwootForwardRetryEvent(repo, queue.events[0]); err != nil {+ t.Fatalf("replay: %v", err)+ }+ if len(requests) != 1 || requests[0] != http.MethodDelete {+ t.Fatalf("authorized queued revoke did not hard-delete: %v", requests)+ }++ // A queued revoke without a decision is denied: no delete and no tombstone.+ requests = nil+ ForgetMessageAuthorizationsForTest("dev-retry")+ if err := processChatwootForwardRetryEvent(repo, &chatstorage.ChatwootForwardEvent{+ DeviceID: "dev-retry",+ EventName: "message.revoked",+ PayloadJSON: `{"payload":{"id":"REV-2","revoked_message_id":"m1","chat_id":"[email protected]","from":"[email protected]"}}`,+ }); err != nil {+ t.Fatalf("replay without a decision: %v", err)+ }+ if len(requests) != 0 {+ t.Fatalf("queued revoke without a decision reached Chatwoot: %v", requests)+ }++ // This account's own revoke without a recorded decision is queued as+ // authorized, as the live path treats it.+ own := map[string]any{"event": "message.revoked", "payload": map[string]any{+ "id": "REV-3", "revoked_message_id": "m1", "chat_id": chatJID, "from": chatJID, "is_from_me": true,+ }}+ if !enqueueChatwootForwardRetry(queue, "dev-retry", "message.revoked", own, &chatwoot.HTTPStatusError{+ StatusCode: http.StatusInternalServerError, Op: "delete message",+ }) {+ t.Fatal("own revoke was not queued")+ }+ if queued := queue.events[len(queue.events)-1].PayloadJSON; !strings.Contains(queued, `"chatwoot_authorized":true`) {+ t.Fatalf("own revoke queued without authorization: %s", queued)+ }+}++func TestChatwootSkipsChatExcludedOnlyByItsStoredLink(t *testing.T) {+ origIgnore := config.ChatwootIgnoreJids+ origDelete := config.ChatwootMessageDelete+ origForward := config.ChatwootForwardDeletes+ origClient := getChatwootClientFn+ t.Cleanup(func() {+ config.ChatwootIgnoreJids = origIgnore+ config.ChatwootMessageDelete = origDelete+ config.ChatwootForwardDeletes = origForward+ getChatwootClientFn = origClient+ })+ config.ChatwootIgnoreJids = []string{"111@lid"}+ config.ChatwootMessageDelete = true+ config.ChatwootForwardDeletes = true++ hit := false+ srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {+ hit = true+ w.WriteHeader(http.StatusOK)+ }))+ defer srv.Close()+ getChatwootClientFn = func(string) (*chatwoot.ResolvedConfig, error) {+ return &chatwoot.ResolvedConfig{+ ConfigID: 3,+ Client: &chatwoot.Client{+ BaseURL: srv.URL, APIToken: "t", AccountID: 1, InboxID: 2, HTTPClient: srv.Client(),+ },+ }, nil+ }+ // The link was stored under the excluded LID. The events name only the phone.+ phone := "[email protected]"+ repo := &authzLinkRepo{link: &chatstorage.ChatwootMessageLink{+ DeviceID: "dev", WhatsAppMessageID: "m1", WhatsAppChatJID: "111@lid",+ ChatwootMessageID: 8, ChatwootConversationID: 9, ChatwootConfigID: 3, ChatwootAccountID: 1,+ ChatwootContactInboxSourceID: "src",+ }}++ for _, tc := range []struct {+ event string+ data map[string]any+ }{+ {"message.deleted", map[string]any{"deleted_message_id": "m1", "chat_id": phone, "from": phone}},+ {"message.ack", map[string]any{"receipt_type": "read", "ids": []string{"m1"}, "chat_id": phone, "from": phone}},+ } {+ if chatwootPayloadExcluded(tc.data) {+ t.Fatalf("%s payload must not be excluded by itself", tc.event)+ }+ if err := syncPayloadToChatwoot(context.Background(), map[string]any{"payload": tc.data}, tc.event, "dev", repo); err != nil {+ t.Fatalf("%s: %v", tc.event, err)+ }+ if hit {+ t.Fatalf("%s reached Chatwoot for a chat excluded by its stored link", tc.event)+ }+ }+}++func TestPayloadExclusionWildcardsApplyToDeliveredAddress(t *testing.T) {+ origChatwoot, origWebhook := config.ChatwootIgnoreJids, config.WhatsappWebhookIgnoreJids+ t.Cleanup(func() { config.ChatwootIgnoreJids, config.WhatsappWebhookIgnoreJids = origChatwoot, origWebhook })++ resolved := map[string]any{"chat_id": "[email protected]", "from": "[email protected]", "chat_lid": "111@lid", "from_lid": "111@lid"}+ config.ChatwootIgnoreJids = []string{"@lid"}+ if chatwootPayloadExcluded(resolved) {+ t.Error("@lid excluded a chat that resolved to a phone number")+ }+ if !chatwootPayloadExcluded(map[string]any{"chat_id": "111@lid", "from": "111@lid"}) {+ t.Error("@lid did not exclude a chat still addressed by its LID")+ }+ config.ChatwootIgnoreJids = []string{"111@lid"}+ if !chatwootPayloadExcluded(resolved) {+ t.Error("an exact LID entry did not exclude the resolved chat")+ }++ config.WhatsappWebhookIgnoreJids = []string{"[email protected]"}+ receipt := map[string]any{"payload": map[string]any{"chat_id": "222@lid", "from": "222@lid", "sender_alt": "[email protected]"}}+ if !shouldIgnoreWebhookJID(receipt) {+ t.Error("the webhook ignore list did not match sender_alt")+ }+}diff --git a/src/pkg/utils/chatwoot.go b/src/pkg/utils/chatwoot.goindex 62c3eec9..c8214283 100644--- a/src/pkg/utils/chatwoot.go+++ b/src/pkg/utils/chatwoot.go@@ -30,6 +30,22 @@ func MatchesIgnoredJID(jid string, ignore []string) bool {return false}+// MatchesIgnoredAliasJID matches jid against the exact (non-wildcard) entries of+// an ignore list. It is used for a chat's other address (its LID or phone+// counterpart), so a wildcard such as "@lid" keeps applying only to the address+// a chat is delivered under.+func MatchesIgnoredAliasJID(jid string, ignore []string) bool {+ if jid == "" {+ return false+ }+ for _, pattern := range ignore {+ if pattern = strings.TrimSpace(pattern); pattern != "" && !strings.HasPrefix(pattern, "@") && jid == pattern {+ return true+ }+ }+ return false+}+// IsSystemBroadcastJID reports the WhatsApp system JIDs that must never reach// Chatwoot: status@broadcast (the per-account status feed) and [email protected]// (WhatsApp's official service account). Forwarding either creates noisediff --git a/src/ui/rest/chatwoot.go b/src/ui/rest/chatwoot.goindex 76286770..ae84e132 100644--- a/src/ui/rest/chatwoot.go+++ b/src/ui/rest/chatwoot.go@@ -176,7 +176,8 @@ func chatwootContactAttrString(attrs map[string]any, key string) string {// resolveChatwootWebhookRoute resolves which WhatsApp device (and destination)// a Chatwoot agent reply should be sent from. Resolution order, safest first:-// 1. Account-scoped conversation link (handles replies to existing conversations).+// 1. Conversation link of the request's configuration (handles replies to+// existing conversations).// 2. Contact custom attribute gowa_device_id (explicit operator override).// 3. Inbox+account reverse map (agent-initiated conversations).// 4. Env config.ChatwootDeviceID — ONLY while no per-device config rows exist@@ -194,16 +195,33 @@ func (h *ChatwootHandler) resolveChatwootWebhookRoute(payload chatwoot.WebhookPa// another account could match a legacy (account 0) link and misroute.legacy := h.legacyChatwootMode()- // 1) Account-scoped conversation link. On the per-device endpoint the link- // must additionally belong to the device's own config: two separate Chatwoot- // servers can collide on (conversation_id, account_id) — fresh installs all- // start at account 1, conversation 1 — and an unscoped match would take the- // destination chat JID from the other server's conversation.- if h != nil && h.ChatStorageRepo != nil && payload.Conversation.ID != 0 {- var scopeConfigID int64- if forced != nil {- scopeConfigID = forced.ConfigID+ // The configuration that owns the payload's (account, inbox), or nil when+ // none or more than one does. It scopes the shared-endpoint link lookup in+ // step 1 and routes agent-initiated conversations in step 3.+ var byInbox *chatwoot.ResolvedConfig+ if reg := chatwoot.GetClientRegistry(); reg != nil {+ rc, err := reg.ResolveByInbox(payload.Account.ID, payload.Conversation.InboxID)+ if err != nil {+ logrus.Errorf("Chatwoot Webhook: inbox reverse lookup failed (account=%d inbox=%d): %v", payload.Account.ID, payload.Conversation.InboxID, err)}+ byInbox = rc+ }++ // 1) Account-scoped conversation link. Outside legacy mode the link must+ // also belong to the configuration the request is for: two separate+ // Chatwoot servers can collide on (conversation_id, account_id) — fresh+ // installs all start at account 1, conversation 1 — and an unscoped match+ // would take the destination chat JID from the other server's conversation.+ // The per-device endpoint forces its config. The shared endpoint uses the+ // config that owns the payload's (account, inbox), which also keeps out+ // legacy config-0 links; with no such config there is no link lookup.+ var scopeConfigID int64+ if forced != nil {+ scopeConfigID = forced.ConfigID+ } else if !legacy && byInbox != nil {+ scopeConfigID = byInbox.ConfigID+ }+ if h != nil && h.ChatStorageRepo != nil && payload.Conversation.ID != 0 && (legacy || scopeConfigID != 0) {link, err := h.ChatStorageRepo.GetLatestChatwootMessageLinkByConversation(payload.Conversation.ID, payload.Account.ID, legacy, scopeConfigID)if err != nil {logrus.Errorf("Chatwoot Webhook: Failed to lookup conversation route %d: %v", payload.Conversation.ID, err)@@ -234,23 +252,27 @@ func (h *ChatwootHandler) resolveChatwootWebhookRoute(payload chatwoot.WebhookPa// by any agent of that Chatwoot account, so an unchecked override would let// account A send from a device belonging to account B.if deviceID := chatwootContactAttrString(contact.CustomAttributes, "gowa_device_id"); deviceID != "" {- if legacy || h.deviceMatchesPayloadScope(deviceID, payload) {+ if legacy {route.DeviceID = deviceIDreturn route}+ if rc := h.resolveChatwootForDevice(deviceID); rc != nil && rc.Client != nil &&+ rc.Client.AccountID == payload.Account.ID && rc.Client.InboxID == payload.Conversation.InboxID {+ route.DeviceID = deviceID+ route.ConfigID = rc.ConfigID+ route.AccountID = rc.Client.AccountID+ route.InboxID = rc.Client.InboxID+ return route+ }logrus.Warnf("Chatwoot Webhook: ignoring gowa_device_id %q: device is not configured for account %d inbox %d",deviceID, payload.Account.ID, payload.Conversation.InboxID)}// 3) Inbox+account reverse map (agent-initiated conversation with no link yet).- if reg := chatwoot.GetClientRegistry(); reg != nil {- if rc, err := reg.ResolveByInbox(payload.Account.ID, payload.Conversation.InboxID); err != nil {- logrus.Errorf("Chatwoot Webhook: inbox reverse lookup failed (account=%d inbox=%d): %v", payload.Account.ID, payload.Conversation.InboxID, err)- } else if rc != nil {- route.DeviceID = rc.DeviceID- route.ConfigID = rc.ConfigID- return route- }+ if byInbox != nil {+ route.DeviceID = byInbox.DeviceID+ route.ConfigID = byInbox.ConfigID+ return route}// 4) Legacy env fallback, only while there are no per-device configs.@@ -264,13 +286,47 @@ func (h *ChatwootHandler) resolveChatwootWebhookRoute(payload chatwoot.WebhookPareturn route}-// deviceMatchesPayloadScope reports whether deviceID has a per-device config-// bound to the payload's account and inbox. Used to validate the-// gowa_device_id contact-attribute override in per-device mode.-func (h *ChatwootHandler) deviceMatchesPayloadScope(deviceID string, payload chatwoot.WebhookPayload) bool {- rc := h.resolveChatwootForDevice(deviceID)- return rc != nil && rc.Client != nil &&- rc.Client.AccountID == payload.Account.ID && rc.Client.InboxID == payload.Conversation.InboxID+// chatwootRouteEnabled reports whether the route's current Chatwoot+// configuration may send or revoke. A disabled or missing configuration fails+// closed. The check uses the route's configuration id when it has one: a+// conversation link is stored under the WhatsApp JID, which is not always the+// key the config row was saved with. Legacy single-account mode has no+// per-device enabled flag; the process-wide CHATWOOT_ENABLED gate covers it.+// There an empty device id is the documented single-device setup+// (CHATWOOT_DEVICE_ID unset), which sends from the only device.+func (h *ChatwootHandler) chatwootRouteEnabled(route chatwootWebhookRoute) bool {+ if h.legacyChatwootMode() {+ return true+ }+ if strings.TrimSpace(route.DeviceID) == "" {+ return false+ }+ if route.ConfigID != 0 {+ cfg, err := h.chatwootConfigByID(route.ConfigID)+ if err != nil {+ logrus.Errorf("Chatwoot Webhook: failed to load configuration %d: %v", route.ConfigID, err)+ return false+ }+ return cfg != nil && cfg.Enabled+ }+ rc := h.resolveChatwootForDevice(route.DeviceID)+ return rc != nil && rc.Client != nil+}++func (h *ChatwootHandler) chatwootConfigByID(id int64) (*domainChatStorage.ChatwootDeviceConfig, error) {+ if h == nil || h.ChatStorageRepo == nil || id == 0 {+ return nil, nil+ }+ configs, err := h.ChatStorageRepo.ListChatwootDeviceConfigs()+ if err != nil {+ return nil, err+ }+ for _, cfg := range configs {+ if cfg != nil && cfg.ID == id {+ return cfg, nil+ }+ }+ return nil, nil}// legacyChatwootMode reports whether the integration is in single-device env@@ -497,6 +553,10 @@ func (h *ChatwootHandler) processChatwootWebhook(c fiber.Ctx, payload chatwoot.W// WhatsApp account.return c.SendStatus(fiber.StatusOK)}+ if !h.chatwootRouteEnabled(route) {+ logrus.Warnf("Chatwoot Webhook: configuration for device %s is disabled; not sending", route.DeviceID)+ return c.SendStatus(fiber.StatusOK)+ }return h.deliverChatwootReply(c, payload, route, contact)}@@ -610,9 +670,12 @@ func (h *ChatwootHandler) handleDeletedChatwootMessage(c fiber.Ctx, payload chatroute := h.resolveChatwootWebhookRoute(payload, forced)if forced != nil {- // The delete path only needs the device to revoke from; the per-device- // endpoint forces it so revokes route to the same device as sends.+ // The per-device endpoint forces the device and its configuration so a+ // revoke cannot keep a disabled or foreign config from the payload.route.DeviceID = forced.DeviceID+ route.ConfigID = forced.ConfigID+ route.AccountID = forced.AccountID+ route.InboxID = forced.InboxIDroute.Unroutable = false}// A delete revokes a WhatsApp message: same gate as a send.@@ -622,6 +685,10 @@ func (h *ChatwootHandler) handleDeletedChatwootMessage(c fiber.Ctx, payload chatif route.Unroutable {return c.SendStatus(fiber.StatusOK)}+ if !h.chatwootRouteEnabled(route) {+ logrus.Warnf("Chatwoot Webhook: configuration for device %s is disabled; not revoking", route.DeviceID)+ return c.SendStatus(fiber.StatusOK)+ }instance, resolvedID, err := h.DeviceManager.ResolveDevice(route.DeviceID)if err != nil {logrus.Errorf("Chatwoot Webhook: Failed to resolve device for delete: %v", err)@@ -641,6 +708,17 @@ func (h *ChatwootHandler) handleDeletedChatwootMessage(c fiber.Ctx, payload chatlogrus.Debugf("Chatwoot Webhook: Not revoking inbound WhatsApp message %s for Chatwoot delete %d", link.WhatsAppMessageID, payload.ID)return c.SendStatus(fiber.StatusOK)}+ // The link must belong to this route's configuration, the rule+ // chatwootLinkMatchesClient applies in the other direction: a link stored+ // through another Chatwoot server names an unrelated customer's message.+ linkMatches := link.ChatwootConfigID == route.ConfigID+ if h.legacyChatwootMode() {+ linkMatches = link.ChatwootConfigID == 0 && (link.ChatwootAccountID == 0 || link.ChatwootAccountID == route.AccountID)+ }+ if !linkMatches {+ logrus.Warnf("Chatwoot Webhook: Not revoking WhatsApp message %s for Chatwoot delete %d: its link belongs to another Chatwoot configuration", link.WhatsAppMessageID, payload.ID)+ return c.SendStatus(fiber.StatusOK)+ }ctx := whatsapp.ContextWithDevice(c.Context(), instance)if _, err := h.MessageUsecase.RevokeMessage(ctx, domainMessage.RevokeRequest{diff --git a/src/ui/rest/chatwoot_device_webhook_test.go b/src/ui/rest/chatwoot_device_webhook_test.goindex bc545fa7..14543203 100644--- a/src/ui/rest/chatwoot_device_webhook_test.go+++ b/src/ui/rest/chatwoot_device_webhook_test.go@@ -170,3 +170,93 @@ func TestResolveChatwootWebhookRouteFailsFastWhenConfigsExist(t *testing.T) {t.Fatalf("legacy mode should use env device, got %q", route.DeviceID)}}++type linkRouteRepo struct {+ deviceWebhookTestRepo+ link *domainChatStorage.ChatwootMessageLink+}++func (r *linkRouteRepo) GetLatestChatwootMessageLinkByConversation(conversationID, accountID int, allowLegacyZero bool, configID int64) (*domainChatStorage.ChatwootMessageLink, error) {+ if r.link == nil || r.link.ChatwootConversationID != conversationID {+ return nil, nil+ }+ if r.link.ChatwootAccountID != accountID && !(allowLegacyZero && r.link.ChatwootAccountID == 0) {+ return nil, nil+ }+ if configID != 0 && r.link.ChatwootConfigID != configID {+ return nil, nil+ }+ cloned := *r.link+ return &cloned, nil+}++func (r *linkRouteRepo) GetChatwootDeviceConfigByInbox(accountID, inboxID int) (*domainChatStorage.ChatwootDeviceConfig, error) {+ if r.cfg != nil && r.cfg.AccountID == accountID && r.cfg.InboxID == inboxID {+ return r.cfg, nil+ }+ return nil, nil+}++func TestContactDeviceOverridePreservesConfigID(t *testing.T) {+ repo := &deviceWebhookTestRepo{+ cfg: &domainChatStorage.ChatwootDeviceConfig{+ ID: 42, DeviceID: "sales", ChatwootURL: "https://chat.example.com",+ AccountID: 7, InboxID: 3, APIToken: "t", Enabled: true,+ },+ count: 1,+ }+ chatwoot.InitClientRegistry(repo)+ t.Cleanup(func() { chatwoot.InitClientRegistry(nil) })++ route := (&ChatwootHandler{ChatStorageRepo: repo}).resolveChatwootWebhookRoute(chatwoot.WebhookPayload{+ Account: chatwoot.Account{ID: 7},+ Conversation: chatwoot.ConversationWebhook{+ ID: 4, InboxID: 3,+ Meta: chatwoot.ConversationMeta{Sender: chatwoot.Contact{CustomAttributes: map[string]any{+ "gowa_device_id": "sales",+ "gowa_whatsapp_jid": "[email protected]",+ }}},+ },+ }, nil)+ if route.Unroutable || route.DeviceID != "sales" || route.ConfigID != 42 || route.AccountID != 7 || route.InboxID != 3 {+ t.Fatalf("override dropped configuration identity: %+v", route)+ }+}++func TestConversationLinkDisabledConfigDoesNotRoute(t *testing.T) {+ repo := &linkRouteRepo{+ deviceWebhookTestRepo: deviceWebhookTestRepo{+ cfg: &domainChatStorage.ChatwootDeviceConfig{+ ID: 42, DeviceID: "sales", ChatwootURL: "https://chat.example.com",+ AccountID: 7, InboxID: 3, APIToken: "t", Enabled: false,+ },+ count: 1,+ },+ link: &domainChatStorage.ChatwootMessageLink{+ DeviceID: "sales", WhatsAppChatJID: "[email protected]",+ ChatwootConversationID: 4, ChatwootConfigID: 42, ChatwootAccountID: 7,+ },+ }+ chatwoot.InitClientRegistry(repo)+ t.Cleanup(func() { chatwoot.InitClientRegistry(nil) })++ handler := &ChatwootHandler{ChatStorageRepo: repo}+ payload := chatwoot.WebhookPayload{+ Account: chatwoot.Account{ID: 7},+ Conversation: chatwoot.ConversationWebhook{ID: 4, InboxID: 3},+ }+ // The shared endpoint scopes the link to the config that owns the inbox,+ // and a disabled config owns none.+ if route := handler.resolveChatwootWebhookRoute(payload, nil); !route.Unroutable {+ t.Fatalf("disabled configuration's link routed the shared endpoint: %+v", route)+ }+ // A route that still carries the config (disabled after the per-device+ // endpoint resolved it) must not send either.+ route := handler.resolveChatwootWebhookRoute(payload, &chatwootWebhookRoute{DeviceID: "sales", ConfigID: 42})+ if route.DeviceID == "" || route.Destination == "" {+ t.Fatalf("stored link should still identify the conversation: %+v", route)+ }+ if handler.chatwootRouteEnabled(route) {+ t.Fatalf("disabled configuration must not send: %+v", route)+ }+}diff --git a/src/ui/rest/chatwoot_test.go b/src/ui/rest/chatwoot_test.goindex 09ee51c5..1fa870fc 100644--- a/src/ui/rest/chatwoot_test.go+++ b/src/ui/rest/chatwoot_test.go@@ -539,3 +539,32 @@ func TestChatwootWebhookEmptyReplyText(t *testing.T) {})}}++// TestChatwootWebhookLegacyWithoutDeviceIDSendsFromOnlyDevice: the documented+// single-device setup leaves CHATWOOT_DEVICE_ID empty. A reply to a new+// conversation (no link yet) is sent from the only device.+func TestChatwootWebhookLegacyWithoutDeviceIDSendsFromOnlyDevice(t *testing.T) {+ withChatwootWebhookSecret(t, "legacy-secret")+ prevDevice := config.ChatwootDeviceID+ config.ChatwootDeviceID = ""+ t.Cleanup(func() { config.ChatwootDeviceID = prevDevice })+ chatwoot.InitClientRegistry(nil)+ t.Cleanup(func() { chatwoot.InitClientRegistry(nil) })++ manager := whatsapp.NewDeviceManager(nil, nil, nil)+ manager.AddDevice(whatsapp.NewDeviceInstance("only-device", nil, nil))+ stub := &chatwootReplySendStub{}+ handler := &ChatwootHandler{SendUsecase: stub, DeviceManager: manager, ChatStorageRepo: &deviceWebhookTestRepo{}}+ app := fiber.New()+ app.Post("/chatwoot/webhook", handler.HandleWebhook)++ body := `{"event":"message_created","message_type":"outgoing","content":"hello","account":{"id":1},` ++ `"conversation":{"id":5,"inbox_id":9,"meta":{"sender":{"phone_number":"+628123456789"}}}}`+ req := webhookAuthRequest{body: body, headers: map[string]string{"X-Chatwoot-Webhook-Secret": "legacy-secret"}}+ if got := postChatwootWebhook(t, app, req); got != fiber.StatusOK {+ t.Fatalf("status = %d, want 200", got)+ }+ if len(stub.texts) != 1 || stub.texts[0] != "hello" {+ t.Fatalf("SendText messages = %q, want [\"hello\"]", stub.texts)+ }+}diff --git a/src/ui/rest/chatwoot_webhook_route_auth_test.go b/src/ui/rest/chatwoot_webhook_route_auth_test.goindex aef0b55e..dcda1bf4 100644--- a/src/ui/rest/chatwoot_webhook_route_auth_test.go+++ b/src/ui/rest/chatwoot_webhook_route_auth_test.go@@ -298,11 +298,17 @@ func TestChatwootSharedWebhookEnforcesRoutedDeviceSecret(t *testing.T) {t.Run("with a global secret", func(t *testing.T) {const global = "global-secret"f := newRouteAuthFixture(t, global)- // Conversation 7 is linked to the support device (by storage JID), so- // it routes there whatever inbox the payload names.+ // Conversation 7 is linked to the support device (by storage JID) under+ // support's configuration. Only a payload for support's inbox uses the+ // link; another inbox's configuration routes its own payload and does+ // not take the link's device or recipient. Conversation 6 has only a+ // legacy config-0 (env-era) link, which per-device mode never uses.f.repo.links = []*domainChatStorage.ChatwootMessageLink{{- DeviceID: routeAuthSupportJID, WhatsAppChatJID: "[email protected]",+ DeviceID: routeAuthSupportJID, WhatsAppChatJID: "[email protected]",ChatwootConversationID: 7, ChatwootAccountID: 1, ChatwootConfigID: 2,+ }, {+ DeviceID: routeAuthSalesJID, WhatsAppChatJID: "[email protected]",+ ChatwootConversationID: 6, ChatwootAccountID: 1,}}runRouteAuthCases(t, f, []routeAuthCase{{name: "global secret for a protected device", inbox: 2, signWith: global, want: 401},@@ -314,9 +320,10 @@ func TestChatwootSharedWebhookEnforcesRoutedDeviceSecret(t *testing.T) {{name: "global secret, unknown inbox: acknowledged, nothing sent", inbox: 99, signWith: global, want: 200},{name: "unsigned, unknown inbox", inbox: 99, want: 401},{name: "device secret, unknown inbox", inbox: 99, signWith: routeAuthSalesSecret, want: 401},- {name: "linked conversation, global secret", inbox: 4, conv: 7, signWith: global, want: 401},- {name: "linked conversation, another device's secret", inbox: 2, conv: 7, signWith: routeAuthSalesSecret, want: 401},- {name: "linked conversation, the linked device's secret", inbox: 3, conv: 7, signWith: routeAuthSupportSecret, want: 200, wantSend: "support" + toContact},+ {name: "linked conversation from another inbox, global secret", inbox: 4, conv: 7, signWith: global, want: 200, wantSend: "open" + toContact},+ {name: "linked conversation from another inbox, that inbox's secret", inbox: 2, conv: 7, signWith: routeAuthSalesSecret, want: 200, wantSend: "sales" + toContact},+ {name: "linked conversation, the linked device's secret", inbox: 3, conv: 7, signWith: routeAuthSupportSecret, want: 200, wantSend: "support -> 628777777777"},+ {name: "legacy config-0 link is not used", inbox: 2, conv: 6, signWith: routeAuthSalesSecret, want: 200, wantSend: "sales" + toContact},})})@@ -363,7 +370,7 @@ func TestChatwootSharedWebhookDeleteEnforcesRoutedDeviceSecret(t *testing.T) {f := newRouteAuthFixture(t, global)f.repo.links = []*domainChatStorage.ChatwootMessageLink{{DeviceID: routeAuthSalesJID, WhatsAppMessageID: "WA-OUT-1", WhatsAppChatJID: "[email protected]",- ChatwootMessageID: 55, Direction: "outgoing",+ ChatwootMessageID: 55, Direction: "outgoing", ChatwootConfigID: 1,}}body := `{"event":"message_updated","message_type":"outgoing","id":55,"content_attributes":{"deleted":true},` +`"account":{"id":1},"conversation":{"id":5,"inbox_id":2}}`@@ -392,6 +399,21 @@ func TestChatwootSharedWebhookDeleteEnforcesRoutedDeviceSecret(t *testing.T) {}})}++ // The same Chatwoot message id linked under another configuration+ // (another server's, or legacy config 0) names an unrelated+ // customer's message: a delete through sales must not revoke it.+ for _, foreign := range []int64{0, 2} {+ f.repo.links[0].ChatwootConfigID = foreign+ for _, path := range []string{"", "/chatwoot/webhook/sales"} {+ chatwootReplays.reset()+ f.message.revoked = nil+ got := postChatwootWebhook(t, f.app, webhookAuthRequest{path: path, body: body, headers: chatwootSigned(routeAuthSalesSecret, body)})+ if got != fiber.StatusOK || len(f.message.revoked) != 0 {+ t.Errorf("link under config %d, path %q: status = %d, revoked = %v; want 200 and nothing revoked", foreign, path, got, f.message.revoked)+ }+ }+ }})}}