Skip to content

Conversation

@guedesrv
Copy link

@guedesrv guedesrv commented Oct 21, 2025

πŸ“‹ 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

Refactor WhatsApp service initialization and authentication storage, migrate to the baileys package, normalize RabbitMQ event publishing, tighten configuration defaults, fix various webhook and status-fetching bugs, and add CI for Docker image publishing.

New Features:

  • Ignore newsletter JIDs in WhatsApp socket message filtering
  • Support documentWithCaptionMessage types in WhatsApp handlers
  • Add fallback Chatwoot inbox lookup by base name before '-cwId-'
  • Publish Docker image via GitHub Actions workflow

Bug Fixes:

  • Correct fetchStatus indexing when reading profile status
  • Normalize RabbitMQ queue names by replacing underscores and binding to lower-case routing keys
  • Fix base64 handling for documentWithCaption in webhooks
  • Resolve pairing code generation issue
  • Update default WA_BUSINESS token, URL, and version values

Enhancements:

  • Extract WhatsApp client setup into createClient and refine socket configuration defaults (timeouts, retries, logging)
  • Overhaul multi-file auth state to combine filesystem and MongoDB storage
  • Migrate from @whiskeysockets/baileys to baileys package and update import paths
  • Conditionally initialize ProviderFiles behind feature flag and use optional chaining for providerSession
  • Introduce useCachedGroupMetadata flag and add isJidNewsletter to message ignore logic

Build:

  • Bump version to 1.8.2 in package.json and Swagger docs
  • Add GitHub Actions workflow to build and push latest Docker image

Documentation:

  • Update CHANGELOG and Swagger API version to 1.8.2

DavidsonGomes and others added 30 commits June 9, 2024 14:20
Updated package.json to include the latest version of baileys for improved functionality. Modified whatsapp.baileys.service.ts to adjust socket configuration, enhancing the stability and performance of the service.
Updated server.module.ts and monitor.service.ts to improve service initialization and monitoring logic. Modified main.ts to integrate changes. This enhances the application's performance and reliability.
Updated default values for WA_BUSINESS_TOKEN_WEBHOOK, WA_BUSINESS_URL, and WA_BUSINESS_VERSION in env.config.ts to 'evolution', 'https://graph.facebook.com', and 'v19.0' respectively. This change ensures that the application uses more appropriate defaults if environment variables are not set, improving reliability and consistency.
Updated package.json to include latest dependencies. Enhanced caching logic in cache.service.ts and rediscache.ts for better performance. Improved DTOs in chat.dto.ts, instance.dto.ts, and sendMessage.dto.ts for more robust data handling. Refined instance.controller.ts and chatwoot.service.ts to streamline API integrations. Adjusted authentication state management in use-multi-file-auth-state-db.ts, use-multi-file-auth-state-provider-files.ts, and use-multi-file-auth-state-redis-db.ts. These changes aim to optimize the system's performance and reliability.
Reordered imports in multiple files to resolve linting issues and improve code readability. This change does not impact the functionality but ensures the code adheres to the project's coding standards.
Refactored the use-multi-file-auth-state-db.ts to better handle edge cases in multi-file authentication state management. This change improves reliability and ensures more robust error handling, reducing potential issues during authentication.
Normalized event names by replacing underscores with dots and converting to lowercase. This ensures consistent naming conventions and prevents potential issues with queue bindings.
…service

Modified whatsapp.baileys.service.ts to include handling for documentWithCaptionMessage. This change ensures that messages with documents having captions are properly processed, enhancing the service's message handling capabilities. No impact on existing functionalities.
Update package.json to use the new Baileys repository and modify the Whatsapp Baileys service to generate a pairing code. This change fixes the issue with the previous Baileys repository and improves the pairing process for Whatsapp.

Changes:
- Update package.json to use the new Baileys repository
- Modify Whatsapp Baileys service to generate a pairing code
- Fix issue with previous Baileys repository
- Improve pairing process for Whatsapp
Fix global RabbitMQ queue name in `channel.service.ts` and update CHANGELOG.md.
The queue name has been changed from `transformedWe` to `event`.
This fix prevents queue errors and ensures correct functionality of inter-service communication.
This commit updates the changelog to reflect the release of version 1.8.2. The date of the release has been updated in the header of the changelog. No functional changes were made in this release.

