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

feat(chat): add whatsapp number check guardrails

Open nikolasdehor opened this issue 5 months ago • 3 comments

Summary

Adds abuse-safety guardrails for the POST /chat/whatsappNumbers/{instance} endpoint.

This endpoint can call Baileys onWhatsApp for uncached numbers. When callers submit large batches, the instance can generate a burst of WhatsApp Web checks. This PR adds bounded, configurable backpressure for that path and documents responsible messaging expectations.

What Changed

  • Adds configurable whatsappNumbers guardrails:
    • ABUSE_SAFETY_WHATSAPP_NUMBERS_MAX_BATCH_SIZE
    • ABUSE_SAFETY_WHATSAPP_NUMBERS_QUERY_BATCH_SIZE
    • ABUSE_SAFETY_WHATSAPP_NUMBERS_QUERY_BATCH_INTERVAL_MS
  • Returns 429 Too Many Requests plus Retry-After when a request exceeds the configured max batch size.
  • Chunks direct Baileys onWhatsApp checks for uncached numbers instead of sending all checks in a single call.
  • Requires numbers in the request schema to avoid accidental malformed calls.
  • Adds docs/responsible-messaging.md and links it from the README.

References

  • Refs #2228: account risk when checking many numbers through /chat/whatsappNumbers.
  • Related community context: #1870, #2538, #1854, #2404.
  • Policy context:
    • https://whatsappbusiness.com/policy/
    • https://www.whatsapp.com/legal/business-terms

Scope Notes

This is not an anti-ban feature and does not guarantee delivery or account safety.

Intentionally out of scope:

  • proxy or IP rotation
  • fingerprint randomization
  • automatic warmup
  • human-like behavior simulation
  • high-volume campaign tooling
  • promises to bypass platform enforcement

The goal is narrower: prevent accidental bursts on a sensitive endpoint, provide clear 429 feedback, and document responsible operation.

Validation

  • DATABASE_PROVIDER=postgresql npm run db:generate
  • npm run lint:check
  • npm run build

Summary by Sourcery

Add configurable abuse-safety guardrails for the /chat/whatsappNumbers endpoint, including batch limiting, chunked Baileys checks, and clearer error handling and documentation around responsible messaging.

New Features:

  • Introduce configurable ABUSE_SAFETY_WHATSAPP_NUMBERS limits for batch size, query batch size, and inter-batch delay on WhatsApp number checks.
  • Add a 429 Too Many Requests exception type and propagate HTTP 429 with Retry-After for oversized whatsappNumbers batches.

Enhancements:

  • Validate that whatsappNumbers requests include a numbers field and treat missing numbers as a bad request.
  • Chunk uncached Baileys onWhatsApp lookups to apply backpressure instead of issuing a single large check burst.
  • Extend chat routing error handling to set Retry-After headers and return the appropriate HTTP status from thrown exceptions.

Documentation:

  • Document responsible messaging guardrails and deliverability considerations in docs/responsible-messaging.md and reference them from the README.

nikolasdehor avatar Jun 12 '26 04:06 nikolasdehor

Reviewer's Guide

Implements abuse-safety guardrails for the /chat/whatsappNumbers endpoint by enforcing configurable batch limits, chunking Baileys onWhatsApp checks with pacing, tightening request validation, propagating 429 responses with Retry-After, and documenting responsible messaging expectations.

Sequence diagram for whatsappNumbers guardrails and Baileys chunked checks

sequenceDiagram
  actor Client
  participant ChatRouter
  participant BaileysStartupService
  participant ConfigService
  participant BaileysClient

  Client->>ChatRouter: POST /chat/whatsappNumbers
  ChatRouter->>BaileysStartupService: whatsappNumber(WhatsAppNumberDto)
  BaileysStartupService->>BaileysStartupService: getWhatsappNumbersGuardrails()
  BaileysStartupService->>ConfigService: get ABUSE_SAFETY
  ConfigService-->>BaileysStartupService: AbuseSafety
  BaileysStartupService->>BaileysStartupService: validate numbers required

  alt [numbers.length > guardrails.maxBatchSize]
    BaileysStartupService->>BaileysStartupService: TooManyRequestsException(retryAfter, details)
    BaileysStartupService-->>ChatRouter: error { status 429, retryAfter }
    ChatRouter->>ChatRouter: set Retry-After header
    ChatRouter-->>Client: 429 Too Many Requests
  else [numbers.length <= guardrails.maxBatchSize]
    BaileysStartupService->>BaileysStartupService: compute normalNumbersNotInCache
    opt [normalNumbersNotInCache.length > 0]
      BaileysStartupService->>BaileysStartupService: queryOnWhatsappInChunks(numbers, batchSize, intervalMs)
      loop for each chunk
        BaileysStartupService->>BaileysClient: onWhatsApp(...chunk)
        BaileysClient-->>BaileysStartupService: results
        alt [hasMoreChunks && intervalMs > 0]
          BaileysStartupService->>BaileysStartupService: delay(intervalMs)
        end
      end
    end
    BaileysStartupService-->>ChatRouter: whatsappNumber response
    ChatRouter-->>Client: 200 OK
  end

