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
feat(webhook): let a per-device webhook add to the global targets instead of replacing them (#842)
Kizuno1807361dcfb347
diff --git a/docs/webhook-payload.md b/docs/webhook-payload.mdindex 3b68d4ac..72da552f 100644--- a/docs/webhook-payload.md+++ b/docs/webhook-payload.md@@ -109,6 +109,11 @@ [email protected],[email protected]entry is an **exact** JID match.- Empty/unset (default) forwards everything.- Independent from the Chatwoot integration, which keeps its own `CHATWOOT_IGNORE_JIDS`.+- `WHATSAPP_WEBHOOK_DEVICE_MERGE_GLOBAL=true` (`--webhook-device-merge-global`) changes what a per-device+ `webhook_url` means: instead of replacing the global `WHATSAPP_WEBHOOK` targets it is added to them. The+ device URL is signed with the device's `webhook_secret` and filtered by its `webhook_events`; the global+ URLs keep the global secret and `WHATSAPP_WEBHOOK_EVENTS`. The ignore-JID rules above apply to both. A+ global URL that equals the device URL is delivered once. Default `false` keeps the replace behaviour.- `@g.us` is the recommended way to mute groups (it matches the group `chat_id`). The`@s.whatsapp.net` wildcard matches the **sender** too, so it also suppresses group messages (whose`from` is the participant's `@s.whatsapp.net` JID) — use exact JIDs if you only want to mute specificdiff --git a/readme.md b/readme.mdindex a331c111..607b72d0 100644--- a/readme.md+++ b/readme.md@@ -144,6 +144,10 @@ Download:- When a device has a custom webhook, events for that device are sent to the device-specific URL.- When no device webhook is set, events fall back to the global webhook (`--webhook`).- Set `webhook_url` to an empty string with `PATCH` to clear it and use the global webhook.+ - Set `WHATSAPP_WEBHOOK_DEVICE_MERGE_GLOBAL=true` (or `--webhook-device-merge-global=true`) to make a+ device webhook an addition instead of a replacement: the global `--webhook` URLs still receive the+ device's events (signed with the global secret, filtered by `WHATSAPP_WEBHOOK_EVENTS`) while the+ device URL keeps its own secret and event filter.- **Webhook signatures** — Webhook requests include an HMAC-SHA-256 signature in the `X-Hub-Signature-256`header, generated with the default key `secret`.@@ -258,6 +262,7 @@ To use environment variables:| `WHATSAPP_WEBHOOK_INSECURE_SKIP_VERIFY` | Skip TLS verification for webhooks (insecure) | `false` | `WHATSAPP_WEBHOOK_INSECURE_SKIP_VERIFY=true` || `WHATSAPP_WEBHOOK_EVENTS` | Whitelist of events to forward (comma-separated, empty = all) | - | `WHATSAPP_WEBHOOK_EVENTS=message,message.ack` || `WHATSAPP_WEBHOOK_IGNORE_JIDS` | JIDs/wildcards to skip when forwarding (comma-separated) | - | `[email protected]` |+| `WHATSAPP_WEBHOOK_DEVICE_MERGE_GLOBAL` | Per-device webhook adds to the global URLs instead of replacing them | `false` | `WHATSAPP_WEBHOOK_DEVICE_MERGE_GLOBAL=true` || `WHATSAPP_ACCOUNT_VALIDATION` | Enable account validation | `true` | `WHATSAPP_ACCOUNT_VALIDATION=false` || `WHATSAPP_PRESENCE_ON_CONNECT` | Presence on connect: `available`, `unavailable`, or `none` | `unavailable` | `WHATSAPP_PRESENCE_ON_CONNECT=unavailable` || `WHATSAPP_PROXY` | Outbound proxy for the WhatsApp WebSocket (SOCKS5/HTTP/HTTPS) | - | `WHATSAPP_PROXY=socks5://user:pass@host:1080` |diff --git a/src/.env.example b/src/.env.exampleindex c4c39ef8..73d37eb8 100644--- a/src/.env.example+++ b/src/.env.example@@ -57,6 +57,8 @@ WHATSAPP_WEBHOOK_EVENTS=message,message.reaction,message.revoked,message.edited,# Comma-separated WhatsApp JIDs (or "@g.us"/"@s.whatsapp.net"/"@lid" wildcards) to skip when forwarding to the webhook.# Example: "@g.us" drops all group traffic; add exact JIDs to mute specific chats/senders.WHATSAPP_WEBHOOK_IGNORE_JIDS=+# When a device has its own webhook (PATCH /devices/:id/webhook), also deliver its events to the global WHATSAPP_WEBHOOK URLs.+WHATSAPP_WEBHOOK_DEVICE_MERGE_GLOBAL=falseWHATSAPP_WEBHOOK_INCLUDE_OUTGOING=falseWHATSAPP_ACCOUNT_VALIDATION=trueWHATSAPP_PRESENCE_ON_CONNECT=unavailablediff --git a/src/cmd/root.go b/src/cmd/root.goindex 3d5aa6f4..4624c99a 100644--- a/src/cmd/root.go+++ b/src/cmd/root.go@@ -184,6 +184,9 @@ func initEnvConfig() {}config.WhatsappWebhookIgnoreJids = jids}+ if viper.IsSet("whatsapp_webhook_device_merge_global") {+ config.WhatsappWebhookDeviceMergeGlobal = viper.GetBool("whatsapp_webhook_device_merge_global")+ }if viper.IsSet("whatsapp_account_validation") {config.WhatsappAccountValidation = viper.GetBool("whatsapp_account_validation")}@@ -456,6 +459,12 @@ func initFlags() {config.WhatsappWebhookIgnoreJids,`comma-separated WhatsApp JIDs (or "@g.us"/"@s.whatsapp.net"/"@lid" wildcards) to skip when forwarding to webhooks --webhook-ignore-jids <list> | example: --webhook-ignore-jids="@g.us,[email protected]"`,)+ rootCmd.PersistentFlags().BoolVarP(+ &config.WhatsappWebhookDeviceMergeGlobal,+ "webhook-device-merge-global", "",+ config.WhatsappWebhookDeviceMergeGlobal,+ `also deliver a device's events to the global --webhook URLs when that device has its own webhook (default: device webhook replaces the global ones) --webhook-device-merge-global <true/false> | example: --webhook-device-merge-global=true`,+ )rootCmd.PersistentFlags().BoolVarP(&config.WhatsappAccountValidation,"account-validation", "",diff --git a/src/config/settings.go b/src/config/settings.goindex 65e69742..41277821 100644--- a/src/config/settings.go+++ b/src/config/settings.go@@ -50,6 +50,7 @@ var (WhatsappWebhookInsecureSkipVerify = false // Skip TLS certificate verification for webhooks (insecure)WhatsappWebhookEvents []string // Whitelist of events to forward to webhook (empty = all events)WhatsappWebhookIgnoreJids []string // JIDs (or "@g.us"/"@s.whatsapp.net"/"@lid" wildcards) to skip when forwarding to webhooks+ WhatsappWebhookDeviceMergeGlobal = false // Per-device webhook adds to the global WHATSAPP_WEBHOOK targets instead of replacing themWhatsappAutoRejectCall = false // Auto-reject incoming callsWhatsappLogLevel = "ERROR"WhatsappSettingMaxImageSize int64 = 20000000 // 20MBdiff --git a/src/infrastructure/whatsapp/webhook_forward.go b/src/infrastructure/whatsapp/webhook_forward.goindex e5d5a44c..9ca966a1 100644--- a/src/infrastructure/whatsapp/webhook_forward.go+++ b/src/infrastructure/whatsapp/webhook_forward.go@@ -5,6 +5,7 @@ import ("encoding/json""fmt""hash/fnv"+ "slices""strings""sync""time"@@ -107,26 +108,37 @@ func forwardPayloadToConfiguredWebhooks(ctx context.Context, payload map[string]webhookConfig = nil}- webhookAllowed := isEventWhitelistedForDevice(eventName, webhookConfig) &&- !shouldIgnoreWebhookJID(payload)+ jidAllowed := !shouldIgnoreWebhookJID(payload)+ webhookAllowed := jidAllowed && isEventWhitelistedForDevice(eventName, webhookConfig)chatwootAllowed := config.ChatwootEnabled && shouldForwardEventToChatwoot(eventName) && isEventWhitelistedForChatwoot(eventName)- if !webhookAllowed && !chatwootAllowed {- logrus.Debugf("Skipping event %s - not allowed for webhooks or Chatwoot", eventName)- return nil- }-webhookURLs := getWebhookURLsFromConfig(webhookConfig)if len(webhookURLs) == 0 {webhookURLs = config.WhatsappWebhook}+ // With WHATSAPP_WEBHOOK_DEVICE_MERGE_GLOBAL a per-device webhook is an addition+ // to the global targets instead of a replacement: the global URLs still get the+ // event, signed with the global secret and filtered by the global event+ // whitelist, while the device URL keeps its own secret and event filter.+ var globalURLs []string+ if config.WhatsappWebhookDeviceMergeGlobal && webhookConfig != nil && jidAllowed &&+ isEventWhitelistedForDevice(eventName, nil) {+ globalURLs = globalWebhookURLsExcluding(webhookURLs)+ }+ globalAllowed := len(globalURLs) > 0++ if !webhookAllowed && !globalAllowed && !chatwootAllowed {+ logrus.Debugf("Skipping event %s - not allowed for webhooks or Chatwoot", eventName)+ return nil+ }+// Enrich the payload with the operator-facing session id so multi-tenant// consumers can correlate a webhook (whose device_id is the WhatsApp JID)// back to the session id they registered via POST /devices. Done here,// synchronously, before the Chatwoot goroutine is spawned below, so the// shared payload map is never mutated concurrently.- if webhookAllowed {+ if webhookAllowed || globalAllowed {addWebhookSessionID(payload)}@@ -136,6 +148,19 @@ func forwardPayloadToConfiguredWebhooks(ctx context.Context, payload map[string]} else {logrus.Debugf("Skipping event %s for configured webhooks, but allowing Chatwoot", eventName)}+ if globalAllowed {+ globalErr := forwardToWebhooks(ctx, payload, eventName, globalURLs, nil)+ // Same contract as forwardToWebhooks: only report failure when every+ // target that was attempted failed.+ switch {+ case !webhookAllowed:+ webhookErr = globalErr+ case webhookErr != nil && globalErr != nil:+ webhookErr = fmt.Errorf("%w; global: %v", webhookErr, globalErr)+ default:+ webhookErr = nil+ }+ }if chatwootAllowed {go forwardToChatwoot(ctx, payload, eventName)@@ -192,6 +217,23 @@ func getWebhookURLsFromConfig(config *domainChatStorage.DeviceWebhookConfig) []sreturn []string{*config.WebhookURL}}+// globalWebhookURLsExcluding returns the global WHATSAPP_WEBHOOK targets minus any+// URL already covered by the device-specific delivery, so a device whose webhook+// duplicates a global URL is not hit twice for the same event.+func globalWebhookURLsExcluding(deviceURLs []string) []string {+ if len(config.WhatsappWebhook) == 0 {+ return nil+ }+ urls := make([]string, 0, len(config.WhatsappWebhook))+ for _, url := range config.WhatsappWebhook {+ if slices.Contains(deviceURLs, url) {+ continue+ }+ urls = append(urls, url)+ }+ return urls+}+// isEventWhitelistedForDevice checks if an event is whitelisted for a specific device.// Uses device-specific events if set, otherwise falls back to global config.func isEventWhitelistedForDevice(eventName string, deviceConfig *domainChatStorage.DeviceWebhookConfig) bool {diff --git a/src/infrastructure/whatsapp/webhook_forward_device_merge_test.go b/src/infrastructure/whatsapp/webhook_forward_device_merge_test.gonew file mode 100644index 00000000..afaec84b--- /dev/null+++ b/src/infrastructure/whatsapp/webhook_forward_device_merge_test.go@@ -0,0 +1,144 @@+package whatsapp++import (+ "context"+ "errors"+ "sort"+ "testing"++ "github.com/aldinokemal/go-whatsapp-web-multidevice/config"+ domainChatStorage "github.com/aldinokemal/go-whatsapp-web-multidevice/domains/chatstorage"+)++type mergeDelivery struct {+ url string+ secret string+}++// runDeviceMergeForward runs the forwarder for a device that has its own webhook+// (deviceURL / deviceEvents) while the global config holds globalURLs, and reports+// every delivery attempted together with the secret each one was signed with.+func runDeviceMergeForward(t *testing.T, merge bool, globalURLs []string, globalEvents []string, deviceURL, deviceEvents, eventName string, failURLs map[string]bool) ([]mergeDelivery, error) {+ t.Helper()++ originalWebhooks := config.WhatsappWebhook+ originalEvents := config.WhatsappWebhookEvents+ originalIgnore := config.WhatsappWebhookIgnoreJids+ originalMerge := config.WhatsappWebhookDeviceMergeGlobal+ config.WhatsappWebhook = globalURLs+ config.WhatsappWebhookEvents = globalEvents+ config.WhatsappWebhookIgnoreJids = nil+ config.WhatsappWebhookDeviceMergeGlobal = merge+ defer func() {+ config.WhatsappWebhook = originalWebhooks+ config.WhatsappWebhookEvents = originalEvents+ config.WhatsappWebhookIgnoreJids = originalIgnore+ config.WhatsappWebhookDeviceMergeGlobal = originalMerge+ }()++ originalStorage := webhookStorageForTest+ webhookStorageForTest = func(deviceJID string) (*domainChatStorage.DeviceRecord, error) {+ url := deviceURL+ return &domainChatStorage.DeviceRecord{+ DeviceID: deviceJID,+ WebhookURL: &url,+ WebhookSecret: "device-secret",+ WebhookEvents: deviceEvents,+ }, nil+ }+ defer func() { webhookStorageForTest = originalStorage }()++ var deliveries []mergeDelivery+ originalSubmit := submitWebhookFn+ submitWebhookFn = func(_ context.Context, _ map[string]any, url string, cfg *domainChatStorage.DeviceWebhookConfig) error {+ secret := "global-secret"+ if cfg != nil {+ secret = cfg.WebhookSecret+ }+ deliveries = append(deliveries, mergeDelivery{url: url, secret: secret})+ if failURLs[url] {+ return errors.New("boom")+ }+ return nil+ }+ defer func() { submitWebhookFn = originalSubmit }()++ payload := ignoreJidPayload("[email protected]", "[email protected]")+ payload["event"] = eventName+ err := forwardPayloadToConfiguredWebhooks(context.Background(), payload, eventName)+ sort.Slice(deliveries, func(i, j int) bool { return deliveries[i].url < deliveries[j].url })+ return deliveries, err+}++func TestWebhookDeviceMerge_DisabledKeepsDeviceOnlyDelivery(t *testing.T) {+ deliveries, err := runDeviceMergeForward(t, false, []string{"https://global-a", "https://global-b"}, nil, "https://device", "", "message", nil)+ if err != nil {+ t.Fatalf("unexpected error: %v", err)+ }+ if len(deliveries) != 1 || deliveries[0].url != "https://device" || deliveries[0].secret != "device-secret" {+ t.Fatalf("expected a single device delivery signed with the device secret, got %+v", deliveries)+ }+}++func TestWebhookDeviceMerge_EnabledDeliversToDeviceAndGlobalWithOwnSecrets(t *testing.T) {+ deliveries, err := runDeviceMergeForward(t, true, []string{"https://global-a", "https://global-b"}, nil, "https://device", "", "message", nil)+ if err != nil {+ t.Fatalf("unexpected error: %v", err)+ }+ want := []mergeDelivery{+ {url: "https://device", secret: "device-secret"},+ {url: "https://global-a", secret: "global-secret"},+ {url: "https://global-b", secret: "global-secret"},+ }+ if len(deliveries) != len(want) {+ t.Fatalf("expected %d deliveries, got %+v", len(want), deliveries)+ }+ for i := range want {+ if deliveries[i] != want[i] {+ t.Fatalf("delivery %d: expected %+v, got %+v", i, want[i], deliveries[i])+ }+ }+}++func TestWebhookDeviceMerge_GlobalLegUsesGlobalEventWhitelist(t *testing.T) {+ // Device only subscribed to "message"; global whitelist allows everything, so a+ // reaction still reaches the global targets but not the device URL.+ deliveries, err := runDeviceMergeForward(t, true, []string{"https://global-a"}, nil, "https://device", "message", "message.reaction", nil)+ if err != nil {+ t.Fatalf("unexpected error: %v", err)+ }+ if len(deliveries) != 1 || deliveries[0].url != "https://global-a" {+ t.Fatalf("expected only the global delivery, got %+v", deliveries)+ }++ // And the other way round: global whitelist excludes the event, device explicitly+ // allows it (a device with no webhook_events of its own inherits the global list).+ deliveries, err = runDeviceMergeForward(t, true, []string{"https://global-a"}, []string{"message.ack"}, "https://device", "message", "message", nil)+ if err != nil {+ t.Fatalf("unexpected error: %v", err)+ }+ if len(deliveries) != 1 || deliveries[0].url != "https://device" {+ t.Fatalf("expected only the device delivery, got %+v", deliveries)+ }+}++func TestWebhookDeviceMerge_SkipsGlobalURLAlreadyCoveredByDevice(t *testing.T) {+ deliveries, err := runDeviceMergeForward(t, true, []string{"https://device", "https://global-b"}, nil, "https://device", "", "message", nil)+ if err != nil {+ t.Fatalf("unexpected error: %v", err)+ }+ if len(deliveries) != 2 || deliveries[0].url != "https://device" || deliveries[1].url != "https://global-b" {+ t.Fatalf("expected the shared URL to be delivered once, got %+v", deliveries)+ }+}++func TestWebhookDeviceMerge_ErrorOnlyWhenEveryLegFails(t *testing.T) {+ _, err := runDeviceMergeForward(t, true, []string{"https://global-a"}, nil, "https://device", "", "message", map[string]bool{"https://device": true})+ if err != nil {+ t.Fatalf("a surviving global delivery must not surface an error, got %v", err)+ }+ _, err = runDeviceMergeForward(t, true, []string{"https://global-a"}, nil, "https://device", "", "message", map[string]bool{"https://device": true, "https://global-a": true})+ if err == nil {+ t.Fatal("expected an error when both the device and global deliveries fail")+ }+}