sync: 0.7.2 from main (6164dced8d3ab8f9bcce9bf333fb4e8663760ff1)

This commit is contained in:
github-actions[bot] committed 2026-07-03 01:55:33 +00:00
1 parent 0f9ef308d2
commit 9337afc47e
74 files changed
+11173 -4687

No files matched your search

+2 -2
View File
@@ -3,8 +3,8 @@ package call_handler
import (
"net/http"
call_service "github.com/EvolutionAPI/evolution-go/pkg/call/service"
instance_model "github.com/EvolutionAPI/evolution-go/pkg/instance/model"
call_service "github.com/evolution-foundation/evolution-go/pkg/call/service"
instance_model "github.com/evolution-foundation/evolution-go/pkg/instance/model"
"github.com/gin-gonic/gin"
)
+3 -3
View File
@@ -5,9 +5,9 @@ import (
"errors"
"time"
instance_model "github.com/EvolutionAPI/evolution-go/pkg/instance/model"
logger_wrapper "github.com/EvolutionAPI/evolution-go/pkg/logger"
whatsmeow_service "github.com/EvolutionAPI/evolution-go/pkg/whatsmeow/service"
instance_model "github.com/evolution-foundation/evolution-go/pkg/instance/model"
logger_wrapper "github.com/evolution-foundation/evolution-go/pkg/logger"
whatsmeow_service "github.com/evolution-foundation/evolution-go/pkg/whatsmeow/service"
"github.com/gomessguii/logger"
"go.mau.fi/whatsmeow"
"go.mau.fi/whatsmeow/types"
+3 -3
View File
@@ -3,8 +3,8 @@ package chat_handler
import (
"net/http"
chat_service "github.com/EvolutionAPI/evolution-go/pkg/chat/service"
instance_model "github.com/EvolutionAPI/evolution-go/pkg/instance/model"
chat_service "github.com/evolution-foundation/evolution-go/pkg/chat/service"
instance_model "github.com/evolution-foundation/evolution-go/pkg/instance/model"
"github.com/gin-gonic/gin"
)
@@ -302,7 +302,7 @@ func (c *chatHandler) ChatUnmute(ctx *gin.Context) {
// @Success 200 {object} gin.H "success"
// @Failure 400 {object} gin.H "Error on validation"
// @Failure 500 {object} gin.H "Internal server error"
// @Router /chat/history-sync-request [post]
// @Router /chat/history-sync [post]
func (c *chatHandler) HistorySyncRequest(ctx *gin.Context) {
getInstance := ctx.MustGet("instance")
+4 -4
View File
@@ -5,10 +5,10 @@ import (
"errors"
"time"
instance_model "github.com/EvolutionAPI/evolution-go/pkg/instance/model"
logger_wrapper "github.com/EvolutionAPI/evolution-go/pkg/logger"
"github.com/EvolutionAPI/evolution-go/pkg/utils"
whatsmeow_service "github.com/EvolutionAPI/evolution-go/pkg/whatsmeow/service"
instance_model "github.com/evolution-foundation/evolution-go/pkg/instance/model"
logger_wrapper "github.com/evolution-foundation/evolution-go/pkg/logger"
"github.com/evolution-foundation/evolution-go/pkg/utils"
whatsmeow_service "github.com/evolution-foundation/evolution-go/pkg/whatsmeow/service"
"go.mau.fi/whatsmeow"
"go.mau.fi/whatsmeow/appstate"
"go.mau.fi/whatsmeow/types"
+2 -2
View File
@@ -3,8 +3,8 @@ package community_handler
import (
"net/http"
community_service "github.com/EvolutionAPI/evolution-go/pkg/community/service"
instance_model "github.com/EvolutionAPI/evolution-go/pkg/instance/model"
community_service "github.com/evolution-foundation/evolution-go/pkg/community/service"
instance_model "github.com/evolution-foundation/evolution-go/pkg/instance/model"
"github.com/gin-gonic/gin"
)
+4 -4
View File
@@ -5,10 +5,10 @@ import (
"errors"
"time"
instance_model "github.com/EvolutionAPI/evolution-go/pkg/instance/model"
logger_wrapper "github.com/EvolutionAPI/evolution-go/pkg/logger"
"github.com/EvolutionAPI/evolution-go/pkg/utils"
whatsmeow_service "github.com/EvolutionAPI/evolution-go/pkg/whatsmeow/service"
instance_model "github.com/evolution-foundation/evolution-go/pkg/instance/model"
logger_wrapper "github.com/evolution-foundation/evolution-go/pkg/logger"
"github.com/evolution-foundation/evolution-go/pkg/utils"
whatsmeow_service "github.com/evolution-foundation/evolution-go/pkg/whatsmeow/service"
"github.com/gin-gonic/gin"
"go.mau.fi/whatsmeow"
"go.mau.fi/whatsmeow/types"
+1 -2
View File
@@ -13,7 +13,7 @@ import (
"gorm.io/driver/postgres"
"gorm.io/gorm"
config_env "github.com/EvolutionAPI/evolution-go/pkg/config/env"
config_env "github.com/evolution-foundation/evolution-go/pkg/config/env"
)
type Config struct {
@@ -68,7 +68,6 @@ type Config struct {
LogMaxAge int
LogDirectory string
LogCompress bool
}
// EnsureDBExists connects to postgres (without the target database) and creates it if it doesn't exist.
+301 -230
View File
File diff suppressed because it is too large. Load diff
+2 -2
View File
@@ -1,8 +1,8 @@
package nats_producer
import (
producer_interfaces "github.com/EvolutionAPI/evolution-go/pkg/events/interfaces"
logger_wrapper "github.com/EvolutionAPI/evolution-go/pkg/logger"
producer_interfaces "github.com/evolution-foundation/evolution-go/pkg/events/interfaces"
logger_wrapper "github.com/evolution-foundation/evolution-go/pkg/logger"
"github.com/gomessguii/logger"
"github.com/nats-io/nats.go"
)
+2 -2
View File
@@ -6,8 +6,8 @@ import (
"strings"
"time"
producer_interfaces "github.com/EvolutionAPI/evolution-go/pkg/events/interfaces"
logger_wrapper "github.com/EvolutionAPI/evolution-go/pkg/logger"
producer_interfaces "github.com/evolution-foundation/evolution-go/pkg/events/interfaces"
logger_wrapper "github.com/evolution-foundation/evolution-go/pkg/logger"
"github.com/gomessguii/logger"
amqp "github.com/rabbitmq/amqp091-go"
)
+2 -2
View File
@@ -9,8 +9,8 @@ import (
"strings"
"time"
producer_interfaces "github.com/EvolutionAPI/evolution-go/pkg/events/interfaces"
logger_wrapper "github.com/EvolutionAPI/evolution-go/pkg/logger"
producer_interfaces "github.com/evolution-foundation/evolution-go/pkg/events/interfaces"
logger_wrapper "github.com/evolution-foundation/evolution-go/pkg/logger"
)
type webhookProducer struct {
+1 -1
View File
@@ -5,7 +5,7 @@ import (
"strings"
"sync"
logger_wrapper "github.com/EvolutionAPI/evolution-go/pkg/logger"
logger_wrapper "github.com/evolution-foundation/evolution-go/pkg/logger"
"github.com/gomessguii/logger"
"github.com/gorilla/websocket"
)
+49 -2
View File
@@ -3,8 +3,8 @@ package group_handler
import (
"net/http"
group_service "github.com/EvolutionAPI/evolution-go/pkg/group/service"
instance_model "github.com/EvolutionAPI/evolution-go/pkg/instance/model"
group_service "github.com/evolution-foundation/evolution-go/pkg/group/service"
instance_model "github.com/evolution-foundation/evolution-go/pkg/instance/model"
"github.com/gin-gonic/gin"
)
@@ -20,6 +20,7 @@ type GroupHandler interface {
GetMyGroups(ctx *gin.Context)
JoinGroupLink(ctx *gin.Context)
LeaveGroup(ctx *gin.Context)
UpdateGroupSettings(ctx *gin.Context)
}
type groupHandler struct {
@@ -477,6 +478,52 @@ func (g *groupHandler) LeaveGroup(ctx *gin.Context) {
ctx.JSON(http.StatusOK, gin.H{"message": "success"})
}
// Update group settings
// @Summary Update group settings
// @Description Update group settings (announcement, not_announcement, locked, unlocked, approval_on, approval_off, admin_add, all_member_add)
// @Tags Group
// @Accept json
// @Produce json
// @Param message body group_service.UpdateGroupSettingsStruct true "Group data"
// @Success 200 {object} gin.H "success"
// @Failure 400 {object} gin.H "Error on validation"
// @Failure 500 {object} gin.H "Internal server error"
// @Router /group/settings [post]
func (g *groupHandler) UpdateGroupSettings(ctx *gin.Context) {
getInstance := ctx.MustGet("instance")
instance, ok := getInstance.(*instance_model.Instance)
if !ok {
ctx.JSON(http.StatusInternalServerError, gin.H{"error": "instance not found"})
return
}
var data *group_service.UpdateGroupSettingsStruct
err := ctx.ShouldBindBodyWithJSON(&data)
if err != nil {
ctx.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
return
}
if data.GroupJID == "" {
ctx.JSON(http.StatusBadRequest, gin.H{"error": "groupJid is required"})
return
}
if data.Action == "" {
ctx.JSON(http.StatusBadRequest, gin.H{"error": "action is required"})
return
}
err = g.groupService.UpdateGroupSettings(data, instance)
if err != nil {
ctx.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
return
}
ctx.JSON(http.StatusOK, gin.H{"message": "success"})
}
func NewGroupHandler(
groupService group_service.GroupService,
) GroupHandler {
+4 -5
View File
@@ -9,10 +9,10 @@ import (
"strings"
"time"
instance_model "github.com/EvolutionAPI/evolution-go/pkg/instance/model"
logger_wrapper "github.com/EvolutionAPI/evolution-go/pkg/logger"
"github.com/EvolutionAPI/evolution-go/pkg/utils"
whatsmeow_service "github.com/EvolutionAPI/evolution-go/pkg/whatsmeow/service"
instance_model "github.com/evolution-foundation/evolution-go/pkg/instance/model"
logger_wrapper "github.com/evolution-foundation/evolution-go/pkg/logger"
"github.com/evolution-foundation/evolution-go/pkg/utils"
whatsmeow_service "github.com/evolution-foundation/evolution-go/pkg/whatsmeow/service"
"github.com/gin-gonic/gin"
"github.com/vincent-petithory/dataurl"
"go.mau.fi/whatsmeow"
@@ -116,7 +116,6 @@ type UpdateGroupRequestParticipantsStruct struct {
Participants []string `json:"participants"`
}
func (g *groupService) ensureClientConnected(instanceId string) (*whatsmeow.Client, error) {
client := g.clientPointer[instanceId]
g.loggerWrapper.GetLogger(instanceId).LogInfo("[%s] Checking client connection status - Client exists: %v", instanceId, client != nil)
+19 -5
View File
@@ -6,10 +6,10 @@ import (
"github.com/gin-gonic/gin"
config "github.com/EvolutionAPI/evolution-go/pkg/config"
instance_model "github.com/EvolutionAPI/evolution-go/pkg/instance/model"
instance_service "github.com/EvolutionAPI/evolution-go/pkg/instance/service"
"github.com/EvolutionAPI/evolution-go/pkg/utils"
config "github.com/evolution-foundation/evolution-go/pkg/config"
instance_model "github.com/evolution-foundation/evolution-go/pkg/instance/model"
instance_service "github.com/evolution-foundation/evolution-go/pkg/instance/service"
"github.com/evolution-foundation/evolution-go/pkg/utils"
)
type InstanceHandler interface {
@@ -359,7 +359,7 @@ func (i *instanceHandler) All(ctx *gin.Context) {
// @Success 200 {object} gin.H "Instance"
// @Failure 400 {object} gin.H "Error on validation"
// @Failure 500 {object} gin.H "Internal server error"
// @Router /instance/get/{instanceId} [get]
// @Router /instance/info/{instanceId} [get]
func (i *instanceHandler) Info(ctx *gin.Context) {
instanceId := ctx.Param("instanceId")
@@ -538,6 +538,20 @@ type GetLogsQuery struct {
Limit int `form:"limit"`
}
// GetLogs returns the log entries for an instance
// @Summary Get instance logs
// @Description Returns log entries for an instance, filterable by date range, level and limit
// @Tags Instance
// @Produce json
// @Param instanceId path string true "Instance Id"
// @Param start_date query string false "Start date (YYYY-MM-DD, defaults to 7 days ago)"
// @Param end_date query string false "End date (YYYY-MM-DD, defaults to now)"
// @Param level query string false "Log level filter"
// @Param limit query int false "Max number of entries"
// @Success 200 {object} gin.H "Logs"
// @Failure 400 {object} gin.H "Error on validation"
// @Failure 500 {object} gin.H "Internal server error"
// @Router /instance/logs/{instanceId} [get]
func (h *instanceHandler) GetLogs(c *gin.Context) {
instanceId := c.Param("instanceId")
@@ -3,16 +3,16 @@ package instance_repository
import (
"fmt"
instance_model "github.com/EvolutionAPI/evolution-go/pkg/instance/model"
instance_model "github.com/evolution-foundation/evolution-go/pkg/instance/model"
"github.com/gomessguii/logger"
"github.com/google/uuid"
"gorm.io/gorm"
label_model "github.com/EvolutionAPI/evolution-go/pkg/label/model"
label_repository "github.com/EvolutionAPI/evolution-go/pkg/label/repository"
label_model "github.com/evolution-foundation/evolution-go/pkg/label/model"
label_repository "github.com/evolution-foundation/evolution-go/pkg/label/repository"
message_model "github.com/EvolutionAPI/evolution-go/pkg/message/model"
message_repository "github.com/EvolutionAPI/evolution-go/pkg/message/repository"
message_model "github.com/evolution-foundation/evolution-go/pkg/message/model"
message_repository "github.com/evolution-foundation/evolution-go/pkg/message/repository"
)
type InstanceRepository interface {
+83 -18
View File
@@ -3,6 +3,7 @@ package instance_service
import (
"bufio"
"context"
"encoding/base64"
"encoding/json"
"errors"
"fmt"
@@ -13,13 +14,13 @@ import (
"strings"
"time"
"github.com/EvolutionAPI/evolution-go/pkg/config"
instance_model "github.com/EvolutionAPI/evolution-go/pkg/instance/model"
instance_repository "github.com/EvolutionAPI/evolution-go/pkg/instance/repository"
event_types "github.com/EvolutionAPI/evolution-go/pkg/internal/event_types"
logger_wrapper "github.com/EvolutionAPI/evolution-go/pkg/logger"
"github.com/EvolutionAPI/evolution-go/pkg/utils"
whatsmeow_service "github.com/EvolutionAPI/evolution-go/pkg/whatsmeow/service"
"github.com/evolution-foundation/evolution-go/pkg/config"
instance_model "github.com/evolution-foundation/evolution-go/pkg/instance/model"
instance_repository "github.com/evolution-foundation/evolution-go/pkg/instance/repository"
event_types "github.com/evolution-foundation/evolution-go/pkg/internal/event_types"
logger_wrapper "github.com/evolution-foundation/evolution-go/pkg/logger"
"github.com/evolution-foundation/evolution-go/pkg/utils"
whatsmeow_service "github.com/evolution-foundation/evolution-go/pkg/whatsmeow/service"
"go.mau.fi/whatsmeow"
"go.mau.fi/whatsmeow/types"
)
@@ -89,8 +90,15 @@ type StatusStruct struct {
}
type QrcodeStruct struct {
Qrcode string
Code string
Qrcode string `json:"qrcode"`
Code string `json:"code"`
// Passkey ceremony fields. Populated when the account requires a WebAuthn
// passkey to finish linking (no QR to scan at that point). The manager uses
// PasskeyStage to switch its UI and PasskeyOpenUrl for the
// "Abrir WhatsApp Web" button that launches the passkey ceremony.
PasskeyStage string `json:"passkeyStage,omitempty"`
PasskeyOpenURL string `json:"passkeyOpenUrl,omitempty"`
PasskeyCode string `json:"passkeyCode,omitempty"`
}
type PairStruct struct {
@@ -376,9 +384,13 @@ func (i instances) Logout(instance *instance_model.Instance) (*instance_model.In
}
func (i instances) Status(instance *instance_model.Instance) (*StatusStruct, error) {
client, err := i.ensureClientConnected(instance.Id)
if err != nil {
return nil, err
client := i.clientPointer[instance.Id]
if client == nil {
return &StatusStruct{
Connected: false,
LoggedIn: false,
}, nil
}
isConnected := client.IsConnected()
@@ -391,14 +403,12 @@ func (i instances) Status(instance *instance_model.Instance) (*StatusStruct, err
name = client.Store.PushName
}
status := &StatusStruct{
return &StatusStruct{
Connected: isConnected,
LoggedIn: isLoggedIn,
myJid: myJid,
Name: name,
}
return status, nil
}, nil
}
func (i instances) GetQr(instance *instance_model.Instance) (*QrcodeStruct, error) {
@@ -440,6 +450,21 @@ func (i instances) GetQr(instance *instance_model.Instance) (*QrcodeStruct, erro
return nil, err
}
// If a passkey ceremony is in progress, there is no QR to scan — return the
// passkey stage + the #wapk openUrl so the manager can render the
// "Abrir WhatsApp Web" button. Checked before the empty-QR branch because
// during a passkey ceremony instance.Qrcode is empty.
if store := i.whatsmeowService.PasskeyCeremonyStore(); store != nil {
if token, state, ok := store.StateByInstance(instance.Id); ok {
logger.LogInfo("[%s] Passkey ceremony active (stage=%s) — returning passkey info instead of QR", instance.Id, state.Stage)
return &QrcodeStruct{
PasskeyStage: state.Stage,
PasskeyCode: state.Code,
PasskeyOpenURL: buildPasskeyOpenURL(token),
}, nil
}
}
code := instance.Qrcode
if code == "" {
// Se não há QR code ainda, aguardar um pouco mais e tentar novamente
@@ -470,10 +495,50 @@ func (i instances) GetQr(instance *instance_model.Instance) (*QrcodeStruct, erro
return qr, nil
}
// buildPasskeyOpenURL builds the URL the manager opens to start the passkey
// ceremony: https://web.whatsapp.com/#wapk=<base64url({t:token,b:publicBase})>.
// publicBase must be the PUBLICLY reachable API base the browser can hit; set it
// via PASSKEY_PUBLIC_URL. Kept in sync with the event handler in whatsmeow.go.
func buildPasskeyOpenURL(token string) string {
publicBase := os.Getenv("PASSKEY_PUBLIC_URL")
if publicBase == "" {
publicBase = "<SET_PASSKEY_PUBLIC_URL>"
}
payload := fmt.Sprintf(`{"t":%q,"b":%q}`, token, publicBase)
wapk := base64.RawURLEncoding.EncodeToString([]byte(payload))
return "https://web.whatsapp.com/#wapk=" + wapk
}
func (i instances) Pair(data *PairStruct, instance *instance_model.Instance) (*PairReturnStruct, error) {
code, err := i.clientPointer[instance.Id].PairPhone(context.Background(), data.Phone, true, whatsmeow.PairClientChrome, "Chrome (Linux)")
logger := i.loggerWrapper.GetLogger(instance.Id)
client := i.clientPointer[instance.Id]
if client == nil || !client.IsConnected() {
if client != nil && client.IsLoggedIn() {
return nil, fmt.Errorf("instance is already authenticated")
}
logger.LogInfo("[%s] No active connection, starting instance for phone pairing", instance.Id)
if err := i.whatsmeowService.StartInstance(instance.Id); err != nil {
logger.LogError("[%s] Failed to start instance for pairing: %v", instance.Id, err)
return nil, fmt.Errorf("failed to start instance: %w", err)
}
// Wait for the WA websocket connection and initial QR generation to establish.
// PairPhone must be called after the QR event is received per whatsmeow docs.
time.Sleep(3 * time.Second)
client = i.clientPointer[instance.Id]
if client == nil {
return nil, fmt.Errorf("failed to initialize client for pairing")
}
}
if client.IsLoggedIn() {
return nil, fmt.Errorf("instance is already authenticated")
}
code, err := client.PairPhone(context.Background(), data.Phone, true, whatsmeow.PairClientChrome, "Chrome (Linux)")
if err != nil {
i.loggerWrapper.GetLogger(instance.Id).LogError("[%s] something went wrong calling pair phone", instance.Id)
logger.LogError("[%s] PairPhone failed: %v", instance.Id, err)
return nil, fmt.Errorf("pairing failed: %w", err)
}
return &PairReturnStruct{PairingCode: code}, nil
+6
View File
@@ -16,6 +16,8 @@ const (
NEWSLETTER = "NEWSLETTER"
QRCODE = "QRCODE"
BUTTON_CLICK = "BUTTON_CLICK"
PICTURE = "PICTURE"
USER_ABOUT = "USER_ABOUT"
)
var AllEventTypes = []string{
@@ -33,6 +35,8 @@ var AllEventTypes = []string{
NEWSLETTER,
QRCODE,
BUTTON_CLICK,
PICTURE,
USER_ABOUT,
}
var validEventTypes = map[string]bool{
@@ -51,6 +55,8 @@ var validEventTypes = map[string]bool{
NEWSLETTER: true,
QRCODE: true,
BUTTON_CLICK: true,
PICTURE: true,
USER_ABOUT: true,
}
func IsEventType(eventType string) bool {
+3 -3
View File
@@ -3,8 +3,8 @@ package label_handler
import (
"net/http"
instance_model "github.com/EvolutionAPI/evolution-go/pkg/instance/model"
label_service "github.com/EvolutionAPI/evolution-go/pkg/label/service"
instance_model "github.com/evolution-foundation/evolution-go/pkg/instance/model"
label_service "github.com/evolution-foundation/evolution-go/pkg/label/service"
"github.com/gin-gonic/gin"
)
@@ -269,7 +269,7 @@ func (l *labelHandler) MessageUnlabel(ctx *gin.Context) {
// @Produce json
// @Success 200 {object} gin.H "success"
// @Failure 500 {object} gin.H "Internal server error"
// @Router /label [get]
// @Router /label/list [get]
func (l *labelHandler) GetLabels(ctx *gin.Context) {
getInstance := ctx.MustGet("instance")
+1 -1
View File
@@ -1,7 +1,7 @@
package label_repository
import (
label_model "github.com/EvolutionAPI/evolution-go/pkg/label/model"
label_model "github.com/evolution-foundation/evolution-go/pkg/label/model"
"gorm.io/gorm"
"gorm.io/gorm/clause"
)
+6 -6
View File
@@ -5,12 +5,12 @@ import (
"errors"
"time"
instance_model "github.com/EvolutionAPI/evolution-go/pkg/instance/model"
label_model "github.com/EvolutionAPI/evolution-go/pkg/label/model"
label_repository "github.com/EvolutionAPI/evolution-go/pkg/label/repository"
logger_wrapper "github.com/EvolutionAPI/evolution-go/pkg/logger"
"github.com/EvolutionAPI/evolution-go/pkg/utils"
whatsmeow_service "github.com/EvolutionAPI/evolution-go/pkg/whatsmeow/service"
instance_model "github.com/evolution-foundation/evolution-go/pkg/instance/model"
label_model "github.com/evolution-foundation/evolution-go/pkg/label/model"
label_repository "github.com/evolution-foundation/evolution-go/pkg/label/repository"
logger_wrapper "github.com/evolution-foundation/evolution-go/pkg/logger"
"github.com/evolution-foundation/evolution-go/pkg/utils"
whatsmeow_service "github.com/evolution-foundation/evolution-go/pkg/whatsmeow/service"
"go.mau.fi/whatsmeow"
"go.mau.fi/whatsmeow/appstate"
)
+1 -1
View File
@@ -8,7 +8,7 @@ import (
"sync"
"time"
"github.com/EvolutionAPI/evolution-go/pkg/config"
"github.com/evolution-foundation/evolution-go/pkg/config"
"github.com/gomessguii/logger"
"gopkg.in/natefinch/lumberjack.v2"
)
+58 -7
View File
@@ -3,8 +3,8 @@ package message_handler
import (
"net/http"
instance_model "github.com/EvolutionAPI/evolution-go/pkg/instance/model"
message_service "github.com/EvolutionAPI/evolution-go/pkg/message/service"
instance_model "github.com/evolution-foundation/evolution-go/pkg/instance/model"
message_service "github.com/evolution-foundation/evolution-go/pkg/message/service"
"github.com/gin-gonic/gin"
)
@@ -12,6 +12,7 @@ type MessageHandler interface {
React(ctx *gin.Context)
ChatPresence(ctx *gin.Context)
MarkRead(ctx *gin.Context)
MarkPlayed(ctx *gin.Context)
DownloadMedia(ctx *gin.Context)
GetMessageStatus(ctx *gin.Context)
DeleteMessageEveryone(ctx *gin.Context)
@@ -168,17 +169,67 @@ func (m *messageHandler) MarkRead(ctx *gin.Context) {
ctx.JSON(http.StatusOK, gin.H{"message": "success", "data": responseData})
}
// DownloadImage download an image
// @Summary Download an image
// @Description Download an image
// MarkPlayed mark an audio message as played (blue mic icon)
// @Summary Mark an audio message as played
// @Description Mark an audio message as played
// @Tags Message
// @Accept json
// @Produce json
// @Param message body message_service.DownloadMediaStruct true "Download an image"
// @Param message body message_service.MarkPlayedStruct true "Mark an audio message as played"
// @Success 200 {object} gin.H "success"
// @Failure 400 {object} gin.H "Error on validation"
// @Failure 500 {object} gin.H "Internal server error"
// @Router /message/downloadimage [post]
// @Router /message/markplayed [post]
func (m *messageHandler) MarkPlayed(ctx *gin.Context) {
getInstance := ctx.MustGet("instance")
instance, ok := getInstance.(*instance_model.Instance)
if !ok {
ctx.JSON(http.StatusInternalServerError, gin.H{"error": "instance not found"})
return
}
var data *message_service.MarkPlayedStruct
err := ctx.ShouldBindBodyWithJSON(&data)
if err != nil {
ctx.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
return
}
if data.Number == "" {
ctx.JSON(http.StatusBadRequest, gin.H{"error": "phone number is required"})
return
}
if len(data.Id) < 1 {
ctx.JSON(http.StatusBadRequest, gin.H{"error": "id is required"})
return
}
ts, err := m.messageService.MarkPlayed(data, instance)
if err != nil {
ctx.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
return
}
responseData := gin.H{
"timestamp": ts,
}
ctx.JSON(http.StatusOK, gin.H{"message": "success", "data": responseData})
}
// DownloadMedia download a media message (image, video, audio, document)
// @Summary Download media
// @Description Download the media content of a message (image, video, audio or document)
// @Tags Message
// @Accept json
// @Produce json
// @Param message body message_service.DownloadMediaStruct true "Download media"
// @Success 200 {object} gin.H "success"
// @Failure 400 {object} gin.H "Error on validation"
// @Failure 500 {object} gin.H "Internal server error"
// @Router /message/downloadmedia [post]
func (m *messageHandler) DownloadMedia(ctx *gin.Context) {
getInstance := ctx.MustGet("instance")
+8 -5
View File
@@ -1,16 +1,19 @@
package message_model
import (
"encoding/json"
"github.com/google/uuid"
"gorm.io/gorm"
)
type Message struct {
Id string `json:"id" gorm:"type:uuid;primaryKey"`
MessageID string `json:"message_id" gorm:"unique"`
Timestamp string `json:"timestamp"`
Status string `json:"status"`
Source string `json:"source"`
Id string `json:"id" gorm:"type:uuid;primaryKey"`
MessageID string `json:"message_id" gorm:"unique"`
Timestamp string `json:"timestamp"`
Status string `json:"status"`
Source string `json:"source"`
Referral json.RawMessage `json:"referral,omitempty" gorm:"type:jsonb"`
}
func (m *Message) BeforeCreate(tx *gorm.DB) (err error) {
+11 -2
View File
@@ -1,7 +1,7 @@
package message_repository
import (
message_model "github.com/EvolutionAPI/evolution-go/pkg/message/model"
message_model "github.com/evolution-foundation/evolution-go/pkg/message/model"
"gorm.io/gorm"
"gorm.io/gorm/clause"
)
@@ -17,10 +17,19 @@ type messageRepository struct {
db *gorm.DB
}
func messageUpdateColumns(message message_model.Message) []string {
updates := []string{"timestamp", "status", "source"}
if len(message.Referral) > 0 {
updates = append(updates, "referral")
}
return updates
}
func (m *messageRepository) InsertMessage(message message_model.Message) error {
return m.db.Clauses(clause.OnConflict{
Columns: []clause.Column{{Name: "message_id"}},
DoUpdates: clause.AssignmentColumns([]string{"timestamp", "status", "source"}),
DoUpdates: clause.AssignmentColumns(messageUpdateColumns(message)),
}).Create(&message).Error
}
@@ -0,0 +1,80 @@
package message_repository
import (
"bytes"
"encoding/json"
"log"
"strings"
"testing"
"github.com/DATA-DOG/go-sqlmock"
message_model "github.com/evolution-foundation/evolution-go/pkg/message/model"
"gorm.io/driver/postgres"
"gorm.io/gorm"
gormlogger "gorm.io/gorm/logger"
)
func TestInsertMessagePreservesReferralOnStatusUpdate(t *testing.T) {
sqlDB, _, err := sqlmock.New()
if err != nil {
t.Fatalf("open sqlmock db: %v", err)
}
defer sqlDB.Close()
var logBuffer bytes.Buffer
gormDB, err := gorm.Open(postgres.New(postgres.Config{
Conn: sqlDB,
WithoutReturning: true,
}), &gorm.Config{
DryRun: true,
SkipDefaultTransaction: true,
Logger: gormlogger.New(
log.New(&logBuffer, "", 0),
gormlogger.Config{LogLevel: gormlogger.Info, Colorful: false},
),
})
if err != nil {
t.Fatalf("open gorm db: %v", err)
}
repo := NewMessageRepository(gormDB)
referral := json.RawMessage(`{"ctwaClid":"abc123","showAdAttribution":true}`)
initial := message_model.Message{
MessageID: "msg-1",
Timestamp: "2026-05-09 10:00:00",
Status: "Received",
Source: "1551999999999",
Referral: referral,
}
if err := repo.InsertMessage(initial); err != nil {
t.Fatalf("insert initial message: %v", err)
}
initialSQL := logBuffer.String()
if !strings.Contains(initialSQL, `"referral"="excluded"."referral"`) {
t.Fatalf("expected initial upsert SQL to update referral, got %q", initialSQL)
}
logBuffer.Reset()
updated := message_model.Message{
MessageID: "msg-1",
Timestamp: "2026-05-09 10:05:00",
Status: "Read",
Source: "1551999999999",
}
if err := repo.InsertMessage(updated); err != nil {
t.Fatalf("insert updated message: %v", err)
}
updatedSQL := logBuffer.String()
if strings.Contains(updatedSQL, `"referral"="excluded"."referral"`) {
t.Fatalf("expected updated upsert SQL to omit referral update, got %q", updatedSQL)
}
if !strings.Contains(updatedSQL, `"timestamp"="excluded"."timestamp","status"="excluded"."status","source"="excluded"."source"`) {
t.Fatalf("expected updated upsert SQL to keep core columns, got %q", updatedSQL)
}
}
+119 -17
View File
@@ -9,12 +9,12 @@ import (
"strings"
"time"
instance_model "github.com/EvolutionAPI/evolution-go/pkg/instance/model"
logger_wrapper "github.com/EvolutionAPI/evolution-go/pkg/logger"
message_model "github.com/EvolutionAPI/evolution-go/pkg/message/model"
message_repository "github.com/EvolutionAPI/evolution-go/pkg/message/repository"
"github.com/EvolutionAPI/evolution-go/pkg/utils"
whatsmeow_service "github.com/EvolutionAPI/evolution-go/pkg/whatsmeow/service"
instance_model "github.com/evolution-foundation/evolution-go/pkg/instance/model"
logger_wrapper "github.com/evolution-foundation/evolution-go/pkg/logger"
message_model "github.com/evolution-foundation/evolution-go/pkg/message/model"
message_repository "github.com/evolution-foundation/evolution-go/pkg/message/repository"
"github.com/evolution-foundation/evolution-go/pkg/utils"
whatsmeow_service "github.com/evolution-foundation/evolution-go/pkg/whatsmeow/service"
"github.com/vincent-petithory/dataurl"
"go.mau.fi/whatsmeow"
"go.mau.fi/whatsmeow/proto/waCommon"
@@ -27,6 +27,7 @@ type MessageService interface {
React(data *ReactStruct, instance *instance_model.Instance) (*MessageSendStruct, error)
ChatPresence(data *ChatPresenceStruct, instance *instance_model.Instance) (string, error)
MarkRead(data *MarkReadStruct, instance *instance_model.Instance) (string, error)
MarkPlayed(data *MarkPlayedStruct, instance *instance_model.Instance) (string, error)
DownloadMedia(data *DownloadMediaStruct, instance *instance_model.Instance, request *http.Request) (*dataurl.DataURL, string, error)
GetMessageStatus(data *MessageStatusStruct, instance *instance_model.Instance) (*message_model.Message, string, error)
DeleteMessageEveryone(data *MessageStruct, instance *instance_model.Instance) (string, string, error)
@@ -52,6 +53,10 @@ type ChatPresenceStruct struct {
Number string `json:"number"`
State string `json:"state"`
IsAudio bool `json:"isAudio"`
// Delay, in milliseconds, keeps the "composing"/"recording" indicator alive
// for the given duration (re-sending it periodically) and then sends "paused".
// Only applies when State is "composing". 0 = single fire (legacy behaviour).
Delay int `json:"delay"`
}
type MarkReadStruct struct {
@@ -59,6 +64,11 @@ type MarkReadStruct struct {
Number string `json:"number"`
}
type MarkPlayedStruct struct {
Id []string `json:"id"`
Number string `json:"number"`
}
type DownloadMediaStruct struct {
Message *waE2E.Message `json:"message"`
}
@@ -137,6 +147,13 @@ func (m *messageService) React(data *ReactStruct, instance *instance_model.Insta
return nil, errors.New("invalid phone number")
}
// Strip the "+" that ParseJID/CreateJID adds. The recipient is used both as
// the SendMessage target (usync/device resolution) AND as the MessageKey
// RemoteJID that references the reacted message's chat. A malformed "+JID"
// breaks device resolution (usync) and prevents the reaction from matching
// the original message's chat. See utils.CanonicalJID.
recipient = utils.CanonicalJID(recipient)
if data.Id == "" {
m.loggerWrapper.GetLogger(instance.Id).LogError("[%s] Missing Id in Payload", instance.Id)
return nil, errors.New("missing id in payload")
@@ -150,7 +167,8 @@ func (m *messageService) React(data *ReactStruct, instance *instance_model.Insta
reaction = ""
}
// Create MessageKey
// Create MessageKey — msgId is the ID of the message being reacted to,
// NOT the ID of the reaction envelope itself.
messageKey := &waCommon.MessageKey{
RemoteJID: proto.String(recipient.String()),
FromMe: proto.Bool(fromMe),
@@ -161,22 +179,23 @@ func (m *messageService) React(data *ReactStruct, instance *instance_model.Insta
if data.Participant != "" {
participantJID, ok := utils.ParseJID(data.Participant)
if ok {
messageKey.Participant = proto.String(participantJID.String())
messageKey.Participant = proto.String(utils.CanonicalJID(participantJID).String())
}
}
msg := &waE2E.Message{
ReactionMessage: &waE2E.ReactionMessage{
Key: messageKey,
Text: proto.String(reaction),
// GroupingKey: proto.String(reaction),
Key: messageKey,
Text: proto.String(reaction),
SenderTimestampMS: proto.Int64(time.Now().UnixMilli()),
},
}
response, err := client.SendMessage(context.Background(), recipient, msg, whatsmeow.SendRequestExtra{
ID: msgId,
})
// Do NOT pass ID: msgId in SendRequestExtra. Doing so would reuse the
// original message ID as the reaction envelope ID; WhatsApp silently
// deduplicates it and drops the reaction. Let whatsmeow generate a
// fresh, unique ID for the envelope.
response, err := client.SendMessage(context.Background(), recipient, msg)
if err != nil {
return nil, err
}
@@ -191,7 +210,7 @@ func (m *messageService) React(data *ReactStruct, instance *instance_model.Insta
IsFromMe: true,
IsGroup: isGroup,
},
ID: msgId,
ID: response.ID,
Timestamp: time.Now(),
ServerID: response.ServerID,
Type: messageType,
@@ -219,18 +238,70 @@ func (m *messageService) ChatPresence(data *ChatPresenceStruct, instance *instan
return "", errors.New("invalid phone number")
}
// chatstate (typing) is a RAW node sent without usync normalization, so it
// needs a canonical digits-only JID or WhatsApp silently drops it. See
// utils.CanonicalJID for the full rationale.
recipient = utils.CanonicalJID(recipient)
media := ""
if data.IsAudio {
media = "audio"
}
err = client.SendChatPresence(context.Background(), recipient, types.ChatPresence(data.State), types.ChatPresenceMedia(media))
// WhatsApp only forwards chatstate (typing / recording) events to the
// recipient while the sender is marked online. SendChatPresence merely
// sends the chatstate node — it does NOT mark us available. Background
// presence handling (events.AppStateSyncComplete) may have set us to
// Unavailable, in which case the server silently drops the typing
// indicator. Mark ourselves available first to guarantee delivery.
if presErr := client.SendPresence(context.Background(), types.PresenceAvailable); presErr != nil {
m.loggerWrapper.GetLogger(instance.Id).LogWarn("[%s] SendPresence(available) before chatstate failed (non-fatal): %v", instance.Id, presErr)
}
state := types.ChatPresence(data.State)
mediaType := types.ChatPresenceMedia(media)
err = client.SendChatPresence(context.Background(), recipient, state, mediaType)
if err != nil {
return "", err
}
m.loggerWrapper.GetLogger(instance.Id).LogInfo("Message sent to %s", data.Number)
// A single "composing" indicator is ephemeral: WhatsApp expires it after a
// few seconds unless refreshed. When a Delay is provided (and we're typing),
// keep the indicator alive for the requested duration by re-sending it, then
// send "paused" so the indicator clears cleanly instead of timing out.
if data.Delay > 0 && state == types.ChatPresenceComposing {
const keepAliveInterval = 5 * time.Second
const maxDelay = 60 * time.Second
remaining := time.Duration(data.Delay) * time.Millisecond
if remaining > maxDelay {
remaining = maxDelay
}
for remaining > 0 {
sleep := keepAliveInterval
if remaining < sleep {
sleep = remaining
}
time.Sleep(sleep)
remaining -= sleep
if remaining > 0 {
// Refresh the indicator so it doesn't expire mid-delay.
if refreshErr := client.SendChatPresence(context.Background(), recipient, state, mediaType); refreshErr != nil {
m.loggerWrapper.GetLogger(instance.Id).LogWarn("[%s] Refresh chatstate failed (non-fatal): %v", instance.Id, refreshErr)
}
}
}
if pausedErr := client.SendChatPresence(context.Background(), recipient, types.ChatPresencePaused, mediaType); pausedErr != nil {
m.loggerWrapper.GetLogger(instance.Id).LogWarn("[%s] SendChatPresence(paused) failed (non-fatal): %v", instance.Id, pausedErr)
}
}
m.loggerWrapper.GetLogger(instance.Id).LogInfo("Presence (%s) sent to %s", data.State, data.Number)
return ts.String(), nil
}
@@ -249,6 +320,10 @@ func (m *messageService) MarkRead(data *MarkReadStruct, instance *instance_model
return "", errors.New("invalid phone number")
}
// Read receipts are RAW nodes (no usync) — strip the "+" so the receipt
// reaches the recipient. Same root cause as the typing fix above.
jid = utils.CanonicalJID(jid)
err = client.MarkRead(context.Background(), data.Id, time.Now(), jid, jid)
if err != nil {
m.loggerWrapper.GetLogger(instance.Id).LogError("[%s] error marking message as read: %v", instance.Id, err)
@@ -258,6 +333,33 @@ func (m *messageService) MarkRead(data *MarkReadStruct, instance *instance_model
return ts.String(), nil
}
func (m *messageService) MarkPlayed(data *MarkPlayedStruct, instance *instance_model.Instance) (string, error) {
client, err := m.ensureClientConnected(instance.Id)
if err != nil {
return "", err
}
var ts time.Time
jid, ok := utils.ParseJID(data.Number)
if !ok {
m.loggerWrapper.GetLogger(instance.Id).LogError("[%s] Error validating message fields", instance.Id)
return "", errors.New("invalid phone number")
}
// Played receipts are RAW nodes (no usync) — strip the "+" so the receipt
// reaches the recipient. Same root cause as the MarkRead fix.
jid = utils.CanonicalJID(jid)
err = client.MarkRead(context.Background(), data.Id, time.Now(), jid, jid, types.ReceiptTypePlayed)
if err != nil {
m.loggerWrapper.GetLogger(instance.Id).LogError("[%s] error marking message as played: %v", instance.Id, err)
return "", errors.New("error marking message as played")
}
return ts.String(), nil
}
func (m *messageService) DownloadMedia(data *DownloadMediaStruct, instance *instance_model.Instance, request *http.Request) (*dataurl.DataURL, string, error) {
client, err := m.ensureClientConnected(instance.Id)
if err != nil {
+2 -2
View File
@@ -3,8 +3,8 @@ package auth_middleware
import (
"net/http"
"github.com/EvolutionAPI/evolution-go/pkg/config"
instance_service "github.com/EvolutionAPI/evolution-go/pkg/instance/service"
"github.com/evolution-foundation/evolution-go/pkg/config"
instance_service "github.com/evolution-foundation/evolution-go/pkg/instance/service"
"github.com/gin-gonic/gin"
)
+1 -1
View File
@@ -8,7 +8,7 @@ import (
"net/http"
"strings"
"github.com/EvolutionAPI/evolution-go/pkg/utils"
"github.com/evolution-foundation/evolution-go/pkg/utils"
"github.com/gin-gonic/gin"
"github.com/gomessguii/logger"
)
+2 -2
View File
@@ -3,8 +3,8 @@ package newsletter_handler
import (
"net/http"
instance_model "github.com/EvolutionAPI/evolution-go/pkg/instance/model"
newsletter_service "github.com/EvolutionAPI/evolution-go/pkg/newsletter/service"
instance_model "github.com/evolution-foundation/evolution-go/pkg/instance/model"
newsletter_service "github.com/evolution-foundation/evolution-go/pkg/newsletter/service"
"github.com/gin-gonic/gin"
)
+3 -3
View File
@@ -5,9 +5,9 @@ import (
"errors"
"time"
instance_model "github.com/EvolutionAPI/evolution-go/pkg/instance/model"
logger_wrapper "github.com/EvolutionAPI/evolution-go/pkg/logger"
whatsmeow_service "github.com/EvolutionAPI/evolution-go/pkg/whatsmeow/service"
instance_model "github.com/evolution-foundation/evolution-go/pkg/instance/model"
logger_wrapper "github.com/evolution-foundation/evolution-go/pkg/logger"
whatsmeow_service "github.com/evolution-foundation/evolution-go/pkg/whatsmeow/service"
"go.mau.fi/whatsmeow"
"go.mau.fi/whatsmeow/types"
)
+251
View File
@@ -0,0 +1,251 @@
// Package ceremony holds the in-memory state of WhatsApp passkey (WebAuthn)
// pairing ceremonies. It is written by the whatsmeow event goroutine and read
// by the public HTTP polling endpoint, so every access is mutex-guarded.
//
// The lifecycle mirrors the browser-extension contract (tools/passkey-helper):
// the extension polls GET /passkey-ceremony/{token} and drives the ceremony
// through the stages below.
package ceremony
import (
"crypto/rand"
"encoding/hex"
"encoding/json"
"sync"
"time"
)
// Stage is the ceremony state the extension polls for. The values are the
// literal strings the extension's content.js switches on.
const (
StageChallenge = "challenge" // publicKey available; extension runs navigator.credentials.get()
StageAwaitingConfirmation = "awaiting_confirmation" // response sent to WhatsApp, waiting for the confirmation code
StageConfirmation = "confirmation" // code available; user must verify + confirm
StageConfirmed = "confirmed" // confirmation sent, pairing completing
StageError = "error" // something failed
)
// defaultTTL mirrors the whatsmeow passkey handoff validity window (~5 min).
const defaultTTL = 5 * time.Minute
// State is the snapshot the poll endpoint serializes back to the extension.
// The extension reads json.data || json, so a flat object is fine; keys match
// what content.js expects.
//
// PublicKey is stored pre-serialized (json.RawMessage) because whatsmeow's
// types.WebAuthnPublicKey already carries the exact json tags the extension
// needs (challenge, rpId, allowCredentials[].{id,type,transports},
// userVerification, base64url-unpadded via jsonbytes). The event goroutine
// json.Marshals the WebAuthnPublicKey once and hands the bytes here — no
// field-by-field remap, no base64 re-encoding mismatch.
type State struct {
Stage string `json:"stage"`
PublicKey json.RawMessage `json:"publicKey,omitempty"`
Code string `json:"code,omitempty"`
SkipHandoffUX bool `json:"skipHandoffUX"`
Error string `json:"error,omitempty"`
}
type entry struct {
instanceID string
state State
expiresAt time.Time
}
// Store keeps token -> ceremony entry. It is shared (pointer) across the
// value-receiver whatsmeowService copies and the HTTP handler, so its internal
// map is protected by a RWMutex.
type Store struct {
mu sync.RWMutex
byToken map[string]*entry // ephemeral ceremony token -> entry
byInst map[string]string // instanceID -> active token (for event-goroutine writes)
}
// NewStore builds an empty ceremony store.
func NewStore() *Store {
return &Store{
byToken: make(map[string]*entry),
byInst: make(map[string]string),
}
}
func newToken() string {
b := make([]byte, 32)
// crypto/rand.Read never returns a short read on supported platforms.
_, _ = rand.Read(b)
return hex.EncodeToString(b)
}
func (s *Store) prune(now time.Time) {
for tok, e := range s.byToken {
if now.After(e.expiresAt) {
delete(s.byToken, tok)
if s.byInst[e.instanceID] == tok {
delete(s.byInst, e.instanceID)
}
}
}
}
// Start begins (or restarts) a ceremony for an instance with the challenge
// publicKey (pre-serialized JSON), mints a fresh ephemeral token, and returns
// it. Any previous ceremony for the same instance is replaced.
func (s *Store) Start(instanceID string, pk json.RawMessage) string {
s.mu.Lock()
defer s.mu.Unlock()
now := time.Now()
s.prune(now)
// Drop any previous token for this instance.
if old, ok := s.byInst[instanceID]; ok {
delete(s.byToken, old)
}
tok := newToken()
s.byToken[tok] = &entry{
instanceID: instanceID,
state: State{Stage: StageChallenge, PublicKey: pk, SkipHandoffUX: false},
expiresAt: now.Add(defaultTTL),
}
s.byInst[instanceID] = tok
return tok
}
// setStateByInstance updates the state of the active ceremony for an instance.
// No-op if the instance has no active ceremony.
func (s *Store) setStateByInstance(instanceID string, mutate func(*State)) {
s.mu.Lock()
defer s.mu.Unlock()
tok, ok := s.byInst[instanceID]
if !ok {
return
}
e, ok := s.byToken[tok]
if !ok {
return
}
mutate(&e.state)
e.expiresAt = time.Now().Add(defaultTTL)
}
// SetConfirmation moves the ceremony to the confirmation stage with a code.
// skipHandoffUX is intentionally forced to false by callers (DOC2 §4.2: never
// auto-confirm), so the extension always shows the manual "Confirmar" button.
func (s *Store) SetConfirmation(instanceID, code string, skipHandoffUX bool) {
s.setStateByInstance(instanceID, func(st *State) {
st.Stage = StageConfirmation
st.Code = code
st.SkipHandoffUX = skipHandoffUX
st.Error = ""
})
}
// SetAwaitingConfirmation is set right after the WebAuthn response is submitted.
func (s *Store) SetAwaitingConfirmation(instanceID string) {
s.setStateByInstance(instanceID, func(st *State) {
st.Stage = StageAwaitingConfirmation
st.PublicKey = nil
st.Error = ""
})
}
// SetConfirmed marks the confirmation as sent; pairing is finishing.
func (s *Store) SetConfirmed(instanceID string) {
s.setStateByInstance(instanceID, func(st *State) {
st.Stage = StageConfirmed
st.Error = ""
})
}
// SetError records a ceremony error.
func (s *Store) SetError(instanceID, msg string) {
s.setStateByInstance(instanceID, func(st *State) {
st.Stage = StageError
st.Error = msg
})
}
// Clear removes the ceremony for an instance (e.g. on PairSuccess). After this,
// the poll endpoint returns not-found, and the extension treats a cleared state
// after having started as "pairing concluded".
func (s *Store) Clear(instanceID string) {
s.mu.Lock()
defer s.mu.Unlock()
if tok, ok := s.byInst[instanceID]; ok {
delete(s.byToken, tok)
delete(s.byInst, instanceID)
}
}
// Lookup resolves a ceremony token to its instance id and current state.
// ok is false if the token is unknown or expired.
func (s *Store) Lookup(token string) (instanceID string, state State, ok bool) {
s.mu.Lock()
defer s.mu.Unlock()
s.prune(time.Now())
e, found := s.byToken[token]
if !found {
return "", State{}, false
}
return e.instanceID, e.state, true
}
// InstanceForToken resolves just the instance id for a token (used by the
// response/confirm endpoints to reach the right whatsmeow client).
func (s *Store) InstanceForToken(token string) (string, bool) {
s.mu.RLock()
defer s.mu.RUnlock()
e, ok := s.byToken[token]
if !ok {
return "", false
}
if time.Now().After(e.expiresAt) {
return "", false
}
return e.instanceID, true
}
// StateByInstance returns the active ceremony token and state for an instance,
// or ok=false if there is no non-expired ceremony. Used by the authenticated
// instance/QR poll so the manager can render the passkey UI (the token lets it
// rebuild the #wapk openUrl).
func (s *Store) StateByInstance(instanceID string) (token string, state State, ok bool) {
s.mu.RLock()
defer s.mu.RUnlock()
tok, has := s.byInst[instanceID]
if !has {
return "", State{}, false
}
e, has := s.byToken[tok]
if !has {
return "", State{}, false
}
if time.Now().After(e.expiresAt) {
return "", State{}, false
}
return tok, e.state, true
}
// HasActiveByInstance reports whether an instance has a non-expired passkey
// ceremony in progress that is NOT yet in a terminal (error) stage. The QR
// rotation uses this to avoid tearing down the socket/client while a passkey
// ceremony — which is driven by a human in a browser and can easily outlast the
// QR rotation window — is still in flight. Without this, teardownQR would delete
// the client mid-ceremony and the /response and /confirm steps would fail.
func (s *Store) HasActiveByInstance(instanceID string) bool {
s.mu.RLock()
defer s.mu.RUnlock()
tok, ok := s.byInst[instanceID]
if !ok {
return false
}
e, ok := s.byToken[tok]
if !ok {
return false
}
if time.Now().After(e.expiresAt) {
return false
}
// A ceremony in the error stage is terminal — QR teardown may proceed.
return e.state.Stage != StageError
}
+183
View File
@@ -0,0 +1,183 @@
// Package handler exposes the PUBLIC passkey-ceremony HTTP endpoints that the
// Evolution Passkey Helper browser extension calls from the web.whatsapp.com
// origin. These routes are intentionally unauthenticated (no apikey): access is
// gated only by an opaque, short-lived ceremony token minted per pairing.
//
// Contract (tools/passkey-helper/content.js):
//
// GET /passkey-ceremony/:token -> { stage, publicKey?, code?, skipHandoffUX, error? }
// POST /passkey-ceremony/:token/response -> body = WebAuthn assertion
// POST /passkey-ceremony/:token/confirm -> finish pairing
package handler
import (
"net/http"
whatsmeow_service "github.com/evolution-foundation/evolution-go/pkg/whatsmeow/service"
"github.com/gin-gonic/gin"
"go.mau.fi/whatsmeow/types"
)
// PasskeyHandler wires the public ceremony endpoints to the whatsmeow service.
type PasskeyHandler struct {
whatsmeowService whatsmeow_service.WhatsmeowService
}
// NewPasskeyHandler builds the handler.
func NewPasskeyHandler(svc whatsmeow_service.WhatsmeowService) *PasskeyHandler {
return &PasskeyHandler{whatsmeowService: svc}
}
// GetCeremony returns the current ceremony state for a token. The extension
// polls this and drives its UI off the `stage` field.
// @Summary Get passkey ceremony state
// @Description Returns the current WebAuthn passkey-pairing ceremony state for a token. PUBLIC endpoint (no apikey) — access is gated by the opaque short-lived ceremony token. Polled by the Evolution Passkey Helper browser extension.
// @Tags Passkey
// @Produce json
// @Param token path string true "Ceremony token"
// @Success 200 {object} gin.H "Ceremony state ({stage, skipHandoffUX, publicKey?, code?, error?})"
// @Failure 400 {object} gin.H "token is required"
// @Failure 404 {object} gin.H "ceremony not found or expired"
// @Failure 503 {object} gin.H "passkey ceremony unavailable"
// @Router /passkey-ceremony/{token} [get]
func (h *PasskeyHandler) GetCeremony(c *gin.Context) {
token := c.Param("token")
if token == "" {
c.JSON(http.StatusBadRequest, gin.H{"error": "token is required"})
return
}
store := h.whatsmeowService.PasskeyCeremonyStore()
if store == nil {
c.JSON(http.StatusServiceUnavailable, gin.H{"error": "passkey ceremony unavailable"})
return
}
_, state, ok := store.Lookup(token)
if !ok {
// Unknown/expired token. The extension treats an empty/cleared state
// after having started as "pairing concluded"; before that it keeps
// waiting. Return 404 so a never-valid token is distinguishable.
c.JSON(http.StatusNotFound, gin.H{"error": "ceremony not found or expired"})
return
}
// gin.H keeps keys verbatim (publicKey, skipHandoffUX) — no struct-tag risk.
resp := gin.H{
"stage": state.Stage,
"skipHandoffUX": state.SkipHandoffUX,
}
if len(state.PublicKey) > 0 {
resp["publicKey"] = state.PublicKey // json.RawMessage — emitted as-is
}
if state.Code != "" {
resp["code"] = state.Code
}
if state.Error != "" {
resp["error"] = state.Error
}
c.JSON(http.StatusOK, resp)
}
// SubmitResponse receives the WebAuthn assertion produced by the extension and
// forwards it to WhatsApp via SendPasskeyResponse.
// @Summary Submit passkey WebAuthn response
// @Description Receives the WebAuthn assertion produced by the browser extension and forwards it to WhatsApp. PUBLIC endpoint (no apikey) — gated by the ceremony token. Body is the WebAuthnResponse shape (id, rawId, type, response{clientDataJSON, authenticatorData, signature, userHandle?}), base64url-unpadded.
// @Tags Passkey
// @Accept json
// @Produce json
// @Param token path string true "Ceremony token"
// @Param response body types.WebAuthnResponse true "WebAuthn assertion"
// @Success 200 {object} gin.H "ok"
// @Failure 400 {object} gin.H "token is required / invalid body"
// @Failure 404 {object} gin.H "ceremony not found or expired"
// @Failure 500 {object} gin.H "Internal server error"
// @Failure 503 {object} gin.H "passkey ceremony unavailable"
// @Router /passkey-ceremony/{token}/response [post]
func (h *PasskeyHandler) SubmitResponse(c *gin.Context) {
token := c.Param("token")
if token == "" {
c.JSON(http.StatusBadRequest, gin.H{"error": "token is required"})
return
}
store := h.whatsmeowService.PasskeyCeremonyStore()
if store == nil {
c.JSON(http.StatusServiceUnavailable, gin.H{"error": "passkey ceremony unavailable"})
return
}
instanceID, ok := store.InstanceForToken(token)
if !ok {
c.JSON(http.StatusNotFound, gin.H{"error": "ceremony not found or expired"})
return
}
// The extension posts exactly the WebAuthnResponse shape (id, rawId, type,
// response{clientDataJSON, authenticatorData, signature, userHandle?}),
// base64url-unpadded, which matches types.WebAuthnResponse's json tags.
var resp types.WebAuthnResponse
if err := c.ShouldBindJSON(&resp); err != nil {
c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
return
}
if err := h.whatsmeowService.SubmitPasskeyResponse(instanceID, &resp); err != nil {
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
return
}
c.JSON(http.StatusOK, gin.H{"ok": true})
}
// Confirm finishes the pairing after the user verified the confirmation code.
// @Summary Confirm passkey pairing
// @Description Finishes the passkey pairing after the user verified the confirmation code. PUBLIC endpoint (no apikey) — gated by the ceremony token.
// @Tags Passkey
// @Produce json
// @Param token path string true "Ceremony token"
// @Success 200 {object} gin.H "ok"
// @Failure 400 {object} gin.H "token is required"
// @Failure 404 {object} gin.H "ceremony not found or expired"
// @Failure 500 {object} gin.H "Internal server error"
// @Failure 503 {object} gin.H "passkey ceremony unavailable"
// @Router /passkey-ceremony/{token}/confirm [post]
func (h *PasskeyHandler) Confirm(c *gin.Context) {
token := c.Param("token")
if token == "" {
c.JSON(http.StatusBadRequest, gin.H{"error": "token is required"})
return
}
store := h.whatsmeowService.PasskeyCeremonyStore()
if store == nil {
c.JSON(http.StatusServiceUnavailable, gin.H{"error": "passkey ceremony unavailable"})
return
}
instanceID, ok := store.InstanceForToken(token)
if !ok {
c.JSON(http.StatusNotFound, gin.H{"error": "ceremony not found or expired"})
return
}
if err := h.whatsmeowService.ConfirmPasskey(instanceID); err != nil {
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
return
}
c.JSON(http.StatusOK, gin.H{"ok": true})
}
// RegisterRoutes wires the 3 PUBLIC ceremony endpoints directly on the engine,
// with NO auth group (mirrors core.LicenseRoutes). Call from main.go right
// after the license routes.
func RegisterRoutes(eng *gin.Engine, svc whatsmeow_service.WhatsmeowService) {
h := NewPasskeyHandler(svc)
grp := eng.Group("/passkey-ceremony")
{
grp.GET("/:token", h.GetCeremony)
grp.POST("/:token/response", h.SubmitResponse)
grp.POST("/:token/confirm", h.Confirm)
}
}
+3 -3
View File
@@ -4,9 +4,9 @@ import (
"encoding/json"
"net/http"
logger_wrapper "github.com/EvolutionAPI/evolution-go/pkg/logger"
poll_model "github.com/EvolutionAPI/evolution-go/pkg/poll/model"
poll_service "github.com/EvolutionAPI/evolution-go/pkg/poll/service"
logger_wrapper "github.com/evolution-foundation/evolution-go/pkg/logger"
poll_model "github.com/evolution-foundation/evolution-go/pkg/poll/model"
poll_service "github.com/evolution-foundation/evolution-go/pkg/poll/service"
"github.com/gin-gonic/gin"
)
+2 -2
View File
@@ -7,8 +7,8 @@ import (
"strings"
"time"
logger_wrapper "github.com/EvolutionAPI/evolution-go/pkg/logger"
"github.com/EvolutionAPI/evolution-go/pkg/poll/model"
logger_wrapper "github.com/evolution-foundation/evolution-go/pkg/logger"
"github.com/evolution-foundation/evolution-go/pkg/poll/model"
"github.com/google/uuid"
waProto "go.mau.fi/whatsmeow/proto/waE2E"
"go.mau.fi/whatsmeow/types"
+16 -14
View File
@@ -7,20 +7,20 @@ import (
swaggerFiles "github.com/swaggo/files"
ginSwagger "github.com/swaggo/gin-swagger"
_ "github.com/EvolutionAPI/evolution-go/docs"
call_handler "github.com/EvolutionAPI/evolution-go/pkg/call/handler"
chat_handler "github.com/EvolutionAPI/evolution-go/pkg/chat/handler"
community_handler "github.com/EvolutionAPI/evolution-go/pkg/community/handler"
group_handler "github.com/EvolutionAPI/evolution-go/pkg/group/handler"
instance_handler "github.com/EvolutionAPI/evolution-go/pkg/instance/handler"
label_handler "github.com/EvolutionAPI/evolution-go/pkg/label/handler"
message_handler "github.com/EvolutionAPI/evolution-go/pkg/message/handler"
auth_middleware "github.com/EvolutionAPI/evolution-go/pkg/middleware"
newsletter_handler "github.com/EvolutionAPI/evolution-go/pkg/newsletter/handler"
poll_handler "github.com/EvolutionAPI/evolution-go/pkg/poll/handler"
send_handler "github.com/EvolutionAPI/evolution-go/pkg/sendMessage/handler"
server_handler "github.com/EvolutionAPI/evolution-go/pkg/server/handler"
user_handler "github.com/EvolutionAPI/evolution-go/pkg/user/handler"
_ "github.com/evolution-foundation/evolution-go/docs"
call_handler "github.com/evolution-foundation/evolution-go/pkg/call/handler"
chat_handler "github.com/evolution-foundation/evolution-go/pkg/chat/handler"
community_handler "github.com/evolution-foundation/evolution-go/pkg/community/handler"
group_handler "github.com/evolution-foundation/evolution-go/pkg/group/handler"
instance_handler "github.com/evolution-foundation/evolution-go/pkg/instance/handler"
label_handler "github.com/evolution-foundation/evolution-go/pkg/label/handler"
message_handler "github.com/evolution-foundation/evolution-go/pkg/message/handler"
auth_middleware "github.com/evolution-foundation/evolution-go/pkg/middleware"
newsletter_handler "github.com/evolution-foundation/evolution-go/pkg/newsletter/handler"
poll_handler "github.com/evolution-foundation/evolution-go/pkg/poll/handler"
send_handler "github.com/evolution-foundation/evolution-go/pkg/sendMessage/handler"
server_handler "github.com/evolution-foundation/evolution-go/pkg/server/handler"
user_handler "github.com/evolution-foundation/evolution-go/pkg/user/handler"
)
type Routes struct {
@@ -151,6 +151,7 @@ func (r *Routes) AssignRoutes(eng *gin.Engine) {
routes.POST("/react", r.jidValidationMiddleware.ValidateJIDFields("number"), r.messageHandler.React)
routes.POST("/presence", r.jidValidationMiddleware.ValidateNumberField(), r.messageHandler.ChatPresence)
routes.POST("/markread", r.jidValidationMiddleware.ValidateNumberField(), r.messageHandler.MarkRead)
routes.POST("/markplayed", r.jidValidationMiddleware.ValidateNumberField(), r.messageHandler.MarkPlayed)
routes.POST("/downloadmedia", r.messageHandler.DownloadMedia)
routes.POST("/status", r.messageHandler.GetMessageStatus)
routes.POST("/delete", r.jidValidationMiddleware.ValidateNumberField(), r.messageHandler.DeleteMessageEveryone)
@@ -185,6 +186,7 @@ func (r *Routes) AssignRoutes(eng *gin.Engine) {
routes.GET("/myall", r.groupHandler.GetMyGroups) // TODO: not working
routes.POST("/join", r.groupHandler.JoinGroupLink)
routes.POST("/leave", r.jidValidationMiddleware.ValidateNumberField(), r.groupHandler.LeaveGroup)
routes.POST("/settings", r.jidValidationMiddleware.ValidateNumberField(), r.groupHandler.UpdateGroupSettings)
}
}
routes = eng.Group("/call")
+2 -2
View File
@@ -7,8 +7,8 @@ import (
"strconv"
"strings"
instance_model "github.com/EvolutionAPI/evolution-go/pkg/instance/model"
send_service "github.com/EvolutionAPI/evolution-go/pkg/sendMessage/service"
instance_model "github.com/evolution-foundation/evolution-go/pkg/instance/model"
send_service "github.com/evolution-foundation/evolution-go/pkg/sendMessage/service"
"github.com/gin-gonic/gin"
)
File diff suppressed because it is too large. Load diff
+142
View File
@@ -0,0 +1,142 @@
package send_service
import (
"bytes"
"image"
"image/color"
"image/jpeg"
"image/png"
"os/exec"
"testing"
)
// encodePNG builds a simple solid-color PNG of the given size for testing.
func encodePNG(t *testing.T, w, h int) []byte {
t.Helper()
img := image.NewRGBA(image.Rect(0, 0, w, h))
for y := 0; y < h; y++ {
for x := 0; x < w; x++ {
img.Set(x, y, color.RGBA{R: 10, G: 120, B: 200, A: 255})
}
}
var buf bytes.Buffer
if err := png.Encode(&buf, img); err != nil {
t.Fatalf("failed to encode test PNG: %v", err)
}
return buf.Bytes()
}
func TestMakeJPEGThumbnail_ResizesLandscape(t *testing.T) {
src := encodePNG(t, 800, 400)
thumb := makeJPEGThumbnail(src, 72)
if thumb == nil {
t.Fatal("expected a thumbnail, got nil")
}
cfg, format, err := image.DecodeConfig(bytes.NewReader(thumb))
if err != nil {
t.Fatalf("thumbnail is not a decodable image: %v", err)
}
if format != "jpeg" {
t.Fatalf("expected jpeg thumbnail, got %q", format)
}
if cfg.Width != 72 {
t.Fatalf("expected width 72, got %d", cfg.Width)
}
// Aspect ratio (2:1) must be preserved: 72 wide -> 36 tall.
if cfg.Height != 36 {
t.Fatalf("expected height 36 to preserve aspect ratio, got %d", cfg.Height)
}
}
func TestMakeJPEGThumbnail_DoesNotUpscaleSmallImages(t *testing.T) {
src := encodePNG(t, 40, 40)
thumb := makeJPEGThumbnail(src, 72)
if thumb == nil {
t.Fatal("expected a thumbnail, got nil")
}
cfg, _, err := image.DecodeConfig(bytes.NewReader(thumb))
if err != nil {
t.Fatalf("thumbnail is not a decodable image: %v", err)
}
if cfg.Width != 40 || cfg.Height != 40 {
t.Fatalf("expected the thumbnail to keep the original 40x40 size, got %dx%d", cfg.Width, cfg.Height)
}
}
func TestMakeJPEGThumbnail_InvalidInputReturnsNil(t *testing.T) {
if thumb := makeJPEGThumbnail([]byte("not an image"), 72); thumb != nil {
t.Fatalf("expected nil for non-image input, got %d bytes", len(thumb))
}
if thumb := makeJPEGThumbnail(nil, 72); thumb != nil {
t.Fatalf("expected nil for nil input, got %d bytes", len(thumb))
}
}
func TestMakeJPEGThumbnail_DefaultsInvalidMaxWidth(t *testing.T) {
src := encodePNG(t, 800, 800)
thumb := makeJPEGThumbnail(src, 0)
if thumb == nil {
t.Fatal("expected a thumbnail with defaulted maxWidth, got nil")
}
cfg, _, err := image.DecodeConfig(bytes.NewReader(thumb))
if err != nil {
t.Fatalf("thumbnail is not a decodable image: %v", err)
}
if cfg.Width != 72 {
t.Fatalf("expected defaulted width 72, got %d", cfg.Width)
}
}
func TestMakePDFThumbnail_InvalidInputReturnsNil(t *testing.T) {
// With or without pdftoppm installed, garbage input must never panic and
// must yield nil so the caller falls back to sending without a preview.
if thumb := makePDFThumbnail([]byte("%PDF-not-really"), 200); thumb != nil {
t.Fatalf("expected nil for invalid PDF input, got %d bytes", len(thumb))
}
if thumb := makePDFThumbnail(nil, 200); thumb != nil {
t.Fatalf("expected nil for nil input, got %d bytes", len(thumb))
}
}
func TestMakePDFThumbnail_RendersFirstPageWhenPopplerAvailable(t *testing.T) {
if _, err := exec.LookPath("pdftoppm"); err != nil {
t.Skip("pdftoppm not installed; skipping PDF rasterization test")
}
pdf := minimalPDF(t)
thumb := makePDFThumbnail(pdf, 200)
if thumb == nil {
t.Fatal("expected a thumbnail from a valid PDF, got nil")
}
cfg, format, err := image.DecodeConfig(bytes.NewReader(thumb))
if err != nil {
t.Fatalf("PDF thumbnail is not a decodable image: %v", err)
}
if format != "jpeg" {
t.Fatalf("expected jpeg thumbnail, got %q", format)
}
if cfg.Width < 1 || cfg.Width > 200 {
t.Fatalf("expected width within (0, 200], got %d", cfg.Width)
}
}
// minimalPDF returns the bytes of a tiny, valid single-page PDF.
func minimalPDF(t *testing.T) []byte {
t.Helper()
const doc = "%PDF-1.1\n" +
"1 0 obj<< /Type /Catalog /Pages 2 0 R >>endobj\n" +
"2 0 obj<< /Type /Pages /Kids [3 0 R] /Count 1 >>endobj\n" +
"3 0 obj<< /Type /Page /Parent 2 0 R /MediaBox [0 0 200 200] /Resources << >> >>endobj\n" +
"trailer<< /Root 1 0 R >>\n" +
"%%EOF\n"
return []byte(doc)
}
// ensure the jpeg encoder import stays referenced even if the helper changes.
var _ = jpeg.DefaultQuality
+1 -1
View File
@@ -8,7 +8,7 @@ import (
"strings"
"time"
storage_interfaces "github.com/EvolutionAPI/evolution-go/pkg/storage/interfaces"
storage_interfaces "github.com/evolution-foundation/evolution-go/pkg/storage/interfaces"
"github.com/minio/minio-go/v7"
"github.com/minio/minio-go/v7/pkg/credentials"
)
+2 -2
View File
@@ -3,8 +3,8 @@ package user_handler
import (
"net/http"
instance_model "github.com/EvolutionAPI/evolution-go/pkg/instance/model"
user_service "github.com/EvolutionAPI/evolution-go/pkg/user/service"
instance_model "github.com/evolution-foundation/evolution-go/pkg/instance/model"
user_service "github.com/evolution-foundation/evolution-go/pkg/user/service"
"github.com/gin-gonic/gin"
)
+4 -4
View File
@@ -8,10 +8,10 @@ import (
"net/http"
"time"
instance_model "github.com/EvolutionAPI/evolution-go/pkg/instance/model"
logger_wrapper "github.com/EvolutionAPI/evolution-go/pkg/logger"
"github.com/EvolutionAPI/evolution-go/pkg/utils"
whatsmeow_service "github.com/EvolutionAPI/evolution-go/pkg/whatsmeow/service"
instance_model "github.com/evolution-foundation/evolution-go/pkg/instance/model"
logger_wrapper "github.com/evolution-foundation/evolution-go/pkg/logger"
"github.com/evolution-foundation/evolution-go/pkg/utils"
whatsmeow_service "github.com/evolution-foundation/evolution-go/pkg/whatsmeow/service"
"go.mau.fi/whatsmeow"
"go.mau.fi/whatsmeow/types"
"go.mau.fi/whatsmeow/types/events"
+15
View File
@@ -215,6 +215,21 @@ func ParseJID(arg string) (whatsmeow_types.JID, bool) {
return recipient, true
}
// CanonicalJID returns a JID safe for RAW protocol nodes (chatstate / typing,
// read receipts, presence subscribe, reactions, etc.).
//
// CreateJID intentionally prefixes phone numbers with "+" (e.g.
// "[email protected]") to match the IsOnWhatsApp/display convention.
// Message sending tolerates this because whatsmeow normalizes the JID during
// usync/device resolution. RAW nodes are sent WITHOUT usync, so a malformed
// "+JID" reaches the server and the node is silently dropped (e.g. the "typing"
// indicator never reaches the recipient). WhatsApp user JIDs are digits-only, so
// strip the leading "+" to get the canonical form.
func CanonicalJID(jid whatsmeow_types.JID) whatsmeow_types.JID {
jid.User = strings.TrimPrefix(jid.User, "+")
return jid
}
func CreateHTTPProxy(httpHost, httpPort, user, password string) (func(*http.Request) (*url.URL, error), error) {
address := fmt.Sprintf("http://%s:%s@%s:%s", user, password, httpHost, httpPort)
+59
View File
@@ -1,6 +1,7 @@
package utils
import (
"strings"
"testing"
)
@@ -325,3 +326,61 @@ func TestParseJID(t *testing.T) {
})
}
}
// TestCanonicalJID locks in the fix for the silent typing-indicator / receipt
// drop: ParseJID (via CreateJID) prefixes phone numbers with "+", which is
// tolerated by message sending (usync normalizes it) but breaks RAW nodes
// (chatstate, read receipts, reactions). CanonicalJID must strip that "+" while
// leaving already-canonical JIDs (LID, group, digits-only) untouched.
func TestCanonicalJID(t *testing.T) {
tests := []struct {
name string
input string
expectedJID string // canonical JID expected after ParseJID -> CanonicalJID
}{
{
name: "BR phone strips the leading +",
input: "554187083284",
expectedJID: "[email protected]",
},
{
name: "US phone strips the leading +",
input: "15551234567",
expectedJID: "[email protected]",
},
{
name: "Already-canonical JID is unchanged",
input: "[email protected]",
expectedJID: "[email protected]",
},
{
name: "LID JID is left untouched",
input: "15883309207561@lid",
expectedJID: "15883309207561@lid",
},
{
name: "Group JID is left untouched",
input: "[email protected]",
expectedJID: "[email protected]",
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
jid, ok := ParseJID(tt.input)
if !ok {
t.Fatalf("ParseJID(%q) failed", tt.input)
}
canonical := CanonicalJID(jid)
if got := canonical.String(); got != tt.expectedJID {
t.Errorf("CanonicalJID for input %q = %q, want %q", tt.input, got, tt.expectedJID)
}
if strings.HasPrefix(canonical.User, "+") {
t.Errorf("CanonicalJID for input %q still has '+' in User: %q", tt.input, canonical.User)
}
})
}
}
+50
View File
@@ -0,0 +1,50 @@
package whatsmeow_service
import (
"encoding/json"
"go.mau.fi/whatsmeow/proto/waE2E"
"google.golang.org/protobuf/encoding/protojson"
)
func extractReferralFromMessage(message *waE2E.Message) json.RawMessage {
contextInfo := getContextInfoFromMessage(message)
if contextInfo == nil || contextInfo.GetExternalAdReply() == nil {
return nil
}
referral, err := protojson.Marshal(contextInfo.GetExternalAdReply())
if err != nil || len(referral) == 0 {
return nil
}
return json.RawMessage(referral)
}
func getContextInfoFromMessage(message *waE2E.Message) *waE2E.ContextInfo {
if message == nil {
return nil
}
if extendedText := message.GetExtendedTextMessage(); extendedText != nil {
return extendedText.GetContextInfo()
}
if image := message.GetImageMessage(); image != nil {
return image.GetContextInfo()
}
if audio := message.GetAudioMessage(); audio != nil {
return audio.GetContextInfo()
}
if document := message.GetDocumentMessage(); document != nil {
return document.GetContextInfo()
}
if video := message.GetVideoMessage(); video != nil {
return video.GetContextInfo()
}
return nil
}
+66
View File
@@ -0,0 +1,66 @@
package whatsmeow_service
import (
"encoding/json"
"testing"
"go.mau.fi/whatsmeow/proto/waE2E"
)
func TestExtractReferralFromMessage(t *testing.T) {
message := &waE2E.Message{
ExtendedTextMessage: &waE2E.ExtendedTextMessage{
Text: stringPtr("Hello! I want to know more about this ad."),
ContextInfo: &waE2E.ContextInfo{
ExternalAdReply: &waE2E.ContextInfo_ExternalAdReplyInfo{
Title: stringPtr("Your Dream Farm"),
Body: stringPtr("Discover exclusive rural properties in the countryside."),
CtwaClid: stringPtr("FAKE_CLID_abc123xyz"),
Ref: stringPtr("landing_page_01"),
SourceApp: stringPtr("facebook"),
SourceType: stringPtr("ad"),
SourceID: stringPtr("123456789012345"),
SourceURL: stringPtr("https://fb.me/fake-ad-link"),
ShowAdAttribution: boolPtr(true),
ClickToWhatsappCall: boolPtr(true),
AutomatedGreetingMessageShown: boolPtr(true),
GreetingMessageBody: stringPtr("Hello! I want to know more about this ad."),
},
},
},
}
referral := extractReferralFromMessage(message)
if len(referral) == 0 {
t.Fatal("expected referral payload, got empty")
}
var got map[string]any
if err := json.Unmarshal(referral, &got); err != nil {
t.Fatalf("unmarshal referral: %v", err)
}
if got["ctwaClid"] != "FAKE_CLID_abc123xyz" {
t.Fatalf("expected ctwaClid to be preserved, got %#v", got["ctwaClid"])
}
if got["sourceURL"] != "https://fb.me/fake-ad-link" {
t.Fatalf("expected sourceURL to be preserved, got %#v", got["sourceURL"])
}
if got["showAdAttribution"] != true {
t.Fatalf("expected showAdAttribution to be preserved, got %#v", got["showAdAttribution"])
}
if got["automatedGreetingMessageShown"] != true {
t.Fatalf("expected automatedGreetingMessageShown to be preserved, got %#v", got["automatedGreetingMessageShown"])
}
}
func stringPtr(v string) *string {
return &v
}
func boolPtr(v bool) *bool {
return &v
}
+429 -242
View File
@@ -6,12 +6,12 @@ import (
"database/sql"
"encoding/base64"
"encoding/json"
"errors"
"fmt"
"image/png"
"io"
"math/rand"
"net/http"
"os"
"regexp"
"strconv"
"strings"
@@ -34,19 +34,20 @@ import (
"go.mau.fi/whatsmeow/types/events"
waLog "go.mau.fi/whatsmeow/util/log"
"github.com/EvolutionAPI/evolution-go/pkg/config"
producer_interfaces "github.com/EvolutionAPI/evolution-go/pkg/events/interfaces"
instance_model "github.com/EvolutionAPI/evolution-go/pkg/instance/model"
instance_repository "github.com/EvolutionAPI/evolution-go/pkg/instance/repository"
"github.com/EvolutionAPI/evolution-go/pkg/internal/event_types"
label_model "github.com/EvolutionAPI/evolution-go/pkg/label/model"
label_repository "github.com/EvolutionAPI/evolution-go/pkg/label/repository"
logger_wrapper "github.com/EvolutionAPI/evolution-go/pkg/logger"
message_model "github.com/EvolutionAPI/evolution-go/pkg/message/model"
message_repository "github.com/EvolutionAPI/evolution-go/pkg/message/repository"
poll_service "github.com/EvolutionAPI/evolution-go/pkg/poll/service"
storage_interfaces "github.com/EvolutionAPI/evolution-go/pkg/storage/interfaces"
"github.com/EvolutionAPI/evolution-go/pkg/utils"
"github.com/evolution-foundation/evolution-go/pkg/config"
producer_interfaces "github.com/evolution-foundation/evolution-go/pkg/events/interfaces"
instance_model "github.com/evolution-foundation/evolution-go/pkg/instance/model"
instance_repository "github.com/evolution-foundation/evolution-go/pkg/instance/repository"
"github.com/evolution-foundation/evolution-go/pkg/internal/event_types"
label_model "github.com/evolution-foundation/evolution-go/pkg/label/model"
label_repository "github.com/evolution-foundation/evolution-go/pkg/label/repository"
logger_wrapper "github.com/evolution-foundation/evolution-go/pkg/logger"
message_model "github.com/evolution-foundation/evolution-go/pkg/message/model"
message_repository "github.com/evolution-foundation/evolution-go/pkg/message/repository"
"github.com/evolution-foundation/evolution-go/pkg/passkey/ceremony"
poll_service "github.com/evolution-foundation/evolution-go/pkg/poll/service"
storage_interfaces "github.com/evolution-foundation/evolution-go/pkg/storage/interfaces"
"github.com/evolution-foundation/evolution-go/pkg/utils"
)
type WhatsmeowService interface {
@@ -61,6 +62,12 @@ type WhatsmeowService interface {
UpdateInstanceSettings(instanceId string) error
UpdateInstanceAdvancedSettings(instanceId string) error
GetPollService() poll_service.PollService // NOVO: Acesso ao serviço de polls
// Passkey (WebAuthn) pairing bridge — read by the public ceremony endpoint,
// written by the whatsmeow event goroutine.
PasskeyCeremonyStore() *ceremony.Store
SubmitPasskeyResponse(instanceId string, resp *types.WebAuthnResponse) error
ConfirmPasskey(instanceId string) error
}
type clientVersion struct {
@@ -89,6 +96,7 @@ type whatsmeowService struct {
processedMessages *cache.Cache
natsProducer producer_interfaces.Producer
loggerWrapper *logger_wrapper.LoggerManager
passkeyCeremony *ceremony.Store
}
type MyClient struct {
@@ -108,6 +116,7 @@ type MyClient struct {
labelRepository label_repository.LabelRepository
pollService poll_service.PollService // NOVO: Serviço de enquetes
clientPointer map[string]*whatsmeow.Client
myClientPointer map[string]*MyClient
killChannel map[string](chan bool)
userInfoCache *cache.Cache
config *config.Config
@@ -120,6 +129,19 @@ type MyClient struct {
natsProducer producer_interfaces.Producer
loggerWrapper *logger_wrapper.LoggerManager
qrcodeCount int
passkeyCeremony *ceremony.Store
}
func (mycli *MyClient) persistMessageAsync(message message_model.Message) {
if mycli == nil || mycli.messageRepository == nil {
return
}
go func() {
if err := mycli.messageRepository.InsertMessage(message); err != nil {
mycli.loggerWrapper.GetLogger(mycli.userID).LogError("[%s] Failed to persist message %s: %v", mycli.userID, message.MessageID, err)
}
}()
}
type ClientData struct {
@@ -460,6 +482,7 @@ func (w whatsmeowService) StartClient(cd *ClientData) {
pollService: w.pollService, // NOVO: Serviço de enquetes
userInfoCache: w.userInfoCache,
clientPointer: w.clientPointer,
myClientPointer: w.myClientPointer,
killChannel: w.killChannel,
config: w.config,
historySyncID: 0,
@@ -471,6 +494,7 @@ func (w whatsmeowService) StartClient(cd *ClientData) {
natsProducer: w.natsProducer,
loggerWrapper: w.loggerWrapper,
qrcodeCount: 0,
passkeyCeremony: w.passkeyCeremony,
}
mycli.eventHandlerID = mycli.WAClient.AddEventHandler(mycli.myEventHandler)
@@ -509,224 +533,41 @@ func (w whatsmeowService) StartClient(cd *ClientData) {
}
}
} else {
qrChan, err := client.GetQRChannel(context.Background())
// New-device pairing. We intentionally do NOT use client.GetQRChannel:
// in the installed whatsmeow its qrChannel handler auto-confirms a
// passkey ceremony (SkipHandoffUX) and Disconnects the socket when the
// QR codes run out, both of which break passkey pairing (DOC2 §4.3/§4.4).
// Instead we Connect() directly and consume *events.QR in myEventHandler
// (see handleQRCodes), which pair.go dispatches to every handler anyway.
err = client.Connect()
if err != nil {
if !errors.Is(err, whatsmeow.ErrQRStoreContainsID) {
w.loggerWrapper.GetLogger(cd.Instance.Id).LogError("[%s] Failed to get QR channel: %v", cd.Instance.Id, err)
return
}
} else {
err = client.Connect()
if err != nil {
if strings.Contains(err.Error(), "EOF") {
w.loggerWrapper.GetLogger(cd.Instance.Id).LogError("[%s] Erro de conexão WebSocket (EOF). Tentando reconectar em 5 segundos...", cd.Instance.Id)
time.Sleep(5 * time.Second)
err = client.Connect()
if err != nil {
w.loggerWrapper.GetLogger(cd.Instance.Id).LogError("[%s] Falha na segunda tentativa de conexão: %v", cd.Instance.Id, err)
return
}
} else if strings.Contains(err.Error(), "username/password authentication failed") {
w.loggerWrapper.GetLogger(cd.Instance.Id).LogWarn("[%s] Proxy authentication failed during QR connection, attempting without proxy", cd.Instance.Id)
// Desabilita o proxy
client.SetProxy(nil)
// Tenta conectar sem proxy
err = client.Connect()
if err != nil {
w.loggerWrapper.GetLogger(cd.Instance.Id).LogError("[%s] Failed to connect even without proxy: %v", cd.Instance.Id, err)
return
}
w.loggerWrapper.GetLogger(cd.Instance.Id).LogInfo("[%s] Successfully connected without proxy", cd.Instance.Id)
} else {
w.loggerWrapper.GetLogger(cd.Instance.Id).LogError("[%s] Failed to connect: %v", cd.Instance.Id, err)
if strings.Contains(err.Error(), "EOF") {
w.loggerWrapper.GetLogger(cd.Instance.Id).LogError("[%s] Erro de conexão WebSocket (EOF). Tentando reconectar em 5 segundos...", cd.Instance.Id)
time.Sleep(5 * time.Second)
err = client.Connect()
if err != nil {
w.loggerWrapper.GetLogger(cd.Instance.Id).LogError("[%s] Falha na segunda tentativa de conexão: %v", cd.Instance.Id, err)
return
}
}
} else if strings.Contains(err.Error(), "username/password authentication failed") {
w.loggerWrapper.GetLogger(cd.Instance.Id).LogWarn("[%s] Proxy authentication failed during QR connection, attempting without proxy", cd.Instance.Id)
for evt := range qrChan {
w.loggerWrapper.GetLogger(cd.Instance.Id).LogInfo("[%s] Received QR code event %s", cd.Instance.Id, evt.Event)
if evt.Event == "code" {
// Incrementar contador de QR codes
mycli.qrcodeCount++
// Desabilita o proxy
client.SetProxy(nil)
// Log com status do limite
if w.config.QrcodeMaxCount > 0 {
w.loggerWrapper.GetLogger(cd.Instance.Id).LogInfo("[%s] QR code generated #%d (max: %d)", cd.Instance.Id, mycli.qrcodeCount, w.config.QrcodeMaxCount)
} else {
w.loggerWrapper.GetLogger(cd.Instance.Id).LogInfo("[%s] QR code generated #%d (limit disabled)", cd.Instance.Id, mycli.qrcodeCount)
}
// Verificar se atingiu o limite máximo (0 = desabilitado)
if w.config.QrcodeMaxCount > 0 && mycli.qrcodeCount >= w.config.QrcodeMaxCount {
w.loggerWrapper.GetLogger(cd.Instance.Id).LogWarn("[%s] Maximum QR code count reached (%d), forcing logout and QRTimeout", cd.Instance.Id, w.config.QrcodeMaxCount)
// 1. Forçar logout da instância
if mycli.WAClient.IsConnected() {
w.loggerWrapper.GetLogger(cd.Instance.Id).LogInfo("[%s] Forcing client logout due to QR limit", cd.Instance.Id)
err := mycli.WAClient.Logout(context.Background())
if err != nil {
w.loggerWrapper.GetLogger(cd.Instance.Id).LogWarn("[%s] Error during forced logout: %v", cd.Instance.Id, err)
}
}
// 2. Limpar QR code no banco
cd.Instance.Qrcode = ""
err := w.instanceRepository.UpdateQrcode(cd.Instance.Id, "")
if err != nil {
w.loggerWrapper.GetLogger(cd.Instance.Id).LogError("[%s] Error clearing QR code: %v", cd.Instance.Id, err)
}
// 3. Atualizar status da instância como desconectada
cd.Instance.Connected = false
cd.Instance.DisconnectReason = fmt.Sprintf("QR code limit reached (%d)", w.config.QrcodeMaxCount)
err = w.instanceRepository.UpdateConnected(cd.Instance.Id, false, cd.Instance.DisconnectReason)
if err != nil {
w.loggerWrapper.GetLogger(cd.Instance.Id).LogError("[%s] Error updating instance status: %v", cd.Instance.Id, err)
}
// 4. Limpar recursos
w.loggerWrapper.GetLogger(cd.Instance.Id).LogWarn("[%s] Cleaning up resources due to QR limit", cd.Instance.Id)
delete(w.clientPointer, cd.Instance.Id)
delete(w.myClientPointer, cd.Instance.Id)
// 5. Enviar sinal de kill
if killChan, exists := w.killChannel[cd.Instance.Id]; exists {
select {
case killChan <- true:
w.loggerWrapper.GetLogger(cd.Instance.Id).LogInfo("[%s] Kill signal sent due to QR limit", cd.Instance.Id)
default:
// Canal pode estar bloqueado
}
delete(w.killChannel, cd.Instance.Id)
}
// 6. Enviar evento QRTimeout
postMap := make(map[string]interface{})
postMap["event"] = "QRTimeout"
postMap["data"] = map[string]interface{}{
"reason": fmt.Sprintf("Maximum QR code count (%d) reached", w.config.QrcodeMaxCount),
"qrcount": mycli.qrcodeCount,
"maxCount": w.config.QrcodeMaxCount,
"forceLogout": true,
}
postMap["instanceToken"] = mycli.token
postMap["instanceId"] = mycli.userID
postMap["instanceName"] = cd.Instance.Name
queueName := strings.ToLower(fmt.Sprintf("%s.%s", cd.Instance.Id, postMap["event"]))
values, err := json.Marshal(postMap)
if err == nil {
go w.CallWebhook(cd.Instance, queueName, values)
if mycli.config.AmqpGlobalEnabled || mycli.config.NatsGlobalEnabled {
go mycli.service.SendToGlobalQueues(postMap["event"].(string), values, mycli.userID)
}
}
w.loggerWrapper.GetLogger(cd.Instance.Id).LogInfo("[%s] QRTimeout event sent due to QR limit enforcement", cd.Instance.Id)
return
}
if w.config.LogType != "json" {
fmt.Println("QR code:\n", evt.Code)
}
image, _ := qrcode.Encode(evt.Code, qrcode.Medium, 256)
base64qrcode := "data:image/png;base64," + base64.StdEncoding.EncodeToString(image)
base64WithCode := base64qrcode + "|" + evt.Code
cd.Instance.Qrcode = base64WithCode
err := w.instanceRepository.UpdateQrcode(cd.Instance.Id, base64WithCode)
if err != nil {
w.loggerWrapper.GetLogger(cd.Instance.Id).LogError("[%s] Error updating instance: %s", cd.Instance.Id, err)
}
postMap := make(map[string]interface{})
postMap["event"] = "QRCode"
dataMap := make(map[string]interface{})
dataMap["qrcode"] = base64qrcode
dataMap["code"] = evt.Code
dataMap["count"] = mycli.qrcodeCount
dataMap["maxCount"] = w.config.QrcodeMaxCount
postMap["data"] = dataMap
postMap["instanceToken"] = mycli.token
postMap["instanceId"] = mycli.userID
postMap["instanceName"] = cd.Instance.Name
var queueName string
if _, ok := postMap["event"]; ok {
queueName = strings.ToLower(fmt.Sprintf("%s.%s", cd.Instance.Id, postMap["event"]))
}
values, err := json.Marshal(postMap)
if err != nil {
w.loggerWrapper.GetLogger(cd.Instance.Id).LogError("[%s] Failed to marshal JSON for queue", cd.Instance.Id)
return
}
go w.CallWebhook(cd.Instance, queueName, values)
if mycli.config.AmqpGlobalEnabled || mycli.config.NatsGlobalEnabled {
go mycli.service.SendToGlobalQueues(postMap["event"].(string), values, mycli.userID)
}
} else if evt.Event == "timeout" {
cd.Instance.Qrcode = ""
err := w.instanceRepository.UpdateQrcode(cd.Instance.Id, "")
if err != nil {
w.loggerWrapper.GetLogger(cd.Instance.Id).LogError("[%s] Error updating instance: %s", cd.Instance.Id, err)
}
w.loggerWrapper.GetLogger(cd.Instance.Id).LogWarn("[%s] QR timeout killing channel", cd.Instance.Id)
delete(w.clientPointer, cd.Instance.Id)
delete(w.myClientPointer, cd.Instance.Id)
w.killChannel[cd.Instance.Id] <- true
postMap := make(map[string]interface{})
postMap["event"] = "QRTimeout"
dataMap := make(map[string]interface{})
postMap["data"] = dataMap
postMap["instanceToken"] = mycli.token
postMap["instanceId"] = mycli.userID
postMap["instanceName"] = cd.Instance.Name
var queueName string
if _, ok := postMap["event"]; ok {
queueName = strings.ToLower(fmt.Sprintf("%s.%s", cd.Instance.Id, postMap["event"]))
}
values, err := json.Marshal(postMap)
if err != nil {
w.loggerWrapper.GetLogger(cd.Instance.Id).LogError("[%s] Failed to marshal JSON for queue", cd.Instance.Id)
return
}
go w.CallWebhook(cd.Instance, queueName, values)
if mycli.config.AmqpGlobalEnabled || mycli.config.NatsGlobalEnabled {
go mycli.service.SendToGlobalQueues(postMap["event"].(string), values, mycli.userID)
}
} else if evt.Event == "success" {
w.loggerWrapper.GetLogger(cd.Instance.Id).LogInfo("[%s] QR pairing ok!", cd.Instance.Id)
} else {
w.loggerWrapper.GetLogger(cd.Instance.Id).LogInfo("[%s] Login event: %s", cd.Instance.Id, evt.Event)
// Tenta conectar sem proxy
err = client.Connect()
if err != nil {
w.loggerWrapper.GetLogger(cd.Instance.Id).LogError("[%s] Failed to connect even without proxy: %v", cd.Instance.Id, err)
return
}
w.loggerWrapper.GetLogger(cd.Instance.Id).LogInfo("[%s] Successfully connected without proxy", cd.Instance.Id)
} else {
w.loggerWrapper.GetLogger(cd.Instance.Id).LogError("[%s] Failed to connect: %v", cd.Instance.Id, err)
return
}
}
}
// Removed auto-reconnect logic to prevent infinite loops
@@ -844,6 +685,174 @@ func processPresenceUpdates(mycli *MyClient) {
}
}
// handleQRCodes forwards a batch of QR codes (events.QR.Codes) to the manager,
// rotating them with whatsmeow's native timing (first code ~60s, the rest ~20s)
// WITHOUT using GetQRChannel. GetQRChannel is deliberately avoided for new-device
// pairing because, in the installed whatsmeow, its qrChannel handler both
// auto-confirms PairPasskeyConfirmation when SkipHandoffUX is set (racing our
// own confirm flow) and Disconnects the socket when codes run out — either of
// which breaks an in-flight passkey ceremony (DOC2 §4.3/§4.4). Consuming
// events.QR here keeps the socket alive for as long as pairing (QR or passkey)
// needs, since events.QR is dispatched to every handler by pair.go regardless.
//
// This preserves the original GetQRChannel-loop behavior byte-for-byte for the
// per-code work (max-count enforcement, PNG encode, DB persist, webhook/queue
// fan-out) and the timeout teardown; only the trigger (batch vs. per-code) and
// the rotation/self-timer are new. Runs in its own goroutine so it never blocks
// the whatsmeow event dispatch.
func (mycli *MyClient) handleQRCodes(codes []string) {
go func() {
instanceID := mycli.userID
for i, code := range codes {
// A successful pair (Store.ID set) or an in-flight passkey ceremony
// supersedes QR — stop rotating WITHOUT tearing down. Store.ID stays
// nil throughout a passkey ceremony (it is only set at PairSuccess),
// so we must also consult the ceremony store, otherwise a ceremony
// that outlasts QR rotation would have its socket/client torn down.
if mycli.WAClient == nil || mycli.WAClient.Store.ID != nil {
return
}
if mycli.passkeyCeremony != nil && mycli.passkeyCeremony.HasActiveByInstance(instanceID) {
mycli.loggerWrapper.GetLogger(instanceID).LogInfo("[%s] Passkey ceremony in progress — pausing QR rotation, keeping socket alive", instanceID)
return
}
mycli.qrcodeCount++
if mycli.config.QrcodeMaxCount > 0 {
mycli.loggerWrapper.GetLogger(instanceID).LogInfo("[%s] QR code generated #%d (max: %d)", instanceID, mycli.qrcodeCount, mycli.config.QrcodeMaxCount)
} else {
mycli.loggerWrapper.GetLogger(instanceID).LogInfo("[%s] QR code generated #%d (limit disabled)", instanceID, mycli.qrcodeCount)
}
// Max-count reached: force logout + teardown + QRTimeout (0 = disabled).
// But never tear down while a passkey ceremony is in flight.
if mycli.config.QrcodeMaxCount > 0 && mycli.qrcodeCount >= mycli.config.QrcodeMaxCount {
if mycli.passkeyCeremony != nil && mycli.passkeyCeremony.HasActiveByInstance(instanceID) {
mycli.loggerWrapper.GetLogger(instanceID).LogInfo("[%s] QR max-count reached but passkey ceremony active — not tearing down", instanceID)
return
}
mycli.loggerWrapper.GetLogger(instanceID).LogWarn("[%s] Maximum QR code count reached (%d), forcing logout and QRTimeout", instanceID, mycli.config.QrcodeMaxCount)
if mycli.WAClient.IsConnected() {
if err := mycli.WAClient.Logout(context.Background()); err != nil {
mycli.loggerWrapper.GetLogger(instanceID).LogWarn("[%s] Error during forced logout: %v", instanceID, err)
}
}
mycli.teardownQR(fmt.Sprintf("Maximum QR code count (%d) reached", mycli.config.QrcodeMaxCount), true)
return
}
if mycli.config.LogType != "json" {
fmt.Println("QR code:\n", code)
}
image, _ := qrcode.Encode(code, qrcode.Medium, 256)
base64qrcode := "data:image/png;base64," + base64.StdEncoding.EncodeToString(image)
base64WithCode := base64qrcode + "|" + code
if err := mycli.instanceRepository.UpdateQrcode(instanceID, base64WithCode); err != nil {
mycli.loggerWrapper.GetLogger(instanceID).LogError("[%s] Error updating instance: %s", instanceID, err)
}
postMap := map[string]interface{}{
"event": "QRCode",
"data": map[string]interface{}{
"qrcode": base64qrcode,
"code": code,
"count": mycli.qrcodeCount,
"maxCount": mycli.config.QrcodeMaxCount,
},
"instanceToken": mycli.token,
"instanceId": instanceID,
"instanceName": mycli.Instance.Name,
}
queueName := strings.ToLower(fmt.Sprintf("%s.%s", instanceID, "QRCode"))
if values, err := json.Marshal(postMap); err == nil {
go mycli.service.CallWebhook(mycli.Instance, queueName, values)
if mycli.config.AmqpGlobalEnabled || mycli.config.NatsGlobalEnabled {
go mycli.service.SendToGlobalQueues("QRCode", values, instanceID)
}
} else {
mycli.loggerWrapper.GetLogger(instanceID).LogError("[%s] Failed to marshal JSON for queue", instanceID)
}
// Rotation timing: first code lives ~60s, subsequent ~20s (whatsmeow native).
timeout := 20 * time.Second
if i == 0 {
timeout = 60 * time.Second
}
time.Sleep(timeout)
}
// Ran out of codes without a PairSuccess. Treat as QR timeout (mirrors
// GetQRChannel's "timeout") — UNLESS a passkey ceremony is in flight, in
// which case the socket must stay alive for the ceremony to complete.
if mycli.WAClient != nil && mycli.WAClient.Store.ID == nil {
if mycli.passkeyCeremony != nil && mycli.passkeyCeremony.HasActiveByInstance(instanceID) {
mycli.loggerWrapper.GetLogger(instanceID).LogInfo("[%s] QR codes exhausted but passkey ceremony active — keeping socket alive", instanceID)
return
}
mycli.teardownQR("", false)
}
}()
}
// teardownQR clears the QR state and emits a QRTimeout event, then signals the
// kill channel so StartClient's select loop performs the actual disconnect and
// map cleanup. IMPORTANT: this method must NOT delete from the shared
// clientPointer/myClientPointer/killChannel maps itself — those are unsynchronized
// service-wide maps and this runs in the handleQRCodes goroutine; doing the
// delete()s here (concurrent with other instances' goroutines and the whatsmeow
// dispatch) risks a `fatal error: concurrent map writes`. The kill-channel send
// is blocking (like the original GetQRChannel timeout branch) so the signal is
// never dropped and the socket can't be orphaned. Cleanup happens in the
// StartClient goroutine, the single writer of those maps for this instance.
// If reason is non-empty it is included in the QRTimeout payload (max-count path).
func (mycli *MyClient) teardownQR(reason string, forceLogout bool) {
instanceID := mycli.userID
if err := mycli.instanceRepository.UpdateQrcode(instanceID, ""); err != nil {
mycli.loggerWrapper.GetLogger(instanceID).LogError("[%s] Error updating instance: %s", instanceID, err)
}
if reason != "" {
if err := mycli.instanceRepository.UpdateConnected(instanceID, false, reason); err != nil {
mycli.loggerWrapper.GetLogger(instanceID).LogError("[%s] Error updating instance status: %v", instanceID, err)
}
}
data := map[string]interface{}{}
if reason != "" {
data["reason"] = reason
data["qrcount"] = mycli.qrcodeCount
data["maxCount"] = mycli.config.QrcodeMaxCount
data["forceLogout"] = forceLogout
}
postMap := map[string]interface{}{
"event": "QRTimeout",
"data": data,
"instanceToken": mycli.token,
"instanceId": instanceID,
"instanceName": mycli.Instance.Name,
}
queueName := strings.ToLower(fmt.Sprintf("%s.%s", instanceID, "QRTimeout"))
if values, err := json.Marshal(postMap); err == nil {
go mycli.service.CallWebhook(mycli.Instance, queueName, values)
if mycli.config.AmqpGlobalEnabled || mycli.config.NatsGlobalEnabled {
go mycli.service.SendToGlobalQueues("QRTimeout", values, instanceID)
}
}
// Signal StartClient's select loop to disconnect and clean up the shared
// maps (it is the single writer for this instance). Blocking send mirrors
// the original timeout branch so the signal is never dropped.
mycli.loggerWrapper.GetLogger(instanceID).LogWarn("[%s] QR timeout — signaling kill channel", instanceID)
if killChan, exists := mycli.killChannel[instanceID]; exists {
killChan <- true
}
}
func (mycli *MyClient) myEventHandler(rawEvt interface{}) {
userID := mycli.userID
postMap := make(map[string]interface{})
@@ -851,6 +860,11 @@ func (mycli *MyClient) myEventHandler(rawEvt interface{}) {
doWebhook := false
switch evt := rawEvt.(type) {
case *events.QR:
// New-device pairing emits QR codes here (we connect without GetQRChannel
// so the socket survives a passkey ceremony). Forward + rotate them.
mycli.handleQRCodes(evt.Codes)
return
case *events.AppStateSyncComplete:
if len(mycli.WAClient.Store.PushName) > 0 && evt.Name == appstate.WAPatchCriticalBlock {
err := mycli.WAClient.SendPresence(context.Background(), types.PresenceUnavailable)
@@ -905,13 +919,28 @@ func (mycli *MyClient) myEventHandler(rawEvt interface{}) {
postMap["data"] = dataMap
go schedulePresenceUpdates(mycli)
// Respect the alwaysOnline instance flag. Previously the device was marked
// online unconditionally on every connect (and the periodic presence job was
// started), which kept the linked device permanently "available". WhatsApp then
// delivers messages to that active session and suppresses push notifications on
// the user's phone. When alwaysOnline is false we now send Unavailable instead.
var err error
if mycli.Instance.AlwaysOnline {
go schedulePresenceUpdates(mycli)
err := mycli.WAClient.SendPresence(context.Background(), types.PresenceAvailable)
if err != nil {
mycli.loggerWrapper.GetLogger(mycli.userID).LogWarn("[%s] Failed to send available presence %v", mycli.userID, err)
err = mycli.WAClient.SendPresence(context.Background(), types.PresenceAvailable)
if err != nil {
mycli.loggerWrapper.GetLogger(mycli.userID).LogWarn("[%s] Failed to send available presence %v", mycli.userID, err)
} else {
mycli.loggerWrapper.GetLogger(mycli.userID).LogWarn("[%s] Marked self as available", mycli.userID)
}
} else {
mycli.loggerWrapper.GetLogger(mycli.userID).LogWarn("[%s] Marked self as available", mycli.userID)
err = mycli.WAClient.SendPresence(context.Background(), types.PresenceUnavailable)
if err != nil {
mycli.loggerWrapper.GetLogger(mycli.userID).LogWarn("[%s] Failed to send unavailable presence %v", mycli.userID, err)
} else {
mycli.loggerWrapper.GetLogger(mycli.userID).LogInfo("[%s] Marked self as unavailable (alwaysOnline=false)", mycli.userID)
}
}
mycli.Instance.Connected = true
@@ -994,6 +1023,82 @@ func (mycli *MyClient) myEventHandler(rawEvt interface{}) {
}
postMap["data"] = dataMap
// Pairing succeeded — tear down any pending passkey ceremony for this instance.
mycli.passkeyCeremony.Clear(mycli.userID)
case *events.PairPasskeyRequest:
// The server demands a WebAuthn passkey to finish linking. We CANNOT
// produce the assertion here (it needs the user's authenticator on the
// web.whatsapp.com origin) — we only forward the challenge. The browser
// extension (tools/passkey-helper) runs navigator.credentials.get() and
// POSTs the assertion back to /passkey-ceremony/{token}/response, which
// is where SendPasskeyResponse is actually called.
doWebhook = true
postMap["event"] = "PasskeyRequest"
pkJSON, err := json.Marshal(evt.PublicKey)
if err != nil {
mycli.loggerWrapper.GetLogger(mycli.userID).LogError("[%s] Failed to marshal passkey publicKey: %v", mycli.userID, err)
mycli.passkeyCeremony.SetError(mycli.userID, "failed to encode passkey challenge")
return
}
token := mycli.passkeyCeremony.Start(mycli.userID, pkJSON)
// Build the #wapk payload the extension consumes: base64url({t,b}).
// `b` must be the PUBLICLY reachable API base the browser can hit
// (a tunnel / LAN IP in dev) — set PASSKEY_PUBLIC_URL to that base.
publicBase := os.Getenv("PASSKEY_PUBLIC_URL")
if publicBase == "" {
publicBase = "<SET_PASSKEY_PUBLIC_URL>"
}
payload := fmt.Sprintf(`{"t":%q,"b":%q}`, token, publicBase)
wapk := base64.RawURLEncoding.EncodeToString([]byte(payload))
openURL := "https://web.whatsapp.com/#wapk=" + wapk
mycli.loggerWrapper.GetLogger(mycli.userID).LogInfo(
"[%s] Passkey required. Open this URL in a browser with the Evolution Passkey Helper extension:\n%s\n(ceremony token=%s, base=%s)",
mycli.userID, openURL, token, publicBase,
)
// Surface the ceremony info to webhooks/queues so the manager UI can
// render the "Abrir WhatsApp Web" button.
postMap["data"] = map[string]interface{}{
"ceremonyToken": token,
"openUrl": openURL,
"stage": "challenge",
}
case *events.PairPasskeyConfirmation:
// The server returned a confirmation code. Per DOC2 §4.2 we NEVER
// auto-confirm on SkipHandoffUX — we always force skipHandoffUX=false so
// the extension shows the manual "Confirmar" button, and the actual
// SendPasskeyConfirmation happens from /passkey-ceremony/{token}/confirm.
doWebhook = true
postMap["event"] = "PasskeyConfirmation"
mycli.passkeyCeremony.SetConfirmation(mycli.userID, evt.Code, false)
mycli.loggerWrapper.GetLogger(mycli.userID).LogInfo(
"[%s] Passkey confirmation code=%s (skipHandoffUX from server=%v, forced to manual)",
mycli.userID, evt.Code, evt.SkipHandoffUX,
)
postMap["data"] = map[string]interface{}{
"code": evt.Code,
"stage": "confirmation",
}
case *events.PairPasskeyError:
doWebhook = true
postMap["event"] = "PasskeyError"
msg := "unknown passkey error"
if evt.Error != nil {
msg = evt.Error.Error()
}
mycli.passkeyCeremony.SetError(mycli.userID, msg)
mycli.loggerWrapper.GetLogger(mycli.userID).LogError(
"[%s] Passkey pairing error (continuation=%v): %s", mycli.userID, evt.Continuation, msg,
)
postMap["data"] = map[string]interface{}{
"error": msg,
"stage": "error",
}
case *events.StreamReplaced:
mycli.loggerWrapper.GetLogger(mycli.userID).LogInfo("[%s] Received StreamReplaced event", mycli.userID)
return
@@ -1161,6 +1266,8 @@ func (mycli *MyClient) myEventHandler(rawEvt interface{}) {
dataMap = make(map[string]interface{})
}
referral := extractReferralFromMessage(evt.Message)
if evt.Message.GetPollUpdateMessage() != nil {
fmt.Printf("[POLL DEBUG] 🎯 PollUpdateMessage detected!\n")
fmt.Printf("[POLL DEBUG] � BEFORE accessing evt.Info - Sender: %s, Server: %s\n", evt.Info.Sender.String(), evt.Info.Sender.Server)
@@ -1256,6 +1363,10 @@ func (mycli *MyClient) myEventHandler(rawEvt interface{}) {
dataMap["isQuoted"] = true
}
if len(referral) > 0 {
dataMap["referral"] = referral
}
if mycli.config.WebhookFiles {
isMedia := false
@@ -1514,6 +1625,18 @@ func (mycli *MyClient) myEventHandler(rawEvt interface{}) {
postMap["data"] = dataMap
if mycli.config.DatabaseSaveMessages {
message := message_model.Message{
MessageID: evt.Info.ID,
Timestamp: evt.Info.Timestamp.Format("2006-01-02 15:04:05"),
Status: "Received",
Source: evt.Info.Chat.ToNonAD().User,
Referral: referral,
}
mycli.persistMessageAsync(message)
}
// ===== BUTTON CLICK EVENT DETECTION =====
// Detecta cliques em botões e emite evento separado "ButtonClick"
// Suporta 3 formatos: ButtonsResponseMessage, InteractiveResponseMessage (NativeFlow), TemplateButtonReplyMessage
@@ -1577,17 +1700,17 @@ func (mycli *MyClient) myEventHandler(rawEvt interface{}) {
buttonClickMap := map[string]interface{}{
"event": "ButtonClick",
"data": map[string]interface{}{
"buttonId": buttonClickData["buttonId"],
"buttonText": buttonClickData["buttonText"],
"type": buttonClickData["type"],
"phone": dataMap["Sender"],
"jid": dataMap["Sender"],
"pushName": dataMap["PushName"],
"messageId": dataMap["ID"],
"chat": dataMap["Chat"],
"fromMe": dataMap["FromMe"],
"timestamp": evt.Info.Timestamp.Unix(),
"extraData": buttonClickData,
"buttonId": buttonClickData["buttonId"],
"buttonText": buttonClickData["buttonText"],
"type": buttonClickData["type"],
"phone": dataMap["Sender"],
"jid": dataMap["Sender"],
"pushName": dataMap["PushName"],
"messageId": dataMap["ID"],
"chat": dataMap["Chat"],
"fromMe": dataMap["FromMe"],
"timestamp": evt.Info.Timestamp.Unix(),
"extraData": buttonClickData,
},
"instanceToken": mycli.token,
"instanceId": mycli.userID,
@@ -1643,7 +1766,7 @@ func (mycli *MyClient) myEventHandler(rawEvt interface{}) {
message.Source = evt.Chat.ToNonAD().User
if mycli.config.DatabaseSaveMessages {
go mycli.messageRepository.InsertMessage(message)
mycli.persistMessageAsync(message)
}
}
} else {
@@ -1668,7 +1791,7 @@ func (mycli *MyClient) myEventHandler(rawEvt interface{}) {
mycli.processedMessages.Set(messageKey, true, 30*time.Minute)
if mycli.config.DatabaseSaveMessages {
go mycli.messageRepository.InsertMessage(message)
mycli.persistMessageAsync(message)
}
mycli.loggerWrapper.GetLogger(mycli.userID).LogInfo("[%s] Message delivered to %s", mycli.userID, evt.SourceString())
@@ -1898,6 +2021,12 @@ func (mycli *MyClient) myEventHandler(rawEvt interface{}) {
case *events.PushName:
doWebhook = true
postMap["event"] = "PushName"
case *events.Picture:
doWebhook = true
postMap["event"] = "Picture"
case *events.UserAbout:
doWebhook = true
postMap["event"] = "UserAbout"
case *events.IdentityChange:
doWebhook = false
case *events.GroupInfo:
@@ -1994,6 +2123,7 @@ func (w *whatsmeowService) CallWebhook(instance *instance_model.Instance, queueN
if len(eventArray) < 1 {
subscriptions = append(subscriptions, event_types.MESSAGE)
subscriptions = append(subscriptions, event_types.SEND_MESSAGE)
} else {
for _, arg := range eventArray {
if !event_types.IsEventType(arg) {
@@ -2107,6 +2237,16 @@ func (w *whatsmeowService) CallWebhook(instance *instance_model.Instance, queueN
w.loggerWrapper.GetLogger(instance.Id).LogInfo("[%s] Event received of type %s", instance.Id, eventType)
w.sendToQueueOrWebhook(instance, queueName, jsonData)
}
case "Picture":
if contains(subscriptions, "PICTURE") {
w.loggerWrapper.GetLogger(instance.Id).LogInfo("[%s] Event received of type %s", instance.Id, eventType)
w.sendToQueueOrWebhook(instance, queueName, jsonData)
}
case "UserAbout":
if contains(subscriptions, "USER_ABOUT") {
w.loggerWrapper.GetLogger(instance.Id).LogInfo("[%s] Event received of type %s", instance.Id, eventType)
w.sendToQueueOrWebhook(instance, queueName, jsonData)
}
case "GroupInfo", "JoinedGroup":
if contains(subscriptions, "GROUP") {
w.loggerWrapper.GetLogger(instance.Id).LogInfo("[%s] Event received of type %s", instance.Id, eventType)
@@ -2376,6 +2516,10 @@ func (w *whatsmeowService) SendToGlobalQueues(eventType string, payload []byte,
globalEventType = "LABEL"
case "Contact", "PushName":
globalEventType = "CONTACT"
case "Picture":
globalEventType = "PICTURE"
case "UserAbout":
globalEventType = "USER_ABOUT"
case "GroupInfo", "JoinedGroup":
globalEventType = "GROUP"
case "NewsletterJoin", "NewsletterLeave":
@@ -2686,6 +2830,7 @@ func NewWhatsmeowService(
processedMessages: cache.New(30*time.Minute, 1*time.Hour),
natsProducer: natsProducer,
loggerWrapper: loggerWrapper,
passkeyCeremony: ceremony.NewStore(),
}
}
@@ -2694,6 +2839,48 @@ func (w *whatsmeowService) GetPollService() poll_service.PollService {
return w.pollService
}
// PasskeyCeremonyStore exposes the shared ceremony store so the public HTTP
// polling endpoint can read the current stage for a given ceremony token.
func (w *whatsmeowService) PasskeyCeremonyStore() *ceremony.Store {
return w.passkeyCeremony
}
// SubmitPasskeyResponse forwards the browser's WebAuthn assertion to WhatsApp
// for the given instance. Called by POST /passkey-ceremony/{token}/response.
func (w *whatsmeowService) SubmitPasskeyResponse(instanceId string, resp *types.WebAuthnResponse) error {
client, ok := w.clientPointer[instanceId]
if !ok || client == nil {
return fmt.Errorf("no active client for instance %s", instanceId)
}
ctx, cancel := context.WithTimeout(context.Background(), 45*time.Second)
defer cancel()
if err := client.SendPasskeyResponse(ctx, resp); err != nil {
w.passkeyCeremony.SetError(instanceId, err.Error())
return err
}
// Server will asynchronously emit PairPasskeyConfirmation (or Error) into
// the event handler; move to the waiting stage in the meantime.
w.passkeyCeremony.SetAwaitingConfirmation(instanceId)
return nil
}
// ConfirmPasskey finishes the pairing after the user verified the code.
// Called by POST /passkey-ceremony/{token}/confirm.
func (w *whatsmeowService) ConfirmPasskey(instanceId string) error {
client, ok := w.clientPointer[instanceId]
if !ok || client == nil {
return fmt.Errorf("no active client for instance %s", instanceId)
}
ctx, cancel := context.WithTimeout(context.Background(), 45*time.Second)
defer cancel()
if err := client.SendPasskeyConfirmation(ctx); err != nil {
w.passkeyCeremony.SetError(instanceId, err.Error())
return err
}
w.passkeyCeremony.SetConfirmed(instanceId)
return nil
}
// cleanSenderID remove a parte ":numero" do sender ID para exibir apenas o remoteJid correto
// Exemplo: "557499879409:[email protected]" -> "[email protected]"
func cleanSenderID(senderID string) string {