Skip to content

GOWA - WhatsApp REST API with support for UI, Multi Account, Webhooks, and MCP, and Chatwoot. Built with Golang for efficient memory use.

fix(webhook): close per-device webhook gaps from #671 review

Aldino Kemal23620dc2f054
diff --git a/docs/openapi.yaml b/docs/openapi.yaml
index 1f521d7e..5948f0a0 100644
--- a/docs/openapi.yaml
+++ b/docs/openapi.yaml
@@ -338,6 +338,18 @@ paths:
type: string
description: Optional device-specific webhook URL. If set, events for this device will be sent here instead of the global webhook.
example: 'https://device-webhook.example.com/handler'
+ webhook_secret:
+ type: string
+ description: Optional secret used to sign device-specific webhook payloads (HMAC).
+ example: 'super-secret-key'
+ webhook_events:
+ type: string
+ description: Optional comma-separated list of event names to forward to the device-specific webhook. Empty means all events.
+ example: 'message,message.ack'
+ webhook_insecure_skip_verify:
+ type: boolean
+ description: Optional. Skip TLS certificate verification when delivering to the device-specific webhook.
+ example: false
responses:
'200':
description: OK
diff --git a/src/domains/device/interfaces.go b/src/domains/device/interfaces.go
index 2547166d..e355e8e7 100644
--- a/src/domains/device/interfaces.go
+++ b/src/domains/device/interfaces.go
@@ -10,7 +10,9 @@ import (
type IDeviceUsecase interface {
ListDevices(ctx context.Context) ([]Device, error)
GetDevice(ctx context.Context, deviceID string) (*Device, error)
- AddDevice(ctx context.Context, deviceID string, webhookURL string) (*Device, error)
+ // AddDevice creates a new device. A non-nil webhook applies the full device-specific
+ // webhook configuration (url, secret, events, insecure_skip_verify) at creation time.
+ AddDevice(ctx context.Context, deviceID string, webhook *chatstorage.DeviceWebhookConfig) (*Device, error)
RemoveDevice(ctx context.Context, deviceID string) error
LoginDevice(ctx context.Context, deviceID string) error
LoginDeviceWithCode(ctx context.Context, deviceID string, phone string) (string, error)
diff --git a/src/infrastructure/whatsapp/event_handler.go b/src/infrastructure/whatsapp/event_handler.go
index f89dab82..0b5e95e4 100644
--- a/src/infrastructure/whatsapp/event_handler.go
+++ b/src/infrastructure/whatsapp/event_handler.go
@@ -313,7 +313,7 @@ func handlePresence(_ context.Context, evt *events.Presence) {
func handleAppState(_ context.Context, evt *events.AppState, deviceID string, client *whatsmeow.Client) {
log.Debugf("App state event: %+v / %+v", evt.Index, evt.SyncActionValue)
- if len(config.WhatsappWebhook) > 0 && isLabelAppState(evt) {
+ if isLabelAppState(evt) {
go func(e *events.AppState, c *whatsmeow.Client) {
webhookCtx, cancel := context.WithTimeout(context.Background(), 30*time.Second)
defer cancel()
diff --git a/src/infrastructure/whatsapp/event_label_test.go b/src/infrastructure/whatsapp/event_label_test.go
index ccb4938d..1f47c447 100644
--- a/src/infrastructure/whatsapp/event_label_test.go
+++ b/src/infrastructure/whatsapp/event_label_test.go
@@ -6,8 +6,11 @@ import (
"testing"
"time"
+ "github.com/aldinokemal/go-whatsapp-web-multidevice/config"
+ "github.com/aldinokemal/go-whatsapp-web-multidevice/domains/chatstorage"
"go.mau.fi/whatsmeow/proto/waSyncAction"
"go.mau.fi/whatsmeow/types/events"
+ waLog "go.mau.fi/whatsmeow/util/log"
"google.golang.org/protobuf/proto"
)
@@ -36,14 +39,14 @@ func TestBuildLabelAppStatePayload(t *testing.T) {
},
eventName: eventTypeLabelEdit,
payload: map[string]any{
- "label_id": "9",
- "name": "Accounts",
- "color": int32(8),
- "deleted": false,
- "order_index": int32(9),
- "is_active": true,
+ "label_id": "9",
+ "name": "Accounts",
+ "color": int32(8),
+ "deleted": false,
+ "order_index": int32(9),
+ "is_active": true,
"is_immutable": false,
- "type": "CUSTOM",
+ "type": "CUSTOM",
},
},
{
@@ -246,3 +249,56 @@ func assertPayloadEqual(t *testing.T, actual map[string]any, expected map[string
}
}
}
+
+// TestHandleAppState_DeviceWebhookOnly_ForwardsLabelEvent verifies that label appstate
+// events are forwarded when only a device-specific webhook is configured and no global
+// webhook is set. Regression test for the leftover global-webhook gate in handleAppState
+// that the per-device webhook feature (#671) removed from every other handler.
+func TestHandleAppState_DeviceWebhookOnly_ForwardsLabelEvent(t *testing.T) {
+ // The package logger is normally initialized by InitWaDB, which unit tests don't run.
+ if log == nil {
+ log = waLog.Noop
+ }
+
+ originalWebhooks := config.WhatsappWebhook
+ config.WhatsappWebhook = nil
+ defer func() { config.WhatsappWebhook = originalWebhooks }()
+
+ deviceWebhookURL := "https://device-only-webhook.example.com"
+ originalStorageForTest := webhookStorageForTest
+ webhookStorageForTest = func(deviceJID string) (*chatstorage.DeviceRecord, error) {
+ return &chatstorage.DeviceRecord{
+ DeviceID: deviceJID,
+ WebhookURL: &deviceWebhookURL,
+ }, nil
+ }
+ defer func() { webhookStorageForTest = originalStorageForTest }()
+
+ called := make(chan string, 1)
+ originalSubmit := submitWebhookFn
+ submitWebhookFn = func(_ context.Context, _ map[string]any, url string, _ *chatstorage.DeviceWebhookConfig) error {
+ called <- url
+ return nil
+ }
+ defer func() { submitWebhookFn = originalSubmit }()
+
+ evt := &events.AppState{
+ Index: []string{"label_edit", "9"},
+ SyncActionValue: &waSyncAction.SyncActionValue{
+ LabelEditAction: &waSyncAction.LabelEditAction{
+ Name: proto.String("Accounts"),
+ },
+ },
+ }
+
+ handleAppState(context.Background(), evt, "device_1", nil)
+
+ select {
+ case url := <-called:
+ if url != deviceWebhookURL {
+ t.Fatalf("expected forward to device webhook %s, got %s", deviceWebhookURL, url)
+ }
+ case <-time.After(2 * time.Second):
+ t.Fatal("label appstate event was not forwarded when only a device webhook is configured")
+ }
+}
diff --git a/src/infrastructure/whatsapp/webhook_forward.go b/src/infrastructure/whatsapp/webhook_forward.go
index 0545596c..5849bf07 100644
--- a/src/infrastructure/whatsapp/webhook_forward.go
+++ b/src/infrastructure/whatsapp/webhook_forward.go
@@ -88,8 +88,10 @@ func forwardPayloadToConfiguredWebhooks(ctx context.Context, payload map[string]
deviceJID, _ := payload["device_id"].(string)
webhookConfig, err := getWebhookConfigForDevice(deviceJID)
if err != nil {
- logrus.Warnf("Failed to get webhook config for device %s: %v", deviceJID, err)
- return err
+ // 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.
+ logrus.Warnf("Failed to get webhook config for device %s, falling back to global config: %v", deviceJID, err)
+ webhookConfig = nil
}
webhookAllowed := isEventWhitelistedForDevice(eventName, webhookConfig)
diff --git a/src/infrastructure/whatsapp/webhook_forward_test.go b/src/infrastructure/whatsapp/webhook_forward_test.go
index 6fe4dd2b..33692b58 100644
--- a/src/infrastructure/whatsapp/webhook_forward_test.go
+++ b/src/infrastructure/whatsapp/webhook_forward_test.go
@@ -460,6 +460,48 @@ func TestForwardPayloadToConfiguredWebhooks_DeviceWebhookCleared_FallsBackToGlob
}
}
+// TestForwardPayloadToConfiguredWebhooks_DeviceLookupError_FallsBackToGlobal verifies that a
+// transient storage error while resolving the device webhook config does not abort forwarding:
+// the event must still be delivered using the global webhook config. The function's contract is
+// to only return an error when all webhook deliveries fail — a config lookup failure is not a
+// delivery failure.
+func TestForwardPayloadToConfiguredWebhooks_DeviceLookupError_FallsBackToGlobal(t *testing.T) {
+ ctx := context.Background()
+ payload := map[string]any{
+ "foo": "bar",
+ "device_id": "[email protected]",
+ }
+
+ originalWebhooks := config.WhatsappWebhook
+ config.WhatsappWebhook = []string{"https://global-webhook.com"}
+ defer func() { config.WhatsappWebhook = originalWebhooks }()
+
+ originalStorageForTest := webhookStorageForTest
+ webhookStorageForTest = func(deviceJID string) (*chatstorage.DeviceRecord, error) {
+ return nil, errors.New("database is locked")
+ }
+ defer func() { webhookStorageForTest = originalStorageForTest }()
+
+ var calledURLs []string
+ originalSubmit := submitWebhookFn
+ submitWebhookFn = func(_ context.Context, _ map[string]any, url string, _ *chatstorage.DeviceWebhookConfig) error {
+ calledURLs = append(calledURLs, url)
+ return nil
+ }
+ defer func() { submitWebhookFn = originalSubmit }()
+
+ if err := forwardPayloadToConfiguredWebhooks(ctx, payload, "message"); err != nil {
+ t.Fatalf("device config lookup failure must not abort forwarding, got error: %v", err)
+ }
+
+ if len(calledURLs) != 1 {
+ t.Fatalf("expected 1 webhook call (global fallback), got %d: %v", len(calledURLs), calledURLs)
+ }
+ if calledURLs[0] != "https://global-webhook.com" {
+ t.Fatalf("expected global webhook, got %s", calledURLs[0])
+ }
+}
+
// TestForwardPayloadToConfiguredWebhooks_DeviceWebhookOnly_NoGlobal verifies that when
// no global webhook is configured but a device-specific webhook is set, events are
// forwarded to the device-specific webhook. This is the primary path aldinokemal asked
diff --git a/src/ui/rest/device.go b/src/ui/rest/device.go
index 1c854799..a3a1f0d1 100644
--- a/src/ui/rest/device.go
+++ b/src/ui/rest/device.go
@@ -58,8 +58,11 @@ func (handler *Device) GetDevice(c *fiber.Ctx) error {
func (handler *Device) AddDevice(c *fiber.Ctx) error {
var req struct {
- DeviceID string `json:"device_id"`
- WebhookURL string `json:"webhook_url"`
+ DeviceID string `json:"device_id"`
+ WebhookURL string `json:"webhook_url"`
+ WebhookSecret string `json:"webhook_secret"`
+ WebhookEvents string `json:"webhook_events"`
+ WebhookInsecureSkipVerify bool `json:"webhook_insecure_skip_verify"`
}
if err := c.BodyParser(&req); err != nil {
@@ -71,7 +74,17 @@ func (handler *Device) AddDevice(c *fiber.Ctx) error {
})
}
- device, err := handler.Service.AddDevice(c.UserContext(), req.DeviceID, req.WebhookURL)
+ var webhook *chatstorage.DeviceWebhookConfig
+ if req.WebhookURL != "" || req.WebhookSecret != "" || req.WebhookEvents != "" || req.WebhookInsecureSkipVerify {
+ webhook = &chatstorage.DeviceWebhookConfig{
+ WebhookURL: &req.WebhookURL,
+ WebhookSecret: req.WebhookSecret,
+ WebhookEvents: req.WebhookEvents,
+ WebhookInsecureSkipVerify: req.WebhookInsecureSkipVerify,
+ }
+ }
+
+ device, err := handler.Service.AddDevice(c.UserContext(), req.DeviceID, webhook)
utils.PanicIfNeeded(err)
result := map[string]any{
@@ -80,7 +93,12 @@ func (handler *Device) AddDevice(c *fiber.Ctx) error {
"jid": device.JID,
"state": device.State,
"created_at": device.CreatedAt,
- "webhook_url": req.WebhookURL,
+ }
+ if webhook != nil {
+ result["webhook_url"] = req.WebhookURL
+ result["webhook_secret"] = req.WebhookSecret
+ result["webhook_events"] = req.WebhookEvents
+ result["webhook_insecure_skip_verify"] = req.WebhookInsecureSkipVerify
}
return c.JSON(utils.ResponseData{
@@ -180,10 +198,10 @@ func (handler *Device) Status(c *fiber.Ctx) error {
func (handler *Device) UpdateDeviceWebhook(c *fiber.Ctx) error {
deviceID := c.Params("device_id")
var req struct {
- WebhookURL *string `json:"webhook_url"`
- WebhookSecret string `json:"webhook_secret"`
- WebhookEvents string `json:"webhook_events"`
- WebhookInsecureSkipVerify bool `json:"webhook_insecure_skip_verify"`
+ WebhookURL *string `json:"webhook_url"`
+ WebhookSecret string `json:"webhook_secret"`
+ WebhookEvents string `json:"webhook_events"`
+ WebhookInsecureSkipVerify bool `json:"webhook_insecure_skip_verify"`
}
if err := c.BodyParser(&req); err != nil {
@@ -205,9 +223,9 @@ func (handler *Device) UpdateDeviceWebhook(c *fiber.Ctx) error {
}
config := &chatstorage.DeviceWebhookConfig{
- WebhookURL: req.WebhookURL,
- WebhookSecret: req.WebhookSecret,
- WebhookEvents: req.WebhookEvents,
+ WebhookURL: req.WebhookURL,
+ WebhookSecret: req.WebhookSecret,
+ WebhookEvents: req.WebhookEvents,
WebhookInsecureSkipVerify: req.WebhookInsecureSkipVerify,
}
@@ -219,10 +237,10 @@ func (handler *Device) UpdateDeviceWebhook(c *fiber.Ctx) error {
Code: "SUCCESS",
Message: "Device webhook updated",
Results: map[string]any{
- "device_id": deviceID,
- "webhook_url": *req.WebhookURL,
- "webhook_secret": req.WebhookSecret,
- "webhook_events": req.WebhookEvents,
+ "device_id": deviceID,
+ "webhook_url": *req.WebhookURL,
+ "webhook_secret": req.WebhookSecret,
+ "webhook_events": req.WebhookEvents,
"webhook_insecure_skip_verify": req.WebhookInsecureSkipVerify,
},
})
@@ -246,9 +264,24 @@ func (handler *Device) GetDeviceWebhook(c *fiber.Ctx) error {
Results: map[string]any{
"device_id": deviceID,
"webhook_url": webhookURL,
- "webhook_secret": func() string { if config != nil { return config.WebhookSecret }; return "" }(),
- "webhook_events": func() string { if config != nil { return config.WebhookEvents }; return "" }(),
- "webhook_insecure_skip_verify": func() bool { if config != nil { return config.WebhookInsecureSkipVerify }; return false }(),
+ "webhook_secret": func() string {
+ if config != nil {
+ return config.WebhookSecret
+ }
+ return ""
+ }(),
+ "webhook_events": func() string {
+ if config != nil {
+ return config.WebhookEvents
+ }
+ return ""
+ }(),
+ "webhook_insecure_skip_verify": func() bool {
+ if config != nil {
+ return config.WebhookInsecureSkipVerify
+ }
+ return false
+ }(),
},
})
}
diff --git a/src/ui/rest/device_test.go b/src/ui/rest/device_test.go
new file mode 100644
index 00000000..37edac0a
--- /dev/null
+++ b/src/ui/rest/device_test.go
@@ -0,0 +1,115 @@
+package rest
+
+import (
+ "context"
+ "encoding/json"
+ "net/http"
+ "net/http/httptest"
+ "strings"
+ "testing"
+
+ "github.com/aldinokemal/go-whatsapp-web-multidevice/domains/chatstorage"
+ domainDevice "github.com/aldinokemal/go-whatsapp-web-multidevice/domains/device"
+ "github.com/aldinokemal/go-whatsapp-web-multidevice/ui/rest/middleware"
+ "github.com/gofiber/fiber/v2"
+)
+
+// addDeviceStubUsecase implements domainDevice.IDeviceUsecase by embedding the
+// interface while recording the arguments actually received by AddDevice.
+type addDeviceStubUsecase struct {
+ domainDevice.IDeviceUsecase
+ receivedDeviceID string
+ receivedWebhook *chatstorage.DeviceWebhookConfig
+}
+
+func (s *addDeviceStubUsecase) AddDevice(_ context.Context, deviceID string, webhook *chatstorage.DeviceWebhookConfig) (*domainDevice.Device, error) {
+ s.receivedDeviceID = deviceID
+ s.receivedWebhook = webhook
+ return &domainDevice.Device{ID: deviceID}, nil
+}
+
+func newAddDeviceTestApp(stub *addDeviceStubUsecase) *fiber.App {
+ app := fiber.New()
+ app.Use(middleware.Recovery())
+ controller := Device{Service: stub}
+ app.Post("/devices", controller.AddDevice)
+ return app
+}
+
+// TestAddDevice_ForwardsFullWebhookConfig verifies that POST /devices accepts the
+// complete webhook configuration (url, secret, events, insecure_skip_verify) that the
+// device manager UI sends, instead of silently dropping everything but webhook_url.
+func TestAddDevice_ForwardsFullWebhookConfig(t *testing.T) {
+ stub := &addDeviceStubUsecase{}
+ app := newAddDeviceTestApp(stub)
+
+ body := `{
+ "device_id": "dev1",
+ "webhook_url": "https://hook.example.com",
+ "webhook_secret": "s3cret",
+ "webhook_events": "message,message.ack",
+ "webhook_insecure_skip_verify": true
+ }`
+ req := httptest.NewRequest(http.MethodPost, "/devices", strings.NewReader(body))
+ req.Header.Set("Content-Type", "application/json")
+
+ resp, err := app.Test(req)
+ if err != nil {
+ t.Fatalf("request failed: %v", err)
+ }
+ if resp.StatusCode != http.StatusOK {
+ t.Fatalf("expected status 200, got %d", resp.StatusCode)
+ }
+
+ if stub.receivedDeviceID != "dev1" {
+ t.Fatalf("expected device_id dev1, got %q", stub.receivedDeviceID)
+ }
+ cfg := stub.receivedWebhook
+ if cfg == nil {
+ t.Fatal("expected webhook config to be forwarded to the usecase, got nil")
+ }
+ if cfg.WebhookURL == nil || *cfg.WebhookURL != "https://hook.example.com" {
+ t.Fatalf("expected webhook_url to be forwarded, got %v", cfg.WebhookURL)
+ }
+ if cfg.WebhookSecret != "s3cret" {
+ t.Fatalf("expected webhook_secret to be forwarded, got %q", cfg.WebhookSecret)
+ }
+ if cfg.WebhookEvents != "message,message.ack" {
+ t.Fatalf("expected webhook_events to be forwarded, got %q", cfg.WebhookEvents)
+ }
+ if !cfg.WebhookInsecureSkipVerify {
+ t.Fatal("expected webhook_insecure_skip_verify to be forwarded as true")
+ }
+}
+
+// TestAddDevice_NoWebhookFields verifies that a plain device creation without any
+// webhook fields passes a nil config to the usecase.
+func TestAddDevice_NoWebhookFields(t *testing.T) {
+ stub := &addDeviceStubUsecase{}
+ app := newAddDeviceTestApp(stub)
+
+ req := httptest.NewRequest(http.MethodPost, "/devices", strings.NewReader(`{"device_id":"dev2"}`))
+ req.Header.Set("Content-Type", "application/json")
+
+ resp, err := app.Test(req)
+ if err != nil {
+ t.Fatalf("request failed: %v", err)
+ }
+ if resp.StatusCode != http.StatusOK {
+ t.Fatalf("expected status 200, got %d", resp.StatusCode)
+ }
+
+ if stub.receivedWebhook != nil {
+ t.Fatalf("expected nil webhook config when no webhook fields sent, got %+v", stub.receivedWebhook)
+ }
+
+ var parsed struct {
+ Results map[string]any `json:"results"`
+ }
+ if err := json.NewDecoder(resp.Body).Decode(&parsed); err != nil {
+ t.Fatalf("failed to decode response: %v", err)
+ }
+ if parsed.Results["id"] != "dev2" {
+ t.Fatalf("expected result id dev2, got %v", parsed.Results["id"])
+ }
+}
diff --git a/src/usecase/device.go b/src/usecase/device.go
index c9cc3422..59570714 100644
--- a/src/usecase/device.go
+++ b/src/usecase/device.go
@@ -47,7 +47,7 @@ func (s *serviceDevice) GetDevice(_ context.Context, deviceID string) (*domainDe
return nil, fmt.Errorf("device %s not found", deviceID)
}
-func (s *serviceDevice) AddDevice(ctx context.Context, deviceID string, webhookURL string) (*domainDevice.Device, error) {
+func (s *serviceDevice) AddDevice(ctx context.Context, deviceID string, webhook *chatstorage.DeviceWebhookConfig) (*domainDevice.Device, error) {
if s.manager == nil {
return nil, fmt.Errorf("device manager not initialized")
}
@@ -57,13 +57,17 @@ func (s *serviceDevice) AddDevice(ctx context.Context, deviceID string, webhookU
return nil, err
}
- // Set device-specific webhook if provided
- if webhookURL != "" {
+ // Apply the device-specific webhook configuration if provided. Failures are
+ // surfaced instead of logged away: the caller was promised the webhook config,
+ // so a silent partial success would leave the API reporting a webhook that was
+ // never persisted.
+ if webhook != nil {
storage := s.manager.GetStorage()
- if storage != nil {
- if err := storage.SetDeviceWebhookURL(deviceID, &webhookURL); err != nil {
- logrus.Warnf("Failed to set webhook for device %s: %v", deviceID, err)
- }
+ if storage == nil {
+ return nil, fmt.Errorf("device %s created but storage is unavailable to save webhook config", deviceID)
+ }
+ if err := storage.SetDeviceWebhookConfig(deviceID, webhook); err != nil {
+ return nil, fmt.Errorf("device %s created but webhook config could not be saved: %w", deviceID, err)
}
}