t1385.3: WhatsApp bot subagent doc (Baileys)#2761
Conversation
WalkthroughAdds a new comprehensive documentation file describing a Baileys-based WhatsApp bot implementation (TypeScript/Node.js), covering architecture, authentication (QR/pairing), session and multi-device management, messaging features, group management, privacy/security considerations, runner-dispatch integration, and Matterbridge bridging options. Changes
Estimated code review effort🎯 3 (Moderate) | ⏱️ ~25 minutes Suggested labels
Poem
🚥 Pre-merge checks | ✅ 5✅ Passed checks (5 passed)
✏️ Tip: You can configure your own custom pre-merge checks in the settings. ✨ Finishing Touches🧪 Generate unit tests (beta)
Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out. Comment |
🔍 Code Quality Report�[0;35m[MONITOR]�[0m Code Review Monitoring Report �[0;34m[INFO]�[0m Latest Quality Status: �[0;34m[INFO]�[0m Recent monitoring activity: 📈 Current Quality Metrics
Generated on: Tue Mar 3 04:43:50 UTC 2026 Generated by AI DevOps Framework Code Review Monitoring |
Summary of ChangesHello, I'm Gemini Code Assist1! I'm currently reviewing this pull request and will post my feedback shortly. In the meantime, here's a summary to help you and other reviewers quickly get up to speed! This pull request adds a new subagent documentation file for WhatsApp bot integration using the Baileys library. It provides detailed instructions on setting up and using Baileys, along with a comprehensive overview of its features, security considerations, and integration possibilities with other tools. Highlights
Changelog
Activity
Using Gemini Code AssistThe full guide for Gemini Code Assist can be found on our documentation page, here are some quick tips. Invoking Gemini You can request assistance from Gemini at any point by creating a comment using either
Customization To customize Gemini Code Assist for GitHub experience, repository maintainers can create a configuration file and/or provide a custom code review style guide (such as PEP-8 for Python) by creating and adding files to a Limitations & Feedback Gemini Code Assist may make mistakes. Please leave feedback on any instances where its feedback is incorrect or counter productive. You can react with 👍 and 👎 on @gemini-code-assist comments. If you're interested in giving your feedback about your experience with Gemini Code Assist for Github and other Google products, sign up here. You can also get AI-powered code generation, chat, as well as code reviews directly in the IDE at no cost with the Gemini Code Assist IDE Extension. Footnotes
|
There was a problem hiding this comment.
Code Review
This pull request adds a comprehensive documentation file for WhatsApp bot integration using the Baileys library. The document is well-structured and covers a wide range of topics from setup to advanced features and security considerations. My review focuses on improving the correctness, robustness, and security of the code examples provided within the documentation to ensure users who copy them have a safe and stable starting point. I've identified a few areas for improvement, including a potential security vulnerability in input sanitization (with a reference to repository guidelines on safe command construction), risky recursive function calls for reconnection logic, and best practices for dependency management.
Note: Security Review has been skipped due to the limited scope of the PR.
| ): Promise<string> { | ||
| try { | ||
| // Sanitize input — treat all inbound messages as untrusted | ||
| const sanitized = prompt.replace(/[`$\\]/g, "") |
There was a problem hiding this comment.
The input sanitization is insufficient and poses a security risk. It only removes backticks, dollar signs, and backslashes, but misses other critical shell metacharacters like ;, |, &, (, ), <, and >. If the downstream runner-helper.sh script is not written to handle arbitrary arguments safely (e.g., if it uses eval), this could lead to a command injection vulnerability. The sanitization should be made more robust by removing all potentially dangerous characters. As per repository guidelines, to avoid command injection vulnerabilities when constructing shell commands dynamically, it is recommended to avoid eval and instead use a bash array to build the command and its arguments safely.
| const sanitized = prompt.replace(/[`$\\]/g, "") | |
| const sanitized = prompt.replace(/[`$\\;|()<>!]/g, "") |
References
- To avoid command injection vulnerabilities when constructing shell commands dynamically, do not use
eval. Instead, use a bash array to build the command and its arguments safely.
| const shouldReconnect = reason !== DisconnectReason.loggedOut | ||
| console.log(`Connection closed: ${reason}. Reconnect: ${shouldReconnect}`) | ||
| if (shouldReconnect) { | ||
| startBot() // Recursive reconnect |
There was a problem hiding this comment.
The recursive call startBot() for reconnection can lead to a stack overflow if connection failures occur in quick succession. It's safer to use setTimeout to schedule the reconnection, which avoids increasing the call stack depth. This also makes the example consistent with the more robust reconnection strategy shown later in this document.
| startBot() // Recursive reconnect | |
| setTimeout(startBot, 5000) // Reconnect after a delay |
|
|
||
| // Request pairing code for a phone number | ||
| if (!sock.authState.creds.registered) { | ||
| const code = await sock.requestPairingCode("+1234567890") |
There was a problem hiding this comment.
The example phone number +1234567890 includes a + prefix. According to the Baileys documentation and this document's "JID Format" section (line 519), phone numbers should be provided without the + prefix. This example is incorrect and could cause errors.
| const code = await sock.requestPairingCode("+1234567890") | |
| const code = await sock.requestPairingCode("1234567890") |
| go install -tags whatsappmulti github.com/42wim/matterbridge@master | ||
|
|
||
| # Without MS Teams (saves ~2.5GB RAM during build) + with WhatsApp | ||
| go install -tags nomsteams,whatsappmulti github.com/42wim/matterbridge@master |
There was a problem hiding this comment.
Using @master to install the Matterbridge binary is not recommended for stable setups as it can pull in breaking changes unexpectedly. For reproducible builds, it is a best practice to pin to a specific version tag (e.g., @v1.20.0). Please update the command to use the latest stable release tag instead of @master.
| break | ||
| case DisconnectReason.restartRequired: | ||
| // Normal restart — reconnect immediately | ||
| startBot() |
There was a problem hiding this comment.
This direct recursive call to startBot() can lead to stack depth issues on repeated restarts, which is a robustness concern. For consistency with the other reconnection cases and to prevent potential stack overflows, it's safer to use setTimeout to schedule the restart, even with a short delay.
| startBot() | |
| setTimeout(() => startBot(), 1000) |
There was a problem hiding this comment.
Actionable comments posted: 3
🧹 Nitpick comments (1)
.agents/services/communications/whatsapp.md (1)
175-182: Consider adding backoff delay for reconnection.The immediate recursive reconnection on line 180 could cause rapid connection attempts if the server is temporarily unavailable. While the
shouldReconnectguard is good, adding a brief delay would be more resilient.⏱️ Proposed fix with connection backoff
if (connection === "close") { const reason = (lastDisconnect?.error as Boom)?.output?.statusCode const shouldReconnect = reason !== DisconnectReason.loggedOut console.log(`Connection closed: ${reason}. Reconnect: ${shouldReconnect}`) if (shouldReconnect) { - startBot() // Recursive reconnect + setTimeout(() => startBot(), 3000) // Reconnect with 3s delay } }🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In @.agents/services/communications/whatsapp.md around lines 175 - 182, The reconnect path currently calls startBot() immediately when connection === "close" and shouldReconnect is true; add a backoff delay before calling startBot() to avoid rapid retries (e.g., use a setTimeout or an exponential backoff helper with an increasing delay and jitter) and ensure the logic uses the same lastDisconnect/DisconnectReason.loggedOut check so you only schedule reconnection when appropriate; update the block that checks shouldReconnect to schedule startBot() after the computed delay and reset/backoff counters on successful connection.
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.
Inline comments:
In @.agents/services/communications/whatsapp.md:
- Around line 787-796: Update the security guidance to recommend the secure
implementation patterns instead of weak sanitization: replace any suggestion to
sanitize strings inline for runner dispatch with explicit guidance to use
execFileSync (or equivalent) with argument arrays and avoid shell interpolation,
or to use JSON-based IPC for passing messages to runners; reference the
prompt-injection scan step (`prompt-guard-helper.sh scan "$message"`) as a
pre-dispatch check but state it does not replace safe execution models; call out
credential isolation and leak detection remain required (see
`tools/credentials/gopass.md`) and link to
`tools/security/prompt-injection-defender.md` for examples of using
execFileSync/JSON IPC in the runner dispatch flow.
- Around line 755-784: The dispatchToRunner function currently builds a shell
command string and uses execSync with a lightly "sanitized" prompt, which allows
shell injection; replace this by calling a non-shell API (e.g.,
child_process.execFile or spawnSync) to run runner-helper.sh with an argument
array instead of a single interpolated string (pass ["dispatch", runner, prompt]
or similar), remove the unsafe string interpolation and the fragile regex
sanitization (or, if you must restrict input, validate prompt/runner against a
strict whitelist/regex before calling), ensure environment variables
(DISPATCH_SENDER, DISPATCH_CHANNEL) are still passed, and update the error
handling message to mention secure dispatch failure; target the dispatchToRunner
function and the execSync invocation to make this change.
- Around line 22-29: Update the Baileys entry to reflect current requirements:
change the runtime requirement text from "Node.js 18+" to "Node.js 20+"; update
the npm package name from "`@whiskeysockets/baileys`" to the unscoped
"`baileys`"; and change the "Session store" line to state that Baileys only
provides a file-based example (useMultiFileAuthState) for non-production use and
that SQLite/Redis/PostgreSQL require custom implementations rather than being
built-in pluggable options.
---
Nitpick comments:
In @.agents/services/communications/whatsapp.md:
- Around line 175-182: The reconnect path currently calls startBot() immediately
when connection === "close" and shouldReconnect is true; add a backoff delay
before calling startBot() to avoid rapid retries (e.g., use a setTimeout or an
exponential backoff helper with an increasing delay and jitter) and ensure the
logic uses the same lastDisconnect/DisconnectReason.loggedOut check so you only
schedule reconnection when appropriate; update the block that checks
shouldReconnect to schedule startBot() after the computed delay and
reset/backoff counters on successful connection.
ℹ️ Review info
Configuration used: Path: .coderabbit.yaml
Review profile: CHILL
Plan: Pro
📥 Commits
Reviewing files that changed from the base of the PR and between ac2beaf and e7676532fa2a7d1f57cf698bb6bd3f098d4a8a2a.
📒 Files selected for processing (1)
.agents/services/communications/whatsapp.md
Create .agents/services/communications/whatsapp.md covering: - Baileys library (TypeScript, MIT, unofficial WhatsApp Web API) - QR code linking and pairing code authentication - Multi-device support and session persistence - Full messaging features (text, media, reactions, polls, status) - Group management and JID format reference - Access control patterns (allowlist, rate limiting, permission levels) - Privacy/security assessment: Signal Protocol E2E for content but extensive Meta metadata harvesting, ToS violation risks, account ban mitigation strategies - aidevops runner dispatch integration with command router pattern - Matterbridge bridging via whatsmeow (native WhatsApp support) - Connection management and health monitoring - Comparison tables vs SimpleX, Matrix, XMTP, WhatsApp Business API Closes #2750
🔍 Code Quality Report�[0;35m[MONITOR]�[0m Code Review Monitoring Report �[0;34m[INFO]�[0m Latest Quality Status: �[0;34m[INFO]�[0m Recent monitoring activity: 📈 Current Quality Metrics
Generated on: Tue Mar 3 04:59:19 UTC 2026 Generated by AI DevOps Framework Code Review Monitoring |
|
- Replace execSync with execFileSync + argument array to eliminate shell injection vulnerability (critical security fix) - Add setTimeout backoff delays to all reconnect paths to prevent stack overflow on rapid connection failures - Update package name from @whiskeysockets/baileys to baileys (official unscoped package) and Node.js requirement from 18+ to 20+ - Clarify session store as non-production example, not pluggable built-in - Update security guidance to recommend execFileSync and JSON IPC patterns - Fix pairing code example to omit + prefix per JID format spec - Pin matterbridge install to @latest instead of @master for stability
e46caad to
fb5f161
Compare
There was a problem hiding this comment.
🧹 Nitpick comments (1)
.agents/services/communications/whatsapp.md (1)
139-215: Consider adding a note about production-ready patterns.The minimal setup example is clear and functional, but developers might benefit from a brief callout that this is an illustrative starting point. Production deployments would typically add:
- Structured logging with correlation IDs
- Metrics/telemetry for message throughput and latency
- Persistent message queuing for reliability
- Database-backed auth state instead of file-based
This doesn't require code changes — just a short note like "This minimal example is suitable for development and testing. See production deployment patterns for scaling considerations."
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In @.agents/services/communications/whatsapp.md around lines 139 - 215, Add a short production-readiness note to the README or the top of the example file explaining that startBot() and the file-based auth from useMultiFileAuthState("./auth_info") are for development only and listing recommended production practices (structured logging with correlation IDs, metrics/telemetry, durable message queuing, and storing auth state in a DB or secure store); place the note near the example invocation of startBot() or above the WASocket setup so readers see that sock.ev event handling and simple echo logic are illustrative, and link to a longer "production deployment patterns" doc if available.
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.
Nitpick comments:
In @.agents/services/communications/whatsapp.md:
- Around line 139-215: Add a short production-readiness note to the README or
the top of the example file explaining that startBot() and the file-based auth
from useMultiFileAuthState("./auth_info") are for development only and listing
recommended production practices (structured logging with correlation IDs,
metrics/telemetry, durable message queuing, and storing auth state in a DB or
secure store); place the note near the example invocation of startBot() or above
the WASocket setup so readers see that sock.ev event handling and simple echo
logic are illustrative, and link to a longer "production deployment patterns"
doc if available.
ℹ️ Review info
Configuration used: Path: .coderabbit.yaml
Review profile: CHILL
Plan: Pro
📥 Commits
Reviewing files that changed from the base of the PR and between e7676532fa2a7d1f57cf698bb6bd3f098d4a8a2a and fb5f161.
📒 Files selected for processing (1)
.agents/services/communications/whatsapp.md
|
This PR was superseded by the batch merge in PR #2771 (feat: t1385 — add 11 chat platform integration agents), which merged all the content from this branch. Closing as the content is already in main. |



Summary
.agents/services/communications/whatsapp.md— comprehensive subagent doc for WhatsApp bot integration using the Baileys library (TypeScript, MIT, unofficial WhatsApp Web API)Closes #2750
Summary by CodeRabbit