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.

feat(webhook): report temporary bans, reach-out timelocks and logout reasons (#919)

MalikD2004b4ef48921036
diff --git a/docs/webhook-payload.md b/docs/webhook-payload.md
index 24368fc5..801f8be5 100644
--- a/docs/webhook-payload.md
+++ b/docs/webhook-payload.md
@@ -32,6 +32,9 @@ The following events can be received via webhook:
| `newsletter.message` | New message(s) posted in a newsletter |
| `newsletter.mute` | Newsletter mute setting changed |
| `call.offer` | Incoming call received |
+| `device.logged_out` | The device was logged out, with WhatsApp's reason |
+| `device.temporary_ban` | WhatsApp temporarily banned the account |
+| `device.reachout_timelock` | WhatsApp restricted the account from starting new chats |
## Event Filtering
@@ -61,6 +64,9 @@ WHATSAPP_WEBHOOK_EVENTS=newsletter.joined,newsletter.left,newsletter.message,new
# Receive call events
WHATSAPP_WEBHOOK_EVENTS=call.offer
+# Receive device events
+WHATSAPP_WEBHOOK_EVENTS=device.logged_out,device.temporary_ban,device.reachout_timelock
+
# Receive all group and newsletter events
WHATSAPP_WEBHOOK_EVENTS=group.participants,group.info,group.joined,newsletter.joined,newsletter.left,newsletter.message
```
@@ -191,9 +197,9 @@ All webhook payloads follow a consistent top-level structure:
| **Field** | **Type** | **Description** |
|--------------|----------|---------------------------------------------------------------------------------------------------------------------|
-| `event` | string | Event type: `message`, `message.reaction`, `message.revoked`, `message.edited`, `message.ack`, `message.deleted`, `chat_presence`, `presence`, `group.participants`, `group.info`, `group.joined`, `label.edit`, `label.association`, `newsletter.joined`, `newsletter.left`, `newsletter.message`, `newsletter.mute`, `call.offer` |
+| `event` | string | Event type: `message`, `message.reaction`, `message.revoked`, `message.edited`, `message.ack`, `message.deleted`, `chat_presence`, `presence`, `group.participants`, `group.info`, `group.joined`, `label.edit`, `label.association`, `newsletter.joined`, `newsletter.left`, `newsletter.message`, `newsletter.mute`, `call.offer`, `device.logged_out`, `device.temporary_ban`, `device.reachout_timelock` |
| `device_id` | string | JID of the device that received this event (e.g., `[email protected]`) |
-| `session_id` | string | Session ID registered via `POST /devices` (e.g., `org_2`), for correlating the event back to a tenant. Omitted when the JID can't be mapped to a session. |
+| `session_id` | string | ID of the emitting slot. Device events always set this field; auto-created slots may use a WhatsApp JID. Other events may omit it when the JID cannot be mapped to a session. |
| `payload` | object | Event-specific payload data |
### Common Payload Fields
@@ -1114,6 +1120,107 @@ app.post('/webhook', async (req, res) => {
4. If the call should be rejected, call `POST /call/reject` with the values from the webhook payload
5. The call is rejected on WhatsApp, and the caller sees a "declined" status
+## Device Events
+
+Device events report what WhatsApp tells a device about its account: a logout and its reason, a temporary ban, or a
+restriction on starting new chats. Without them a temporary ban only shows as a disconnected device, and a reach-out
+timelock only shows as sends failing with error 463.
+
+The codes are WhatsApp's, forwarded unchanged; the reason texts are whatsmeow's descriptions of them. A code whatsmeow
+does not know is still forwarded, with its generic reason text. Device events are not sent to Chatwoot.
+
+`session_id` is always set on device events, to the slot the event is about, so slots that share one WhatsApp number
+can be told apart.
+
+### Device Logged Out
+
+Triggered when the device is logged out remotely: unlinked from the phone, or logged out by WhatsApp. The device slot
+is kept for re-pairing, as before. `device_id` and `session_id` are the ones the device had before the logout.
+
+```json
+{
+ "event": "device.logged_out",
+ "device_id": "[email protected]",
+ "session_id": "org_2",
+ "timestamp": "2026-10-28T09:00:00Z",
+ "payload": {
+ "code": 401,
+ "reason": "logged out from another device",
+ "on_connect": true
+ }
+}
+```
+
+| **`code`** | **`reason`** | **Notes** |
+|------------|--------------------------------|----------------------------------------------------------------------------|
+| 401 | logged out from another device | The usual code when the device is removed from the phone |
+| 403 | primary device was logged out | Called LOCKED in WhatsApp Web; seen both on bans and when switching phones |
+| 406 | logged out for unknown reason | Called BANNED in WhatsApp Web |
+
+### Device Temporary Ban
+
+Triggered when WhatsApp refuses the connection because the account is temporarily banned. The session is kept, so the
+device can connect again once the ban expires.
+
+```json
+{
+ "event": "device.temporary_ban",
+ "device_id": "[email protected]",
+ "session_id": "org_2",
+ "timestamp": "2026-10-28T09:00:00Z",
+ "payload": {
+ "code": 101,
+ "reason": "you sent too many messages to people who don't have you in their address books",
+ "expires_in_seconds": 86400,
+ "expires_at": "2026-10-29T09:00:00Z"
+ }
+}
+```
+
+| **`code`** | **`reason`** |
+|------------|-----------------------------------------------------------------------------------|
+| 101 | you sent too many messages to people who don't have you in their address books |
+| 102 | too many people blocked you |
+| 103 | you created too many groups with people who don't have you in their address books |
+| 104 | you sent the same message to too many people |
+| 106 | you sent too many messages to a broadcast list |
+
+### Device Reach-out Timelock
+
+Triggered when WhatsApp notifies the account that it is restricted from starting new chats. While the restriction is
+active, sends to people the account has no conversation with fail with error 463. `is_active` is `false` when WhatsApp
+reports the restriction as no longer active.
+
+```json
+{
+ "event": "device.reachout_timelock",
+ "device_id": "[email protected]",
+ "session_id": "org_2",
+ "timestamp": "2026-10-28T09:00:00Z",
+ "payload": {
+ "is_active": true,
+ "ends_at": "2026-10-28T21:00:00Z"
+ }
+}
+```
+
+### Device Event Fields
+
+| **Field** | **Type** | **Description** |
+|------------------------------|----------|---------------------------------------------------------------------------------------------------------------------|
+| `event` | string | `device.logged_out`, `device.temporary_ban` or `device.reachout_timelock` |
+| `device_id` | string | JID of the device the event is about; omitted when the slot has no JID yet |
+| `session_id` | string | Slot ID: the ID registered via `POST /devices`, or a WhatsApp JID for slots gowa created; always set |
+| `timestamp` | string | RFC3339 formatted timestamp when the event was received |
+| `payload.code` | number | Logged out and temporary ban: the reason code |
+| `payload.reason` | string | Logged out and temporary ban: whatsmeow's description of the code |
+| `payload.on_connect` | boolean | Logged out: `true` when WhatsApp refused the connection, `false` when it closed an open one |
+| `payload.expires_in_seconds` | number | Temporary ban: seconds until the ban expires, as WhatsApp reported it; `0` when it gave none |
+| `payload.expires_at` | string | Temporary ban: RFC3339 expiry, computed from `expires_in_seconds` when the event was received; omitted when unknown |
+| `payload.is_active` | boolean | Reach-out timelock: whether the restriction is in force |
+| `payload.enforcement_type` | string | Reach-out timelock: WhatsApp's enforcement type, passed through unchanged; omitted when empty |
+| `payload.ends_at` | string | Reach-out timelock: RFC3339 time the restriction ends; omitted when WhatsApp gave none |
+
## Media Messages
### Image Message
diff --git a/readme.md b/readme.md
index 14882298..21711651 100644
--- a/readme.md
+++ b/readme.md
@@ -191,6 +191,9 @@ Download:
| `newsletter.message` | New message(s) posted in a newsletter |
| `newsletter.mute` | Newsletter mute setting changed |
| `call.offer` | Incoming call received |
+ | `device.logged_out` | The device was logged out, with the reason |
+ | `device.temporary_ban` | WhatsApp temporarily banned the account |
+ | `device.reachout_timelock` | WhatsApp restricted starting new chats |
If this setting is empty, all events are forwarded.
- **Webhook JID filtering**
diff --git a/src/infrastructure/whatsapp/AGENTS.md b/src/infrastructure/whatsapp/AGENTS.md
index 623c4cfe..1fd1c316 100644
--- a/src/infrastructure/whatsapp/AGENTS.md
+++ b/src/infrastructure/whatsapp/AGENTS.md
@@ -16,6 +16,10 @@ This package owns clients, device lifecycle, JIDs, events, presence, and forward
Keep work bounded and failures observable without blocking the event loop.
Preserve the `shouldForwardReceipt` guard: contacts' linked-device receipts stay
dropped 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
+ just before `TriggerLoggedOut` clears the JID; delivery starts before the bounded
+ websocket broadcast.
- Chatwoot retries: `StartChatwootForwardRetryWorker` uses durable chat-storage jobs
keyed by device, event name, and WhatsApp message ID. Initialize the client registry
before the retry worker; preserve device routing when replaying queued events.
diff --git a/src/infrastructure/whatsapp/event_device.go b/src/infrastructure/whatsapp/event_device.go
new file mode 100644
index 00000000..1e7a63d2
--- /dev/null
+++ b/src/infrastructure/whatsapp/event_device.go
@@ -0,0 +1,158 @@
+package whatsapp
+
+import (
+ "context"
+ "fmt"
+ "strings"
+ "time"
+
+ domainChatStorage "github.com/aldinokemal/go-whatsapp-web-multidevice/domains/chatstorage"
+ "github.com/aldinokemal/go-whatsapp-web-multidevice/ui/websocket"
+ "github.com/sirupsen/logrus"
+ "go.mau.fi/whatsmeow/types/events"
+)
+
+// Webhook events for the account restrictions WhatsApp reports to a device. Without
+// them a temporary ban only shows as a disconnected device, and a reach-out timelock
+// only shows as failed sends.
+const (
+ EventTypeDeviceLoggedOut = "device.logged_out"
+ EventTypeDeviceTemporaryBan = "device.temporary_ban"
+ EventTypeDeviceReachoutTimelock = "device.reachout_timelock"
+)
+
+// reasonText drops the "<code>: " prefix whatsmeow puts on its reason strings, since
+// the code is sent in its own field.
+func reasonText(code int, s string) string {
+ return strings.TrimPrefix(s, fmt.Sprintf("%d: ", code))
+}
+
+func loggedOutPayload(evt *events.LoggedOut) map[string]any {
+ return map[string]any{
+ "code": int(evt.Reason),
+ "reason": reasonText(int(evt.Reason), evt.Reason.String()),
+ "on_connect": evt.OnConnect,
+ }
+}
+
+func temporaryBanPayload(evt *events.TemporaryBan, now time.Time) map[string]any {
+ payload := map[string]any{
+ "code": int(evt.Code),
+ "reason": reasonText(int(evt.Code), evt.Code.String()),
+ "expires_in_seconds": int64(evt.Expire / time.Second),
+ }
+ if evt.Expire > 0 {
+ payload["expires_at"] = now.Add(evt.Expire).UTC().Format(time.RFC3339)
+ }
+ return payload
+}
+
+func reachoutTimelockPayload(evt *events.NotifyAccountReachoutTimelock) map[string]any {
+ payload := map[string]any{
+ "is_active": evt.IsActive,
+ }
+ if evt.EnforcementType != "" {
+ payload["enforcement_type"] = evt.EnforcementType
+ }
+ if !evt.TimeEnforcementEnds.IsZero() {
+ payload["ends_at"] = evt.TimeEnforcementEnds.UTC().Format(time.RFC3339)
+ }
+ return payload
+}
+
+func handleTemporaryBan(ctx context.Context, instance *DeviceInstance, evt *events.TemporaryBan) {
+ logrus.Warnf("[TEMPORARY_BAN] Device %s: %s", instance.ID(), evt)
+
+ payload := temporaryBanPayload(evt, time.Now())
+ forwardDeviceEvent(ctx, EventTypeDeviceTemporaryBan, instance, payload)
+ broadcastDeviceEvent("DEVICE_TEMPORARY_BAN", evt.String(), instance.ID(), payload)
+}
+
+func handleReachoutTimelock(ctx context.Context, instance *DeviceInstance, evt *events.NotifyAccountReachoutTimelock) {
+ payload := reachoutTimelockPayload(evt)
+
+ message := "Reach-out timelock lifted"
+ if evt.IsActive {
+ message = "Reach-out timelock active: WhatsApp is restricting this account from starting new chats"
+ if endsAt, ok := payload["ends_at"]; ok {
+ message = fmt.Sprintf("%s until %s", message, endsAt)
+ }
+ logrus.Warnf("[REACHOUT_TIMELOCK] Device %s: %s (enforcement type %q)", instance.ID(), message, evt.EnforcementType)
+ } else {
+ logrus.Infof("[REACHOUT_TIMELOCK] Device %s: %s", instance.ID(), message)
+ }
+
+ forwardDeviceEvent(ctx, EventTypeDeviceReachoutTimelock, instance, payload)
+ broadcastDeviceEvent("DEVICE_REACHOUT_TIMELOCK", message, instance.ID(), payload)
+}
+
+// deviceBroadcastTimeout bounds how long a device event waits for the websocket hub,
+// which writes to each browser in turn with no deadline.
+var deviceBroadcastTimeout = 5 * time.Second
+
+// broadcastDeviceEvent tells the websocket clients, adding the device_id the UI routes by.
+// A hub stalled on a slow browser drops the message rather than holding the event loop.
+func broadcastDeviceEvent(code, message, deviceID string, payload map[string]any) {
+ result := make(map[string]any, len(payload)+1)
+ for key, value := range payload {
+ result[key] = value
+ }
+ result["device_id"] = deviceID
+
+ select {
+ case websocket.Broadcast <- websocket.BroadcastMessage{Code: code, Message: message, Result: result}:
+ case <-time.After(deviceBroadcastTimeout):
+ logrus.Warnf("Dropped websocket %s broadcast for device %s: the hub did not take it within %s", code, deviceID, deviceBroadcastTimeout)
+ }
+}
+
+// forwardDeviceEvent sends a device event to the webhooks. The webhook config and session
+// id come from the emitting slot and are read before this returns, because a remote logout
+// clears its JID right after (keep-slot reset). Only the delivery runs in the background.
+func forwardDeviceEvent(ctx context.Context, eventName string, instance *DeviceInstance, payload map[string]any) {
+ body := map[string]any{
+ "event": eventName,
+ "payload": payload,
+ "timestamp": time.Now().Format(time.RFC3339),
+ "session_id": instance.ID(),
+ }
+ if jid := instance.JID(); jid != "" {
+ body["device_id"] = jid
+ }
+ webhookConfig := instanceWebhookConfig(instance)
+
+ go func() {
+ webhookCtx, cancel := context.WithTimeout(context.WithoutCancel(ctx), 30*time.Second)
+ defer cancel()
+ if err := forwardPayloadWithWebhookConfig(webhookCtx, body, eventName, webhookConfig); err != nil {
+ logrus.Errorf("Failed to forward %s event to webhook: %v", eventName, err)
+ }
+ }()
+}
+
+// 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 == "" {
+ return nil
+ }
+ record, err := getDeviceRecordForTest(jid)
+ if err != nil {
+ logrus.Warnf("Failed to get webhook config for device %s, falling back to global config: %v", jid, err)
+ return nil
+ }
+ if record == nil || record.DeviceID != instance.ID() {
+ return nil
+ }
+ return webhookConfigFromRecord(record)
+}
diff --git a/src/infrastructure/whatsapp/event_device_test.go b/src/infrastructure/whatsapp/event_device_test.go
new file mode 100644
index 00000000..0dda2083
--- /dev/null
+++ b/src/infrastructure/whatsapp/event_device_test.go
@@ -0,0 +1,313 @@
+package whatsapp
+
+import (
+ "context"
+ "sync/atomic"
+ "testing"
+ "time"
+
+ "github.com/aldinokemal/go-whatsapp-web-multidevice/config"
+ domainChatStorage "github.com/aldinokemal/go-whatsapp-web-multidevice/domains/chatstorage"
+ "github.com/stretchr/testify/assert"
+ "github.com/stretchr/testify/require"
+ "go.mau.fi/whatsmeow/types/events"
+)
+
+type deliveredWebhook struct {
+ url string
+ body map[string]any
+}
+
+// captureDeviceWebhooks sends webhooks to a stub instead of the network, with one global
+// URL, no per-device config and no session ids, and restores the globals afterwards.
+func captureDeviceWebhooks(t *testing.T) <-chan deliveredWebhook {
+ t.Helper()
+ origURLs, origEvents := config.WhatsappWebhook, config.WhatsappWebhookEvents
+ origSubmit, origStorage, origSessionID := submitWebhookFn, webhookStorageForTest, sessionIDForJIDFn
+ t.Cleanup(func() {
+ config.WhatsappWebhook, config.WhatsappWebhookEvents = origURLs, origEvents
+ submitWebhookFn, webhookStorageForTest, sessionIDForJIDFn = origSubmit, origStorage, origSessionID
+ })
+
+ config.WhatsappWebhook = []string{"https://global.example.test/webhook"}
+ config.WhatsappWebhookEvents = nil
+ webhookStorageForTest = func(string) (*domainChatStorage.DeviceRecord, error) { return nil, nil }
+ sessionIDForJIDFn = func(string) string { return "" }
+
+ got := make(chan deliveredWebhook, 4)
+ submitWebhookFn = func(_ context.Context, payload map[string]any, url string, _ *domainChatStorage.DeviceWebhookConfig) error {
+ got <- deliveredWebhook{url: url, body: payload}
+ return nil
+ }
+ return got
+}
+
+func recvWebhook(t *testing.T, got <-chan deliveredWebhook) deliveredWebhook {
+ t.Helper()
+ select {
+ case delivered := <-got:
+ return delivered
+ case <-time.After(2 * time.Second):
+ t.Fatal("timed out waiting for webhook submission")
+ return deliveredWebhook{}
+ }
+}
+
+func TestTemporaryBanPayload(t *testing.T) {
+ now := time.Date(2026, 10, 28, 9, 0, 0, 0, time.UTC)
+ tests := []struct {
+ name string
+ evt events.TemporaryBan
+ want map[string]any
+ }{
+ {
+ name: "known reason with expiry",
+ evt: events.TemporaryBan{Code: events.TempBanSentToTooManyPeople, Expire: 2 * time.Hour},
+ want: map[string]any{
+ "code": 101,
+ "reason": "you sent too many messages to people who don't have you in their address books",
+ "expires_in_seconds": int64(7200),
+ "expires_at": "2026-10-28T11:00:00Z",
+ },
+ },
+ {
+ name: "no expiry given",
+ evt: events.TemporaryBan{Code: events.TempBanBlockedByUsers},
+ want: map[string]any{
+ "code": 102,
+ "reason": "too many people blocked you",
+ "expires_in_seconds": int64(0),
+ },
+ },
+ {
+ name: "unknown reason code",
+ evt: events.TemporaryBan{Code: 105, Expire: 90 * time.Second},
+ want: map[string]any{
+ "code": 105,
+ "reason": "you may have violated the terms of service (unknown error)",
+ "expires_in_seconds": int64(90),
+ "expires_at": "2026-10-28T09:01:30Z",
+ },
+ },
+ }
+
+ for _, tt := range tests {
+ t.Run(tt.name, func(t *testing.T) {
+ assert.Equal(t, tt.want, temporaryBanPayload(&tt.evt, now))
+ })
+ }
+}
+
+func TestReachoutTimelockPayload(t *testing.T) {
+ active := &events.NotifyAccountReachoutTimelock{EnforcementType: "example-type", IsActive: true}
+ active.TimeEnforcementEnds.Time = time.Date(2026, 10, 29, 6, 30, 0, 0, time.FixedZone("AST", 3*60*60))
+ assert.Equal(t, map[string]any{
+ "is_active": true,
+ "enforcement_type": "example-type",
+ "ends_at": "2026-10-29T03:30:00Z",
+ }, reachoutTimelockPayload(active))
+
+ lifted := &events.NotifyAccountReachoutTimelock{}
+ assert.Equal(t, map[string]any{"is_active": false}, reachoutTimelockPayload(lifted))
+}
+
+func TestLoggedOutPayload(t *testing.T) {
+ assert.Equal(t, map[string]any{
+ "code": 406,
+ "reason": "logged out for unknown reason",
+ "on_connect": true,
+ }, loggedOutPayload(&events.LoggedOut{OnConnect: true, Reason: events.ConnectFailureUnknownLogout}))
+
+ assert.Equal(t, map[string]any{
+ "code": 401,
+ "reason": "logged out from another device",
+ "on_connect": false,
+ }, loggedOutPayload(&events.LoggedOut{Reason: events.ConnectFailureLoggedOut}))
+}
+
+func TestHandlerTemporaryBanBroadcastsAndForwards(t *testing.T) {
+ got := captureDeviceWebhooks(t)
+ inst := &DeviceInstance{id: "slot-ban", jid: "[email protected]", createdAt: time.Now()}
+
+ go handler(context.Background(), inst, &events.TemporaryBan{Code: events.TempBanBlockedByUsers, Expire: time.Hour})
+
+ msg := recvBroadcast(t)
+ assert.Equal(t, "DEVICE_TEMPORARY_BAN", msg.Code)
+ result, ok := msg.Result.(map[string]any)
+ require.True(t, ok, "broadcast result = %#v", msg.Result)
+ assert.Equal(t, "slot-ban", result["device_id"])
+ assert.Equal(t, 102, result["code"])
+
+ delivered := recvWebhook(t, got)
+ assert.Equal(t, EventTypeDeviceTemporaryBan, delivered.body["event"])
+ assert.Equal(t, "[email protected]", delivered.body["device_id"])
+ payload, ok := delivered.body["payload"].(map[string]any)
+ require.True(t, ok, "webhook payload = %#v", delivered.body["payload"])
+ assert.Equal(t, 102, payload["code"])
+ assert.Equal(t, "too many people blocked you", payload["reason"])
+ assert.Equal(t, int64(3600), payload["expires_in_seconds"])
+}
+
+func TestHandlerReachoutTimelockBroadcastsAndForwards(t *testing.T) {
+ got := captureDeviceWebhooks(t)
+ inst := &DeviceInstance{id: "slot-timelock", jid: "[email protected]", createdAt: time.Now()}
+ evt := &events.NotifyAccountReachoutTimelock{EnforcementType: "example-type", IsActive: true}
+ evt.TimeEnforcementEnds.Time = time.Date(2026, 10, 29, 3, 30, 0, 0, time.UTC)
+
+ go handler(context.Background(), inst, evt)
+
+ msg := recvBroadcast(t)
+ assert.Equal(t, "DEVICE_REACHOUT_TIMELOCK", msg.Code)
+ assert.Contains(t, msg.Message, "until 2026-10-29T03:30:00Z")
+
+ delivered := recvWebhook(t, got)
+ assert.Equal(t, EventTypeDeviceReachoutTimelock, delivered.body["event"])
+ assert.Equal(t, "[email protected]", delivered.body["device_id"])
+ assert.Equal(t, map[string]any{
+ "is_active": true,
+ "enforcement_type": "example-type",
+ "ends_at": "2026-10-29T03:30:00Z",
+ }, delivered.body["payload"])
+}
+
+// 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
+// reach a device-only webhook, addressed to the JID the device had.
+func TestHandlerLoggedOutForwardsWithIdentityFromBeforeReset(t *testing.T) {
+ got := captureDeviceWebhooks(t)
+ config.WhatsappWebhook = nil
+
+ 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.SetOnLoggedOut(func(string) {
+ reset.Store(true)
+ inst.ResetClient()
+ })
+
+ go handler(context.Background(), inst, &events.LoggedOut{OnConnect: true, Reason: events.ConnectFailureUnknownLogout})
+
+ msg := recvBroadcast(t)
+ assert.Equal(t, "DEVICE_LOGGED_OUT", msg.Code)
+ assert.Equal(t, map[string]string{"device_id": "slot-out", "reason": "406: logged out for unknown reason"}, msg.Result)
+
+ delivered := recvWebhook(t, got)
+ assert.Equal(t, deviceURL, delivered.url)
+ assert.Equal(t, EventTypeDeviceLoggedOut, delivered.body["event"])
+ assert.Equal(t, jid, delivered.body["device_id"])
+ assert.Equal(t, "slot-out", delivered.body["session_id"])
+ assert.Equal(t, map[string]any{
+ "code": 406,
+ "reason": "logged out for unknown reason",
+ "on_connect": true,
+ }, delivered.body["payload"])
+
+ assert.Empty(t, inst.JID(), "the keep-slot reset should still clear the JID")
+}
+
+// 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.
+func TestDeviceEventRoutesSharedNumberToEmittingSlot(t *testing.T) {
+ got := captureDeviceWebhooks(t)
+ config.WhatsappWebhook = nil
+
+ const bareJID = "[email protected]"
+ urlA, urlB := "https://slot-a.example.test/webhook", "https://slot-b.example.test/webhook"
+ records := []*domainChatStorage.DeviceRecord{
+ {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()}
+ go handler(context.Background(), slotB, &events.TemporaryBan{Code: events.TempBanSentTooManySameMessage})
+ recvBroadcast(t)
+
+ delivered := recvWebhook(t, got)
+ assert.Equal(t, urlB, delivered.url)
+ assert.Equal(t, "slot-b", delivered.body["session_id"])
+ assert.Equal(t, bareJID, delivered.body["device_id"])
+}
+
+// The websocket hub writes to each browser in turn with no deadline, so it can stop
+// taking broadcasts. The webhook must still go out promptly, and the handler return.
+func TestDeviceEventWebhookDoesNotWaitForStalledWebsocket(t *testing.T) {
+ got := captureDeviceWebhooks(t)
+ origTimeout := deviceBroadcastTimeout
+ deviceBroadcastTimeout = time.Second
+ t.Cleanup(func() { deviceBroadcastTimeout = origTimeout })
+
+ inst := &DeviceInstance{id: "slot-stalled", jid: "[email protected]", createdAt: time.Now()}
+ returned := make(chan struct{})
+ // Nothing receives from websocket.Broadcast here, as with a stalled hub.
+ go func() {
+ handler(context.Background(), inst, &events.NotifyAccountReachoutTimelock{IsActive: true})
+ close(returned)
+ }()
+
+ select {
+ case delivered := <-got:
+ assert.Equal(t, EventTypeDeviceReachoutTimelock, delivered.body["event"])
+ case <-time.After(500 * time.Millisecond):
+ t.Fatal("webhook waited for the websocket broadcast")
+ }
+ select {
+ case <-returned:
+ case <-time.After(3 * time.Second):
+ t.Fatal("handler did not return while the websocket hub was stalled")
+ }
+}
+
+// When the emitting slot's own record has no JID saved (auto-created slots are not
+// persisted on connect), the shared bare JID can find only the sibling's record. That
+// webhook is the sibling's, so the event must go to the global webhook instead.
+func TestDeviceEventIgnoresSiblingRecordFoundByBareJID(t *testing.T) {
+ got := captureDeviceWebhooks(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()}
+ go handler(context.Background(), slotB, &events.TemporaryBan{Code: events.TempBanBlockedByUsers})
+ recvBroadcast(t)
+
+ delivered := recvWebhook(t, got)
+ assert.Equal(t, "https://global.example.test/webhook", delivered.url)
+ assert.Equal(t, "slot-b", delivered.body["session_id"])
+}
diff --git a/src/infrastructure/whatsapp/event_handler.go b/src/infrastructure/whatsapp/event_handler.go
index f7130428..c026254c 100644
--- a/src/infrastructure/whatsapp/event_handler.go
+++ b/src/infrastructure/whatsapp/event_handler.go
@@ -45,7 +45,11 @@ func handler(ctx context.Context, instance *DeviceInstance, rawEvt any) {
case *events.PairPasskeyError:
handlePairPasskeyError(instance, evt)
case *events.LoggedOut:
- handleLoggedOut(instance)
+ handleLoggedOut(ctx, instance, evt)
+ case *events.TemporaryBan:
+ handleTemporaryBan(ctx, instance, evt)
+ case *events.NotifyAccountReachoutTimelock:
+ handleReachoutTimelock(ctx, instance, evt)
case *events.Connected, *events.PushNameSetting:
handleConnectionEvents(ctx, client, instance)
case *events.StreamReplaced:
@@ -236,8 +240,8 @@ func handlePairPasskeyError(instance *DeviceInstance, evt *events.PairPasskeyErr
}
}
-func handleLoggedOut(instance *DeviceInstance) {
- logrus.Warnf("[REMOTE_LOGOUT] Received LoggedOut event for device %s - user logged out from phone", instance.ID())
+func handleLoggedOut(ctx context.Context, instance *DeviceInstance, evt *events.LoggedOut) {
+ logrus.Warnf("[REMOTE_LOGOUT] Received LoggedOut event for device %s (reason %s)", instance.ID(), evt.Reason)
instance.ClearPasskeyState()
if client := instance.GetClient(); client != nil {
@@ -251,6 +255,9 @@ func handleLoggedOut(instance *DeviceInstance) {
deviceID := instance.ID()
+ // Before TriggerLoggedOut: the webhook is addressed by the JID it clears.
+ forwardDeviceEvent(ctx, EventTypeDeviceLoggedOut, instance, loggedOutPayload(evt))
+
// TriggerLoggedOut fires the manager's keep-slot callback (resets the in-memory
// client + clears the persisted JID, but keeps the slot id and display name).
instance.TriggerLoggedOut()
@@ -258,7 +265,7 @@ func handleLoggedOut(instance *DeviceInstance) {
websocket.Broadcast <- websocket.BroadcastMessage{
Code: "DEVICE_LOGGED_OUT",
Message: "Device logged out (slot kept)",
- Result: map[string]string{"device_id": deviceID},
+ Result: map[string]string{"device_id": deviceID, "reason": evt.Reason.String()},
}
}
diff --git a/src/infrastructure/whatsapp/webhook_forward.go b/src/infrastructure/whatsapp/webhook_forward.go
index 615f83df..9823bd13 100644
--- a/src/infrastructure/whatsapp/webhook_forward.go
+++ b/src/infrastructure/whatsapp/webhook_forward.go
@@ -178,7 +178,23 @@ func forwardPayloadToConfiguredWebhooks(ctx context.Context, payload map[string]
logrus.Warnf("Failed to get webhook config for device %s, falling back to global config: %v", deviceJID, err)
webhookConfig = nil
}
+ 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.
+func forwardPayloadWithWebhookConfig(ctx context.Context, payload map[string]any, eventName string, webhookConfig *domainChatStorage.DeviceWebhookConfig) error {
jidAllowed := !shouldIgnoreWebhookJID(payload)
webhookAllowed := jidAllowed && isEventWhitelistedForDevice(eventName, webhookConfig)
chatwootAllowed := config.ChatwootEnabled && shouldForwardEventToChatwoot(eventName) && isEventWhitelistedForChatwoot(eventName)