feat(chat): add whatsapp number check guardrails
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
whatsappNumbersguardrails:ABUSE_SAFETY_WHATSAPP_NUMBERS_MAX_BATCH_SIZEABUSE_SAFETY_WHATSAPP_NUMBERS_QUERY_BATCH_SIZEABUSE_SAFETY_WHATSAPP_NUMBERS_QUERY_BATCH_INTERVAL_MS
- Returns
429 Too Many RequestsplusRetry-Afterwhen a request exceeds the configured max batch size. - Chunks direct Baileys
onWhatsAppchecks for uncached numbers instead of sending all checks in a single call. - Requires
numbersin the request schema to avoid accidental malformed calls. - Adds
docs/responsible-messaging.mdand 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:generatenpm run lint:checknpm 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.
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. |
|
src/config/env.config.tssrc/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. |
|
src/exceptions/429.exception.tssrc/api/routes/index.router.tssrc/exceptions/index.tssrc/api/routes/chat.router.ts |
| Tighten whatsappNumbers request validation and document responsible messaging behavior and guardrails. |
|
src/validate/chat.schema.tsREADME.mddocs/responsible-messaging.md.env.exampleenv.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 reviewon 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 issueto create an issue from it. - Generate a pull request title: Write
@sourcery-aianywhere in the pull request title to generate a title at any time. You can also comment@sourcery-ai titleon the pull request to (re-)generate the title at any time. - Generate a pull request summary: Write
@sourcery-ai summaryanywhere in the pull request body to generate a PR summary at any time exactly where you want it. You can also comment@sourcery-ai summaryon the pull request to (re-)generate the summary at any time. - Generate reviewer's guide: Comment
@sourcery-ai guideon the pull request to (re-)generate the reviewer's guide at any time. - Resolve all Sourcery comments: Comment
@sourcery-ai resolveon 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 dismisson 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 reviewto 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.
Addressed the Sourcery review in 7af44d9:
TooManyRequestsExceptionnow extendsErrorand keeps structured fields for route serialization.whatsappNumbersnow returns a normalized error payload instead of serializing the whole thrown object.Retry-Afteris emitted whenretryAfter != null, so0remains valid if used later.- Non-array
numbersinput now gets an explicit 400 validation error instead of being silently treated as empty.
Validated locally:
npm run lint:checknpm run build
@sourcery-ai review
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
🔴 👎
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