From 5fc974ef20effe8d9efd7733154fc8dec9925f19 Mon Sep 17 00:00:00 2001 From: "Bob (AI Agent)" Date: Thu, 29 Jan 2026 20:24:08 +0000 Subject: [PATCH 1/2] fix(whatsapp): resolve Brazilian mobile JID variants (8/9 digit) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Brazilian mobile numbers transitioned from 8 to 9 digits around 2012-2016. WhatsApp accounts created before the migration may still be registered with the old 8-digit format internally, causing silent message delivery failures. This fix: - Adds brazil-jid.ts resolver that detects BR mobile numbers - Uses sock.onWhatsApp() to query which format is actually registered - Caches results for 7 days to avoid repeated lookups - Modifies monitor.ts to pass onWhatsApp to createWebSendApi - Falls back gracefully if onWhatsApp is not available Tested: Successfully resolved +5511999998888 → 551199998888@s.whatsapp.net Fixes #4168 --- src/web/inbound/brazil-jid.ts | 186 ++++++++++++++++++++++++++++++++++ src/web/inbound/monitor.ts | 1 + src/web/inbound/send-api.ts | 28 ++++- 3 files changed, 211 insertions(+), 4 deletions(-) create mode 100644 src/web/inbound/brazil-jid.ts diff --git a/src/web/inbound/brazil-jid.ts b/src/web/inbound/brazil-jid.ts new file mode 100644 index 000000000..51f2c6f59 --- /dev/null +++ b/src/web/inbound/brazil-jid.ts @@ -0,0 +1,186 @@ +/** + * Brazil WhatsApp JID Resolver + * + * Handles the legacy 8-digit vs 9-digit mobile number issue in Brazil. + * Uses Baileys' onWhatsApp() to discover the correct registered JID. + */ + +import { existsSync, readFileSync, writeFileSync, mkdirSync } from "node:fs"; +import { dirname, join } from "node:path"; +import { homedir } from "node:os"; + +const CONFIG_DIR = process.env.CLAWDBOT_CONFIG_DIR || join(homedir(), ".config", "clawdbot"); +const CACHE_FILE = join(CONFIG_DIR, "brazil-jid-cache.json"); +const CACHE_TTL_MS = 7 * 24 * 60 * 60 * 1000; // 7 days + +interface CacheEntry { + jid: string; + originalInput: string; + variant: string; + timestamp: number; +} + +interface JidCache { + entries: Record; + updatedAt: string; +} + +// In-memory cache (persisted to disk) +let jidCache: Record | null = null; + +function loadCache(): Record { + if (jidCache !== null) return jidCache; + + try { + if (existsSync(CACHE_FILE)) { + const data = JSON.parse(readFileSync(CACHE_FILE, "utf-8")) as JidCache; + jidCache = data.entries || {}; + } else { + jidCache = {}; + } + } catch { + jidCache = {}; + } + return jidCache; +} + +function saveCache(): void { + try { + mkdirSync(dirname(CACHE_FILE), { recursive: true }); + writeFileSync( + CACHE_FILE, + JSON.stringify( + { + entries: jidCache, + updatedAt: new Date().toISOString(), + }, + null, + 2, + ), + ); + } catch (err) { + console.error("[brazil-jid] Failed to save cache:", (err as Error).message); + } +} + +/** + * Check if a number is a Brazilian mobile number that needs resolution + */ +export function isBrazilianMobile(digits: string): boolean { + if (!digits.startsWith("55")) return false; + + const afterCountryCode = digits.slice(2); + if (afterCountryCode.length < 10 || afterCountryCode.length > 11) return false; + + const areaCode = afterCountryCode.slice(0, 2); + const areaNum = parseInt(areaCode, 10); + if (areaNum < 11 || areaNum > 99) return false; + + const localNumber = afterCountryCode.slice(2); + + // Mobile numbers: 8-digit legacy or 9-digit modern (starts with 9) + if (localNumber.length >= 8 && localNumber.length <= 9) { + if (localNumber.length === 9 && localNumber[0] === "9") return true; + if (localNumber.length === 8 && ["6", "7", "8", "9"].includes(localNumber[0])) return true; + } + + return false; +} + +/** + * Generate both 8-digit and 9-digit variants for a Brazilian number + */ +export function generateBrazilianVariants(digits: string): string[] { + if (!digits.startsWith("55")) return [digits]; + + const areaCode = digits.slice(2, 4); + const localNumber = digits.slice(4); + + const variants: string[] = []; + + if (localNumber.length === 9 && localNumber.startsWith("9")) { + // Has 9-digit format: try as-is and without leading 9 + variants.push(digits); // 9-digit + variants.push(`55${areaCode}${localNumber.slice(1)}`); // 8-digit + } else if (localNumber.length === 8) { + // Has 8-digit format: try as-is and with leading 9 + variants.push(digits); // 8-digit + variants.push(`55${areaCode}9${localNumber}`); // 9-digit + } else { + variants.push(digits); + } + + return variants; +} + +interface OnWhatsAppResult { + exists: boolean; + jid?: string; +} + +interface SockWithOnWhatsApp { + onWhatsApp?: (jid: string) => Promise; +} + +/** + * Resolve a Brazilian WhatsApp JID to its correct registered format + */ +export async function resolveBrazilianJid( + sock: SockWithOnWhatsApp, + inputJid: string, +): Promise { + // Extract digits from JID + const match = inputJid.match(/^(\d+)@/); + if (!match) return inputJid; + + const digits = match[1]; + + // Only process Brazilian mobile numbers + if (!isBrazilianMobile(digits)) { + return inputJid; + } + + // Check cache first + const cache = loadCache(); + const cached = cache[digits]; + if (cached && Date.now() - cached.timestamp < CACHE_TTL_MS) { + console.log(`[brazil-jid] Cache hit: ${digits} → ${cached.jid}`); + return cached.jid; + } + + // Need onWhatsApp to resolve + if (!sock.onWhatsApp) { + return inputJid; + } + + // Generate variants and query WhatsApp + const variants = generateBrazilianVariants(digits); + console.log(`[brazil-jid] Checking variants for ${digits}:`, variants); + + for (const variant of variants) { + try { + const results = await sock.onWhatsApp(variant); + if (results?.[0]?.exists && results[0].jid) { + const resolvedJid = results[0].jid; + console.log(`[brazil-jid] Found: ${digits} → ${resolvedJid}`); + + // Cache the result + cache[digits] = { + jid: resolvedJid, + originalInput: digits, + variant, + timestamp: Date.now(), + }; + jidCache = cache; + saveCache(); + + return resolvedJid; + } + } catch { + // Continue to next variant + } + } + + // Fallback to original + return inputJid; +} diff --git a/src/web/inbound/monitor.ts b/src/web/inbound/monitor.ts index 3633cbce9..e543d73c9 100644 --- a/src/web/inbound/monitor.ts +++ b/src/web/inbound/monitor.ts @@ -336,6 +336,7 @@ export async function monitorWebInbox(options: { sock: { sendMessage: (jid: string, content: AnyMessageContent) => sock.sendMessage(jid, content), sendPresenceUpdate: (presence, jid?: string) => sock.sendPresenceUpdate(presence, jid), + onWhatsApp: (jid: string) => sock.onWhatsApp(jid), }, defaultAccountId: options.accountId, }); diff --git a/src/web/inbound/send-api.ts b/src/web/inbound/send-api.ts index 06860e896..c21a0f66b 100644 --- a/src/web/inbound/send-api.ts +++ b/src/web/inbound/send-api.ts @@ -2,14 +2,34 @@ import type { AnyMessageContent, WAPresence } from "@whiskeysockets/baileys"; import { recordChannelActivity } from "../../infra/channel-activity.js"; import { toWhatsappJid } from "../../utils.js"; import type { ActiveWebSendOptions } from "../active-listener.js"; +import { resolveBrazilianJid } from "./brazil-jid.js"; + +interface OnWhatsAppResult { + exists: boolean; + jid?: string; +} export function createWebSendApi(params: { sock: { sendMessage: (jid: string, content: AnyMessageContent) => Promise; sendPresenceUpdate: (presence: WAPresence, jid?: string) => Promise; + onWhatsApp?: (jid: string) => Promise; }; defaultAccountId: string; }) { + const resolveJid = async (to: string): Promise => { + const jid = toWhatsappJid(to); + if (params.sock.onWhatsApp) { + try { + return await resolveBrazilianJid(params.sock, jid); + } catch (err) { + console.warn('[send-api] Brazil JID resolution failed, using original:', (err as Error).message); + return jid; + } + } + return jid; + }; + return { sendMessage: async ( to: string, @@ -18,7 +38,7 @@ export function createWebSendApi(params: { mediaType?: string, sendOptions?: ActiveWebSendOptions, ): Promise<{ messageId: string }> => { - const jid = toWhatsappJid(to); + const jid = await resolveJid(to); let payload: AnyMessageContent; if (mediaBuffer && mediaType) { if (mediaType.startsWith("image/")) { @@ -65,7 +85,7 @@ export function createWebSendApi(params: { to: string, poll: { question: string; options: string[]; maxSelections?: number }, ): Promise<{ messageId: string }> => { - const jid = toWhatsappJid(to); + const jid = await resolveJid(to); const result = await params.sock.sendMessage(jid, { poll: { name: poll.question, @@ -91,7 +111,7 @@ export function createWebSendApi(params: { fromMe: boolean, participant?: string, ): Promise => { - const jid = toWhatsappJid(chatJid); + const jid = await resolveJid(chatJid); await params.sock.sendMessage(jid, { react: { text: emoji, @@ -105,7 +125,7 @@ export function createWebSendApi(params: { } as AnyMessageContent); }, sendComposingTo: async (to: string): Promise => { - const jid = toWhatsappJid(to); + const jid = await resolveJid(to); await params.sock.sendPresenceUpdate("composing", jid); }, } as const; From c4183e2ce6c8c8c91906571d62ab3a105ea1766b Mon Sep 17 00:00:00 2001 From: "Bob (AI Agent)" Date: Thu, 29 Jan 2026 20:41:22 +0000 Subject: [PATCH 2/2] fix: TypeScript type for onWhatsApp (allow undefined return) --- src/web/inbound/brazil-jid.ts | 2 +- src/web/inbound/send-api.ts | 7 +++++-- 2 files changed, 6 insertions(+), 3 deletions(-) diff --git a/src/web/inbound/brazil-jid.ts b/src/web/inbound/brazil-jid.ts index 51f2c6f59..531d9e0dc 100644 --- a/src/web/inbound/brazil-jid.ts +++ b/src/web/inbound/brazil-jid.ts @@ -119,7 +119,7 @@ interface OnWhatsAppResult { } interface SockWithOnWhatsApp { - onWhatsApp?: (jid: string) => Promise; + onWhatsApp?: (jid: string) => Promise; } /** diff --git a/src/web/inbound/send-api.ts b/src/web/inbound/send-api.ts index c21a0f66b..cc864e9a7 100644 --- a/src/web/inbound/send-api.ts +++ b/src/web/inbound/send-api.ts @@ -13,7 +13,7 @@ export function createWebSendApi(params: { sock: { sendMessage: (jid: string, content: AnyMessageContent) => Promise; sendPresenceUpdate: (presence: WAPresence, jid?: string) => Promise; - onWhatsApp?: (jid: string) => Promise; + onWhatsApp?: (jid: string) => Promise; }; defaultAccountId: string; }) { @@ -23,7 +23,10 @@ export function createWebSendApi(params: { try { return await resolveBrazilianJid(params.sock, jid); } catch (err) { - console.warn('[send-api] Brazil JID resolution failed, using original:', (err as Error).message); + console.warn( + "[send-api] Brazil JID resolution failed, using original:", + (err as Error).message, + ); return jid; } }