Modified: CHANGELOG.md
Explanation:
This commit updates the package and documentation versions to v1.8.2. The package.json and swagger.yaml files were modified accordingly. These changes are mainly for maintenance purposes and do not affect the functionality of the application.
* Corretion in globall rabbitmq queue name
* Improvement in the use of mongodb database for credentials
* Fixed base64 in webhook for documentWithCaption
* Fixed Generate pairing code
* Corretion in globall rabbitmq queue name
* Improvement in the use of mongodb database for credentials
* Fixed base64 in webhook for documentWithCaption
* Fixed Generate pairing code
* Corretion in globall rabbitmq queue name
* Improvement in the use of mongodb database for credentials
* Fixed base64 in webhook for documentWithCaption
* Fixed Generate pairing code
A new untracked file '.github/workflows/publish\_docker\_image\_latest.yml' was added. This workflow will handle the process of publishing the latest Docker image. This change allows for easier and more automated deployment of the Node.js project.
@sourcery-ai
Copy link
Contributor

sourcery-ai bot commented Oct 21, 2025

Reviewer's Guide

This PR refactors the WhatsApp connection flow by centralizing socket creation, enhancing configuration and message handling, overhauls multi-file auth state persistence to use both MongoDB and local file storage, normalizes AMQP queue naming, updates dependencies and imports to the new baileys package with version bumps, and adds conditional provider initialization and minor Chatwoot service improvements.

Sequence diagram for WhatsApp connection flow refactor

sequenceDiagram
  participant S as BaileysStartupService
  participant C as ConfigService
  participant P as Proxy
  participant W as WASocket
  S->>C: get session config
  S->>P: (if proxy enabled) setup proxy agent
  S->>S: define auth state
  S->>W: create socket with config
  W-->>S: socket instance
  S->>S: eventHandler()
  S-->>Caller: return WASocket
Loading

Sequence diagram for multi-file auth state persistence (MongoDB + local file)

sequenceDiagram
  participant U as useMultiFileAuthStateDb
  participant F as LocalFileSystem
  participant M as MongoDB
  U->>F: writeData(key != 'creds')
  U->>M: writeData(key == 'creds')
  U->>F: readData(key != 'creds')
  U->>M: readData(key == 'creds')
  U->>F: removeData(key != 'creds')
  U->>M: removeData(key == 'creds')
Loading

Class diagram for BaileysStartupService refactor and socket creation

classDiagram
  class BaileysStartupService {
    +createClient(number?: string, mobile?: boolean): Promise<WASocket>
    +connectToWhatsapp(number?: string, mobile?: boolean): Promise<WASocket>
    +reloadConnection(): Promise<WASocket>
    -defineAuthState()
    -loadWebhook()
    -loadChatwoot()
    -loadSettings()
    -loadWebsocket()
    -loadRabbitmq()
    -loadSqs()
    -loadTypebot()
    -loadProxy()
    -loadChamaai()
    +findGroup(id: GroupJid, reply: 'inner' | 'out' = 'out')
    +fetchAllGroups(getParticipants: GetParticipant)
    +profilePictureUrl
    +get profileStatus()
    +eventHandler()
    +client: WASocket
    +instance: Instance
    +logger: Logger
    +configService: ConfigService
    +localProxy
    +localSettings
    +msgRetryCounterCache
    +userDevicesCache
    +endSession
    +phoneNumber
    +mobile
  }
  BaileysStartupService --|> ChannelStartupService
  class ChannelStartupService {
    +connectToWhatsapp()
    +reloadConnection()
    +findGroup()
    +fetchAllGroups()
    +instanceName
  }
Loading

Class diagram for useMultiFileAuthStateDb persistence overhaul

classDiagram
  class useMultiFileAuthStateDb {
    +useMultiFileAuthStateDb(coll: string): Promise
    -writeData(data, key)
    -readData(key)
    -removeData(key)
    -fileExists(file)
    -fixFileName(file)
    -localFile(key)
    -localFolder
    -sessionId
    -collection
    -client
    -logger
  }
  useMultiFileAuthStateDb --> AuthenticationState
  class AuthenticationState {
    +creds
    +keys
  }
  AuthenticationState --> keys
  class keys {
    +get(type, ids)
    +set(data)
  }
Loading

Flow diagram for AMQP queue naming normalization

