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: add whitelist event
Aldino Kemal5087c111c579
diff --git a/docs/webhook-payload.md b/docs/webhook-payload.mdindex 80d0685b..3c6b1e19 100644--- a/docs/webhook-payload.md+++ b/docs/webhook-payload.md@@ -8,6 +8,55 @@ Multidevice application.The webhook system sends HTTP POST requests to configured URLs whenever WhatsApp events occur. Each webhook requestincludes event data in JSON format and security headers for verification.+## Available Webhook Events++The following events can be received via webhook:++| Event | Description |+|----------------------|---------------------------------------------------------|+| `message` | Text, media, contact, location, and other message types |+| `message.reaction` | Emoji reactions to messages |+| `message.revoked` | Deleted/revoked messages |+| `message.edited` | Edited messages |+| `message.ack` | Delivery and read receipts |+| `group.participants` | Group member join/leave/promote/demote events |++## Event Filtering++You can configure which events are forwarded to your webhook using the `WHATSAPP_WEBHOOK_EVENTS` environment variable or+`--webhook-events` CLI flag.++### Configuration Examples++**Environment Variable:**++```bash+# Only receive message and read receipt events+WHATSAPP_WEBHOOK_EVENTS=message,message.ack++# Receive all message-related events+WHATSAPP_WEBHOOK_EVENTS=message,message.reaction,message.revoked,message.edited,message.ack++# Receive only group events+WHATSAPP_WEBHOOK_EVENTS=group.participants+```++**CLI Flag:**++```bash+# Only receive message events+./whatsapp rest --webhook="https://yourapp.com/webhook" --webhook-events="message"++# Receive message and group events+./whatsapp rest --webhook="https://yourapp.com/webhook" --webhook-events="message,group.participants"+```++**Behavior:**++- If `WHATSAPP_WEBHOOK_EVENTS` is empty or not set, **all events** are forwarded (default behavior)+- If configured, only the specified events are forwarded to webhooks+- Event names are case-insensitive+## Security### HMAC Signature Verification@@ -71,24 +120,24 @@ All webhook payloads follow a consistent top-level structure:### Top-Level Fields-| **Field** | **Type** | **Description** |-|-------------|----------|---------------------------------------------------------------------------------|+| **Field** | **Type** | **Description** |+|-------------|----------|---------------------------------------------------------------------------------------------------------------------|| `event` | string | Event type: `message`, `message.reaction`, `message.revoked`, `message.edited`, `message.ack`, `group.participants` |-| `device_id` | string | JID of the device that received this event (e.g., `[email protected]`) |-| `payload` | object | Event-specific payload data |+| `device_id` | string | JID of the device that received this event (e.g., `[email protected]`) |+| `payload` | object | Event-specific payload data |### Common Payload FieldsFields commonly found inside the `payload` object:-| **Field** | **Type** | **Description** |-|---------------|----------|-------------------------------------------------------------------|-| `id` | string | Message ID |-| `chat_id` | string | Chat JID (e.g., `[email protected]` or `[email protected]` for groups) |-| `from` | string | Full JID of the sender (e.g., `[email protected]`) |-| `from_lid` | string | LID (Linked ID) of the sender if available |-| `from_name` | string | Display name (pushname) of the sender |-| `timestamp` | string | RFC3339 formatted timestamp (e.g., `2023-10-15T10:30:00Z`) |+| **Field** | **Type** | **Description** |+|-------------|----------|-------------------------------------------------------------------------------|+| `id` | string | Message ID |+| `chat_id` | string | Chat JID (e.g., `[email protected]` or `[email protected]` for groups) |+| `from` | string | Full JID of the sender (e.g., `[email protected]`) |+| `from_lid` | string | LID (Linked ID) of the sender if available |+| `from_name` | string | Display name (pushname) of the sender |+| `timestamp` | string | RFC3339 formatted timestamp (e.g., `2023-10-15T10:30:00Z`) |## Message Events@@ -162,7 +211,9 @@ Triggered when a message is successfully delivered to the recipient's device."device_id": "[email protected]","timestamp": "2025-07-18T22:44:20Z","payload": {- "ids": ["3EB00106E8BE0F407E88EC"],+ "ids": [+ "3EB00106E8BE0F407E88EC"+ ],"chat_id": "[email protected]","from": "[email protected]","from_lid": "251556368777322@lid",@@ -182,7 +233,9 @@ Triggered when a message is read by the recipient (they opened the chat and saw"device_id": "[email protected]","timestamp": "2025-07-18T22:44:44Z","payload": {- "ids": ["3EB00106E8BE0F407E88EC"],+ "ids": [+ "3EB00106E8BE0F407E88EC"+ ],"chat_id": "[email protected]","from": "[email protected]","receipt_type": "read",@@ -207,7 +260,9 @@ Triggered when a message is read by the recipient (they opened the chat and saw## Group Events-Group events are triggered when group metadata changes, including member join/leave events, admin promotions/demotions, and group settings updates. These events use the `group.participants` event type and provide comprehensive information about group changes.+Group events are triggered when group metadata changes, including member join/leave events, admin promotions/demotions,+and group settings updates. These events use the `group.participants` event type and provide comprehensive information+about group changes.### Group Member Join@@ -648,25 +703,25 @@ app.post('/webhook', (req, res) => {chat_id: data.payload.chat_id});break;-+case 'message.reaction':console.log('Reaction:', {reaction: data.payload.reaction,reacted_message_id: data.payload.reacted_message_id});break;-+case 'message.revoked':console.log('Message revoked:', data.payload.revoked_message_id);break;-+case 'message.edited':console.log('Message edited:', {original_id: data.payload.original_message_id,new_body: data.payload.body});break;-+case 'message.ack':console.log(`Message ${data.payload.receipt_type}:`, {chat_id: data.payload.chat_id,@@ -674,7 +729,7 @@ app.post('/webhook', (req, res) => {description: data.payload.receipt_type_description});break;-+case 'group.participants':console.log(`Group ${data.payload.type} event:`, {chat_id: data.payload.chat_id,diff --git a/readme.md b/readme.mdindex e563d393..024c0497 100644--- a/readme.md+++ b/readme.md@@ -41,22 +41,24 @@ Download:- Starting version 7.x we are using goreleaser to build the binary, so you can download the binaryfrom [release](https://github.com/aldinokemal/go-whatsapp-web-multidevice/releases/latest)- `v8`- - **Multi-device support**: You can now connect and manage multiple WhatsApp accounts simultaneously in a single server instance+ - **Multi-device support**: You can now connect and manage multiple WhatsApp accounts simultaneously in a single+ server instance- **New Device Management API**: New endpoints under `/devices` for managing multiple devices- **Device scoping required**: All device-scoped REST API calls now require either:- `X-Device-Id` header, or- `device_id` query parameter- If only one device is registered, it will be used as the default- **WebSocket device scoping**: Connect to `/ws?device_id=<id>` to scope WebSocket to a specific device- - **Webhook payload changes**: All webhook payloads now include a top-level `device_id` field identifying which device received the event:+ - **Webhook payload changes**: All webhook payloads now include a top-level `device_id` field identifying which+ device received the event:- ```json- {- "event": "message",- "device_id": "[email protected]",- "payload": { ... }- }- ```+ ```json+ {+ "event": "message",+ "device_id": "[email protected]",+ "payload": { ... }+ }+ ```## Feature@@ -100,9 +102,27 @@ Download:- **Webhook Payload Documentation**For detailed webhook payload schemas, security implementation, and integration examples,see [Webhook Payload Documentation](./docs/webhook-payload.md)+- **Webhook Event Filtering**+ You can filter which events are forwarded to your webhook using:+ - `--webhook-events="message,message.ack"` (comma-separated list)+ - Or environment variable: `WHATSAPP_WEBHOOK_EVENTS=message,message.ack`++ **Available Webhook Events:**++ | Event | Description |+ |----------------------|-----------------------------------------------|+ | `message` | Text, media, contact, location messages |+ | `message.reaction` | Emoji reactions to messages |+ | `message.revoked` | Deleted/revoked messages |+ | `message.edited` | Edited messages |+ | `message.ack` | Delivery and read receipts |+ | `group.participants` | Group member join/leave/promote/demote events |++ If not configured (empty), all events will be forwarded.- **Webhook TLS Configuration**- If you encounter TLS certificate verification errors when using webhooks (e.g., with Cloudflare tunnels or self-signed certificates):+ If you encounter TLS certificate verification errors when using webhooks (e.g., with Cloudflare tunnels or self-signed+ certificates):```tls: failed to verify certificate: x509: certificate signed by unknown authority@@ -117,7 +137,8 @@ Download:- Cloudflare tunnels (which provide their own security layer)- Internal networks with self-signed certificates- **For production environments**, it's strongly recommended to use proper SSL certificates (e.g., Let's Encrypt) instead of disabling verification.+ **For production environments**, it's strongly recommended to use proper SSL certificates (e.g., Let's Encrypt)+ instead of disabling verification.## Configuration@@ -145,23 +166,24 @@ To use environment variables:#### Available Environment Variables-| Variable | Description | Default | Example |-|-------------------------------|---------------------------------------------|----------------------------------------------|---------------------------------------------|-| `APP_PORT` | Application port | `3000` | `APP_PORT=8080` |-| `APP_HOST` | Host address to bind the server | `0.0.0.0` | `APP_HOST=127.0.0.1` |-| `APP_DEBUG` | Enable debug logging | `false` | `APP_DEBUG=true` |-| `APP_OS` | OS name (device name in WhatsApp) | `Chrome` | `APP_OS=MyApp` |-| `APP_BASIC_AUTH` | Basic authentication credentials | - | `APP_BASIC_AUTH=user1:pass1,user2:pass2` |-| `APP_BASE_PATH` | Base path for subpath deployment | - | `APP_BASE_PATH=/gowa` |-| `APP_TRUSTED_PROXIES` | Trusted proxy IP ranges for reverse proxy | - | `APP_TRUSTED_PROXIES=0.0.0.0/0` |-| `DB_URI` | Database connection URI | `file:storages/whatsapp.db?_foreign_keys=on` | `DB_URI=postgres://user:pass@host/db` |-| `WHATSAPP_AUTO_REPLY` | Auto-reply message | - | `WHATSAPP_AUTO_REPLY="Auto reply message"` |-| `WHATSAPP_AUTO_MARK_READ` | Auto-mark incoming messages as read | `false` | `WHATSAPP_AUTO_MARK_READ=true` |-| `WHATSAPP_AUTO_DOWNLOAD_MEDIA`| Auto-download media from incoming messages | `true` | `WHATSAPP_AUTO_DOWNLOAD_MEDIA=false` |-| `WHATSAPP_WEBHOOK` | Webhook URL(s) for events (comma-separated) | - | `WHATSAPP_WEBHOOK=https://webhook.site/xxx` |-| `WHATSAPP_WEBHOOK_SECRET` | Webhook secret for validation | `secret` | `WHATSAPP_WEBHOOK_SECRET=super-secret-key` |-| `WHATSAPP_WEBHOOK_INSECURE_SKIP_VERIFY` | Skip TLS verification for webhooks (insecure) | `false` | `WHATSAPP_WEBHOOK_INSECURE_SKIP_VERIFY=true` |-| `WHATSAPP_ACCOUNT_VALIDATION` | Enable account validation | `true` | `WHATSAPP_ACCOUNT_VALIDATION=false` |+| Variable | Description | Default | Example |+|-----------------------------------------|---------------------------------------------------------------|----------------------------------------------|-----------------------------------------------|+| `APP_PORT` | Application port | `3000` | `APP_PORT=8080` |+| `APP_HOST` | Host address to bind the server | `0.0.0.0` | `APP_HOST=127.0.0.1` |+| `APP_DEBUG` | Enable debug logging | `false` | `APP_DEBUG=true` |+| `APP_OS` | OS name (device name in WhatsApp) | `Chrome` | `APP_OS=MyApp` |+| `APP_BASIC_AUTH` | Basic authentication credentials | - | `APP_BASIC_AUTH=user1:pass1,user2:pass2` |+| `APP_BASE_PATH` | Base path for subpath deployment | - | `APP_BASE_PATH=/gowa` |+| `APP_TRUSTED_PROXIES` | Trusted proxy IP ranges for reverse proxy | - | `APP_TRUSTED_PROXIES=0.0.0.0/0` |+| `DB_URI` | Database connection URI | `file:storages/whatsapp.db?_foreign_keys=on` | `DB_URI=postgres://user:pass@host/db` |+| `WHATSAPP_AUTO_REPLY` | Auto-reply message | - | `WHATSAPP_AUTO_REPLY="Auto reply message"` |+| `WHATSAPP_AUTO_MARK_READ` | Auto-mark incoming messages as read | `false` | `WHATSAPP_AUTO_MARK_READ=true` |+| `WHATSAPP_AUTO_DOWNLOAD_MEDIA` | Auto-download media from incoming messages | `true` | `WHATSAPP_AUTO_DOWNLOAD_MEDIA=false` |+| `WHATSAPP_WEBHOOK` | Webhook URL(s) for events (comma-separated) | - | `WHATSAPP_WEBHOOK=https://webhook.site/xxx` |+| `WHATSAPP_WEBHOOK_SECRET` | Webhook secret for validation | `secret` | `WHATSAPP_WEBHOOK_SECRET=super-secret-key` |+| `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_ACCOUNT_VALIDATION` | Enable account validation | `true` | `WHATSAPP_ACCOUNT_VALIDATION=false` |Note: Command-line flags will override any values set in environment variables or `.env` file.@@ -242,7 +264,8 @@ standardized protocol.#### Available MCP Tools-The WhatsApp MCP server provides comprehensive tools for AI agents to interact with WhatsApp through a standardized protocol. Below is the complete list of available tools:+The WhatsApp MCP server provides comprehensive tools for AI agents to interact with WhatsApp through a standardized+protocol. Below is the complete list of available tools:##### **π± Connection Management**@@ -440,8 +463,8 @@ You can fork or edit this source code !- Use [SwaggerEditor](https://editor.swagger.io) to visualize the API.- Generate HTTP clients using [openapi-generator](https://openapi-generator.tech/#try).-| Feature | Menu | Method | URL |-|---------|----------------------------------------|--------|-------------------------------------|+| Feature | Menu | Method | URL |+|----------|----------------------------------------|--------|-------------------------------------|| β | List Devices | GET | /devices || β | Add Device | POST | /devices || β | Get Device Info | GET | /devices/:device_id |@@ -515,7 +538,7 @@ You can fork or edit this source code !| β | Archive Chat | POST | /chat/:chat_jid/archive || β | Set Disappearing Messages | POST | /chat/:chat_jid/disappearing |-```txt+```β = Availableβ = Not Available Yet```diff --git a/src/.env.example b/src/.env.exampleindex 3e1344ae..15529d77 100644--- a/src/.env.example+++ b/src/.env.example@@ -18,5 +18,6 @@ WHATSAPP_AUTO_DOWNLOAD_MEDIA=trueWHATSAPP_WEBHOOK=https://webhook.site/07b69616-5943-4c7f-a8be-db4819df699e,https://webhook.site/09a38aff-d11a-4a38-a176-3f3efa0b5e8bWHATSAPP_WEBHOOK_SECRET=super-secret-keyWHATSAPP_WEBHOOK_INSECURE_SKIP_VERIFY=false+WHATSAPP_WEBHOOK_EVENTS=message,message.reaction,message.revoked,message.edited,message.ack,group.participantsWHATSAPP_ACCOUNT_VALIDATION=trueWHATSAPP_CHAT_STORAGE=true\ No newline at end of filediff --git a/src/cmd/root.go b/src/cmd/root.goindex 07c356b9..47845a2e 100644--- a/src/cmd/root.go+++ b/src/cmd/root.go@@ -133,6 +133,10 @@ func initEnvConfig() {if viper.IsSet("whatsapp_webhook_insecure_skip_verify") {config.WhatsappWebhookInsecureSkipVerify = viper.GetBool("whatsapp_webhook_insecure_skip_verify")}+ if envWebhookEvents := viper.GetString("whatsapp_webhook_events"); envWebhookEvents != "" {+ events := strings.Split(envWebhookEvents, ",")+ config.WhatsappWebhookEvents = events+ }if viper.IsSet("whatsapp_account_validation") {config.WhatsappAccountValidation = viper.GetBool("whatsapp_account_validation")}@@ -236,6 +240,12 @@ func initFlags() {config.WhatsappWebhookInsecureSkipVerify,`skip TLS certificate verification for webhooks (INSECURE - use only for development/self-signed certs) --webhook-insecure-skip-verify <true/false> | example: --webhook-insecure-skip-verify=true`,)+ rootCmd.PersistentFlags().StringSliceVarP(+ &config.WhatsappWebhookEvents,+ "webhook-events", "",+ config.WhatsappWebhookEvents,+ `whitelist of events to forward to webhook (empty = all events) --webhook-events <string> | example: --webhook-events="message,message.ack,group.participants"`,+ )rootCmd.PersistentFlags().BoolVarP(&config.WhatsappAccountValidation,"account-validation", "",diff --git a/src/config/settings.go b/src/config/settings.goindex ee4730bd..0448a13d 100644--- a/src/config/settings.go+++ b/src/config/settings.go@@ -32,6 +32,7 @@ var (WhatsappWebhook []stringWhatsappWebhookSecret = "secret"WhatsappWebhookInsecureSkipVerify = false // Skip TLS certificate verification for webhooks (insecure)+ WhatsappWebhookEvents []string // Whitelist of events to forward to webhook (empty = all events)WhatsappLogLevel = "ERROR"WhatsappSettingMaxImageSize int64 = 20000000 // 20MBWhatsappSettingMaxFileSize int64 = 50000000 // 50MBdiff --git a/src/infrastructure/whatsapp/webhook_forward.go b/src/infrastructure/whatsapp/webhook_forward.goindex 98098a39..8bdf098a 100644--- a/src/infrastructure/whatsapp/webhook_forward.go+++ b/src/infrastructure/whatsapp/webhook_forward.go@@ -16,6 +16,14 @@ var submitWebhookFn = submitWebhook// It only returns an error when all webhook deliveries fail. Partial failures are logged and suppressed so// successful targets still receive the event.func forwardPayloadToConfiguredWebhooks(ctx context.Context, payload map[string]any, eventName string) error {+ // Check if event is whitelisted (if whitelist is configured)+ if len(config.WhatsappWebhookEvents) > 0 {+ if !isEventWhitelisted(eventName) {+ logrus.Debugf("Skipping event %s - not in webhook events whitelist", eventName)+ return nil+ }+ }+total := len(config.WhatsappWebhook)logrus.Infof("Forwarding %s to %d configured webhook(s)", eventName, total)@@ -49,3 +57,13 @@ func forwardPayloadToConfiguredWebhooks(ctx context.Context, payload map[string]return nil}++// isEventWhitelisted checks if the given event name is in the configured whitelist+func isEventWhitelisted(eventName string) bool {+ for _, allowed := range config.WhatsappWebhookEvents {+ if strings.EqualFold(strings.TrimSpace(allowed), eventName) {+ return true+ }+ }+ return false+}