Skip to content

Conversation

@ricaelchiquetti
Copy link

@ricaelchiquetti ricaelchiquetti commented Oct 30, 2025

📋 Description

Consolida correções e melhorias nas integrações WhatsApp (Business API e Baileys) e compatibilidade com Undici no utilitário de proxy.

WhatsApp Business API:

  1. Correção do envio de mídia em base64
  2. Tratamento para evitar envio indevido de filename e caption em cenários específicos
  3. Ajuste do tratamento da chave de mídia nas mensagens

WhatsApp Baileys:

  1. Ajuste na manipulação do remoteJid no serviço
  2. Atualizações para compatibilidade com a nova versão da API (Baileys 7)

Utilitários:

  1. src/utils/makeProxyAgent.ts: compatibilidade com Undici, ordenação de imports e formatação (Prettier/ESLint)

🧪 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

Cenários validados:

  1. Envio de mensagens com mídia base64 (Business API)
  2. Não enviar filename/caption quando não aplicável
  3. Manipulação correta de remoteJid (Baileys)
  4. Fluxos de envio padrão (texto, mídia, docs) em Baileys e Business
  5. Build/Typecheck/Lint via hooks (pre-push)

Passos para reproduzir:

  1. npm ci
  2. npm run build
  3. npm run lint:check
  4. Validar endpoints de envio WhatsApp (Business/Baileys) com e sem mídia base64, com/sem filename/caption, e checar remoteJid.
  • Manual testing completed
  • Functionality verified in development environment
  • No breaking changes introduced
  • Tested with different connection types (if applicable)

✅ Checklist

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

Summary by Sourcery

Consolidate fixes and enhancements for WhatsApp Business API and Baileys integrations, improving media handling, remoteJid selection, and proxy utility compatibility with Undici

Bug Fixes:

  • Prevent filename and caption from being sent in Business API messages for unsupported media types
  • Correct remoteJid resolution in Baileys integration by using alternate remoteJid when needed

Enhancements:

  • Add Undici ProxyAgent support and clean up imports in makeProxyAgent util
  • Send base64 media in Business API only when local webhook supports it and ensure base64 is always populated by downloading if missing
  • Harmonize fileName and filename properties in Business API media payload

@sourcery-ai
Copy link
Contributor

sourcery-ai bot commented Oct 30, 2025

Reviewer's Guide

Refines media payload logic in WhatsApp Business API and Baileys services—conditional base64 inclusion, dynamic filename/caption omission, remoteJid correction—while updating the proxy agent utility to support Undici.

Sequence diagram for conditional base64 media handling in WhatsApp Business API

sequenceDiagram
    participant S as Service (BusinessStartupService)
    participant S3 as S3Service
    participant W as Webhook
    participant O as OpenAI
    participant P as PrismaRepository
    participant U as User

    U->>S: Send media message
    S->>S3: getObjectUrl(fullName)
    S3-->>S: mediaUrl
    S->>S: Check localWebhook.enabled and webhookBase64
    alt base64 should be included
        S->>S: Add base64 to messageRaw
    else base64 not included
        S->>S: Skip base64
    end
    S->>W: Send messageRaw
    alt mediaType is audio and OpenAI enabled
        S->>O: Send base64 for speech-to-text
        O-->>S: Transcription
        S->>P: Save transcription
    end
Loading

Sequence diagram for remoteJid correction in WhatsApp Baileys service

sequenceDiagram
    participant S as Service (BaileysStartupService)
    participant M as MessageRaw
    participant W as Webhook

    S->>M: Receive message
    S->>S: Check if key.remoteJid includes '@lid' and remoteJidAlt exists
    alt Correction needed
        S->>M: Set key.remoteJid = key.remoteJidAlt
    end
    S->>W: sendDataWebhook(Events.MESSAGES_UPSERT, messageRaw)
Loading

Class diagram for updated BusinessStartupService media handling

classDiagram
    class BusinessStartupService {
        +localWebhook_enabled: boolean
        +localWebhook_webhookBase64: boolean
        +configService: ConfigService
        +prismaRepository: PrismaRepository
        +downloadMediaMessage()
        +handleMediaUpload()
        +handleOpenAISpeechToText()
    }
    class Openai {
        +ENABLED: boolean
    }
    class MessageRaw {
        +mediaUrl
        +base64
        +fileName
        +caption
    }
    BusinessStartupService --> Openai
    BusinessStartupService --> MessageRaw
    BusinessStartupService --> PrismaRepository
Loading

Class diagram for BaileysStartupService remoteJid logic

classDiagram
    class BaileysStartupService {
        +sendDataWebhook()
        +logger
    }
    class MessageRaw {
        +key_remoteJid
        +key_remoteJidAlt
    }
    BaileysStartupService --> MessageRaw
Loading

Class diagram for makeProxyAgentUndici utility update

