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(storage): scope remaining user-facing reads to the calling device (#906)

gobeyondpty56ac266f76e1
diff --git a/src/domains/chatstorage/interfaces.go b/src/domains/chatstorage/interfaces.go
index 0a7ee913..532691ea 100644
--- a/src/domains/chatstorage/interfaces.go
+++ b/src/domains/chatstorage/interfaces.go
@@ -16,6 +16,8 @@ type IChatStorageRepository interface {
// CreateIncomingCallRecord persists an incoming call as a synthetic message (media_type "call") for chat history.
CreateIncomingCallRecord(ctx context.Context, evt *events.CallOffer, autoRejected bool) error
StoreChat(chat *Chat) error
+ // GetChat matches a JID on any device. Not for user-facing flows: use
+ // GetChatByDevice.
GetChat(jid string) (*Chat, error)
GetChatByDevice(deviceID, jid string) (*Chat, error)
GetChats(filter *ChatFilter) ([]*Chat, error)
@@ -26,7 +28,10 @@ type IChatStorageRepository interface {
StoreMessage(message *Message) error
StoreMessageEdit(edit *MessageEdit) error
StoreMessagesBatch(messages []*Message) error
- GetMessageByID(id string) (*Message, error) // New method for efficient ID-only search
+ // GetMessageByID matches an ID on any device and returns an arbitrary one of
+ // the rows. Each device stores its own copy (with its own "from me" flag and
+ // media keys), so user-facing flows must use the device-scoped lookups below.
+ GetMessageByID(id string) (*Message, error)
GetMessageByIDAndDevice(deviceID, id string) (*Message, error) // Device-scoped ID lookup for device-isolated flows
GetMessageByIDChatAndDevice(deviceID, chatJID, id string) (*Message, error) // Full storage identity lookup for chat-scoped flows
GetMessageEdits(originalMessageID, deviceID string) ([]*MessageEdit, error)
diff --git a/src/infrastructure/whatsapp/chatstorage_wrapper.go b/src/infrastructure/whatsapp/chatstorage_wrapper.go
index d8070459..c2d7c70f 100644
--- a/src/infrastructure/whatsapp/chatstorage_wrapper.go
+++ b/src/infrastructure/whatsapp/chatstorage_wrapper.go
@@ -91,8 +91,10 @@ func (r *deviceChatStorage) StoreMessagesBatch(messages []*domainChatStorage.Mes
return r.base.StoreMessagesBatch(messages)
}
+// GetMessageByID is scoped to this device, like every other read on the
+// wrapper: the base lookup by ID alone can return another device's row.
func (r *deviceChatStorage) GetMessageByID(id string) (*domainChatStorage.Message, error) {
- return r.base.GetMessageByID(id)
+ return r.base.GetMessageByIDAndDevice(r.deviceID, id)
}
func (r *deviceChatStorage) GetMessageByIDAndDevice(deviceID, id string) (*domainChatStorage.Message, error) {
diff --git a/src/infrastructure/whatsapp/device_scope_test.go b/src/infrastructure/whatsapp/device_scope_test.go
new file mode 100644
index 00000000..e4dec95f
--- /dev/null
+++ b/src/infrastructure/whatsapp/device_scope_test.go
@@ -0,0 +1,165 @@
+package whatsapp
+
+import (
+ "context"
+ "testing"
+
+ domainChatStorage "github.com/aldinokemal/go-whatsapp-web-multidevice/domains/chatstorage"
+ "go.mau.fi/whatsmeow/proto/waHistorySync"
+ "go.mau.fi/whatsmeow/types"
+ waLog "go.mau.fi/whatsmeow/util/log"
+ "google.golang.org/protobuf/proto"
+)
+
+// scopeRepo is a minimal message store with the base repository's semantics:
+// the unscoped calls act on every device's rows, the scoped ones on one
+// device's. (The SQLite repository cannot be imported here: it imports this
+// package.)
+type scopeRepo struct {
+ domainChatStorage.IChatStorageRepository
+ rows []*domainChatStorage.Message
+}
+
+func (r *scopeRepo) GetMessageByID(id string) (*domainChatStorage.Message, error) {
+ for _, row := range r.rows {
+ if row.ID == id {
+ return row, nil
+ }
+ }
+ return nil, nil
+}
+
+func (r *scopeRepo) GetMessageByIDAndDevice(deviceID, id string) (*domainChatStorage.Message, error) {
+ for _, row := range r.rows {
+ if row.ID == id && row.DeviceID == deviceID {
+ return row, nil
+ }
+ }
+ return nil, nil
+}
+
+func (r *scopeRepo) DeleteMessage(id, chatJID string) error {
+ return r.delete(func(row *domainChatStorage.Message) bool { return row.ID == id && row.ChatJID == chatJID })
+}
+
+func (r *scopeRepo) DeleteMessageByDevice(deviceID, id, chatJID string) error {
+ return r.delete(func(row *domainChatStorage.Message) bool {
+ return row.ID == id && row.ChatJID == chatJID && row.DeviceID == deviceID
+ })
+}
+
+func (r *scopeRepo) delete(match func(*domainChatStorage.Message) bool) error {
+ kept := r.rows[:0]
+ for _, row := range r.rows {
+ if !match(row) {
+ kept = append(kept, row)
+ }
+ }
+ r.rows = kept
+ return nil
+}
+
+func newScopeRepo(t *testing.T) *scopeRepo {
+ t.Helper()
+ originalLog := log
+ log = waLog.Noop
+ t.Cleanup(func() { log = originalLog })
+ const group = "[email protected]"
+ return &scopeRepo{rows: []*domainChatStorage.Message{
+ {ID: "msg-1", ChatJID: group, DeviceID: "[email protected]", IsFromMe: true},
+ {ID: "msg-1", ChatJID: group, DeviceID: "[email protected]"},
+ }}
+}
+
+// "Delete for me" on one account must remove that account's stored copy only.
+func TestDeleteForMeRemovesOnlyTheReceivingDevicesCopy(t *testing.T) {
+ repo := newScopeRepo(t)
+
+ removed := deleteStoredMessageForMe(repo, "[email protected]", "msg-1")
+
+ if removed == nil || removed.DeviceID != "[email protected]" {
+ t.Fatalf("removed = %+v, want device B's copy", removed)
+ }
+ if len(repo.rows) != 1 || repo.rows[0].DeviceID != "[email protected]" {
+ t.Fatalf("remaining rows = %+v, want only device A's copy", repo.rows)
+ }
+}
+
+func TestDeleteForMeWithoutADeviceDeletesNothing(t *testing.T) {
+ repo := newScopeRepo(t)
+
+ if removed := deleteStoredMessageForMe(repo, "", "msg-1"); removed != nil {
+ t.Fatalf("removed = %+v, want nil", removed)
+ }
+ if len(repo.rows) != 2 {
+ t.Fatalf("remaining rows = %d, want 2", len(repo.rows))
+ }
+}
+
+// The per-device wrapper must not hand out another device's row.
+func TestDeviceChatStorageGetMessageByIDIsScoped(t *testing.T) {
+ repo := newScopeRepo(t)
+
+ message, err := newDeviceChatStorage("[email protected]", repo).GetMessageByID("msg-1")
+ if err != nil {
+ t.Fatalf("GetMessageByID: %v", err)
+ }
+ if message == nil || message.DeviceID != "[email protected]" {
+ t.Fatalf("message = %+v, want device B's copy", message)
+ }
+
+ message, err = newDeviceChatStorage("[email protected]", repo).GetMessageByID("msg-1")
+ if err != nil {
+ t.Fatalf("GetMessageByID: %v", err)
+ }
+ if message != nil {
+ t.Fatalf("message = %+v, want nil for a device with no copy", message)
+ }
+}
+
+// historyNameRepoSpy answers the unscoped chat-name lookup with a name that
+// belongs to another device, and records the device asked for by the scoped one.
+type historyNameRepoSpy struct {
+ domainChatStorage.IChatStorageRepository
+ scopedDeviceIDs []string
+ unscopedCalls int
+}
+
+func (r *historyNameRepoSpy) GetChatNameWithPushName(types.JID, string, string, string) string {
+ r.unscopedCalls++
+ return "Name saved by another device"
+}
+
+func (r *historyNameRepoSpy) GetChatNameWithPushNameByDevice(deviceID string, jid types.JID, _ string, _ string, _ string) string {
+ r.scopedDeviceIDs = append(r.scopedDeviceIDs, deviceID)
+ return jid.User
+}
+
+// History sync names a chat from this device's own stored chat, never from
+// another device's row for the same JID.
+func TestHistorySyncChatNameLookupIsDeviceScoped(t *testing.T) {
+ originalLog := log
+ log = waLog.Noop
+ t.Cleanup(func() { log = originalLog })
+
+ repo := &historyNameRepoSpy{}
+ ctx := ContextWithDevice(context.Background(), NewDeviceInstance("[email protected]", nil, nil))
+ syncType := waHistorySync.HistorySync_RECENT
+ data := &waHistorySync.HistorySync{
+ SyncType: &syncType,
+ Conversations: []*waHistorySync.Conversation{
+ {ID: proto.String("[email protected]")},
+ },
+ }
+
+ if err := processConversationMessages(ctx, data, repo, nil); err != nil {
+ t.Fatalf("process conversation messages: %v", err)
+ }
+
+ if repo.unscopedCalls != 0 {
+ t.Fatalf("unscoped chat-name lookups = %d, want 0", repo.unscopedCalls)
+ }
+ if len(repo.scopedDeviceIDs) != 1 || repo.scopedDeviceIDs[0] != "[email protected]" {
+ t.Fatalf("scoped lookups = %v, want one for device B", repo.scopedDeviceIDs)
+ }
+}
diff --git a/src/infrastructure/whatsapp/event_handler.go b/src/infrastructure/whatsapp/event_handler.go
index 0125d90f..aec82987 100644
--- a/src/infrastructure/whatsapp/event_handler.go
+++ b/src/infrastructure/whatsapp/event_handler.go
@@ -102,25 +102,14 @@ func handleUndecryptableMessage(evt *events.UndecryptableMessage) {
func handleDeleteForMe(ctx context.Context, evt *events.DeleteForMe, chatStorageRepo domainChatStorage.IChatStorageRepository, deviceID string, client *whatsmeow.Client) {
log.Infof("Deleted message %s for %s", evt.MessageID, evt.SenderJID.String())
- // Find the message to get its chat JID
- message, err := chatStorageRepo.GetMessageByID(evt.MessageID)
- if err != nil {
- log.Errorf("Failed to find message %s for deletion: %v", evt.MessageID, err)
- return
+ if deviceID == "" && client != nil && client.Store != nil && client.Store.ID != nil {
+ deviceID = client.Store.ID.ToNonAD().String()
}
-
+ message := deleteStoredMessageForMe(chatStorageRepo, deviceID, evt.MessageID)
if message == nil {
- log.Warnf("Message %s not found in database, skipping deletion", evt.MessageID)
return
}
- // Delete the message from database
- if err := chatStorageRepo.DeleteMessage(evt.MessageID, message.ChatJID); err != nil {
- log.Errorf("Failed to delete message %s from database: %v", evt.MessageID, err)
- } else {
- log.Infof("Successfully deleted message %s from database", evt.MessageID)
- }
-
// Send webhook notification for delete event
go func(c *whatsmeow.Client) {
webhookCtx, cancel := context.WithTimeout(context.WithoutCancel(ctx), 30*time.Second)
@@ -131,6 +120,38 @@ func handleDeleteForMe(ctx context.Context, evt *events.DeleteForMe, chatStorage
}(client)
}
+// deleteStoredMessageForMe removes one device's stored copy of a message after
+// that device's account deleted it "for me", and returns the removed row (nil
+// when the device holds none). Each device keeps its own copy, and a delete on
+// one account says nothing about another account's copy, so both the lookup
+// and the delete are scoped to the device that received the event.
+func deleteStoredMessageForMe(chatStorageRepo domainChatStorage.IChatStorageRepository, deviceID, messageID string) *domainChatStorage.Message {
+ if deviceID == "" {
+ log.Warnf("Cannot delete message %s without a device ID", messageID)
+ return nil
+ }
+
+ // Find the message to get its chat JID
+ message, err := chatStorageRepo.GetMessageByIDAndDevice(deviceID, messageID)
+ if err != nil {
+ log.Errorf("Failed to find message %s for deletion: %v", messageID, err)
+ return nil
+ }
+
+ if message == nil {
+ log.Warnf("Message %s not found in database, skipping deletion", messageID)
+ return nil
+ }
+
+ // Delete the message from database
+ if err := chatStorageRepo.DeleteMessageByDevice(deviceID, messageID, message.ChatJID); err != nil {
+ log.Errorf("Failed to delete message %s from database: %v", messageID, err)
+ } else {
+ log.Infof("Successfully deleted message %s from database", messageID)
+ }
+ return message
+}
+
func resolvePresenceOnConnect() (types.Presence, bool) {
switch config.WhatsappPresenceOnConnect {
case "available":
diff --git a/src/infrastructure/whatsapp/history_sync.go b/src/infrastructure/whatsapp/history_sync.go
index 4a4e30d6..327894eb 100644
--- a/src/infrastructure/whatsapp/history_sync.go
+++ b/src/infrastructure/whatsapp/history_sync.go
@@ -125,7 +125,9 @@ func processConversationMessages(ctx context.Context, data *waHistorySync.Histor
displayName := conversationChatName(ctx, chatNameResolver, chatJID, jid, conv.GetDisplayName())
// Get or create chat
- chatName := chatStorageRepo.GetChatNameWithPushName(jid, chatJID, "", displayName)
+ // Device-scoped: another device's stored name for this chat (for
+ // example a contact name only that account saved) is not this one's.
+ chatName := chatStorageRepo.GetChatNameWithPushNameByDevice(deviceID, jid, chatJID, "", displayName)
// Extract ephemeral expiration from conversation
ephemeralExpiration := conv.GetEphemeralExpiration()
diff --git a/src/infrastructure/whatsapp/history_sync_test.go b/src/infrastructure/whatsapp/history_sync_test.go
index 10cc1e56..bda56369 100644
--- a/src/infrastructure/whatsapp/history_sync_test.go
+++ b/src/infrastructure/whatsapp/history_sync_test.go
@@ -310,7 +310,7 @@ func (r *historyMessageBatchRepoSpy) StoreMessagesBatch(messages []*domainChatSt
return nil
}
-func (r *historyMessageBatchRepoSpy) GetChatNameWithPushName(jid types.JID, _ string, _ string, pushName string) string {
+func (r *historyMessageBatchRepoSpy) GetChatNameWithPushNameByDevice(_ string, jid types.JID, _ string, _ string, pushName string) string {
if pushName != "" {
return pushName
}
@@ -333,7 +333,7 @@ func (r *historyPollRepoSpy) UpsertPollDefinition(definition *domainChatStorage.
return nil
}
-func (r *historyPollRepoSpy) GetChatNameWithPushName(jid types.JID, _ string, _ string, pushName string) string {
+func (r *historyPollRepoSpy) GetChatNameWithPushNameByDevice(_ string, jid types.JID, _ string, _ string, pushName string) string {
if pushName != "" {
return pushName
}
@@ -346,7 +346,7 @@ func (r *historyReactionRepoSpy) CreateReaction(_ context.Context, evt *events.M
return nil
}
-func (r *historyReactionRepoSpy) GetChatNameWithPushName(jid types.JID, _ string, _ string, pushName string) string {
+func (r *historyReactionRepoSpy) GetChatNameWithPushNameByDevice(_ string, jid types.JID, _ string, _ string, pushName string) string {
if pushName != "" {
return pushName
}
diff --git a/src/usecase/AGENTS.md b/src/usecase/AGENTS.md
index 2d14589e..e4ef9c21 100644
--- a/src/usecase/AGENTS.md
+++ b/src/usecase/AGENTS.md
@@ -22,8 +22,11 @@ the matching domain interface; keep Fiber/MCP response types in the adapters.
undecorated base usecase, never the decorator. Rows are keyed by `instance.ID()`
(slot alias) so the worker can resolve them with `DeviceManager.GetDevice`.
- `chat.go` owns history queries; `message.go` owns reactions, revokes, edits, and
- other message actions. Existing protocol-specific global ID lookups are exceptions,
- not a pattern for new user-facing reads; verify their caller contract before reuse.
+ other message actions. Message actions read the calling device's own stored copy
+ in the requested chat; a lookup by ID alone can return another device's row,
+ whose "from me" flag and media keys differ. Media downloads use
+ `storedMessageForAction`; resolve scope with `storageDeviceID(ctx)` and refuse
+ that read when it is empty.
- `group.go` handles participant JIDs and group settings, `user.go` account/contact
operations, and `device.go` delegates lifecycle operations to `DeviceManager`.
diff --git a/src/usecase/chat.go b/src/usecase/chat.go
index 783283c2..4e341346 100644
--- a/src/usecase/chat.go
+++ b/src/usecase/chat.go
@@ -31,11 +31,17 @@ func (service serviceChat) ListChats(ctx context.Context, request domainChat.Lis
return response, err
}
+ // An empty device filter would list every device's chats.
+ deviceID := storageDeviceID(ctx)
+ if deviceID == "" {
+ return response, fmt.Errorf("device identification required")
+ }
+
chatDisplayNameResolver := whatsapp.NewChatDisplayNameResolver(ctx, whatsapp.ClientFromContext(ctx))
// Create filter from request
filter := &domainChatStorage.ChatFilter{
- DeviceID: deviceIDFromContext(ctx),
+ DeviceID: deviceID,
Limit: request.Limit,
Offset: request.Offset,
SearchName: request.Search,
@@ -260,6 +266,21 @@ func (service serviceChat) GetChatMessages(ctx context.Context, request domainCh
return response, nil
}
+// storageDeviceID returns the identity chat storage files this request's rows
+// under: the device in the context, or, for a caller that carries no device
+// (the single-device fallback of ClientFromContext), the account of the client
+// that fallback selects. It returns "" when neither is known; callers must then
+// refuse a read rather than run it without a device filter.
+func storageDeviceID(ctx context.Context) string {
+ if deviceID := deviceIDFromContext(ctx); deviceID != "" {
+ return deviceID
+ }
+ if client := whatsapp.ClientFromContext(ctx); client != nil && client.Store != nil && client.Store.ID != nil {
+ return client.Store.ID.ToNonAD().String()
+ }
+ return ""
+}
+
func deviceIDFromContext(ctx context.Context) string {
if inst, ok := whatsapp.DeviceFromContext(ctx); ok && inst != nil {
if jid := inst.JID(); jid != "" {
diff --git a/src/usecase/device_scope_test.go b/src/usecase/device_scope_test.go
new file mode 100644
index 00000000..dc1de41a
--- /dev/null
+++ b/src/usecase/device_scope_test.go
@@ -0,0 +1,151 @@
+package usecase
+
+import (
+ "context"
+ "database/sql"
+ "testing"
+ "time"
+
+ domainChat "github.com/aldinokemal/go-whatsapp-web-multidevice/domains/chat"
+ domainChatStorage "github.com/aldinokemal/go-whatsapp-web-multidevice/domains/chatstorage"
+ domainMessage "github.com/aldinokemal/go-whatsapp-web-multidevice/domains/message"
+ "github.com/aldinokemal/go-whatsapp-web-multidevice/infrastructure/chatstorage"
+ "github.com/aldinokemal/go-whatsapp-web-multidevice/infrastructure/whatsapp"
+ "github.com/aldinokemal/go-whatsapp-web-multidevice/pkg/sqlite"
+ "github.com/stretchr/testify/require"
+ "go.mau.fi/whatsmeow"
+ waStore "go.mau.fi/whatsmeow/store"
+ "go.mau.fi/whatsmeow/types"
+)
+
+// Two accounts paired on one server share a group. Each stores its own copy of
+// a group message: device A sent it, device B received it. These tests pin that
+// a request made as one device only ever reads that device's copy.
+
+const (
+ scopeDeviceA = "[email protected]"
+ scopeDeviceB = "[email protected]"
+)
+
+var (
+ scopeGroup = types.NewJID("120363000000000042", types.GroupServer)
+ scopeMember = types.NewJID("628333333333", types.DefaultUserServer)
+)
+
+type scopeFixture struct {
+ repo domainChatStorage.IChatStorageRepository
+ service serviceMessage
+}
+
+func newScopeFixture(t *testing.T) *scopeFixture {
+ t.Helper()
+ db, err := sql.Open(sqlite.DriverName, ":memory:")
+ require.NoError(t, err)
+ db.SetMaxOpenConns(1)
+ t.Cleanup(func() { _ = db.Close() })
+
+ repo := chatstorage.NewStorageRepository(db)
+ require.NoError(t, repo.InitializeSchema())
+
+ f := &scopeFixture{repo: repo}
+ f.service = serviceMessage{
+ chatStorageRepo: repo,
+ validateJIDFn: func(_ *whatsmeow.Client, _ string) (types.JID, error) {
+ return scopeGroup, nil
+ },
+ }
+ return f
+}
+
+func (f *scopeFixture) storeChat(t *testing.T, deviceID string, ephemeral uint32) {
+ t.Helper()
+ require.NoError(t, f.repo.StoreChat(&domainChatStorage.Chat{
+ DeviceID: deviceID,
+ JID: scopeGroup.String(),
+ Name: "Shared group",
+ LastMessageTime: time.Now(),
+ EphemeralExpiration: ephemeral,
+ }))
+}
+
+func (f *scopeFixture) storeMessage(t *testing.T, message domainChatStorage.Message) {
+ t.Helper()
+ message.ChatJID = scopeGroup.String()
+ message.Timestamp = time.Now()
+ require.NoError(t, f.repo.StoreMessage(&message))
+}
+
+func scopeContext(deviceID string) context.Context {
+ jid, _ := types.ParseJID(deviceID)
+ client := &whatsmeow.Client{Store: &waStore.Device{ID: &jid}}
+ return whatsapp.ContextWithDevice(context.Background(), whatsapp.NewDeviceInstance(deviceID, client, nil))
+}
+
+func TestDownloadMediaCannotReadAnotherDevicesMessage(t *testing.T) {
+ f := newScopeFixture(t)
+ f.storeChat(t, scopeDeviceA, 0)
+ f.storeChat(t, scopeDeviceB, 0)
+ // Only device A received this image (for example before device B joined
+ // the group), so only device A holds its media keys.
+ f.storeMessage(t, domainChatStorage.Message{
+ ID: "image-1",
+ DeviceID: scopeDeviceA,
+ Sender: scopeMember.String(),
+ MediaType: "image",
+ URL: "https://mmg.whatsapp.net/v/t62.7118-24/secret.enc",
+ DirectPath: "/v/t62.7118-24/secret.enc",
+ MediaKey: []byte("device-a-media-key-0123456789abcd"),
+ })
+
+ _, err := f.service.DownloadMedia(scopeContext(scopeDeviceB), domainMessage.DownloadMediaRequest{
+ MessageID: "image-1",
+ Phone: scopeGroup.String(),
+ })
+
+ require.ErrorContains(t, err, "not found")
+}
+
+func TestDownloadMediaRejectsMessageFromAnotherChat(t *testing.T) {
+ f := newScopeFixture(t)
+ otherGroup := types.NewJID("120363000000000099", types.GroupServer)
+ require.NoError(t, f.repo.StoreChat(&domainChatStorage.Chat{
+ DeviceID: scopeDeviceB, JID: otherGroup.String(), Name: "Other group", LastMessageTime: time.Now(),
+ }))
+ require.NoError(t, f.repo.StoreMessage(&domainChatStorage.Message{
+ ID: "image-2", ChatJID: otherGroup.String(), DeviceID: scopeDeviceB, Sender: scopeMember.String(),
+ MediaType: "image", DirectPath: "/v/t62.7118-24/other.enc", Timestamp: time.Now(),
+ }))
+
+ _, err := f.service.DownloadMedia(scopeContext(scopeDeviceB), domainMessage.DownloadMediaRequest{
+ MessageID: "image-2",
+ Phone: scopeGroup.String(),
+ })
+
+ require.ErrorContains(t, err, "not found")
+}
+
+func TestDefaultEphemeralExpirationIsPerDevice(t *testing.T) {
+ f := newScopeFixture(t)
+ f.storeChat(t, scopeDeviceA, 86400)
+ f.storeChat(t, scopeDeviceB, 0)
+ service := serviceSend{chatStorageRepo: f.repo}
+
+ require.Equal(t, uint32(86400), service.getDefaultEphemeralExpiration(scopeContext(scopeDeviceA), scopeGroup.String()))
+ require.Equal(t, uint32(0), service.getDefaultEphemeralExpiration(scopeContext(scopeDeviceB), scopeGroup.String()))
+ require.Equal(t, uint32(0), service.getDefaultEphemeralExpiration(context.Background(), scopeGroup.String()),
+ "a caller with no device must not inherit some device's timer")
+}
+
+func TestListChatsRequiresADevice(t *testing.T) {
+ f := newScopeFixture(t)
+ f.storeChat(t, scopeDeviceA, 0)
+ f.storeChat(t, scopeDeviceB, 0)
+
+ response, err := NewChatService(f.repo).ListChats(context.Background(), domainChat.ListChatsRequest{})
+ require.ErrorContains(t, err, "device identification required")
+ require.Empty(t, response.Data)
+
+ response, err = NewChatService(f.repo).ListChats(scopeContext(scopeDeviceB), domainChat.ListChatsRequest{})
+ require.NoError(t, err)
+ require.Len(t, response.Data, 1)
+}
diff --git a/src/usecase/forward.go b/src/usecase/forward.go
index 06735a52..0b779f15 100644
--- a/src/usecase/forward.go
+++ b/src/usecase/forward.go
@@ -44,7 +44,7 @@ func (service serviceSend) SendForward(ctx context.Context, request domainSend.F
return response, err
}
- opts := utils.ForwardBuildOptions{Duration: forwardDurationOption(service, request)}
+ opts := utils.ForwardBuildOptions{Duration: forwardDurationOption(ctx, service, request)}
content := forwardStoredContent(message)
var msg *waE2E.Message
@@ -74,11 +74,11 @@ func (service serviceSend) SendForward(ctx context.Context, request domainSend.F
return response, nil
}
-func forwardDurationOption(service serviceSend, request domainSend.ForwardRequest) *int {
+func forwardDurationOption(ctx context.Context, service serviceSend, request domainSend.ForwardRequest) *int {
if request.Duration != nil {
return request.Duration
}
- expiration := service.getDefaultEphemeralExpiration(request.Phone)
+ expiration := service.getDefaultEphemeralExpiration(ctx, request.Phone)
if expiration == 0 {
return nil
}
diff --git a/src/usecase/message.go b/src/usecase/message.go
index 53593ed2..781ef7fb 100644
--- a/src/usecase/message.go
+++ b/src/usecase/message.go
@@ -89,6 +89,22 @@ func (service serviceMessage) deleteStoredMessage(ctx context.Context, client *w
return nil
}
+// storedMessageForAction loads the calling device's own copy of a message in
+// one chat. Each device stores its own row for a message, and the rows differ:
+// the sender's copy is "from me", a recipient's is not, and only a device that
+// received the message holds its media keys. A lookup by ID alone can return
+// another device's row, so it must never back a user-facing action.
+func (service serviceMessage) storedMessageForAction(ctx context.Context, chatJID types.JID, messageID string) (*domainChatStorage.Message, error) {
+ if service.chatStorageRepo == nil {
+ return nil, nil
+ }
+ deviceID := storageDeviceID(ctx)
+ if deviceID == "" {
+ return nil, fmt.Errorf("device identification required")
+ }
+ return service.chatStorageRepo.GetMessageByIDChatAndDevice(deviceID, chatJID.ToNonAD().String(), messageID)
+}
+
func isGroupReadSenderServer(server string) bool {
switch server {
case types.DefaultUserServer, types.HiddenUserServer, types.LegacyUserServer, types.MessengerServer:
@@ -619,19 +635,24 @@ func (service serviceMessage) DownloadMedia(ctx context.Context, request domainM
return response, pkgError.ErrWaCLI
}
- dataWaRecipient, err := utils.ValidateJidWithLogin(client, request.Phone)
+ dataWaRecipient, err := service.validateJID(client, request.Phone)
if err != nil {
return response, err
}
- // Query the message from chat storage
- message, err := service.chatStorageRepo.GetMessageByID(request.MessageID)
+ // Query the message from chat storage. The row holds the media keys, so
+ // it must be this device's own copy in the requested chat: a message that
+ // only another device received is "not found" here.
+ if service.chatStorageRepo == nil {
+ return response, fmt.Errorf("cannot download media for message %s without chat storage", request.MessageID)
+ }
+ message, err := service.storedMessageForAction(ctx, dataWaRecipient, request.MessageID)
if err != nil {
return response, fmt.Errorf("message not found: %v", err)
}
if message == nil {
- return response, fmt.Errorf("message with ID %s not found", request.MessageID)
+ return response, fmt.Errorf("message with ID %s not found in chat %s for current device", request.MessageID, dataWaRecipient.String())
}
directPath := utils.ResolveMediaDirectPath(message.DirectPath, message.URL)
@@ -641,11 +662,6 @@ func (service serviceMessage) DownloadMedia(ctx context.Context, request domainM
return response, fmt.Errorf("message %s does not contain downloadable media", request.MessageID)
}
- // Verify the message is from the specified chat
- if message.ChatJID != dataWaRecipient.String() {
- return response, fmt.Errorf("message %s does not belong to chat %s", request.MessageID, dataWaRecipient.String())
- }
-
// Create directory structure for organized storage
chatDir := filepath.Join(config.PathMedia, utils.ExtractPhoneNumber(message.ChatJID))
dateDir := filepath.Join(chatDir, message.Timestamp.Format("2006-01-02"))
diff --git a/src/usecase/send.go b/src/usecase/send.go
index ce53c412..1c4e7670 100644
--- a/src/usecase/send.go
+++ b/src/usecase/send.go
@@ -343,7 +343,7 @@ func (service serviceSend) SendText(ctx context.Context, request domainSend.Mess
if request.BaseRequest.Duration != nil && *request.BaseRequest.Duration > 0 {
msg.ExtendedTextMessage.ContextInfo.Expiration = proto.Uint32(uint32(*request.BaseRequest.Duration))
} else {
- msg.ExtendedTextMessage.ContextInfo.Expiration = proto.Uint32(service.getDefaultEphemeralExpiration(request.BaseRequest.Phone))
+ msg.ExtendedTextMessage.ContextInfo.Expiration = proto.Uint32(service.getDefaultEphemeralExpiration(ctx, request.BaseRequest.Phone))
}
if mentionedJIDs := service.resolveMentions(ctx, request.Message, request.Mentions, dataWaRecipient); len(mentionedJIDs) > 0 {
@@ -2080,13 +2080,20 @@ func getWebPInfo(ctx context.Context, filePath string) (isAnimated bool, width i
return isAnimated, width, height
}
-func (service serviceSend) getDefaultEphemeralExpiration(jid string) (expiration uint32) {
+// getDefaultEphemeralExpiration returns the disappearing-message timer this
+// device has stored for the chat. Another device's timer for the same chat is
+// not this device's setting, so the lookup is device-scoped.
+func (service serviceSend) getDefaultEphemeralExpiration(ctx context.Context, jid string) (expiration uint32) {
expiration = 0
- if jid == "" {
+ if jid == "" || service.chatStorageRepo == nil {
+ return expiration
+ }
+ deviceID := storageDeviceID(ctx)
+ if deviceID == "" {
return expiration
}
- chat, err := service.chatStorageRepo.GetChat(jid)
+ chat, err := service.chatStorageRepo.GetChatByDevice(deviceID, jid)
if err != nil {
return expiration
}
diff --git a/src/usecase/send_test.go b/src/usecase/send_test.go
index f0fcbd0c..5b2d2a25 100644
--- a/src/usecase/send_test.go
+++ b/src/usecase/send_test.go
@@ -539,7 +539,7 @@ func TestSendForwardMessageNotFound(t *testing.T) {
func TestForwardDurationOptionExplicitZero(t *testing.T) {
zero := 0
- got := forwardDurationOption(serviceSend{}, domainSend.ForwardRequest{
+ got := forwardDurationOption(context.Background(), serviceSend{}, domainSend.ForwardRequest{
Duration: &zero,
})