Commit Graph

889 Commits

Author SHA1 Message Date
Renato Alcara d66fd14775 fix(messages): use precise check for private chats when injecting bot node
The previous condition `!isJidGroup()` was too broad and would incorrectly
inject bot nodes for status broadcasts, newsletters, and Meta AI bots.

Now uses explicit checks for private 1:1 user conversations:
- isPnUser() for @s.whatsapp.net JIDs
- isLidUser() for @lid JIDs
- @c.us suffix for legacy format
- Excludes bot JIDs with isJidBot()

This prevents potential issues with message delivery to non-user destinations.

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
2026-01-26 11:49:12 -03:00
Renato Alcara 2b4685944a feat(messages): complete binary node wrappers for interactive messages
- Update getButtonType() to return 'native_flow' for modern nativeFlowMessage format
- Add product list detection (PRODUCT_LIST type returns native_flow)
- Implement getButtonArgs() with proper v:4 attributes for native_flow
- Add special attribute handling for payment flows (review_and_pay, mpm, review_order)
- Add bot node injection for private chats (required for interactive messages to render)
- Based on Itsukichan/Baileys and baileys_helpers implementation

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
2026-01-26 03:47:42 -03:00
Renato Alcara d081afe02b fix(messages): check all 7 message types inside viewOnceMessage wrapper
Address PR review comment: the viewOnceMessage detection now checks
all 7 message types for consistency with direct message detection:
- buttonsMessage
- templateMessage
- listMessage
- buttonsResponseMessage
- listResponseMessage
- templateButtonReplyMessage
- interactiveMessage

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
2026-01-26 02:49:21 -03:00
Renato Alcara b5c5989ed8 fix(messages): detect interactive messages inside viewOnceMessage wrapper
The getButtonType function was not detecting interactive messages
when wrapped inside viewOnceMessage (the modern nativeFlowMessage format).

This fix adds detection for:
- viewOnceMessage > interactiveMessage
- viewOnceMessage > listMessage
- viewOnceMessage > buttonsMessage

When enableInteractiveMessages is true, the 'biz' node will now be
correctly injected for messages using the viewOnceMessage wrapper.

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
2026-01-26 02:27:22 -03:00
Claude d132e1cfd8 fix: address code review feedback (batch 2)
1. Add logger to writeCacheFile (version-cache.ts)
   - Now logs warnings when file write fails
   - Helps debugging in production environments

2. Sanitize logging in parseGroupResult (communities.ts)
   - Changed from info to debug level
   - Removed full node/groupNode dumps (sensitive data)
   - Now only logs nodeTag and groupId

3. Add input validation in parseNewsletterCreateResponse (newsletter.ts)
   - Validates response structure before destructuring
   - Adds fallback values for parseInt (prevents NaN)
   - Adds null checks for optional fields

4. Add health-status.ts module
   - getHealthStatus(): Full health check with circuit breakers, cache, memory
   - isHealthy(): Simple boolean for liveness probes
   - getSimpleHealthStatus(): Returns 'ok', 'degraded', or 'error'
   - Useful for k8s probes and monitoring dashboards
2026-01-24 20:04:53 +00:00
Claude 22eda03eb2 fix(unified-session): address code review feedback
Fixes 3 issues identified in code review:

1. ENV VAR PRECEDENCE: Changed DEFAULT_CONNECTION_CONFIG to use
   undefined for enableUnifiedSession, allowing env var
   BAILEYS_UNIFIED_SESSION_ENABLED to take precedence.
   Priority is now: explicit config > env var > default (true)

2. SINGLE INITIALIZATION: UnifiedSessionManager is now created
   only once, after sendNode is defined. This avoids:
   - Duplicate circuit breaker instances
   - State reinitialization
   - Unnecessary overhead and logs

3. CONTINUOUS TIME SYNC: serverTimeOffset is now updated on
   every received frame that contains a 't' attribute, not just
   on CB:success. This keeps the offset accurate even during
   long-running connections.
2026-01-24 19:14:02 +00:00
Claude 9f17567951 feat(telemetry): add unified_session telemetry to reduce detection
Implements WhatsApp's unified_session telemetry feature to reduce
detection of unofficial clients. This is an enterprise-grade implementation
inspired by whatsmeow PR #1057 and Baileys PR #2294.

