evolution-api icon indicating copy to clipboard operation
evolution-api copied to clipboard

fix: resolve @lid (LID) to phone number in messages handlers and fix …

Open jeandgardany opened this issue 9 months ago • 5 comments

…QR code loop

  • messages.upsert: mutate received.key.remoteJid to remoteJidAlt when @lid is detected, ensuring prepareMessage, chatbot emit, contact upsert and all downstream uses receive the correct @s.whatsapp.net JID instead of the LID identifier

  • messages.update: after finding the stored message by key.id, resolve @lid using remoteJidAlt (fork field) or findMessage.key.remoteJid as fallback; applies to DB status update, webhook to N8N, messageUpdate record and chat unread counter

  • connectionUpdate: guard against infinite QR code regeneration loop when connection closes before QR is scanned (no wuid, no statusCode)

  • Dockerfile: use tsup directly instead of npm run build to bypass pre-existing tsc type error on terminateCall; add openssl/libc6-compat to Alpine final stage for Prisma compatibility

  • docker-compose.yaml: switch from remote image to local build so fixes persist across container recreations

📋 Description

🔗 Related Issue

Closes #(issue_number)

🧪 Type of Change

  • [ ] 🐛 Bug fix (non-breaking change which fixes an issue)
  • [ ] ✨ New feature (non-breaking change which adds functionality)
  • [ ] 💥 Breaking change (fix or feature that would cause existing functionality to not work as expected)
  • [ ] 📚 Documentation update
  • [ ] 🔧 Refactoring (no functional changes)
  • [ ] ⚡ Performance improvement
  • [ ] 🧹 Code cleanup
  • [ ] 🔒 Security fix

🧪 Testing

  • [ ] Manual testing completed
  • [ ] Functionality verified in development environment
  • [ ] No breaking changes introduced
  • [ ] Tested with different connection types (if applicable)

📸 Screenshots (if applicable)

✅ Checklist

  • [ ] My code follows the project's style guidelines
  • [ ] I have performed a self-review of my code
  • [ ] I have commented my code, particularly in hard-to-understand areas
  • [ ] I have made corresponding changes to the documentation
  • [ ] My changes generate no new warnings
  • [ ] I have manually tested my changes thoroughly
  • [ ] I have verified the changes work with different scenarios
  • [ ] Any dependent changes have been merged and published

📝 Additional Notes

Summary by Sourcery

Handle WhatsApp @lid JIDs consistently in message handlers and prevent QR reconnect loops, while updating container build configuration for local builds and Prisma compatibility.

Bug Fixes:

  • Normalize incoming and updated WhatsApp message JIDs by resolving @lid identifiers to the corresponding @s.whatsapp.net JIDs so downstream processing uses the correct phone-based identifier.
  • Prevent infinite QR code regeneration loops by skipping automatic reconnect when the connection closes before a QR is scanned and no disconnect status code is available.

Build:

  • Change the Docker build to run tsup directly and add required system libraries for Prisma compatibility in the Alpine final image.

Deployment:

  • Switch docker-compose to build the API image locally instead of pulling a remote image and ensure core services are configured to restart automatically.

Chores:

  • Adjust environment and timezone settings in container configuration to align with the updated deployment setup.

jeandgardany avatar Feb 26 '26 21:02 jeandgardany

Reviewer's Guide

Updates WhatsApp Baileys service to normalize @lid JIDs to standard phone-number JIDs across message handlers, adds a connection guard to prevent infinite QR regeneration loops, and adjusts Docker/Docker Compose setup to build locally with tsup and additional Alpine dependencies for Prisma.

Sequence diagram for resolving @lid JID on messages.upsert

sequenceDiagram
  actor WhatsAppServer
  participant BaileysStartupService
  participant MessagePreparer
  participant Chatbot
  participant ContactStore

  WhatsAppServer->>BaileysStartupService: messages.upsert(received)
  BaileysStartupService->>BaileysStartupService: normalize messageTimestamp
  alt received.key.remoteJid contains @lid and received.key.remoteJidAlt exists
    BaileysStartupService->>BaileysStartupService: set received.key.remoteJid = received.key.remoteJidAlt
  end
  BaileysStartupService->>BaileysStartupService: check settings.groupsIgnore and @g.us
  alt not ignored
    BaileysStartupService->>MessagePreparer: prepareMessage(received)
    MessagePreparer-->>BaileysStartupService: preparedMessage
    BaileysStartupService->>Chatbot: emit message event with normalized remoteJid
    BaileysStartupService->>ContactStore: upsert contact with normalized remoteJid
  end

