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: preserve WhatsApp store identity on restart (#706)

Aldino Kemalcf8b1b488e49
diff --git a/src/infrastructure/whatsapp/device_manager.go b/src/infrastructure/whatsapp/device_manager.go
index 88a3890b..82b9c83b 100644
--- a/src/infrastructure/whatsapp/device_manager.go
+++ b/src/infrastructure/whatsapp/device_manager.go
@@ -304,7 +304,7 @@ func (m *DeviceManager) LoadExistingDevices(ctx context.Context) error {
// Check if device already exists by ID or JID
m.mu.RLock()
- _, existsByID := m.devices[jid]
+ existingByID := m.devices[jid]
var matchedDevice *DeviceInstance
var orphanDevice *DeviceInstance
for _, inst := range m.devices {
@@ -319,16 +319,18 @@ func (m *DeviceManager) LoadExistingDevices(ctx context.Context) error {
m.mu.RUnlock()
// Skip if already matched
- if existsByID || matchedDevice != nil {
+ if existingByID != nil {
+ m.applyStoreJID(existingByID, jid)
+ continue
+ }
+ if matchedDevice != nil {
continue
}
// Match orphaned device with this JID
if orphanDevice != nil {
logrus.Infof("[DEVICE_MANAGER] matching orphaned device %s with JID %s", orphanDevice.ID(), jid)
- orphanDevice.mu.Lock()
- orphanDevice.jid = jid
- orphanDevice.mu.Unlock()
+ m.applyStoreJID(orphanDevice, jid)
if m.storage != nil {
_ = m.storage.SaveDeviceRecord(&domainChatStorage.DeviceRecord{
DeviceID: orphanDevice.ID(),
@@ -341,12 +343,23 @@ func (m *DeviceManager) LoadExistingDevices(ctx context.Context) error {
// Create new device instance
instance := NewDeviceInstance(jid, nil, newDeviceChatStorage(jid, m.storage))
instance.SetState(domainDevice.DeviceStateDisconnected)
+ m.applyStoreJID(instance, jid)
m.AddDevice(instance)
}
return nil
}
+func (m *DeviceManager) applyStoreJID(instance *DeviceInstance, jid string) {
+ if instance == nil || jid == "" {
+ return
+ }
+ instance.mu.Lock()
+ instance.jid = jid
+ instance.mu.Unlock()
+ instance.SetChatStorage(newDeviceChatStorage(jid, m.storage))
+}
+
// loadFromRegistry loads devices from the registry, handling deduplication.
func (m *DeviceManager) loadFromRegistry(records []*domainChatStorage.DeviceRecord) {
// Collect JIDs from manual devices (device_id doesn't contain @)
@@ -548,7 +561,9 @@ func (m *DeviceManager) getOrCreateStoreDevice(ctx context.Context, deviceID str
// Try to reuse an existing device record if the ID maps to a JID.
if deviceID != "" {
if jid, err := types.ParseJID(deviceID); err == nil {
- if dev, err := m.store.GetDevice(ctx, jid); err == nil && dev != nil {
+ if dev, err := findStoreDeviceByJID(ctx, m.store, jid); err != nil {
+ return nil, err
+ } else if dev != nil {
return dev, nil
}
}
@@ -563,19 +578,11 @@ func (m *DeviceManager) getOrCreateStoreDevice(ctx context.Context, deviceID str
if instJID != "" {
if jid, err := types.ParseJID(instJID); err == nil {
- if dev, err := m.store.GetDevice(ctx, jid); err == nil && dev != nil {
+ if dev, err := findStoreDeviceByJID(ctx, m.store, jid); err != nil {
+ return nil, err
+ } else if dev != nil {
return dev, nil
}
- // Fallback: iterate all devices to find one with matching User (ignoring AD-ID)
- // This handles cases where registry has Non-AD JID but store has full JID
- if allDevices, err := m.store.GetAllDevices(ctx); err == nil {
- targetUser := jid.User
- for _, d := range allDevices {
- if d != nil && d.ID != nil && d.ID.User == targetUser {
- return d, nil
- }
- }
- }
}
}
}
@@ -589,12 +596,37 @@ func (m *DeviceManager) configureKeysStore(ctx context.Context, device *store.De
}
innerStore := sqlstore.NewSQLStore(m.keys, *device.ID)
- syncKeysDevice(ctx, m.store, m.keys)
+ syncKeysDevice(ctx, m.store, m.keys, *device.ID)
applyKeyCacheStore(device, innerStore)
return nil
}
+func findStoreDeviceByJID(ctx context.Context, container *sqlstore.Container, jid types.JID) (*store.Device, error) {
+ if container == nil || jid.IsEmpty() {
+ return nil, nil
+ }
+
+ if dev, err := container.GetDevice(ctx, jid); err != nil {
+ return nil, err
+ } else if dev != nil {
+ return dev, nil
+ }
+
+ devices, err := container.GetAllDevices(ctx)
+ if err != nil {
+ return nil, err
+ }
+
+ targetJID := jid.ToNonAD().String()
+ for _, dev := range devices {
+ if dev != nil && dev.ID != nil && dev.ID.ToNonAD().String() == targetJID {
+ return dev, nil
+ }
+ }
+ return nil, nil
+}
+
func configureDeviceProps() {
osName := fmt.Sprintf("%s %s", config.AppOs, config.AppVersion)
store.DeviceProps.PlatformType = &config.AppPlatform
diff --git a/src/infrastructure/whatsapp/device_manager_test.go b/src/infrastructure/whatsapp/device_manager_test.go
index 980d59f8..1b5dc06b 100644
--- a/src/infrastructure/whatsapp/device_manager_test.go
+++ b/src/infrastructure/whatsapp/device_manager_test.go
@@ -1,11 +1,17 @@
package whatsapp
import (
+ "context"
"errors"
+ "path/filepath"
"testing"
"time"
+ "github.com/aldinokemal/go-whatsapp-web-multidevice/pkg/sqlite"
+ "go.mau.fi/whatsmeow/proto/waAdv"
"go.mau.fi/whatsmeow/store"
+ "go.mau.fi/whatsmeow/store/sqlstore"
+ "go.mau.fi/whatsmeow/types"
)
func TestApplyKeyCacheStorePreservesPrivacyTokens(t *testing.T) {
@@ -140,3 +146,181 @@ func TestListDevices_SameCreatedAt(t *testing.T) {
}
}
}
+
+func TestLoadExistingDevicesPreservesStoreJIDForStoreOnlyDevice(t *testing.T) {
+ ctx := context.Background()
+ storeContainer := newTestSQLStore(t)
+ adJID := types.NewADJID("6281111111111", types.WhatsAppDomain, 12)
+ device := newTestStoreDevice(storeContainer, adJID, "stored-device")
+ if err := storeContainer.PutDevice(ctx, device); err != nil {
+ t.Fatalf("put device: %v", err)
+ }
+
+ manager := NewDeviceManager(storeContainer, nil, nil)
+
+ if err := manager.LoadExistingDevices(ctx); err != nil {
+ t.Fatalf("load existing devices: %v", err)
+ }
+
+ nonADJID := adJID.ToNonAD().String()
+ instance, ok := manager.GetDevice(nonADJID)
+ if !ok {
+ t.Fatalf("expected device %s to be registered", nonADJID)
+ }
+ if instance.JID() != nonADJID {
+ t.Fatalf("expected instance JID %s, got %q", nonADJID, instance.JID())
+ }
+}
+
+func TestEnsureClientReusesPersistedADStoreDeviceFromNonADID(t *testing.T) {
+ ctx := context.Background()
+ storeContainer := newTestSQLStore(t)
+ adJID := types.NewADJID("6281222222222", types.WhatsAppDomain, 23)
+ device := newTestStoreDevice(storeContainer, adJID, "stored-device")
+ if err := storeContainer.PutDevice(ctx, device); err != nil {
+ t.Fatalf("put device: %v", err)
+ }
+
+ manager := NewDeviceManager(storeContainer, nil, nil)
+ nonADJID := adJID.ToNonAD().String()
+
+ instance, err := manager.EnsureClient(ctx, nonADJID)
+ if err != nil {
+ t.Fatalf("ensure client: %v", err)
+ }
+
+ client := instance.GetClient()
+ if client == nil || client.Store == nil || client.Store.ID == nil {
+ t.Fatal("expected client to reuse persisted store device with a known JID")
+ }
+ if got := client.Store.ID.String(); got != adJID.String() {
+ t.Fatalf("expected store JID %s, got %s", adJID.String(), got)
+ }
+ if got := instance.JID(); got != nonADJID {
+ t.Fatalf("expected instance JID %s, got %q", nonADJID, got)
+ }
+}
+
+func TestSyncKeysDeviceDoesNotDeleteOtherDevices(t *testing.T) {
+ ctx := context.Background()
+ primaryStore := newTestSQLStore(t)
+ keysStore := newTestSQLStore(t)
+
+ firstJID := types.NewADJID("6281333333333", types.WhatsAppDomain, 31)
+ secondJID := types.NewADJID("6281444444444", types.WhatsAppDomain, 32)
+ for _, testDevice := range []*store.Device{
+ newTestStoreDevice(primaryStore, firstJID, "primary-first"),
+ newTestStoreDevice(primaryStore, secondJID, "primary-second"),
+ newTestStoreDevice(keysStore, firstJID, "keys-first"),
+ newTestStoreDevice(keysStore, secondJID, "keys-second"),
+ } {
+ if err := testDevice.Save(ctx); err != nil {
+ t.Fatalf("save device %s: %v", testDevice.ID.String(), err)
+ }
+ }
+
+ syncKeysDevice(ctx, primaryStore, keysStore, firstJID)
+
+ devices, err := keysStore.GetAllDevices(ctx)
+ if err != nil {
+ t.Fatalf("get keys devices: %v", err)
+ }
+ if len(devices) != 2 {
+ t.Fatalf("expected keys DB to retain 2 devices, got %d", len(devices))
+ }
+ assertStoreHasDevice(t, devices, firstJID.String())
+ assertStoreHasDevice(t, devices, secondJID.String())
+}
+
+func TestSyncKeysDeviceUsesValueEquality(t *testing.T) {
+ ctx := context.Background()
+ primaryStore := newTestSQLStore(t)
+ keysStore := newTestSQLStore(t)
+ jid := types.NewADJID("6281555555555", types.WhatsAppDomain, 44)
+
+ primaryDevice := newTestStoreDevice(primaryStore, jid, "primary")
+ keysDevice := newTestStoreDevice(keysStore, jid, "keys")
+ if err := primaryDevice.Save(ctx); err != nil {
+ t.Fatalf("save primary device: %v", err)
+ }
+ if err := keysDevice.Save(ctx); err != nil {
+ t.Fatalf("save keys device: %v", err)
+ }
+
+ syncKeysDevice(ctx, primaryStore, keysStore, jid)
+
+ storedDevice, err := keysStore.GetDevice(ctx, jid)
+ if err != nil {
+ t.Fatalf("get keys device: %v", err)
+ }
+ if storedDevice == nil {
+ t.Fatal("expected keys device to remain present")
+ }
+ if storedDevice.PushName != "keys" {
+ t.Fatalf("expected existing keys device to be preserved, got push name %q", storedDevice.PushName)
+ }
+}
+
+func TestSyncKeysDeviceMatchesAcrossADAndNonADFormats(t *testing.T) {
+ ctx := context.Background()
+ primaryStore := newTestSQLStore(t)
+ keysStore := newTestSQLStore(t)
+ adJID := types.NewADJID("6281666666666", types.WhatsAppDomain, 50)
+ nonADJID := adJID.ToNonAD()
+
+ primaryDevice := newTestStoreDevice(primaryStore, adJID, "primary")
+ keysDevice := newTestStoreDevice(keysStore, nonADJID, "keys")
+ if err := primaryDevice.Save(ctx); err != nil {
+ t.Fatalf("save primary device: %v", err)
+ }
+ if err := keysDevice.Save(ctx); err != nil {
+ t.Fatalf("save keys device: %v", err)
+ }
+
+ syncKeysDevice(ctx, primaryStore, keysStore, adJID)
+
+ devices, err := keysStore.GetAllDevices(ctx)
+ if err != nil {
+ t.Fatalf("get keys devices: %v", err)
+ }
+ if len(devices) != 1 {
+ t.Fatalf("expected keys DB to avoid duplicating AD and non-AD JIDs, got %d devices", len(devices))
+ }
+}
+
+func newTestSQLStore(t *testing.T) *sqlstore.Container {
+ t.Helper()
+
+ uri := sqlite.FormatChatStorageURI("file:"+filepath.Join(t.TempDir(), "whatsmeow.db"), true, true)
+ container, err := sqlstore.New(context.Background(), sqlite.DriverName, uri, nil)
+ if err != nil {
+ t.Fatalf("create sqlstore: %v", err)
+ }
+ t.Cleanup(func() {
+ _ = container.Close()
+ })
+ return container
+}
+
+func newTestStoreDevice(container *sqlstore.Container, jid types.JID, pushName string) *store.Device {
+ device := container.NewDevice()
+ device.ID = &jid
+ device.PushName = pushName
+ device.Account = &waAdv.ADVSignedDeviceIdentity{
+ Details: []byte{1},
+ AccountSignature: make([]byte, 64),
+ AccountSignatureKey: make([]byte, 32),
+ DeviceSignature: make([]byte, 64),
+ }
+ return device
+}
+
+func assertStoreHasDevice(t *testing.T, devices []*store.Device, jid string) {
+ t.Helper()
+ for _, device := range devices {
+ if device != nil && device.ID != nil && device.ID.String() == jid {
+ return
+ }
+ }
+ t.Fatalf("expected store to contain device %s", jid)
+}
diff --git a/src/infrastructure/whatsapp/event_handler.go b/src/infrastructure/whatsapp/event_handler.go
index 9dca001a..67aa1a45 100644
--- a/src/infrastructure/whatsapp/event_handler.go
+++ b/src/infrastructure/whatsapp/event_handler.go
@@ -149,7 +149,7 @@ func handlePairSuccess(ctx context.Context, evt *events.PairSuccess) {
Message: fmt.Sprintf("Successfully pair with %s", evt.ID.String()),
}
primaryDB, secondaryDB := getStoreContainers()
- syncKeysDevice(ctx, primaryDB, secondaryDB)
+ syncKeysDevice(ctx, primaryDB, secondaryDB, evt.ID)
}
func handleLoggedOut(ctx context.Context, instance *DeviceInstance, chatStorageRepo domainChatStorage.IChatStorageRepository) {
diff --git a/src/infrastructure/whatsapp/init.go b/src/infrastructure/whatsapp/init.go
index affe9a17..9ac14b34 100644
--- a/src/infrastructure/whatsapp/init.go
+++ b/src/infrastructure/whatsapp/init.go
@@ -11,6 +11,7 @@ import (
"go.mau.fi/whatsmeow"
"go.mau.fi/whatsmeow/store"
"go.mau.fi/whatsmeow/store/sqlstore"
+ "go.mau.fi/whatsmeow/types"
waLog "go.mau.fi/whatsmeow/util/log"
)
@@ -32,33 +33,35 @@ var (
startupTime = time.Now().Unix()
)
-func syncKeysDevice(ctx context.Context, db, keysDB *sqlstore.Container) {
- if keysDB == nil {
+func syncKeysDevice(ctx context.Context, db, keysDB *sqlstore.Container, jid types.JID) {
+ if db == nil || keysDB == nil || jid.IsEmpty() {
return
}
- dev, err := db.GetFirstDevice(ctx)
+ dev, err := findStoreDeviceByJID(ctx, db, jid)
if err != nil {
- log.Errorf("Failed to get all devices: %v", err)
- } else {
- found := false
- if devs, err := keysDB.GetAllDevices(ctx); err != nil {
- log.Errorf("Failed to get all devices: %v", err)
- } else {
- for _, d := range devs {
- if d.ID == dev.ID {
- found = true
- break
- } else {
- keysDB.DeleteDevice(ctx, d)
- }
- }
-
- if !found {
- keysDB.PutDevice(ctx, dev)
- }
+ log.Errorf("Failed to find device for keys sync: %v", err)
+ return
+ }
+ if dev == nil || dev.ID == nil {
+ return
+ }
+
+ devices, err := keysDB.GetAllDevices(ctx)
+ if err != nil {
+ log.Errorf("Failed to get keys devices: %v", err)
+ return
+ }
+ targetJID := dev.ID.ToNonAD().String()
+ for _, existing := range devices {
+ if existing != nil && existing.ID != nil && existing.ID.ToNonAD().String() == targetJID {
+ return
}
}
+
+ if err := keysDB.PutDevice(ctx, dev); err != nil {
+ log.Errorf("Failed to sync keys device %s: %v", targetJID, err)
+ }
}
// InitWaCLI initializes the WhatsApp client
@@ -87,7 +90,7 @@ func InitWaCLI(ctx context.Context, storeContainer, keysStoreContainer *sqlstore
if keysContainer != nil && device.ID != nil {
innerStore := sqlstore.NewSQLStore(keysStoreContainer, *device.ID)
- syncKeysDevice(ctx, primaryDB, keysContainer)
+ syncKeysDevice(ctx, primaryDB, keysContainer, *device.ID)
applyKeyCacheStore(device, innerStore)
}