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(webhook): retain slot policy after re-pairing and bound config reads (#931)
Aldino Kemaldc6229eb38f8
diff --git a/src/domains/chatstorage/interfaces.go b/src/domains/chatstorage/interfaces.goindex e54d2153..eeedadef 100644--- a/src/domains/chatstorage/interfaces.go+++ b/src/domains/chatstorage/interfaces.go@@ -153,7 +153,7 @@ type IChatStorageRepository interface {// SetDeviceWebhookConfig sets the full webhook configuration for a device.SetDeviceWebhookConfig(deviceID string, config *DeviceWebhookConfig) error// GetDeviceWebhookConfig retrieves the full webhook configuration for a device.- GetDeviceWebhookConfig(deviceID string) (*DeviceWebhookConfig, error)+ GetDeviceWebhookConfig(ctx context.Context, deviceID string) (*DeviceWebhookConfig, error)// Schema operationsInitializeSchema() errordiff --git a/src/infrastructure/chatstorage/sqlite_repository.go b/src/infrastructure/chatstorage/sqlite_repository.goindex 822afef2..2b22198a 100644--- a/src/infrastructure/chatstorage/sqlite_repository.go+++ b/src/infrastructure/chatstorage/sqlite_repository.go@@ -2167,13 +2167,13 @@ func (r *SQLiteRepository) SetDeviceWebhookConfig(deviceID string, config *domai// GetDeviceWebhookConfig retrieves the complete webhook configuration for a device.// Returns (nil, nil) if no device-specific webhook configuration is set.-func (r *SQLiteRepository) GetDeviceWebhookConfig(deviceID string) (*domainChatStorage.DeviceWebhookConfig, error) {+func (r *SQLiteRepository) GetDeviceWebhookConfig(ctx context.Context, deviceID string) (*domainChatStorage.DeviceWebhookConfig, error) {if strings.TrimSpace(deviceID) == "" {return nil, fmt.Errorf("device id is required")}var config domainChatStorage.DeviceWebhookConfigvar webhookURL *string- err := r.db.QueryRow(`+ err := r.db.QueryRowContext(ctx, `SELECT webhook_url, COALESCE(webhook_secret, ''), COALESCE(webhook_events, ''), COALESCE(webhook_insecure_skip_verify, FALSE)FROM devices WHERE device_id = ? LIMIT 1`, deviceID).Scan(&webhookURL, &config.WebhookSecret, &config.WebhookEvents, &config.WebhookInsecureSkipVerify)diff --git a/src/infrastructure/whatsapp/AGENTS.md b/src/infrastructure/whatsapp/AGENTS.mdindex 1fd1c316..8e35e1f7 100644--- a/src/infrastructure/whatsapp/AGENTS.md+++ b/src/infrastructure/whatsapp/AGENTS.md@@ -16,8 +16,9 @@ This package owns clients, device lifecycle, JIDs, events, presence, and forwardKeep work bounded and failures observable without blocking the event loop.Preserve the `shouldForwardReceipt` guard: contacts' linked-device receipts staydropped to prevent duplicates; only the account's own read receipts pass from any device.- Device events (`event_device.go`) take the webhook config (by companion JID first) and- session id from the emitting slot before returning, since `handleLoggedOut` forwards+ Device events (`event_device.go`) take the webhook config by stable slot ID with a+ bounded context-aware SQL lookup. They capture the session id before returning,+ since `handleLoggedOut` forwardsjust before `TriggerLoggedOut` clears the JID; delivery starts before the boundedwebsocket broadcast.- Chatwoot retries: `StartChatwootForwardRetryWorker` uses durable chat-storage jobsdiff --git a/src/infrastructure/whatsapp/chatstorage_wrapper.go b/src/infrastructure/whatsapp/chatstorage_wrapper.goindex aaaf396c..054b7466 100644--- a/src/infrastructure/whatsapp/chatstorage_wrapper.go+++ b/src/infrastructure/whatsapp/chatstorage_wrapper.go@@ -441,6 +441,6 @@ func (r *deviceChatStorage) SetDeviceWebhookConfig(deviceID string, config *doma}// GetDeviceWebhookConfig retrieves the complete webhook configuration for a device.-func (r *deviceChatStorage) GetDeviceWebhookConfig(deviceID string) (*domainChatStorage.DeviceWebhookConfig, error) {- return r.base.GetDeviceWebhookConfig(deviceID)+func (r *deviceChatStorage) GetDeviceWebhookConfig(ctx context.Context, deviceID string) (*domainChatStorage.DeviceWebhookConfig, error) {+ return r.base.GetDeviceWebhookConfig(ctx, deviceID)}diff --git a/src/infrastructure/whatsapp/device_manager_companion_test.go b/src/infrastructure/whatsapp/device_manager_companion_test.goindex 671adcb2..3fbcf869 100644--- a/src/infrastructure/whatsapp/device_manager_companion_test.go+++ b/src/infrastructure/whatsapp/device_manager_companion_test.go@@ -26,6 +26,15 @@ func (s *registryStubStorage) ListDeviceRecords() ([]*domainChatStorage.DeviceRereturn s.records, nil}+func (s *registryStubStorage) GetDeviceWebhookConfig(_ context.Context, id string) (*domainChatStorage.DeviceWebhookConfig, error) {+ for _, rec := range s.records {+ if rec.DeviceID == id {+ return webhookConfigFromRecord(rec), nil+ }+ }+ return nil, nil+}+// countStoreRows returns how many device rows in the container share the NonAD number.func countStoreRows(t *testing.T, ctx context.Context, m *DeviceManager, nonAD string) int {t.Helper()diff --git a/src/infrastructure/whatsapp/event_device.go b/src/infrastructure/whatsapp/event_device.goindex 1e7a63d2..28465cba 100644--- a/src/infrastructure/whatsapp/event_device.go+++ b/src/infrastructure/whatsapp/event_device.go@@ -119,7 +119,9 @@ func forwardDeviceEvent(ctx context.Context, eventName string, instance *DeviceIif jid := instance.JID(); jid != "" {body["device_id"] = jid}- webhookConfig := instanceWebhookConfig(instance)+ lookupCtx, cancelLookup := context.WithTimeout(context.WithoutCancel(ctx), time.Second)+ webhookConfig := instanceWebhookConfig(lookupCtx, instance)+ cancelLookup()go func() {webhookCtx, cancel := context.WithTimeout(context.WithoutCancel(ctx), 30*time.Second)@@ -130,29 +132,20 @@ func forwardDeviceEvent(ctx context.Context, eventName string, instance *DeviceI}()}-// instanceWebhookConfig resolves the slot's webhook config by its exact companion JID-// first: two slots on one number share the bare JID, which the record lookup rejects as-// ambiguous. The bare JID is the fallback for records saved without a companion JID, and-// only counts when the record it finds is this slot's: a sibling whose record holds the-// shared JID would otherwise lend this slot its webhook. Anything else uses the global config.-func instanceWebhookConfig(instance *DeviceInstance) *domainChatStorage.DeviceWebhookConfig {- if adJID := instance.ADJID(); adJID != "" {- if webhookConfig := resolveWebhookConfig(adJID); webhookConfig != nil {- return webhookConfig- }- }-- jid := instance.JID()- if jid == "" {+// instanceWebhookConfig uses the stable slot ID, which survives logout and re-pairing.+// A companion or bare JID may be stale or belong to another slot on the same number.+func instanceWebhookConfig(ctx context.Context, instance *DeviceInstance) *domainChatStorage.DeviceWebhookConfig {+ repo := instance.GetChatStorage()+ if repo == nil {return nil}- record, err := getDeviceRecordForTest(jid)+ webhookConfig, err := repo.GetDeviceWebhookConfig(ctx, instance.ID())if err != nil {- logrus.Warnf("Failed to get webhook config for device %s, falling back to global config: %v", jid, err)+ logrus.Warnf("Failed to get webhook config for device %s, falling back to global config: %v", instance.ID(), err)return nil}- if record == nil || record.DeviceID != instance.ID() {+ if webhookConfig == nil || webhookConfig.WebhookURL == nil || *webhookConfig.WebhookURL == "" {return nil}- return webhookConfigFromRecord(record)+ return webhookConfig}diff --git a/src/infrastructure/whatsapp/event_device_export_test.go b/src/infrastructure/whatsapp/event_device_export_test.gonew file mode 100644index 00000000..d6701bd1--- /dev/null+++ b/src/infrastructure/whatsapp/event_device_export_test.go@@ -0,0 +1,20 @@+package whatsapp++import (+ "context"+ domain "github.com/aldinokemal/go-whatsapp-web-multidevice/domains/chatstorage"+ "testing"+)++var HandleDeviceEventForTest = handler++func CaptureDeviceEventsForTest(t *testing.T, repo domain.IChatStorageRepository, receive func(map[string]any, string, *domain.DeviceWebhookConfig)) {+ t.Helper()+ oldLookup, oldSubmit := webhookStorageForTest, submitWebhookFn+ webhookStorageForTest = repo.GetDeviceRecordByJID+ submitWebhookFn = func(_ context.Context, body map[string]any, url string, cfg *domain.DeviceWebhookConfig) error {+ receive(body, url, cfg)+ return nil+ }+ t.Cleanup(func() { webhookStorageForTest, submitWebhookFn = oldLookup, oldSubmit })+}diff --git a/src/infrastructure/whatsapp/event_device_sql_test.go b/src/infrastructure/whatsapp/event_device_sql_test.gonew file mode 100644index 00000000..692449d5--- /dev/null+++ b/src/infrastructure/whatsapp/event_device_sql_test.go@@ -0,0 +1,139 @@+package whatsapp_test++import (+ "context"+ "database/sql"+ "github.com/aldinokemal/go-whatsapp-web-multidevice/config"+ domain "github.com/aldinokemal/go-whatsapp-web-multidevice/domains/chatstorage"+ storage "github.com/aldinokemal/go-whatsapp-web-multidevice/infrastructure/chatstorage"+ wa "github.com/aldinokemal/go-whatsapp-web-multidevice/infrastructure/whatsapp"+ "github.com/aldinokemal/go-whatsapp-web-multidevice/pkg/sqlite"+ "github.com/aldinokemal/go-whatsapp-web-multidevice/ui/websocket"+ "github.com/stretchr/testify/require"+ "go.mau.fi/whatsmeow"+ "go.mau.fi/whatsmeow/store"+ "go.mau.fi/whatsmeow/types"+ "go.mau.fi/whatsmeow/types/events"+ "path/filepath"+ "testing"+ "time"+)++func eventSQLFixture(t *testing.T) (*sql.DB, domain.IChatStorageRepository, <-chan string) {+ t.Helper()+ db, err := sql.Open(sqlite.DriverName, filepath.Join(t.TempDir(), "events.db"))+ require.NoError(t, err)+ t.Cleanup(func() { db.Close() })+ repo := storage.NewStorageRepository(db)+ require.NoError(t, repo.InitializeSchema())+ oldURLs, oldEvents := config.WhatsappWebhook, config.WhatsappWebhookEvents+ config.WhatsappWebhook = []string{"https://global.test/hook"}+ config.WhatsappWebhookEvents = nil+ t.Cleanup(func() { config.WhatsappWebhook, config.WhatsappWebhookEvents = oldURLs, oldEvents })+ got := make(chan string, 8)+ wa.CaptureDeviceEventsForTest(t, repo, func(_ map[string]any, url string, _ *domain.DeviceWebhookConfig) { got <- url })+ return db, repo, got+}++func TestDeviceEventSQLRepairedSlotKeepsWebhook(t *testing.T) {+ _, repo, got := eventSQLFixture(t)+ const slot = "628123:[email protected]"+ ownURL, siblingURL := "https://own.test/hook", "https://sibling.test/hook"+ require.NoError(t, repo.SaveDeviceRecord(&domain.DeviceRecord{DeviceID: slot}))+ require.NoError(t, repo.SetDeviceWebhookConfig(slot, &domain.DeviceWebhookConfig{WebhookURL: &ownURL}))+ require.NoError(t, repo.SaveDeviceRecord(&domain.DeviceRecord{DeviceID: "sibling", JID: "[email protected]", ADJID: "628123:[email protected]", WebhookURL: &siblingURL}))+ jid := types.NewADJID("628123", 0, 7)+ inst := wa.NewDeviceInstance(slot, whatsmeow.NewClient(&store.Device{ID: &jid}, nil), repo)+ done := make(chan struct{})+ go func() {+ wa.HandleDeviceEventForTest(context.Background(), inst, &events.TemporaryBan{Code: events.TempBanBlockedByUsers})+ close(done)+ }()+ select {+ case <-websocket.Broadcast:+ case <-time.After(3 * time.Second):+ t.Fatal("missing broadcast")+ }+ <-done+ select {+ case url := <-got:+ require.Equal(t, ownURL, url)+ case <-time.After(3 * time.Second):+ t.Fatal("missing webhook")+ }+}++func TestDeviceEventSQLBlockedLookupDoesNotHoldLogout(t *testing.T) {+ db, repo, got := eventSQLFixture(t)+ require.NoError(t, repo.SaveDeviceRecord(&domain.DeviceRecord{DeviceID: "slot", JID: "[email protected]"}))+ db.SetMaxOpenConns(1)+ conn, err := db.Conn(context.Background())+ require.NoError(t, err)+ defer conn.Close()+ jid := types.NewADJID("628123", 0, 7)+ inst := wa.NewDeviceInstance("slot", whatsmeow.NewClient(&store.Device{ID: &jid}, nil), repo)+ reset, done := make(chan struct{}), make(chan struct{})+ inst.SetOnLoggedOut(func(string) { inst.ResetClient(); close(reset) })+ go func() { wa.HandleDeviceEventForTest(context.Background(), inst, &events.LoggedOut{}); close(done) }()+ select {+ case <-reset:+ case <-time.After(2 * time.Second):+ conn.Close()+ <-reset+ <-websocket.Broadcast+ <-done+ <-got+ t.Fatal("blocked SQL lookup held logout beyond its budget")+ }+ <-websocket.Broadcast+ <-done+ select {+ case url := <-got:+ require.Equal(t, "https://global.test/hook", url)+ case <-time.After(time.Second):+ t.Fatal("missing fallback webhook")+ }+ require.Empty(t, inst.JID())+}++func TestDeviceEventSQLWebhookPolicy(t *testing.T) {+ for _, tc := range []struct{ name, url, events, want string }{+ {"configured", "https://own.test/hook", "device.temporary_ban", "https://own.test/hook"},+ {"filtered", "https://own.test/hook", "message", ""},+ {"empty URL uses global policy", "", "message", "https://global.test/hook"},+ } {+ t.Run(tc.name, func(t *testing.T) {+ _, repo, _ := eventSQLFixture(t)+ require.NoError(t, repo.SaveDeviceRecord(&domain.DeviceRecord{DeviceID: "slot"}))+ require.NoError(t, repo.SetDeviceWebhookConfig("slot", &domain.DeviceWebhookConfig{WebhookURL: &tc.url, WebhookEvents: tc.events, WebhookSecret: "device-secret", WebhookInsecureSkipVerify: true}))+ type delivery struct {+ url string+ cfg *domain.DeviceWebhookConfig+ }+ got := make(chan delivery, 1)+ wa.CaptureDeviceEventsForTest(t, repo, func(_ map[string]any, url string, cfg *domain.DeviceWebhookConfig) { got <- delivery{url, cfg} })+ inst := wa.NewDeviceInstance("slot", nil, repo)+ ctx, cancel := context.WithCancel(context.Background())+ cancel()+ done := make(chan struct{})+ go func() {+ wa.HandleDeviceEventForTest(ctx, inst, &events.TemporaryBan{Code: events.TempBanBlockedByUsers})+ close(done)+ }()+ <-websocket.Broadcast+ <-done+ select {+ case d := <-got:+ require.Equal(t, tc.want, d.url)+ if tc.url == "" {+ require.Nil(t, d.cfg)+ } else {+ require.Equal(t, "device-secret", d.cfg.WebhookSecret)+ require.True(t, d.cfg.WebhookInsecureSkipVerify)+ }+ case <-time.After(100 * time.Millisecond):+ require.Empty(t, tc.want, "missing configured delivery")+ }+ })+ }+}diff --git a/src/infrastructure/whatsapp/event_device_test.go b/src/infrastructure/whatsapp/event_device_test.goindex 0dda2083..c7a6af0f 100644--- a/src/infrastructure/whatsapp/event_device_test.go+++ b/src/infrastructure/whatsapp/event_device_test.go@@ -2,7 +2,6 @@ package whatsappimport ("context"- "sync/atomic""testing""time"@@ -171,7 +170,7 @@ func TestHandlerReachoutTimelockBroadcastsAndForwards(t *testing.T) {}// The keep-slot reset that a remote logout triggers clears the device's JID, and the-// webhook config is found by that JID. The logout webhook must still+// webhook config belongs to its stable slot ID. The logout webhook must still// reach a device-only webhook, addressed to the JID the device had.func TestHandlerLoggedOutForwardsWithIdentityFromBeforeReset(t *testing.T) {got := captureDeviceWebhooks(t)@@ -179,18 +178,11 @@ func TestHandlerLoggedOutForwardsWithIdentityFromBeforeReset(t *testing.T) {const jid = "[email protected]"deviceURL := "https://device.example.test/webhook"- var reset atomic.Bool- webhookStorageForTest = func(deviceJID string) (*domainChatStorage.DeviceRecord, error) {- if reset.Load() || deviceJID != jid {- return nil, nil- }- return &domainChatStorage.DeviceRecord{DeviceID: "slot-out", JID: jid, WebhookURL: &deviceURL}, nil- }inst := &DeviceInstance{id: "slot-out", jid: jid, createdAt: time.Now()}// Stands in for the device manager's keep-slot callback.+ inst.SetChatStorage(deviceEventConfigRepo{records: []*domainChatStorage.DeviceRecord{{DeviceID: "slot-out", WebhookURL: &deviceURL}}})inst.SetOnLoggedOut(func(string) {- reset.Store(true)inst.ResetClient()})@@ -216,7 +208,7 @@ func TestHandlerLoggedOutForwardsWithIdentityFromBeforeReset(t *testing.T) {// Two slots linked to one number share the bare JID. The record lookup rejects a shared// JID as ambiguous, and a JID-to-session lookup can return the sibling, so a device event-// must be routed by the emitting slot's companion JID and carry that slot's id.+// must be routed by the emitting slot ID and carry that slot's id.func TestDeviceEventRoutesSharedNumberToEmittingSlot(t *testing.T) {got := captureDeviceWebhooks(t)config.WhatsappWebhook = nil@@ -227,28 +219,9 @@ func TestDeviceEventRoutesSharedNumberToEmittingSlot(t *testing.T) {{DeviceID: "slot-a", JID: bareJID, ADJID: "6284444444444:[email protected]", WebhookURL: &urlA},{DeviceID: "slot-b", JID: bareJID, ADJID: "6284444444444:[email protected]", WebhookURL: &urlB},}- // Mirrors GetDeviceRecordByJID: match jid or ad_jid, and ignore an ambiguous match.- webhookStorageForTest = func(deviceJID string) (*domainChatStorage.DeviceRecord, error) {- var matches []*domainChatStorage.DeviceRecord- for _, rec := range records {- if rec.JID == deviceJID || rec.ADJID == deviceJID {- matches = append(matches, rec)- }- }- if len(matches) != 1 {- return nil, nil- }- return matches[0], nil- }- // Mirrors getDeviceByJID resolving the shared bare JID to the first slot.- sessionIDForJIDFn = func(deviceJID string) string {- if deviceJID == bareJID {- return "slot-a"- }- return ""- }slotB := &DeviceInstance{id: "slot-b", jid: bareJID, adJID: "6284444444444:[email protected]", createdAt: time.Now()}+ slotB.SetChatStorage(deviceEventConfigRepo{records: records})go handler(context.Background(), slotB, &events.TemporaryBan{Code: events.TempBanSentTooManySameMessage})recvBroadcast(t)@@ -296,14 +269,9 @@ func TestDeviceEventIgnoresSiblingRecordFoundByBareJID(t *testing.T) {const bareJID = "[email protected]"siblingURL := "https://slot-a.example.test/webhook"sibling := &domainChatStorage.DeviceRecord{DeviceID: "slot-a", JID: bareJID, ADJID: "6286666666666:[email protected]", WebhookURL: &siblingURL}- webhookStorageForTest = func(deviceJID string) (*domainChatStorage.DeviceRecord, error) {- if deviceJID == sibling.JID || deviceJID == sibling.ADJID {- return sibling, nil- }- return nil, nil- }slotB := &DeviceInstance{id: "slot-b", jid: bareJID, adJID: "6286666666666:[email protected]", createdAt: time.Now()}+ slotB.SetChatStorage(deviceEventConfigRepo{records: []*domainChatStorage.DeviceRecord{sibling}})go handler(context.Background(), slotB, &events.TemporaryBan{Code: events.TempBanBlockedByUsers})recvBroadcast(t)@@ -311,3 +279,18 @@ func TestDeviceEventIgnoresSiblingRecordFoundByBareJID(t *testing.T) {assert.Equal(t, "https://global.example.test/webhook", delivered.url)assert.Equal(t, "slot-b", delivered.body["session_id"])}++// deviceEventConfigRepo adapts the existing record fixtures to the slot storage API.+type deviceEventConfigRepo struct {+ domainChatStorage.IChatStorageRepository+ records []*domainChatStorage.DeviceRecord+}++func (r deviceEventConfigRepo) GetDeviceWebhookConfig(_ context.Context, id string) (*domainChatStorage.DeviceWebhookConfig, error) {+ for _, rec := range r.records {+ if rec.DeviceID == id {+ return webhookConfigFromRecord(rec), nil+ }+ }+ return nil, nil+}diff --git a/src/infrastructure/whatsapp/webhook_forward.go b/src/infrastructure/whatsapp/webhook_forward.goindex 9823bd13..355e36e7 100644--- a/src/infrastructure/whatsapp/webhook_forward.go+++ b/src/infrastructure/whatsapp/webhook_forward.go@@ -181,16 +181,6 @@ func forwardPayloadToConfiguredWebhooks(ctx context.Context, payload map[string]return forwardPayloadWithWebhookConfig(ctx, payload, eventName, webhookConfig)}-// resolveWebhookConfig returns the device-specific webhook config, or nil to use the global one.-func resolveWebhookConfig(deviceJID string) *domainChatStorage.DeviceWebhookConfig {- webhookConfig, err := getWebhookConfigForDevice(deviceJID)- if err != nil {- logrus.Warnf("Failed to get webhook config for device %s, falling back to global config: %v", deviceJID, err)- return nil- }- return webhookConfig-}-// forwardPayloadWithWebhookConfig is forwardPayloadToConfiguredWebhooks with the device's// webhook config already resolved, for callers that must look it up before the device// record changes.diff --git a/src/usecase/device.go b/src/usecase/device.goindex 0544d5a8..70100fea 100644--- a/src/usecase/device.go+++ b/src/usecase/device.go@@ -327,7 +327,7 @@ func (s *serviceDevice) GetDeviceWebhookConfig(ctx context.Context, deviceID strreturn nil, fmt.Errorf("storage not available")}- config, err := storage.GetDeviceWebhookConfig(deviceID)+ config, err := storage.GetDeviceWebhookConfig(ctx, deviceID)if err != nil {return nil, fmt.Errorf("failed to get device webhook config: %w", err)}