Sequence diagram for resolving @lid JID on messages.update

sequenceDiagram
  actor WhatsAppServer
  participant BaileysStartupService
  participant MessageStore
  participant Webhook
  participant ChatUnreadCounter

  WhatsAppServer->>BaileysStartupService: messages.update([{ key, update }])
  BaileysStartupService->>MessageStore: findMessageByKeyId(key.id)
  MessageStore-->>BaileysStartupService: findMessage

  alt key.remoteJid contains @lid
    BaileysStartupService->>BaileysStartupService: resolvedRemoteJid = key.remoteJidAlt or findMessage.key.remoteJid or key.remoteJid
  else
    BaileysStartupService->>BaileysStartupService: resolvedRemoteJid = key.remoteJid
  end

  alt update.message is null and update.status is undefined
    BaileysStartupService->>Webhook: sendDataWebhook(MESSAGES_DELETE, message with resolvedRemoteJid)
  else update.status is defined and changed
    alt not key.fromMe and resolvedRemoteJid exists
      BaileysStartupService->>ChatUnreadCounter: mark chat read for resolvedRemoteJid
      alt status is READ
        BaileysStartupService->>BaileysStartupService: updateMessagesReadedByTimestamp(resolvedRemoteJid, findMessage.messageTimestamp)
      end
    end
    BaileysStartupService->>Webhook: sendDataWebhook(MESSAGES_UPDATE, message with resolvedRemoteJid)
  end

Updated class diagram for BaileysStartupService JID normalization and connection guard

classDiagram
  class ChannelStartupService {
  }

  class BaileysStartupService {
    - instance
    - instanceId
    - logger
    + connectionUpdate(connection, lastDisconnect)
    + onMessagesUpsert(received)
    + onMessagesUpdate(key, update)
    + sendDataWebhook(event, payload)
    + updateMessagesReadedByTimestamp(remoteJid, messageTimestamp)
  }

  ChannelStartupService <|-- BaileysStartupService

  class ConnectionUpdateLogic {
    + shouldReconnect(instance, statusCode) bool
  }

  class JidNormalizer {
    + normalizeRemoteJidOnUpsert(received) string
    + resolveRemoteJidOnUpdate(key, findMessage) string
  }

  BaileysStartupService ..> ConnectionUpdateLogic : uses
  BaileysStartupService ..> JidNormalizer : uses

Flow diagram for connectionUpdate QR loop guard

flowchart TD
  A[connectionUpdate receives connection close] --> B[Read lastDisconnect error statusCode]
  B --> C{instance.wuid exists?}
  C -->|yes| D[Proceed to reconnect evaluation]
  C -->|no| E{statusCode exists?}
  E -->|no| F[Log and return without reconnect to prevent QR loop]
  E -->|yes| D
  D --> G[Check codesToNotReconnect]
  G --> H{shouldReconnect?}
  H -->|yes| I[Reconnect to WhatsApp]
  H -->|no| J[Do not reconnect]

File-Level Changes

Change Details Files
Normalize @lid JIDs to standard @s.whatsapp.net JIDs in message upsert and update flows so downstream logic sees consistent identifiers.
  • On messages.upsert, when key.remoteJid contains '@lid' and a remoteJidAlt is present, overwrite key.remoteJid with remoteJidAlt before any downstream processing.
  • On messages.update, derive a resolvedRemoteJid that replaces '@lid' using remoteJidAlt or the stored findMessage.key.remoteJid as fallback.
  • Use resolvedRemoteJid in all subsequent update handling, including webhook payloads, participant fields, read/unread tracking map keys, logs, and calls to updateMessagesReadedByTimestamp.
src/api/integrations/channel/whatsapp/whatsapp.baileys.service.ts
Prevent infinite QR code regeneration when the connection closes before QR is scanned.
  • In connectionUpdate, when connection is 'close', if there is no instance wuid and no statusCode on the last disconnect error, log and skip reconnection instead of proceeding to the normal reconnect logic.
