Compare commits

...

6 Commits

Author SHA1 Message Date
Renato Alcara ba1c1b0fdb fix: align Bad MAC retry receipt with WA Desktop behavior
Three issues corrected in sendRetryRequest (receiver side):

1. BUG — error code hardcoded as '0' (UnknownError) in retry receipt.
   The peer (especially another InfiniteAPI instance) could not detect
   the failure type and would fall back to the 1-hour session recreation
   timeout instead of recreating immediately.
   Fix: derive error code from the actual libsignal decryption error
   message stored in messageStubParameters[0].

2. BUG — shouldRecreateSession block was reading the wrong node: it
   called getBinaryNodeChild(node, 'retry') on the incoming bad-MAC
   message, which never has a <retry> child. errorCode was always
   undefined, so MAC_ERROR_CODES never matched — the logic was dead.

3. BUG (consequence of #2) — when shouldRecreateSession accidentally
   did fire (no-session or 1-hour timeout), it deleted the receiver's
   session BEFORE the sender's pkmsg arrived. This opened a race window
   where concurrent messages would fail with "No Session".
   Fix: remove the entire session-deletion block from sendRetryRequest.
   The Signal Protocol pkmsg automatically overwrites the corrupted
   session — no explicit delete needed on the receiver side.

WA Desktop reference (CDP capture 2026-03-19):
- Retry receipt sent ~99ms after Bad MAC with specific error code
- pkmsg arrives ~304ms later, new session established automatically
- Old session is never deleted; pkmsg overwrites it implicitly
- Full recovery in ~1.3s without any race window

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-03-19 23:10:59 -03:00
Renato Alcara 876af2e96c fix: HistorySync LID improvements — raw_id mapping, prekey pool strategy, keepalive jitter, CDN cleanup
fix: HistorySync LID improvements — raw_id mapping, prekey pool strategy, keepalive jitter, CDN cleanup
2026-03-19 18:24:20 -03:00
Renato Alcara 5bb18da6bf fix: address PR #305 review comments — Origin header, lowServerCount threshold, keepalive guard
- history.ts: add Origin: DEFAULT_ORIGIN to CDN DELETE request headers —
  the download path injects it internally but options does not carry it
- socket.ts: fix lowServerCount comparison — was preKeyCount <= topUpAmount
  which triggered uploads even when above MIN_PREKEY_COUNT (e.g. 250 prekeys
  → topUp=550 → 250<=550=true → unnecessary upload). Now uses correct
  threshold: preKeyCount < MIN_PREKEY_COUNT
- socket.ts: guard scheduleNextKeepAlive() with !closed check to prevent
  orphan timers when end() was called concurrently on a different path

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-03-19 18:23:41 -03:00
Renato Alcara 52d8ddae32 fix: prevent double prekey upload when concurrent uploads race on count=0
uploadPreKeys() waited for a concurrent upload but then proceeded to upload
again. With top-up logic and count=0, both handleEncryptNotification and
uploadPreKeysToServerIfRequired fire simultaneously, both see count=0, first
wins and uploads 800, second waits then uploads another 800 → 1600 prekeys.

Fix: return immediately after awaiting the concurrent upload — it already
replenished the pool.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-03-19 18:23:41 -03:00
Renato Alcara 8c8c5a312e fix: address PR review comments — CDN DELETE timing, keepalive leak, spread order
- history.ts: move CDN DELETE from downloadHistory() to
  downloadAndProcessHistorySyncNotification(), after processHistoryMessage()
  succeeds — prevents permanent history loss if processing throws post-download
- history.ts: fix fetch spread order: { ...options, method: 'DELETE' } so
  options.method cannot shadow the intended DELETE verb
- socket.ts: add early return after void end() in onKeepAliveTick to prevent
  scheduleNextKeepAlive() from leaking a timer while connection is closing

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-03-19 18:23:28 -03:00
Renato Alcara 52756fb50d fix: histsync LID improvements — raw_id mapping, prekeys, keepalive jitter, CDN DELETE
1. USyncQuery: extract raw_id attr from node attrs into rawId field; implement
   side_list parsing (was TODO/commented) reusing shared parseNodeList helper

2. getUSyncDevices: add 4th LID→PN source via raw_id pairing from device-list
   WA Business sends zero phoneNumberToLidMappings in HistorySync — raw_id is
   the only way to resolve LID↔PN for those accounts during message send

3. MIN_PREKEY_COUNT: 5 → 25 (WA Business maintains ~812; 5 was too low a buffer
   before triggering replenishment upload)

4. startKeepAliveRequest: replace fixed setInterval with recursive setTimeout
   + ±15% jitter, matching WA Desktop's ~25-30s variable heartbeat pattern;
   clearInterval → clearTimeout for the handle

5. downloadHistory: fire-and-forget DELETE to CDN after successful download,
   mirroring WA Desktop behaviour (server-side one-time file cleanup)

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-03-19 18:23:27 -03:00
3 changed files with 43 additions and 45 deletions
+26 -39
View File
@@ -1213,7 +1213,7 @@ export const makeMessagesRecvSocket = (config: SocketConfig) => {
return await query(stanza) return await query(stanza)
} }
const sendRetryRequest = async (node: BinaryNode, forceIncludeKeys = false) => { const sendRetryRequest = async (node: BinaryNode, forceIncludeKeys = false, decryptionError?: string) => {
const { fullMessage } = decodeMessageNode(node, authState.creds.me!.id, authState.creds.me!.lid || '') const { fullMessage } = decodeMessageNode(node, authState.creds.me!.id, authState.creds.me!.lid || '')
const { key: msgKey } = fullMessage const { key: msgKey } = fullMessage
const msgId = msgKey.id! const msgId = msgKey.id!
@@ -1311,39 +1311,27 @@ export const makeMessagesRecvSocket = (config: SocketConfig) => {
const { account, signedPreKey, signedIdentityKey: identityKey } = authState.creds const { account, signedPreKey, signedIdentityKey: identityKey } = authState.creds
const fromJid = node.attrs.from! const fromJid = node.attrs.from!
// Check if we should recreate the session // Derive the Signal error code from the actual decryption failure message.
let shouldRecreateSession = false // This is sent in the retry receipt so the peer (even another InfiniteAPI instance)
let recreateReason = '' // knows the exact reason and can recreate the session immediately instead of waiting
// for the 1-hour timeout fallback.
if (enableAutoSessionRecreation && messageRetryManager && retryCount >= 1) { //
try { // Codes mirror RetryReason enum in message-retry-manager.ts:
// Check if we have a session with this JID // 0 = UnknownError | 1 = NoSession | 2 = InvalidKey
const sessionId = signalRepository.jidToSignalProtocolAddress(fromJid) // 3 = InvalidKeyId | 7 = BadMac (= SignalErrorInvalidMessage/InvalidCipherKey)
const hasSession = await signalRepository.validateSession(fromJid) //
// NOTE: We do NOT delete the session here (receiver side). The Signal Protocol
// Extract error code from retry node if present (for MAC error detection) // recovers automatically when the sender's pkmsg arrives — it overwrites the
const retryNode = getBinaryNodeChild(node, 'retry') // corrupted session. Deleting prematurely creates a race window where no session
const errorAttr = retryNode?.attrs?.error // exists, which can cause "No Session" errors on concurrent messages.
const errorCode = messageRetryManager.parseRetryErrorCode(errorAttr) const retryErrorCode = (() => {
if (!decryptionError) return 0
const result = messageRetryManager.shouldRecreateSession(fromJid, hasSession.exists, errorCode) if (/bad\s*mac/i.test(decryptionError)) return 7 // SignalErrorBadMac
shouldRecreateSession = result.recreate if (/no\s*session/i.test(decryptionError)) return 1 // SignalErrorNoSession
recreateReason = result.reason if (/pre\s*key/i.test(decryptionError)) return 3 // SignalErrorInvalidKeyId
if (/invalid\s*key/i.test(decryptionError)) return 2 // SignalErrorInvalidKey
if (shouldRecreateSession) { return 0
logger.debug({ fromJid, retryCount, reason: recreateReason, errorCode }, 'recreating session for retry') })()
// Delete existing session to force recreation
// CRITICAL: Use same transaction key as encrypt/decrypt operations to prevent race
// Using meId ensures this delete serializes with sendMessage() and other session operations
await authState.keys.transaction(async () => {
await authState.keys.set({ session: { [sessionId]: null } })
}, authState.creds.me?.id || 'session-operation')
forceIncludeKeys = true
}
} catch (error) {
logger.warn({ error, fromJid }, 'failed to check session recreation')
}
}
if (retryCount <= 2) { if (retryCount <= 2) {
// Use new retry manager for phone requests if available // Use new retry manager for phone requests if available
@@ -1384,8 +1372,7 @@ export const makeMessagesRecvSocket = (config: SocketConfig) => {
id: node.attrs.id!, id: node.attrs.id!,
t: node.attrs.t!, t: node.attrs.t!,
v: '1', v: '1',
// ADD ERROR FIELD error: retryErrorCode.toString()
error: '0'
} }
}, },
{ {
@@ -1404,7 +1391,7 @@ export const makeMessagesRecvSocket = (config: SocketConfig) => {
receipt.attrs.participant = node.attrs.participant receipt.attrs.participant = node.attrs.participant
} }
if (retryCount > 1 || forceIncludeKeys || shouldRecreateSession) { if (retryCount > 1 || forceIncludeKeys) {
const { update, preKeys } = await getNextPreKeys(authState, 1) const { update, preKeys } = await getNextPreKeys(authState, 1)
const [keyId] = Object.keys(preKeys) const [keyId] = Object.keys(preKeys)
@@ -2507,7 +2494,7 @@ export const makeMessagesRecvSocket = (config: SocketConfig) => {
} }
const encNode = getBinaryNodeChild(node, 'enc') const encNode = getBinaryNodeChild(node, 'enc')
await sendRetryRequest(node, !encNode) await sendRetryRequest(node, !encNode, errorMessage)
if (retryRequestDelayMs) { if (retryRequestDelayMs) {
await delay(retryRequestDelayMs) await delay(retryRequestDelayMs)
} }
@@ -2516,7 +2503,7 @@ export const makeMessagesRecvSocket = (config: SocketConfig) => {
// Still attempt retry even if pre-key upload failed // Still attempt retry even if pre-key upload failed
try { try {
const encNode = getBinaryNodeChild(node, 'enc') const encNode = getBinaryNodeChild(node, 'enc')
await sendRetryRequest(node, !encNode) await sendRetryRequest(node, !encNode, errorMessage)
} catch (retryErr) { } catch (retryErr) {
logger.error({ retryErr }, 'Failed to send retry after error handling') logger.error({ retryErr }, 'Failed to send retry after error handling')
} }
+11 -5
View File
@@ -701,10 +701,12 @@ export const makeSocket = (config: SocketConfig) => {
} }
} }
// Prevent multiple concurrent uploads // Prevent multiple concurrent uploads — if one is already running, wait for it and return:
// the concurrent upload already replenished the pool, so there is nothing left to do.
if (uploadPreKeysPromise) { if (uploadPreKeysPromise) {
logger.debug('Pre-key upload already in progress, waiting for completion') logger.debug('Pre-key upload already in progress, waiting for completion')
await uploadPreKeysPromise await uploadPreKeysPromise
return
} }
const uploadLogic = async () => { const uploadLogic = async () => {
@@ -784,14 +786,15 @@ export const makeSocket = (config: SocketConfig) => {
try { try {
let count = 0 let count = 0
const preKeyCount = await getAvailablePreKeysOnServer() const preKeyCount = await getAvailablePreKeysOnServer()
if (preKeyCount === 0) count = INITIAL_PREKEY_COUNT // How many to upload: top-up to INITIAL_PREKEY_COUNT from whatever remains on server
else count = Math.max(0, INITIAL_PREKEY_COUNT - preKeyCount) count = Math.max(0, INITIAL_PREKEY_COUNT - preKeyCount)
const { exists: currentPreKeyExists, currentPreKeyId } = await verifyCurrentPreKeyExists() const { exists: currentPreKeyExists, currentPreKeyId } = await verifyCurrentPreKeyExists()
logger.info(`${preKeyCount} pre-keys found on server`) logger.info(`${preKeyCount} pre-keys found on server`)
logger.info(`Current prekey ID: ${currentPreKeyId}, exists in storage: ${currentPreKeyExists}`) logger.info(`Current prekey ID: ${currentPreKeyId}, exists in storage: ${currentPreKeyExists}`)
const lowServerCount = preKeyCount <= count // Trigger upload when below the replenishment threshold, not when count < topUp amount
const lowServerCount = preKeyCount < MIN_PREKEY_COUNT
const missingCurrentPreKey = !currentPreKeyExists && currentPreKeyId > 0 const missingCurrentPreKey = !currentPreKeyExists && currentPreKeyId > 0
const shouldUpload = lowServerCount || missingCurrentPreKey const shouldUpload = lowServerCount || missingCurrentPreKey
@@ -1307,7 +1310,10 @@ export const makeSocket = (config: SocketConfig) => {
logger.warn('keep alive called when WS not open') logger.warn('keep alive called when WS not open')
} }
scheduleNextKeepAlive() // Do not reschedule once shutdown has started (closed set by end() on any concurrent path)
if (!closed) {
scheduleNextKeepAlive()
}
} }
scheduleNextKeepAlive() scheduleNextKeepAlive()
+6 -1
View File
@@ -15,6 +15,7 @@ import {
import { toNumber } from './generics' import { toNumber } from './generics'
import type { ILogger } from './logger.js' import type { ILogger } from './logger.js'
import { normalizeMessageContent } from './messages' import { normalizeMessageContent } from './messages'
import { DEFAULT_ORIGIN } from '../Defaults'
import { downloadContentFromMessage, getUrlFromDirectPath } from './messages-media' import { downloadContentFromMessage, getUrlFromDirectPath } from './messages-media'
const inflatePromise = promisify(inflate) const inflatePromise = promisify(inflate)
@@ -430,7 +431,11 @@ export const downloadAndProcessHistorySyncNotification = async (
// processing throws — the server copy would be gone and retry after reconnect would fail. // processing throws — the server copy would be gone and retry after reconnect would fail.
if (msg.directPath) { if (msg.directPath) {
const cdnUrl = getUrlFromDirectPath(msg.directPath) const cdnUrl = getUrlFromDirectPath(msg.directPath)
fetch(cdnUrl, { ...options, method: 'DELETE' }).catch(() => { fetch(cdnUrl, {
...options,
method: 'DELETE',
headers: { ...((options as RequestInit).headers ?? {}), Origin: DEFAULT_ORIGIN }
}).catch(() => {
// non-fatal — server will expire it anyway // non-fatal — server will expire it anyway
}) })
} }