From 5269789b516c14aa15f15272a55eb844d9d6659e Mon Sep 17 00:00:00 2001 From: Hamza-Ayed Date: Fri, 22 May 2026 20:09:55 +0300 Subject: [PATCH] Fix: Reply via LID JID instead of phone JID to prevent E2EE session conflicts --- whatsapp-gateway/baileys-client.js | 23 +++++++++++++++++++++-- 1 file changed, 21 insertions(+), 2 deletions(-) diff --git a/whatsapp-gateway/baileys-client.js b/whatsapp-gateway/baileys-client.js index 5992232..923d555 100644 --- a/whatsapp-gateway/baileys-client.js +++ b/whatsapp-gateway/baileys-client.js @@ -10,6 +10,7 @@ const path = require('path'); const sessions = new Map(); // Store active sockets in memory const retryCounters = new Map(); // Track reconnection attempts per session const recentMessages = new Map(); // Cache of recent messages in memory to serve getMessage callback +const phoneToLid = new Map(); // Map phone numbers to LID JIDs for correct E2EE routing // Global retry counter cache — persists across socket reconnects // This is CRITICAL for E2EE: tracks message retry attempts so Baileys can @@ -191,11 +192,17 @@ async function startSession(session_key, webhook_url) { let senderPhone = ''; if (msg.key.senderPn && msg.key.senderPn.endsWith('@s.whatsapp.net')) { senderPhone = msg.key.senderPn.split('@')[0]; + // CRITICAL: Map this phone number to the LID JID for reply routing. + // Signal E2EE sessions are bound to the LID, so replies MUST go + // to the LID JID, not the phone JID, to prevent session conflicts. + if (remoteJid.endsWith('@lid')) { + phoneToLid.set(senderPhone, remoteJid); + console.log(`[LID] Mapped ${senderPhone} → ${remoteJid}`); + } } else if (remoteJid.endsWith('@s.whatsapp.net')) { senderPhone = remoteJid.split('@')[0]; } else if (remoteJid.endsWith('@lid')) { senderPhone = remoteJid.split('@')[0]; - senderPhone = remoteJid.split('@')[0]; } if (!senderPhone) continue; @@ -359,7 +366,19 @@ async function sendMessage(session_key, phone, message, mediaUrl = null, audioBa throw new Error(`Session ${session_key} is not active or connected`); } - let jid = phone.includes('@') ? phone : `${phone}@s.whatsapp.net`; + // Use the LID JID if we have a mapping for this phone number. + // This is CRITICAL: Signal E2EE sessions are bound to the LID JID, + // so replying to the phone JID creates a separate session that + // conflicts with the LID session, causing "Waiting for this message". + let jid; + if (phone.includes('@')) { + jid = phone; + } else if (phoneToLid.has(phone)) { + jid = phoneToLid.get(phone); + console.log(`[LID] Routing reply to ${phone} via LID: ${jid}`); + } else { + jid = `${phone}@s.whatsapp.net`; + } let sentMsg; if (audioBase64) {