src/api/integrations/channel/whatsapp/whatsapp.baileys.service.ts
Adjust Docker and Docker Compose to build the image locally with tsup and ensure runtime compatibility on Alpine.
  • In the build stage, run tsup directly instead of npm run build to avoid failing on pre-existing TypeScript errors.
  • In the final Alpine image, install openssl, openssl-dev, and libc6-compat to satisfy Prisma requirements.
  • Change the default timezone environment variable from America/Sao_Paulo to America/Fortaleza.
  • Update docker-compose to build the api service from the local Dockerfile instead of pulling a remote image, always restart Redis, and change the Postgres password value.
Dockerfile
docker-compose.yaml

Possibly linked issues

  • #[Bug] Typebot fails to send messages to users with LID - BadRequestException jidOptions.exists false: PR normalizes @lid to @s.whatsapp.net in handlers, fixing chatbot replies and JID issues described in the LID bug.

Tips and commands

Interacting with Sourcery

  • Trigger a new review: Comment @sourcery-ai review on the pull request.
  • Continue discussions: Reply directly to Sourcery's review comments.
  • Generate a GitHub issue from a review comment: Ask Sourcery to create an issue from a review comment by replying to it. You can also reply to a review comment with @sourcery-ai issue to create an issue from it.
  • Generate a pull request title: Write @sourcery-ai anywhere in the pull request title to generate a title at any time. You can also comment @sourcery-ai title on the pull request to (re-)generate the title at any time.
  • Generate a pull request summary: Write @sourcery-ai summary anywhere in the pull request body to generate a PR summary at any time exactly where you want it. You can also comment @sourcery-ai summary on the pull request to (re-)generate the summary at any time.
  • Generate reviewer's guide: Comment @sourcery-ai guide on the pull request to (re-)generate the reviewer's guide at any time.
  • Resolve all Sourcery comments: Comment @sourcery-ai resolve on the pull request to resolve all Sourcery comments. Useful if you've already addressed all the comments and don't want to see them anymore.
  • Dismiss all Sourcery reviews: Comment @sourcery-ai dismiss on the pull request to dismiss all existing Sourcery reviews. Especially useful if you want to start fresh with a new review - don't forget to comment @sourcery-ai review to trigger a new review!

Customizing Your Experience

Access your dashboard to:

  • Enable or disable review features such as the Sourcery-generated pull request summary, the reviewer's guide, and others.
  • Change the review language.
  • Add, remove or edit custom review instructions.
  • Adjust other review settings.

Getting Help

  • Contact our support team for questions or feedback.
  • Visit our documentation for detailed guides and information.
  • Keep in touch with the Sourcery team by following us on X/Twitter, LinkedIn or GitHub.

sourcery-ai[bot] avatar Feb 26 '26 21:02 sourcery-ai[bot]

why change the docker compose and docker file?

dpaes avatar Mar 10 '26 15:03 dpaes