flowchart TD
  A["event"] -->|replace _ with . and toLowerCase| B["eventName"]
  B --> C["queueName = instanceName.eventName"]
  C --> D["amqp.assertQueue(queueName)"]
  C --> E["amqp.bindQueue(queueName, exchangeName, eventName)"]
Loading

File-Level Changes

Change Details Files
WhatsApp client initialization and configuration refactor
  • Extracted createClient method and unified connectToWhatsapp/reloadConnection
  • Updated socket config: timeouts, retries, keep-alive, fireInitQueries, maxMsgRetryCount
  • Added isJidNewsletter filter and support for documentWithCaption messages
  • Fixed fetchStatus to use status[0]?.status
src/api/services/channels/whatsapp.baileys.service.ts
Multi-file auth state persistence overhaul
  • Replaced single-file state with DB-backed + per-key JSON files
  • Implemented fixFileName, fileExists, and separate read/write/remove routines
  • Ensured creds initialization and proper saveCreds behavior
src/utils/use-multi-file-auth-state-db.ts
AMQP event queue naming normalization
  • Converted event names from underscores to dot notation for queueName and binding
src/api/services/channel.service.ts
Dependency, import updates and version bump
  • Switched imports from '@whiskeysockets/baileys' to 'baileys'
  • Bumped package.json, CHANGELOG, and swagger.yaml versions
  • Updated DTO and type files to use new imports
package.json
CHANGELOG.md
src/docs/swagger.yaml
src/api/dto/chat.dto.ts
src/api/dto/sendMessage.dto.ts
src/api/types/wa.types.ts
Conditional provider files initialization
  • Wrapped ProviderFiles instantiation behind configService.PROVIDER.ENABLED
src/main.ts
src/api/server.module.ts
Chatwoot service minor enhancements
  • Formatted mergeBrazilianContacts if-statement
  • Added fallback for inbox name matching by stripping '-cwId-' suffix
src/api/integrations/chatwoot/services/chatwoot.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

@guedesrv guedesrv closed this Oct 21, 2025
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 and found some issues that need to be addressed.

Blocking issues:

  • An action sourced from a third-party repository on GitHub is not pinned to a full length commit SHA. Pinning an action to a full length commit SHA is currently the only way to use an action as an immutable release. Pinning to a particular SHA helps mitigate the risk of a bad actor adding a backdoor to the action's repository, as they would need to generate a SHA-1 collision for a valid Git object payload. (link)
  • An action sourced from a third-party repository on GitHub is not pinned to a full length commit SHA. Pinning an action to a full length commit SHA is currently the only way to use an action as an immutable release. Pinning to a particular SHA helps mitigate the risk of a bad actor adding a backdoor to the action's repository, as they would need to generate a SHA-1 collision for a valid Git object payload. (link)
  • An action sourced from a third-party repository on GitHub is not pinned to a full length commit SHA. Pinning an action to a full length commit SHA is currently the only way to use an action as an immutable release. Pinning to a particular SHA helps mitigate the risk of a bad actor adding a backdoor to the action's repository, as they would need to generate a SHA-1 collision for a valid Git object payload. (link)
  • An action sourced from a third-party repository on GitHub is not pinned to a full length commit SHA. Pinning an action to a full length commit SHA is currently the only way to use an action as an immutable release. Pinning to a particular SHA helps mitigate the risk of a bad actor adding a backdoor to the action's repository, as they would need to generate a SHA-1 collision for a valid Git object payload. (link)
  • An action sourced from a third-party repository on GitHub is not pinned to a full length commit SHA. Pinning an action to a full length commit SHA is currently the only way to use an action as an immutable release. Pinning to a particular SHA helps mitigate the risk of a bad actor adding a backdoor to the action's repository, as they would need to generate a SHA-1 collision for a valid Git object payload. (link)
  • Detected that function argument file has entered the fs module. An attacker could potentially control the location of this file, to include going backwards in the directory with '../'. To address this, ensure that user-controlled variables in file paths are validated. (link)
  • Detected possible user input going into a path.join or path.resolve function. This could possibly lead to a path traversal vulnerability, where the attacker can access arbitrary files stored in the file system. Instead, be sure to sanitize or validate user input first. (link)
  • Detected possible user input going into a path.join or path.resolve function. This could possibly lead to a path traversal vulnerability, where the attacker can access arbitrary files stored in the file system. Instead, be sure to sanitize or validate user input first. (link)
  • Detected possible user input going into a path.join or path.resolve function. This could possibly lead to a path traversal vulnerability, where the attacker can access arbitrary files stored in the file system. Instead, be sure to sanitize or validate user input first. (link)
  • Detected that function argument coll has entered the fs module. An attacker could potentially control the location of this file, to include going backwards in the directory with '../'. To address this, ensure that user-controlled variables in file paths are validated. (link)
  • Detected that function argument key has entered the fs module. An attacker could potentially control the location of this file, to include going backwards in the directory with '../'. To address this, ensure that user-controlled variables in file paths are validated. (link)
  • Detected that function argument key has entered the fs module. An attacker could potentially control the location of this file, to include going backwards in the directory with '../'. To address this, ensure that user-controlled variables in file paths are validated. (link)
  • Detected that function argument key has entered the fs module. An attacker could potentially control the location of this file, to include going backwards in the directory with '../'. To address this, ensure that user-controlled variables in file paths are validated. (link)