classDiagram
    class makeProxyAgentUndici {
        +makeProxyAgentUndici(proxy: Proxy | string): ProxyAgent
    }
    class Proxy {
        +host: string
        +port: number
        +protocol: string
        +username: string
        +password: string
    }
    class ProxyAgent {}
    makeProxyAgentUndici --> ProxyAgent
    makeProxyAgentUndici --> Proxy
Loading

File-Level Changes

Change Details Files
Add Undici ProxyAgent support and unify proxy agent logic
  • Imported ProxyAgent from 'undici' alongside existing agents
  • Standardized semicolon usage and import ordering
  • Defined protocol constants and streamlined switch-case for ProxyAgent creation
src/utils/makeProxyAgent.ts
Conditional base64 assignment and payload refinement in WhatsApp Business API
  • Wrapped base64 assignment under localWebhook.webhookBase64 check in S3 and download flows
  • Introduced openAiBase64 fallback for audio speech-to-text processing
  • Excluded filename for audio/video and conditional caption to prevent unwanted metadata
  • Ensured incoming messages missing base64 trigger download and assignment, unified fileName fallback
src/api/integrations/channel/meta/whatsapp.business.service.ts
Correct remoteJid for Baileys messages with legacy IDs
  • Overrode messageRaw.key.remoteJid with remoteJidAlt when remoteJid contains '@lid'
  • Added console logging of adjusted messageRaw for verification
src/api/integrations/channel/whatsapp/whatsapp.baileys.service.ts

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 there - I've reviewed your changes - here's some feedback:

  • Extract the repeated base64 assignment logic in BusinessStartupService into a helper method to eliminate duplication and improve readability.
  • Remove the console.log in BaileysStartupService and use the existing logger for consistent logging practices.
  • Centralize the proxy protocol constants (PROXY_HTTP_PROTOCOL, PROXY_SOCKS5_PROTOCOL, etc.) in a shared module or enum to avoid scattered literals and ease future updates.
Prompt for AI Agents
Please address the comments from this code review:

## Overall Comments
- Extract the repeated base64 assignment logic in BusinessStartupService into a helper method to eliminate duplication and improve readability.
- Remove the console.log in BaileysStartupService and use the existing logger for consistent logging practices.
- Centralize the proxy protocol constants (PROXY_HTTP_PROTOCOL, PROXY_SOCKS5_PROTOCOL, etc.) in a shared module or enum to avoid scattered literals and ease future updates.

## Individual Comments

### Comment 1
<location> `src/api/integrations/channel/meta/whatsapp.business.service.ts:1620-1621` </location>
<code_context>
       const messageType = msg.messageType.includes('Message') ? msg.messageType : msg.messageType + 'Message';
       const mediaMessage = msg.message[messageType];

+      if (!msg.message?.base64) {
+        const buffer = await this.downloadMediaMessage({ type: messageType, ...msg.message });
+        msg.message.base64 = buffer.toString('base64');
+      }
</code_context>

<issue_to_address>
**issue (bug_risk):** Possible risk of overwriting existing message properties.

Spreading msg.message may overwrite the type property if it exists. Explicitly set type to prevent this.
</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.

} else {
const { host, password, port, protocol: proto, username } = proxy
protocol = (proto || 'http').replace(':', '')
const { host, password, port, protocol: proto, username } = proxy;

Check failure

Code scanning / CodeQL

Insecure randomness High

This uses a cryptographically insecure random number generated at
Math.random()
in a security context.
} else {
const { host, password, port, protocol: proto, username } = proxy
protocol = (proto || 'http').replace(':', '')
const { host, password, port, protocol: proto, username } = proxy;

Check failure

Code scanning / CodeQL

Insecure randomness High

This uses a cryptographically insecure random number generated at
Math.random()
in a security context.
} else {
const { host, password, port, protocol: proto, username } = proxy
protocol = (proto || 'http').replace(':', '')
const { host, password, port, protocol: proto, username } = proxy;

Check failure

Code scanning / CodeQL

Insecure randomness High

This uses a cryptographically insecure random number generated at
Math.random()
in a security context.
} else {
const { host, password, port, protocol: proto, username } = proxy
protocol = (proto || 'http').replace(':', '')
const { host, password, port, protocol: proto, username } = proxy;

Check failure

Code scanning / CodeQL

Insecure randomness High

This uses a cryptographically insecure random number generated at
Math.random()
in a security context.
} else {
const { host, password, port, protocol: proto, username } = proxy
protocol = (proto || 'http').replace(':', '')
const { host, password, port, protocol: proto, username } = proxy;

Check failure

Code scanning / CodeQL

Insecure randomness High

This uses a cryptographically insecure random number generated at
Math.random()
in a security context.
@DavidsonGomes DavidsonGomes merged commit 71322cd into EvolutionAPI:develop Nov 7, 2025
4 of 5 checks passed
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.

4 participants