Features:
- UnifiedSessionManager class with circuit breaker protection
- Server time synchronization for accurate session IDs
- Rate limiting to prevent spam (1 minute between sends)
- Prometheus metrics integration (unified_session_sent, errors)
- Structured logging for debugging
- Configurable via SocketConfig.enableUnifiedSession
- Environment variable support (BAILEYS_UNIFIED_SESSION_ENABLED)

Trigger points (matching official WhatsApp Web):
- After successful login (CB:success)
- After successful pairing (CB:iq,,pair-success)
- When sending 'available' presence

Implementation details:
- Session ID algorithm: (now + serverOffset + 3days) % 7days
- Time constants exported from Defaults/index.ts
- Full test coverage (31 tests)

References:
- https://github.com/tulir/whatsmeow/pull/1057
- https://github.com/WhiskeySockets/Baileys/pull/2294
- https://github.com/tulir/whatsmeow/issues/810
2026-01-24 18:56:08 +00:00
Renato Alcara d95b2236c0 fix(album): resolve TypeScript strict array access errors
Fix TS2345 errors where array element access (medias[i]) was inferred as
`AlbumMediaItem | undefined` instead of `AlbumMediaItem`.

Changes:
- Add non-null assertion (!) after array access in for loops
- Add explicit cast to AnyMessageContent for hasNonNullishProperty calls

The non-null assertion is safe here because we iterate with `i < medias.length`,
guaranteeing the index is valid.

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
2026-01-23 15:48:09 -03:00
Renato Alcara 688739239a fix(album): improve validation consistency and result clarity
Addresses additional PR review suggestions:

1. **Consistent media type validation**
   - Changed from `'image' in m` to `hasNonNullishProperty(m, 'image')`
   - Aligns with validation in generateWAMessageContent
   - Prevents counting items with undefined image/video properties

2. **Explicit interrupted send indication**
   - Added `attemptedItems: number` - how many items were actually tried
   - Added `stoppedEarly: boolean` - true if interrupted by continueOnFailure=false
   - Updated `success` to be false if stoppedEarly (even if no failures in attempted items)
   - Helps automated integrations understand partial sends

Example result when interrupted:
```json
{
  "totalItems": 5,
  "attemptedItems": 3,
  "successCount": 2,
  "failedCount": 1,
  "stoppedEarly": true,
  "success": false
}
```

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
2026-01-23 15:33:46 -03:00
Renato Alcara 54549c4fc1 fix(album): address code review feedback
Fixes all issues identified in PR #44 review:

1. **Album root message now relayed to server** (Critical)
   - Before: Only generated root message, never sent it
   - After: Calls relayMessage() on albumRootMsg before sending media items
   - Also emits own event if emitOwnEvents is enabled

2. **Fixed messageId collision**
   - Before: Spread ...options could pass same messageId to all items
   - After: Explicitly pass only safe options (timestamp, quoted, etc.)
   - Each media item now gets a fresh ID from generateWAMessage

3. **Fixed proto structure for album association**
   - Before: Used non-existent messageContextInfo.messageAddOnType
   - After: Uses correct messageContextInfo.messageAssociation with:
     - associationType: proto.MessageAssociation.AssociationType.MEDIA_ALBUM
     - parentMessageKey: albumKey

4. **Added runtime error for sendMessage misuse**
   - sendMessage() now throws clear error if called with { album: ... }
   - Forces users to use sendAlbumMessage() for proper behavior

5. **Fixed documentation**
   - delay: Changed "based on media size" to "based on media type"
   - retryAttempts: Clarified it's "total attempts" not just retries

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
2026-01-23 15:09:31 -03:00
Renato Alcara 6e0694e72a feat(album): add album message sending with intelligent retry and adaptive delay
Implements WhatsApp album messages (grouped media) with the following features:

- Send 2-10 images/videos grouped as a single album message
- Adaptive delay between sends based on media type (videos get 2x delay)
- Intelligent retry with exponential backoff for failed items
- parentMessageKey reference to album root (as suggested by maintainer)
- Complete result structure with success/failure tracking per item
- Validation for min (2) and max (10) media items

Types added:
- AlbumMediaItem: Single image/video with caption, mentions, dimensions
- AlbumMessageOptions: Configuration for delay, retry, continueOnFailure
- AlbumMediaResult: Per-item result with latency and retry attempts
- AlbumSendResult: Complete result with albumKey and statistics

