Defensive: if WhatsApp ever flips AB prop 10518
(privacy_token_sending_on_all_1_on_1_messages) to false, the gate added
in 225b692b7c would drop the tctoken from ALL 1:1 sends — including
carousel, which Pastorini CDP capture confirms requires tctoken to
render correctly on Android.
Match the fork's pre-PR #2339 behaviour for carousel only: always
attach when a tcTokenBuffer is available. Regular 1:1 sends still
honour the AB prop.
Backports the 4 critical/major gaps the audit identified vs Baileys
PR #2339, surgically and without touching carousel, buttons, lists,
LID/PN normalization, Bad MAC handling or app-state-sync code.
TIER 1 — eliminates production error 463 in two scenarios:
- onBeforeSessionRefresh callback (identity-change-handler.ts):
invoked BEFORE assertSessions for an existing-session identity
change. Skipped for self / companion / debounced / offline paths.
- reissueTcTokenAfterIdentityChange (messages-recv.ts): fire-and-
forget, runs IN PARALLEL with the session refresh (not after) and
preserves the existing senderTimestamp so the contact gets a fresh
token in the same bucket window. Replaces the fork's previous
post-refresh reissue, which raced with the next outbound send.
- storeTcTokensFromHistorySync (process-message.ts): extracts
tcToken / tcTokenTimestamp / tcTokenSenderTimestamp from history-
sync chats and persists them BEFORE messaging-history.set fires,
so multi-device login doesn't lose tokens. Strict > monotonicity
(matches upstream).
TIER 2 — server AB-prop gating:
- serverProps in chats.ts: parses 10518 (privacy_token_sending_on_
all_1_on_1_messages), 9666 (profile_scraping_privacy_token_in_
photo_iq), 14303 (lid_trusted_token_issue_to_lid). Defaults match
WA Web (true / true / false). Exported in the socket return so
messages-send/messages-recv can read it.
- profilePictureUrl gates inclusion on serverProps.profilePicPrivacyToken.
- 1:1 send gates attach on serverProps.privacyTokenOn1to1.
- resolveIssuanceJid (tc-token-utils.ts): routes issuance to LID
vs PN based on AB prop 14303. Used by both the post-send fire-
and-forget and the identity-change reissue.
TIER 3 — defensive hardening:
- isRegularUser (tc-token-utils.ts): Wid.isRegularUser() port that
rejects PSA WID '0', bot phone patterns (1313555XXXX / 131655500XX)
and MetaAI (@bot). storeTcTokensFromIqResult drops malformed
notifications before writing. Send-side issuance also gates on
PSA / bot / protocol-message exclusions (matches WA Web's
TcTokenChatAction).
- inFlightTcTokenIssuance Set (messages-send.ts): dedupes
fire-and-forget issuance when several rapid sends to the same
contact happen before senderTimestamp persists. Distinct from
the existing tcTokenFetchingJids (which dedupes inbound fetches).
- TC_TOKEN_INDEX_KEY exported from tc-token-utils.ts and re-used
in messages-recv.ts (was previously inlined as a separate local
const — risk of divergence on rename). Same value '__index'.
- readTcTokenIndex / buildMergedTcTokenIndexWrite: cross-session
prune index helpers so issuance / history-sync / pruner all
merge with the persisted set instead of clobbering each other.
Audit findings explicitly addressed:
- TC_TOKEN_INDEX_KEY duplication: unified via import.
- Index write race (prune vs issuance): documented; worst case is a
one-cycle delay of pruning, no data loss.
- Identity-change reissue + post-send issuance double-fire: bounded
by bucket coalescing — both use the same senderTimestamp window so
even if both IQs go out, the persisted state converges.
Tests:
- identity-change-handling: 2 new cases covering onBeforeSessionRefresh
ordering (fires BEFORE assertSessions) and skip behavior on
no_identity / offline / self.
- tc-token: 32 new cases across isRegularUser (PSA / bot / MetaAI /
hosted), resolveIssuanceJid (AB prop 14303 ON/OFF, missing mappings),
TC_TOKEN_INDEX_KEY ('__index' frozen), readTcTokenIndex (corruption /
empty / sentinel filter), buildMergedTcTokenIndexWrite (merge /
sentinel drop / empty), storeTcTokensFromIqResult gating (PSA / bot /
MetaAI rejection, fallbackJid storage routing, monotonicity).
Suite: 35/35, 821/821 passing (+115 vs baseline 706).
Customizations untouched: zero diff in src/Utils/messages.ts (carousel
generators), src/Socket/groups.ts, WAProto/*. Confirmed via grep for
carousel/button/interactive/nativeFlow/list/biz/album in the modified
files — no matches.
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
* perf: optimize history sync memory and CPU usage
Aligns with Baileys upstream PR #2333 . Surgical port of
4 micro-optimizations + 2 test files. No collision with InfiniteAPI's
LID/PN, carousel, buttons, Bad MAC or app state sync resilience code.
Changes:
1. WAProto longToString/longToNumber: use native BigInt instead of
Long library division loops. ~4.6x faster per call (237ns -> 52ns).
BigInt.toString() delegates to V8 native C++. Same change applied
to fix-imports.js (template) and index.js (generated artifact) so
future regenerations stay in sync.
2. downloadHistory: stream-pipe createInflate instead of buffering
the full compressed payload then inflating. Cuts RSS peak ~50%
on 50MB history payloads.
3. processHistoryMessage: drop the { ...chat } shallow copy before
pushing to chats[]. The decoded protobuf object is not referenced
after the push.
4. downloadEncryptedContent transform: skip Buffer.concat when
remainingBytes is empty (the common case — chunks usually arrive
AES-aligned). ~19x faster per chunk (78ms -> 4ms over 25k chunks).
Tests:
- bigint-validation.test.ts (NEW): 32 parameterized cases covering
zero, MAX_SAFE_INTEGER boundary, max int64/uint64, negative values,
tricky bit patterns and powers of 2; plus 200-iter fuzz comparing
old Long vs new BigInt implementations for equivalence.
- proto-tojson-long.test.ts: kept the existing fork-only test for
string-in-Long-field graceful handling, appended 4 upstream tests
covering Long->string fast path, large unsigned > MAX_SAFE_INTEGER,
zero/small values and encode/decode roundtrip.
* test(binary): cover reconnection sync skip for both signals
Ports the upstream reconnection-sync-skip test from Baileys PR #2350
and adapts it to cover InfiniteAPI's dual-signal reconnect detection
in chats.ts:
1. accountSyncCounter > 0 (a previous full sync completed)
2. socketSkippedOfflineBuffer (forwarded from socket.ts when
hadStaleRoutingInfo is true, e.g. routingInfo discarded on start)
Both are required because they cover different reconnect scenarios
and the absence of the second branch causes a buffer mismatch where
socket.ts skips the offline buffer while chats.ts still waits in
AwaitingInitialSync — stalling live messages for up to 4 seconds.
Co-Authored-By: Renato Alcara
* perf(messages-recv): early-ignore JIDs before buffer/queue
Aligns with Baileys upstream PR #2352. Moves the shouldIgnoreJid check
out of handleMessage/handleReceipt/handleNotification and into
processNode so ignored stanzas are acked and dropped before entering
ev.buffer(), the offline queue, or the keyed mutexes. Skips the LID->PN
resolution work in handleReceipt for ignored receipts as a side effect.
Diverges from upstream by excluding type='call' from the early-ignore
check — InfiniteAPI's handleCall has never used shouldIgnoreJid, so
keeping calls outside this filter preserves existing behavior for
integrators that filter messages but still want call events.
Carousel, buttons, LID/PN normalization, Bad MAC fix and retry manager
untouched.
Co-Authored-By: Renato Alcara
* feat: add inbound username support and USync username protocol
Aligns with Baileys upstream PR #2480. WhatsApp is rolling out an
inbound username field that maps to the user's LID. This change is
purely additive — it captures and propagates the new optional field
through types, decoders, USync queries, and group/contact events.
Skipped intentionally to preserve InfiniteAPI's LID/PN customization:
- handleGroupNotification in messages-recv.ts (custom LID->PN flow on
groups.upsert / participants.map). Username for these specific
events still flows via process-message's emitParticipantsUpdate
(reads message.key.participantUsername added in decode-wa-message).
Carousel/buttons code (messages.ts, messages-send.ts) untouched.
Co-Authored-By: Renato Alcara
Adds experimental native protocol mode (WAM\x05) as alternative to
web protocol (WA\x06\x03). Configurable via BAILEYS_PROTOCOL env var:
- web (default): standard WhatsApp Web protocol
- native: Android native protocol (may enable view-once media on companions)
When native mode is enabled:
- NOISE_WA_HEADER changes from WA\x06\x03 to WAM\x05
- DICT_VERSION changes from 3 to 5
- WebInfo is omitted from ClientPayload
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
Add webdPayload to WebInfo during connection with:
- supportsE2EImage/Video/Audio/Document = true
- supportsMediaRetry = true
- features bitmask with view-once capability flag
This may enable the WA server to deliver view-once media content
to Baileys companions instead of just <unavailable> placeholders.
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
When receiving <unavailable type='view_once'/>, attempt to request
the actual media content from the primary phone via PDO
(Peer Data Operation / PLACEHOLDER_MESSAGE_RESEND).
If the phone responds, the full media (url, mediaKey, directPath)
arrives via messages.upsert, allowing consumers to display the image.
Falls back to placeholder if PDO fails or phone doesn't respond.
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
The early unavailable handler at line ~2261 was intercepting
view_once stanzas and silently discarding them (sendMessageAck + return)
before the view_once_unavailable_fanout handler could emit them.
Now emits a viewOnceMessage placeholder with isViewOnce=true so
consumers receive the event in messages.upsert.
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
Two issues found during view-once testing on linked devices:
1. msmsg block removal:
The "temporary fix" that discarded all msmsg-type encrypted messages
was also blocking legitimate view-once messages. On linked devices,
view-once arrives as msmsg encryption type. The block was originally
added to prevent crashes from missing messageSecret, but the existing
try/catch in the decrypt path already handles those errors gracefully
by marking the message as a CIPHERTEXT stub.
2. view_once_unavailable_fanout emission:
When a linked device receives a view-once, the WA server sends only
<unavailable type="view_once"/> (no <enc> with actual media content).
Previously this was silently acknowledged without emitting any event,
so consumers (zpro, astra-api, etc.) never knew a view-once arrived.
Now it emits the message as a CIPHERTEXT stub with key.isViewOnce=true
so consumers can display "view-once message received" in their UI.
Co-Authored-By: Renato Alcara
Two issues found during view-once testing on linked devices:
1. msmsg block removal:
The "temporary fix" that discarded all msmsg-type encrypted messages
was also blocking legitimate view-once messages. On linked devices,
view-once arrives as msmsg encryption type. The block was originally
added to prevent crashes from missing messageSecret, but the existing
try/catch in the decrypt path already handles those errors gracefully
by marking the message as a CIPHERTEXT stub.
2. view_once_unavailable_fanout emission:
When a linked device receives a view-once, the WA server sends only
<unavailable type="view_once"/> (no <enc> with actual media content).
Previously this was silently acknowledged without emitting any event,
so consumers (zpro, astra-api, etc.) never knew a view-once arrived.
Now it emits the message as a CIPHERTEXT stub with key.isViewOnce=true
so consumers can display "view-once message received" in their UI.
Co-Authored-By: Renato Alcara