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

+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 {