Based on PR #2058 from WhiskeySockets/Baileys with improvements.

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
2026-01-23 14:41:19 -03:00
Claude dc899faa11 fix(ctwa): address code review feedback from Copilot
- Update outdated file reference in comment (process-message.ts:399-421
  -> PDO response handler in src/Utils/process-message.ts)
- Add missing else branch in fallback path for duplicate request logging
  to maintain observability parity with scheduled path
- Clarify log message in fallback path to reflect direct request flow
  ('Message received before direct resend request completed')

https://claude.ai/code/session_011WM4Nb6tE1S5nLjHen8Xsi
2026-01-23 13:39:56 +00:00
Claude 65768bc70c refactor(ctwa): use messageRetryManager for placeholder resend scheduling
Aligns CTWA recovery with upstream philosophy by using messageRetryManager
instead of direct requestPlaceholderResend calls.

Benefits:
- Uses 3-second delay from manager (avoids request spam)
- Enables automatic cancellation if message arrives before request
- Centralizes phone request logic in messageRetryManager
- Adds fallback for when manager is not available

Changes:
- Wrap requestPlaceholderResend in messageRetryManager.schedulePhoneRequest()
- Add new metric status 'scheduled' for tracking scheduled requests
- Add metric status 'sent' when request is actually sent after delay
- Keep direct call as fallback when messageRetryManager is null

https://claude.ai/code/session_011WM4Nb6tE1S5nLjHen8Xsi
2026-01-23 13:17:32 +00:00
Renato Alcara 90db2512d9 feat(experimental): add interactive messages support (buttons, lists, templates, carousel)
⚠️ EXPERIMENTAL FEATURE - Use only for testing with disposable accounts

Implements full support for WhatsApp interactive messages including:
- Simple text buttons (up to 3 buttons)
- Buttons with images/videos
- List messages (up to 10 items in sections)
- Template buttons (quick reply, URL, call actions)
- Carousel messages (up to 10 scrollable cards)

Features:
- Feature flag 'enableInteractiveMessages' (default: true for dev/testing)
- Prometheus metrics for tracking sends, successes, failures, and latency
- Comprehensive TypeScript types for all interactive message formats
- Extensive logging with warnings about potential account bans
- Automatic 'biz' node injection when feature is enabled

CRITICAL WARNINGS:
- These features may NOT work on non-business WhatsApp accounts
- Can cause temporary or permanent account BANS
- WhatsApp actively blocks this functionality since April 2022
- Messages may be rejected or fail silently
- Use ONLY in dev environment with test accounts

Architecture:
- Added ButtonInfo, Templatable, Listable, Carouselable types to Message.ts
- Extended AnyMediaMessageContent and AnyRegularMessageContent
- Implemented message generation in messages.ts
- Added getButtonType() and getButtonArgs() helpers in messages-send.ts
- Injected 'biz' node in stanza construction with metrics tracking
- Added 4 new Prometheus metrics: interactiveMessagesSent, Success, Failures, Latency

Documentation:
- Complete usage guide in INTERACTIVE_MESSAGES.md
- Examples for all interactive message types
- Metrics monitoring queries
- Troubleshooting guide
- Migration path to WhatsApp Business API

Related issues:
- https://github.com/WhiskeySockets/Baileys/issues/56
- https://github.com/WhiskeySockets/Baileys/issues/25
- https://github.com/WhiskeySockets/Baileys/pull/2291

Co-Authored-By: Claude Sonnet 4.5 <noreply@anthropic.com>
2026-01-23 00:51:33 -03:00
Renato Alcara 7ec7e2c430 fix(messages-recv): add age validation for CTWA placeholder resend requests
Prevents unnecessary placeholder resend requests for messages older than 7 days,
improving resource efficiency and aligning with upstream best practices. Adds
metrics tracking for rejected old messages and includes message age in logs.

Co-Authored-By: Claude Sonnet 4.5 <noreply@anthropic.com>
2026-01-22 20:07:11 -03:00
Claude f2dd5c81c8 config: skip FULL history sync by default (market standard)
Remove the override that was forcing full history sync when
syncFullHistory was true. Now uses the default from Defaults/index.ts
which skips FULL sync type for better performance and stability.

