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(device): make DELETE purge reliable and decode path device_id (#843)
hanlest3d179363843a
diff --git a/src/infrastructure/whatsapp/device_logout_keepslot_test.go b/src/infrastructure/whatsapp/device_logout_keepslot_test.goindex 461a9050..96aaed99 100644--- a/src/infrastructure/whatsapp/device_logout_keepslot_test.go+++ b/src/infrastructure/whatsapp/device_logout_keepslot_test.go@@ -24,6 +24,7 @@ type keepSlotStubStorage struct {saveErr errordeleteDataErr errorsavedRecords []*domainChatStorage.DeviceRecord+ deviceRecords []*domainChatStorage.DeviceRecorddeletedData []stringdeletedRecords []string}@@ -50,6 +51,10 @@ func (s *keepSlotStubStorage) GetChatwootDeviceConfig(string) (*domainChatStoragreturn nil, nil}+func (s *keepSlotStubStorage) ListDeviceRecords() ([]*domainChatStorage.DeviceRecord, error) {+ return s.deviceRecords, nil+}+// assertStoreLacksJID fails if any device row in the container still matches the given// NonAD JID. Matching mirrors deleteStoreRowsForJID / LoadExistingDevices.func assertStoreLacksJID(t *testing.T, ctx context.Context, c *sqlstore.Container, nonADJID string) {@@ -185,9 +190,131 @@ func TestPurgeDevice_SurfacesLocalCleanupFailure(t *testing.T) {const slotID = "slot-cleanup-err"manager.devices[slotID] = &DeviceInstance{id: slotID, createdAt: time.Now()}- if err := manager.PurgeDevice(ctx, slotID); err == nil || !strings.Contains(err.Error(), "chatstorage down") {+ err := manager.PurgeDevice(ctx, slotID)+ if err == nil || !strings.Contains(err.Error(), "chatstorage down") {t.Fatalf("expected PurgeDevice to surface the local cleanup failure, got %v", err)}+ if _, ok := manager.GetDevice(slotID); !ok {+ t.Fatal("expected slot to remain registered after failed purge so DELETE can be retried")+ }+}++func TestPurgeDevice_RetryAfterTransientCleanupFailure(t *testing.T) {+ ctx := context.Background()+ storage := &keepSlotStubStorage{deleteDataErr: errors.New("chatstorage down")}+ manager := NewDeviceManager(nil, nil, storage)++ const slotID = "slot-retry-cleanup"+ manager.devices[slotID] = &DeviceInstance{id: slotID, createdAt: time.Now()}++ if err := manager.PurgeDevice(ctx, slotID); err == nil {+ t.Fatal("expected first purge to fail")+ }+ storage.deleteDataErr = nil+ if err := manager.PurgeDevice(ctx, slotID); err != nil {+ t.Fatalf("expected second purge to succeed, got %v", err)+ }+ if _, ok := manager.GetDevice(slotID); ok {+ t.Fatal("expected slot removed after successful retry")+ }+}++func TestPurgeDevice_ExactSlotIDDoesNotTrimToSibling(t *testing.T) {+ ctx := context.Background()+ storage := &keepSlotStubStorage{}+ manager := NewDeviceManager(nil, nil, storage)++ const salesID = "sales"+ const spacedID = " sales "+ manager.devices[salesID] = &DeviceInstance{id: salesID, createdAt: time.Now()}+ manager.devices[spacedID] = &DeviceInstance{id: spacedID, createdAt: time.Now()}++ if err := manager.PurgeDevice(ctx, spacedID); err != nil {+ t.Fatalf("PurgeDevice returned error: %v", err)+ }+ if _, ok := manager.GetDevice(salesID); !ok {+ t.Fatal("expected sibling slot sales to remain when purging exact id \" sales \"")+ }+ if _, ok := manager.GetDevice(spacedID); ok {+ t.Fatal("expected spaced slot to be removed")+ }+}++func TestPurgeDevice_DoesNotDeleteSharedJIDPartitionWhenSiblingSlotExists(t *testing.T) {+ ctx := context.Background()+ storage := &keepSlotStubStorage{}+ manager := NewDeviceManager(nil, nil, storage)++ const slotA = "companion-a"+ const slotB = "companion-b"+ sharedJID := "[email protected]"+ manager.devices[slotA] = &DeviceInstance{id: slotA, jid: sharedJID, createdAt: time.Now()}+ manager.devices[slotB] = &DeviceInstance{id: slotB, jid: sharedJID, createdAt: time.Now()}+ storage.deviceRecords = []*domainChatStorage.DeviceRecord{+ {DeviceID: slotA, JID: sharedJID},+ {DeviceID: slotB, JID: sharedJID},+ }++ if err := manager.PurgeDevice(ctx, slotA); err != nil {+ t.Fatalf("PurgeDevice returned error: %v", err)+ }+ for _, key := range storage.deletedData {+ if key == sharedJID {+ t.Fatalf("expected shared JID partition %q not to be deleted while sibling slot remains, got deletes %v", sharedJID, storage.deletedData)+ }+ }+ if _, ok := manager.GetDevice(slotB); !ok {+ t.Fatal("expected sibling slot to remain in registry")+ }+}++func TestPurgeDevice_RequiresExistingSlot(t *testing.T) {+ manager := NewDeviceManager(nil, nil, nil)+ if err := manager.PurgeDevice(context.Background(), "missing-slot"); err == nil || !strings.Contains(err.Error(), "not found") {+ t.Fatalf("expected PurgeDevice to fail for missing slot, got %v", err)+ }+}++func TestPurgeDevice_ResolvesByJID(t *testing.T) {+ ctx := context.Background()+ storage := &keepSlotStubStorage{}+ manager := NewDeviceManager(nil, nil, storage)++ const slotID = "slot-resolve-jid"+ nonAD := "[email protected]"+ manager.devices[slotID] = &DeviceInstance{id: slotID, jid: nonAD, createdAt: time.Now()}++ if err := manager.PurgeDevice(ctx, nonAD); err != nil {+ t.Fatalf("PurgeDevice returned error: %v", err)+ }+ if _, ok := manager.GetDevice(slotID); ok {+ t.Fatal("expected slot to be removed when purging by JID")+ }+ if len(storage.deletedRecords) == 0 || storage.deletedRecords[0] != slotID {+ t.Fatalf("expected device record deletion for %s, got %v", slotID, storage.deletedRecords)+ }+}++func TestPurgeDevice_RemovesSlotEvenWhenLogoutWouldKeepIt(t *testing.T) {+ ctx := context.Background()+ storage := &keepSlotStubStorage{}+ manager := NewDeviceManager(nil, nil, storage)++ const slotID = "slot-purge-over-keep"+ inst := &DeviceInstance{id: slotID, jid: "[email protected]", createdAt: time.Now()}+ inst.SetOnLoggedOut(func(deviceID string) {+ if err := manager.keepSlotLogout(ctx, deviceID); err != nil {+ t.Errorf("keepSlotLogout during purge: %v", err)+ }+ })+ manager.devices[slotID] = inst++ if err := manager.PurgeDevice(ctx, slotID); err != nil {+ t.Fatalf("PurgeDevice returned error: %v", err)+ }+ if _, ok := manager.GetDevice(slotID); ok {+ t.Fatal("expected slot to be removed even when a keep-slot callback is wired")+ }}// deleteStoreRowsForJID is a no-op for an empty JID: a slot that was never paired has nodiff --git a/src/infrastructure/whatsapp/device_manager.go b/src/infrastructure/whatsapp/device_manager.goindex f07285fe..8629f35f 100644--- a/src/infrastructure/whatsapp/device_manager.go+++ b/src/infrastructure/whatsapp/device_manager.go@@ -187,6 +187,61 @@ func (m *DeviceManager) ResolveDevice(deviceID string) (*DeviceInstance, string,return nil, "", fmt.Errorf("device id is required")}+// resolveDeviceForPurge locates a slot for destructive cleanup without trimming the+// requested id. CreateDevice stores ids verbatim, so "sales" and " sales" are distinct+// slots; ResolveDevice trims and must not be used for DELETE/purge.+func (m *DeviceManager) resolveDeviceForPurge(deviceID string) (*DeviceInstance, string, error) {+ if m == nil {+ return nil, "", fmt.Errorf("device manager not initialized")+ }+ if deviceID == "" {+ return nil, "", fmt.Errorf("device id is required")+ }+ if inst, ok := m.GetDevice(deviceID); ok && inst != nil {+ return inst, deviceID, nil+ }+ if inst, ok := m.getDeviceByJID(deviceID); ok && inst != nil {+ return inst, inst.ID(), nil+ }+ return nil, deviceID, fmt.Errorf("device %s not found", deviceID)+}++// nonADJIDClaimedByOtherSlot reports whether another registered slot still uses the+// same bare-number JID for chat-storage partitioning (companion slots on one number).+func (m *DeviceManager) nonADJIDClaimedByOtherSlot(excludeSlotID, nonADJID string) bool {+ nonADJID = strings.TrimSpace(nonADJID)+ excludeSlotID = strings.TrimSpace(excludeSlotID)+ if nonADJID == "" {+ return false+ }+ if m.storage != nil {+ records, err := m.storage.ListDeviceRecords()+ if err != nil {+ logrus.WithError(err).Warn("[DEVICE_MANAGER] failed to list device records while checking shared JID partitions")+ return true+ }+ for _, rec := range records {+ if rec == nil || rec.DeviceID == excludeSlotID {+ continue+ }+ if strings.TrimSpace(rec.JID) == nonADJID {+ return true+ }+ }+ }+ m.mu.RLock()+ defer m.mu.RUnlock()+ for id, inst := range m.devices {+ if id == excludeSlotID || inst == nil {+ continue+ }+ if strings.TrimSpace(inst.JID()) == nonADJID {+ return true+ }+ }+ return false+}+func (m *DeviceManager) RemoveDevice(id string) {m.mu.Lock()defer m.mu.Unlock()@@ -266,6 +321,11 @@ func (m *DeviceManager) PurgeDevice(ctx context.Context, deviceID string) errorreturn fmt.Errorf("device id is required")}+ inst, resolvedID, err := m.resolveDeviceForPurge(deviceID)+ if err != nil {+ return err+ }+var firstErr errorrecordErr := func(err error) {if err != nil {@@ -275,46 +335,58 @@ func (m *DeviceManager) PurgeDevice(ctx context.Context, deviceID string) error// Resolve the device's WhatsApp identity before tearing anything down so we can// delete its whatsmeow store rows even when no live client is attached.- var jid string- if inst, ok := m.GetDevice(deviceID); ok && inst != nil {- jid = storeIdentity(inst)- if cli := inst.GetClient(); cli != nil {- // The WhatsApp unlink is best-effort: a dead/expired session may fail- // here, but that must not block local cleanup or fail the purge.- if err := cli.Logout(ctx); err != nil {- logrus.WithError(err).Warnf("[DEVICE_MANAGER] remote unlink failed for device %s (best-effort)", deviceID)- }- cli.Disconnect()+ jid := storeIdentity(inst)+ if cli := inst.GetClient(); cli != nil {+ // A purge-triggered LoggedOut must not run the keep-slot callback: that+ // would resurrect the slot (and persist it) while DELETE promises removal.+ inst.SetOnLoggedOut(nil)+ // The WhatsApp unlink is best-effort: a dead/expired session may fail+ // here, but that must not block local cleanup or fail the purge.+ if err := cli.Logout(ctx); err != nil {+ logrus.WithError(err).Warnf("[DEVICE_MANAGER] remote unlink failed for device %s (best-effort)", resolvedID)}+ cli.Disconnect()}// Delete chatstorage data for this device (local cleanup — surfaced on failure).+ // Chats/messages are partitioned by the WhatsApp JID once paired, while the+ // registry slot keeps its own id — purge both keys when they differ.if m.storage != nil {- if err := m.storage.DeleteDeviceData(deviceID); err != nil {- logrus.WithError(err).Warnf("[DEVICE_MANAGER] failed to delete chatstorage for device %s", deviceID)- recordErr(err)+ partitionKeys := []string{resolvedID}+ if jidKey := strings.TrimSpace(inst.JID()); jidKey != "" && jidKey != resolvedID {+ if !m.nonADJIDClaimedByOtherSlot(resolvedID, jidKey) {+ partitionKeys = append(partitionKeys, jidKey)+ } else {+ logrus.Warnf("[DEVICE_MANAGER] skipping shared chatstorage partition %s for slot %s (another slot still claims this number)", jidKey, resolvedID)+ }+ }+ for _, key := range partitionKeys {+ if err := m.storage.DeleteDeviceData(key); err != nil {+ logrus.WithError(err).Warnf("[DEVICE_MANAGER] failed to delete chatstorage for device %s (partition %s)", resolvedID, key)+ recordErr(err)+ }}// Drop the device's Chatwoot config (and its message links) with it. An// orphaned row would keep claiming the device's JID under the unique// device_jid index, blocking a re-created device for the same number from// being configured.- if cfg, err := m.storage.GetChatwootDeviceConfig(deviceID); err != nil {- logrus.WithError(err).Warnf("[DEVICE_MANAGER] failed to load chatwoot config for device %s", deviceID)+ if cfg, err := m.storage.GetChatwootDeviceConfig(resolvedID); err != nil {+ logrus.WithError(err).Warnf("[DEVICE_MANAGER] failed to load chatwoot config for device %s", resolvedID)recordErr(err)} else if cfg != nil {- if err := m.storage.DeleteChatwootDeviceConfig(deviceID); err != nil {- logrus.WithError(err).Warnf("[DEVICE_MANAGER] failed to delete chatwoot config for device %s", deviceID)+ if err := m.storage.DeleteChatwootDeviceConfig(resolvedID); err != nil {+ logrus.WithError(err).Warnf("[DEVICE_MANAGER] failed to delete chatwoot config for device %s", resolvedID)recordErr(err)} else {if cfg.ID != 0 {if err := m.storage.DeleteChatwootMessageLinksByConfig(cfg.ID); err != nil {- logrus.WithError(err).Warnf("[DEVICE_MANAGER] failed to delete chatwoot links for device %s", deviceID)+ logrus.WithError(err).Warnf("[DEVICE_MANAGER] failed to delete chatwoot links for device %s", resolvedID)recordErr(err)}}if reg := chatwoot.GetClientRegistry(); reg != nil {- reg.Invalidate(deviceID)+ reg.Invalidate(resolvedID)}}}@@ -323,8 +395,10 @@ func (m *DeviceManager) PurgeDevice(ctx context.Context, deviceID string) error// Delete whatsmeow store/keys rows by JID (local cleanup — surfaced on failure).recordErr(m.deleteStoreRowsForJID(ctx, jid))- // Remove from registry last- m.RemoveDevice(deviceID)+ // Keep the registry entry when local cleanup failed so DELETE can be retried.+ if firstErr == nil {+ m.RemoveDevice(resolvedID)+ }return firstErr}diff --git a/src/ui/rest/chatwoot.go b/src/ui/rest/chatwoot.goindex 3e0ea2ad..6e3516f7 100644--- a/src/ui/rest/chatwoot.go+++ b/src/ui/rest/chatwoot.go@@ -377,7 +377,7 @@ func (h *ChatwootHandler) HandleDeviceWebhook(c fiber.Ctx) error {// JID). Unknown ids are acknowledged without processing — this endpoint can// be reached unauthenticated, so it must neither leak which device ids exist// nor grow the client-registry cache with arbitrary identifiers.- deviceID := strings.TrimSpace(c.Params("device_id"))+ deviceID := pathDeviceID(c)if h.DeviceManager != nil {resolved, ok := h.resolveConfigDeviceID(c)if !ok {diff --git a/src/ui/rest/chatwoot_config.go b/src/ui/rest/chatwoot_config.goindex 76fb24a6..6ccadb7b 100644--- a/src/ui/rest/chatwoot_config.go+++ b/src/ui/rest/chatwoot_config.go@@ -202,7 +202,7 @@ func (h *ChatwootHandler) DeleteChatwootConfig(c fiber.Ctx) error {// param so a config orphaned by device removal stays deletable.deviceID, ok := h.resolveConfigDeviceID(c)if !ok {- deviceID = strings.TrimSpace(c.Params("device_id"))+ deviceID = pathDeviceID(c)}if deviceID == "" {return utils.ResponseError(c, "device_id is required")@@ -233,7 +233,7 @@ func (h *ChatwootHandler) DeleteChatwootConfig(c fiber.Ctx) error {// request. Handlers persist this id (config rows, registry cache), so an// uncopied value would mutate under the next request.func (h *ChatwootHandler) resolveConfigDeviceID(c fiber.Ctx) (string, bool) {- deviceID := strings.TrimSpace(c.Params("device_id"))+ deviceID := pathDeviceID(c)if deviceID == "" || h.DeviceManager == nil {return "", false}diff --git a/src/ui/rest/device.go b/src/ui/rest/device.goindex fd89ce65..e3777de6 100644--- a/src/ui/rest/device.go+++ b/src/ui/rest/device.go@@ -47,7 +47,7 @@ func (handler *Device) ListDevices(c fiber.Ctx) error {}func (handler *Device) GetDevice(c fiber.Ctx) error {- deviceID := c.Params("device_id")+ deviceID := pathDeviceID(c)device, err := handler.Service.GetDevice(c.Context(), deviceID)utils.PanicIfNeeded(err)@@ -113,7 +113,7 @@ func (handler *Device) AddDevice(c fiber.Ctx) error {}func (handler *Device) RemoveDevice(c fiber.Ctx) error {- deviceID := c.Params("device_id")+ deviceID := pathDeviceID(c)err := handler.Service.RemoveDevice(c.Context(), deviceID)utils.PanicIfNeeded(err)@@ -126,7 +126,7 @@ func (handler *Device) RemoveDevice(c fiber.Ctx) error {}func (handler *Device) LoginDevice(c fiber.Ctx) error {- deviceID := c.Params("device_id")+ deviceID := pathDeviceID(c)response, err := handler.Service.LoginDevice(c.Context(), deviceID)utils.PanicIfNeeded(err)@@ -143,7 +143,7 @@ func (handler *Device) LoginDevice(c fiber.Ctx) error {}func (handler *Device) LoginDeviceWithCode(c fiber.Ctx) error {- deviceID := c.Params("device_id")+ deviceID := pathDeviceID(c)code, err := handler.Service.LoginDeviceWithCode(c.Context(), deviceID, c.Query("phone"))utils.PanicIfNeeded(err)@@ -159,7 +159,7 @@ func (handler *Device) LoginDeviceWithCode(c fiber.Ctx) error {}func (handler *Device) LogoutDevice(c fiber.Ctx) error {- deviceID := c.Params("device_id")+ deviceID := pathDeviceID(c)err := handler.Service.LogoutDevice(c.Context(), deviceID)utils.PanicIfNeeded(err)@@ -172,7 +172,7 @@ func (handler *Device) LogoutDevice(c fiber.Ctx) error {}func (handler *Device) ReconnectDevice(c fiber.Ctx) error {- deviceID := c.Params("device_id")+ deviceID := pathDeviceID(c)err := handler.Service.ReconnectDevice(c.Context(), deviceID)utils.PanicIfNeeded(err)@@ -185,7 +185,7 @@ func (handler *Device) ReconnectDevice(c fiber.Ctx) error {}func (handler *Device) Status(c fiber.Ctx) error {- deviceID := c.Params("device_id")+ deviceID := pathDeviceID(c)isConnected, isLoggedIn, err := handler.Service.GetStatus(c.Context(), deviceID)utils.PanicIfNeeded(err)@@ -203,7 +203,7 @@ func (handler *Device) Status(c fiber.Ctx) error {// UpdateDeviceWebhook handles PATCH /devices/:device_id/webhook.func (handler *Device) UpdateDeviceWebhook(c fiber.Ctx) error {- deviceID := c.Params("device_id")+ deviceID := pathDeviceID(c)var req struct {WebhookURL *string `json:"webhook_url"`WebhookSecret string `json:"webhook_secret"`@@ -255,7 +255,7 @@ func (handler *Device) UpdateDeviceWebhook(c fiber.Ctx) error {// GetDeviceWebhook handles GET /devices/:device_id/webhook.func (handler *Device) GetDeviceWebhook(c fiber.Ctx) error {- deviceID := c.Params("device_id")+ deviceID := pathDeviceID(c)config, err := handler.Service.GetDeviceWebhookConfig(c.Context(), deviceID)utils.PanicIfNeeded(err)diff --git a/src/ui/rest/device_path_param_test.go b/src/ui/rest/device_path_param_test.gonew file mode 100644index 00000000..baccfd74--- /dev/null+++ b/src/ui/rest/device_path_param_test.go@@ -0,0 +1,27 @@+package rest++import (+ "io"+ "net/http"+ "net/http/httptest"+ "testing"++ "github.com/gofiber/fiber/v3"+)++func TestPathDeviceID_DecodesPercentEncodedSpace(t *testing.T) {+ app := fiber.New()+ app.Get("/devices/:device_id", func(c fiber.Ctx) error {+ return c.SendString(pathDeviceID(c))+ })++ req := httptest.NewRequest(http.MethodGet, "/devices/Estar%20Siempre", nil)+ resp, err := app.Test(req)+ if err != nil {+ t.Fatalf("request failed: %v", err)+ }+ body, _ := io.ReadAll(resp.Body)+ if string(body) != "Estar Siempre" {+ t.Fatalf("expected decoded device id, got %q", body)+ }+}diff --git a/src/ui/rest/params.go b/src/ui/rest/params.gonew file mode 100644index 00000000..009e58b7--- /dev/null+++ b/src/ui/rest/params.go@@ -0,0 +1,22 @@+package rest++import (+ "net/url"+ "strings"++ "github.com/gofiber/fiber/v3"+)++// pathDeviceID returns the :device_id route parameter, path-unescaped so clients+// may safely use encodeURIComponent. Fiber v3 leaves percent-escapes in Params.+func pathDeviceID(c fiber.Ctx) string {+ raw := strings.TrimSpace(c.Params("device_id"))+ if raw == "" {+ return ""+ }+ decoded, err := url.PathUnescape(raw)+ if err != nil {+ return raw+ }+ return decoded+}diff --git a/src/usecase/device.go b/src/usecase/device.goindex e0e8bd70..0544d5a8 100644--- a/src/usecase/device.go+++ b/src/usecase/device.go@@ -3,6 +3,7 @@ package usecaseimport ("context""fmt"+ "strings"domainApp "github.com/aldinokemal/go-whatsapp-web-multidevice/domains/app""github.com/aldinokemal/go-whatsapp-web-multidevice/domains/chatstorage"@@ -96,9 +97,28 @@ func (s *serviceDevice) RemoveDevice(ctx context.Context, deviceID string) error// cleanup (chatstorage / store / keys rows) are surfaced: DELETE promises a real// purge, so we propagate the error instead of masking it as success.if err := s.manager.PurgeDevice(ctx, deviceID); err != nil {+ if strings.Contains(err.Error(), "not found") {+ return pkgError.ErrDeviceNotFound+ }logrus.WithError(err).Warnf("[DEVICE] purge for %s failed", deviceID)return fmt.Errorf("purge device %s: %w", deviceID, err)}++ var devices []domainDevice.Device+ for _, inst := range s.manager.ListDevices() {+ inst.UpdateStateFromClient()+ devices = append(devices, convertInstance(inst))+ }++ websocket.Broadcast <- websocket.BroadcastMessage{+ Code: "DEVICE_REMOVED",+ Message: fmt.Sprintf("Device %s removed", deviceID),+ Result: map[string]any{+ "device_id": deviceID,+ "devices": devices,+ },+ }+return nil}