Prompt for AI Agents
Please address the comments from this code review:

## Individual Comments

### Comment 1
<location> `src/config/env.config.ts:369-371` </location>
<code_context>
         GLOBAL_EVENTS: process.env?.WEBSOCKET_GLOBAL_EVENTS === 'true',
       },
       WA_BUSINESS: {
-        TOKEN_WEBHOOK: process.env.WA_BUSINESS_TOKEN_WEBHOOK || '',
-        URL: process.env.WA_BUSINESS_URL || '',
-        VERSION: process.env.WA_BUSINESS_VERSION || '',
+        TOKEN_WEBHOOK: process.env.WA_BUSINESS_TOKEN_WEBHOOK || 'evolution',
+        URL: process.env.WA_BUSINESS_URL || 'https://graph.facebook.com',
+        VERSION: process.env.WA_BUSINESS_VERSION || 'v19.0',
</code_context>

<issue_to_address>
**🚨 suggestion (security):** Default WA_BUSINESS config values may expose sensitive endpoints.

Defaulting to hardcoded values for these configuration options can lead to accidental exposure in production. It's safer to enforce explicit configuration and avoid fallback defaults for sensitive settings.

```suggestion
        TOKEN_WEBHOOK: process.env.WA_BUSINESS_TOKEN_WEBHOOK,
        URL: process.env.WA_BUSINESS_URL,
        VERSION: process.env.WA_BUSINESS_VERSION,
```
</issue_to_address>

### Comment 2
<location> `CHANGELOG.md:5` </location>
<code_context>
+
+### Fixed
+
+* Corretion in globall rabbitmq queue name
+* Improvement in the use of mongodb database for credentials
+* Fixed base64 in webhook for documentWithCaption
</code_context>

<issue_to_address>
**issue (typo):** Correct typos: 'Corretion' should be 'Correction' and 'globall' should be 'global'.

Update the line to 'Correction in global rabbitmq queue name' to address the typos.

```suggestion
* Correction in global rabbitmq queue name
```
</issue_to_address>

### Comment 3
<location> `.github/workflows/publish_docker_image_latest.yml:21` </location>
<code_context>
        uses: docker/metadata-action@v5
</code_context>

<issue_to_address>
**security (yaml.github-actions.security.third-party-action-not-pinned-to-commit-sha):** An action sourced from a third-party repository on GitHub is not pinned to a full length commit SHA. Pinning an action to a full length commit SHA is currently the only way to use an action as an immutable release. Pinning to a particular SHA helps mitigate the risk of a bad actor adding a backdoor to the action's repository, as they would need to generate a SHA-1 collision for a valid Git object payload.

*Source: opengrep*
</issue_to_address>

### Comment 4
<location> `.github/workflows/publish_docker_image_latest.yml:27` </location>
<code_context>
        uses: docker/setup-qemu-action@v3
</code_context>

<issue_to_address>
**security (yaml.github-actions.security.third-party-action-not-pinned-to-commit-sha):** An action sourced from a third-party repository on GitHub is not pinned to a full length commit SHA. Pinning an action to a full length commit SHA is currently the only way to use an action as an immutable release. Pinning to a particular SHA helps mitigate the risk of a bad actor adding a backdoor to the action's repository, as they would need to generate a SHA-1 collision for a valid Git object payload.

*Source: opengrep*
</issue_to_address>

### Comment 5
<location> `.github/workflows/publish_docker_image_latest.yml:30` </location>
<code_context>
        uses: docker/setup-buildx-action@v3
</code_context>

<issue_to_address>
**security (yaml.github-actions.security.third-party-action-not-pinned-to-commit-sha):** An action sourced from a third-party repository on GitHub is not pinned to a full length commit SHA. Pinning an action to a full length commit SHA is currently the only way to use an action as an immutable release. Pinning to a particular SHA helps mitigate the risk of a bad actor adding a backdoor to the action's repository, as they would need to generate a SHA-1 collision for a valid Git object payload.

*Source: opengrep*
</issue_to_address>

### Comment 6
<location> `.github/workflows/publish_docker_image_latest.yml:33` </location>
<code_context>
        uses: docker/login-action@v3
</code_context>

<issue_to_address>
**security (yaml.github-actions.security.third-party-action-not-pinned-to-commit-sha):** An action sourced from a third-party repository on GitHub is not pinned to a full length commit SHA. Pinning an action to a full length commit SHA is currently the only way to use an action as an immutable release. Pinning to a particular SHA helps mitigate the risk of a bad actor adding a backdoor to the action's repository, as they would need to generate a SHA-1 collision for a valid Git object payload.

*Source: opengrep*
</issue_to_address>

### Comment 7
<location> `.github/workflows/publish_docker_image_latest.yml:40` </location>
<code_context>
        uses: docker/build-push-action@v5
</code_context>

<issue_to_address>
**security (yaml.github-actions.security.third-party-action-not-pinned-to-commit-sha):** An action sourced from a third-party repository on GitHub is not pinned to a full length commit SHA. Pinning an action to a full length commit SHA is currently the only way to use an action as an immutable release. Pinning to a particular SHA helps mitigate the risk of a bad actor adding a backdoor to the action's repository, as they would need to generate a SHA-1 collision for a valid Git object payload.

*Source: opengrep*
</issue_to_address>

### Comment 8
<location> `src/utils/use-multi-file-auth-state-db.ts:21` </location>
<code_context>
    const stat = await fs.stat(file);
</code_context>

<issue_to_address>
**security (javascript.lang.security.audit.detect-non-literal-fs-filename):** Detected that function argument `file` has entered the fs module. An attacker could potentially control the location of this file, to include going backwards in the directory with '../'. To address this, ensure that user-controlled variables in file paths are validated.

*Source: opengrep*
</issue_to_address>

### Comment 9
<location> `src/utils/use-multi-file-auth-state-db.ts:41` </location>
<code_context>
  const localFolder = path.join(INSTANCE_DIR, sessionId);
</code_context>

<issue_to_address>
**security (javascript.lang.security.audit.path-traversal.path-join-resolve-traversal):** Detected possible user input going into a `path.join` or `path.resolve` function. This could possibly lead to a path traversal vulnerability,  where the attacker can access arbitrary files stored in the file system. Instead, be sure to sanitize or validate user input first.

*Source: opengrep*
</issue_to_address>

### Comment 10
<location> `src/utils/use-multi-file-auth-state-db.ts:42` </location>
<code_context>
  const localFile = (key: string) => path.join(localFolder, fixFileName(key) + '.json');
</code_context>

<issue_to_address>
**security (javascript.lang.security.audit.path-traversal.path-join-resolve-traversal):** Detected possible user input going into a `path.join` or `path.resolve` function. This could possibly lead to a path traversal vulnerability,  where the attacker can access arbitrary files stored in the file system. Instead, be sure to sanitize or validate user input first.

*Source: opengrep*
</issue_to_address>

### Comment 11
<location> `src/utils/use-multi-file-auth-state-db.ts:42` </location>
<code_context>
  const localFile = (key: string) => path.join(localFolder, fixFileName(key) + '.json');
</code_context>

<issue_to_address>
**security (javascript.lang.security.audit.path-traversal.path-join-resolve-traversal):** Detected possible user input going into a `path.join` or `path.resolve` function. This could possibly lead to a path traversal vulnerability,  where the attacker can access arbitrary files stored in the file system. Instead, be sure to sanitize or validate user input first.

*Source: opengrep*
</issue_to_address>

### Comment 12
<location> `src/utils/use-multi-file-auth-state-db.ts:43` </location>
<code_context>
  await fs.mkdir(localFolder, { recursive: true });
</code_context>

<issue_to_address>
**security (javascript.lang.security.audit.detect-non-literal-fs-filename):** Detected that function argument `coll` has entered the fs module. An attacker could potentially control the location of this file, to include going backwards in the directory with '../'. To address this, ensure that user-controlled variables in file paths are validated.

*Source: opengrep*
</issue_to_address>

### Comment 13
<location> `src/utils/use-multi-file-auth-state-db.ts:50` </location>
<code_context>
        await fs.writeFile(localFile(key), dataString);
</code_context>

<issue_to_address>
**security (javascript.lang.security.audit.detect-non-literal-fs-filename):** Detected that function argument `key` has entered the fs module. An attacker could potentially control the location of this file, to include going backwards in the directory with '../'. To address this, ensure that user-controlled variables in file paths are validated.

*Source: opengrep*
</issue_to_address>

### Comment 14
<location> `src/utils/use-multi-file-auth-state-db.ts:74` </location>
<code_context>
        const rawData = await fs.readFile(localFile(key), { encoding: 'utf-8' });
</code_context>

<issue_to_address>
**security (javascript.lang.security.audit.detect-non-literal-fs-filename):** Detected that function argument `key` has entered the fs module. An attacker could potentially control the location of this file, to include going backwards in the directory with '../'. To address this, ensure that user-controlled variables in file paths are validated.

*Source: opengrep*
</issue_to_address>

### Comment 15
<location> `src/utils/use-multi-file-auth-state-db.ts:96` </location>
<code_context>
        await fs.unlink(localFile(key));
</code_context>

<issue_to_address>
**security (javascript.lang.security.audit.detect-non-literal-fs-filename):** Detected that function argument `key` has entered the fs module. An attacker could potentially control the location of this file, to include going backwards in the directory with '../'. To address this, ensure that user-controlled variables in file paths are validated.

*Source: opengrep*
</issue_to_address>

### Comment 16
<location> `src/utils/use-multi-file-auth-state-db.ts:15-16` </location>
<code_context>
  const replacedColon = replacedSlash.replace(/:/g, '-');
  return replacedColon;

</code_context>

<issue_to_address>
**suggestion (code-quality):** Inline variable that is immediately returned ([`inline-immediately-returned-variable`](https://docs.sourcery.ai/Reference/Rules-and-In-Line-Suggestions/TypeScript/Default-Rules/inline-immediately-returned-variable))

```suggestion
  return replacedSlash.replace(/:/g, '-');

```

<br/><details><summary>Explanation</summary>Something that we often see in people's code is assigning to a result variable
and then immediately returning it.

Returning the result directly shortens the code and removes an unnecessary
variable, reducing the mental load of reading the function.

Where intermediate variables can be useful is if they then get used as a
parameter or a condition, and the name can act like a comment on what the
variable represents. In the case where you're returning it from a function, the
function name is there to tell you what the result is, so the variable name
is unnecessary.
</details>
</issue_to_address>

### Comment 17
<location> `src/utils/use-multi-file-auth-state-db.ts:70-91` </location>
<code_context>

</code_context>

<issue_to_address>
**issue (code-quality):** Avoid function declarations, favouring function assignment expressions, inside blocks. ([`avoid-function-declarations-in-blocks`](https://docs.sourcery.ai/Reference/Rules-and-In-Line-Suggestions/TypeScript/Default-Rules/avoid-function-declarations-in-blocks))

<details><summary>Explanation</summary>Function declarations may be hoisted in Javascript, but the behaviour is inconsistent between browsers.
Hoisting is generally confusing and should be avoided. Rather than using function declarations inside blocks, you
should use function expressions, which create functions in-scope.
</details>
</issue_to_address>

### Comment 18
<location> `src/utils/use-multi-file-auth-state-db.ts:76-77` </location>
<code_context>
        const parsedData = JSON.parse(rawData, BufferJSON.reviver);
        return parsedData;

</code_context>

<issue_to_address>
**suggestion (code-quality):** Inline variable that is immediately returned ([`inline-immediately-returned-variable`](https://docs.sourcery.ai/Reference/Rules-and-In-Line-Suggestions/TypeScript/Default-Rules/inline-immediately-returned-variable))

```suggestion
        return JSON.parse(rawData, BufferJSON.reviver);

```

<br/><details><summary>Explanation</summary>Something that we often see in people's code is assigning to a result variable
and then immediately returning it.

Returning the result directly shortens the code and removes an unnecessary
variable, reducing the mental load of reading the function.

Where intermediate variables can be useful is if they then get used as a
parameter or a condition, and the name can act like a comment on what the
variable represents. In the case where you're returning it from a function, the
function name is there to tell you what the result is, so the variable name
is unnecessary.
</details>
</issue_to_address>

### Comment 19
<location> `src/utils/use-multi-file-auth-state-db.ts:93-105` </location>
<code_context>

</code_context>

<issue_to_address>
**issue (code-quality):** Avoid function declarations, favouring function assignment expressions, inside blocks. ([`avoid-function-declarations-in-blocks`](https://docs.sourcery.ai/Reference/Rules-and-In-Line-Suggestions/TypeScript/Default-Rules/avoid-function-declarations-in-blocks))

<details><summary>Explanation</summary>Function declarations may be hoisted in Javascript, but the behaviour is inconsistent between browsers.
Hoisting is generally confusing and should be avoided. Rather than using function declarations inside blocks, you
should use function expressions, which create functions in-scope.
</details>
</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.

Comment on lines -369 to -371
TOKEN_WEBHOOK: process.env.WA_BUSINESS_TOKEN_WEBHOOK || '',
URL: process.env.WA_BUSINESS_URL || '',
VERSION: process.env.WA_BUSINESS_VERSION || '',
Copy link
Contributor

Choose a reason for hiding this comment

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

🚨 suggestion (security): Default WA_BUSINESS config values may expose sensitive endpoints.

Defaulting to hardcoded values for these configuration options can lead to accidental exposure in production. It's safer to enforce explicit configuration and avoid fallback defaults for sensitive settings.

Suggested change
TOKEN_WEBHOOK: process.env.WA_BUSINESS_TOKEN_WEBHOOK || '',
URL: process.env.WA_BUSINESS_URL || '',
VERSION: process.env.WA_BUSINESS_VERSION || '',
TOKEN_WEBHOOK: process.env.WA_BUSINESS_TOKEN_WEBHOOK,
URL: process.env.WA_BUSINESS_URL,
VERSION: process.env.WA_BUSINESS_VERSION,


### Fixed

* Corretion in globall rabbitmq queue name
Copy link
Contributor

Choose a reason for hiding this comment

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

issue (typo): Correct typos: 'Corretion' should be 'Correction' and 'globall' should be 'global'.

Update the line to 'Correction in global rabbitmq queue name' to address the typos.

Suggested change
* Corretion in globall rabbitmq queue name
* Correction in global rabbitmq queue name


- name: Docker meta
id: meta
uses: docker/metadata-action@v5
Copy link
Contributor

Choose a reason for hiding this comment

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

security (yaml.github-actions.security.third-party-action-not-pinned-to-commit-sha): An action sourced from a third-party repository on GitHub is not pinned to a full length commit SHA. Pinning an action to a full length commit SHA is currently the only way to use an action as an immutable release. Pinning to a particular SHA helps mitigate the risk of a bad actor adding a backdoor to the action's repository, as they would need to generate a SHA-1 collision for a valid Git object payload.

Source: opengrep

tags: latest

- name: Set up QEMU
uses: docker/setup-qemu-action@v3
Copy link
Contributor

Choose a reason for hiding this comment

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

security (yaml.github-actions.security.third-party-action-not-pinned-to-commit-sha): An action sourced from a third-party repository on GitHub is not pinned to a full length commit SHA. Pinning an action to a full length commit SHA is currently the only way to use an action as an immutable release. Pinning to a particular SHA helps mitigate the risk of a bad actor adding a backdoor to the action's repository, as they would need to generate a SHA-1 collision for a valid Git object payload.

Source: opengrep

uses: docker/setup-qemu-action@v3

- name: Set up Docker Buildx
uses: docker/setup-buildx-action@v3
Copy link
Contributor

Choose a reason for hiding this comment

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

security (yaml.github-actions.security.third-party-action-not-pinned-to-commit-sha): An action sourced from a third-party repository on GitHub is not pinned to a full length commit SHA. Pinning an action to a full length commit SHA is currently the only way to use an action as an immutable release. Pinning to a particular SHA helps mitigate the risk of a bad actor adding a backdoor to the action's repository, as they would need to generate a SHA-1 collision for a valid Git object payload.

Source: opengrep


- name: Build and push
id: docker_build
uses: docker/build-push-action@v5
Copy link
Contributor

Choose a reason for hiding this comment

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

security (yaml.github-actions.security.third-party-action-not-pinned-to-commit-sha): An action sourced from a third-party repository on GitHub is not pinned to a full length commit SHA. Pinning an action to a full length commit SHA is currently the only way to use an action as an immutable release. Pinning to a particular SHA helps mitigate the risk of a bad actor adding a backdoor to the action's repository, as they would need to generate a SHA-1 collision for a valid Git object payload.

Source: opengrep

Comment on lines +15 to +16
const replacedColon = replacedSlash.replace(/:/g, '-');
return replacedColon;
Copy link
Contributor

Choose a reason for hiding this comment

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

suggestion (code-quality): Inline variable that is immediately returned (inline-immediately-returned-variable)

Suggested change
const replacedColon = replacedSlash.replace(/:/g, '-');
return replacedColon;
return replacedSlash.replace(/:/g, '-');


ExplanationSomething that we often see in people's code is assigning to a result variable
and then immediately returning it.

Returning the result directly shortens the code and removes an unnecessary
variable, reducing the mental load of reading the function.

Where intermediate variables can be useful is if they then get used as a
parameter or a condition, and the name can act like a comment on what the
variable represents. In the case where you're returning it from a function, the
function name is there to tell you what the result is, so the variable name
is unnecessary.

Comment on lines +70 to +91
async function readData(key: string): Promise<any> {
try {
await client.connect();
let data = (await collection.findOne({ _id: key })) as any;
if (data?.content_array) {
data = data.content_array;
if (key != 'creds') {
if (!(await fileExists(localFile(key)))) return null;
const rawData = await fs.readFile(localFile(key), { encoding: 'utf-8' });

const parsedData = JSON.parse(rawData, BufferJSON.reviver);
return parsedData;
} else {
await client.connect();
let data = (await collection.findOne({ _id: key })) as any;
if (data?.content_array) {
data = data.content_array;
}
const creds = JSON.stringify(data);
return JSON.parse(creds, BufferJSON.reviver);
}
const creds = JSON.stringify(data);
return JSON.parse(creds, BufferJSON.reviver);
} catch (error) {
logger.error(error);
return null;
}
};
}
Copy link
Contributor

Choose a reason for hiding this comment

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

issue (code-quality): Avoid function declarations, favouring function assignment expressions, inside blocks. (avoid-function-declarations-in-blocks)

ExplanationFunction declarations may be hoisted in Javascript, but the behaviour is inconsistent between browsers. Hoisting is generally confusing and should be avoided. Rather than using function declarations inside blocks, you should use function expressions, which create functions in-scope.

Comment on lines +76 to +77
const parsedData = JSON.parse(rawData, BufferJSON.reviver);
return parsedData;
Copy link
Contributor

Choose a reason for hiding this comment

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

suggestion (code-quality): Inline variable that is immediately returned (inline-immediately-returned-variable)

Suggested change
const parsedData = JSON.parse(rawData, BufferJSON.reviver);
return parsedData;
return JSON.parse(rawData, BufferJSON.reviver);


ExplanationSomething that we often see in people's code is assigning to a result variable
and then immediately returning it.

Returning the result directly shortens the code and removes an unnecessary
variable, reducing the mental load of reading the function.

Where intermediate variables can be useful is if they then get used as a
parameter or a condition, and the name can act like a comment on what the
variable represents. In the case where you're returning it from a function, the
function name is there to tell you what the result is, so the variable name
is unnecessary.

Comment on lines +93 to +105
async function removeData(key: string): Promise<any> {
try {
await client.connect();
return await collection.deleteOne({ _id: key });
if (key != 'creds') {
await fs.unlink(localFile(key));
} else {
await client.connect();
return await collection.deleteOne({ _id: key });
}
} catch (error) {
logger.error(error);
return;
}
};
}
Copy link
Contributor

Choose a reason for hiding this comment

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

issue (code-quality): Avoid function declarations, favouring function assignment expressions, inside blocks. (avoid-function-declarations-in-blocks)

ExplanationFunction declarations may be hoisted in Javascript, but the behaviour is inconsistent between browsers. Hoisting is generally confusing and should be avoided. Rather than using function declarations inside blocks, you should use function expressions, which create functions in-scope.

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