Benefits:
- Faster connection time (2-10s vs 30s-5min)
- Lower bandwidth usage (1-10MB vs 50-500MB+)
- More stable connections (no timeouts)
- INITIAL_BOOTSTRAP + RECENT provide sufficient data

Users can still customize via shouldSyncHistoryMessage if needed.
2026-01-22 19:59:20 +00:00
Claude 1dfdd47a12 feat(history): fortify contact data extraction with fallbacks
- Add fallback chain for contact name: displayName || name || username
- Add fallback for LID: lidJid || accountLid
- Add TODO marker for WAJIDHASH support in picture updates

These fallbacks improve robustness when WhatsApp returns contact
data in different fields depending on account type (business, personal).
2026-01-22 19:48:20 +00:00
Claude c4da46321f feat: add identity change handler for improved connection stability
Cherry-pick from upstream PR #2264 (commit 5cbad317) with enhancements:

## Changes

### New Files
- `src/Utils/identity-change-handler.ts`: Centralized identity change handling
  - Enterprise-grade JSDoc documentation
  - Clear result types for all 9 possible outcomes
  - Debouncing to prevent duplicate session refreshes
  - Companion device filtering
  - Offline notification handling

- `src/__tests__/Socket/identity-change-handling.test.ts`: Comprehensive tests
  - Core functionality tests
  - Debounce behavior tests
  - Error handling tests
  - Edge case coverage

### Modified Files
- `src/Socket/messages-recv.ts`: Updated error handling
  - MISSING_KEYS_ERROR now returns NACK with ParsingError
  - Maintains CTWA recovery logic intact
  - Preserves all Prometheus metrics integration

- `src/Utils/generics.ts`: Added `isStringNullOrEmpty()` helper
- `src/Utils/index.ts`: Added identity-change-handler export

