Commit Graph

25 Commits

Author SHA1 Message Date
Claude 38575fb2d8 fix: replace static whatsapp-rust-bridge imports with lazy dynamic loading
The whatsapp-rust-bridge package contains a top-level await on an inline
WASM binary, which propagates through the ESM graph and causes
ERR_REQUIRE_ASYNC_MODULE when CJS consumers try to require() this package.

Replace all static imports from whatsapp-rust-bridge with a lazy-loading
bridge module (wasm-bridge.ts) that uses import().then() instead of
top-level await, keeping the dependency out of the static ESM graph.

https://claude.ai/code/session_01XaA7GwNaB6azTHFYQ8WEpB
2026-02-09 02:31:52 +00: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 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
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 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 64c7712da7 refactor(utils): translate all comments to English and enhance circuit breaker
- Translate all Portuguese comments to English in utility modules
- Enhance circuit-breaker.ts with sliding window failure tracking
- Add factory functions for WhatsApp-specific circuit breakers
  (createPreKeyCircuitBreaker, createConnectionCircuitBreaker, createMessageCircuitBreaker)
- Improve volume threshold support for circuit breaker decisions
- Standardize documentation across all utility files

Files updated:
- structured-logger.ts: English comments
- baileys-logger.ts: English comments
- trace-context.ts: English comments
- prometheus-metrics.ts: English comments
- cache-utils.ts: English comments
- circuit-breaker.ts: Enhanced with sliding window + English comments
- retry-utils.ts: English comments
- baileys-event-stream.ts: English comments
- index.ts: English comments
2026-01-20 01:48:23 +00:00
Claude 882a1f57cf feat(utils): add observability and resilience utilities
Implement comprehensive utility modules for InfiniteAPI:

Logging:
- structured-logger: JSON logging with levels, sanitization, metrics
- logger-adapter: Pino/Console/Structured adapter pattern
- baileys-logger: WhatsApp-specific logger with categories

Observability:
- trace-context: Distributed tracing with spans, correlation IDs
- prometheus-metrics: Counter, Gauge, Histogram, Summary metrics

Resilience:
- cache-utils: LRU cache with TTL, multi-level support
- circuit-breaker: 3-state circuit breaker with fallbacks
- retry-utils: Exponential backoff with jitter, predicates

Event Streaming:
- baileys-event-stream: Priority queues, backpressure, DLQ

Includes unit tests for all new modules.
2026-01-20 01:26:06 +00:00
Rajeh Taher 50d410d117 chore: lint 2025-11-19 16:25:56 +02:00
Rajeh Taher 334977f983 general: revert #1665 2025-10-03 18:14:30 +03:00
Rajeh Taher e965385841 utils: update exports 2025-09-26 05:52:53 +03:00
Paulo Victor Lund ae0cb89714 Session recreation and improved message retry (#1735)
* Add message retry manager for session recreation and caching

Introduces a MessageRetryManager to cache recent sent messages and manage automatic Signal session recreation for failed message retries. Adds new config options to enable these features, integrates retry manager into message send/receive logic, and provides periodic cache cleanup. Improves reliability of message delivery and retry handling.

* Add buffer timeout and cache limit to event-buffer

Introduces a buffer timeout to auto-flush events after 30 seconds and limits the history cache size to prevent memory bloat in event-buffer.ts.

* Add session validation to SignalRepository

Introduces a validateSession method to SignalRepository for checking session existence and state. Updates message retry logic to use the new validation, improving session recreation handling and retry management.

* Improve message retry management and tracking

Refactored message retry manager to use LRU caches for recent messages and session history, added retry counters and statistics tracking, and implemented phone request scheduling. Updated message receive and send logic to mark retry success and pass max retry count. Removed periodic cleanup logic in favor of cache TTLs for better resource management.

* lint fix

* Use validateSession for session checks in message send

Replaces direct session existence checks with the improved validateSession method, which also checks for session staleness. Adds debug logging for failed session validations to aid troubleshooting.

* Delete src/Utils/message-retry.ts

---------

Co-authored-by: Rajeh Taher <rajeh@reforward.dev>
2025-09-07 20:20:51 +03:00
Adhiraj Singh 36d6cfd5fb refactor: poll decryption 2023-03-02 17:41:43 +05:30
Alan Mosko 78f04d8714 wip 2023-01-11 23:58:29 -03:00
Adhiraj Singh 48abf73e57 chore: export process-message utils 2022-10-23 17:11:17 +05:30
Adhiraj Singh 5aaefa94d6 chore: remove single file auth state 2022-09-20 12:00:37 +05:30
Adhiraj Singh e7f6838fa4 chore: remove legacy code 2022-09-19 14:59:35 +05:30
Adhiraj Singh 7421f55daa feat: implement event buffer for offline msgs
!BREAKING_CHANGE

1. this allows all offline notifications to be combined into a batch -- to reduce the number of events being sent out
2. to enable the above, the "message.reaction" event has been made an array. Also removes the need for the "operation" field
3. have also now started processing all events under a single queue to prevent state sync problems
2022-06-27 13:38:29 +05:30
Adhiraj Singh 15761ca9df chore: more modular link preview generation 2022-05-27 13:30:37 +05:30
Adhiraj Singh 06437e182d feat: add "multi file auth state" implementation
1. add multi file auth state since it's far more efficient than single state
2. deprecate single file auth state (please don't use it anymore)
2022-05-22 21:21:35 +05:30
Adhiraj Singh 806138a35e feat: add logging event stream 2022-03-29 18:25:42 +05:30
Adhiraj Singh 19a9980492 feat: add legacy connection 2021-12-17 19:27:04 +05:30
Adhiraj Singh 3d0704a317 feat: cleaner auth state management
1. removes the "auth-state.update" event since it was bloated and fairly unnecessary
2. adds "creds.update" event that only sends the updated properties of the auth credentials
3. ensure the auth creds are not mutated anywhere, but only with the "creds.update" event
4. Separates the signal credentials from the auth credentials (kinda in progress)
5. in memory key store requires a save function to let one know when to save the keys

!BREAKING_CHANGE
2021-11-20 16:21:56 +05:30
Adhiraj Singh d3b7ffecf2 code cleanup 2021-10-11 09:36:17 +05:30
Adhiraj Singh f1527a9f6b separate out crypto utils 2021-09-23 22:37:33 +05:30
Adhiraj Singh 71e34fc5f8 Cleanup + add remaining utils 2021-07-12 23:50:08 +05:30