Skip to content

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

Open
jeandgardany wants to merge 4 commits intoEvolutionAPI:mainfrom
jeandgardany:fix/lid-resolution-and-qrcode-loop
Open

fix: resolve @lid (LID) to phone number in messages handlers and fix …#2450
jeandgardany wants to merge 4 commits intoEvolutionAPI:mainfrom
jeandgardany:fix/lid-resolution-and-qrcode-loop

Conversation

@jeandgardany
Copy link

@jeandgardany jeandgardany commented Feb 26, 2026

…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.

…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

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
@sourcery-ai
Copy link
Contributor

sourcery-ai bot commented Feb 26, 2026

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
Loading

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
Loading

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
Loading

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]
Loading

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

Copy link
Contributor

@sourcery-ai sourcery-ai bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Hey - I've found 1 issue, and left some high level feedback:

  • The hard-coded POSTGRES_PASSWORD=090271jd in docker-compose.yaml exposes a real-looking credential; consider reverting to a placeholder or environment-driven secret so sensitive values are not committed.
  • Switching the Docker build step from npm run build to running tsup directly to bypass an existing tsc error may hide real type issues; it would be more robust to fix the underlying terminateCall type problem and keep a type-checking step in the build/CI pipeline.
  • The new remoteJidAlt handling relies on multiple (key as any) casts; defining a proper type/interface for the message key structure would make this logic safer and easier to maintain.
Prompt for AI Agents
Please address the comments from this code review:

## Overall Comments
- The hard-coded `POSTGRES_PASSWORD=090271jd` in `docker-compose.yaml` exposes a real-looking credential; consider reverting to a placeholder or environment-driven secret so sensitive values are not committed.
- Switching the Docker build step from `npm run build` to running `tsup` directly to bypass an existing `tsc` error may hide real type issues; it would be more robust to fix the underlying `terminateCall` type problem and keep a type-checking step in the build/CI pipeline.
- The new `remoteJidAlt` handling relies on multiple `(key as any)` casts; defining a proper type/interface for the message key structure would make this logic safer and easier to maintain.

## Individual Comments

### Comment 1
<location path="docker-compose.yaml" line_range="45" />
<code_context>
       - 5432:5432
     environment:
-      - POSTGRES_PASSWORD=PASSWORD
+      - POSTGRES_PASSWORD=090271jd
     volumes:
       - postgres_data:/var/lib/postgresql/data
</code_context>
<issue_to_address>
**🚨 issue (security):** Hardcoding the Postgres password in docker-compose is a security risk.

Commiting a concrete password in `docker-compose.yaml` increases the risk of secret leakage and complicates rotation. Use an env var, Docker secret, or `.env` file instead (e.g., `POSTGRES_PASSWORD=${POSTGRES_PASSWORD}`) and manage the actual value outside version control.
</issue_to_address>

Sourcery is free for open source - if you like our reviews please consider sharing them ✨
Help me be more useful! Please click 👍 or 👎 on each comment and I'll use the feedback to improve your reviews.

Copy link
Author

@jeandgardany jeandgardany left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Correçao ENV

root and others added 3 commits February 26, 2026 19:51
Replace literal password with \${POSTGRES_PASSWORD} env var reference.
Password must be set in .env file (already gitignored).

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
…dlers

- message-receipt.update: resolve @lid to @s.whatsapp.net before updating
  read status, ensuring receipts match messages stored with resolved JIDs

- contacts.upsert: use lidJidAlt when contact.id contains @lid, so contacts
  are saved with the correct @s.whatsapp.net JID

- contacts.update: same LID resolution for contact updates

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
… LidContact)

Addresses Sourcery AI review feedback: introduces LidMessageKey and LidContact
interfaces extending Baileys proto types with the LID-specific fields
(remoteJidAlt, lidJidAlt), and adds resolveLidJid/resolveLidContact helpers
to eliminate all `as any` casts for LID resolution across the codebase.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
@jeandgardany jeandgardany force-pushed the fix/lid-resolution-and-qrcode-loop branch from b66926f to b3b2d24 Compare February 27, 2026 11:13
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant