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(device): logout should disconnect session, not delete device entry (#728)

Hub Operacional4d39e10f2772
diff --git a/docs/openapi.yaml b/docs/openapi.yaml
index d8eedc21..c2f3c590 100644
--- a/docs/openapi.yaml
+++ b/docs/openapi.yaml
@@ -88,7 +88,11 @@ paths:
operationId: appLogout
tags:
- app
- summary: Remove database and logout
+ summary: Logout the active device (keeps the device slot)
+ description: >-
+ Logs the active device out of WhatsApp and clears its session. The device
+ slot (id and display name) is kept, so it stays listed (disconnected) and
+ can be re-paired under the same id. Use DELETE /devices/{device_id} to remove the slot.
parameters:
- $ref: '#/components/parameters/DeviceIdHeader'
responses:
@@ -299,7 +303,10 @@ paths:
tags:
- device
summary: Remove a device
- description: Remove a device from the server (does not logout from WhatsApp)
+ description: >-
+ Remove a device slot from the server. This also logs it out of WhatsApp and
+ clears its session and chat data. To log out while keeping the slot, use the
+ logout endpoint instead.
parameters:
- name: device_id
in: path
@@ -408,7 +415,10 @@ paths:
tags:
- device
summary: Logout device
- description: Logout a specific device from WhatsApp and remove its session
+ description: >-
+ Logs a specific device out of WhatsApp and clears its session, but keeps the
+ device slot (id and display name) so it can be re-paired under the same id.
+ To remove the slot entirely, use DELETE /devices/{device_id}.
parameters:
- name: device_id
in: path
diff --git a/src/infrastructure/whatsapp/device_instance.go b/src/infrastructure/whatsapp/device_instance.go
index cc5058c4..20e4e2e2 100644
--- a/src/infrastructure/whatsapp/device_instance.go
+++ b/src/infrastructure/whatsapp/device_instance.go
@@ -101,6 +101,19 @@ func (d *DeviceInstance) SetClient(client *whatsmeow.Client) {
d.state = domainDevice.DeviceStateDisconnected
}
+// ResetClient detaches the WhatsApp client and clears the session-derived identity
+// (jid, phone number) so the slot can be re-paired with a fresh client on the next
+// login. The device id, display name and creation time are preserved, keeping the
+// slot in place after a logout.
+func (d *DeviceInstance) ResetClient() {
+ d.mu.Lock()
+ defer d.mu.Unlock()
+ d.client = nil
+ d.jid = ""
+ d.phoneNumber = ""
+ d.state = domainDevice.DeviceStateDisconnected
+}
+
// SetChatStorage swaps the chat storage repository for this device.
func (d *DeviceInstance) SetChatStorage(repo domainChatStorage.IChatStorageRepository) {
d.mu.Lock()
diff --git a/src/infrastructure/whatsapp/device_logout_keepslot_test.go b/src/infrastructure/whatsapp/device_logout_keepslot_test.go
new file mode 100644
index 00000000..1d2617c7
--- /dev/null
+++ b/src/infrastructure/whatsapp/device_logout_keepslot_test.go
@@ -0,0 +1,356 @@
+package whatsapp
+
+import (
+ "context"
+ "errors"
+ "strings"
+ "testing"
+ "time"
+
+ domainChatStorage "github.com/aldinokemal/go-whatsapp-web-multidevice/domains/chatstorage"
+ "github.com/sirupsen/logrus"
+ logrustest "github.com/sirupsen/logrus/hooks/test"
+ "go.mau.fi/whatsmeow"
+ "go.mau.fi/whatsmeow/store/sqlstore"
+ "go.mau.fi/whatsmeow/types"
+)
+
+// keepSlotStubStorage is a minimal IChatStorageRepository that records the device
+// registry calls exercised by the logout/purge paths and can be told to fail, so the
+// tests can assert error propagation. All other interface methods are nil (embedded)
+// and must not be called by the code under test.
+type keepSlotStubStorage struct {
+ domainChatStorage.IChatStorageRepository
+ saveErr error
+ deleteDataErr error
+ savedRecords []*domainChatStorage.DeviceRecord
+ deletedData []string
+ deletedRecords []string
+}
+
+func (s *keepSlotStubStorage) SaveDeviceRecord(rec *domainChatStorage.DeviceRecord) error {
+ cloned := *rec
+ s.savedRecords = append(s.savedRecords, &cloned)
+ return s.saveErr
+}
+
+func (s *keepSlotStubStorage) DeleteDeviceData(deviceID string) error {
+ s.deletedData = append(s.deletedData, deviceID)
+ return s.deleteDataErr
+}
+
+func (s *keepSlotStubStorage) DeleteDeviceRecord(deviceID string) error {
+ s.deletedRecords = append(s.deletedRecords, deviceID)
+ return 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) {
+ t.Helper()
+ devices, err := c.GetAllDevices(ctx)
+ if err != nil {
+ t.Fatalf("get all devices: %v", err)
+ }
+ for _, d := range devices {
+ if d != nil && d.ID != nil && d.ID.ToNonAD().String() == nonADJID {
+ t.Fatalf("expected store to no longer contain jid %s", nonADJID)
+ }
+ }
+}
+
+// Scenario: keep-slot logout for a slot that was loaded from storage with NO live
+// client (the case aldinokemal flagged at device_manager.go:240). The orphan whatsmeow
+// rows must be deleted by JID from BOTH the primary and the separate keys container,
+// while the slot itself (id + display name) is preserved with an empty persisted JID.
+// The slot id is deliberately different from the JID to prove matching is by JID, not
+// by the slot id (the latent AD-JID-vs-slot-id mismatch in the old code).
+func TestLogoutDeviceKeepSlot_NoClientDeletesStoreRowsByJIDKeepsSlot(t *testing.T) {
+ ctx := context.Background()
+ primaryStore := newTestSQLStore(t)
+ keysStore := newTestSQLStore(t)
+
+ adJID := types.NewADJID("6281999999991", types.WhatsAppDomain, 10)
+ nonAD := adJID.ToNonAD().String()
+ if err := newTestStoreDevice(primaryStore, adJID, "primary").Save(ctx); err != nil {
+ t.Fatalf("save primary device: %v", err)
+ }
+ if err := newTestStoreDevice(keysStore, adJID, "keys").Save(ctx); err != nil {
+ t.Fatalf("save keys device: %v", err)
+ }
+
+ storage := &keepSlotStubStorage{}
+ manager := NewDeviceManager(primaryStore, keysStore, storage)
+
+ const slotID = "slot-uuid-1" // intentionally != JID
+ inst := &DeviceInstance{id: slotID, jid: nonAD, displayName: "tIAtendo", createdAt: time.Now()}
+ manager.devices[slotID] = inst
+
+ if err := manager.LogoutDeviceKeepSlot(ctx, slotID); err != nil {
+ t.Fatalf("LogoutDeviceKeepSlot returned error: %v", err)
+ }
+
+ assertStoreLacksJID(t, ctx, primaryStore, nonAD)
+ assertStoreLacksJID(t, ctx, keysStore, nonAD)
+
+ if _, ok := manager.GetDevice(slotID); !ok {
+ t.Fatal("expected slot to be kept after logout")
+ }
+ if got := inst.JID(); got != "" {
+ t.Fatalf("expected instance JID cleared after logout, got %q", got)
+ }
+ if len(storage.savedRecords) == 0 {
+ t.Fatal("expected SaveDeviceRecord to persist the kept slot")
+ }
+ last := storage.savedRecords[len(storage.savedRecords)-1]
+ if last.DeviceID != slotID || last.JID != "" {
+ t.Fatalf("expected persisted slot %s with empty JID, got %s / %q", slotID, last.DeviceID, last.JID)
+ }
+}
+
+// Scenario: DELETE purge removes the whatsmeow rows by JID from both containers even
+// when the slot id differs from the JID (the old code compared the AD JID string to the
+// slot id and never matched, so the rows were never deleted), and removes the slot.
+func TestPurgeDevice_DeletesStoreRowsByJIDAcrossPrimaryAndKeys(t *testing.T) {
+ ctx := context.Background()
+ primaryStore := newTestSQLStore(t)
+ keysStore := newTestSQLStore(t)
+
+ adJID := types.NewADJID("6281999999992", types.WhatsAppDomain, 11)
+ nonAD := adJID.ToNonAD().String()
+ if err := newTestStoreDevice(primaryStore, adJID, "primary").Save(ctx); err != nil {
+ t.Fatalf("save primary device: %v", err)
+ }
+ if err := newTestStoreDevice(keysStore, adJID, "keys").Save(ctx); err != nil {
+ t.Fatalf("save keys device: %v", err)
+ }
+
+ storage := &keepSlotStubStorage{}
+ manager := NewDeviceManager(primaryStore, keysStore, storage)
+
+ const slotID = "slot-uuid-2"
+ manager.devices[slotID] = &DeviceInstance{id: slotID, jid: nonAD, displayName: "tIAtendo", createdAt: time.Now()}
+
+ if err := manager.PurgeDevice(ctx, slotID); err != nil {
+ t.Fatalf("PurgeDevice returned error: %v", err)
+ }
+
+ assertStoreLacksJID(t, ctx, primaryStore, nonAD)
+ assertStoreLacksJID(t, ctx, keysStore, nonAD)
+
+ if _, ok := manager.GetDevice(slotID); ok {
+ t.Fatal("expected slot to be removed after purge")
+ }
+ if len(storage.deletedData) == 0 || storage.deletedData[0] != slotID {
+ t.Fatalf("expected chatstorage data deletion for %s, got %v", slotID, storage.deletedData)
+ }
+ if len(storage.deletedRecords) == 0 || storage.deletedRecords[0] != slotID {
+ t.Fatalf("expected device record deletion for %s, got %v", slotID, storage.deletedRecords)
+ }
+}
+
+// resetDeviceKeepSlot must surface a persistence failure instead of silently
+// succeeding (coderabbitai device_manager.go:252-276), and LogoutDeviceKeepSlot must
+// combine that error into its return value.
+func TestResetDeviceKeepSlot_PropagatesSaveError(t *testing.T) {
+ ctx := context.Background()
+ storage := &keepSlotStubStorage{saveErr: errors.New("disk full")}
+ manager := NewDeviceManager(nil, nil, storage)
+
+ const slotID = "slot-persist-err"
+ manager.devices[slotID] = &DeviceInstance{id: slotID, jid: "[email protected]", createdAt: time.Now()}
+
+ if err := manager.resetDeviceKeepSlot(slotID); err == nil || !strings.Contains(err.Error(), "disk full") {
+ t.Fatalf("expected resetDeviceKeepSlot to propagate save error, got %v", err)
+ }
+
+ if err := manager.LogoutDeviceKeepSlot(ctx, slotID); err == nil || !strings.Contains(err.Error(), "disk full") {
+ t.Fatalf("expected LogoutDeviceKeepSlot to surface the persistence error, got %v", err)
+ }
+}
+
+// DELETE promises a real purge: a LOCAL cleanup failure (chatstorage/store/keys) must
+// be surfaced, not masked as success (aldinokemal/coderabbitai usecase device.go:68).
+func TestPurgeDevice_SurfacesLocalCleanupFailure(t *testing.T) {
+ ctx := context.Background()
+ storage := &keepSlotStubStorage{deleteDataErr: errors.New("chatstorage down")}
+ manager := NewDeviceManager(nil, nil, storage)
+
+ 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") {
+ t.Fatalf("expected PurgeDevice to surface the local cleanup failure, got %v", err)
+ }
+}
+
+// deleteStoreRowsForJID is a no-op for an empty JID: a slot that was never paired has no
+// store rows, and an empty JID must never scan/delete anything.
+func TestDeleteStoreRowsForJID_EmptyJIDIsNoOp(t *testing.T) {
+ ctx := context.Background()
+ primaryStore := newTestSQLStore(t)
+ adJID := types.NewADJID("6281999999994", types.WhatsAppDomain, 12)
+ if err := newTestStoreDevice(primaryStore, adJID, "primary").Save(ctx); err != nil {
+ t.Fatalf("save primary device: %v", err)
+ }
+
+ manager := NewDeviceManager(primaryStore, nil, nil)
+ if err := manager.deleteStoreRowsForJID(ctx, ""); err != nil {
+ t.Fatalf("expected empty-jid no-op, got error: %v", err)
+ }
+
+ devices, err := primaryStore.GetAllDevices(ctx)
+ if err != nil {
+ t.Fatalf("get all devices: %v", err)
+ }
+ if len(devices) != 1 {
+ t.Fatalf("expected the unrelated device to be retained, got %d devices", len(devices))
+ }
+}
+
+// Scenario: the remote-logout callback holds a stale device id. InitWaCLI registers the
+// callback with the instance's AD JID string (device.ID.String()), but loadFromRegistry
+// can replace that instance with a named registry slot keyed by uuid (same account,
+// NonAD JID). keepSlotLogout must then fall back to resolving the slot by JID, so the
+// cleanup still deletes the store rows and clears the slot instead of no-opping with
+// "device not found" (leaving a stale JID + orphan keys row).
+func TestKeepSlotLogout_StaleADJIDFallsBackToJIDResolution(t *testing.T) {
+ ctx := context.Background()
+ primaryStore := newTestSQLStore(t)
+ keysStore := newTestSQLStore(t)
+
+ adJID := types.NewADJID("6281999999996", types.WhatsAppDomain, 14)
+ nonAD := adJID.ToNonAD().String()
+ if err := newTestStoreDevice(primaryStore, adJID, "primary").Save(ctx); err != nil {
+ t.Fatalf("save primary device: %v", err)
+ }
+ if err := newTestStoreDevice(keysStore, adJID, "keys").Save(ctx); err != nil {
+ t.Fatalf("save keys device: %v", err)
+ }
+
+ storage := &keepSlotStubStorage{}
+ manager := NewDeviceManager(primaryStore, keysStore, storage)
+
+ // The registry slot that replaced the startup instance: keyed by uuid, NonAD JID.
+ const slotID = "slot-uuid-3"
+ inst := &DeviceInstance{id: slotID, jid: nonAD, displayName: "tIAtendo", createdAt: time.Now()}
+ manager.devices[slotID] = inst
+
+ // The stale id the startup path registered the callback with: the AD JID string.
+ if err := manager.keepSlotLogout(ctx, adJID.String()); err != nil {
+ t.Fatalf("keepSlotLogout with stale AD JID id returned error: %v", err)
+ }
+
+ assertStoreLacksJID(t, ctx, primaryStore, nonAD)
+ assertStoreLacksJID(t, ctx, keysStore, nonAD)
+
+ if _, ok := manager.GetDevice(slotID); !ok {
+ t.Fatal("expected slot to be kept after stale-id logout")
+ }
+ if got := inst.JID(); got != "" {
+ t.Fatalf("expected instance JID cleared after stale-id logout, got %q", got)
+ }
+ if len(storage.savedRecords) == 0 {
+ t.Fatal("expected SaveDeviceRecord to persist the kept slot")
+ }
+ last := storage.savedRecords[len(storage.savedRecords)-1]
+ if last.DeviceID != slotID || last.JID != "" {
+ t.Fatalf("expected persisted slot %s with empty JID, got %s / %q", slotID, last.DeviceID, last.JID)
+ }
+}
+
+// Scenario: explicit logout for a paired client that is currently DISCONNECTED.
+// IsLoggedIn() is only true while connected, so gating the unlink on it silently skips
+// the remove-companion-device IQ and the phone keeps showing the linked device forever
+// (the local session is deleted, so it can never reconnect to unlink later). The unlink
+// must be ATTEMPTED whenever the client is paired (Store.ID set); failure stays
+// best-effort and must not fail the local keep-slot cleanup.
+func TestLogoutDeviceKeepSlot_AttemptsUnlinkWhenPairedButDisconnected(t *testing.T) {
+ ctx := context.Background()
+ primaryStore := newTestSQLStore(t)
+
+ adJID := types.NewADJID("6281999999997", types.WhatsAppDomain, 15)
+ nonAD := adJID.ToNonAD().String()
+ dev := newTestStoreDevice(primaryStore, adJID, "primary")
+ if err := dev.Save(ctx); err != nil {
+ t.Fatalf("save primary device: %v", err)
+ }
+
+ // Real paired client (Store.ID set) that is not connected.
+ cli := whatsmeow.NewClient(dev, nil)
+
+ storage := &keepSlotStubStorage{}
+ manager := NewDeviceManager(primaryStore, nil, storage)
+
+ const slotID = "slot-uuid-4"
+ inst := &DeviceInstance{id: slotID, jid: nonAD, displayName: "tIAtendo", client: cli, createdAt: time.Now()}
+ manager.devices[slotID] = inst
+
+ hook := logrustest.NewLocal(logrus.StandardLogger())
+ defer hook.Reset()
+
+ if err := manager.LogoutDeviceKeepSlot(ctx, slotID); err != nil {
+ t.Fatalf("LogoutDeviceKeepSlot returned error: %v", err)
+ }
+
+ // The unlink attempt fails offline (best-effort), which is observable as the
+ // remote-unlink warning. No warning means the attempt was skipped entirely.
+ attempted := false
+ for _, entry := range hook.AllEntries() {
+ if strings.Contains(entry.Message, "remote unlink failed") {
+ attempted = true
+ }
+ }
+ if !attempted {
+ t.Fatal("expected cli.Logout to be attempted for a paired-but-disconnected client")
+ }
+
+ // Local keep-slot cleanup must still have run.
+ assertStoreLacksJID(t, ctx, primaryStore, nonAD)
+ if _, ok := manager.GetDevice(slotID); !ok {
+ t.Fatal("expected slot to be kept after logout")
+ }
+ if got := inst.JID(); got != "" {
+ t.Fatalf("expected instance JID cleared after logout, got %q", got)
+ }
+}
+
+// Remote logout (events.LoggedOut) keeps the slot: routing the SetOnLoggedOut callback
+// through keepSlotLogout (the same behavior both the lazy EnsureClient path and the
+// startup InitWaCLI path now use) deletes the whatsmeow rows by JID but preserves the
+// slot, instead of deleting it via RemoveDevice (aldinokemal device_manager.go:581).
+func TestRemoteLogoutCallback_KeepsSlot(t *testing.T) {
+ ctx := context.Background()
+ primaryStore := newTestSQLStore(t)
+ keysStore := newTestSQLStore(t)
+
+ adJID := types.NewADJID("6281999999995", types.WhatsAppDomain, 13)
+ nonAD := adJID.ToNonAD().String()
+ if err := newTestStoreDevice(primaryStore, adJID, "primary").Save(ctx); err != nil {
+ t.Fatalf("save primary device: %v", err)
+ }
+ if err := newTestStoreDevice(keysStore, adJID, "keys").Save(ctx); err != nil {
+ t.Fatalf("save keys device: %v", err)
+ }
+
+ storage := &keepSlotStubStorage{}
+ manager := NewDeviceManager(primaryStore, keysStore, storage)
+
+ inst := &DeviceInstance{id: nonAD, jid: nonAD, displayName: "tIAtendo", createdAt: time.Now()}
+ manager.devices[nonAD] = inst
+
+ // Wire the callback exactly as the manager does for remote logout.
+ inst.SetOnLoggedOut(func(deviceID string) {
+ if err := manager.keepSlotLogout(context.Background(), deviceID); err != nil {
+ t.Errorf("keepSlotLogout in remote-logout callback: %v", err)
+ }
+ })
+
+ inst.TriggerLoggedOut()
+
+ if _, ok := manager.GetDevice(nonAD); !ok {
+ t.Fatal("expected slot to be kept on remote logout, but it was removed")
+ }
+ assertStoreLacksJID(t, ctx, primaryStore, nonAD)
+ assertStoreLacksJID(t, ctx, keysStore, nonAD)
+}
diff --git a/src/infrastructure/whatsapp/device_manager.go b/src/infrastructure/whatsapp/device_manager.go
index 77f7e110..17e5f972 100644
--- a/src/infrastructure/whatsapp/device_manager.go
+++ b/src/infrastructure/whatsapp/device_manager.go
@@ -148,6 +148,49 @@ func (m *DeviceManager) RemoveDevice(id string) {
}
}
+// deleteStoreRowsForJID removes the whatsmeow device rows (primary + keys containers)
+// whose JID matches jid. Matching uses the NonAD form to mirror LoadExistingDevices,
+// where the devices table stores NonAD JIDs. It is idempotent — a row that is already
+// gone is simply not found — and an empty jid is a no-op (a slot that was never paired
+// has no store rows to delete).
+func (m *DeviceManager) deleteStoreRowsForJID(ctx context.Context, jid string) error {
+ if strings.TrimSpace(jid) == "" {
+ return nil
+ }
+
+ var firstErr error
+ deleteFrom := func(container *sqlstore.Container, label string) {
+ if container == nil {
+ return
+ }
+ devices, err := container.GetAllDevices(ctx)
+ if err != nil {
+ logrus.WithError(err).Warnf("[DEVICE_MANAGER] failed to enumerate %s devices for jid %s", label, jid)
+ firstErr = errors.Join(firstErr, err)
+ return
+ }
+ for _, dev := range devices {
+ if dev == nil || dev.ID == nil {
+ continue
+ }
+ if dev.ID.ToNonAD().String() != jid {
+ continue
+ }
+ if err := container.DeleteDevice(ctx, dev); err != nil {
+ logrus.WithError(err).Warnf("[DEVICE_MANAGER] failed to delete jid %s from %s store", jid, label)
+ firstErr = errors.Join(firstErr, err)
+ }
+ break
+ }
+ }
+
+ deleteFrom(m.store, "primary")
+ if m.keys != nil && m.keys != m.store {
+ deleteFrom(m.keys, "keys")
+ }
+ return firstErr
+}
+
// PurgeDevice cleanly logs out a device, removes its persisted records (store/keys),
// deletes its chatstorage data, and removes it from the in-memory registry.
func (m *DeviceManager) PurgeDevice(ctx context.Context, deviceID string) error {
@@ -162,18 +205,22 @@ func (m *DeviceManager) PurgeDevice(ctx context.Context, deviceID string) error
}
}
- // Attempt logout/disconnect if a client exists
+ // Resolve the device's WhatsApp JID before tearing anything down so we can delete
+ // its whatsmeow store rows by JID even when no live client is attached.
+ var jid string
if inst, ok := m.GetDevice(deviceID); ok && inst != nil {
+ jid = inst.JID()
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] logout failed for device %s", deviceID)
- recordErr(err)
+ logrus.WithError(err).Warnf("[DEVICE_MANAGER] remote unlink failed for device %s (best-effort)", deviceID)
}
cli.Disconnect()
}
}
- // Delete chatstorage data for this device
+ // Delete chatstorage data for this device (local cleanup — surfaced on failure).
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)
@@ -181,47 +228,106 @@ func (m *DeviceManager) PurgeDevice(ctx context.Context, deviceID string) error
}
}
- // Remove device records from primary store
- if m.store != nil {
- if devices, err := m.store.GetAllDevices(ctx); err != nil {
- logrus.WithError(err).Warn("[DEVICE_MANAGER] failed to enumerate devices for purge")
- recordErr(err)
- } else {
- for _, dev := range devices {
- if dev != nil && dev.ID != nil && dev.ID.String() == deviceID {
- if err := m.store.DeleteDevice(ctx, dev); err != nil {
- logrus.WithError(err).Warnf("[DEVICE_MANAGER] failed to delete device %s from store", deviceID)
- recordErr(err)
- }
- break
- }
- }
- }
+ // Delete whatsmeow store/keys rows by JID (local cleanup — surfaced on failure).
+ recordErr(m.deleteStoreRowsForJID(ctx, jid))
+
+ // Remove from registry last
+ m.RemoveDevice(deviceID)
+ return firstErr
+}
+
+// LogoutDeviceKeepSlot logs the device out of WhatsApp (clearing its session/keys)
+// but PRESERVES the device slot in the registry, so it keeps its id and display name
+// and can be re-paired later under the same id. Unlike PurgeDevice, it does not remove
+// the device record. Removing the slot entirely is the job of RemoveDevice (DELETE).
+func (m *DeviceManager) LogoutDeviceKeepSlot(ctx context.Context, deviceID string) error {
+ if deviceID == "" {
+ return fmt.Errorf("device id is required")
}
- // Remove device records from keys store if separate
- if m.keys != nil && m.keys != m.store {
- if devices, err := m.keys.GetAllDevices(ctx); err != nil {
- logrus.WithError(err).Warn("[DEVICE_MANAGER] failed to enumerate keys devices for purge")
- recordErr(err)
- } else {
- for _, dev := range devices {
- if dev != nil && dev.ID != nil && dev.ID.String() == deviceID {
- if err := m.keys.DeleteDevice(ctx, dev); err != nil {
- logrus.WithError(err).Warnf("[DEVICE_MANAGER] failed to delete device %s from keys store", deviceID)
- recordErr(err)
- }
- break
- }
+ inst, ok := m.GetDevice(deviceID)
+ if !ok || inst == nil {
+ return fmt.Errorf("device %s not found", deviceID)
+ }
+
+ if cli := inst.GetClient(); cli != nil {
+ // Attempt the unlink whenever the client is paired (Store.ID set), not only when
+ // IsLoggedIn: that is true only while connected, and skipping the attempt for a
+ // momentarily-offline client would leave the phone showing the linked device
+ // forever (the local session is deleted below, so it can never unlink later).
+ // The WhatsApp unlink is best-effort: a dead/expired session may fail
+ // here, but that must not block the local keep-slot cleanup below.
+ if cli.Store != nil && cli.Store.ID != nil {
+ if err := cli.Logout(ctx); err != nil {
+ logrus.WithError(err).Warnf("[DEVICE_MANAGER] remote unlink failed for device %s (best-effort)", deviceID)
}
}
+ cli.Disconnect()
}
- // Remove from registry last
- m.RemoveDevice(deviceID)
+ return m.keepSlotLogout(ctx, deviceID)
+}
+
+// keepSlotLogout is the shared "logout but keep the slot" cleanup used by both explicit
+// logout and the remote LoggedOut callbacks. It deletes the device's whatsmeow store
+// rows (by JID, resolved before the reset clears it) and resets the in-memory client +
+// persisted JID, keeping the slot (id + display name) for re-pairing. It does NOT call
+// cli.Logout — explicit logout handles the unlink before delegating here, and a remote
+// LoggedOut has already been unlinked on the phone.
+func (m *DeviceManager) keepSlotLogout(ctx context.Context, deviceID string) error {
+ inst, ok := m.GetDevice(deviceID)
+ if !ok || inst == nil {
+ // The remote-logout callback can hold a stale id: InitWaCLI keys its instance by
+ // the AD JID string, but loadFromRegistry may replace it with a registry slot
+ // keyed by uuid (instances store NonAD JIDs). Fall back to JID resolution so the
+ // cleanup still lands on the surviving slot instead of leaving a stale JID and
+ // an orphan keys-container row.
+ if parsed, err := types.ParseJID(deviceID); err == nil && parsed.User != "" {
+ inst, ok = m.getDeviceByJID(parsed.ToNonAD().String())
+ }
+ if !ok || inst == nil {
+ return fmt.Errorf("device %s not found", deviceID)
+ }
+ deviceID = inst.ID()
+ }
+
+ // Resolve the JID before resetDeviceKeepSlot clears it, so we can delete the stored
+ // whatsmeow rows even when no live client is attached (slot loaded from storage).
+ // Always delete (don't rely on cli.Logout having done it): an orphan row would
+ // otherwise get matched back on restart. Idempotent when the row is already gone.
+ jid := inst.JID()
+
+ var firstErr error
+ firstErr = errors.Join(firstErr, m.deleteStoreRowsForJID(ctx, jid))
+ firstErr = errors.Join(firstErr, m.resetDeviceKeepSlot(deviceID))
return firstErr
}
+// resetDeviceKeepSlot detaches the in-memory client and clears the persisted session
+// identity (jid) while keeping the device slot (id + display name) in both the
+// in-memory registry and the persisted device registry. EnsureClient rebuilds a
+// fresh client on the next login, so the slot can be re-paired under the same id.
+func (m *DeviceManager) resetDeviceKeepSlot(deviceID string) error {
+ inst, ok := m.GetDevice(deviceID)
+ if !ok || inst == nil {
+ return fmt.Errorf("device %s not found", deviceID)
+ }
+ inst.ResetClient()
+
+ if m.storage != nil && strings.TrimSpace(deviceID) != "" {
+ if err := m.storage.SaveDeviceRecord(&domainChatStorage.DeviceRecord{
+ DeviceID: deviceID,
+ DisplayName: inst.DisplayName(),
+ JID: "",
+ CreatedAt: inst.CreatedAt(),
+ UpdatedAt: time.Now(),
+ }); err != nil {
+ return fmt.Errorf("persist logged-out device %s: %w", deviceID, err)
+ }
+ }
+ return nil
+}
+
// CreateDevice registers a new device placeholder so routes can be scoped strictly by device_id.
func (m *DeviceManager) CreateDevice(ctx context.Context, requestedID string) (*DeviceInstance, error) {
if m == nil {
@@ -523,7 +629,12 @@ func (m *DeviceManager) EnsureClient(ctx context.Context, deviceID string) (*Dev
})
inst.SetOnLoggedOut(func(deviceID string) {
- m.RemoveDevice(deviceID)
+ // On remote logout (device unlinked from the phone) keep the slot so it can
+ // be re-paired under the same id, matching the explicit logout semantics.
+ // Use a fresh context: the original request ctx may already be cancelled.
+ if err := m.keepSlotLogout(context.Background(), deviceID); err != nil {
+ logrus.WithError(err).Warnf("[REMOTE_LOGOUT] keep-slot cleanup failed for %s", deviceID)
+ }
})
inst.SetClient(client)
diff --git a/src/infrastructure/whatsapp/event_handler.go b/src/infrastructure/whatsapp/event_handler.go
index 4982004e..29a39ac7 100644
--- a/src/infrastructure/whatsapp/event_handler.go
+++ b/src/infrastructure/whatsapp/event_handler.go
@@ -39,7 +39,7 @@ func handler(ctx context.Context, instance *DeviceInstance, rawEvt any) {
case *events.PairSuccess:
handlePairSuccess(ctx, evt)
case *events.LoggedOut:
- handleLoggedOut(ctx, instance, chatStorageRepo)
+ handleLoggedOut(instance)
case *events.Connected, *events.PushNameSetting:
handleConnectionEvents(ctx, client, instance)
case *events.StreamReplaced:
@@ -153,7 +153,7 @@ func handlePairSuccess(ctx context.Context, evt *events.PairSuccess) {
syncKeysDevice(ctx, primaryDB, secondaryDB, evt.ID)
}
-func handleLoggedOut(ctx context.Context, instance *DeviceInstance, chatStorageRepo domainChatStorage.IChatStorageRepository) {
+func handleLoggedOut(instance *DeviceInstance) {
logrus.Warnf("[REMOTE_LOGOUT] Received LoggedOut event for device %s - user logged out from phone", instance.ID())
if client := instance.GetClient(); client != nil {
@@ -161,19 +161,19 @@ func handleLoggedOut(ctx context.Context, instance *DeviceInstance, chatStorageR
}
instance.SetState(domainDevice.DeviceStateDisconnected)
- if chatStorageRepo != nil {
- if err := chatStorageRepo.TruncateAllDataWithLogging("REMOTE_LOGOUT"); err != nil {
- logrus.Errorf("[REMOTE_LOGOUT] Failed to truncate chat storage: %v", err)
- }
- }
+ // Chat history is intentionally preserved on remote logout (it is only cleared on
+ // a full purge via DELETE). A remote logout keeps the device slot, so truncating
+ // here would contradict the keep-slot semantics and lose the conversation history.
deviceID := instance.ID()
+ // 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()
websocket.Broadcast <- websocket.BroadcastMessage{
- Code: "LOGOUT_COMPLETE",
- Message: "Remote logout cleanup completed - device removed from server",
+ Code: "DEVICE_LOGGED_OUT",
+ Message: "Device logged out (slot kept)",
Result: map[string]string{"device_id": deviceID},
}
}
diff --git a/src/infrastructure/whatsapp/init.go b/src/infrastructure/whatsapp/init.go
index 9ac14b34..0a3b5826 100644
--- a/src/infrastructure/whatsapp/init.go
+++ b/src/infrastructure/whatsapp/init.go
@@ -8,6 +8,7 @@ import (
"github.com/aldinokemal/go-whatsapp-web-multidevice/config"
domainChatStorage "github.com/aldinokemal/go-whatsapp-web-multidevice/domains/chatstorage"
+ "github.com/sirupsen/logrus"
"go.mau.fi/whatsmeow"
"go.mau.fi/whatsmeow/store"
"go.mau.fi/whatsmeow/store/sqlstore"
@@ -121,7 +122,11 @@ func InitWaCLI(ctx context.Context, storeContainer, keysStoreContainer *sqlstore
if dm != nil && instanceID != "" {
dm.EnsureDefault(instance)
instance.SetOnLoggedOut(func(deviceID string) {
- dm.RemoveDevice(deviceID)
+ // Route the startup path through the same keep-slot cleanup as the lazy
+ // EnsureClient path, so a remote logout never deletes the device slot.
+ if err := dm.keepSlotLogout(context.Background(), deviceID); err != nil {
+ logrus.WithError(err).Warnf("[REMOTE_LOGOUT] keep-slot cleanup failed for %s", deviceID)
+ }
})
}
diff --git a/src/usecase/app.go b/src/usecase/app.go
index e84ec927..7404ac50 100644
--- a/src/usecase/app.go
+++ b/src/usecase/app.go
@@ -160,26 +160,30 @@ func (service *serviceApp) LoginWithCode(ctx context.Context, deviceID string, p
}
func (service *serviceApp) Logout(ctx context.Context, deviceID string) error {
+ if err := validations.ValidateDeviceID(ctx, deviceID); err != nil {
+ return err
+ }
if service.deviceManager == nil {
return fmt.Errorf("device manager not initialized")
}
- if err := service.deviceManager.PurgeDevice(ctx, deviceID); err != nil {
- logrus.WithError(err).Warnf("[LOGOUT][%s] purge completed with warnings", deviceID)
+ if err := service.deviceManager.LogoutDeviceKeepSlot(ctx, deviceID); err != nil {
+ logrus.WithError(err).Warnf("[LOGOUT][%s] logout completed with warnings", deviceID)
return err
}
- // Broadcast device removal so UI can refresh without manual polling
+ // Broadcast the logout so the UI can refresh without manual polling. The slot is
+ // kept, so the device stays listed (disconnected) and can be re-paired by id.
var devices []domainApp.DevicesResponse
if list, err := service.FetchDevices(ctx); err == nil {
devices = list
} else {
- logrus.WithError(err).Warn("[LOGOUT] failed to fetch devices after purge")
+ logrus.WithError(err).Warn("[LOGOUT] failed to fetch devices after logout")
}
websocket.Broadcast <- websocket.BroadcastMessage{
- Code: "DEVICE_REMOVED",
- Message: fmt.Sprintf("Device %s logged out and removed", deviceID),
+ Code: "DEVICE_LOGGED_OUT",
+ Message: fmt.Sprintf("Device %s logged out (slot kept)", deviceID),
Result: map[string]any{
"device_id": deviceID,
"devices": devices,
diff --git a/src/usecase/device.go b/src/usecase/device.go
index cb9e14e8..48e5ea32 100644
--- a/src/usecase/device.go
+++ b/src/usecase/device.go
@@ -7,6 +7,8 @@ import (
domainDevice "github.com/aldinokemal/go-whatsapp-web-multidevice/domains/device"
"github.com/aldinokemal/go-whatsapp-web-multidevice/infrastructure/whatsapp"
"github.com/aldinokemal/go-whatsapp-web-multidevice/ui/websocket"
+ "github.com/aldinokemal/go-whatsapp-web-multidevice/validations"
+ "github.com/sirupsen/logrus"
)
type serviceDevice struct {
@@ -56,11 +58,23 @@ func (s *serviceDevice) AddDevice(ctx context.Context, deviceID string) (*domain
return &device, nil
}
-func (s *serviceDevice) RemoveDevice(_ context.Context, deviceID string) error {
+func (s *serviceDevice) RemoveDevice(ctx context.Context, deviceID string) error {
+ if err := validations.ValidateDeviceID(ctx, deviceID); err != nil {
+ return err
+ }
if s.manager == nil {
return fmt.Errorf("device manager not initialized")
}
- s.manager.RemoveDevice(deviceID)
+ // Deleting a device fully purges it: logs it out of WhatsApp, clears its session
+ // and chat data, then removes the slot from the registry. (Logout, in contrast,
+ // keeps the slot.) The WhatsApp unlink itself is best-effort inside PurgeDevice
+ // (an already-dead session must not block the delete), but failures of the LOCAL
+ // 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 {
+ logrus.WithError(err).Warnf("[DEVICE] purge for %s failed", deviceID)
+ return fmt.Errorf("purge device %s: %w", deviceID, err)
+ }
return nil
}
@@ -73,15 +87,19 @@ func (s *serviceDevice) LoginDeviceWithCode(_ context.Context, _ string, _ strin
}
func (s *serviceDevice) LogoutDevice(ctx context.Context, deviceID string) error {
+ if err := validations.ValidateDeviceID(ctx, deviceID); err != nil {
+ return err
+ }
if s.manager == nil {
return fmt.Errorf("device manager not initialized")
}
- if err := s.manager.PurgeDevice(ctx, deviceID); err != nil {
+ if err := s.manager.LogoutDeviceKeepSlot(ctx, deviceID); err != nil {
return err
}
- // Broadcast device removal so UI clients can refresh.
+ // Broadcast the logout so UI clients can refresh. The device slot is kept, so it
+ // still appears in the list (disconnected) and can be re-paired under the same id.
var devices []domainDevice.Device
if s.manager != nil {
for _, inst := range s.manager.ListDevices() {
@@ -91,8 +109,8 @@ func (s *serviceDevice) LogoutDevice(ctx context.Context, deviceID string) error
}
websocket.Broadcast <- websocket.BroadcastMessage{
- Code: "DEVICE_REMOVED",
- Message: fmt.Sprintf("Device %s logged out and removed", deviceID),
+ Code: "DEVICE_LOGGED_OUT",
+ Message: fmt.Sprintf("Device %s logged out (slot kept)", deviceID),
Result: map[string]any{
"device_id": deviceID,
"devices": devices,
diff --git a/src/validations/device_validation.go b/src/validations/device_validation.go
new file mode 100644
index 00000000..f47e08ec
--- /dev/null
+++ b/src/validations/device_validation.go
@@ -0,0 +1,21 @@
+package validations
+
+import (
+ "context"
+ "strings"
+
+ pkgError "github.com/aldinokemal/go-whatsapp-web-multidevice/pkg/error"
+)
+
+// ValidateDeviceID ensures a device id was provided before any logout/remove work.
+// Device lifecycle routes (POST /devices/{device_id}/logout, DELETE /devices/{device_id})
+// are addressed by path param and do not pass through the X-Device-Id header middleware,
+// so the usecase validates the id here and operates on it via the device manager rather
+// than resolving a WhatsApp client from context (which would fall back to the global
+// client and break multi-device, and must work even when no live client is attached).
+func ValidateDeviceID(_ context.Context, deviceID string) error {
+ if strings.TrimSpace(deviceID) == "" {
+ return pkgError.ValidationError("device_id is required")
+ }
+ return nil
+}
diff --git a/src/views/components/DeviceManager.js b/src/views/components/DeviceManager.js
index 5083037a..6d281c14 100644
--- a/src/views/components/DeviceManager.js
+++ b/src/views/components/DeviceManager.js
@@ -97,12 +97,11 @@ export default {
}
try {
this.isDeleting = true;
-
- // Logout first (fire and forget), then delete
- window.http.get(`/app/logout`, {
- headers: { 'X-Device-Id': encodeURIComponent(deviceId) }
- }).catch(() => {});
-
+
+ // DELETE owns the full purge/logout flow: it logs the device out of
+ // WhatsApp and clears its session before removing the slot. Firing a
+ // separate /app/logout here would race the DELETE response and could
+ // make a removed slot momentarily reappear, so we don't.
await window.http.delete(`/devices/${encodeURIComponent(deviceId)}`);
showSuccessInfo(`Device ${deviceId} deleted successfully`);
$('#deleteDeviceModal').modal('hide');
diff --git a/src/views/index.html b/src/views/index.html
index 1451fe1b..4b77f393 100644
--- a/src/views/index.html
+++ b/src/views/index.html
@@ -389,13 +389,6 @@
case 'LIST_DEVICES':
this.connected_devices = message.result
break;
- case 'LOGOUT_COMPLETE':
- // Handle successful cleanup after remote logout
- showSuccessInfo('✅ ' + message.message)
- console.log('[LOGOUT_COMPLETE] Remote logout cleanup completed:', message)
- // Optionally refresh the device list
- this.handleReloadDevice()
- break;
case 'DEVICE_REMOVED': {
const removedId = message.result?.device_id;
const devices = message.result?.devices;
@@ -419,6 +412,20 @@
}
break;
}
+ case 'DEVICE_LOGGED_OUT': {
+ // Logout keeps the slot: refresh the list (device is now
+ // disconnected) but keep the current selection so the user
+ // can re-pair it under the same id.
+ const devices = message.result?.devices;
+ showSuccessInfo('✅ ' + (message.message || 'Device logged out'));
+ if (Array.isArray(devices)) {
+ this.deviceList = devices;
+ this.connected_devices = devices;
+ } else {
+ this.handleReloadDevice();
+ }
+ break;
+ }
default:
console.log(message)
}