## Benefits
- Fixes "Online" status shown when actually disconnected (#2132)
- Better session management after contact identity changes
- Clear separation of concerns with dedicated handler module

Co-authored-by: João Lucas de Oliveira Lopes <55464917+jlucaso1@users.noreply.github.com>
2026-01-22 18:34:19 +00:00
Claude 9e1e67df6a fix: skip retry for expired status messages over 24 hours old
Cherry-pick from upstream PR #2280 (commit 92d4198)

- Add STATUS_EXPIRY_SECONDS constant (24h = 86400s)
- Skip retry attempts for status broadcast messages older than 24h
- Saves resources by not retrying messages that are already expired

Co-authored-by: João Lucas de Oliveira Lopes <55464917+jlucaso1@users.noreply.github.com>
2026-01-22 18:24:18 +00:00
Claude b3917299cd feat: add message retry and failure metrics tracking
Added metrics tracking for:
- message_retries_total: Incremented when message retry is attempted
- message_failures_total: Incremented when max retries reached or encryption fails

Note: messages_queued metric is not applicable as this implementation
sends messages directly without an explicit queue system.
2026-01-22 14:42:22 +00:00
Claude de5988ba8f feat: implement WhatsApp connection and message metrics
Added tracking for all WhatsApp-related metrics:

Connection metrics:
- active_connections: Gauge tracking active connections (inc on open, dec on close)
- connection_attempts_total: Counter for connection attempts (success/failure)

Message metrics:
- messages_sent_total: Counter with type label (text, image, video, audio, etc)
- messages_received_total: Counter with type label
- history_sync_messages_total: Counter for history sync messages

Added helper functions in prometheus-metrics.ts:
- incrementActiveConnections(), decrementActiveConnections(), setActiveConnections()
- recordConnectionAttempt(status)
- recordMessageSent(type), recordMessageReceived(type)
- recordMessageRetry(type), recordMessageFailure(type, reason)
- setMessagesQueued(count, priority)
- recordHistorySyncMessages(count)
2026-01-22 14:20:17 +00:00
Claude 8d0c03cc2a feat: add connection_errors_total metric tracking
Added recordConnectionError() function and integrated it into socket.ts
to track connection errors by type:
- connection_closed
- connection_lost
- connection_replaced
- timed_out
- logged_out
- bad_session
- restart_required
- multidevice_mismatch
- error_{code} for other status codes
2026-01-22 13:43:31 +00:00
Claude 29475018a3 fix: address PR review comments for version cache
- Replace Function type with proper VersionCacheLogger interface
- Add documentation for cacheFilePath about container/serverless limitations
- Handle fetchInProgress in clearVersionCache to prevent cache restoration
- Add deduplication check in refreshVersionCache
- Remove unused fetchLatestWaWebVersion import
- Return success status from refreshVersionCache to detect fallback
- Fix inefficient getCachedVersion call - use cacheStatus.version directly
- Remove as any casts by using logger adapter pattern
- Don't downgrade version on transient network errors
2026-01-21 19:14:32 +00:00
Claude 185632c053 feat: add persistent shared version cache for multiple connections
- Add version-cache.ts with file-based persistence
- 150 connections = 1 request (not 150) via request deduplication
- Cache survives server restarts via .baileys-version-cache.json
- Export cache utilities: getCachedVersion, refreshVersionCache, clearVersionCache
- Update makeWASocketAutoVersion to use shared cache
2026-01-21 18:47:12 +00:00
Claude 46ffaf027c fix: address PR review comments
Fixes from code review:

1. Fix #1,6: Use connection.update event instead of overriding sock.end()
   - Listens for 'close' event to cleanup interval
   - Handles both explicit close and internal disconnections

2. Fix #3: Exit code 2 when fetch fails (not 0)
   - Allows CI to distinguish success/error/fetch-failed
   - Properly signals fetch failures to workflows

3. Fix #4: Document revision bounds + add env vars
   - Added detailed comments explaining min/max revision values
   - Made configurable via WA_MIN_REVISION/WA_MAX_REVISION env vars

4. Fix #5,9: Remove unused fetchLatestVersion option
   - Removed from SocketConfig and defaults
   - Updated versionCheckIntervalMs docs to clarify it's only for makeWASocketAutoVersion

5. Fix #7: Use separate variable for version tracking
   - trackedVersion instead of mutating mergedConfig
   - Prevents unexpected side effects

6. Fix #8: Check socket state before emitting events
   - isSocketClosed flag to prevent race conditions
   - Double-check after async operations

7. Fix #10: Implement force parameter in workflow
   - Creates PR even without version changes when force=true
   - Useful for re-triggering updates manually

Note: Test coverage (Fix #2) deferred to separate PR due to
ESM mocking complexity with Jest.
2026-01-21 17:21:49 +00:00
Claude 805fdd3525 feat: add periodic version check with soft reconnection
Implements automatic version updates that are transparent to users:

- Checks for new WhatsApp Web version every 6 hours (configurable)
- When new version detected, saves it for next natural reconnection
- Emits 'version.update' event so users can track updates
- No disconnection required - WhatsApp naturally reconnects every 30min-2h
- Cleans up interval when socket closes

Configuration:
```typescript
const sock = await makeWASocketAutoVersion({
    auth: state,
    versionCheckIntervalMs: 6 * 60 * 60 * 1000 // 6 hours (default)
})

sock.ev.on('version.update', ({ currentVersion, newVersion, isCritical }) => {
    console.log(`New version: ${newVersion.join('.')}`)
})
```
2026-01-21 16:51:39 +00:00
Claude 76e080daec feat: add makeWASocketAutoVersion for automatic version fetching
Adds a new async function that automatically fetches the latest
WhatsApp Web version from web.whatsapp.com before connecting.

Usage:
```typescript
// Option 1: Auto-fetch version (recommended)
const sock = await makeWASocketAutoVersion({ auth: state })

// Option 2: Manual version (existing behavior)
const sock = makeWASocket({ auth: state })
```

Benefits:
- No need to update library for version changes
- Automatic fallback to bundled version if fetch fails
- Logged warnings when using fallback
2026-01-21 16:38:46 +00:00
Claude 5a36ae20d4 feat: add automatic CTWA (Click-to-WhatsApp) ads message recovery
Messages from Facebook/Instagram ads (Click-to-WhatsApp) don't arrive on
linked devices because Meta's ads endpoint doesn't encrypt for multi-device.
They arrive as "Message absent from node" placeholders.

This change automatically requests the message from the primary phone via
PDO (Peer Data Operation) when a CTWA placeholder is detected.

Changes:
- Add enableCTWARecovery config option (default: true)
- Trigger requestPlaceholderResend() for "Message absent from node" errors
- Add Prometheus metrics for CTWA recovery tracking
- Add comprehensive unit tests for CTWA recovery functionality

Resolves: https://github.com/WhiskeySockets/Baileys/issues/1723
Resolves: https://github.com/WhiskeySockets/Baileys/issues/1034
2026-01-21 14:56:39 +00:00
Renato Alcara 31fdfa8b7c chore: log fallback mapping availability 2026-01-21 00:52:17 -03:00
Claude 3f2ced4501 feat(logger): add [BAILEYS] console-friendly logging functions
Add formatted logging functions with [BAILEYS] prefix and emojis:
- logEventBuffer: buffer events (📦, 🔄, ⚠️, , 🧹, 🧠)
- logBufferMetrics: metrics display (📊)
- logMessageSent/Received: message events (📤, 📥)
- logConnection: connection events (🔌, , 🔴, 🔄, )
- logAuth: authentication events (📱, 🔑, 🚪, 🔐)
- logCircuitBreaker: circuit breaker state (, , 🔶)
- logRetry: retry attempts (🔁)
- logInfo/Warn/Error: generic messages (ℹ️, ⚠️, )
- logLidMapping: LID store events (🗂️, 🔍, 💾, 📦)

All functions respect BAILEYS_LOG=false environment variable.
Integrated into event-buffer.ts and messages-send/recv.ts.
2026-01-20 20:48:46 +00:00
Renato Alcara b21847addb Merge branch 'WhiskeySockets:master' into master 2026-01-20 09:58:02 -03:00
João Lucas de Oliveira Lopes 8ff01b8bb3 fix: store LID-PN mapping from contactAction sync (#2266)
* fix: store LID-PN mapping from contactAction sync

* chore: improve testing of sync actions
2026-01-20 12:39:41 +02:00
Luiz Braga 32134a870e chore: Add messageTimestamp to message updates in messages-recv when receiving a message status update (#2277) 2026-01-20 12:37:34 +02:00
Claude 3afb8b80c5 feat(socket): add configurable maxListeners to prevent memory leaks
Based on RSocket's battle-tested configuration:

- Add maxWebSocketListeners config option (default: 20)
  - 8 base WS events + 10 dynamic listeners + 2 buffer slots
- Add maxSocketClientListeners config option (default: 50)
- Replace dangerous setMaxListeners(0) with configurable limits
- Add warning log if user explicitly sets limit to 0

BREAKING: Previous behavior used setMaxListeners(0) which removed
all limits. Now defaults to safe limits but can be overridden via config.
2026-01-20 05:19:22 +00:00
Claude 61f5f76ef0 feat(socket): integrate circuit breaker with Socket operations
- Add circuit breaker configuration options to SocketConfig type
- Initialize circuit breakers for query, connection, and pre-key operations
- Wrap query() with circuit breaker protection for all WhatsApp queries
- Wrap sendRawMessage() with connection circuit breaker
- Integrate pre-key circuit breaker with uploadPreKeys()
- Add circuit breaker utilities to socket return object (stats, reset)
- Clean up circuit breakers on connection close
- Fix TypeScript errors in utility files (prometheus-metrics, logger-adapter, etc.)

Circuit breakers provide:
- Sliding window failure tracking
- Automatic state transitions (closed -> open -> half-open)
- Configurable thresholds and timeouts
- Prometheus metrics integration
- Event callbacks for monitoring
2026-01-20 02:31:23 +00:00
Rajeh Taher b62cb40a70 chore: lint 2026-01-18 17:16:28 +02:00
Rajeh Taher 282f065f53 connection-deadlock, socket: improve socket end conditions 2026-01-18 17:16:28 +02:00
Rajeh Taher e740fc5b4a messages-send: revamp message type function 2026-01-18 01:35:50 +02:00
Rajeh Taher 83e0f22af8 messages-recv: decrease PDO response timeout 2026-01-18 01:34:39 +02:00
Rajeh Taher b1c76ebe2d chore: lint+bugfix 2026-01-18 01:31:56 +02:00
João Lucas de Oliveira Lopes e53fa7b8e5 Feat improve testing coverage e2e (#1799)
* fix: ensure proper socket closure and await connection termination in tests

* feat(tests): enhance E2E tests for image and video message handling, including downloads and group interactions
2026-01-18 01:16:24 +02:00
YonkoSam 1408499d7c moved retryCount before validating the session (#2167) 2026-01-18 01:11:10 +02:00
Matheus Filype 349e7bd771 feat: send tctoken to profile update and presence subscribe (#2257)
* fix: improve message resend logic by adding checks for message IDs

* Revert "fix: improve message resend logic by adding checks for message IDs"

This reverts commit c03f9d8e6fc6cbfbb9d1f8f67c169700e704213d.

* feat(tc-token): implement buildTcTokenFromJid utility and integrate into chats socket

* fix(tc-token): ensure consistent return value when tcTokenBuffer is absent

* fix(chats): update import path for buildTcTokenFromJid utility
2026-01-18 01:07:53 +02:00
vini 432c26a07c fix(messages): handle encryption failures per recipient and fail when all fail (#2226) 2026-01-08 22:07:11 +02:00
Ibrahim Pelumi Lasisi 720cc688d6 fix: avoid variable shadowing and preserve empty business profile fields (#2183)
* Update business.ts

* chore: fix lint issues
2026-01-08 21:56:13 +02:00
Gustavo Quadri 81d9c12e86 fix: getmessagetype to ensure consistency with whatsapp behavior (#2245) 2026-01-08 21:51:34 +02:00
João Lucas de Oliveira Lopes c9c3481817 implement message reporting tokens (#1906)
* feat: implement message reporting tokens and privacy token handling

* feat: add support for privacy tokens in profile picture requests and history sync

* chore: pr feedback purpshell

* fix: improve privacy token handling and error messaging in socket configuration

* feat: enhance privacy token handling with improved sender mapping

* chore: removing tc token in favor of #2080

* chore: revert some unecessary changes

* feat(reporting): enhance reporting token extraction and compilation logic

* feat(reporting): add unit tests for reporting token utilities

* fix(reporting): streamline reporting token attachment logic in message sending

* fix: adjust reporting token inclusion logic to prevent retries

* chore: add return type to shouldIncludeReportingToken and improve getToken function type safety
2026-01-08 21:50:49 +02:00
Matheus Filype 250477497d Add Feature LabelMember (Based on #2164) (#2198)
* fix: improve message resend logic by adding checks for message IDs

* Revert "fix: improve message resend logic by adding checks for message IDs"

This reverts commit c03f9d8e6fc6cbfbb9d1f8f67c169700e704213d.

* feat: add group member label update functionality and event emission

* feat: refactor updateMemberLabel function for improved readability

* feat: use optional chaining for label association message in processMessage

* feat: add updateMemberLabel to makeMessagesSocket for enhanced functionality

* fix: correct log message for group member tag update event

Co-authored-by: FgsiDev
2025-12-19 22:00:48 +02:00
Matheus Filype b7960dbb9a feat: Optimize Offline Node Processing with Batching and Event Loop Yielding (#2138)
* fix: improve message resend logic by adding checks for message IDs

* Revert "fix: improve message resend logic by adding checks for message IDs"

This reverts commit c03f9d8e6fc6cbfbb9d1f8f67c169700e704213d.

* fix(messages-recv): improve offline node processing and error handling

* feat: improve offline node processing by yielding to event loop
2025-12-12 06:50:18 +02:00
YonkoSam 1e6f65cf5e fix Memory leak in makeMutex - Promise never gets garbage collected (#2151)
* Memory leak in makeMutex - Promise never gets garbage collected

Hey, I've been debugging a memory leak in my application and traced it back to the makeMutex implementation.

The current implementation chains promises indefinitely without ever breaking the chain:

Every call to mutex() creates a new Promise that awaits the previous task, then becomes the new task. The problem is the old promises never get released because each one holds a reference to the previous through the closure.

What I found
Took a heap snapshot after running for a while and found hundreds of Promises from make-mutex.js holding ~15MB and growing. The retainer graph shows a long chain of Promises all pointing back to each other.

Since processingMutex handles every incoming message/notification, this chain grows constantly and never shrinks.

This keeps the same mutex behavior but lets the GC clean up old promises every 50 tasks instead of holding them forever.

* Refactor makeMutex to use AsyncMutex directly

* lint

* revert
2025-12-12 04:35:24 +02:00