File-Level Changes

Change Details Files
Add configurable abuse-safety guardrails for whatsappNumbers batch size and query pacing, and apply them in Baileys whatsappNumber handling.
  • Introduce AbuseSafety config type and ABUSE_SAFETY_WHATSAPP_NUMBERS settings (max batch size, query batch size, and inter-batch delay) in env.config, with helpers to parse positive and non-negative integers from env vars and wire them into ConfigService
  • Add getWhatsappNumbersGuardrails helper in BaileysStartupService to read and normalize guardrail values from configuration
  • Update whatsappNumber handler to normalize and validate the numbers array, enforce a non-empty set of numbers, and reject oversized batches using a TooManyRequestsException with structured error payload and documentation references
  • Refactor uncached Baileys onWhatsApp lookups to use a new queryOnWhatsappInChunks helper that logs progress, issues checks in fixed-size chunks, and introduces a delay between batches based on guardrail config
src/config/env.config.ts
src/api/integrations/channel/whatsapp/whatsapp.baileys.service.ts
Expose a reusable 429 Too Many Requests exception and propagate status and Retry-After headers from chat routes.
  • Define a TooManyRequestsException class that throws a standardized 429 error object including status, message, and optional retryAfter metadata
  • Extend HttpStatus enum to include TOO_MANY_REQUESTS = 429 and export the new exception from the exceptions barrel file
  • Update chat router error handling to detect errors with retryAfter, set the Retry-After response header, and return the error with its own status code when present instead of always 400
src/exceptions/429.exception.ts
src/api/routes/index.router.ts
src/exceptions/index.ts
src/api/routes/chat.router.ts
Tighten whatsappNumbers request validation and document responsible messaging behavior and guardrails.
  • Require the numbers field in whatsappNumberSchema so requests must include at least a numbers key
  • Add Responsible messaging section to README pointing to a new responsible-messaging guide
  • Create docs/responsible-messaging.md describing whatsappNumbers guardrail behavior, configuration, limitations, and relevant community and policy references
  • Add abuse-safety environment variable examples to env example files so operators can configure the new guardrails
src/validate/chat.schema.ts
README.md
docs/responsible-messaging.md
.env.example
env.example

Possibly linked issues

  • #2228: PR implements batching, max batch size, delays, 429 errors, and docs to mitigate whatsappNumbers bulk-check ban risk.

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 Jun 12 '26 04:06 sourcery-ai[bot]

Addressed the Sourcery review in 7af44d9:

  • TooManyRequestsException now extends Error and keeps structured fields for route serialization.
  • whatsappNumbers now returns a normalized error payload instead of serializing the whole thrown object.
  • Retry-After is emitted when retryAfter != null, so 0 remains valid if used later.
  • Non-array numbers input now gets an explicit 400 validation error instead of being silently treated as empty.

Validated locally:

  • npm run lint:check
  • npm run build

@sourcery-ai review

nikolasdehor avatar Jun 12 '26 04:06 nikolasdehor

Added a scoped test/observability follow-up in e8b6531:

  • Extracted whatsappNumbers guardrail logic into a small pure helper for easier review and testing.
  • Added aggregate operational logs for accepted/rejected checks: requested count, cache hits/misses, Baileys query count, cache writes, configured limits, elapsed time, and rejection reason.
  • Kept logs free of raw phone numbers/contact identifiers.
  • Added node:test coverage for defaults, invalid config normalization, missing/non-array/empty payloads, oversized 429 metadata, and safe aggregate observation payloads.
  • Added npm run test:run and included test/**/*.ts in tsconfig so tests are typechecked by build.

Validated locally:

  • npm run test:run
  • npm run lint:check
  • npx eslint --ext .ts src test
  • npm run build
  • DATABASE_PROVIDER=postgresql npm run db:generate

Sidecar read-only code review also found no blocking issues.

@sourcery-ai review

nikolasdehor avatar Jun 12 '26 05:06 nikolasdehor

🔴 👎

A ideia dos guardrails é válida, mas o PR está desatualizado (em conflito com a develop) e mexe em arquivos estruturais demais pro escopo — package.json, tsconfig.json, env.config e o whatsapp.baileys.service. Rebaseia na develop e isola só o guardrail (sem mexer em config/build) que a gente reavalia.

@dpaes

NeritonDias avatar Jun 26 '26 02:06 NeritonDias