Skip to content

Soul-driven AI agent with permission-hardened tools, token budgets, and multi-channel access. Runs 24/7 from CLI, Telegram or More.

fix(whatsapp): owner and member messages arrive when WhatsApp sends a LID (#252)

Salman Qureshi7f5fb93bfdc4
diff --git a/plugins/whatsapp/companion/src/main.rs b/plugins/whatsapp/companion/src/main.rs
index d4fb7acb..8203b1d8 100644
--- a/plugins/whatsapp/companion/src/main.rs
+++ b/plugins/whatsapp/companion/src/main.rs
@@ -107,14 +107,102 @@ fn db_path(dir: &Path) -> PathBuf {
dir.join("whatsapp.db")
}
-/// The user part of a phone-number JID ("[email protected]" → "15551234567").
+/// The phone number of a phone-number JID ("[email protected]" →
+/// "15551234567"; `@hosted` business numbers too). None for a LID, a group
+/// or anything else: those say nothing about the number by themselves.
pub fn phone_of(jid: &Jid) -> Option<String> {
- let s = jid.to_string();
- let (user, server) = s.split_once('@')?;
- if server != "s.whatsapp.net" {
+ if !jid.server.is_pn_family() {
return None;
}
- Some(user.split(':').next().unwrap_or(user).to_string())
+ let user = jid.user.split(':').next().unwrap_or(&jid.user);
+ (!user.is_empty()).then(|| user.to_string())
+}
+
+/// The phone number behind a sender, however WhatsApp addressed them.
+///
+/// WhatsApp increasingly addresses people by LID (`…@lid`), a private id
+/// that is not their number. Mercury allows the owner and members by
+/// number, so a LID has to be turned back into one, or their messages are
+/// ignored as if a stranger sent them (issue #247). In order: the JID
+/// itself, the alternate JID WhatsApp sometimes sends alongside, the
+/// LID↔number mapping this device has learned, and, when that's unknown,
+/// one lookup with WhatsApp (which stores the pair for next time).
+pub async fn resolve_phone(client: &Client, jid: &Jid, alt: Option<&Jid>) -> Option<String> {
+ if let Some(phone) = phone_of(jid).or_else(|| alt.and_then(phone_of)) {
+ return Some(phone);
+ }
+ if !jid.server.is_lid_family() {
+ return None;
+ }
+ let known = |entry: Option<whatsapp_rust::lid_pn_cache::LidPnEntry>| entry.map(|e| e.phone_number.to_string()).filter(|p| !p.is_empty());
+ if let Some(phone) = known(client.get_lid_pn_entry(jid).await.ok().flatten()) {
+ return Some(phone);
+ }
+ // One lookup per unknown LID per window: a stranger writing again and
+ // again mustn't turn this device into a stream of lookups (WhatsApp
+ // watches for that), and the answer won't change within minutes.
+ if !lookup_due(&jid.user, std::time::Instant::now()) {
+ return None;
+ }
+ if let Err(e) = client.contacts().is_on_whatsapp(&[jid.to_non_ad()]).await {
+ log(format!("couldn't look up a sender's number (LID {}): {e}", masked(&jid.user)));
+ }
+ let phone = known(client.get_lid_pn_entry(jid).await.ok().flatten());
+ if phone.is_none() {
+ log(format!("a sender's number is unknown (LID {}): Mercury will treat them as unknown", masked(&jid.user)));
+ }
+ phone
+}
+
+/// How long an unknown LID waits before WhatsApp is asked about it again.
+const LOOKUP_EVERY: Duration = Duration::from_secs(600);
+
+/// Whether this LID may be looked up now (and, if so, note that it was).
+fn lookup_due(lid: &str, now: std::time::Instant) -> bool {
+ static LAST: std::sync::OnceLock<std::sync::Mutex<HashMap<String, std::time::Instant>>> = std::sync::OnceLock::new();
+ let mut last = LAST.get_or_init(Default::default).lock().unwrap_or_else(|e| e.into_inner());
+ if last.get(lid).is_some_and(|t| now.duration_since(*t) < LOOKUP_EVERY) {
+ return false;
+ }
+ if last.len() >= 1000 {
+ last.retain(|_, t| now.duration_since(*t) < LOOKUP_EVERY);
+ }
+ last.insert(lid.to_string(), now);
+ true
+}
+
+/// The last four characters, for logs: enough to tell people apart, not to identify them.
+pub fn masked(id: &str) -> String {
+ let tail: String = id.chars().rev().take(4).collect::<Vec<_>>().into_iter().rev().collect();
+ format!("…{tail}")
+}
+
+/// Learn the LIDs of the owner and members once connected, so their first
+/// message already resolves to their number (WhatsApp may address them by
+/// LID before this device has seen them).
+async fn learn_allowed_people(client: Arc<Client>) {
+ let s = voice::settings();
+ let mut numbers: Vec<String> = Vec::new();
+ for key in ["owner", "members"] {
+ let raw = s.get(key).and_then(Value::as_str).unwrap_or("");
+ for part in raw.split(|c: char| c == ',' || c.is_whitespace()) {
+ let digits: String = part.chars().filter(char::is_ascii_digit).collect();
+ if digits.len() >= 6 && !numbers.contains(&digits) {
+ numbers.push(digits);
+ }
+ }
+ }
+ if numbers.is_empty() {
+ return;
+ }
+ let jids: Vec<Jid> = numbers.iter().filter_map(|n| format!("{n}@s.whatsapp.net").parse().ok()).collect();
+ match client.contacts().is_on_whatsapp(&jids).await {
+ Ok(found) => {
+ let with_lid = found.iter().filter(|r| r.lid.is_some()).count();
+ log(format!("looked up {} allowed number(s): {} on WhatsApp, {} with a LID", jids.len(), found.iter().filter(|r| r.is_registered).count(), with_lid));
+ }
+ Err(e) => log(format!("couldn't look up the allowed numbers yet: {e}")),
+ }
}
#[tokio::main]
@@ -444,6 +532,7 @@ async fn start_bot(st: Arc<State>, phone: Option<String>) -> anyhow::Result<()>
let st = st_conn.clone();
async move {
let account = client.pn().and_then(|j| phone_of(&j));
+ tokio::spawn(learn_allowed_people(client.clone()));
*st.client.lock().await = Some(client);
st.out.status("connected", json!({ "account": account }));
}
@@ -496,7 +585,7 @@ async fn on_message(st: Arc<State>, out: Out, ctx: MessageContext) {
return;
}
let chat = src.chat.to_string();
- let sender_phone = phone_of(&src.sender).or_else(|| src.sender_alt.as_ref().and_then(phone_of));
+ let sender_phone = resolve_phone(&ctx.client, &src.sender, src.sender_alt.as_ref()).await;
let mut text = ctx.message.text_content().map(str::to_string).unwrap_or_default();
let mut attachments = Vec::new();
@@ -557,3 +646,44 @@ async fn save(dir: &Path, kind: &str, id: &str, ext: &str, bytes: Result<Vec<u8>
Err(e) => log(format!("attachment download failed: {e}")),
}
}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ fn jid(s: &str) -> Jid {
+ s.parse().expect("jid")
+ }
+
+ #[test]
+ fn a_phone_number_jid_gives_its_number() {
+ assert_eq!(phone_of(&jid("[email protected]")).as_deref(), Some("15551234567"));
+ assert_eq!(phone_of(&jid("15551234567:[email protected]")).as_deref(), Some("15551234567"));
+ // Business numbers hosted by Meta are phone numbers too.
+ assert_eq!(phone_of(&jid("15551234567@hosted")).as_deref(), Some("15551234567"));
+ }
+
+ #[test]
+ fn a_lid_or_a_group_is_not_a_phone_number() {
+ // A LID's digits look like a number but aren't one: treating them as
+ // the sender's number is what made Mercury ignore the owner (#247).
+ assert_eq!(phone_of(&jid("100000012345678@lid")), None);
+ assert_eq!(phone_of(&jid("[email protected]")), None);
+ assert_eq!(phone_of(&jid("[email protected]")), None);
+ }
+
+ #[test]
+ fn an_unknown_lid_is_looked_up_at_most_once_per_window() {
+ let t0 = std::time::Instant::now();
+ assert!(lookup_due("test-lid-1", t0));
+ assert!(!lookup_due("test-lid-1", t0 + Duration::from_secs(60)));
+ assert!(lookup_due("test-lid-2", t0), "another sender has its own window");
+ assert!(lookup_due("test-lid-1", t0 + LOOKUP_EVERY + Duration::from_secs(1)));
+ }
+
+ #[test]
+ fn logs_show_only_the_last_four() {
+ assert_eq!(masked("100000012345678"), "…5678");
+ assert_eq!(masked("12"), "…12");
+ }
+}
diff --git a/plugins/whatsapp/companion/src/voice.rs b/plugins/whatsapp/companion/src/voice.rs
index f1d1885a..41992114 100644
--- a/plugins/whatsapp/companion/src/voice.rs
+++ b/plugins/whatsapp/companion/src/voice.rs
@@ -20,7 +20,7 @@ use whatsapp_rust::types::call::{CallAction, IncomingCall};
use whatsapp_rust::voip::CallHandle;
use crate::links::{self, Brain, Link, LinkCmd, LinkConfig, LinkEvent};
-use crate::{Out, State, log, phone_of};
+use crate::{Out, State, log, phone_of, resolve_phone};
const FRAME: usize = 960;
const RING_TIMEOUT: Duration = Duration::from_secs(45);
@@ -69,13 +69,17 @@ pub async fn route_call_event(watchers: &CallWatchers, call: &IncomingCall) {
pub async fn on_offer(st: Arc<State>, client: Arc<Client>, call: Box<IncomingCall>) {
let CallAction::Offer { call_id, caller_pn, is_video, group_jid, .. } = &call.action else { return };
let from = call.from.to_string();
- let from_phone = caller_pn.as_ref().and_then(phone_of).or_else(|| phone_of(&call.from));
let call_id = call_id.clone();
if group_jid.is_some() || settings().get("answerCalls").and_then(Value::as_bool) == Some(false) {
let _ = client.voip().reject(&call).await;
return;
}
+ // A caller addressed by LID still has to be recognised as the owner (#247).
+ let from_phone = match caller_pn.as_ref().and_then(phone_of) {
+ Some(phone) => Some(phone),
+ None => resolve_phone(&client, &call.from, None).await,
+ };
let decision = st
.out
.request("mercury/call/incoming", json!({ "callId": call_id, "from": from, "fromPhone": from_phone, "video": is_video, "voiceReady": voice_ready(), "voiceProblem": voice_problem() }), Duration::from_secs(8))
diff --git a/plugins/whatsapp/mercury-plugin.template.json b/plugins/whatsapp/mercury-plugin.template.json
index 4164dc73..824ba636 100644
--- a/plugins/whatsapp/mercury-plugin.template.json
+++ b/plugins/whatsapp/mercury-plugin.template.json
@@ -2,7 +2,7 @@
"manifestVersion": 1,
"id": "whatsapp",
"name": "WhatsApp",
- "version": "0.1.1",
+ "version": "0.1.2",
"description": "Chat with Mercury on WhatsApp and talk to it by voice call: OpenAI by default, or Gemini, Grok, ElevenLabs, Azure, Qwen, or your own Mercury model with Deepgram/Cartesia/MiniMax/Sarvam voices. Runs on a spare number as a linked device (unofficial protocol).",
"kind": "out-of-process",
"author": "Cosmic Stack",
diff --git a/src/plugins/channel-bridge.ts b/src/plugins/channel-bridge.ts
index 80058d73..a723ad0a 100644
--- a/src/plugins/channel-bridge.ts
+++ b/src/plugins/channel-bridge.ts
@@ -178,6 +178,8 @@ export class PluginChannel extends BaseChannel {
/** The owner's chat as WhatsApp addresses it (often a LID, not their phone JID). */
private ownerChatId: string | undefined;
private seen = new Set<string>();
+ /** When each ignored sender was last logged (once an hour each, so a chatty stranger can't flood the log). */
+ private ignoredLogged = new Map<string, number>();
private statusListeners = new Set<(s: ChannelStatus) => void>();
/** In-flight `ask_mercury` turns, by call target (`call:<callId>`). */
private callAsks = new Map<string, { chunks: string[]; resolve: (answer: string) => void; timer: ReturnType<typeof setTimeout> }>();
@@ -531,6 +533,32 @@ export class PluginChannel extends BaseChannel {
return members.includes(d) ? 'member' : null;
}
+ /**
+ * Why a message didn't reach the agent, for the owner reading the log:
+ * no-owner no owner number is set, so nobody gets through
+ * number-unknown WhatsApp sent a private id (LID) and the plugin couldn't
+ * find the number behind it (an older plugin, or a first
+ * message before the mapping is known)
+ * not-allowed a number that isn't the owner or a member
+ * The sender shows as its last four digits only.
+ */
+ private noteIgnored(reason: 'no-owner' | 'number-unknown' | 'not-allowed', sender: string): void {
+ const who = digits(sender);
+ const key = `${reason}:${who}`;
+ const now = Date.now();
+ if (now - (this.ignoredLogged.get(key) ?? 0) < 3_600_000) return;
+ this.ignoredLogged.set(key, now);
+ if (this.ignoredLogged.size > 500) this.ignoredLogged.delete(this.ignoredLogged.keys().next().value!);
+ const tail = who ? `…${who.slice(-4)}` : 'unknown';
+ const hint = reason === 'no-owner'
+ ? 'no owner number is set'
+ : reason === 'number-unknown'
+ ? 'WhatsApp addressed the sender by a private id (LID) and the plugin could not find their number; update the plugin, or have them send another message'
+ : 'not the owner or a listed member';
+ const log = reason === 'not-allowed' ? logger.info.bind(logger) : logger.warn.bind(logger);
+ log({ plugin: this.manifest.id, reason, sender: tail }, `Channel message ignored: ${hint}`);
+ }
+
private onMessageNotification(p: IncomingParams): void {
if (typeof p.chatId !== 'string' || typeof p.senderId !== 'string') return;
if (p.fromMe === true) return; // never answer ourselves
@@ -544,10 +572,12 @@ export class PluginChannel extends BaseChannel {
const sender = typeof p.senderPhone === 'string' && p.senderPhone ? p.senderPhone : p.senderId;
const role = this.roleOf(sender);
if (!role) {
- if (!digits(String(settings.owner ?? ''))) {
- logger.warn({ plugin: this.manifest.id }, 'Channel message ignored: no owner number set');
- }
- return; // unknown senders are ignored, silently
+ // Strangers get no reply, but the owner can see why a message didn't
+ // get through (#247). Never the content; never a whole number.
+ if (!digits(String(settings.owner ?? ''))) this.noteIgnored('no-owner', p.senderId);
+ else if (!p.senderPhone && /@(hosted\.)?lid$/.test(p.senderId)) this.noteIgnored('number-unknown', p.senderId);
+ else this.noteIgnored('not-allowed', sender);
+ return;
}
const text = typeof p.text === 'string' ? p.text.slice(0, 20_000) : '';
diff --git a/src/plugins/channel.test.ts b/src/plugins/channel.test.ts
index e53e3eda..e1ccbd34 100644
--- a/src/plugins/channel.test.ts
+++ b/src/plugins/channel.test.ts
@@ -1,8 +1,9 @@
import { mkdirSync, readFileSync, existsSync, writeFileSync } from 'node:fs';
import { join } from 'node:path';
import type { Tool } from 'ai';
-import { afterEach, beforeEach, describe, expect, it } from 'vitest';
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
import { PermissionManager } from '../capabilities/permissions.js';
+import { logger } from '../utils/logger.js';
import type { Channel } from '../channels/base.js';
import type { ChannelMessage } from '../types/channel.js';
import { PluginManager, setProviderLookup } from './manager.js';
@@ -172,6 +173,32 @@ describe('plugin channels (plugin API 1.1)', () => {
]);
});
+ // #247: WhatsApp addresses people by a private id (LID). The plugin turns it
+ // back into their number; when it can't, the owner can see why in the log.
+ it('a sender addressed by LID gets through once the plugin knows their number', async () => {
+ await installChannel('+1 (555) 0002');
+ await inject({ id: 'l1', senderId: '100000012345678@lid', chatId: '100000012345678@lid', senderPhone: '15550002', text: 'hi by lid' });
+ expect(received.map((m) => [m.content, m.senderRole])).toEqual([['hi by lid', 'admin']]);
+ });
+
+ it('a LID with no number is ignored, and the log says why without the message or the whole id', async () => {
+ const warn = vi.spyOn(logger, 'warn');
+ try {
+ await installChannel('+1 (555) 0002');
+ await inject({ id: 'l2', senderId: '100000012345678@lid', chatId: '100000012345678@lid', text: 'secret words' });
+ await inject({ id: 'l3', senderId: '100000012345678@lid', chatId: '100000012345678@lid', text: 'again' });
+ expect(received).toEqual([]);
+ const ignored = warn.mock.calls.filter(([, msg]) => typeof msg === 'string' && msg.startsWith('Channel message ignored'));
+ // Once per sender per hour: a second message doesn't log again.
+ expect(ignored).toHaveLength(1);
+ expect(ignored[0][0]).toMatchObject({ reason: 'number-unknown', sender: '…5678' });
+ expect(JSON.stringify(ignored)).not.toContain('secret words');
+ expect(JSON.stringify(ignored)).not.toContain('100000012345678');
+ } finally {
+ warn.mockRestore();
+ }
+ });
+
it('no owner set means nobody gets through', async () => {
await installChannel('');
await inject({ id: 'n1', senderPhone: '15550002', text: 'hello' });