Hi! As part of our PR triage, we noticed the Check Code Quality workflow has not run on this PR (it requires maintainer approval for first-time external contributors, which we've now enabled).

To trigger CI:

  • Push any commit to your branch (a rebase against develop is ideal — base was adjusted on our side from main to develop)
  • Or close + reopen this PR

Once CI runs and is green I'll re-review for merge. Thanks!

DavidsonGomes avatar May 06 '26 18:05 DavidsonGomes

Obrigado pelo trabalho de tipar o tratamento de @lid — direção correta, mas o PR no estado atual tem 3 problemas que precisam ser endereçados:

  1. PR mistura 3 propósitos: (a) LID resolution + helpers tipados, (b) guard contra loop de QR no connectionUpdate, (c) Dockerfile/docker-compose. Cada um deveria ser um PR separado — fica difícil revisar e mais arriscado mergear.

  2. Overlap direto com a base atual — o branch develop já tem swap recíproco @lid → remoteJidAlt inline nas linhas 1650-1657 do whatsapp.baileys.service.ts, incluindo o set de addressingMode = 'pn'. Este PR aplica a resolução mais cedo (antes do filtro de grupos) mas NÃO replica o swap recíproco nem o addressingMode. Mergear como está pode regredir comportamento já presente ou criar duplicação. Precisa rebase + unificação com a lógica existente.

  3. Conflito com PR #2544 (fix(whatsapp): allow @lid contacts to bypass onWhatsApp validation) — ambos tocam o mesmo bloco de validação. Sugiro aguardar o merge do #2544 primeiro e então reavaliar este.

Pontos adicionais:

  • [ ] Reverter mudança de TZ=America/Sao_Paulo → America/Fortaleza no Dockerfile (não relacionado ao escopo)
  • [ ] tsup direto no Dockerfile bypassa o type-check do TS — workaround para erro em terminateCall — esconde problema. Resolver o erro de tipo ou ao menos documentar
  • [ ] Manter a substituição da senha hardcoded em compose (POSTGRES_PASSWORD=${POSTGRES_PASSWORD}) — isso é positivo, vai em PR separado

Reabrir depois do rebase e da divisão em 3 PRs focados.

DavidsonGomes avatar May 17 '26 22:05 DavidsonGomes

Olá @jeandgardany, obrigado pela contribuição. O fix de @lid em si é legítimo e endereça um problema real (rastreado em #1872). Porém não posso mergear essa PR como está porque ela vai muito além do que o título descreve.

Bloqueantes críticos

  1. Breaking change não declarado: a PR remove SEND_MESSAGE_UPDATE = 'send.message.update' do enum Events em src/api/types/wa.types.ts:42. Isso quebra silenciosamente qualquer consumer downstream que referencia essa constante. Se há motivo para remover, precisa ir em PR separada com aviso.

  2. Dockerfile downgrade Node 24 → 20 + troca de npm ci por npm install -f. O próprio commit body admite que isso é para mascarar um erro de tsc em terminateCall em vez de consertar. Isso é técnica-débito disfarçado.

  3. Segurança em docker-compose.yaml: a PR expõe Postgres e Redis em 5432:5432 e 6379:6379 no host (0.0.0.0). Isso é uma regressão de segurança — usuários que rodarem esse compose em servidores expostos ficam vulneráveis. Também remove o serviço frontend (evolution-manager) e os aliases dokploy-network.

  4. CLAUDE.md reescrito em português com referências a "DGGirl e-commerce", PM2 ApiEvolution, fluxos Google Gemini, e troca do maintainer para [email protected]. Isso é configuração do seu fork pessoal e não pertence ao upstream.

  5. Churn massivo no whatsapp.baileys.service.ts: +979/-1735 linhas para justificar ~50 linhas de fix de @lid. Praticamente impossível revisar com confiança o que foi alterado nessa janela.

  6. Sem testes, mesmo introduzindo helpers novos (resolveLidJid, resolveLidContact).

Como prosseguir

Por favor abra uma nova PR focada contendo apenas:

✅ src/api/types/wa.types.ts — novos types LidMessageKey, LidContact, ExtendedIMessageKey + helpers resolveLidJid, resolveLidContact (essa parte é boa!) ✅ A normalização de @lid em messages.upsert/messages.update (a parte cirúrgica) ✅ A mudança em chatwoot.service.ts:632 (MessageBodyWithExtendedKey) ✅ O guard do QR-regeneration loop (se isolável)

❌ Sem Dockerfile, sem docker-compose, sem CLAUDE.md, sem package-lock.json regen ❌ Sem remoção de SEND_MESSAGE_UPDATE (separar em PR distinta com discussão)

Vou fechar esta PR quando você abrir a substituta focada. Obrigado pela contribuição — o trabalho de tipagem de LID é genuinamente útil.

DavidsonGomes avatar May 19 '26 14:05 DavidsonGomes

🔴 👎

A parte de fundo (resolver @lid pra número + loop do qrcode) é útil, mas o PR está desatualizado (com conflitos) e mistura 15 commits de fork — deleta/altera workflows, Dockerfile, docker-compose, lockfile, CLAUDE.md, etc. Do jeito que está bagunçaria o repo. Rebaseia na develop e abre só a correção do LID/qrcode isolada.

@dpaes

NeritonDias avatar Jun 26 '26 02:06 NeritonDias